@tangle-network/sandbox-cli 0.23.371 → 0.23.372

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.
Files changed (2) hide show
  1. package/dist/index.mjs +21 -19
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -124,28 +124,30 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
124
124
  `))},d=e=>{t&&(process.stderr.write(`${o?`
125
125
  `:``}${e}\n`),o=!1)},f=({id:e,text:t})=>{let n=l.get(e)??(l.size===0?r:void 0);if(n!==void 0&&t.startsWith(n))u(t.slice(n.length));else if(n?.startsWith(t))return;else r&&!r.endsWith(`
126
126
  `)&&u(`
127
- `),u(t);l.set(e,t)},p;try{for await(let t of e){a.observe(t);let e=t.data?.executionId;switch(typeof e==`string`&&e.length>0&&(p=e),t.type){case`execution.started`:{if(s)break;s=!0;let e=t.data?.effectiveBackend?.model;d(`[agent${n?` ${n}`:``}] working${e?` on ${e}`:``}`);break}case`token`:{let e=t.data?.value;typeof e==`string`&&l.size===0&&u(e);break}case`message.part.updated`:{let e=qt(t.data);e&&f(e);let n=Jt(t.data);n&&!c.has(n.call)&&(c.add(n.call),d(n.line));break}case`interaction`:{let{kind:e,subject:n}=t.data.request??{},r=n?.toolName?` ${n.toolName}`:``;d(`[agent asks ${e??`a response`}]${r}`);break}case`result`:i=t.data;break}}}catch(e){a.observe({type:`error`,data:{message:e instanceof Error?e.message:String(e)}})}if(r.length===0&&i){let e=Yt(i);typeof e==`string`&&u(e)}return{outcome:{result:a.finish(),tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{},...p?{executionId:p}:{}}}function Zt(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function Qt(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(L.yellow(`⚠ Blocked on a hub approval.`));let t=e.approval?.approvalId;console.error(t?`Approve it: tangle hub approvals approve ${t}`:"Approve the pending request (`tangle hub approvals`), then re-run.");return}if(e.status===`awaiting_question`){console.error(L.yellow(`⚠ Agent is awaiting an answer to a question.`)),console.error(`Re-run with --interactive to answer it, or answer programmatically via box.session(<id>).answer(<questionId>, { ... }).`);return}if(e.status===`awaiting_interaction`){console.error(L.yellow(`⚠ Agent is awaiting a response.`)),console.error(`Open an interactive session, or answer the canonical interaction through the Sandbox SDK.`);return}if(e.status===`awaiting_plan_decision`){console.error(L.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(L.red(`✗ ${en(e.error)??(e.error||t)}`))}const $t={model_not_allowed:`Fix the field the message names and send the request again.`};function en(e){let t=e?.slice(e.indexOf(`{`),e.lastIndexOf(`}`)+1),n;try{n=JSON.parse(t||`null`)??{}}catch{return}let{message:r,code:i}=n;if(typeof r!=`string`||typeof i!=`string`)return;let a=/^(\S+) execution failed/.exec(e??``)?.[1],o=$t[i];return`The model router refused this ${a?`${a} `:``}turn (${i}): ${r}${o?` ${o}`:``}`}async function tn(e,t,n,r){if(n.errorCode!==`TIMEOUT`)return;let i=n.executionId,a=V(t);if(!n.error?.startsWith(`Prompt stream timed out`))return{partial:[],note:`A gateway timed out; the run may still be going in the box. Read it with the Sandbox SDK: box.session(${a}).messages()`};if(!i)return{partial:[],note:`Nothing ran: the box never admitted this turn.`};let o=e.session(t).messages(),s=We(5e3,[],{ref:!1});return{partial:(await Promise.race([o,s]).catch(()=>[])).filter(e=>e.role===`assistant`&&e.id.startsWith(i)).flatMap(e=>e.parts).flatMap(e=>{if(e.type===`text`&&typeof e.text==`string`)return[e.text];let t=e.state;return e.type===`tool`?[`[tool ${String(e.tool)}: ${t?.status??`unknown`}]`]:[]}),note:`The run stopped in the box at the same limit; files it wrote stay there.`,next:`tangle agent prompt ${V(e.id)} 'continue' --session ${a} --timeout ${r*2}`}}function nn(e,t){if(!e.result.success){Qt(e.result,`Agent run failed`);return}let n=performance.now(),r=e=>`${(e/1e3).toFixed(1)} s`,i=e.tokenUsage,a=[`agent ${r(n-t.agentStartedAt)}`,`total ${r(n-t.commandStartedAt)}`,i?.inputTokens===void 0?void 0:`${i.inputTokens} in`,i?.outputTokens===void 0?void 0:`${i.outputTokens} out`].filter(e=>!!e);console.log(L.green(`✓ Done`),L.dim(`(${a.join(`, `)})`))}async function rn(t){t.json||(c(`Streaming response...`),console.log());let n=t.session??`prompt-${Ue()}`,r=Date.now(),i=performance.now(),a=await Xt(t.box.streamPrompt(t.message,{sessionId:n,timeoutMs:t.timeoutMs,...t.backend?{backend:t.backend}:{}}),!t.json,t.harness),o=await tn(t.box,n,{...a.outcome.result,...a.executionId?{executionId:a.executionId}:{}},t.timeoutMs);if(t.json){e({...a.outcome.result,sessionId:n,...a.response?{response:a.response}:{},...a.outcome.tokenUsage?{tokenUsage:a.outcome.tokenUsage}:{},...o,durationMs:Date.now()-r}),a.outcome.result.success||(process.exitCode=1);return}a.printed>0&&console.log();for(let e of o?.partial??[])console.log(e);nn(a.outcome,{commandStartedAt:t.commandStartedAt,agentStartedAt:i}),o&&console.error(o.note),o?.next&&console.error(`Continue it: ${o.next}`)}function an(e){let t=Et(e??[]);if(t.length!==0)return{profile:{connections:t}}}function on(e,t,n){if(!_t(e)||ht.has(e))return;let r=`Harness "${e}" takes no opening prompt, so it has no interactive session; run the task headless.`;throw new p(`USAGE_INVALID`,r,r,`tangle agent prompt ${t?`${V(t)} `:``}${V(n)} --harness ${e}`)}function sn(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:Ye(o),initialPrompt:a};return{...s,run:qe({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function cn(e){let t=Et(e.connection??[]);if(t.length===0)throw Error(`--allow-writes needs at least one --connection to grant writes for.`);if(t.some(e=>e.connectionId===`*`))throw Error("--allow-writes needs explicit --connection ids; the `*:*` wildcard can't be bulk-granted. Grant per connection, e.g. --connection conn_x:* --allow-writes.");let n=await fe({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||c(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||c(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function ln(e){!e.connection||e.connection.length===0||(e.connection=await Tt(e.connection,()=>fe({hubKey:e.hubKey})))}function un(){let t=new z(`agent`).description(`Interact with AI agent`);return t.command(`prompt <idOrMessage> [message]`).description("Send a single prompt to the agent. With one arg it's the prompt and the box comes from `tangle use` / --box / TANGLE_SANDBOX; with two it's <id> <message>. With no box named and none active, the sandbox named after this folder is used, or created if there is none, and becomes the active one.").option(`--box <id>`,`Target sandbox (overrides the active one)`).option(`--session <id>`,`Continue existing session`).option(`--model <model>`,`Model to use`).option(`-t, --timeout <ms>`,`Timeout in milliseconds; with --interactive, detach after this long with no agent output or input`,`300000`).option(`--stream`,`Stream response in real-time`).option(`--interactive`,`Spawn the harness's interactive TUI in the sandbox, inject this prompt, and print a link to watch + drive the live session in the browser (omit for the default headless run)`).option(`--harness <name>`,`Harness that executes this run (claude-code, codex, kimi-code, opencode, pi, hermes; amp needs your own Amp token, so create its box with --backend amp --backend-api-key-env AMP_API_KEY). Defaults to the sandbox's configured backend. The box ships every harness, so this is a per-run choice.`).option(`--profile <source>`,`Agent profile to run: a local JSON path, an https URL, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--skills <ref...>`,`Attach skills (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>] to pull from a repo`).option(`--tools <ref...>`,`Attach tools (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--system-prompt <text>`,`Override the agent's system prompt for this run`).option(`--connection <spec>`,"Grant a hub connection to the agent as MCP tools (repeatable). The connection is a connection id or a provider name. Modes: <connection>:<cap1>,<cap2> (least privilege, recommended), <connection>:* (all of one connection), or *:* (all connections). List connections with `tangle hub connections`; paths with `tangle hub tools search <keyword>`.",wt,[]).option(`--allow-writes`,"Pre-approve every WRITE action of each granted --connection so the agent can write unattended (reads are already allowed; destructive actions still prompt). Revert with `tangle hub permissions revert-writes`.").option(`--no-hub-key`,`Do not auto-mint a platform Hub key for --allow-writes; use the stored credential as-is`).action(async(t,n,r)=>{let i=performance.now(),a=n===void 0?t:n,s=O(r.timeout,`--timeout`,`ms`),{context:l,client:u}=D(r),f=n===void 0?r.box||process.env.TANGLE_SANDBOX||void 0:t,p=f?void 0:T().currentSandbox,m=f??p,h=await Ct({profileSource:r.profile,systemPrompt:r.systemPrompt,skills:r.skills,tools:r.tools});await ln(r);let g=an(r.connection);r.allowWrites&&await cn(r);let _=h||g?{...h,...g?.profile}:void 0,v=r.harness;r.interactive&&v&&on(v,m,a);let y=_||v||r.model?{...v?{type:v}:{},..._?{profile:_}:{},...r.model?{model:{model:r.model}}:{}}:void 0,b=f?await G(u,l,f,{toRun:!0}):await Lt(u,l,p);if(b=await K(b),r.interactive){let t=r.session??`int-${Ue()}`,n=v??(await b.backend.status()).type;on(n,b.id,a);let i=sn(b.id,t,n,_,r.model,a),s=b.session(t).interactive(),u=d(`Starting interactive ${n} session...`);u.start();let f;try{f=await s.start(i)}finally{u.stop()}let p=f.ref.preparationReceipt.harness,m=f.state===`running`?f.streamUrl:void 0,h=`${Zt(l.baseUrl)}/dashboard/sandbox/${encodeURIComponent(b.id)}?interactive=${encodeURIComponent(f.ref.run.sessionId)}`;if(r.json){e({state:f.state,sessionId:f.ref.run.sessionId,harness:p,...m?{streamUrl:m}:{},webUrl:h});return}let g=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,y=()=>{o({"Watch & drive":h}),console.log()};if(c(`Interactive ${p} session ${f.state}.`),console.log(),f.state===`running`&&!g&&y(),f.state===`exited`){c(`The initial prompt completed with reason: ${f.reason}.`);return}if(!g){c(`Open the link to watch the agent and type to take over.`);return}c(`Attaching to the live session — press Ctrl-] to detach.`),await jt(s,Number.parseInt(r.timeout,10)),y();return}if(r.stream)await rn({box:b,message:a,session:r.session,timeoutMs:s,backend:y,harness:v,json:!!r.json,commandStartedAt:i});else{let t=d(`Processing prompt...`);t.start();let n=r.session??`prompt-${Ue()}`,i=await b.prompt(a,{sessionId:n,timeoutMs:s,...y?{backend:y}:{}}),c=await tn(b,n,i,s);if(t.stop(),r.json)e({...i,sessionId:n,...c}),i.success===!1&&(process.exitCode=1);else if(i.success===!1){for(let e of c?.partial??[])console.log(e);Qt(i,`Agent prompt failed`),c&&console.error(c.note),c?.next&&console.error(`Continue it: ${c.next}`)}else console.log(i.response),console.log(),o({Duration:`${i.durationMs}ms`,"Input Tokens":i.usage?.inputTokens,"Output Tokens":i.usage?.outputTokens})}}),t.addCommand(Wt()),t.addCommand(Gt()),t}function dn(e){if(e.status===`stopped`)throw new p(`INVALID_STATE`,`Sandbox ${e.id} is stopped, so its backend is not running`,"The next `tangle agent` or `tangle exec` command resumes it",`tangle sandbox resume ${e.id}`)}function fn(){let r=new z(`backend`).description(`Manage sandbox AI agent backend`);return r.command(`status <sandboxId-or-name>`).description(`Get the harness type the sandbox runs`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching backend status...`);a.start();let o=await G(i,r,t);dn(o);let s=await o.backend.status();a.stop(),n.json?e(s):c(`Backend Type: ${s.type}`)}),r.command(`configure <sandboxId-or-name>`).description(`Update backend configuration; resumes a stopped sandbox`).option(`--model <model>`,`Model id (e.g. provider/model)`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Updating backend config...`);o.start();let s=await K(await G(a,i,t)),c=r.model?{model:r.model}:{};await s.backend.updateConfig(c),o.stop(),n(`Backend configuration updated`),r.json&&e(c)}),r.command(`mcp-status <sandboxId-or-name>`).description(`Get status of MCP servers`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching MCP status...`);o.start();let s=await G(a,i,n);dn(s);let l=await s.backend.getMcpStatus();if(o.stop(),r.json)e(l);else{let e=Object.entries(l);e.length===0?c(`No MCP servers configured`):t(e.map(([e,t])=>{let n=t;return{name:e,status:n.status,error:n.error??``}}),[{key:`name`,header:`Name`,width:24},{key:`status`,header:`Status`,width:12},{key:`error`,header:`Error`,width:40}])}}),r}function pn(e){let t=e.indexOf(`=`);if(t<=0)throw Error(`Invalid --task "${e}": expected format id=message (e.g. t1=summarize README)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!n||!r)throw Error(`Invalid --task "${e}": id and message must be non-empty`);return{id:n,message:r}}function mn(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--tasks file is not valid JSON: ${e.message}`)}let n=Array.isArray(t)?t:t?.tasks;if(!Array.isArray(n))throw Error(`--tasks file must contain an array or an object with a "tasks" array`);return n.map((e,t)=>{if(!e||typeof e!=`object`)throw Error(`--tasks[${t}] must be an object`);let n=e,r=typeof n.id==`string`?n.id.trim():``,i=typeof n.message==`string`?n.message:``;if(!r)throw Error(`--tasks[${t}].id must be a non-empty string`);if(!i.trim())throw Error(`--tasks[${t}].message must be a non-empty string`);let a={id:r,message:i};if(n.context!==void 0&&(typeof n.context!=`object`||n.context===null||Array.isArray(n.context)))throw Error(`--tasks[${t}].context must be a JSON object`);if(n.context!==void 0&&(a.context=n.context),n.timeoutMs!==void 0&&(!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0))throw Error(`--tasks[${t}].timeoutMs must be a positive integer`);return n.timeoutMs!==void 0&&(a.timeoutMs=n.timeoutMs),a})}function hn(e){let t=e.readFile??(e=>F(e,`utf8`)),n=[];e.file&&n.push(...mn(t(e.file)));for(let t of e.inline??[])n.push(pn(t));if(n.length===0)throw Error(`No tasks provided. Use --tasks <file> and/or --task id=message.`);let r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate task id: ${e.id}`);r.add(e.id)}return n}const gn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function _n(e){let t=e.trim(),n=t.indexOf(`/`);if(n<=0||n===t.length-1)throw Error(`--model must be in the form provider/model (got "${e}")`);return{provider:t.slice(0,n),model:t.slice(n+1)}}function vn(e){let t=e.indexOf(`=`);if(t<=0||t===e.length-1)throw Error(`Invalid --backend "${e}": expected format id=type (e.g. primary=opencode)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!gn.test(n))throw Error(`Invalid backend id "${n}": use 1-128 letters, numbers, dots, underscores, or hyphens, starting with a letter or number`);if(!r||r.includes(`=`))throw Error(`Invalid --backend "${e}": type must be a non-empty backend name`);return{id:n,type:r}}function yn(e,t){if(!e||e.length===0)throw Error(`No backends provided. Use --backend id=type or --request <file>.`);let n=e.map(vn),r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate backend id: ${e.id}`);r.add(e.id)}if(t&&n.length!==1)throw Error(`--model requires exactly one backend; use a profile to configure models for multiple backends`);return t&&(n[0]={...n[0],model:_n(t)}),n}function bn(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--request file is not valid JSON: ${e.message}`)}try{return Ne(t)}catch(e){throw Error(`--request file is not a valid batch request: ${e.message}`)}}function xn(e,t,n){return n?`${e} [${t}]`:e}function Sn(e){let t=new Map;for(let n of e)t.set(n.taskId,(t.get(n.taskId)??0)+1);return new Set([...t.entries()].filter(([,e])=>e>1).map(([e])=>e))}function Cn(){let t=new z(`batch`).description(`Run multiple agent tasks in parallel across sandboxes`);return t.command(`run`).description(`Execute a batch of tasks. Provide tasks via --tasks <file.json> and/or repeated --task id=message flags.`).option(`--tasks <file>`,`Path to a JSON file with an array of tasks (or {tasks: [...]})`).option(`--request <file>`,`Path to a complete batch request JSON file`).option(`--task <id=message>`,`Inline task, id=message. Repeatable.`,(e,t=[])=>[...t,e],[]).option(`--stream`,`Stream per-task events as they arrive`).option(`-t, --timeout <ms>`,`Per-task timeout in milliseconds`,`300000`).option(`--persistent`,`Keep sandboxes alive after completion`,!1).option(`--reuse-key <key>`,`Stable workspace identity required by --persistent`).option(`--replay-only`,`Rejoin existing keyed work; refuse missing custody`).option(`--idempotency-key <key>`,`Retry identity; keyed runs continue after disconnect`).option(`--backend <id=type>`,`Backend identity and type. Required and repeatable without --request.`,(e,t=[])=>[...t,e],[]).option(`--model <provider/model>`,`Model override when exactly one backend is selected`).option(`--runtime <runtime>`,`Isolation on platform hosts: docker or firecracker`).action(async(t,n)=>{let r=new AbortController,i=!1,a=()=>{i||(i=!0,c(`Cancel requested — stopping stream...`),r.abort())};process.on(`SIGINT`,a),process.on(`SIGTERM`,a);try{let i;if(t.request){let e=[`tasks`,`task`,`backend`,`model`,`runtime`,`timeout`,`persistent`,`reuseKey`].filter(e=>n.getOptionValueSource(e)===`cli`);if(e.length>0){let t={reuseKey:`reuse-key`};throw Error(`--request cannot be combined with ${e.map(e=>`--${t[e]??e}`).join(`, `)}`)}i=bn(F(t.request,`utf8`))}else{let e=hn({file:t.tasks,inline:t.task}),n=yn(t.backend,t.model),r=Number(t.timeout);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer number of milliseconds`);let a=!!t.persistent;if(a&&!t.reuseKey)throw Error(`--persistent requires --reuse-key`);if(!a&&t.reuseKey)throw Error(`--reuse-key requires --persistent`);i=Ne({tasks:e,timeoutMs:r,backends:n,...t.runtime?{runtime:t.runtime}:{},...a?{persistent:!0,reuseKey:t.reuseKey}:{persistent:!1}})}let{tasks:a,backends:s}=i,{client:l}=D(t),u={signal:r.signal,replayOnly:!!t.replayOnly,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}},d;if(t.stream){let e=t.json?console.error:console.log;c(`Streaming batch of ${a.length} task(s)...`),e();let n=l.streamBatch(i,u),r=s.length>1;for(;;){let t=await n.next();if(t.done){d=t.value;break}let i=t.value;switch(i.type){case`batch.started`:{let e=i.data;c(`Batch started (${e.taskCount} tasks, ${e.backendCount} backends)`);break}case`task.started`:{let t=i.data;e(L.dim(`→ ${xn(t.taskId,t.backendId,r)} started`));break}case`task.retry`:{let t=i.data;e(L.yellow(`↻ ${xn(t.taskId,t.backendId,r)} retry ${t.attempt}: ${t.error}`));break}case`task.completed`:{let t=i.data;e(L.green(`✓ ${xn(t.taskId,t.backendId,r)} completed in ${t.durationMs}ms`+(t.retries?` (${t.retries} retries)`:``)));break}case`task.failed`:{let t=i.data;e(L.red(`✗ ${xn(t.taskId,t.backendId,r)} failed: ${t.error}`));break}}}e()}else c(`Running batch of ${a.length} task(s)...`),d=await l.runBatch(i,u),t.json||console.log();if(t.json)e(d);else if(o({"Total tasks":d.totalTasks,"Total backends":d.totalBackends,"Total executions":d.totalExecutions,Succeeded:d.totalSuccess,Failed:d.totalFailure,"Total retries":d.totalRetries,"Success rate":`${d.successRate.toFixed(1)}%`}),!t.stream&&d.results.length>0){let e=Sn(d.results);console.log(),console.log(L.bold(`Task Results`)),console.log(L.dim(`─`.repeat(40)));for(let t of d.results){let n=t.success?L.green(`✓`):L.red(`✗`),r=t.success?t.usage.inputTokens+t.usage.outputTokens:0,i=r>0?` • ${r} tokens`:``;console.log(`${n} ${xn(t.taskId,t.backendId,e.has(t.taskId))} ${L.dim(`(${t.durationMs}ms, ${t.retries} retries${i})`)}`),t.success||console.log(L.red(` ${t.error}`))}}d.totalFailure>0&&(process.exitCode=1)}catch(n){let r=n instanceof Error&&`batchCustody`in n?n.batchCustody:void 0;if(r?.acceptance===`accepted`&&!(r.cleanup?.mode===`release`&&r.cleanup.isComplete)&&c(`Batch accepted; retirement receipt unproved.`),i){console.log(),c(`Batch cancelled.`),t.json&&n instanceof Error&&`batchCustody`in n&&e({ok:!1,batchCustody:n.batchCustody}),process.exitCode=130;return}f(n,t.json)}finally{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)}}),t}function wn(){let r=new z(`branch`).description(`Branch a running sandbox into copy-on-write children`);return r.command(`create <sandbox-id-or-name>`).description(`Branch a running sandbox into N copy-on-write children`).option(`--count <n>`,`Number of children to create`,`1`).option(`--idempotency-key <key>`,`Retry identity: the same key and count replays the first fan-out and creates no second one`).action(async(r,i)=>{let a=Number.parseInt(i.count,10);if(!Number.isInteger(a)||a<1)throw Error(`--count must be an integer >= 1 (got ${i.count})`);let{context:o,client:l}=D(i),u=d(`Branching into ${a} child(ren)...`);u.start();let f=await G(l,o,r),p=await f.fork(a,{...i.idempotencyKey?{idempotencyKey:i.idempotencyKey}:{}}),m=p.children;u.stop(),i.json?e({children:m.map(e=>({sandboxId:e.id})),requestedCount:p.requestedCount,materializedCount:p.materializedCount,complete:p.complete,...p.idempotency?{idempotency:p.idempotency}:{}}):(p.complete?n(`Branched ${m.length} child(ren) from ${f.id}`):s(`Branched ${p.materializedCount} of ${p.requestedCount} requested child(ren) from ${f.id}`),p.idempotency?.outcome===`replayed`&&c(`Replayed an earlier fan-out under this key; created none.`),t(m.map(e=>({sandboxId:e.id})),[{key:`sandboxId`,header:`Child Sandbox`,width:28}]))}),r}const Tn=[`codex`,`claude-code`,`nanoclaw`,`kimi-code`,`opencode`,`pi`,`openclaw`,`hermes`],En=`https://intelligence.tangle.tools/v1/otlp`,Dn=[`codex`,`claude-code`],On=[`codex`,`claude-code`,`nanoclaw`],kn=[`SessionStart`,`UserPromptSubmit`,`PreToolUse`,`PostToolUse`,`Stop`],An={codex:{kind:`native`,surface:`codex`,label:`Codex`,buildFiles:Un},"claude-code":{kind:`native`,surface:`claude-code`,label:`Claude Code`,buildFiles:Wn},nanoclaw:{kind:`native`,surface:`nanoclaw`,label:`NanoClaw`,buildFiles:Wn},"kimi-code":{kind:`manual`,surface:`kimi-code`,label:`Kimi Code`,reason:`Kimi Code loads hooks through an explicit config file, so use standard OTLP env wiring until the native config adapter is verified.`},opencode:{kind:`manual`,surface:`opencode`,label:`OpenCode`,reason:`OpenCode hooks run as plugins; use standard OTLP env wiring until the native plugin adapter is verified.`},pi:{kind:`manual`,surface:`pi`,label:`Pi`,reason:`Pi hooks run through TypeScript extensions; use standard OTLP env wiring until the native extension adapter is verified.`},openclaw:{kind:`manual`,surface:`openclaw`,label:`OpenClaw`,reason:`OpenClaw project hooks require user opt-in; use standard OTLP env wiring until the hook toggle and adapter are verified.`},hermes:{kind:`manual`,surface:`hermes`,label:`Hermes`,reason:`Hermes project plugins require explicit enablement; use standard OTLP env wiring until the plugin adapter is verified.`}};function jn(e){let t=e.split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>Hn(e));return t.length===0?[...Dn]:rr(t)}function Mn(e){return Object.hasOwn(An,e)}function Nn(e=process.cwd()){return Fe(Re(e))||`agent-workspace`}function Pn(){return R(H(),`.tangle`,`intelligence.json`)}function Fn(e=Pn()){if(!P(e))return null;let t=er(e),n=ir(t,`apiKey`),r=ir(t,`endpoint`),i=ir(t,`serviceName`),a=ir(t,`environment`);if(!n||!r||!i||!a)throw Error(`${e} is missing apiKey, endpoint, serviceName, or environment`);return{apiKey:n,endpoint:r,serviceName:i,environment:a}}async function In(e){let t=Re(e.workspace),n=Pn(),r=jn(e.selection),i=[],a=[],o=[],s={apiKey:e.apiKey,endpoint:q(e.endpoint),serviceName:e.serviceName,environment:e.environment};e.dryRun||Zn(n,s),o.push(n);for(let n of r){let r=An[n];if(r.kind===`manual`){a.push({agent:r.surface,label:r.label,reason:r.reason});continue}i.push(r.surface);let s=t=>Ln(e.hookCommand,r.surface,t);for(let n of r.buildFiles(s)){let r=R(t,n.relPath);if(e.dryRun){o.push(r);continue}$n(r,JSON.parse(n.content),n.mode),o.push(r)}}return!e.smoke||e.dryRun?{configPath:n,written:o,agents:r,nativeAgents:i,manual:a}:{configPath:n,written:o,agents:r,nativeAgents:i,manual:a,smokeTraceId:await zn({agent:i[0]??r[0]??`codex`,event:`install.smoke`,endpoint:s.endpoint,apiKey:s.apiKey,serviceName:s.serviceName,environment:s.environment,sessionId:`install-smoke-${Date.now()}`,payload:{source:`tangle intelligence connect`}})}}function Ln(e,t,n){return`${e.trim()} --agent ${t} --event ${n} --non-blocking`}function Rn(e){let t=BigInt(Date.now())*1000000n,n=or(16),r=or(8),i=e.sessionId??Gn(e.payload),a={"service.name":e.serviceName,"deployment.environment":e.environment,"tangle.agent.surface":e.agent,"tangle.agent.hook.event":e.event,"tangle.agent.hook.source":`local-hook`,...Kn(e.payload)};return i&&(a[`session.id`]=i,a[`gen_ai.conversation.id`]=i,a[`tangle.sessionId`]=i),{body:{resourceSpans:[{resource:{attributes:[sr(`service.name`,e.serviceName),sr(`deployment.environment`,e.environment),sr(`tangle.agent.surface`,e.agent)]},scopeSpans:[{scope:{name:`tangle.intelligence.agent-hook`,version:`1.0.0`},spans:[{traceId:n,spanId:r,name:`agent.${e.agent}.${e.event}`,kind:1,startTimeUnixNano:t.toString(),endTimeUnixNano:(t+1000000n).toString(),attributes:Object.entries(a).map(([e,t])=>sr(e,t)),status:{code:1}}]}]}]},traceId:n}}async function zn(e){let{body:t,traceId:n}=Rn(e),r=await fetch(`${q(e.endpoint)}/v1/traces`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`OTLP smoke ingest failed: ${r.status}${e?` ${e}`:``}`)}return n}function Bn(e){return q(e).replace(/\/v1\/otlp$/,``).replace(/\/+$/,``)}async function Vn(e){let t=`${Bn(e.endpoint)}/v1/onboarding/status`,n=await fetch(t,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`onboarding status request failed: ${n.status}${e?` ${e}`:``}`)}let r=await n.json();return{tracesSeen:!!r.tracesSeen,contentSeen:!!r.contentSeen,lastSeenAt:typeof r.lastSeenAt==`string`?r.lastSeenAt:null,windowDays:typeof r.windowDays==`number`?r.windowDays:7,byAgent:r.byAgent&&typeof r.byAgent==`object`?r.byAgent:{}}}function q(e){let t=e.trim().replace(/\/+$/,``);return t.endsWith(`/v1/traces`)?t.slice(0,-10):t.endsWith(`/v1/logs`)?t.slice(0,-8):t}function Hn(e){switch(e){case`local`:case`both`:return[...Dn];case`all`:return[...On];case`claude`:return[`claude-code`];case`kimi`:return[`kimi-code`];default:if(Mn(e))return[e];throw Error(`agent must be one of: local, all, both, ${Tn.join(`, `)}`)}}function Un(e){let t=Object.fromEntries(kn.map(t=>[t,[{command:e(t),timeoutMs:3e3,blocking:!1,matcher:`*`}]]));return[{relPath:`.codex/hooks.json`,content:JSON.stringify({hooks:t},null,2)}]}function Wn(e){let t=Object.fromEntries(kn.map(t=>[t,[{matcher:`*`,hooks:[{type:`command`,command:e(t),timeout:3}]}]]));return[{relPath:`.claude/settings.json`,content:JSON.stringify({hooks:t},null,2)}]}function Gn(e){return Jn(e,[`session.id`,`sessionId`,`session_id`,`conversationId`,`conversation_id`,`threadId`,`thread_id`,`transcriptId`,`transcript_id`])||process.env.TANGLE_SESSION_ID||process.env.CODEX_THREAD_ID||process.env.CLAUDE_SESSION_ID||process.env.OPENCODE_SESSION_ID}function Kn(e){let t={},n=qn(e,[`tool.name`,`toolName`,`tool_name`,`tool`]),r=qn(e,[`command`,`cmd`,`shell_command`,`shellCommand`]),i=qn(e,[`tool.input`,`toolInput`,`tool_input`,`input`,`arguments`,`args`]),a=qn(e,[`tool.output`,`toolOutput`,`tool_output`,`output`,`result`]),o=qn(e,[`tool.exit_code`,`exitCode`,`exit_code`,`status`]),s=qn(e,[`tool.error.message`,`errorMessage`,`error_message`,`error`]);return n&&(t[`tool.name`]=n),r&&(t[`process.command`]=r),i&&(t[`tool.input.summary`]=i),a&&(t[`tool.output.summary`]=a),o&&(t[`tool.exit_code`]=o),s&&(t[`tool.error.message`]=s),t}function qn(e,t){let n=Yn(e,t);if(n===void 0)return null;if(typeof n==`string`)return Xn(n);if(typeof n==`number`||typeof n==`boolean`||typeof n==`bigint`)return String(n);try{return Xn(JSON.stringify(n))}catch{return null}}function Jn(e,t){let n=Yn(e,t);return typeof n==`string`&&n.length>0?n:void 0}function Yn(e,t){if(typeof e!=`object`||!e)return;let n=[e],r=new Set;for(;n.length;){let e=n.pop();if(typeof e!=`object`||!e||r.has(e))continue;r.add(e);let i=e;for(let e of t){let t=i[e];if(t!=null&&t!==``)return t}for(let e of Object.values(i))typeof e==`object`&&e&&n.push(e)}}function Xn(e){return e.length>4096?`${e.slice(0,4093)}...`:e}function Zn(e,t){Qn(e,`${JSON.stringify(t,null,2)}\n`)}function Qn(e,t){ye(Ie(e),{mode:448,recursive:!0});let n=`${e}.${process.pid}.tmp`;I(n,t,{mode:384}),xe(n,e)}function $n(e,t,n){ye(Ie(e),{recursive:!0});let r=tr(er(e),t);I(e,`${JSON.stringify(r,null,2)}\n`,{mode:n??420})}function er(e){if(!P(e))return{};let t=JSON.parse(F(e,`utf8`));if(!ar(t))throw Error(`${e} must contain a JSON object`);return t}function tr(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];ar(t)&&ar(r)?n[e]=tr(t,r):Array.isArray(t)&&Array.isArray(r)?n[e]=nr([...t,...r]):n[e]=r}return n}function nr(e){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(r);t.has(e)||(t.add(e),n.push(r))}return n}function rr(e){return[...new Set(e)]}function ir(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function ar(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function or(e){return He(e).toString(`hex`)}function sr(e,t){return{key:e,value:{stringValue:t}}}const cr=`tangle.opencode-exporter`,lr=16384;function ur(e){return e.length<=lr?e:`${e.slice(0,lr-1)}…`}function J(e,t){return{key:e,value:{stringValue:t}}}function dr(e){if(!e||typeof e!=`object`)return null;let t=e,n=U(t.type);return n?{type:n,properties:t.properties&&typeof t.properties==`object`?t.properties:void 0}:null}function fr(e,t){let n=[J(`event.name`,e),J(`gen_ai.system`,`opencode`),J(`service.name`,`opencode`)];return t&&(n.push(J(`session.id`,t)),n.push(J(`gen_ai.conversation.id`,t))),n}function pr(e){if(!e)return null;let t=e.part,n=e.info;return U(t?.sessionID)??U(n?.sessionID)??U(e.sessionID)??null}function mr(e,t){let n=U(e.role)??U(e.info?.role);if(n)return n.toLowerCase();let r=U(e.messageID),i=t?.(r)??null;return i?i.toLowerCase():null}function hr(e,t,n){let r=[],i=pr(e.properties),a=(n,r)=>({timeUnixNano:t,severityNumber:9,severityText:`INFO`,...n===null?{}:{body:{stringValue:ur(n)}},attributes:[...fr(e.type,i),...r]});if(e.type===`message.part.updated`){let t=e.properties?.part;if(!t)return r;let i=U(t.type);if(i===`text`||i===`reasoning`){let e=U(t.text);if(e){let i=mr(t,n)===`user`?tt:et;r.push(a(e,[J(i,ur(e))]))}return r}if(i===`tool`){let e=U(t.tool),n=t.state,i=ot(n?.input),o=ot(n?.output),s=U(n?.error)??(typeof n?.error==`object`&&n?.error!==null?ot(n.error):null);if(e||i){let t=[];e&&t.push(J(rt,e)),i&&t.push(J(nt,ur(i))),r.push(a(null,t))}let c=o??s;if(c){let t=[J(it,ur(c))];e&&t.push(J(rt,e)),r.push(a(c,t))}return r}return r}if(e.type===`session.next.text.delta`||e.type===`session.next.text.ended`){let t=e.properties??{},n=U(t.text)??(e.type===`session.next.text.delta`?U(t.delta):null);return n&&r.push(a(n,[J(et,ur(n))])),r}return r}function gr(e=process.env.OTEL_RESOURCE_ATTRIBUTES){if(!e)return null;for(let t of e.split(`,`)){let e=t.indexOf(`=`);if(e===-1||t.slice(0,e).trim()!==at)continue;let n=t.slice(e+1).trim();if(n.length>0)return n}return null}function _r(e,t){if(e.length===0)return null;let n=[J(`service.name`,`opencode`),J(`gen_ai.system`,`opencode`),J(`telemetry.sdk.name`,cr)];return t&&t.trim().length>0&&n.push(J(at,t.trim())),{resourceLogs:[{resource:{attributes:n},scopeLogs:[{scope:{name:cr,version:`1.0.0`},logRecords:e}]}]}}function vr(e){return(e??process.env.OPENCODE_BASE_URL??`http://127.0.0.1:4096`).replace(/\/+$/,``)}async function yr(e){let t=q(e.endpoint),n=await(e.fetchImpl??fetch)(`${t}/v1/logs`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(e.request),signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`OpenCode OTLP logs ingest failed: ${n.status}${e?` ${e}`:``}`)}}var br=class extends Error{partial;constructor(e,t){let n=e instanceof Error?e.message:String(e);super(n),this.name=`OpencodeExporterError`,this.partial=t,e instanceof Error&&(this.cause=e)}};function xr(){return(BigInt(Date.now())*1000000n).toString()}async function Sr(e){let t=vr(e.opencodeBaseUrl),n=e.nowUnixNano??xr,r=e.fetchImpl??fetch,i=e.subjectKey===void 0?gr():e.subjectKey,a=await r(`${t}/event`,{headers:{Accept:`text/event-stream`},signal:e.signal});if(!a.ok){let e=await a.text().catch(()=>``);throw Error(`OpenCode event subscribe failed: ${a.status} at ${t}/event${e?` ${e}`:``}. Is OpenCode running with 'opencode serve'?`)}if(!a.body)throw Error(`OpenCode event stream at ${t}/event returned no body — cannot subscribe`);let o={eventsSeen:0,contentEventsExported:0,recordsExported:0},s=new Map,c=e=>e?s.get(e)??null:null;try{for await(let t of Me(a.body,{signal:e.signal})){o.eventsSeen++;let a=dr(t.data);if(!a)continue;if(a.type===`message.updated`){let e=a.properties?.info,t=U(e?.id),n=U(e?.role);t&&n&&s.set(t,n);continue}let l=hr(a,n(),c),u=_r(l,i);u&&(await yr({endpoint:e.endpoint,apiKey:e.apiKey,request:u,timeoutMs:e.postTimeoutMs,fetchImpl:r}),o.contentEventsExported++,o.recordsExported+=l.length,e.onExport?.({eventType:a.type,records:l.length}))}}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`abort`)))return o;throw new br(e,o)}return o}const Cr=[`claude-code`,`codex`,`opencode`,`openclaw`,`hermes`,`nanoclaw`],wr={"claude-code":`Claude Code`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,hermes:`Hermes`,nanoclaw:`NanoClaw`};function Tr(e){return Cr.includes(e)}function Er(e){return P(e)?F(e,`utf8`):``}function Dr(e,t){ye(Ie(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;I(n,t,{mode:384}),_e(n,384),xe(n,e)}const Or=`# >>> tangle intelligence (claude-code) >>>`,kr=`# <<< tangle intelligence (claude-code) <<<`,Ar={full:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`},{key:`OTEL_LOG_TOOL_CONTENT`,comment:`full tool input+output bodies`},{key:`OTEL_LOG_RAW_API_BODIES`,comment:`full prompt+completion JSON (richest)`}],prompts:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`}],metadata:[]};function jr(e,t){return t===`env`?e:/\s/.test(e)?`"${e}"`:e}function Mr(e,t){let n=t===`shell`?`export `:t===`dockerfile`?`ENV `:``,r=[];for(let i of e){if(i.kind===`blank`){t===`shell`&&r.push(``);continue}if(i.kind===`comment`){t===`shell`&&r.push(`# ${i.text}`);continue}let e=t===`shell`&&i.comment?` # ${i.comment}`:``;r.push(`${n}${i.key}=${jr(i.value,t)}${e}`)}return r.join(`
128
- `)}function Nr(e){let t=q(e.endpoint),n=e.apiKey??"${TANGLE_API_KEY}",r=e.content??`full`,i=e.format??`shell`,a=[{kind:`comment`,text:`Enable + point Claude Code at Tangle (JSON protocol — matches our adapter)`},{kind:`set`,key:`CLAUDE_CODE_ENABLE_TELEMETRY`,value:`1`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_PROTOCOL`,value:`http/json`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_ENDPOINT`,value:t},{kind:`set`,key:`OTEL_EXPORTER_OTLP_HEADERS`,value:`Authorization=Bearer ${n}`}];e.projectKey?a.push({kind:`blank`},{kind:`comment`,text:`Groups your runs into a project so Tangle can roll up + automate per-project:`},{kind:`set`,key:`OTEL_RESOURCE_ATTRIBUTES`,value:`tangle.subject.key=${e.projectKey}`}):a.push({kind:`blank`},{kind:`comment`,text:`Label this project so Tangle rolls up + automates per-project (pick your own):`},{kind:`comment`,text:` export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=<your project>`}),a.push({kind:`blank`},{kind:`comment`,text:`CONTENT rides LOG EVENTS, so the logs exporter is MANDATORY.`},{kind:`set`,key:`OTEL_LOGS_EXPORTER`,value:`otlp`,comment:`required for prompt/completion/tool content`},{kind:`set`,key:`OTEL_METRICS_EXPORTER`,value:`otlp`,comment:`tokens / cost`},{kind:`set`,key:`OTEL_TRACES_EXPORTER`,value:`otlp`,comment:`spans (beta)`},{kind:`blank`});let o=Ar[r];if(o.length===0)a.push({kind:`comment`,text:`Content gates intentionally OFF (metadata-only: tokens, durations, tool names — no prompt/completion/tool bodies).`});else{a.push({kind:`comment`,text:`THE CONTENT GATES (all default OFF):`});for(let e of o)a.push({kind:`set`,key:e.key,value:`1`,comment:e.comment})}return Mr(a,i)}function Pr(e){return[Or,Nr(e),kr].join(`
129
- `)}function Fr(e,t){let n=e.indexOf(Or);if(n!==-1){let r=e.indexOf(kr,n);if(r===-1)throw Error(`shell rc has a '${Or}' marker without its closing '${kr}' — fix it by hand and re-run`);let i=r+43,a=`${e.slice(0,n)}${t}${e.slice(i)}`;return{contents:a,changed:a!==e}}return{contents:`${e.length===0?``:Ir(e)}${t}\n`,changed:!0}}function Ir(e){return e.endsWith(`
127
+ `),u(t);l.set(e,t)},p;try{for await(let t of e){a.observe(t);let e=t.data?.executionId;switch(typeof e==`string`&&e.length>0&&(p=e),t.type){case`execution.started`:{if(s)break;s=!0;let e=t.data?.effectiveBackend?.model;d(`[agent${n?` ${n}`:``}] working${e?` on ${e}`:``}`);break}case`token`:{let e=t.data?.value;typeof e==`string`&&l.size===0&&u(e);break}case`message.part.updated`:{let e=qt(t.data);e&&f(e);let n=Jt(t.data);n&&!c.has(n.call)&&(c.add(n.call),d(n.line));break}case`interaction`:{let{kind:e,subject:n}=t.data.request??{},r=n?.toolName?` ${n.toolName}`:``;d(`[agent asks ${e??`a response`}]${r}`);break}case`result`:i=t.data;break}}}catch(e){a.observe({type:`error`,data:{message:e instanceof Error?e.message:String(e)}})}if(r.length===0&&i){let e=Yt(i);typeof e==`string`&&u(e)}return{outcome:{result:a.finish(),tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{},...p?{executionId:p}:{}}}function Zt(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function Qt(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(L.yellow(`⚠ Blocked on a hub approval.`));let t=e.approval?.approvalId;console.error(t?`Approve it: tangle hub approvals approve ${t}`:"Approve the pending request (`tangle hub approvals`), then re-run.");return}if(e.status===`awaiting_question`){console.error(L.yellow(`⚠ Agent is awaiting an answer to a question.`)),console.error(`Re-run with --interactive to answer it, or answer programmatically via box.session(<id>).answer(<questionId>, { ... }).`);return}if(e.status===`awaiting_interaction`){console.error(L.yellow(`⚠ Agent is awaiting a response.`)),console.error(`Open an interactive session, or answer the canonical interaction through the Sandbox SDK.`);return}if(e.status===`awaiting_plan_decision`){console.error(L.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(L.red(`✗ ${en(e.error)??(e.error||t)}`))}const $t={model_not_allowed:`Fix the field the message names and send the request again.`};function en(e){let t=e?.slice(e.indexOf(`{`),e.lastIndexOf(`}`)+1),n;try{n=JSON.parse(t||`null`)??{}}catch{return}let{message:r,code:i}=n;if(typeof r!=`string`||typeof i!=`string`)return;let a=/^(\S+) execution failed/.exec(e??``)?.[1],o=$t[i];return`The model router refused this ${a?`${a} `:``}turn (${i}): ${r}${o?` ${o}`:``}`}async function tn(e,t,n,r){if(n.errorCode!==`TIMEOUT`)return;let i=n.executionId,a=V(t);if(!n.error?.startsWith(`Prompt stream timed out`))return{partial:[],note:`A gateway timed out; the run may still be going in the box. Read it with the Sandbox SDK: box.session(${a}).messages()`};if(!i)return{partial:[],note:`Nothing ran: the box never admitted this turn.`};let o=e.session(t).messages(),s=We(5e3,[],{ref:!1});return{partial:(await Promise.race([o,s]).catch(()=>[])).filter(e=>e.role===`assistant`&&e.id.startsWith(i)).flatMap(e=>e.parts).flatMap(e=>{if(e.type===`text`&&typeof e.text==`string`)return[e.text];let t=e.state;return e.type===`tool`?[`[tool ${String(e.tool)}: ${t?.status??`unknown`}]`]:[]}),note:`The run stopped in the box at the same limit; files it wrote stay there.`,next:`tangle agent prompt ${V(e.id)} 'continue' --session ${a} --timeout ${r*2}`}}function nn(e,t){if(!e)return[...t];let n=e,r=[];for(let e of t){if(!e)continue;if(n.startsWith(e)){n=n.slice(e.length),n.startsWith(`
128
+ `)&&(n=n.slice(1));continue}if(n.length>0&&e.startsWith(n)){let t=e.slice(n.length);n=``,t&&r.push(t);continue}let t=n.indexOf(e);if(t>=0&&n.slice(0,t).replace(/\n/g,``)===``){n=n.slice(t+e.length),n.startsWith(`
129
+ `)&&(n=n.slice(1));continue}r.push(e)}return r}function rn(e,t){if(!e.result.success){Qt(e.result,`Agent run failed`);return}let n=performance.now(),r=e=>`${(e/1e3).toFixed(1)} s`,i=e.tokenUsage,a=[`agent ${r(n-t.agentStartedAt)}`,`total ${r(n-t.commandStartedAt)}`,i?.inputTokens===void 0?void 0:`${i.inputTokens} in`,i?.outputTokens===void 0?void 0:`${i.outputTokens} out`].filter(e=>!!e);console.log(L.green(`✓ Done`),L.dim(`(${a.join(`, `)})`))}async function an(t){t.json||(c(`Streaming response...`),console.log());let n=t.session??`prompt-${Ue()}`,r=Date.now(),i=performance.now(),a=await Xt(t.box.streamPrompt(t.message,{sessionId:n,timeoutMs:t.timeoutMs,...t.backend?{backend:t.backend}:{}}),!t.json,t.harness),o=await tn(t.box,n,{...a.outcome.result,...a.executionId?{executionId:a.executionId}:{}},t.timeoutMs);if(t.json){e({...a.outcome.result,sessionId:n,...a.response?{response:a.response}:{},...a.outcome.tokenUsage?{tokenUsage:a.outcome.tokenUsage}:{},...o,durationMs:Date.now()-r}),a.outcome.result.success||(process.exitCode=1);return}a.printed>0&&console.log();for(let e of nn(a.response??``,o?.partial??[]))console.log(e);rn(a.outcome,{commandStartedAt:t.commandStartedAt,agentStartedAt:i}),o&&console.error(o.note),o?.next&&console.error(`Continue it: ${o.next}`)}function on(e){let t=Et(e??[]);if(t.length!==0)return{profile:{connections:t}}}function sn(e,t,n){if(!_t(e)||ht.has(e))return;let r=`Harness "${e}" takes no opening prompt, so it has no interactive session; run the task headless.`;throw new p(`USAGE_INVALID`,r,r,`tangle agent prompt ${t?`${V(t)} `:``}${V(n)} --harness ${e}`)}function cn(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:Ye(o),initialPrompt:a};return{...s,run:qe({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function ln(e){let t=Et(e.connection??[]);if(t.length===0)throw Error(`--allow-writes needs at least one --connection to grant writes for.`);if(t.some(e=>e.connectionId===`*`))throw Error("--allow-writes needs explicit --connection ids; the `*:*` wildcard can't be bulk-granted. Grant per connection, e.g. --connection conn_x:* --allow-writes.");let n=await fe({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||c(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||c(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function un(e){!e.connection||e.connection.length===0||(e.connection=await Tt(e.connection,()=>fe({hubKey:e.hubKey})))}function dn(){let t=new z(`agent`).description(`Interact with AI agent`);return t.command(`prompt <idOrMessage> [message]`).description("Send a single prompt to the agent. With one arg it's the prompt and the box comes from `tangle use` / --box / TANGLE_SANDBOX; with two it's <id> <message>. With no box named and none active, the sandbox named after this folder is used, or created if there is none, and becomes the active one.").option(`--box <id>`,`Target sandbox (overrides the active one)`).option(`--session <id>`,`Continue existing session`).option(`--model <model>`,`Model to use`).option(`-t, --timeout <ms>`,`Timeout in milliseconds; with --interactive, detach after this long with no agent output or input`,`300000`).option(`--stream`,`Stream response in real-time`).option(`--interactive`,`Spawn the harness's interactive TUI in the sandbox, inject this prompt, and print a link to watch + drive the live session in the browser (omit for the default headless run)`).option(`--harness <name>`,`Harness that executes this run (claude-code, codex, kimi-code, opencode, pi, hermes; amp needs your own Amp token, so create its box with --backend amp --backend-api-key-env AMP_API_KEY). Defaults to the sandbox's configured backend. The box ships every harness, so this is a per-run choice.`).option(`--profile <source>`,`Agent profile to run: a local JSON path, an https URL, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--skills <ref...>`,`Attach skills (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>] to pull from a repo`).option(`--tools <ref...>`,`Attach tools (repeatable): a local file path, or github:<owner>/<repo>/<path>[@<ref>]`).option(`--system-prompt <text>`,`Override the agent's system prompt for this run`).option(`--connection <spec>`,"Grant a hub connection to the agent as MCP tools (repeatable). The connection is a connection id or a provider name. Modes: <connection>:<cap1>,<cap2> (least privilege, recommended), <connection>:* (all of one connection), or *:* (all connections). List connections with `tangle hub connections`; paths with `tangle hub tools search <keyword>`.",wt,[]).option(`--allow-writes`,"Pre-approve every WRITE action of each granted --connection so the agent can write unattended (reads are already allowed; destructive actions still prompt). Revert with `tangle hub permissions revert-writes`.").option(`--no-hub-key`,`Do not auto-mint a platform Hub key for --allow-writes; use the stored credential as-is`).action(async(t,n,r)=>{let i=performance.now(),a=n===void 0?t:n,s=O(r.timeout,`--timeout`,`ms`),{context:l,client:u}=D(r),f=n===void 0?r.box||process.env.TANGLE_SANDBOX||void 0:t,p=f?void 0:T().currentSandbox,m=f??p,h=await Ct({profileSource:r.profile,systemPrompt:r.systemPrompt,skills:r.skills,tools:r.tools});await un(r);let g=on(r.connection);r.allowWrites&&await ln(r);let _=h||g?{...h,...g?.profile}:void 0,v=r.harness;r.interactive&&v&&sn(v,m,a);let y=_||v||r.model?{...v?{type:v}:{},..._?{profile:_}:{},...r.model?{model:{model:r.model}}:{}}:void 0,b=f?await G(u,l,f,{toRun:!0}):await Lt(u,l,p);if(b=await K(b),r.interactive){let t=r.session??`int-${Ue()}`,n=v??(await b.backend.status()).type;sn(n,b.id,a);let i=cn(b.id,t,n,_,r.model,a),s=b.session(t).interactive(),u=d(`Starting interactive ${n} session...`);u.start();let f;try{f=await s.start(i)}finally{u.stop()}let p=f.ref.preparationReceipt.harness,m=f.state===`running`?f.streamUrl:void 0,h=`${Zt(l.baseUrl)}/dashboard/sandbox/${encodeURIComponent(b.id)}?interactive=${encodeURIComponent(f.ref.run.sessionId)}`;if(r.json){e({state:f.state,sessionId:f.ref.run.sessionId,harness:p,...m?{streamUrl:m}:{},webUrl:h});return}let g=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,y=()=>{o({"Watch & drive":h}),console.log()};if(c(`Interactive ${p} session ${f.state}.`),console.log(),f.state===`running`&&!g&&y(),f.state===`exited`){c(`The initial prompt completed with reason: ${f.reason}.`);return}if(!g){c(`Open the link to watch the agent and type to take over.`);return}c(`Attaching to the live session — press Ctrl-] to detach.`),await jt(s,Number.parseInt(r.timeout,10)),y();return}if(r.stream)await an({box:b,message:a,session:r.session,timeoutMs:s,backend:y,harness:v,json:!!r.json,commandStartedAt:i});else{let t=d(`Processing prompt...`);t.start();let n=r.session??`prompt-${Ue()}`,i=await b.prompt(a,{sessionId:n,timeoutMs:s,...y?{backend:y}:{}}),c=await tn(b,n,i,s);if(t.stop(),r.json)e({...i,sessionId:n,...c}),i.success===!1&&(process.exitCode=1);else if(i.success===!1){for(let e of c?.partial??[])console.log(e);Qt(i,`Agent prompt failed`),c&&console.error(c.note),c?.next&&console.error(`Continue it: ${c.next}`)}else console.log(i.response),console.log(),o({Duration:`${i.durationMs}ms`,"Input Tokens":i.usage?.inputTokens,"Output Tokens":i.usage?.outputTokens})}}),t.addCommand(Wt()),t.addCommand(Gt()),t}function fn(e){if(e.status===`stopped`)throw new p(`INVALID_STATE`,`Sandbox ${e.id} is stopped, so its backend is not running`,"The next `tangle agent` or `tangle exec` command resumes it",`tangle sandbox resume ${e.id}`)}function pn(){let r=new z(`backend`).description(`Manage sandbox AI agent backend`);return r.command(`status <sandboxId-or-name>`).description(`Get the harness type the sandbox runs`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching backend status...`);a.start();let o=await G(i,r,t);fn(o);let s=await o.backend.status();a.stop(),n.json?e(s):c(`Backend Type: ${s.type}`)}),r.command(`configure <sandboxId-or-name>`).description(`Update backend configuration; resumes a stopped sandbox`).option(`--model <model>`,`Model id (e.g. provider/model)`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Updating backend config...`);o.start();let s=await K(await G(a,i,t)),c=r.model?{model:r.model}:{};await s.backend.updateConfig(c),o.stop(),n(`Backend configuration updated`),r.json&&e(c)}),r.command(`mcp-status <sandboxId-or-name>`).description(`Get status of MCP servers`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching MCP status...`);o.start();let s=await G(a,i,n);fn(s);let l=await s.backend.getMcpStatus();if(o.stop(),r.json)e(l);else{let e=Object.entries(l);e.length===0?c(`No MCP servers configured`):t(e.map(([e,t])=>{let n=t;return{name:e,status:n.status,error:n.error??``}}),[{key:`name`,header:`Name`,width:24},{key:`status`,header:`Status`,width:12},{key:`error`,header:`Error`,width:40}])}}),r}function mn(e){let t=e.indexOf(`=`);if(t<=0)throw Error(`Invalid --task "${e}": expected format id=message (e.g. t1=summarize README)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!n||!r)throw Error(`Invalid --task "${e}": id and message must be non-empty`);return{id:n,message:r}}function hn(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--tasks file is not valid JSON: ${e.message}`)}let n=Array.isArray(t)?t:t?.tasks;if(!Array.isArray(n))throw Error(`--tasks file must contain an array or an object with a "tasks" array`);return n.map((e,t)=>{if(!e||typeof e!=`object`)throw Error(`--tasks[${t}] must be an object`);let n=e,r=typeof n.id==`string`?n.id.trim():``,i=typeof n.message==`string`?n.message:``;if(!r)throw Error(`--tasks[${t}].id must be a non-empty string`);if(!i.trim())throw Error(`--tasks[${t}].message must be a non-empty string`);let a={id:r,message:i};if(n.context!==void 0&&(typeof n.context!=`object`||n.context===null||Array.isArray(n.context)))throw Error(`--tasks[${t}].context must be a JSON object`);if(n.context!==void 0&&(a.context=n.context),n.timeoutMs!==void 0&&(!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0))throw Error(`--tasks[${t}].timeoutMs must be a positive integer`);return n.timeoutMs!==void 0&&(a.timeoutMs=n.timeoutMs),a})}function gn(e){let t=e.readFile??(e=>F(e,`utf8`)),n=[];e.file&&n.push(...hn(t(e.file)));for(let t of e.inline??[])n.push(mn(t));if(n.length===0)throw Error(`No tasks provided. Use --tasks <file> and/or --task id=message.`);let r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate task id: ${e.id}`);r.add(e.id)}return n}const _n=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function vn(e){let t=e.trim(),n=t.indexOf(`/`);if(n<=0||n===t.length-1)throw Error(`--model must be in the form provider/model (got "${e}")`);return{provider:t.slice(0,n),model:t.slice(n+1)}}function yn(e){let t=e.indexOf(`=`);if(t<=0||t===e.length-1)throw Error(`Invalid --backend "${e}": expected format id=type (e.g. primary=opencode)`);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!_n.test(n))throw Error(`Invalid backend id "${n}": use 1-128 letters, numbers, dots, underscores, or hyphens, starting with a letter or number`);if(!r||r.includes(`=`))throw Error(`Invalid --backend "${e}": type must be a non-empty backend name`);return{id:n,type:r}}function bn(e,t){if(!e||e.length===0)throw Error(`No backends provided. Use --backend id=type or --request <file>.`);let n=e.map(yn),r=new Set;for(let e of n){if(r.has(e.id))throw Error(`Duplicate backend id: ${e.id}`);r.add(e.id)}if(t&&n.length!==1)throw Error(`--model requires exactly one backend; use a profile to configure models for multiple backends`);return t&&(n[0]={...n[0],model:vn(t)}),n}function xn(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`--request file is not valid JSON: ${e.message}`)}try{return Ne(t)}catch(e){throw Error(`--request file is not a valid batch request: ${e.message}`)}}function Sn(e,t,n){return n?`${e} [${t}]`:e}function Cn(e){let t=new Map;for(let n of e)t.set(n.taskId,(t.get(n.taskId)??0)+1);return new Set([...t.entries()].filter(([,e])=>e>1).map(([e])=>e))}function wn(){let t=new z(`batch`).description(`Run multiple agent tasks in parallel across sandboxes`);return t.command(`run`).description(`Execute a batch of tasks. Provide tasks via --tasks <file.json> and/or repeated --task id=message flags.`).option(`--tasks <file>`,`Path to a JSON file with an array of tasks (or {tasks: [...]})`).option(`--request <file>`,`Path to a complete batch request JSON file`).option(`--task <id=message>`,`Inline task, id=message. Repeatable.`,(e,t=[])=>[...t,e],[]).option(`--stream`,`Stream per-task events as they arrive`).option(`-t, --timeout <ms>`,`Per-task timeout in milliseconds`,`300000`).option(`--persistent`,`Keep sandboxes alive after completion`,!1).option(`--reuse-key <key>`,`Stable workspace identity required by --persistent`).option(`--replay-only`,`Rejoin existing keyed work; refuse missing custody`).option(`--idempotency-key <key>`,`Retry identity; keyed runs continue after disconnect`).option(`--backend <id=type>`,`Backend identity and type. Required and repeatable without --request.`,(e,t=[])=>[...t,e],[]).option(`--model <provider/model>`,`Model override when exactly one backend is selected`).option(`--runtime <runtime>`,`Isolation on platform hosts: docker or firecracker`).action(async(t,n)=>{let r=new AbortController,i=!1,a=()=>{i||(i=!0,c(`Cancel requested — stopping stream...`),r.abort())};process.on(`SIGINT`,a),process.on(`SIGTERM`,a);try{let i;if(t.request){let e=[`tasks`,`task`,`backend`,`model`,`runtime`,`timeout`,`persistent`,`reuseKey`].filter(e=>n.getOptionValueSource(e)===`cli`);if(e.length>0){let t={reuseKey:`reuse-key`};throw Error(`--request cannot be combined with ${e.map(e=>`--${t[e]??e}`).join(`, `)}`)}i=xn(F(t.request,`utf8`))}else{let e=gn({file:t.tasks,inline:t.task}),n=bn(t.backend,t.model),r=Number(t.timeout);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer number of milliseconds`);let a=!!t.persistent;if(a&&!t.reuseKey)throw Error(`--persistent requires --reuse-key`);if(!a&&t.reuseKey)throw Error(`--reuse-key requires --persistent`);i=Ne({tasks:e,timeoutMs:r,backends:n,...t.runtime?{runtime:t.runtime}:{},...a?{persistent:!0,reuseKey:t.reuseKey}:{persistent:!1}})}let{tasks:a,backends:s}=i,{client:l}=D(t),u={signal:r.signal,replayOnly:!!t.replayOnly,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}},d;if(t.stream){let e=t.json?console.error:console.log;c(`Streaming batch of ${a.length} task(s)...`),e();let n=l.streamBatch(i,u),r=s.length>1;for(;;){let t=await n.next();if(t.done){d=t.value;break}let i=t.value;switch(i.type){case`batch.started`:{let e=i.data;c(`Batch started (${e.taskCount} tasks, ${e.backendCount} backends)`);break}case`task.started`:{let t=i.data;e(L.dim(`→ ${Sn(t.taskId,t.backendId,r)} started`));break}case`task.retry`:{let t=i.data;e(L.yellow(`↻ ${Sn(t.taskId,t.backendId,r)} retry ${t.attempt}: ${t.error}`));break}case`task.completed`:{let t=i.data;e(L.green(`✓ ${Sn(t.taskId,t.backendId,r)} completed in ${t.durationMs}ms`+(t.retries?` (${t.retries} retries)`:``)));break}case`task.failed`:{let t=i.data;e(L.red(`✗ ${Sn(t.taskId,t.backendId,r)} failed: ${t.error}`));break}}}e()}else c(`Running batch of ${a.length} task(s)...`),d=await l.runBatch(i,u),t.json||console.log();if(t.json)e(d);else if(o({"Total tasks":d.totalTasks,"Total backends":d.totalBackends,"Total executions":d.totalExecutions,Succeeded:d.totalSuccess,Failed:d.totalFailure,"Total retries":d.totalRetries,"Success rate":`${d.successRate.toFixed(1)}%`}),!t.stream&&d.results.length>0){let e=Cn(d.results);console.log(),console.log(L.bold(`Task Results`)),console.log(L.dim(`─`.repeat(40)));for(let t of d.results){let n=t.success?L.green(`✓`):L.red(`✗`),r=t.success?t.usage.inputTokens+t.usage.outputTokens:0,i=r>0?` • ${r} tokens`:``;console.log(`${n} ${Sn(t.taskId,t.backendId,e.has(t.taskId))} ${L.dim(`(${t.durationMs}ms, ${t.retries} retries${i})`)}`),t.success||console.log(L.red(` ${t.error}`))}}d.totalFailure>0&&(process.exitCode=1)}catch(n){let r=n instanceof Error&&`batchCustody`in n?n.batchCustody:void 0;if(r?.acceptance===`accepted`&&!(r.cleanup?.mode===`release`&&r.cleanup.isComplete)&&c(`Batch accepted; retirement receipt unproved.`),i){console.log(),c(`Batch cancelled.`),t.json&&n instanceof Error&&`batchCustody`in n&&e({ok:!1,batchCustody:n.batchCustody}),process.exitCode=130;return}f(n,t.json)}finally{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)}}),t}function Tn(){let r=new z(`branch`).description(`Branch a running sandbox into copy-on-write children`);return r.command(`create <sandbox-id-or-name>`).description(`Branch a running sandbox into N copy-on-write children`).option(`--count <n>`,`Number of children to create`,`1`).option(`--idempotency-key <key>`,`Retry identity: the same key and count replays the first fan-out and creates no second one`).action(async(r,i)=>{let a=Number.parseInt(i.count,10);if(!Number.isInteger(a)||a<1)throw Error(`--count must be an integer >= 1 (got ${i.count})`);let{context:o,client:l}=D(i),u=d(`Branching into ${a} child(ren)...`);u.start();let f=await G(l,o,r),p=await f.fork(a,{...i.idempotencyKey?{idempotencyKey:i.idempotencyKey}:{}}),m=p.children;u.stop(),i.json?e({children:m.map(e=>({sandboxId:e.id})),requestedCount:p.requestedCount,materializedCount:p.materializedCount,complete:p.complete,...p.idempotency?{idempotency:p.idempotency}:{}}):(p.complete?n(`Branched ${m.length} child(ren) from ${f.id}`):s(`Branched ${p.materializedCount} of ${p.requestedCount} requested child(ren) from ${f.id}`),p.idempotency?.outcome===`replayed`&&c(`Replayed an earlier fan-out under this key; created none.`),t(m.map(e=>({sandboxId:e.id})),[{key:`sandboxId`,header:`Child Sandbox`,width:28}]))}),r}const En=[`codex`,`claude-code`,`nanoclaw`,`kimi-code`,`opencode`,`pi`,`openclaw`,`hermes`],Dn=`https://intelligence.tangle.tools/v1/otlp`,On=[`codex`,`claude-code`],kn=[`codex`,`claude-code`,`nanoclaw`],An=[`SessionStart`,`UserPromptSubmit`,`PreToolUse`,`PostToolUse`,`Stop`],jn={codex:{kind:`native`,surface:`codex`,label:`Codex`,buildFiles:Wn},"claude-code":{kind:`native`,surface:`claude-code`,label:`Claude Code`,buildFiles:Gn},nanoclaw:{kind:`native`,surface:`nanoclaw`,label:`NanoClaw`,buildFiles:Gn},"kimi-code":{kind:`manual`,surface:`kimi-code`,label:`Kimi Code`,reason:`Kimi Code loads hooks through an explicit config file, so use standard OTLP env wiring until the native config adapter is verified.`},opencode:{kind:`manual`,surface:`opencode`,label:`OpenCode`,reason:`OpenCode hooks run as plugins; use standard OTLP env wiring until the native plugin adapter is verified.`},pi:{kind:`manual`,surface:`pi`,label:`Pi`,reason:`Pi hooks run through TypeScript extensions; use standard OTLP env wiring until the native extension adapter is verified.`},openclaw:{kind:`manual`,surface:`openclaw`,label:`OpenClaw`,reason:`OpenClaw project hooks require user opt-in; use standard OTLP env wiring until the hook toggle and adapter are verified.`},hermes:{kind:`manual`,surface:`hermes`,label:`Hermes`,reason:`Hermes project plugins require explicit enablement; use standard OTLP env wiring until the plugin adapter is verified.`}};function Mn(e){let t=e.split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>Un(e));return t.length===0?[...On]:ir(t)}function Nn(e){return Object.hasOwn(jn,e)}function Pn(e=process.cwd()){return Fe(Re(e))||`agent-workspace`}function Fn(){return R(H(),`.tangle`,`intelligence.json`)}function In(e=Fn()){if(!P(e))return null;let t=tr(e),n=ar(t,`apiKey`),r=ar(t,`endpoint`),i=ar(t,`serviceName`),a=ar(t,`environment`);if(!n||!r||!i||!a)throw Error(`${e} is missing apiKey, endpoint, serviceName, or environment`);return{apiKey:n,endpoint:r,serviceName:i,environment:a}}async function Ln(e){let t=Re(e.workspace),n=Fn(),r=Mn(e.selection),i=[],a=[],o=[],s={apiKey:e.apiKey,endpoint:q(e.endpoint),serviceName:e.serviceName,environment:e.environment};e.dryRun||Qn(n,s),o.push(n);for(let n of r){let r=jn[n];if(r.kind===`manual`){a.push({agent:r.surface,label:r.label,reason:r.reason});continue}i.push(r.surface);let s=t=>Rn(e.hookCommand,r.surface,t);for(let n of r.buildFiles(s)){let r=R(t,n.relPath);if(e.dryRun){o.push(r);continue}er(r,JSON.parse(n.content),n.mode),o.push(r)}}return!e.smoke||e.dryRun?{configPath:n,written:o,agents:r,nativeAgents:i,manual:a}:{configPath:n,written:o,agents:r,nativeAgents:i,manual:a,smokeTraceId:await Bn({agent:i[0]??r[0]??`codex`,event:`install.smoke`,endpoint:s.endpoint,apiKey:s.apiKey,serviceName:s.serviceName,environment:s.environment,sessionId:`install-smoke-${Date.now()}`,payload:{source:`tangle intelligence connect`}})}}function Rn(e,t,n){return`${e.trim()} --agent ${t} --event ${n} --non-blocking`}function zn(e){let t=BigInt(Date.now())*1000000n,n=sr(16),r=sr(8),i=e.sessionId??Kn(e.payload),a={"service.name":e.serviceName,"deployment.environment":e.environment,"tangle.agent.surface":e.agent,"tangle.agent.hook.event":e.event,"tangle.agent.hook.source":`local-hook`,...qn(e.payload)};return i&&(a[`session.id`]=i,a[`gen_ai.conversation.id`]=i,a[`tangle.sessionId`]=i),{body:{resourceSpans:[{resource:{attributes:[cr(`service.name`,e.serviceName),cr(`deployment.environment`,e.environment),cr(`tangle.agent.surface`,e.agent)]},scopeSpans:[{scope:{name:`tangle.intelligence.agent-hook`,version:`1.0.0`},spans:[{traceId:n,spanId:r,name:`agent.${e.agent}.${e.event}`,kind:1,startTimeUnixNano:t.toString(),endTimeUnixNano:(t+1000000n).toString(),attributes:Object.entries(a).map(([e,t])=>cr(e,t)),status:{code:1}}]}]}]},traceId:n}}async function Bn(e){let{body:t,traceId:n}=zn(e),r=await fetch(`${q(e.endpoint)}/v1/traces`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`OTLP smoke ingest failed: ${r.status}${e?` ${e}`:``}`)}return n}function Vn(e){return q(e).replace(/\/v1\/otlp$/,``).replace(/\/+$/,``)}async function Hn(e){let t=`${Vn(e.endpoint)}/v1/onboarding/status`,n=await fetch(t,{headers:{Authorization:`Bearer ${e.apiKey}`},signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`onboarding status request failed: ${n.status}${e?` ${e}`:``}`)}let r=await n.json();return{tracesSeen:!!r.tracesSeen,contentSeen:!!r.contentSeen,lastSeenAt:typeof r.lastSeenAt==`string`?r.lastSeenAt:null,windowDays:typeof r.windowDays==`number`?r.windowDays:7,byAgent:r.byAgent&&typeof r.byAgent==`object`?r.byAgent:{}}}function q(e){let t=e.trim().replace(/\/+$/,``);return t.endsWith(`/v1/traces`)?t.slice(0,-10):t.endsWith(`/v1/logs`)?t.slice(0,-8):t}function Un(e){switch(e){case`local`:case`both`:return[...On];case`all`:return[...kn];case`claude`:return[`claude-code`];case`kimi`:return[`kimi-code`];default:if(Nn(e))return[e];throw Error(`agent must be one of: local, all, both, ${En.join(`, `)}`)}}function Wn(e){let t=Object.fromEntries(An.map(t=>[t,[{command:e(t),timeoutMs:3e3,blocking:!1,matcher:`*`}]]));return[{relPath:`.codex/hooks.json`,content:JSON.stringify({hooks:t},null,2)}]}function Gn(e){let t=Object.fromEntries(An.map(t=>[t,[{matcher:`*`,hooks:[{type:`command`,command:e(t),timeout:3}]}]]));return[{relPath:`.claude/settings.json`,content:JSON.stringify({hooks:t},null,2)}]}function Kn(e){return Yn(e,[`session.id`,`sessionId`,`session_id`,`conversationId`,`conversation_id`,`threadId`,`thread_id`,`transcriptId`,`transcript_id`])||process.env.TANGLE_SESSION_ID||process.env.CODEX_THREAD_ID||process.env.CLAUDE_SESSION_ID||process.env.OPENCODE_SESSION_ID}function qn(e){let t={},n=Jn(e,[`tool.name`,`toolName`,`tool_name`,`tool`]),r=Jn(e,[`command`,`cmd`,`shell_command`,`shellCommand`]),i=Jn(e,[`tool.input`,`toolInput`,`tool_input`,`input`,`arguments`,`args`]),a=Jn(e,[`tool.output`,`toolOutput`,`tool_output`,`output`,`result`]),o=Jn(e,[`tool.exit_code`,`exitCode`,`exit_code`,`status`]),s=Jn(e,[`tool.error.message`,`errorMessage`,`error_message`,`error`]);return n&&(t[`tool.name`]=n),r&&(t[`process.command`]=r),i&&(t[`tool.input.summary`]=i),a&&(t[`tool.output.summary`]=a),o&&(t[`tool.exit_code`]=o),s&&(t[`tool.error.message`]=s),t}function Jn(e,t){let n=Xn(e,t);if(n===void 0)return null;if(typeof n==`string`)return Zn(n);if(typeof n==`number`||typeof n==`boolean`||typeof n==`bigint`)return String(n);try{return Zn(JSON.stringify(n))}catch{return null}}function Yn(e,t){let n=Xn(e,t);return typeof n==`string`&&n.length>0?n:void 0}function Xn(e,t){if(typeof e!=`object`||!e)return;let n=[e],r=new Set;for(;n.length;){let e=n.pop();if(typeof e!=`object`||!e||r.has(e))continue;r.add(e);let i=e;for(let e of t){let t=i[e];if(t!=null&&t!==``)return t}for(let e of Object.values(i))typeof e==`object`&&e&&n.push(e)}}function Zn(e){return e.length>4096?`${e.slice(0,4093)}...`:e}function Qn(e,t){$n(e,`${JSON.stringify(t,null,2)}\n`)}function $n(e,t){ye(Ie(e),{mode:448,recursive:!0});let n=`${e}.${process.pid}.tmp`;I(n,t,{mode:384}),xe(n,e)}function er(e,t,n){ye(Ie(e),{recursive:!0});let r=nr(tr(e),t);I(e,`${JSON.stringify(r,null,2)}\n`,{mode:n??420})}function tr(e){if(!P(e))return{};let t=JSON.parse(F(e,`utf8`));if(!or(t))throw Error(`${e} must contain a JSON object`);return t}function nr(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];or(t)&&or(r)?n[e]=nr(t,r):Array.isArray(t)&&Array.isArray(r)?n[e]=rr([...t,...r]):n[e]=r}return n}function rr(e){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(r);t.has(e)||(t.add(e),n.push(r))}return n}function ir(e){return[...new Set(e)]}function ar(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function or(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function sr(e){return He(e).toString(`hex`)}function cr(e,t){return{key:e,value:{stringValue:t}}}const lr=`tangle.opencode-exporter`,ur=16384;function dr(e){return e.length<=ur?e:`${e.slice(0,ur-1)}…`}function J(e,t){return{key:e,value:{stringValue:t}}}function fr(e){if(!e||typeof e!=`object`)return null;let t=e,n=U(t.type);return n?{type:n,properties:t.properties&&typeof t.properties==`object`?t.properties:void 0}:null}function pr(e,t){let n=[J(`event.name`,e),J(`gen_ai.system`,`opencode`),J(`service.name`,`opencode`)];return t&&(n.push(J(`session.id`,t)),n.push(J(`gen_ai.conversation.id`,t))),n}function mr(e){if(!e)return null;let t=e.part,n=e.info;return U(t?.sessionID)??U(n?.sessionID)??U(e.sessionID)??null}function hr(e,t){let n=U(e.role)??U(e.info?.role);if(n)return n.toLowerCase();let r=U(e.messageID),i=t?.(r)??null;return i?i.toLowerCase():null}function gr(e,t,n){let r=[],i=mr(e.properties),a=(n,r)=>({timeUnixNano:t,severityNumber:9,severityText:`INFO`,...n===null?{}:{body:{stringValue:dr(n)}},attributes:[...pr(e.type,i),...r]});if(e.type===`message.part.updated`){let t=e.properties?.part;if(!t)return r;let i=U(t.type);if(i===`text`||i===`reasoning`){let e=U(t.text);if(e){let i=hr(t,n)===`user`?tt:et;r.push(a(e,[J(i,dr(e))]))}return r}if(i===`tool`){let e=U(t.tool),n=t.state,i=ot(n?.input),o=ot(n?.output),s=U(n?.error)??(typeof n?.error==`object`&&n?.error!==null?ot(n.error):null);if(e||i){let t=[];e&&t.push(J(rt,e)),i&&t.push(J(nt,dr(i))),r.push(a(null,t))}let c=o??s;if(c){let t=[J(it,dr(c))];e&&t.push(J(rt,e)),r.push(a(c,t))}return r}return r}if(e.type===`session.next.text.delta`||e.type===`session.next.text.ended`){let t=e.properties??{},n=U(t.text)??(e.type===`session.next.text.delta`?U(t.delta):null);return n&&r.push(a(n,[J(et,dr(n))])),r}return r}function _r(e=process.env.OTEL_RESOURCE_ATTRIBUTES){if(!e)return null;for(let t of e.split(`,`)){let e=t.indexOf(`=`);if(e===-1||t.slice(0,e).trim()!==at)continue;let n=t.slice(e+1).trim();if(n.length>0)return n}return null}function vr(e,t){if(e.length===0)return null;let n=[J(`service.name`,`opencode`),J(`gen_ai.system`,`opencode`),J(`telemetry.sdk.name`,lr)];return t&&t.trim().length>0&&n.push(J(at,t.trim())),{resourceLogs:[{resource:{attributes:n},scopeLogs:[{scope:{name:lr,version:`1.0.0`},logRecords:e}]}]}}function yr(e){return(e??process.env.OPENCODE_BASE_URL??`http://127.0.0.1:4096`).replace(/\/+$/,``)}async function br(e){let t=q(e.endpoint),n=await(e.fetchImpl??fetch)(`${t}/v1/logs`,{method:`POST`,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify(e.request),signal:e.timeoutMs&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`OpenCode OTLP logs ingest failed: ${n.status}${e?` ${e}`:``}`)}}var xr=class extends Error{partial;constructor(e,t){let n=e instanceof Error?e.message:String(e);super(n),this.name=`OpencodeExporterError`,this.partial=t,e instanceof Error&&(this.cause=e)}};function Sr(){return(BigInt(Date.now())*1000000n).toString()}async function Cr(e){let t=yr(e.opencodeBaseUrl),n=e.nowUnixNano??Sr,r=e.fetchImpl??fetch,i=e.subjectKey===void 0?_r():e.subjectKey,a=await r(`${t}/event`,{headers:{Accept:`text/event-stream`},signal:e.signal});if(!a.ok){let e=await a.text().catch(()=>``);throw Error(`OpenCode event subscribe failed: ${a.status} at ${t}/event${e?` ${e}`:``}. Is OpenCode running with 'opencode serve'?`)}if(!a.body)throw Error(`OpenCode event stream at ${t}/event returned no body — cannot subscribe`);let o={eventsSeen:0,contentEventsExported:0,recordsExported:0},s=new Map,c=e=>e?s.get(e)??null:null;try{for await(let t of Me(a.body,{signal:e.signal})){o.eventsSeen++;let a=fr(t.data);if(!a)continue;if(a.type===`message.updated`){let e=a.properties?.info,t=U(e?.id),n=U(e?.role);t&&n&&s.set(t,n);continue}let l=gr(a,n(),c),u=vr(l,i);u&&(await br({endpoint:e.endpoint,apiKey:e.apiKey,request:u,timeoutMs:e.postTimeoutMs,fetchImpl:r}),o.contentEventsExported++,o.recordsExported+=l.length,e.onExport?.({eventType:a.type,records:l.length}))}}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`abort`)))return o;throw new xr(e,o)}return o}const wr=[`claude-code`,`codex`,`opencode`,`openclaw`,`hermes`,`nanoclaw`],Tr={"claude-code":`Claude Code`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,hermes:`Hermes`,nanoclaw:`NanoClaw`};function Er(e){return wr.includes(e)}function Dr(e){return P(e)?F(e,`utf8`):``}function Or(e,t){ye(Ie(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;I(n,t,{mode:384}),_e(n,384),xe(n,e)}const kr=`# >>> tangle intelligence (claude-code) >>>`,Ar=`# <<< tangle intelligence (claude-code) <<<`,jr={full:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`},{key:`OTEL_LOG_TOOL_CONTENT`,comment:`full tool input+output bodies`},{key:`OTEL_LOG_RAW_API_BODIES`,comment:`full prompt+completion JSON (richest)`}],prompts:[{key:`OTEL_LOG_USER_PROMPTS`,comment:`the user/task prompt text`},{key:`OTEL_LOG_TOOL_DETAILS`,comment:`tool arguments`}],metadata:[]};function Mr(e,t){return t===`env`?e:/\s/.test(e)?`"${e}"`:e}function Nr(e,t){let n=t===`shell`?`export `:t===`dockerfile`?`ENV `:``,r=[];for(let i of e){if(i.kind===`blank`){t===`shell`&&r.push(``);continue}if(i.kind===`comment`){t===`shell`&&r.push(`# ${i.text}`);continue}let e=t===`shell`&&i.comment?` # ${i.comment}`:``;r.push(`${n}${i.key}=${Mr(i.value,t)}${e}`)}return r.join(`
130
+ `)}function Pr(e){let t=q(e.endpoint),n=e.apiKey??"${TANGLE_API_KEY}",r=e.content??`full`,i=e.format??`shell`,a=[{kind:`comment`,text:`Enable + point Claude Code at Tangle (JSON protocol — matches our adapter)`},{kind:`set`,key:`CLAUDE_CODE_ENABLE_TELEMETRY`,value:`1`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_PROTOCOL`,value:`http/json`},{kind:`set`,key:`OTEL_EXPORTER_OTLP_ENDPOINT`,value:t},{kind:`set`,key:`OTEL_EXPORTER_OTLP_HEADERS`,value:`Authorization=Bearer ${n}`}];e.projectKey?a.push({kind:`blank`},{kind:`comment`,text:`Groups your runs into a project so Tangle can roll up + automate per-project:`},{kind:`set`,key:`OTEL_RESOURCE_ATTRIBUTES`,value:`tangle.subject.key=${e.projectKey}`}):a.push({kind:`blank`},{kind:`comment`,text:`Label this project so Tangle rolls up + automates per-project (pick your own):`},{kind:`comment`,text:` export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=<your project>`}),a.push({kind:`blank`},{kind:`comment`,text:`CONTENT rides LOG EVENTS, so the logs exporter is MANDATORY.`},{kind:`set`,key:`OTEL_LOGS_EXPORTER`,value:`otlp`,comment:`required for prompt/completion/tool content`},{kind:`set`,key:`OTEL_METRICS_EXPORTER`,value:`otlp`,comment:`tokens / cost`},{kind:`set`,key:`OTEL_TRACES_EXPORTER`,value:`otlp`,comment:`spans (beta)`},{kind:`blank`});let o=jr[r];if(o.length===0)a.push({kind:`comment`,text:`Content gates intentionally OFF (metadata-only: tokens, durations, tool names — no prompt/completion/tool bodies).`});else{a.push({kind:`comment`,text:`THE CONTENT GATES (all default OFF):`});for(let e of o)a.push({kind:`set`,key:e.key,value:`1`,comment:e.comment})}return Nr(a,i)}function Fr(e){return[kr,Pr(e),Ar].join(`
131
+ `)}function Ir(e,t){let n=e.indexOf(kr);if(n!==-1){let r=e.indexOf(Ar,n);if(r===-1)throw Error(`shell rc has a '${kr}' marker without its closing '${Ar}' — fix it by hand and re-run`);let i=r+43,a=`${e.slice(0,n)}${t}${e.slice(i)}`;return{contents:a,changed:a!==e}}return{contents:`${e.length===0?``:Lr(e)}${t}\n`,changed:!0}}function Lr(e){return e.endsWith(`
130
132
 
131
133
  `)?e:e.endsWith(`
132
- `)?`${e}\n`:`${e}\n\n`}function Lr(){let e=process.env.SHELL??``;return e.includes(`zsh`)?R(H(),`.zshrc`):e.includes(`bash`)?R(H(),`.bashrc`):R(H(),`.zshrc`)}function Rr(e){if(e===`shell`||e===`env`||e===`dockerfile`)return e;throw Error(`--format must be one of: shell, env, dockerfile (got '${e}')`)}function zr(e){if(e===`full`||e===`prompts`||e===`metadata`)return e;throw Error(`--content must be one of: full, prompts, metadata (got '${e}')`)}async function Br(e){let t=Nr({endpoint:e.endpoint,apiKey:e.apiKey,projectKey:e.projectKey,content:e.content,format:e.format});if(console.log(t),e.format!==`shell`){console.log(),c(e.format===`env`?"Cron/container path: feed these to your service env (.env, `docker run --env-file`, k8s envFrom). No shell-rc edit, no TTY needed.":`Dockerfile path: paste these ENV lines into your image. No shell-rc edit, no TTY needed.`);return}if(console.log(),c(`Privacy tiers: --content full ships the whole conversation; --content prompts keeps task, prompts, and tool args only; --content metadata turns content off (telemetry still flows). Secrets are scrubbed server-side regardless.`),!e.write)return;let r=e.rcPath??Lr(),i=process.stdin.isTTY?await M(`Append this idempotent block to ${r}? (y/N)`,`n`):`n`;if(i.toLowerCase()!==`y`&&i.toLowerCase()!==`yes`){console.log(),c(`Not writing. To append later: tangle connect claude-code --rc ${r}`);return}let a=Pr({endpoint:e.endpoint,apiKey:e.apiKey,projectKey:e.projectKey,content:e.content,format:e.format}),{contents:o,changed:s}=Fr(Er(r),a);if(!s){console.log(),n(`Already present in ${r} — nothing to change.`);return}Dr(r,o),console.log(),n(`Wrote Tangle Intelligence env block to ${r}.`),c(`Reload your shell (e.g. 'source ${r}') before running the agent.`)}function Vr(e){let t=[],n={header:null,body:[]};for(let r of e.split(`
133
- `))Hr(r)?(t.push(n),n={header:r.trim(),body:[]}):n.body.push(r);return t.push(n),t.length>1&&t[0].header===null&&t[0].body.every(e=>e.trim()===``)&&t.shift(),t}function Hr(e){let t=e.trim();return t.startsWith(`[`)&&t.endsWith(`]`)&&!t.includes(`=`)||t.startsWith(`[[`)&&t.endsWith(`]]`)}function Ur(e){let t=[];for(let n of e)n.header!==null&&t.push(n.header),t.push(...n.body);return t.join(`
134
- `)}function Wr(e){return[{key:`environment`,line:`environment = "prod"`},{key:`log_user_prompt`,line:`log_user_prompt = true`},{key:`exporter`,line:`exporter = { otlp-http = { endpoint = "${q(e.endpoint)}/v1/logs", protocol = "json", headers = { "Authorization" = "Bearer ${e.apiKey??"${TANGLE_API_KEY}"}" } } }`}]}function Gr(e){let t=e.trim();if(t===``||t.startsWith(`#`))return null;let n=t.indexOf(`=`);if(n===-1)return null;let r=t.slice(0,n).trim();return/^[A-Za-z0-9_-]+$/.test(r)?r:null}function Kr(e,t){let n=Wr(t),r=new Set(n.map(e=>e.key));if(e.trim()===``)return{contents:`${[`[otel]`,...n.map(e=>e.line)].join(`
135
- `)}\n`,changed:!0};let i=Vr(e),a=i.find(e=>e.header===`[otel]`);if(!a){let t={header:`[otel]`,body:n.map(e=>e.line)},r=i[i.length-1];r&&!qr(r)&&r.body.push(``),i.push(t);let a=Jr(Ur(i));return{contents:a,changed:a!==Jr(e)}}let o=a.body.filter(e=>{let t=Gr(e);return t===null||!r.has(t)}),s=[];for(;o.length>0&&o[o.length-1].trim()===``;)s.unshift(o.pop());a.body=[...o,...n.map(e=>e.line),...s];let c=Jr(Ur(i));return{contents:c,changed:c!==Jr(e)}}function qr(e){return e.body.length>0&&e.body[e.body.length-1].trim()===``}function Jr(e){return e.endsWith(`
136
- `)?e:`${e}\n`}function Yr(e){let t=R(H(),`.codex`,`config.toml`),{contents:r,changed:i}=Kr(Er(t),{endpoint:e.endpoint,apiKey:e.apiKey});if(!e.write){console.log(r.trimEnd());return}if(!i){n(`${t} already has the Tangle [otel] block — nothing to change.`);return}Dr(t,r),n(`Merged the Tangle [otel] block into ${t}.`),c("Codex emits content on the logs signal (codex.* events). Set TANGLE_API_KEY in your env before running if you kept the ${TANGLE_API_KEY} reference."),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=${e.projectKey??`<your project>`} before running codex.`)}function Xr(e){switch(e){case`claude-code`:return`Claude Code: set OTEL_LOGS_EXPORTER=otlp and the four OTEL_LOG_* gates (OTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS, OTEL_LOG_TOOL_CONTENT, OTEL_LOG_RAW_API_BODIES).`;case`codex`:return`Codex: set log_user_prompt = true in [otel] (default false redacts content).`;case`opencode`:return`OpenCode: a standalone install emits nothing without the tangle-opencode-exporter shim; inside a Tangle sandbox it is already instrumented.`;case`openclaw`:case`hermes`:case`nanoclaw`:return`${wr[e]}: no native OTLP exporter and no standalone server to subscribe to — run it inside a Tangle sandbox, where the sidecar adapter exports its content with gen_ai.system=${e}. A bare standalone install emits metadata only.`}}async function Zr(e){let t=Date.now()+e.timeoutSeconds*1e3,n=3e3,r=Math.min(e.timeoutSeconds*1e3,1e4),i=d(`Checking whether content is flowing…`);i.start();let a;try{for(;;){try{a=await Vn({endpoint:e.endpoint,apiKey:e.apiKey,timeoutMs:r})}catch(e){if(Date.now()>=t)throw e;await We(n);continue}if(a.contentSeen||Date.now()>=t)break;await We(n)}}finally{i.stop()}if(!a)throw Error(`onboarding status check returned no result`);Qr(a,e.agent),a.contentSeen||(process.exitCode=1)}function Qr(e,t){if(e.contentSeen){n(`Content flowing — Tangle Intelligence can analyze this feed.`),o({"Last seen":e.lastSeenAt??`just now`,Window:`${e.windowDays}d`});return}if(e.tracesSeen){s(`Metadata-only — traces are arriving but carry no content. You missed a content gate.`);let n=t?[t]:Object.keys(e.byAgent).filter(Tr),r=n.length>0?n:Cr;for(let n of r){let r=e.byAgent[n];(t||!r||r.tracesSeen&&!r.contentSeen)&&c(Xr(n))}return}s(`No traces yet for your tenant. Run your agent once on a real task, then re-run --verify.`),t&&c(Xr(t))}function $r(e,t){let n=e??process.env.TANGLE_INTELLIGENCE_API_KEY??S(`intelligence`,t);if(!n)throw Error(`No Tangle API key found. Pass --api-key, set TANGLE_API_KEY, or run: tangle auth login`);return n}function ei(e){let t=q(e);if(/^https?:\/\/[A-Za-z0-9.-]+(:\d+)?(\/[A-Za-z0-9._~%/-]*)?$/.test(t))return t;throw new p(`USAGE_INVALID`,`--endpoint ${JSON.stringify(e)} is not a plain http(s) URL`,`letters, digits and . _ ~ % / - only, after the scheme`,`tangle connect --help`)}function ti(){return new z(`connect`).description(`Connect a local coding agent's telemetry to Tangle Intelligence, content on (for SDK integration snippets, see 'tangle agent connect')`).argument(`[agent]`,`claude-code | codex | opencode | openclaw | hermes | nanoclaw`).option(`--endpoint <url>`,`OTLP endpoint base`,En).option(`-p, --project <key>`,`Project label (tangle.subject.key) to group runs; omit to set it yourself`).option(`--rc <path>`,`Shell rc file to append the Claude Code env block to`).option(`--no-write`,`Print the config instead of writing files (Claude Code / Codex)`).option(`--inline-key`,"Embed the resolved API key literally in the config (default: keep ${TANGLE_API_KEY})").option(`--verify`,`Poll onboarding status and report whether CONTENT is flowing`).option(`--timeout <seconds>`,`Verify poll timeout in seconds`,`120`).option(`--run`,`OpenCode only: run the content exporter against a live OpenCode server until interrupted`).option(`--opencode-url <url>`,`OpenCode server base URL for --run (or set OPENCODE_BASE_URL)`).option(`--format <kind>`,`Claude Code output: shell (export block) | env (.env / docker --env-file) | dockerfile (ENV lines). env/dockerfile are the cron/container path — printed to stdout, no shell-rc edit, no TTY`,`shell`).option(`--content <tier>`,`Claude Code content tier: full (everything) | prompts (task+prompts+tool-args) | metadata (telemetry on, content off)`,`full`).action(async(e,t)=>{let n=ei(t.endpoint);if(t.run){if((e?ri(e):`opencode`)!==`opencode`)throw Error(`--run is OpenCode-only: it runs the content exporter against a live OpenCode server. Other agents export natively once configured.`);await si({endpoint:n,apiKey:$r(t.apiKey,n),opencodeUrl:t.opencodeUrl});return}if(t.verify){await Zr({endpoint:n,apiKey:$r(t.apiKey,n),agent:e?ri(e):void 0,timeoutSeconds:k(t.timeout,`--timeout`)});return}let r=e?ri(e):await ii(),i=t.inlineKey?$r(t.apiKey,n):void 0;r===`claude-code`?await Br({endpoint:n,apiKey:i,projectKey:t.project,rcPath:t.rc,write:t.write!==!1,content:zr(t.content),format:Rr(t.format)}):r===`codex`?Yr({endpoint:n,apiKey:i,projectKey:t.project,write:t.write!==!1}):r===`opencode`?ai({endpoint:n}):oi(r,{endpoint:n}),console.log(),c(`Run your agent on a real task, then verify content is flowing: tangle connect ${r} --verify`)})}function ni(){return new z(`opencode-exporter`).description(`Export a running OpenCode's content to Tangle Intelligence (standalone shim)`).option(`--endpoint <url>`,`OTLP endpoint base`,En).option(`--opencode-url <url>`,`OpenCode server base URL (or set OPENCODE_BASE_URL)`).action(async e=>{let t=ei(e.endpoint);await si({endpoint:t,apiKey:$r(e.apiKey,t),opencodeUrl:e.opencodeUrl})})}function ri(e){if(Tr(e))return e;throw Error(`Unknown agent '${e}'. Choose one of: ${Cr.join(`, `)}`)}async function ii(){if(!process.stdin.isTTY)throw Error(`Specify an agent: tangle connect <${Cr.join(`|`)}>`);console.log(`Which coding agent are you connecting?`),Cr.forEach((e,t)=>{console.log(` ${t+1}) ${wr[e]} (${e})`)});let e=await M(`Enter a number or name`,`1`);return Cr[Number.parseInt(e,10)-1]||ri(e.trim())}function ai(e){let t=q(e.endpoint);s(`OpenCode has no native OTel exporter, so a standalone install emits nothing without a shim.`),console.log(),o({"Inside a Tangle sandbox":`already instrumented — our adapter exports OpenCode's event-stream content. Nothing to do.`,Standalone:`run 'tangle connect opencode --run' alongside a running OpenCode, exporting to ${t}.`}),console.log(),c(`Start OpenCode in server mode ('opencode serve'), then in another terminal run: tangle connect opencode --run`),c(`The exporter subscribes to OpenCode's SSE event bus and exports content-bearing OTLP (prompt/completion/tool content) to Tangle. Verify with: tangle connect opencode --verify`),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting the exporter.`)}function oi(e,t){let n=q(t.endpoint),r=wr[e];s(`${r} has no native OTel exporter, so a standalone install emits nothing without instrumentation.`),console.log(),o({"Inside a Tangle sandbox":`already instrumented — the sidecar adapter exports ${r}'s prompt/completion/tool content (gen_ai.system=${e}) to ${n}. Nothing to do.`,Standalone:`${r} exposes no OTLP and no event-bus server; run it inside a Tangle sandbox to capture content.`}),console.log(),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting ${r}.`),c(`Verify content is flowing: tangle connect ${e} --verify`)}async function si(e){let t=vr(e.opencodeUrl),r=new AbortController,i=()=>r.abort();process.on(`SIGINT`,i),process.on(`SIGTERM`,i),c(`Subscribing to OpenCode at ${t} — exporting content to Tangle.`),c(`Run OpenCode tasks now. Press Ctrl-C to stop.`),console.log();let a=0,o;try{o=await Sr({endpoint:e.endpoint,apiKey:e.apiKey,opencodeBaseUrl:t,signal:r.signal,onExport:({eventType:e,records:t})=>{a+=t,c(`exported ${t} record(s) from ${e} (total ${a})`)}})}catch(e){if(e instanceof br){let{recordsExported:t,contentEventsExported:n}=e.partial;console.log(),s(`Exporter failed after exporting ${t} content record(s) from ${n} event(s): ${e.message}`)}throw e}finally{process.off(`SIGINT`,i),process.off(`SIGTERM`,i)}if(console.log(),o.contentEventsExported===0){s(`Saw ${o.eventsSeen} event(s) but none carried content. Run a real OpenCode task (a prompt that produces text or a tool call), then re-run.`);return}n(`Exported ${o.recordsExported} content record(s) from ${o.contentEventsExported} event(s).`),c(`Verify it landed: tangle connect opencode --verify`)}function ci(){let t=new z(`environments`).alias(`env`).description(`Manage sandbox environments`);return t.command(`list`).alias(`ls`).description(`List available environments`).action(async t=>{let{client:n}=D(t),i=d(`Fetching environments...`);t.json||i.start();let a=await n.environments.list();i.stop(),t.json?e(a):a.length===0?console.log(`No environments found`):r([`ID`,`Description`,`Version`,`Runtimes`],a.map(e=>[e.id,e.description??``,e.version,e.runtimes.join(`, `)]))}),t.command(`get`).description(`Get environment details`).argument(`<id>`,`Environment ID`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Fetching environment...`);n.json||i.start();let a=await r.environments.get(t);if(i.stop(),!a){console.error(`Environment not found: ${t}`),process.exit(1);return}n.json?e(a):(console.log(`ID: ${a.id}`),console.log(`Description: ${a.description??`-`}`),console.log(`Version: ${a.version}`),console.log(`Runtimes: ${a.runtimes.join(`, `)}`),a.base&&console.log(`Base: ${a.base}`))}),t}const li=B.string().trim().toLowerCase().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/),ui=B.enum([`no_stock`,`sku_unknown`,`unsupported`,`still_present`,`preempted`,`quota`,`not_found`,`auth_rejected`,`invalid_request`,`provider_not_configured`,`rate_limited`,`conflict`,`indeterminate`,`provider_error`,`transport`]);B.object({provider:li.nullable(),step:B.enum([`initialize`,`check-birth-pause`,`check-limits`,`check-providers`,`quote`,`select-offer`,`check-inventory`,`insert`,`create`,`recover`,`wait-ready`,`cleanup`]),providerErrorCode:B.union([ui,B.literal(`gpu_provider_error`)])});const di=B.string().trim().toLowerCase().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/),fi=B.object({kind:di,count:B.number().int().positive().default(1),vramGb:B.number().positive().optional()}).strict();B.object({command:B.string().min(1).max(8192),timeoutMs:B.number().int().positive().max(2147453647).optional(),env:B.record(B.string(),B.string()).optional(),cwd:B.string().min(1).max(2048).optional()}).strict(),B.object({refresh:B.enum([`true`,`false`]).optional(),acceleratorKind:di.optional(),acceleratorCount:B.coerce.number().pipe(fi.shape.count.unwrap()).optional(),acceleratorVramGb:B.coerce.number().positive().optional()}).strict(),B.object({maxSpendUsd:B.number().positive().max(1e4).optional(),maxLifetimeSeconds:B.number().int().positive().max(1440*60).optional()}).strict().refine(e=>e.maxSpendUsd!==void 0||e.maxLifetimeSeconds!==void 0,`Renewal requires a lifetime or spend cap`);const pi=B.object({provider:li.optional(),image:B.string().min(1).max(512).optional(),env:B.record(B.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),B.string()).optional(),diskGb:B.number().int().positive().optional(),volumeGb:B.number().int().nonnegative().optional(),volumeMountPath:B.string().startsWith(`/`).max(2048).optional(),region:B.string().min(1).max(128).optional(),manifest:B.record(B.string(),B.unknown()).optional(),command:B.array(B.string().max(8192)).min(1).max(256).optional(),ports:B.array(B.number().int().min(1).max(65535)).max(32).optional(),endpoint:B.object({port:B.number().int().min(1).max(65535),healthPath:B.string().regex(/^\/(?![/\\])/).refine(e=>![`\r`,`
137
- `,` `].some(t=>e.includes(t))).max(2048).optional()}).strict().optional(),allowSpot:B.boolean().optional(),maxHourlyUsd:B.number().positive().optional(),weights:B.object({manifestSha:B.string().regex(/^[a-f0-9]{64}$/),sizeBytes:B.number().int().positive().safe()}).strict().optional(),arms:B.array(B.unknown()).min(1).max(256).optional(),maxSpendUsd:B.number().positive().max(1e4),maxLifetimeSeconds:B.number().int().positive().max(1440*60),idleTimeoutSeconds:B.number().int().positive().optional()}).strict();pi.extend({accelerator:fi});const mi=fi,hi=li;B.object({...pi.omit({env:!0}).shape,id:B.string(),projectRef:B.string(),ownerUserId:B.string(),productId:B.string().optional(),provider:hi,providerLeaseId:B.string().optional(),providerInstanceType:B.string().optional(),endpointUrl:B.string().optional(),status:B.enum([`provisioning`,`ready`,`detaching`,`destroyed`,`failed`]),accelerator:mi,providerCostPerHourUsd:B.number().optional(),customerPricePerHourUsd:B.number().optional(),estimatedProviderCostUsd:B.number().optional(),estimatedCustomerCostUsd:B.number().optional(),providerSelection:B.object({strategy:B.enum([`explicit`,`cheapest`,`ranked`]),selectedProvider:hi,requestedProvider:hi.optional(),candidates:B.array(B.object({provider:hi,accelerator:mi,providerInstanceType:B.string().optional(),region:B.string().optional(),pricingSource:B.enum([`live`,`configured`]).optional(),providerCostPerHourUsd:B.number(),customerPricePerHourUsd:B.number(),maxLifetimeSeconds:B.number(),estimatedProviderCostUsd:B.number(),estimatedCustomerCostUsd:B.number()})),rejected:B.array(B.object({provider:hi,error:B.string()}))}).optional(),createdAt:B.string(),updatedAt:B.string(),readyAt:B.string().optional(),startedAt:B.string().optional(),lastUsedAt:B.string().optional(),destroyedAt:B.string().optional(),failure:B.string().optional(),billing:B.object({seconds:B.number(),providerCostUsd:B.number(),customerCostUsd:B.number(),providerCostPerHourUsd:B.number(),customerPricePerHourUsd:B.number(),startedAt:B.string(),stoppedAt:B.string()}).optional()});function gi(e){return{kind:Ci(e.kind),count:e.count?k(e.count,`--accelerator-count`):1,...e.memory?{vramGb:Ti(e.memory,`--accelerator-memory`)}:{}}}function _i(e,t,n){if(!t&&Object.values(e).some(Boolean))throw Error(n);return t?yi(e,`--gpu-`):void 0}function vi(e){return{...yi(e,`--`),accelerator:gi({kind:e.acceleratorKind,count:e.acceleratorCount,memory:e.acceleratorMemory})}}function yi(e,t){let{provider:n,image:r,env:i,maxSpendUsd:a,maxLifetime:o,idleTimeout:s}=e;if(!a||!o)throw Error(`--accelerator-kind requires ${t}max-spend-usd and ${t}max-lifetime`);return{...n?{provider:wi(n,`${t}provider`)}:{},...r?{image:r}:{},...i?{env:Si(i,`${t}env`,`env`)}:{},maxSpendUsd:Ti(a,`${t}max-spend-usd`),maxLifetimeSeconds:O(o,`${t}max-lifetime`),...s?{idleTimeoutSeconds:O(s,`${t}idle-timeout`)}:{}}}function bi(e){return e.length===1?e[0]:e.map(V).join(` `)}function xi(e){return{timeoutMs:e.timeout?O(String(e.timeout),`--timeout`,`ms`):void 0,env:e.env?Si(e.env,`--env`,`env`):void 0}}function Si(e,t,n){let r={};for(let i of e){let[e,...a]=i.split(`=`);if(!e||a.length===0)throw Error(`${t} expects ${n} values in KEY=VALUE format`);r[e]=a.join(`=`)}return r}function Ci(e){let t=di.safeParse(e);if(t.success)return t.data;throw Error(`--accelerator-kind must contain only letters, numbers, dots, underscores, or hyphens`)}function wi(e,t){let n=li.safeParse(e);if(n.success)return n.data;throw Error(`${t} must start with a letter and contain only letters, numbers, or hyphens`)}function Ti(e,t){if(!/^(?:\d+|\d+\.\d+|\.\d+)$/.test(e))throw Error(`${t} must be a positive number`);let n=Number.parseFloat(e);if(!Number.isFinite(n)||n<=0)throw Error(`${t} must be a positive number`);return n}function Ei(){return new z(`exec`).description(`Execute a command in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command...>`,`Command and arguments, or one shell script`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`,`60000`).allowUnknownOption(!0).action(async(t,n,r)=>{try{let{context:i,client:a}=D(r),o=bi(n),s=Si(r.env??[],`--env`,`env`),c=O(r.timeout,`--timeout`,`ms`,0),l=d(`Executing: ${o}`);r.json||l.start();let u=await G(a,i,t,{toRun:!0});u=await K(u);let f=await u.exec(o,{cwd:r.cwd,env:Object.keys(s).length>0?s:void 0,timeoutMs:c});l.stop(),r.json?e(f):(f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr)),f.exitCode!==0&&(process.exitCode=f.exitCode)}catch(e){if(e instanceof we){let t=`Exec transport lost before command status was confirmed. Remote command status is unknown. Original error: ${e.message}. For long-running commands, use \`tangle process spawn\`, \`tangle process logs\`, and \`tangle process kill --tree\`.`;return f(Error(t,{cause:e}))}f(e)}})}function Di(n){n.command(`capabilities`).description(`List fleet drivers and their supported features`).action(async n=>{let{client:r}=D(n),i=d(`Fetching capabilities...`);i.start();let a=await r.fleets.capabilities();i.stop(),n.json?e(a):t(a.drivers,[{key:`driverType`,header:`Driver`,width:16},{key:`sharedWorkspace`,header:`Shared WS`,width:12},{key:`accelerators`,header:`Accel`,width:8},{key:`queueTimings`,header:`Queue`,width:8}])}),n.command(`usage <fleet-id>`).description(`Show fleet usage and reliability insights`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Fetching usage...`);i.start();let a=await r.fleets.usage(t);if(i.stop(),n.json)e(a);else if(o({"Fleet ID":a.usage.fleetId,Status:a.usage.status,Machines:a.usage.machineCount,Running:a.usage.runningMachines,Failed:a.usage.failedMachines,"Runtime (ms)":a.usage.meteredUsage?.runtimeMs,"Reliability score":a.insights.reliabilityScore,"Failure rate":a.insights.failureRate}),a.insights.recommendedActions.length>0){console.log(`
138
- Recommended actions:`);for(let e of a.insights.recommendedActions)console.log(` - ${e}`)}}),n.command(`cost <fleet-id>`).description(`Show the fleet's cost estimate`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Estimating cost...`);i.start();let a=await r.fleets.cost(t);i.stop(),n.json?e(a):o({Plan:a.plan,Currency:a.currency,"Hourly (USD)":a.hourlyUsd,"Max lifetime (s)":a.maxLifetimeSeconds,"Estimated max lifetime (USD)":a.estimatedMaxLifetimeUsd,Machines:a.requestedResources.machines,"Total CPU":a.requestedResources.totalCpu,"Total memory (MB)":a.requestedResources.totalMemoryMb})})}function Oi(e){return[...e.entries()].map(([e,t])=>({machineId:e,sandboxId:t.id,status:t.status}))}function ki(r){r.command(`list <fleet-id>`).description(`List the machines of one fleet (fleet id is required)`).option(`--status <status>`,`Filter machines by status`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Fetching fleet...`);a.start();let o=await i.fleets.list({fleetId:n,status:r.status});a.stop();let s=Oi(o.machines);r.json?e({fleetId:o.fleetId,machines:s}):t(s,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}])}),r.command(`get <fleet-id>`).description(`Show one fleet's manifest (server record)`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Fetching manifest...`);a.start();let s=await i.fleets.manifest(n);a.stop(),r.json?e(s):(o({"Fleet ID":s.fleetId??s.id,Machines:s.machines.length,"Workspace mode":s.workspace?.mode,"Workspace status":s.workspace?.status,"Max lifetime (s)":s.policy?.maxLifetimeSeconds,"Max spend (USD)":s.policy?.maxSpendUsd,Created:s.createdAt,Updated:s.updatedAt}),t(s.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`role`,header:`Role`,width:14},{key:`status`,header:`Status`,width:14}]))}),r.command(`delete <fleet-id>`).description(`Delete a fleet's machine sandboxes and its record`).option(`--continue-on-error`,`Keep deleting remaining machines if one delete fails`).action(async(t,r)=>{let{client:i}=D(r),a=d(`Deleting fleet...`);a.start(),await i.fleets.delete(t,{continueOnError:r.continueOnError}),a.stop(),r.json?e({success:!0,fleetId:t}):n(`Fleet deleted: ${t}`)}),r.command(`reap`).description(`TTL cleanup of all expired fleets (fleet-wide)`).option(`--dry-run`,`Report what would be reaped without deleting`).action(async n=>{let{client:r}=D(n),i=d(`Reaping expired fleets...`);i.start();let a=await r.fleets.reapExpired({dryRun:n.dryRun});i.stop(),n.json?e(a):(o({"Dry run":a.dryRun,Expired:a.expired,Deleted:a.deleted}),t(a.fleets,[{key:`fleetId`,header:`Fleet`,width:24},{key:`expiredAt`,header:`Expired`,width:18},{key:`deleted`,header:`Deleted`,width:10}]))}),r.command(`reconcile`).description(`Drop fleet records whose underlying sandboxes vanished`).option(`--dry-run`,`Report orphans without removing them`).action(async n=>{let{client:r}=D(n),i=d(`Reconciling fleets...`);i.start();let a=await r.fleets.reconcile({dryRun:n.dryRun});i.stop(),n.json?e(a):(o({"Dry run":a.dryRun,Checked:a.checked,Orphaned:a.orphaned,Removed:a.removed}),t(a.machines,[{key:`fleetId`,header:`Fleet`,width:24},{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`removed`,header:`Removed`,width:10}]))})}async function Ai(e,t){let n=await ue({apiKey:t.apiKey,sandboxBaseUrl:t.baseUrl}),r=await fetch(`${n.baseUrl}/v1/agent-profiles/${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${n.token}`,accept:`application/json`}});if(!r.ok){let t=await r.text().catch(()=>``);throw r.status===404?Error(`profile '${e}' not found in the platform catalog (it may be a built-in, a stored profile you own, or neither — run 'tangle profile list' to see what is available)`):Error(`platform returned ${r.status}: ${t.slice(0,200)}`)}let i=await r.json();if(!i.definition||typeof i.definition!=`object`)throw Error(`profile '${e}' resolved but has no definition — the catalog entry is malformed`);return i.definition}async function ji(e){let t=typeof e.envVarName==`string`&&e.envVarName.length>0?e.envVarName:null,n=!!e.fromStdin;if(t&&n)throw Error(`Pass either ${e.flagPrefix}-env or ${e.flagPrefix}-stdin, not both`);if(t){let n=process.env[t];if(!n||n.length===0)throw Error(`${e.flagPrefix}-env points at ${t}, but that environment variable is empty or unset`);return n}if(n){let t=await pe();if(t.length===0)throw Error(`${e.flagPrefix}-stdin received empty input on stdin`);return t}}function Mi(e){if(e.secret===void 0)return;let t=e.backend===`claude-code`?`token`:e.backend===`codex`?`bundle`:void 0;if(!t)throw Error(`--cli-auth needs --backend claude-code or --backend codex`);if(e.apiKeyGiven)throw Error(`--cli-auth cannot be combined with --backend-api-key-env or --backend-api-key-stdin`);return{account:`cli`,secretEnv:e.secret,format:t}}function Ni(e){if(e!==void 0)return e.map(e=>{if(e.includes(`@`)||e.includes(`:`))throw Error(`--secret ${e}: bare secret names only (box delivery). For proxy custody use --proxy-secret with a canonical binding`);return e})}function Pi(e){return{maxLifetimeSeconds:O(e.lifetime,`--lifetime`),idleTimeoutSeconds:O(e.idleTimeout,`--idle-timeout`)}}function Fi(e,t){let n={};return e.cpu!==void 0&&(n.cpuCores=k(e.cpu,`--cpu`)),e.memory!==void 0&&(n.memoryMB=k(e.memory,`--memory`)),e.disk!==void 0&&(n.diskGB=k(e.disk,`--disk`)),t&&(n.accelerator=t),Object.keys(n).length>0?n:void 0}function Ii(e){let t=e.split(`/`);return t.length>=2?{provider:t[0],model:t.slice(1).join(`/`)}:{model:e}}function Li(e){let t={};for(let n of e){let[e,...r]=n.split(`=`);if(!e||r.length===0)throw Error(`--metadata expects values in KEY=VALUE or KEY=JSON format`);t[e]=Ri(r.join(`=`))}return t}function Ri(e){try{return JSON.parse(e)}catch{return e}}function zi(e,t){if(!(!e.gitUrl&&!e.gitRef&&!e.gitDepth&&!e.gitSparse&&!t)){if(!e.gitUrl||typeof e.gitUrl!=`string`)throw Error(`--git-url is required when using git provisioning options`);return{url:e.gitUrl,ref:typeof e.gitRef==`string`?e.gitRef:void 0,depth:typeof e.gitDepth==`string`?k(e.gitDepth,`--git-depth`):void 0,sparse:Array.isArray(e.gitSparse)?e.gitSparse:void 0,auth:t?{token:t}:void 0}}}function Bi(e,t){if(!(!e.storageType&&!e.storageBucket&&!e.storageEndpoint&&!e.storageRegion&&!e.storagePrefix&&!e.storageAccessKeyId&&!t)){if(typeof e.storageType!=`string`||typeof e.storageBucket!=`string`||typeof e.storageAccessKeyId!=`string`||!t)throw Error(`Storage config requires --storage-type, --storage-bucket, --storage-access-key-id, and one of --storage-secret-access-key-env / --storage-secret-access-key-stdin`);return{type:Vi(e.storageType),bucket:e.storageBucket,endpoint:typeof e.storageEndpoint==`string`?e.storageEndpoint:void 0,region:typeof e.storageRegion==`string`?e.storageRegion:void 0,prefix:typeof e.storagePrefix==`string`?e.storagePrefix:void 0,credentials:{accessKeyId:e.storageAccessKeyId,secretAccessKey:t}}}}function Vi(e){if(e===`s3`||e===`gcs`||e===`r2`)return e;throw Error(`--storage-type must be one of s3, gcs, or r2`)}function Hi(e){if(e===void 0)return;let t=[];for(let n of e){let e=n,r=`--proxy-secret <json>`;if(n.startsWith(`@`)){let t=n.slice(1);r=`--proxy-secret @${t}`;try{e=F(t,`utf8`)}catch{throw Error(`${r}: file could not be read`)}}let i;try{i=JSON.parse(e)}catch(e){throw Error(`${r}: not valid JSON (${e instanceof Error?e.message:String(e)})`)}if(Array.isArray(i))t.push(...i);else if(typeof i==`object`&&i)t.push(i);else throw Error(`${r}: expected a binding object or an array of bindings`)}let n=Ge.parse(t);return n.length>0?n:void 0}function Ui(e){c(` Status: ${e.status}`),c(` Provider: ${e.provider}`),c(` GPU: ${e.accelerator.kind} x ${e.accelerator.count}`),e.customerPricePerHourUsd!==void 0&&c(` Customer price: $${e.customerPricePerHourUsd}/hr`),e.estimatedCustomerCostUsd!==void 0&&c(` Max estimate: $${e.estimatedCustomerCostUsd}`),e.billing&&(c(` Billed seconds: ${e.billing.seconds}`),c(` Customer cost: $${e.billing.customerCostUsd}`))}function Wi(e){e.result.stdout&&process.stdout.write(e.result.stdout),e.result.stderr&&process.stderr.write(e.result.stderr),c(`Exit code: ${e.result.exitCode}`)}function Gi(r){let i=r.command(`gpu`).description(`Manage on-demand GPU leases for a sandbox`);i.command(`providers <id-or-name>`).description(`List GPU clouds, whether each credential works, and current prices`).option(`--accelerator-kind <kind>`,`Price this GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Checking GPU providers...`);o.start();let s=await(await G(a,i,n)).gpu.providers(r.acceleratorKind?{accelerator:gi({kind:r.acceleratorKind,count:r.acceleratorCount,memory:r.acceleratorMemory})}:{});if(o.stop(),r.json){e(s);return}t(s.statuses.map(e=>({provider:e.provider,state:e.state,gpu:e.estimate?.providerInstanceType??``,usdHr:e.estimate?e.estimate.customerPricePerHourUsd.toFixed(4):``,pricing:e.estimate?.pricingSource??``,needs:e.envVars.join(` `)})),[{key:`provider`,header:`Provider`},{key:`state`,header:`State`},{key:`gpu`,header:`GPU`},{key:`usdHr`,header:`$/hr`},{key:`pricing`,header:`Price`},{key:`needs`,header:`Needs`}]);for(let e of s.statuses){let t=e.state===`credential-invalid`?e.credential?.detail:e.estimateError;t&&c(`${e.provider}: ${t}`)}s.usable.length===0&&c(`No GPU provider is usable on this deployment: set the variables in Needs for one provider on the server.`)}),i.command(`attach <id-or-name>`).description(`Attach a temporary GPU worker to a sandbox`).requiredOption(`--accelerator-kind <kind>`,`GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--image <image>`,`GPU worker image override`).option(`--env <vars...>`,`Environment variables for the GPU worker (KEY=VALUE)`).requiredOption(`--max-spend-usd <usd>`,`Maximum customer spend for this lease`).requiredOption(`--max-lifetime <duration>`,`Maximum lease lifetime: seconds, or a duration like 30m or 2h`).option(`--idle-timeout <duration>`,`Idle time before destroy, e.g. 10m`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Attaching GPU lease...`);o.start();let s=await(await G(a,i,t)).gpu.attach(vi(r));o.stop(),r.json?e(s):(n(`GPU lease attached: ${s.id}`),Ui(s))}),i.command(`run <id-or-name> <command...>`).description(`Attach a GPU, run a command or script, then destroy it`).requiredOption(`--accelerator-kind <kind>`,`GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--image <image>`,`GPU worker image override`).option(`--env <vars...>`,`Environment variables for the GPU worker and command (KEY=VALUE)`).requiredOption(`--max-spend-usd <usd>`,`Maximum customer spend for this lease`).requiredOption(`--max-lifetime <duration>`,`Maximum lease lifetime: seconds, or a duration like 30m or 2h`).option(`--idle-timeout <duration>`,`Idle time before destroy, e.g. 10m`).option(`--timeout <ms>`,`Command timeout in milliseconds`).option(`--cwd <path>`,`Working directory`).action(async(t,r,i)=>{let a,o,s,c;try{let e=xi(i),{context:n,client:s}=D(i),c=await G(s,n,t),l=d(`Attaching GPU lease...`);l.start(),a=await c.gpu.attach(vi(i)),l.stop();let u=d(`Running GPU command...`);u.start(),o=await c.gpu.exec(a.id,{command:bi(r),...e,cwd:i.cwd}),u.stop(),i.json||Wi(o)}catch(e){s=e}finally{if(a)try{let{context:e,client:n}=D(i);a=await(await G(n,e,t)).gpu.detach(a.id)}catch(e){c=e}}if(s){f(s),c&&f(c);return}if(c){f(c);return}i.json?e({lease:a,result:o}):a&&n(`GPU lease detached: ${a.id}`);let l=o?.result.exitCode;l&&l!==0&&(process.exitCode=l)}),i.command(`list <id-or-name>`).description(`List GPU leases attached to a sandbox`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching GPU leases...`);o.start();let s=await(await G(a,i,n)).gpu.list();o.stop(),r.json?e(s):s.length===0?c(`No GPU leases attached.`):t(s.map(e=>({id:e.id,status:e.status,provider:e.provider,accelerator:`${e.accelerator.kind}x${e.accelerator.count}`,customerUsdHr:e.customerPricePerHourUsd??``})),[{key:`id`,header:`ID`,width:28},{key:`status`,header:`Status`,width:12},{key:`provider`,header:`Provider`,width:12},{key:`accelerator`,header:`GPU`,width:24},{key:`customerUsdHr`,header:`$/hr`,width:10}])}),i.command(`exec <id-or-name> <lease-id> <command...>`).description(`Run a command or script on an attached GPU lease`).option(`--timeout <ms>`,`Command timeout in milliseconds`).option(`--cwd <path>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=d(`Running GPU command...`);s.start();let c=await(await G(o,a,t)).gpu.exec(n,{command:bi(r),...xi(i),cwd:i.cwd});s.stop(),i.json?e(c):Wi(c)}),i.command(`detach <id-or-name> <lease-id>`).description(`Detach and destroy a GPU lease`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=d(`Detaching GPU lease...`);s.start();let c=await(await G(o,a,t)).gpu.detach(r);s.stop(),i.json?e(c):(n(`GPU lease detached: ${c.id}`),Ui(c))})}function Ki(t,r){if(r){e(t);return}if(!t.id){t.kind===`snapshot`&&t.result?.snapshot?n(`Snapshot created: ${t.result.snapshot.snapshotId}`):n(`Sandbox ${t.sandboxId} stopped.`);return}n(`${t.kind===`snapshot`?`Snapshot`:`Stop`} of sandbox ${t.sandboxId} accepted.`),c(`Operation: ${t.id}`),c(`Status: ${t.statusUrl}`)}function qi(e){return`${e.name} (${e.id})`}async function Ji(e,t){if(t.startsWith(`team_`))return e.teams.get(t);let n=(await e.teams.list()).filter(e=>e.name.toLowerCase()===t.toLowerCase());if(n.length===0)throw Error(`Team not found: ${t}`);if(n.length>1)throw Error(`Team name is ambiguous: ${t}. Use a team id instead.`);return n[0]}async function Y(e,t,n){if(t)return Ji(e,t);let r=te(n);if(!r.activeTeamId)throw Error("No active team. Run `tangle team switch <team>` or pass `--team <team>`.");return e.teams.get(r.activeTeamId)}function Yi(e,t){h({id:e.id,name:e.name},t)}function Xi(e){v(e)}async function Zi(e){if(e.explicitTeam&&e.personal)throw Error(`--team and --personal cannot be used together`);if(!e.personal)return e.explicitTeam?(await Ji(e.client,e.explicitTeam)).id:e.activeTeamId}async function Qi(e){if([!!e.explicitTeam,!!e.personal,!!e.allScopes].filter(Boolean).length>1)throw Error(`--team, --personal, and --all-scopes are mutually exclusive`);if(e.allScopes)return`all`;if(e.personal)return`personal`;if(e.explicitTeam)return`team:${(await Ji(e.client,e.explicitTeam)).id}`;if(e.activeTeamId)return`team:${e.activeTeamId}`}function $i(e){if(!e)return e;let t={...e};for(let e of[`authToken`,`execToken`])t[e]!==void 0&&(t[e]=`[REDACTED]`);return t}function ea(r){r.command(`attestation <id-or-name>`).description(`Fetch TEE attestation evidence for a sandbox`).option(`--nonce <hex|auto>`,`Nonce to bind into a fresh attestation report; use auto to generate one`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=r.nonce===`auto`?Ae():r.nonce,s=d(`Fetching TEE attestation...`);s.start();let c=await(await G(a,i,t)).getTeeAttestation(o?{attestationNonce:o}:void 0);s.stop(),r.json?e(c):(n(`Attestation fetched for ${t}`),console.log(`TEE type: ${c.attestation.tee_type}`),console.log(`Evidence bytes: ${c.attestation.evidence.length}`),console.log(`Measurement bytes: ${c.attestation.measurement.length}`),console.log(`Timestamp: ${c.attestation.timestamp}`),c.attestationNonce&&console.log(`Nonce: ${c.attestationNonce}`))}),r.command(`list`).description(`List all sandboxes`).option(`-s, --status <status>`,`Filter by status (running, stopped, deleted, all)`).option(`-l, --limit <n>`,`Limit results`,`50`).option(`--team <team>`,`List sandboxes for a team by id or name`).option(`--personal`,`List personal sandboxes`).option(`--all-scopes`,`List personal and team sandboxes`).action(async n=>{let{context:r,client:i}=D(n),a=d(`Fetching sandboxes...`);a.start();let o=await Qi({client:i,explicitTeam:n.team,personal:n.personal,allScopes:n.allScopes,activeTeamId:r.activeTeamId}),s=await i.list({status:n.status===`all`?void 0:n.status,limit:Number.parseInt(n.limit,10),scope:o});a.stop(),n.json?e(s):t(s.map(e=>({id:e.id,status:e.status,createdAt:e.createdAt,name:e.name??``})),[{key:`id`,header:`ID`,width:24},{key:`status`,header:`Status`,width:14},{key:`createdAt`,header:`Created`,width:16},{key:`name`,header:`Name`,width:20}])}),r.command(`get <id-or-name>`).description(`Get sandbox details`).option(`--profile`,`Show the active agent profile provenance (name, hash, skills)`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching sandbox...`);a.start();let o=await G(i,r,t);if(a.stop(),n.profile){let e=o.getProfileProvenance?.();e?(c(`Agent profile provenance:`),c(` Base profile: ${e.base.name??`(inline)`} (${e.base.sha256.slice(0,12)}...)`),c(` Effective: ${e.effective.name??`(inline)`} (${e.effective.sha256.slice(0,12)}...)`),c(` Materialized: ${e.materializedAt}`),e.base.sha256!==e.effective.sha256&&c(` ⚠ Profile changed since creation (base ≠ effective)`)):c(`No profile materialized (bare sandbox). Create with --profile <name> to install one.`);return}n.json?e(o):l({id:o.id,name:o.name,status:o.status,runtime:o.runtime,resources:o.resources,createdAt:o.createdAt?.toISOString(),expiresAt:o.expiresAt?.toISOString(),connection:o.connection})}),r.command(`shapes`).description(`List the named sandbox sizes, the default, and this account's ceiling`).action(async n=>{let{client:r}=D(n),i=await r.shapes();if(n.json){e(i);return}let o=e=>e.cpuCores<=i.ceiling.cpuCores&&e.memoryMB<=i.ceiling.memoryMB&&e.diskGB<=i.ceiling.diskGB;t(i.presets.map(e=>({name:e.name===i.default?`${e.name} (default)`:e.name,cpu:e.cpuCores,memory:`${e.memoryMB} MB`,disk:`${e.diskGB} GB`,available:o(e)?`yes`:e.name===i.default?`clamped to ceiling`:`above ceiling`})),[{key:`name`,header:`Shape`,width:18},{key:`cpu`,header:`vCPU`,width:6},{key:`memory`,header:`Memory`,width:10},{key:`disk`,header:`Disk`,width:8},{key:`available`,header:`Available`,width:14}]),c(`Ceiling for this account: ${a(i.ceiling)}`)}),r.command(`delete <id-or-name>`).description(`Delete a sandbox`).option(`-f, --force`,`Skip confirmation`).option(`--name`,`Treat the reference as a sandbox name`).addOption(new Be(`--until <state>`,`Wait for physical removal`).choices([`removed`])).option(`--retry-cleanup`,`Retry server-side cleanup after the sandbox disappeared from get/list`).action(async(e,t)=>{if(!t.force&&!await N(`Delete sandbox ${e}? [y/N] `,`--force`)){c(`Cancelled.`);return}let{context:r,client:i}=D(t),a=d(`Deleting sandbox...`);a.start();let o=await Bt(i,r,e,{retryCleanup:t.retryCleanup,name:t.name,until:t.until,beforeDelete:async e=>{let t=await e.listSnapshots().then(e=>e.length,()=>0);t!==0&&(a.clear(),console.error(`This sandbox has ${t} snapshot${t===1?``:`s`}. Deleting the sandbox keeps them until they retire.
139
- List them and their retire date: tangle snapshot list ${e.id}\n Delete one before then: tangle snapshot delete ${e.id} <snapshot-id>`))}});a.stop(),n(o===`already_absent`?`Sandbox ${e} was already gone.`:`Sandbox ${e} deleted.`)}),r.command(`stop <id-or-name>`).description(`Stop a running sandbox`).option(`--name`,`Treat the reference as a sandbox name`).option(`--no-wait`,`Return once the stop is accepted and print the operation to poll`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Stopping sandbox...`);a.start();let o=await G(i,r,e,{nameOnly:t.name});if(t.wait===!1){let e=await o.stop({wait:!1});a.stop(),Ki(e.info,!!t.json);return}await o.stop(),a.stop(),n(`Sandbox ${e} stopped.`)}),r.command(`resume <id-or-name>`).description(`Resume a stopped sandbox`).option(`--wait`,`Wait for sandbox to be running`,!0).option(`-t, --timeout <ms>`,`Resume timeout in milliseconds; a cold resume re-provisions the sandbox, so this defaults higher than other commands (default 120000)`,`120000`).action(async(e,t)=>{let r=O(t.timeout,`--timeout`,`ms`),i=x({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:r}),a=E(i),o=d(`Resuming sandbox...`);o.start();let s=await G(a,i,e);await s.resume({timeoutMs:r}),t.wait&&(o.text=`Waiting for sandbox to start...`,await s.waitFor(`running`,{timeoutMs:r})),o.stop(),n(`Sandbox ${s.id} resumed.`)})}const ta=B.array(B.union([B.cidrv4(),B.cidrv6()])).min(1).max(100);B.strictObject({mode:B.enum([`open`,`strict`,`blocked`]),allowDomains:B.array(B.union([B.string().min(1).max(256),B.strictObject({domain:B.string().min(1).max(256),allowPrivateIps:ta})])).max(100).optional(),includeImplicitDomains:B.boolean().optional()});function na(e){return e===`sandbox`||e===`team`}const ra={mode:`strict`,includeImplicitDomains:!0};function ia(e,t){return e.mode!==`open`||na(t)?e:ra}const aa=e=>typeof e==`string`?e:e.domain;function oa(e,t){if(!e)return{};if(t)throw Error(`--allow-domain is refused for a team sandbox: its own policy would replace the team's egress policy. Create it without the flag; a team owner or admin then runs tangle sandbox egress <id> --allow-domain <hosts>`);return{egressPolicy:{...ra,allowDomains:e}}}function sa(e){let t=e.toJSON().egressRefusedProxySecretHosts??[];if(t.length===0)return;let n=t.join(` `);s(`The egress policy refuses the proxy-secret host ${t.join(`, `)}: a binding does not open its host. Allow it with: tangle sandbox egress ${e.id} --allow-domain ${n} (or create with --allow-domain ${n})`)}async function ca(e,t){for(let n=0;;n++){let r=await e.egress.get(),i=ia(r.policy,r.source);if(i.mode===`open`)return c(`Egress is open: every host is already reachable. Nothing changed.`),r;let a=i.mode===`strict`?i.allowDomains??[]:[],o=new Set(a.map(e=>aa(e).toLowerCase())),s=t.map(e=>e.toLowerCase()).filter(e=>!o.has(e));if(s.length===0)return r;let l={mode:`strict`,allowDomains:[...a,...new Set(s)],includeImplicitDomains:i.mode===`strict`&&i.includeImplicitDomains===!0};try{return await e.egress.update(l,{expectedUpdatedAt:r.updatedAt})}catch(e){if(n===0&&e.code===`CONFLICT`)continue;throw Ft(e,`tangle sandbox egress --help`)}}}function la(t){t.command(`egress <id-or-name>`).description(`Show the egress policy a sandbox enforces, or add hosts to its strict allowlist`).option(`--allow-domain <domains...>`,`Add these hosts to the allowlist; the API judges them. An open policy is left open; a blocked one becomes strict with only these hosts`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=await G(i,r,t),{policy:o,source:s}=n.allowDomain?await ca(a,n.allowDomain):await a.egress.get(),l=ia(o,s);if(n.json){e({policy:l,source:s});return}c(`Egress: ${l.mode} (source ${s})`),l.mode===`strict`&&(c(` Allowed: ${(l.allowDomains??[]).map(aa).join(`, `)||`none`}`),c(` Default registries, Git hosts and model endpoints: ${l.includeImplicitDomains?`included`:`not included`}`))}),t.command(`network <id-or-name>`).description("Show runtime network state (exposed ports) for a sandbox. Outbound policy: `tangle sandbox egress`.").action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Updating network configuration...`);a.start();let o=await G(i,r,t);a.stop();let s=await o.network.getConfig();n.json?e(s):(c(`Network Configuration:`),s.ports&&s.ports.length>0?c(` Exposed Ports: ${s.ports.join(`, `)}`):c(` No exposed ports`))}),t.command(`expose <id-or-name>`).description(`Expose a port and get a public URL`).option(`-p, --port <port>`,`Port to expose`,`8000`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=Number.parseInt(r.port,10);if(Number.isNaN(o)||o<1||o>65535)throw Error(`Port must be a number between 1 and 65535`);let s=d(`Exposing port ${o}...`);s.start();let l=await(await G(a,i,t)).network.exposePort(o);s.stop(),r.json?e({port:o,url:l}):(n(`Port ${o} exposed.`),c(` URL: ${l}`))}),t.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching exposed URLs...`);a.start();let o=await(await G(i,r,t)).network.listUrls();if(a.stop(),n.json)e(o);else{let e=Object.entries(o);if(e.length===0)c(`No ports exposed.`);else{c(`Exposed Ports:`);for(let[t,n]of e)c(` ${t}: ${n}`)}}})}function ua(t){t.command(`create`).option(`--cpu-features <flags>`,`Required Linux CPU flags, comma-separated`).description(`Create a new sandbox`).option(`-n, --name <name>`,`Sandbox name`).option(`-e, --environment <environment>`,pa).addOption(ma()).option(`--bare`,`Create a bare sandbox without the agent runtime`).option(`--ssh`,`Enable SSH access`).option(`--ssh-key <key>`,`SSH public key for authentication`).option(`--ssh-keys <names...>`,`Stored SSH key names or IDs for authentication`).option(`--ssh-key-file <paths...>`,`SSH public key file paths for authentication`).option(`--web-terminal`,`Enable web terminal`).option(`--no-in-box-preview`,`Only your key may publish (public) preview links`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`--secret <names...>`,`Secrets selected by bare name for box delivery (value in the sandbox env). For proxy custody use --proxy-secret`).option(`--proxy-secret <bindings...>`,`Canonical proxy custody binding(s): one binding as inline JSON, or @file with a JSON array. The value stays at the egress proxy and is redeemed only within the binding's scope (hosts/methods/paths/TTL); the box reads a placeholder. Repeatable`).option(`--allow-domain <domains...>`,`Hostnames the sandbox may reach under strict egress, e.g. api.example.com or *.example.com; the platform's own required domains stay allowed. Personal sandboxes only: a team sandbox keeps the team's policy`).option(`--metadata <entries...>`,`Metadata entries (KEY=VALUE or KEY=JSON)`).option(`--cpu <cores>`,"CPU cores (omit for the platform default; see `sandbox shapes`)").option(`--memory <mb>`,`Memory in MB (omit for the platform default)`).option(`--disk <gb>`,`Disk size in GB (omit for the platform default)`).option(`--accelerator-kind <kind>`,`Accelerator kind, for example nvidia-h100 or amd-mi300x`).option(`--accelerator-count <count>`,`Accelerator device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--gpu-provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--gpu-worker-image <image>`,`GPU worker image override`).option(`--gpu-env <vars...>`,`Environment variables for the GPU worker (KEY=VALUE)`).option(`--gpu-max-spend-usd <usd>`,`Maximum customer spend for the create-time GPU lease`).option(`--gpu-max-lifetime <duration>`,`Maximum create-time GPU lease lifetime: seconds, or a duration like 30m or 2h`).option(`--gpu-idle-timeout <duration>`,`Destroy the create-time GPU lease after this idle time: seconds, or a duration like 10m`).option(`--lifetime <duration>`,`Wall-clock lifetime before the sandbox is stopped (not deleted): seconds, or a duration like 90m or 2h; default 3600 = 1h`,`3600`).option(`--idle-timeout <duration>`,`Idle time before the sandbox is stopped (not deleted): seconds, or a duration like 60m; default 900 = 15m. It resumes on next use`,`900`).option(`--from-snapshot <id>`,`Create the sandbox from a snapshot`).option(`--public-template <id-or-slug>`,`Create the sandbox from a published public template`).option(`--public-template-version <id>`,`Pin creation to a specific published public-template version`).option(`--billing-owner <userId>`,`Platform user that pays for the sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).option(`--team <team>`,`Create in a team by id or name`).option(`--personal`,`Create a personal sandbox even when a team is active`).option(`--git-url <url>`,`Git repository URL to clone during provisioning`).option(`--git-ref <ref>`,`Git branch, tag, or commit to checkout`).option(`--git-depth <depth>`,`Git clone depth`).option(`--git-sparse <paths...>`,`Sparse checkout paths`).option(`--git-token-env <name>`,`Name of an environment variable containing the Git HTTPS auth token`).option(`--git-token-stdin`,`Read the Git HTTPS auth token from stdin`).option(`--storage-type <type>`,`BYOS3 storage type (s3, gcs, r2)`).option(`--storage-bucket <name>`,`BYOS3 bucket name`).option(`--storage-endpoint <url>`,`BYOS3 endpoint URL`).option(`--storage-region <region>`,`BYOS3 region`).option(`--storage-prefix <prefix>`,`BYOS3 path prefix`).option(`--storage-access-key-id <id>`,`BYOS3 access key ID`).option(`--storage-secret-access-key-env <name>`,`Name of an environment variable containing the BYOS3 secret access key`).option(`--storage-secret-access-key-stdin`,`Read the BYOS3 secret access key from stdin`).addOption(new Be(`--driver <type>`,`Run on Tangle network operators instead of the platform's hosts (--tee needs it)`).choices([`tangle`])).option(`--backend <type>`,`Backend agent type (${Se.join(`, `)}); amp needs your own Amp token via --backend-api-key-env or --backend-api-key-stdin`).option(`--backend-model <model>`,`Model override (format: provider/model)`).addOption(new Be(`--reasoning-effort <level>`,`Reasoning effort for the backend's model; overrides the profile's model.reasoningEffort`).choices(Ke)).option(`--backend-api-key-env <name>`,`Name of an environment variable containing the BYOK backend API key`).option(`--backend-api-key-stdin`,`Read the BYOK backend API key from stdin`).option(`--cli-auth <secret>`,"Run --backend claude-code or codex on your own subscription: the stored secret holding a `claude setup-token` token or a Codex auth.json (see `tangle secret create`)").option(`--profile <path>`,`Path to an AgentProfile JSON file to install as the sandbox's backend profile (carries skills, tools, MCP, model). Use with --backend; the profile's inline skills materialize into the harness's native skill directory on first turn`).option(`--profile-stdin`,`Read the AgentProfile JSON from stdin instead of a file (use with --profile)`).option(`--tee <type>`,`Require a TEE backend (any, tdx, nitro, sev-snp, phala-dstack)`).option(`--sealed`,`Request TEE sealed-secret support`).option(`--attestation-nonce <hex|auto>`,`Deploy-time attestation nonce; use auto to generate one`).option(`--attestation-refresh`,`Generate a fresh deploy-time attestation nonce when --tee is set`).option(`--require-attestation`,`Fail unless TEE attestation evidence is returned`).option(`--wait`,`Wait for sandbox to be running`,!0).option(`--timeout <ms>`,`HTTP timeout in milliseconds`,`30000`).action(async t=>{let n=await ji({envVarName:t.gitTokenEnv,fromStdin:t.gitTokenStdin,flagPrefix:`--git-token`}),r=await ji({envVarName:t.storageSecretAccessKeyEnv,fromStdin:t.storageSecretAccessKeyStdin,flagPrefix:`--storage-secret-access-key`}),i=await ji({envVarName:t.backendApiKeyEnv,fromStdin:t.backendApiKeyStdin,flagPrefix:`--backend-api-key`}),a=Mi({secret:t.cliAuth,backend:t.backend,apiKeyGiven:i!==void 0}),o;if(t.profileStdin){let e=await pe(`--profile-stdin`,`the AgentProfile JSON`);try{o=JSON.parse(e)}catch{f(Error(`--profile-stdin: the input is not valid JSON`));return}}else if(t.profile){let e=String(t.profile);if(e.startsWith(`.`)||e.startsWith(`/`)||e.endsWith(`.json`))try{o=JSON.parse(F(e,`utf8`))}catch(t){f(ga(e,t));return}else try{o=await Ai(e,t)}catch(t){f(ga(e,t));return}}o=_a(o,t.reasoningEffort);let s=x({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:t.timeout?O(t.timeout,`--timeout`,`ms`):void 0}),c=E(s),l=d(`Creating sandbox...`);l.start();let u=await Zi({client:c,explicitTeam:t.team,personal:t.personal,activeTeamId:s.activeTeamId}),p=Si(t.env??[],`--env`,`env`),m=t.metadata?Li(t.metadata):void 0,h=zi(t,n),g=Bi(t,r),_=t.acceleratorKind?gi({kind:String(t.acceleratorKind),count:String(t.acceleratorCount),memory:typeof t.acceleratorMemory==`string`?t.acceleratorMemory:void 0}):void 0,v=_i({provider:typeof t.gpuProvider==`string`?t.gpuProvider:void 0,image:typeof t.gpuWorkerImage==`string`?t.gpuWorkerImage:void 0,env:Array.isArray(t.gpuEnv)?t.gpuEnv:void 0,maxSpendUsd:typeof t.gpuMaxSpendUsd==`string`?t.gpuMaxSpendUsd:void 0,maxLifetime:typeof t.gpuMaxLifetime==`string`?t.gpuMaxLifetime:void 0,idleTimeout:typeof t.gpuIdleTimeout==`string`?t.gpuIdleTimeout:void 0},!!_,`Create-time GPU lease flags require --accelerator-kind`),y=t.driver?{type:`tangle`}:void 0,b=t.backend||t.backendModel||o?{...t.backend?{type:je(t.backend)}:{},...o?{profile:o}:{},model:t.backendModel||i||a?{...t.backendModel?Ii(t.backendModel):{},apiKey:i,...a?{cliAuth:a}:{}}:void 0}:void 0,S=Ni(t.secret),ee=a?[...new Set([...S??[],a.secretEnv])]:S,C=Hi(t.proxySecret),te=Fi(t,_),w=t.sshKeyFile??(t.ssh&&!t.sshKey&&!t.sshKeys?.length?[ha()]:[]),T=[...t.sshKey?[t.sshKey]:[],...w.map(e=>F(e,`utf8`).trim())],D={name:t.name,environment:t.environment,runtime:t.runtime,cpuFeatures:t.cpuFeatures?.split(`,`).map(e=>e.trim()),bare:t.bare||void 0,sshEnabled:t.ssh||!!t.sshKey||T.length>0||!!t.sshKeys?.length,sshPublicKeys:T.length>0?T:void 0,sshKeyIds:t.sshKeys,webTerminalEnabled:t.webTerminal,inBoxPreviewPublishing:t.inBoxPreview?void 0:!1,env:Object.keys(p).length>0?p:void 0,git:h,...te?{resources:te}:{},gpuLease:v,...Pi(t),storage:g,fromSnapshot:t.fromSnapshot,publicTemplateId:t.publicTemplate,publicTemplateVersionId:t.publicTemplateVersion,teamId:u,...t.billingOwner?{billingOwnerId:t.billingOwner}:{},secrets:ee,...C?{proxySecrets:C}:{},...oa(t.allowDomain,u),metadata:m,driver:y,backend:b},ne=t.tee?{tee:t.tee,sealed:t.sealed||void 0,attestationRefresh:t.attestationRefresh||t.attestationNonce===`auto`||void 0}:void 0,k=ne?await ke(c,{...D,confidential:ne,attestationNonce:t.attestationNonce??(t.attestationRefresh?`auto`:void 0),requireAttestation:t.requireAttestation??!0}):void 0,A=k?.sandbox??await Pt(c,D);t.wait&&(l.text=`Waiting for sandbox to start...`,await A.waitFor(`running`,{timeoutMs:12e4}),await A.refresh()),l.stop();let re=da(A);t.json?e({id:A.id,name:A.name,active:re.active,status:A.status,resources:A.resources,createdAt:A.createdAt,expiresAt:A.expiresAt,connection:$i(A.connection),teamId:u,gpuLease:A.gpuLease,confidential:ne,attestation:k?.attestation,attestationNonce:k?.attestationNonce}):fa(A,re.next,D,{teamId:u,tee:ne?.tee,proof:k}),sa(A)})}function da(e){let t=y();return t||g(e.id),{active:!t,next:t?`Active sandbox is still ${t}. Use this one with: tangle use ${e.id}`:`Active sandbox set to ${e.name??e.id}. Next: tangle agent prompt "<task>"`}}function fa(e,t,r,i){n(`Sandbox created: ${e.id}`),l({id:e.id,name:e.name,status:e.status,runtime:e.runtime,resources:e.resources,createdAt:e.createdAt?.toISOString(),expiresAt:e.expiresAt?.toISOString(),connection:e.connection});for(let[e,t,n]of[[`Idle timeout (requested)`,r.idleTimeoutSeconds,900],[`Lifetime (requested)`,r.maxLifetimeSeconds,3600]])t&&t!==n&&console.log(`${e}: ${le(t)}`);i.teamId&&console.log(`Team: ${i.teamId}`),e.gpuLease&&(console.log(`GPU lease: ${e.gpuLease.id}`),Ui(e.gpuLease)),i.tee&&(console.log(`TEE: ${i.tee}`),console.log(`Attestation: ${i.proof?.attestation?`present`:`not returned`}`),i.proof?.attestationNonce&&console.log(`Attestation nonce: ${i.proof.attestationNonce}`)),c(t)}const pa="A catalog environment, a container image reference, or a built image ID. Firecracker runs only images pinned by repository@sha256 that the cell's Firecracker hosts carry; `tangle environments list` shows each image's runtimes";function ma(){return new Be(`--runtime <runtime>`,`Isolation on the platform's hosts: docker runs a container on the host kernel, firecracker a microVM with its own kernel. Omit for the platform default`).choices(Ee)}function ha(){let e=[`id_ed25519`,`id_ecdsa`,`id_rsa`].map(e=>`${H()}/.ssh/${e}.pub`),t=e.find(e=>P(e));if(!t)throw Error(`--ssh needs a public key and found none at ${e.join(`, `)}. Run ssh-keygen -t ed25519, or pass --ssh-key-file.`);return t}function ga(e,t){return t instanceof p?t:Error(`--profile ${e}: ${t.message}`)}function _a(e,t){if(!t)return e;let n=e?.model??{};return{...e,model:{...n,reasoningEffort:t}}}function va(e){if(e.spec){let t=JSON.parse(F(e.spec,`utf8`));return{base:{fleetId:e.fleetId,defaults:t.defaults,policy:t.policy,workspace:t.workspace,metadata:t.metadata},machines:t.machines??[]}}let t=xa(e),n=Sa(e,!!t?.accelerator),r={...e.environment?{environment:e.environment}:{},...t?{resources:t}:{},...e.runtime?{runtime:e.runtime}:{},...n?{gpuLease:n}:{},...e.backend?{backend:{type:e.backend}}:{}},i=Ca(e),a=Math.max(1,Number(e.count)||1),o=Array.from({length:a},(e,t)=>({machineId:`worker-${t+1}`}));return{base:{fleetId:e.fleetId,defaults:Object.keys(r).length>0?r:void 0,policy:i,workspace:{mode:e.workspace}},machines:o}}function ya(e){let{base:t,machines:n}=va(e);return{...t,machines:n}}function ba(e){let{base:t,machines:n}=va(e);return{...t,workers:n}}function xa(e){let t={};if(e.cpu&&(t.cpuCores=k(e.cpu,`--cpu`)),e.memory&&(t.memoryMB=k(e.memory,`--memory`)),e.disk&&(t.diskGB=k(e.disk,`--disk`)),e.acceleratorKind)t.accelerator=gi({kind:e.acceleratorKind,count:e.acceleratorCount,memory:e.acceleratorMemory});else if(e.acceleratorCount||e.acceleratorMemory)throw Error(`--accelerator-count and --accelerator-memory require --accelerator-kind`);return Object.keys(t).length>0?t:void 0}function Sa(e,t){return _i({provider:e.gpuProvider,image:e.gpuWorkerImage,env:e.gpuEnv,maxSpendUsd:e.gpuMaxSpendUsd,maxLifetime:e.gpuMaxLifetime,idleTimeout:e.gpuIdleTimeout},t,`Fleet GPU lease flags require --accelerator-kind`)}function Ca(e){let t={};return e.maxSpendUsd&&(t.maxSpendUsd=Number(e.maxSpendUsd)),e.maxLifetime&&(t.maxLifetimeSeconds=O(e.maxLifetime,`--max-lifetime`)),Object.keys(t).length>0?t:void 0}function wa(r){r.command(`create`).description(`Create a sandbox fleet`).option(`--fleet-id <id>`,`Stable fleet id (generated when omitted)`).option(`--count <n>`,`Number of worker machines`,`1`).option(`--environment <environment>`,pa).addOption(ma()).option(`--cpu <cores>`,`CPU cores per machine`).option(`--memory <mb>`,`Memory in MB per machine`).option(`--disk <gb>`,`Disk in GB per machine`).option(`--accelerator-kind <kind>`,`Accelerator kind per machine, for example nvidia-l4 or nvidia-h100`).option(`--accelerator-count <count>`,`Accelerator devices per machine`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--gpu-provider <provider>`,`GPU cloud provider per machine; omitted picks the cheapest configured provider`).option(`--gpu-worker-image <image>`,`GPU worker image override`).option(`--gpu-env <vars...>`,`Environment variables for each GPU worker (KEY=VALUE)`).option(`--gpu-max-spend-usd <usd>`,`Maximum spend per machine GPU lease`).option(`--gpu-max-lifetime <duration>`,`Maximum GPU lease lifetime per machine: seconds, or a duration like 2h`).option(`--gpu-idle-timeout <duration>`,`Destroy each GPU lease after this idle time: seconds, or a duration like 10m`).option(`--backend <id>`,`Agent backend type`).option(`--workspace <mode>`,`Workspace mode: isolated (no driver supports shared yet)`,`isolated`).option(`--max-spend-usd <n>`,`Fleet spend cap in USD (policy)`).option(`--max-lifetime <duration>`,`Max lifetime, e.g. 2h (policy)`).option(`--spec <file.json>`,`Path to a JSON file describing the fleet (overrides synthesized machines)`).option(`--coordinator`,`Create a coordinator + workers fleet (routes to createWithCoordinator)`).action(async r=>{let{client:i}=D(r),a=d(`Creating fleet...`);a.start();let o=r.coordinator?await i.fleets.createWithCoordinator(ba(r)):await i.fleets.create(ya(r));a.stop();let s=Oi(o.machines);r.json?e({fleetId:o.fleetId,machines:s}):(n(`Fleet created: ${o.fleetId}`),t(s,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}]))})}function Ta(r){r.command(`exec <fleet-id> <command>`).description(`Run a shell command across the fleet's machines`).option(`--machine <id...>`,`Restrict to a subset of machine ids (default: all)`).option(`--cwd <dir>`,`Working directory for the command`).option(`--timeout <ms>`,`Per-machine timeout in milliseconds`).option(`--max-concurrent <n>`,`Max concurrent dispatches`).action(async(n,r,i)=>{let{client:a}=D(i),o=d(`Dispatching command...`);o.start();let s=await(await a.fleets.list({fleetId:n})).dispatchExecDetailed(r,{machines:i.machine,cwd:i.cwd,timeoutMs:i.timeout?O(i.timeout,`--timeout`,`ms`):void 0,maxConcurrent:i.maxConcurrent?Number(i.maxConcurrent):void 0});if(o.stop(),i.json)e(s);else{t(s.results.map(e=>({machineId:e.machineId,ok:e.ok,exitCode:e.result?.exitCode,durationMs:e.durationMs})),[{key:`machineId`,header:`Machine`,width:20},{key:`ok`,header:`OK`,width:6},{key:`exitCode`,header:`Exit`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14}]);for(let e of s.results){let t=e.result?.stdout,n=e.result?.stderr;t&&(console.log(`\n[${e.machineId}] stdout:`),console.log(t)),n&&(console.log(`\n[${e.machineId}] stderr:`),console.log(n)),e.error&&console.log(`\n[${e.machineId}] error: ${e.error.message}`)}}s.results.some(e=>e.ok===!1)&&(process.exitCode=1)}),r.command(`run [prompt]`).description(`Create a fleet of agents, run one turn on every agent, print each result, then delete the fleet`).requiredOption(`--agents <n|file>`,`Number of agents, or a JSON file with an array of agent specs (agentId, harness, model, profile or { profileId, revision }, task)`).option(`--placement <mode>`,`auto (pack by sandbox memory), dedicated (one sandbox per agent), or a number of agents per sandbox`,`auto`).option(`--model <id>`,`Model every agent runs, e.g. gpt-4.1-mini`).option(`--memory <mb>`,`Memory in MB per sandbox; auto placement packs by it`).option(`--environment <environment>`,`Environment for each sandbox`).option(`--max-spend-usd <usd>`,`Budget for the fleet in USD, enforced by the Platform on the fleet's own key`).option(`--timeout <ms>`,`Per-agent turn timeout in milliseconds`).option(`--fleet-id <id>`,`Stable fleet id (generated when omitted)`).option(`--parent-fleet <id>`,`Fleet that spawns this one; its cap must cover this cap`).option(`--parent-agent <id>`,`Agent of --parent-fleet that spawns this one`).option(`--keep`,`Keep the fleet after the run instead of deleting it`).action(async(t,r)=>{let i=/^\d+$/.test(r.agents)?Number(r.agents):JSON.parse(F(r.agents,`utf8`));if(!Array.isArray(i)&&t===void 0)throw Error(`A prompt is required unless --agents names a file whose agents carry tasks`);let{client:a}=D(r);if(!!r.parentFleet!=!!r.parentAgent)throw Error(`--parent-fleet and --parent-agent go together`);let s=r.placement===`auto`||r.placement===`dedicated`?r.placement:{agentsPerSandbox:Number(r.placement)},c=r.maxSpendUsd?Number(r.maxSpendUsd):void 0,l=r.timeout?O(r.timeout,`--timeout`,`ms`):void 0,u=d(`Creating fleet...`);u.start();let f=Date.now(),p=await a.fleets.create({fleetId:r.fleetId,agents:i,placement:s,defaults:{...r.environment?{environment:r.environment}:{},...r.memory?{resources:{memoryMB:k(r.memory,`--memory`)}}:{},...r.model?{backend:{type:`opencode`,model:{model:r.model}}}:{}},...c===void 0?{}:{budgetUsd:c},...r.parentFleet?{parent:{fleetId:r.parentFleet,agentId:r.parentAgent}}:{}}),m=Date.now()-f;u.stop(),r.json||n(`Fleet ${p.fleetId}: ${p.agents.length} agents on ${p.machines.size} sandboxes in ${m} ms`);let h=[],g;try{for await(let e of p.run(t,{timeoutMs:l})){if(e.type===`agent.finished`&&!r.json){let t=e.result;console.log(`[${t.agentId}] ${t.harness??`default`}/${t.model??`default`} ${t.status} ${t.durationMs}ms ${t.costUsd===void 0?`no cost reported`:`$${t.costUsd.toFixed(5)}`} ${t.result?.response??t.error??``}`)}e.type===`fleet.finished`&&(h=e.results,g=e.spend)}}finally{r.keep||await p.delete({continueOnError:!0})}r.json?e({fleetId:p.fleetId,createMs:m,sandboxes:p.machines.size,results:h,spend:g,deleted:!r.keep}):o({fleetId:p.fleetId,completed:h.filter(e=>e.status===`completed`).length,agents:h.length,spend:JSON.stringify(g),deleted:!r.keep}),h.some(e=>e.status!==`completed`)&&(process.exitCode=1)}),r.command(`cancel <fleet-id>`).description(`Interrupt every agent of a fleet and cancel its child fleets; sandboxes keep running`).action(async(t,r)=>{let{client:i}=D(r),a=await(await i.fleets.list({fleetId:t})).cancel();r.json?e({fleetId:t,...a}):n(`Fleet ${t}: interrupted ${a.interrupted} agents, cancelled ${a.children} child fleets`)})}const Ea=[`list`,`create`,`delete`,`exec`,`prompt`,`read`,`write`];function Da(e){if(!(!e||e.length===0)){for(let t of e)if(!Ea.includes(t))throw Error(`Invalid token action '${t}'. Allowed: ${Ea.join(`, `)}`);return e}}function Oa(e){return e.length<=12?`****`:`${e.slice(0,6)}...${e.slice(-4)} (masked — use --json for full value)`}function ka(t){t.command(`token <fleet-id>`).description(`Mint a scoped fleet bearer token (treated as a secret)`).option(`--action <a...>`,`Allowed actions: list create delete exec prompt read write (prompt grants nothing since fleet prompt dispatch was removed)`).option(`--ttl-minutes <n>`,`Token lifetime in minutes`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Minting fleet token...`);i.start();let a=await r.fleets.createToken(t,{actions:Da(n.action),ttlMinutes:n.ttlMinutes?k(n.ttlMinutes,`--ttl-minutes`):void 0});i.stop(),n.json?e(a):(o({"Fleet ID":a.fleetId,Token:Oa(a.token),"Expires at":new Date(a.expiresAt).toISOString(),Actions:a.actions.join(`, `)}),console.log(`
140
- Re-run with --json to print the full token value.`))})}function Aa(){let r=new z(`workspace`).description(`Manage a fleet's shared workspace`);return r.command(`snapshot <fleet-id>`).description(`Snapshot the fleet's shared workspace`).action(async(t,r)=>{let{client:i}=D(r),a=d(`Creating workspace snapshot...`);a.start();let o=await i.fleets.createWorkspaceSnapshot(t);a.stop(),r.json?e(o):n(`Workspace snapshot created: ${o.snapshotId??o.id}`)}),r.command(`restore <fleet-id> <snapshot-id>`).description(`Restore the fleet's shared workspace from a snapshot`).action(async(t,r,i)=>{let{client:a}=D(i),o=d(`Restoring workspace...`);o.start();let s=await a.fleets.restoreWorkspaceSnapshot(t,r);o.stop(),i.json?e(s):n(`Workspace restored from ${s.snapshotId??r}`)}),r.command(`reconcile <fleet-id>`).description(`Re-mount the shared workspace on all fleet machines`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Reconciling workspace...`);a.start();let s=await i.fleets.reconcileWorkspace(n);a.stop(),r.json?e(s):(o({"Fleet ID":s.fleetId,Checked:s.checked,"Orphaned mounts":s.orphanedMounts}),t(s.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`mounted`,header:`Mounted`,width:10}]))}),r}function ja(){let e=new z(`fleet`).description(`Manage sandbox fleets`);return wa(e),ki(e),e.addCommand(Aa()),Ta(e),Di(e),ka(e),e}function Ma(){let t=new z(`fs`).description(`File system operations on sandboxes`);return t.command(`upload`).description(`Upload a file to a sandbox`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<local-path>`,`Local file path`).argument(`<remote-path>`,`Remote destination path`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);if(s=await K(s),!ge.existsSync(n))throw Error(`Local file not found: ${n}`);let c=ge.statSync(n),l=Date.now();i.json||console.error(`Uploading ${n} to ${r}...`),await s.fs.upload(n,r,{onProgress:e=>{if(i.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesUploaded}/${e.totalBytes} bytes)`)}});let u=Date.now()-l;i.json||console.error(``),i.json?e({success:!0,localPath:n,remotePath:r,size:c.size,durationMs:u}):console.log(`✓ Uploaded ${c.size} bytes in ${u}ms`)}),t.command(`download`).description(`Download a file from a sandbox`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<remote-path>`,`Remote file path`).argument(`<local-path>`,`Local destination path`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);s=await K(s);let c=Date.now();i.json||console.error(`Downloading ${n} to ${r}...`),await s.fs.download(n,r,{onProgress:e=>{if(i.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesDownloaded}/${e.totalBytes} bytes)`)}});let l=Date.now()-c,u=ge.statSync(r);i.json||console.error(``),i.json?e({success:!0,remotePath:n,localPath:r,size:u.size,durationMs:l}):console.log(`✓ Downloaded ${u.size} bytes in ${l}ms`)}),t.command(`ls`).description(`List directory contents`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`[path]`,`Directory path`,`.`).option(`-l, --long`,`Show detailed information`).option(`-a, --all`,`Include hidden files`).action(async(t,n,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);s=await K(s);let c=await s.fs.list(n,{all:i.all,long:i.long});if(i.json)e(c);else if(i.long)r([`Mode`,`Owner`,`Group`,`Size`,`Modified`,`Name`],c.map(e=>{let t=e.isDir?`d`:e.isSymlink?`l`:`-`,n=Na(e.permissions),r=e.isDir?`<DIR>`:Pa(e.size),i=e.modTime.toLocaleDateString();return[t+n,e.owner,e.group,r,i,e.name]}));else{let e=c.map(e=>e.isDir?`${e.name}/`:e.name);console.log(e.join(` `))}}),t.command(`stat`).description(`Get file or directory information`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to file or directory`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.fs.stat(n);r.json?e(s):(console.log(` File: ${s.name}`),console.log(` Path: ${s.path}`),console.log(` Size: ${Pa(s.size)} (${s.size} bytes)`),console.log(` Type: ${s.isDir?`directory`:s.isSymlink?`symlink`:`file`}`),console.log(` Mode: ${Na(s.permissions)} (${s.permissions.toString(8)})`),console.log(` Owner: ${s.owner}`),console.log(` Group: ${s.group}`),console.log(` Modified: ${s.modTime.toISOString()}`),console.log(` Accessed: ${s.accessTime.toISOString()}`))}),t.command(`cat`).description(`Print file contents`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to file`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.read(n);r.json?e({path:n,content:s}):console.log(s)}),t.command(`rm`).description(`Delete a file or directory`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to delete`).option(`-r, --recursive`,`Delete directories recursively`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o),await o.fs.delete(n,{recursive:r.recursive}),r.json?e({success:!0,path:n,deleted:!0}):console.log(`✓ Deleted: ${n}`)}),t.command(`mkdir`).description(`Create a directory`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Directory path to create`).option(`-p, --parents`,`Create parent directories as needed`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o),await o.fs.mkdir(n,{recursive:r.parents}),r.json?e({success:!0,path:n,created:!0}):console.log(`✓ Created: ${n}`)}),t.command(`exists`).description(`Check if a path exists`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to check`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.fs.exists(n);r.json?e({path:n,exists:s}):(console.log(s?`exists`:`not found`),process.exit(+!s))}),t}function Na(e){let t=[`r`,`w`,`x`],n=``;for(let r=2;r>=0;r--){let i=r*3;for(let r=0;r<3;r++)n+=e>>i+(2-r)&1?t[r]:`-`}return n}function Pa(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return r===0?`${n}${t[r]}`:`${n.toFixed(1)}${t[r]}`}function Fa(){let t=new z(`git`).description(`Git operations in a sandbox workspace`);return t.command(`status`).description(`Show git repository status`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching status...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.status();if(a.stop(),n.json)e(s);else if(!s.isRepo)console.log(`No git repository in the sandbox workspace.`);else{if(console.log(`Branch: ${s.branch??`unknown`}`),console.log(`HEAD: ${s.head.slice(0,7)||`(no commits)`}`),console.log(`Dirty: ${s.isDirty?`yes`:`no`}`),s.ahead&&console.log(`Ahead: ${s.ahead}`),s.behind&&console.log(`Behind: ${s.behind}`),s.staged.length>0){console.log(`\nStaged (${s.staged.length}):`);for(let e of s.staged)console.log(` + ${e}`)}if(s.modified.length>0){console.log(`\nModified (${s.modified.length}):`);for(let e of s.modified)console.log(` M ${e}`)}if(s.untracked.length>0){console.log(`\nUntracked (${s.untracked.length}):`);for(let e of s.untracked)console.log(` ? ${e}`)}}}),t.command(`log`).description(`Show commit log`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`-n, --limit <count>`,`Max commits to show`,`10`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching log...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.log(Number.parseInt(n.limit,10));if(a.stop(),n.json)e(s);else if(s.length===0)console.log(`No commits found`);else for(let e of s)console.log(`${e.shortSha} ${e.message.split(`
141
- `)[0]} (${e.author}, ${e.date.toLocaleDateString()})`)}),t.command(`diff`).description(`Show diff`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--ref <ref>`,`Ref to diff against`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching diff...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.diff(n.ref);a.stop(),n.json?e(s):s.raw?console.log(s.raw):console.log(`${s.additions} additions, ${s.deletions} deletions across ${s.files.length} files`)}),t.command(`add`).description(`Stage files`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<paths...>`,`Paths to stage`).action(async(e,t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,e);o=await K(o),await o.git.add(t),n(`Staged: ${t.join(`, `)}`)}),t.command(`commit`).description(`Create a commit`).argument(`<id-or-name>`,`Sandbox ID or name`).requiredOption(`-m, --message <msg>`,`Commit message`).option(`--amend`,`Amend the previous commit`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.git.commit(r.message,{amend:r.amend});r.json?e(s):n(`Committed: ${s.shortSha} ${s.message}`)}),t.command(`push`).description(`Push to remote`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--force`,`Force push`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Pushing...`);a.start();let o=await G(i,r,e);o=await K(o),await o.git.push({force:t.force}),a.stop(),n(`Pushed to remote`)}),t.command(`pull`).description(`Pull from remote`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--rebase`,`Rebase instead of merge`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Pulling...`);a.start();let o=await G(i,r,e);o=await K(o),await o.git.pull({rebase:t.rebase}),a.stop(),n(`Pulled from remote`)}),t.command(`branches`).description(`List branches`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(t,n)=>{let{context:i,client:a}=D(n),o=d(`Fetching branches...`);n.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.git.branches();o.stop(),n.json?e(c):c.length===0?console.log(`No branches found`):r([`Name`,`Current`,`Remote`],c.map(e=>[e.name,e.current?`* `:` `,e.upstream??`-`]))}),t.command(`checkout`).description(`Checkout a branch or ref`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<ref>`,`Branch name or ref`).option(`-b, --create`,`Create a new branch`).action(async(e,t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,e);o=await K(o),await o.git.checkout(t,{create:r.create}),n(`Checked out: ${t}${r.create?` (new)`:``}`)}),t}function Ia(){let n=new z(`intelligence`).description(`Create and inspect trace intelligence reports`);return n.command(`connect [agent]`).alias(`connect-agent`).description(`Connect local agent CLIs to Tangle Intelligence`).option(`--endpoint <url>`,`OTLP endpoint base`,En).option(`--workspace <path>`,`Workspace to write hook files into`,`.`).option(`--service-name <name>`,`OTel service.name label`).option(`--environment <name>`,`OTel deployment.environment label`,`local`).option(`--dry-run`,`Print planned writes without changing files`).option(`--hook-command <command>`,`Command native hooks should run`,`tangle intelligence hook`).option(`--no-smoke`,`Skip the install smoke trace`).action(async(t,n)=>{let r=t??`local`;jn(r);let i=Ra(n.apiKey),a=await In({selection:r,workspace:n.workspace,apiKey:i,endpoint:n.endpoint,serviceName:n.serviceName??Nn(n.workspace),environment:n.environment,smoke:n.smoke,dryRun:!!n.dryRun,hookCommand:n.hookCommand}),s={configPath:a.configPath,agents:a.agents,nativeAgents:a.nativeAgents,manual:a.manual,written:a.written,smokeTraceId:a.smokeTraceId};if(n.json){e(s);return}o({Config:a.configPath,Agents:a.agents.join(`, `),"Native Hooks":a.nativeAgents.join(`, `)||void 0,"Manual Setup":a.manual.length?a.manual.map(e=>`${e.label}: ${e.reason}`).join(` `):void 0,Files:a.written.join(`, `),"Smoke Trace":a.smokeTraceId})}),n.command(`doctor`).description(`Check whether your agent traces carry CONTENT or are metadata-only`).option(`--endpoint <url>`,`OTLP endpoint base`,En).action(async t=>{let n=Fn(),r=await Vn({endpoint:t.endpoint===`https://intelligence.tangle.tools/v1/otlp`?n?.endpoint??`https://intelligence.tangle.tools/v1/otlp`:t.endpoint,apiKey:Ra(t.apiKey??n?.apiKey)});t.json?e(r):La(r),r.contentSeen||(process.exitCode=1)}),n.command(`hook`).description(`Emit one local agent hook event to Tangle Intelligence`).requiredOption(`--agent <agent>`,`Agent surface`).requiredOption(`--event <event>`,`Hook event name`).option(`--payload <json>`,`Hook payload JSON`).option(`--endpoint <url>`,`OTLP endpoint base`).option(`--service-name <name>`,`OTel service.name label`).option(`--environment <name>`,`OTel deployment.environment label`).option(`--session-id <id>`,`Session id override`).option(`--dry-run`,`Build the OTLP request without sending it`).option(`--non-blocking`,`Do not fail the parent agent process`).action(async t=>{try{let n=za(t.agent),r=Fn(),i={agent:n,event:t.event,endpoint:t.endpoint??r?.endpoint??`https://intelligence.tangle.tools/v1/otlp`,apiKey:Ra(t.apiKey??r?.apiKey),serviceName:t.serviceName??r?.serviceName??Nn(process.cwd()),environment:t.environment??r?.environment??`local`,sessionId:t.sessionId,payload:t.payload===void 0?await Va():Ba(t.payload)};if(t.dryRun){let r=Rn(i);if(t.json){e(r);return}o({Trace:r.traceId,Agent:n,Event:t.event});return}let a=await zn(i);if(t.json){e({traceId:a});return}o({Trace:a,Agent:n,Event:t.event})}catch(n){if(t.nonBlocking){let r=n instanceof Error?n.message:String(n);t.json?e({ok:!1,error:r}):console.error(`Tangle Intelligence hook skipped: ${r}`);return}f(n)}}),n.command(`sandbox <sandbox-id>`).description(`Create an intelligence report for one sandbox`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async(e,t)=>{await Ha({type:`sandbox`,id:e},t)}),n.command(`fleet <fleet-id>`).description(`Create an intelligence report for a sandbox fleet`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async(e,t)=>{await Ha({type:`fleet`,id:e},t)}),n.command(`create`).description(`Create a trace intelligence report`).requiredOption(`--subject-type <type>`,`sandbox | fleet`).requiredOption(`--subject-id <id>`,`Subject identifier`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async e=>{await Ha({type:Wa(e.subjectType),id:e.subjectId},e)}),n.command(`get <job-id>`).description(`Get an intelligence report`).action(async(t,n)=>{let{client:r}=D(n),i=n.json?null:d(`Fetching intelligence report...`);i?.start();let a=await r.intelligence.getReport(t);if(i?.stop(),n.json){e(a);return}Ua(a)}),n.command(`list`).description(`List intelligence reports`).option(`--subject-type <type>`,`sandbox | fleet`).option(`--subject-id <id>`,`Subject identifier`).option(`--limit <count>`,`Maximum reports to return`).action(async n=>{let{client:r}=D(n),i=n.json?null:d(`Fetching intelligence reports...`);i?.start();let a=await r.intelligence.listReports({subjectType:n.subjectType===void 0?void 0:Wa(n.subjectType),subjectId:n.subjectId,limit:n.limit===void 0?void 0:qa(n.limit)});if(i?.stop(),n.json){e(a);return}t(a.map(e=>({jobId:e.jobId,subject:`${e.subject.type}:${e.subject.id}`,mode:e.mode,status:e.status,cost:`$${e.billing.costUsd.toFixed(2)}`,updatedAt:e.updatedAt})),[{key:`jobId`,header:`Job`,width:20},{key:`subject`,header:`Subject`,width:28},{key:`mode`,header:`Mode`,width:15},{key:`status`,header:`Status`,width:14},{key:`cost`,header:`Cost`,width:10},{key:`updatedAt`,header:`Updated`,width:18}])}),n}function La(e){o({Status:e.contentSeen?`content flowing`:e.tracesSeen?`metadata-only — a content gate is missing`:`no traces yet`,"Traces seen":e.tracesSeen?`yes`:`no`,"Content seen":e.contentSeen?`yes`:`no`,"Last seen":e.lastSeenAt??`never`,Window:`${e.windowDays}d`});let n=Object.entries(e.byAgent);n.length>0&&(console.log(),t(n.map(([e,t])=>({agent:e,traces:t.tracesSeen?`yes`:`no`,content:t.contentSeen?`yes`:`no`})),[{key:`agent`,header:`Agent`,width:18},{key:`traces`,header:`Traces`,width:10},{key:`content`,header:`Content`,width:10}]))}function Ra(e){let t=e??process.env.TANGLE_INTELLIGENCE_API_KEY??process.env.TANGLE_API_KEY;if(!t)throw Error(`--api-key, TANGLE_INTELLIGENCE_API_KEY, or TANGLE_API_KEY is required`);return t}function za(e){if(Mn(e))return e;throw Error(`agent must be a known Tangle Intelligence agent surface`)}function Ba(e){try{return JSON.parse(e)}catch(e){throw Error(`--payload must be JSON: ${e instanceof Error?e.message:String(e)}`)}}async function Va(){if(process.stdin.isTTY)return;let e=``;for await(let t of process.stdin)if(e+=typeof t==`string`?t:t.toString(`utf8`),e.length>65536)throw Error(`hook payload exceeds 65536 bytes`);let t=e.trim();if(t)try{return JSON.parse(t)}catch{return{body:t.slice(0,4096)}}}async function Ha(t,n){let r=Ga(n.mode),i=Ja(n.metadata),a=n.maxUsd===void 0?void 0:Ka(n.maxUsd);if(r===`agentic`&&a===void 0)throw Error(`Agentic intelligence reports require --max-usd`);let{client:o}=D(n),s=n.json?null:d(`Creating intelligence report...`);s?.start();let c=await o.intelligence.createReport({subject:t,mode:r,...a===void 0?{}:{budget:{billTo:`customer`,maxUsd:a}},...i===void 0?{}:{metadata:i}});if(s?.stop(),n.json){e(c);return}Ua(c)}function Ua(t){o({Job:t.jobId,Subject:`${t.subject.type}:${t.subject.id}`,Mode:t.mode,Status:t.status,"Billed To":t.billing.billedTo,Cost:`$${t.billing.costUsd.toFixed(2)}`,Budget:t.billing.budgetMaxUsd===void 0?void 0:`$${t.billing.budgetMaxUsd.toFixed(2)}`,Updated:t.updatedAt}),t.result!==null&&(console.log(),e(t.result))}function Wa(e){if(e===`sandbox`||e===`fleet`)return e;throw Error(`subject type must be sandbox or fleet`)}function Ga(e){if(e===`deterministic`||e===`agentic`)return e;throw Error(`mode must be deterministic or agentic`)}function Ka(e){let t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`--max-usd must be a non-negative number`);return t}function qa(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Ja(e){if(e===void 0)return;let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`--metadata must be a JSON object`);return t}const Ya=[`router`,`sandbox`,`blueprint-agent`,`evals`,`agent-builder`];async function Xa(e,t){let n=await ue({...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.platformUrl===void 0?{}:{baseUrl:e.platformUrl},...e.baseUrl===void 0?{}:{sandboxBaseUrl:e.baseUrl}});if(!t||!n.minted)return n;throw Error("This command needs a key you minted yourself. A browser login is exchanged for a short-lived key the platform will not accept for key management. Set TANGLE_API_KEY, run `tangle auth login --api-key sk-tan-…`, or mint the key in the web console. `tangle keys list` works from the login alone.")}async function Za(e,t,n={}){let r=new Headers(n.headers);n.body&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await de(e,t,{...n,headers:r});if(n.expected!==void 0&&i.status!==n.expected)throw Error(await Qa(i,t));return i}async function Qa(e,t){let n=await e.text().catch(()=>``),r;try{let e=JSON.parse(n),t=typeof e?.error==`string`?e.error:e?.error?.message;typeof t==`string`&&t.trim()&&(r=t)}catch{}if(r)return`${r} (HTTP ${e.status})`;let i=n?`: ${n.slice(0,400)}`:``;return`Platform request to ${t} returned ${e.status}${i}`}const $a=[`ID`,`Prefix`,`Name`,`Product`,`Created`,`Last used`,`Expires`];function eo(e){return[e.id,e.keyPrefix??``,e.name,e.product??`all`,e.createdAt,e.lastUsedAt??`—`,e.expiresAt??`—`]}function to(){let t=new z(`keys`).description(`Manage sk-tan-* API keys on id.tangle.tools`);return t.command(`list`).description(`List your active API keys`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async t=>{let n=await Xa(t,!1),i=n.baseUrl,a=await(await Za(n,`${i}/v1/keys`,{expected:200})).json();if(t.json){e(a);return}r($a,a.data.map(eo))}),t.command(`create`).description(`Create a new API key`).argument(`<name>`,`Human-readable name for the key`).option(`--product <product>`,`Restrict the key to one product (${Ya.join(`|`)}). Omit for all products.`).option(`--budget-usd <amount>`,`Hard budget cap in USD`).option(`--rpm-limit <limit>`,`Requests-per-minute cap`).option(`--expires-in-days <days>`,`Expire the key after N days (integer)`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async(t,r)=>{if(r.product!==void 0&&!Ya.includes(r.product))throw Error(`Invalid --product. Expected one of ${Ya.join(`, `)}`);let i=await Xa(r,!0),a=i.baseUrl,o=r.expiresInDays===void 0?void 0:new Date(Date.now()+k(r.expiresInDays,`--expires-in-days`)*24*60*60*1e3).toISOString(),s=d(`Creating API key...`);s.start();let l=await Za(i,`${a}/v1/keys`,{method:`POST`,expected:201,body:JSON.stringify({name:t,product:r.product,budgetUsd:r.budgetUsd?Number.parseFloat(r.budgetUsd):void 0,rpmLimit:r.rpmLimit?Number.parseInt(r.rpmLimit,10):void 0,expiresAt:o})});s.stop();let u=await l.json();if(r.json){e(u);return}n(`API key created: ${u.data.prefix}…`),c(`Copy this key now — it will never be shown again:\n${u.data.key}`)}),t.command(`revoke`).description(`Revoke an API key`).argument(`<keyId>`,"Key ID (from `tcloud keys list`)").option(`--yes`,`Skip the confirmation prompt`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async(t,r)=>{let i=await Xa(r,!0),a=i.baseUrl;if(!r.yes&&!await N(`Revoke key ${t}? Any service still using it will start to fail.`,`--yes`)){c(`Aborted.`);return}let o=await(await Za(i,`${a}/v1/keys/${encodeURIComponent(t)}`,{method:`DELETE`,expected:200})).json();if(r.json){e(o);return}n(`Revoked ${t}`)}),t}function X(e){if(b().token)throw Error(`A line relay cannot manage numbers or attachments. Use your owner CLI outside the agent box.`);return E(x(e))}function no(e){if(!e.yes)throw Error(`Review the selected line and use --yes to authorize this change. Attaching enables metered agent work.`)}function ro(e){if(e===`imessage`||e===`whatsapp`||e===`email`||e===`sms`||e===`voice`||e===`telegram`)return e;throw Error(`--transport must be imessage, whatsapp, email, sms, voice, or telegram`)}function Z(e){return e().catch(f)}async function io(e){let t=await st(e,`r`);try{if(!(await t.stat()).isFile())throw Error(`Attachment input must be a regular JSON file`);let e=Buffer.alloc(131073),n=0;for(;n<e.length;){let{bytesRead:r}=await t.read(e,n,e.length-n,null);if(r===0)break;n+=r}if(n===e.length)throw Error(`Attachment JSON exceeds 128 KiB`);let r;try{r=JSON.parse(e.subarray(0,n).toString(`utf8`))}catch{throw Error(`Attachment file is not valid JSON`)}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Attachment JSON must be an object`);if(Object.hasOwn(r,`number`))throw Error(`Use the line ID argument, not a number field in the attachment file`);return r}finally{await t.close()}}function ao(t){t.command(`providers`).description(`List provider transports supported by this Hub deployment`).action(t=>Z(async()=>{e(await X(t).lines.providers())})),t.command(`list`).description(`List owned lines, optionally for a saved agent profile or sandbox`).option(`--profile-id <id>`,`Stored profile ID`).option(`--sandbox <id>`,`Existing sandbox ID`).action(t=>Z(async()=>{e(await X(t).lines.list({profileId:t.profileId,sandboxId:t.sandbox}))})),t.command(`get`).argument(`<line-id>`).description(`Inspect a line and its current attachment`).action((t,n)=>Z(async()=>{e(await X(n).lines.get(t))})),t.command(`numbers`).argument(`<connection-id>`).description(`Discover owned provider numbers; this does not purchase or reserve a number`).option(`--transport <transport>`,`imessage, whatsapp, or sms`,`imessage`).action((t,n)=>Z(async()=>{let r=ro(n.transport);if(r===`email`)throw Error(`Email uses an owned mailbox, not phone inventory`);if(r===`voice`)throw Error(`Voice numbers are listed by ph0ny; provide the owned number ID to lines connect`);if(r===`telegram`)throw Error(`Telegram uses an owned bot, not phone inventory`);e(await X(n).lines.numbers(t,r))})),t.command(`connect`).argument(`<connection-id>`).description(`Bind an owned number or identity through Hub; no provider rental is purchased`).option(`--transport <transport>`,`imessage, whatsapp, sms, email, voice, or telegram`,`imessage`).option(`--number-id <id>`,`Exact owned provider number ID; required for voice, SMS, WhatsApp and Linq iMessage`).option(`--address <email>`,`Owned mailbox on a verified email domain`).requiredOption(`--reference <reference>`,`Stable client reference; keep it unchanged on retry`).option(`--label <label>`,`Line display name`).option(`--yes`,`Authorize provider webhook configuration and line binding`).action((t,n)=>Z(async()=>{no(n);let r=ro(n.transport);if(r!==`email`&&n.address)throw Error(`--address is email-only`);if((r===`email`||r===`telegram`)&&n.numberId)throw Error(`${r} does not take --number-id`);let i={connectionId:t,label:n.label,clientReference:n.reference},a;if(r===`email`)a={...i,transport:r,address:n.address};else if(r===`telegram`)a={...i,transport:r};else if(r===`imessage`)a={...i,transport:r,phoneNumberId:n.numberId};else{if(!n.numberId)throw Error(`${r} requires --number-id`);a={...i,transport:r,phoneNumberId:n.numberId}}e(await X(n).lines.fromConnection(a))})),t.command(`attach`).argument(`<line-id>`).description(`Attach a saved agent to any sandbox, or use an isolated on-demand member instance`).option(`--file <path>`,`Reviewed native attachment JSON (exclusive with quick-setup flags)`).option(`--profile-id <id>`,`Owner-scoped saved profile; each turn pins its source revision`).option(`--member <address>`,`The one allowed sender: E.164 phone or email`).option(`--sandbox <id>`,`Use an existing sandbox instead of an on-demand instance`).option(`--instance-prefix <prefix>`,`Stable instance namespace; defaults to profile:<profile-id>:`).option(`--tools <mode>`,`chat denies tools; act applies the profile's tools and permissions`).option(`--turns-per-day <count>`,`Per-member daily turn ceiling (default 30)`).option(`--yes`,`Authorize agent execution and spend against your key limits`).action((t,n)=>Z(async()=>{no(n);let r=X(n),i;if(n.file){if(n.profileId||n.member||n.sandbox||n.instancePrefix||n.tools||n.turnsPerDay)throw Error(`Choose --file or quick-setup flags, not both`);i=await io(n.file)}else{if(!n.profileId||!n.member)throw Error(`Provide --profile-id and --member, or --file`);if(n.sandbox&&n.instancePrefix)throw Error(`Choose --sandbox or --instance-prefix`);let e=n.tools??`chat`,t=Number(n.turnsPerDay??`30`);if(e!==`chat`&&e!==`act`)throw Error(`--tools must be chat or act`);if(!Number.isSafeInteger(t)||t<1||t>1e4)throw Error(`--turns-per-day must be 1–10000`);if(e===`act`&&n.sandbox)throw Error(`Acting tools require an isolated on-demand instance; omit --sandbox`);i={mode:`personal`,members:[{address:n.member,role:`owner`}],unknownSenders:`reject`,roles:{owner:{context:`own`,tools:e}},respond:{kind:`agent`,profileId:n.profileId,...e===`act`?{rolePolicy:{version:1,roles:{owner:{kind:`general`}},members:{}}}:{}},limits:{turnsPerMemberPerDay:t},...n.sandbox?{sandboxId:n.sandbox}:{instance:{keyPrefix:n.instancePrefix??`profile:${n.profileId}:`,create:{ownerContext:`isolated`,...e===`act`?{egressPolicy:{mode:`strict`,allowDomains:[new URL(_()).hostname],includeImplicitDomains:!1}}:{}}}}}}if(typeof i.sandboxId==`string`==(i.instance!==void 0))throw Error(`Attachment requires exactly one of sandboxId and instance`);let{sandboxId:a,instance:o,...s}=i,c;if(a){let e=await r.get(a);if(!e)throw Error(`Sandbox not found`);c=await e.lines.attach({...s,number:t})}else{if(!o)throw Error(`Attachment requires an instance`);c=await r.lines.attach({...s,number:t,instance:o})}e(c)}));for(let n of[`detach`,`release`])t.command(n).argument(`<line-id>`).description(n===`detach`?`Stop dispatch; preserve history and provider rental`:`Retire a detached Hub line; does not cancel provider rental`).option(`--yes`,`Authorize this change`).action((t,r)=>Z(async()=>{no(r),e({[n]:await X(r).lines[n](t)})}));t.command(`threads`).argument(`<line-id>`).description(`List this line's separate participant threads`).action((t,n)=>Z(async()=>{e(await X(n).lines.threads(t).list())})),t.command(`messages`).argument(`<line-id>`).argument(`<thread-id>`).description(`Read one authorized participant thread`).action((t,n,r)=>Z(async()=>{e(await X(r).lines.threads(t).messages(n))}))}async function oo(e){let{token:t,baseUrl:n}=b();if(t===void 0)return fe(e);if(!t.startsWith(`lrc_`)||!n)throw Error(`The line box needs TANGLE_LINE_TOKEN and TANGLE_HUB_URL`);if(e.apiKey||e.baseUrl&&new URL(e.baseUrl).origin!==new URL(n).origin)throw Error(`A line token cannot be sent to another Hub or combined with an API key`);return new $e({baseUrl:n,authHeaders:()=>({Authorization:`Bearer ${t}`})})}async function so(e,t){if(t)return t;if(!b().token)throw Error(`Provide --line <line-id>`);return(await e.lines.context()).line.id}function co(e){return e().catch(f)}function lo(){return new z(`context`).description(`Show live line identity, members, consent, reminders and quotas`).action(t=>co(async()=>{e(await(await oo(t)).lines.context())}))}function uo(){let t=new z(`lines`).description(`Connect, manage, message and schedule on a Hub line`);return t.command(`members`).description(`List names, roles and consent on this line`).option(`--line <line-id>`,`Line ID; inferred in a line box`).action(t=>co(async()=>{let n=await oo(t);e(await n.lines.members.list(await so(n,t.line)))})),t.command(`send`).description(`Send to a consenting member through Hub`).argument(`<to-member>`,`Exact member ID for an owner; name, ID, or self in a line box`).argument(`<text>`,`Message text`).option(`--line <line-id>`,`Line ID; inferred in a line box`).option(`--on-behalf-of <member>`,`Verified sender for a member relay`).option(`--not-before <iso-time>`,`Delay delivery until this ISO time`).option(`--idempotency-key <key>`,`Stable key for a retry`).action((t,n,r)=>co(async()=>{let i=await oo(r),a=await so(i,r.line);if(!b().token){if(r.onBehalfOf)throw Error(`--on-behalf-of is only available inside a line box`);if(!r.idempotencyKey)throw Error(`Owner sends require --idempotency-key so a retry keeps the same message`);if(!(await i.lines.members.list(a)).some(e=>e.id===t))throw Error(`Owner sends require an exact member ID from tangle lines members`);e(await i.lines.send(a,{memberId:t,text:n,idempotencyKey:r.idempotencyKey,...r.notBefore?{notBefore:r.notBefore}:{}}));return}e(await i.lines.send(a,{toMember:t,text:n,...r.onBehalfOf?{onBehalfOf:r.onBehalfOf}:{},...r.notBefore?{notBefore:r.notBefore}:{},...r.idempotencyKey?{idempotencyKey:r.idempotencyKey}:{}}))})),t.command(`remind`).description(`Wake the agent at a future time to write your reminder`).argument(`<text>`,`What to remember`).requiredOption(`--at <iso-time>`,`Future ISO time`).option(`--line <line-id>`,`Line ID; inferred in a line box`).option(`--idempotency-key <key>`,`Stable key for a retry`).action((t,n)=>co(async()=>{if(!n.at)throw Error(`--at is required`);let r=await oo(n),i=n.idempotencyKey??Ve(`sha256`).update(JSON.stringify([t,n.at])).digest(`hex`).slice(0,32);e(await r.lines.remind(await so(r,n.line),{text:t,notBefore:n.at,idempotencyKey:i}))})),ao(t),t}function fo(){let e=new z(`mcp`).description(`Model Context Protocol bridge commands.`);return e.command(`serve <id-or-name>`).description(`Run a local MCP server (stdio) backed by the given sandbox (ID or name). Pipe its stdio from an MCP client config to expose sandbox tools.`).option(`-s, --session <id>`,`Session id for kernel scoping`,`mcp-local`).option(`--name <name>`,`MCP server name reported to clients`,`tangle-sandbox`).action(async(e,t)=>{let n=x({apiKey:t.apiKey,baseUrl:t.baseUrl}),r=await G(E(n),n,e),i;try{i=(await import(`@modelcontextprotocol/sdk/server/stdio.js`)).StdioServerTransport}catch{throw Error("`@modelcontextprotocol/sdk` is not installed in this environment. Install it with: pnpm add -g @modelcontextprotocol/sdk (or as a dev dep in the project running this command).")}let{connect:a,close:o}=await(await import(`@tangle-network/sandbox/agent`)).createMcpServer(r,{sessionId:t.session,name:t.name});await a(new i),process.stdin.resume(),process.stdin.on(`end`,()=>{o().finally(()=>process.exit(0))});for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>{o().finally(()=>process.exit(0))})}),e}async function po(e,t){if(t.self&&e)throw Error(`Use --self or an explicit sandbox, not both`);if(!t.self&&!e)throw Error(`Specify a sandbox id/name or --self`);let n=m(),r=t.baseUrl||n.tangleBaseUrl||n.sandboxBaseUrl,i=n.hubUrl;if(t.self&&!r&&i&&new URL(i).origin!==`https://id.tangle.tools`)throw Error(`This deployment must set SANDBOX_BASE_URL or pass --base-url for self preview access`);let a=t.self?t.apiKey??ee():t.apiKey;if(t.self&&!a)throw Error(`Self preview access requires the injected sandbox runtime credential; it never reads saved owner credentials`);let o=x({apiKey:a,baseUrl:r}),s=E(o);return t.self?dt(s):G(s,o,e)}async function mo(e,t,n){let r=d(e);t||r.start();try{return await n()}finally{r.stop()}}function ho(e){return e}const go=`
134
+ `)?`${e}\n`:`${e}\n\n`}function Rr(){let e=process.env.SHELL??``;return e.includes(`zsh`)?R(H(),`.zshrc`):e.includes(`bash`)?R(H(),`.bashrc`):R(H(),`.zshrc`)}function zr(e){if(e===`shell`||e===`env`||e===`dockerfile`)return e;throw Error(`--format must be one of: shell, env, dockerfile (got '${e}')`)}function Br(e){if(e===`full`||e===`prompts`||e===`metadata`)return e;throw Error(`--content must be one of: full, prompts, metadata (got '${e}')`)}async function Vr(e){let t=Pr({endpoint:e.endpoint,apiKey:e.apiKey,projectKey:e.projectKey,content:e.content,format:e.format});if(console.log(t),e.format!==`shell`){console.log(),c(e.format===`env`?"Cron/container path: feed these to your service env (.env, `docker run --env-file`, k8s envFrom). No shell-rc edit, no TTY needed.":`Dockerfile path: paste these ENV lines into your image. No shell-rc edit, no TTY needed.`);return}if(console.log(),c(`Privacy tiers: --content full ships the whole conversation; --content prompts keeps task, prompts, and tool args only; --content metadata turns content off (telemetry still flows). Secrets are scrubbed server-side regardless.`),!e.write)return;let r=e.rcPath??Rr(),i=process.stdin.isTTY?await M(`Append this idempotent block to ${r}? (y/N)`,`n`):`n`;if(i.toLowerCase()!==`y`&&i.toLowerCase()!==`yes`){console.log(),c(`Not writing. To append later: tangle connect claude-code --rc ${r}`);return}let a=Fr({endpoint:e.endpoint,apiKey:e.apiKey,projectKey:e.projectKey,content:e.content,format:e.format}),{contents:o,changed:s}=Ir(Dr(r),a);if(!s){console.log(),n(`Already present in ${r} — nothing to change.`);return}Or(r,o),console.log(),n(`Wrote Tangle Intelligence env block to ${r}.`),c(`Reload your shell (e.g. 'source ${r}') before running the agent.`)}function Hr(e){let t=[],n={header:null,body:[]};for(let r of e.split(`
135
+ `))Ur(r)?(t.push(n),n={header:r.trim(),body:[]}):n.body.push(r);return t.push(n),t.length>1&&t[0].header===null&&t[0].body.every(e=>e.trim()===``)&&t.shift(),t}function Ur(e){let t=e.trim();return t.startsWith(`[`)&&t.endsWith(`]`)&&!t.includes(`=`)||t.startsWith(`[[`)&&t.endsWith(`]]`)}function Wr(e){let t=[];for(let n of e)n.header!==null&&t.push(n.header),t.push(...n.body);return t.join(`
136
+ `)}function Gr(e){return[{key:`environment`,line:`environment = "prod"`},{key:`log_user_prompt`,line:`log_user_prompt = true`},{key:`exporter`,line:`exporter = { otlp-http = { endpoint = "${q(e.endpoint)}/v1/logs", protocol = "json", headers = { "Authorization" = "Bearer ${e.apiKey??"${TANGLE_API_KEY}"}" } } }`}]}function Kr(e){let t=e.trim();if(t===``||t.startsWith(`#`))return null;let n=t.indexOf(`=`);if(n===-1)return null;let r=t.slice(0,n).trim();return/^[A-Za-z0-9_-]+$/.test(r)?r:null}function qr(e,t){let n=Gr(t),r=new Set(n.map(e=>e.key));if(e.trim()===``)return{contents:`${[`[otel]`,...n.map(e=>e.line)].join(`
137
+ `)}\n`,changed:!0};let i=Hr(e),a=i.find(e=>e.header===`[otel]`);if(!a){let t={header:`[otel]`,body:n.map(e=>e.line)},r=i[i.length-1];r&&!Jr(r)&&r.body.push(``),i.push(t);let a=Yr(Wr(i));return{contents:a,changed:a!==Yr(e)}}let o=a.body.filter(e=>{let t=Kr(e);return t===null||!r.has(t)}),s=[];for(;o.length>0&&o[o.length-1].trim()===``;)s.unshift(o.pop());a.body=[...o,...n.map(e=>e.line),...s];let c=Yr(Wr(i));return{contents:c,changed:c!==Yr(e)}}function Jr(e){return e.body.length>0&&e.body[e.body.length-1].trim()===``}function Yr(e){return e.endsWith(`
138
+ `)?e:`${e}\n`}function Xr(e){let t=R(H(),`.codex`,`config.toml`),{contents:r,changed:i}=qr(Dr(t),{endpoint:e.endpoint,apiKey:e.apiKey});if(!e.write){console.log(r.trimEnd());return}if(!i){n(`${t} already has the Tangle [otel] block — nothing to change.`);return}Or(t,r),n(`Merged the Tangle [otel] block into ${t}.`),c("Codex emits content on the logs signal (codex.* events). Set TANGLE_API_KEY in your env before running if you kept the ${TANGLE_API_KEY} reference."),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=${e.projectKey??`<your project>`} before running codex.`)}function Zr(e){switch(e){case`claude-code`:return`Claude Code: set OTEL_LOGS_EXPORTER=otlp and the four OTEL_LOG_* gates (OTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS, OTEL_LOG_TOOL_CONTENT, OTEL_LOG_RAW_API_BODIES).`;case`codex`:return`Codex: set log_user_prompt = true in [otel] (default false redacts content).`;case`opencode`:return`OpenCode: a standalone install emits nothing without the tangle-opencode-exporter shim; inside a Tangle sandbox it is already instrumented.`;case`openclaw`:case`hermes`:case`nanoclaw`:return`${Tr[e]}: no native OTLP exporter and no standalone server to subscribe to — run it inside a Tangle sandbox, where the sidecar adapter exports its content with gen_ai.system=${e}. A bare standalone install emits metadata only.`}}async function Qr(e){let t=Date.now()+e.timeoutSeconds*1e3,n=3e3,r=Math.min(e.timeoutSeconds*1e3,1e4),i=d(`Checking whether content is flowing…`);i.start();let a;try{for(;;){try{a=await Hn({endpoint:e.endpoint,apiKey:e.apiKey,timeoutMs:r})}catch(e){if(Date.now()>=t)throw e;await We(n);continue}if(a.contentSeen||Date.now()>=t)break;await We(n)}}finally{i.stop()}if(!a)throw Error(`onboarding status check returned no result`);$r(a,e.agent),a.contentSeen||(process.exitCode=1)}function $r(e,t){if(e.contentSeen){n(`Content flowing — Tangle Intelligence can analyze this feed.`),o({"Last seen":e.lastSeenAt??`just now`,Window:`${e.windowDays}d`});return}if(e.tracesSeen){s(`Metadata-only — traces are arriving but carry no content. You missed a content gate.`);let n=t?[t]:Object.keys(e.byAgent).filter(Er),r=n.length>0?n:wr;for(let n of r){let r=e.byAgent[n];(t||!r||r.tracesSeen&&!r.contentSeen)&&c(Zr(n))}return}s(`No traces yet for your tenant. Run your agent once on a real task, then re-run --verify.`),t&&c(Zr(t))}function ei(e,t){let n=e??process.env.TANGLE_INTELLIGENCE_API_KEY??S(`intelligence`,t);if(!n)throw Error(`No Tangle API key found. Pass --api-key, set TANGLE_API_KEY, or run: tangle auth login`);return n}function ti(e){let t=q(e);if(/^https?:\/\/[A-Za-z0-9.-]+(:\d+)?(\/[A-Za-z0-9._~%/-]*)?$/.test(t))return t;throw new p(`USAGE_INVALID`,`--endpoint ${JSON.stringify(e)} is not a plain http(s) URL`,`letters, digits and . _ ~ % / - only, after the scheme`,`tangle connect --help`)}function ni(){return new z(`connect`).description(`Connect a local coding agent's telemetry to Tangle Intelligence, content on (for SDK integration snippets, see 'tangle agent connect')`).argument(`[agent]`,`claude-code | codex | opencode | openclaw | hermes | nanoclaw`).option(`--endpoint <url>`,`OTLP endpoint base`,Dn).option(`-p, --project <key>`,`Project label (tangle.subject.key) to group runs; omit to set it yourself`).option(`--rc <path>`,`Shell rc file to append the Claude Code env block to`).option(`--no-write`,`Print the config instead of writing files (Claude Code / Codex)`).option(`--inline-key`,"Embed the resolved API key literally in the config (default: keep ${TANGLE_API_KEY})").option(`--verify`,`Poll onboarding status and report whether CONTENT is flowing`).option(`--timeout <seconds>`,`Verify poll timeout in seconds`,`120`).option(`--run`,`OpenCode only: run the content exporter against a live OpenCode server until interrupted`).option(`--opencode-url <url>`,`OpenCode server base URL for --run (or set OPENCODE_BASE_URL)`).option(`--format <kind>`,`Claude Code output: shell (export block) | env (.env / docker --env-file) | dockerfile (ENV lines). env/dockerfile are the cron/container path — printed to stdout, no shell-rc edit, no TTY`,`shell`).option(`--content <tier>`,`Claude Code content tier: full (everything) | prompts (task+prompts+tool-args) | metadata (telemetry on, content off)`,`full`).action(async(e,t)=>{let n=ti(t.endpoint);if(t.run){if((e?ii(e):`opencode`)!==`opencode`)throw Error(`--run is OpenCode-only: it runs the content exporter against a live OpenCode server. Other agents export natively once configured.`);await ci({endpoint:n,apiKey:ei(t.apiKey,n),opencodeUrl:t.opencodeUrl});return}if(t.verify){await Qr({endpoint:n,apiKey:ei(t.apiKey,n),agent:e?ii(e):void 0,timeoutSeconds:k(t.timeout,`--timeout`)});return}let r=e?ii(e):await ai(),i=t.inlineKey?ei(t.apiKey,n):void 0;r===`claude-code`?await Vr({endpoint:n,apiKey:i,projectKey:t.project,rcPath:t.rc,write:t.write!==!1,content:Br(t.content),format:zr(t.format)}):r===`codex`?Xr({endpoint:n,apiKey:i,projectKey:t.project,write:t.write!==!1}):r===`opencode`?oi({endpoint:n}):si(r,{endpoint:n}),console.log(),c(`Run your agent on a real task, then verify content is flowing: tangle connect ${r} --verify`)})}function ri(){return new z(`opencode-exporter`).description(`Export a running OpenCode's content to Tangle Intelligence (standalone shim)`).option(`--endpoint <url>`,`OTLP endpoint base`,Dn).option(`--opencode-url <url>`,`OpenCode server base URL (or set OPENCODE_BASE_URL)`).action(async e=>{let t=ti(e.endpoint);await ci({endpoint:t,apiKey:ei(e.apiKey,t),opencodeUrl:e.opencodeUrl})})}function ii(e){if(Er(e))return e;throw Error(`Unknown agent '${e}'. Choose one of: ${wr.join(`, `)}`)}async function ai(){if(!process.stdin.isTTY)throw Error(`Specify an agent: tangle connect <${wr.join(`|`)}>`);console.log(`Which coding agent are you connecting?`),wr.forEach((e,t)=>{console.log(` ${t+1}) ${Tr[e]} (${e})`)});let e=await M(`Enter a number or name`,`1`);return wr[Number.parseInt(e,10)-1]||ii(e.trim())}function oi(e){let t=q(e.endpoint);s(`OpenCode has no native OTel exporter, so a standalone install emits nothing without a shim.`),console.log(),o({"Inside a Tangle sandbox":`already instrumented — our adapter exports OpenCode's event-stream content. Nothing to do.`,Standalone:`run 'tangle connect opencode --run' alongside a running OpenCode, exporting to ${t}.`}),console.log(),c(`Start OpenCode in server mode ('opencode serve'), then in another terminal run: tangle connect opencode --run`),c(`The exporter subscribes to OpenCode's SSE event bus and exports content-bearing OTLP (prompt/completion/tool content) to Tangle. Verify with: tangle connect opencode --verify`),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting the exporter.`)}function si(e,t){let n=q(t.endpoint),r=Tr[e];s(`${r} has no native OTel exporter, so a standalone install emits nothing without instrumentation.`),console.log(),o({"Inside a Tangle sandbox":`already instrumented — the sidecar adapter exports ${r}'s prompt/completion/tool content (gen_ai.system=${e}) to ${n}. Nothing to do.`,Standalone:`${r} exposes no OTLP and no event-bus server; run it inside a Tangle sandbox to capture content.`}),console.log(),c(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting ${r}.`),c(`Verify content is flowing: tangle connect ${e} --verify`)}async function ci(e){let t=yr(e.opencodeUrl),r=new AbortController,i=()=>r.abort();process.on(`SIGINT`,i),process.on(`SIGTERM`,i),c(`Subscribing to OpenCode at ${t} — exporting content to Tangle.`),c(`Run OpenCode tasks now. Press Ctrl-C to stop.`),console.log();let a=0,o;try{o=await Cr({endpoint:e.endpoint,apiKey:e.apiKey,opencodeBaseUrl:t,signal:r.signal,onExport:({eventType:e,records:t})=>{a+=t,c(`exported ${t} record(s) from ${e} (total ${a})`)}})}catch(e){if(e instanceof xr){let{recordsExported:t,contentEventsExported:n}=e.partial;console.log(),s(`Exporter failed after exporting ${t} content record(s) from ${n} event(s): ${e.message}`)}throw e}finally{process.off(`SIGINT`,i),process.off(`SIGTERM`,i)}if(console.log(),o.contentEventsExported===0){s(`Saw ${o.eventsSeen} event(s) but none carried content. Run a real OpenCode task (a prompt that produces text or a tool call), then re-run.`);return}n(`Exported ${o.recordsExported} content record(s) from ${o.contentEventsExported} event(s).`),c(`Verify it landed: tangle connect opencode --verify`)}function li(){let t=new z(`environments`).alias(`env`).description(`Manage sandbox environments`);return t.command(`list`).alias(`ls`).description(`List available environments`).action(async t=>{let{client:n}=D(t),i=d(`Fetching environments...`);t.json||i.start();let a=await n.environments.list();i.stop(),t.json?e(a):a.length===0?console.log(`No environments found`):r([`ID`,`Description`,`Version`,`Runtimes`],a.map(e=>[e.id,e.description??``,e.version,e.runtimes.join(`, `)]))}),t.command(`get`).description(`Get environment details`).argument(`<id>`,`Environment ID`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Fetching environment...`);n.json||i.start();let a=await r.environments.get(t);if(i.stop(),!a){console.error(`Environment not found: ${t}`),process.exit(1);return}n.json?e(a):(console.log(`ID: ${a.id}`),console.log(`Description: ${a.description??`-`}`),console.log(`Version: ${a.version}`),console.log(`Runtimes: ${a.runtimes.join(`, `)}`),a.base&&console.log(`Base: ${a.base}`))}),t}const ui=B.string().trim().toLowerCase().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/),di=B.enum([`no_stock`,`sku_unknown`,`unsupported`,`still_present`,`preempted`,`quota`,`not_found`,`auth_rejected`,`invalid_request`,`provider_not_configured`,`rate_limited`,`conflict`,`indeterminate`,`provider_error`,`transport`]);B.object({provider:ui.nullable(),step:B.enum([`initialize`,`check-birth-pause`,`check-limits`,`check-providers`,`quote`,`select-offer`,`check-inventory`,`insert`,`create`,`recover`,`wait-ready`,`cleanup`]),providerErrorCode:B.union([di,B.literal(`gpu_provider_error`)])});const fi=B.string().trim().toLowerCase().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/),pi=B.object({kind:fi,count:B.number().int().positive().default(1),vramGb:B.number().positive().optional()}).strict();B.object({command:B.string().min(1).max(8192),timeoutMs:B.number().int().positive().max(2147453647).optional(),env:B.record(B.string(),B.string()).optional(),cwd:B.string().min(1).max(2048).optional()}).strict(),B.object({refresh:B.enum([`true`,`false`]).optional(),acceleratorKind:fi.optional(),acceleratorCount:B.coerce.number().pipe(pi.shape.count.unwrap()).optional(),acceleratorVramGb:B.coerce.number().positive().optional()}).strict(),B.object({maxSpendUsd:B.number().positive().max(1e4).optional(),maxLifetimeSeconds:B.number().int().positive().max(1440*60).optional()}).strict().refine(e=>e.maxSpendUsd!==void 0||e.maxLifetimeSeconds!==void 0,`Renewal requires a lifetime or spend cap`);const mi=B.object({provider:ui.optional(),image:B.string().min(1).max(512).optional(),env:B.record(B.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),B.string()).optional(),diskGb:B.number().int().positive().optional(),volumeGb:B.number().int().nonnegative().optional(),volumeMountPath:B.string().startsWith(`/`).max(2048).optional(),region:B.string().min(1).max(128).optional(),manifest:B.record(B.string(),B.unknown()).optional(),command:B.array(B.string().max(8192)).min(1).max(256).optional(),ports:B.array(B.number().int().min(1).max(65535)).max(32).optional(),endpoint:B.object({port:B.number().int().min(1).max(65535),healthPath:B.string().regex(/^\/(?![/\\])/).refine(e=>![`\r`,`
139
+ `,` `].some(t=>e.includes(t))).max(2048).optional()}).strict().optional(),allowSpot:B.boolean().optional(),maxHourlyUsd:B.number().positive().optional(),weights:B.object({manifestSha:B.string().regex(/^[a-f0-9]{64}$/),sizeBytes:B.number().int().positive().safe()}).strict().optional(),arms:B.array(B.unknown()).min(1).max(256).optional(),maxSpendUsd:B.number().positive().max(1e4),maxLifetimeSeconds:B.number().int().positive().max(1440*60),idleTimeoutSeconds:B.number().int().positive().optional()}).strict();mi.extend({accelerator:pi});const hi=pi,gi=ui;B.object({...mi.omit({env:!0}).shape,id:B.string(),projectRef:B.string(),ownerUserId:B.string(),productId:B.string().optional(),provider:gi,providerLeaseId:B.string().optional(),providerInstanceType:B.string().optional(),endpointUrl:B.string().optional(),status:B.enum([`provisioning`,`ready`,`detaching`,`destroyed`,`failed`]),accelerator:hi,providerCostPerHourUsd:B.number().optional(),customerPricePerHourUsd:B.number().optional(),estimatedProviderCostUsd:B.number().optional(),estimatedCustomerCostUsd:B.number().optional(),providerSelection:B.object({strategy:B.enum([`explicit`,`cheapest`,`ranked`]),selectedProvider:gi,requestedProvider:gi.optional(),candidates:B.array(B.object({provider:gi,accelerator:hi,providerInstanceType:B.string().optional(),region:B.string().optional(),pricingSource:B.enum([`live`,`configured`]).optional(),providerCostPerHourUsd:B.number(),customerPricePerHourUsd:B.number(),maxLifetimeSeconds:B.number(),estimatedProviderCostUsd:B.number(),estimatedCustomerCostUsd:B.number()})),rejected:B.array(B.object({provider:gi,error:B.string()}))}).optional(),createdAt:B.string(),updatedAt:B.string(),readyAt:B.string().optional(),startedAt:B.string().optional(),lastUsedAt:B.string().optional(),destroyedAt:B.string().optional(),failure:B.string().optional(),billing:B.object({seconds:B.number(),providerCostUsd:B.number(),customerCostUsd:B.number(),providerCostPerHourUsd:B.number(),customerPricePerHourUsd:B.number(),startedAt:B.string(),stoppedAt:B.string()}).optional()});function _i(e){return{kind:wi(e.kind),count:e.count?k(e.count,`--accelerator-count`):1,...e.memory?{vramGb:Ei(e.memory,`--accelerator-memory`)}:{}}}function vi(e,t,n){if(!t&&Object.values(e).some(Boolean))throw Error(n);return t?bi(e,`--gpu-`):void 0}function yi(e){return{...bi(e,`--`),accelerator:_i({kind:e.acceleratorKind,count:e.acceleratorCount,memory:e.acceleratorMemory})}}function bi(e,t){let{provider:n,image:r,env:i,maxSpendUsd:a,maxLifetime:o,idleTimeout:s}=e;if(!a||!o)throw Error(`--accelerator-kind requires ${t}max-spend-usd and ${t}max-lifetime`);return{...n?{provider:Ti(n,`${t}provider`)}:{},...r?{image:r}:{},...i?{env:Ci(i,`${t}env`,`env`)}:{},maxSpendUsd:Ei(a,`${t}max-spend-usd`),maxLifetimeSeconds:O(o,`${t}max-lifetime`),...s?{idleTimeoutSeconds:O(s,`${t}idle-timeout`)}:{}}}function xi(e){return e.length===1?e[0]:e.map(V).join(` `)}function Si(e){return{timeoutMs:e.timeout?O(String(e.timeout),`--timeout`,`ms`):void 0,env:e.env?Ci(e.env,`--env`,`env`):void 0}}function Ci(e,t,n){let r={};for(let i of e){let[e,...a]=i.split(`=`);if(!e||a.length===0)throw Error(`${t} expects ${n} values in KEY=VALUE format`);r[e]=a.join(`=`)}return r}function wi(e){let t=fi.safeParse(e);if(t.success)return t.data;throw Error(`--accelerator-kind must contain only letters, numbers, dots, underscores, or hyphens`)}function Ti(e,t){let n=ui.safeParse(e);if(n.success)return n.data;throw Error(`${t} must start with a letter and contain only letters, numbers, or hyphens`)}function Ei(e,t){if(!/^(?:\d+|\d+\.\d+|\.\d+)$/.test(e))throw Error(`${t} must be a positive number`);let n=Number.parseFloat(e);if(!Number.isFinite(n)||n<=0)throw Error(`${t} must be a positive number`);return n}function Di(){return new z(`exec`).description(`Execute a command in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command...>`,`Command and arguments, or one shell script`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`,`60000`).allowUnknownOption(!0).action(async(t,n,r)=>{try{let{context:i,client:a}=D(r),o=xi(n),s=Ci(r.env??[],`--env`,`env`),c=O(r.timeout,`--timeout`,`ms`,0),l=d(`Executing: ${o}`);r.json||l.start();let u=await G(a,i,t,{toRun:!0});u=await K(u);let f=await u.exec(o,{cwd:r.cwd,env:Object.keys(s).length>0?s:void 0,timeoutMs:c});l.stop(),r.json?e(f):(f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr)),f.exitCode!==0&&(process.exitCode=f.exitCode)}catch(e){if(e instanceof we){let t=`Exec transport lost before command status was confirmed. Remote command status is unknown. Original error: ${e.message}. For long-running commands, use \`tangle process spawn\`, \`tangle process logs\`, and \`tangle process kill --tree\`.`;return f(Error(t,{cause:e}))}f(e)}})}function Oi(n){n.command(`capabilities`).description(`List fleet drivers and their supported features`).action(async n=>{let{client:r}=D(n),i=d(`Fetching capabilities...`);i.start();let a=await r.fleets.capabilities();i.stop(),n.json?e(a):t(a.drivers,[{key:`driverType`,header:`Driver`,width:16},{key:`sharedWorkspace`,header:`Shared WS`,width:12},{key:`accelerators`,header:`Accel`,width:8},{key:`queueTimings`,header:`Queue`,width:8}])}),n.command(`usage <fleet-id>`).description(`Show fleet usage and reliability insights`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Fetching usage...`);i.start();let a=await r.fleets.usage(t);if(i.stop(),n.json)e(a);else if(o({"Fleet ID":a.usage.fleetId,Status:a.usage.status,Machines:a.usage.machineCount,Running:a.usage.runningMachines,Failed:a.usage.failedMachines,"Runtime (ms)":a.usage.meteredUsage?.runtimeMs,"Reliability score":a.insights.reliabilityScore,"Failure rate":a.insights.failureRate}),a.insights.recommendedActions.length>0){console.log(`
140
+ Recommended actions:`);for(let e of a.insights.recommendedActions)console.log(` - ${e}`)}}),n.command(`cost <fleet-id>`).description(`Show the fleet's cost estimate`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Estimating cost...`);i.start();let a=await r.fleets.cost(t);i.stop(),n.json?e(a):o({Plan:a.plan,Currency:a.currency,"Hourly (USD)":a.hourlyUsd,"Max lifetime (s)":a.maxLifetimeSeconds,"Estimated max lifetime (USD)":a.estimatedMaxLifetimeUsd,Machines:a.requestedResources.machines,"Total CPU":a.requestedResources.totalCpu,"Total memory (MB)":a.requestedResources.totalMemoryMb})})}function ki(e){return[...e.entries()].map(([e,t])=>({machineId:e,sandboxId:t.id,status:t.status}))}function Ai(r){r.command(`list <fleet-id>`).description(`List the machines of one fleet (fleet id is required)`).option(`--status <status>`,`Filter machines by status`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Fetching fleet...`);a.start();let o=await i.fleets.list({fleetId:n,status:r.status});a.stop();let s=ki(o.machines);r.json?e({fleetId:o.fleetId,machines:s}):t(s,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}])}),r.command(`get <fleet-id>`).description(`Show one fleet's manifest (server record)`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Fetching manifest...`);a.start();let s=await i.fleets.manifest(n);a.stop(),r.json?e(s):(o({"Fleet ID":s.fleetId??s.id,Machines:s.machines.length,"Workspace mode":s.workspace?.mode,"Workspace status":s.workspace?.status,"Max lifetime (s)":s.policy?.maxLifetimeSeconds,"Max spend (USD)":s.policy?.maxSpendUsd,Created:s.createdAt,Updated:s.updatedAt}),t(s.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`role`,header:`Role`,width:14},{key:`status`,header:`Status`,width:14}]))}),r.command(`delete <fleet-id>`).description(`Delete a fleet's machine sandboxes and its record`).option(`--continue-on-error`,`Keep deleting remaining machines if one delete fails`).action(async(t,r)=>{let{client:i}=D(r),a=d(`Deleting fleet...`);a.start(),await i.fleets.delete(t,{continueOnError:r.continueOnError}),a.stop(),r.json?e({success:!0,fleetId:t}):n(`Fleet deleted: ${t}`)}),r.command(`reap`).description(`TTL cleanup of all expired fleets (fleet-wide)`).option(`--dry-run`,`Report what would be reaped without deleting`).action(async n=>{let{client:r}=D(n),i=d(`Reaping expired fleets...`);i.start();let a=await r.fleets.reapExpired({dryRun:n.dryRun});i.stop(),n.json?e(a):(o({"Dry run":a.dryRun,Expired:a.expired,Deleted:a.deleted}),t(a.fleets,[{key:`fleetId`,header:`Fleet`,width:24},{key:`expiredAt`,header:`Expired`,width:18},{key:`deleted`,header:`Deleted`,width:10}]))}),r.command(`reconcile`).description(`Drop fleet records whose underlying sandboxes vanished`).option(`--dry-run`,`Report orphans without removing them`).action(async n=>{let{client:r}=D(n),i=d(`Reconciling fleets...`);i.start();let a=await r.fleets.reconcile({dryRun:n.dryRun});i.stop(),n.json?e(a):(o({"Dry run":a.dryRun,Checked:a.checked,Orphaned:a.orphaned,Removed:a.removed}),t(a.machines,[{key:`fleetId`,header:`Fleet`,width:24},{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`removed`,header:`Removed`,width:10}]))})}async function ji(e,t){let n=await ue({apiKey:t.apiKey,sandboxBaseUrl:t.baseUrl}),r=await fetch(`${n.baseUrl}/v1/agent-profiles/${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${n.token}`,accept:`application/json`}});if(!r.ok){let t=await r.text().catch(()=>``);throw r.status===404?Error(`profile '${e}' not found in the platform catalog (it may be a built-in, a stored profile you own, or neither — run 'tangle profile list' to see what is available)`):Error(`platform returned ${r.status}: ${t.slice(0,200)}`)}let i=await r.json();if(!i.definition||typeof i.definition!=`object`)throw Error(`profile '${e}' resolved but has no definition — the catalog entry is malformed`);return i.definition}async function Mi(e){let t=typeof e.envVarName==`string`&&e.envVarName.length>0?e.envVarName:null,n=!!e.fromStdin;if(t&&n)throw Error(`Pass either ${e.flagPrefix}-env or ${e.flagPrefix}-stdin, not both`);if(t){let n=process.env[t];if(!n||n.length===0)throw Error(`${e.flagPrefix}-env points at ${t}, but that environment variable is empty or unset`);return n}if(n){let t=await pe();if(t.length===0)throw Error(`${e.flagPrefix}-stdin received empty input on stdin`);return t}}function Ni(e){if(e.secret===void 0)return;let t=e.backend===`claude-code`?`token`:e.backend===`codex`?`bundle`:void 0;if(!t)throw Error(`--cli-auth needs --backend claude-code or --backend codex`);if(e.apiKeyGiven)throw Error(`--cli-auth cannot be combined with --backend-api-key-env or --backend-api-key-stdin`);return{account:`cli`,secretEnv:e.secret,format:t}}function Pi(e){if(e!==void 0)return e.map(e=>{if(e.includes(`@`)||e.includes(`:`))throw Error(`--secret ${e}: bare secret names only (box delivery). For proxy custody use --proxy-secret with a canonical binding`);return e})}function Fi(e){return{maxLifetimeSeconds:O(e.lifetime,`--lifetime`),idleTimeoutSeconds:O(e.idleTimeout,`--idle-timeout`)}}function Ii(e,t){let n={};return e.cpu!==void 0&&(n.cpuCores=k(e.cpu,`--cpu`)),e.memory!==void 0&&(n.memoryMB=k(e.memory,`--memory`)),e.disk!==void 0&&(n.diskGB=k(e.disk,`--disk`)),t&&(n.accelerator=t),Object.keys(n).length>0?n:void 0}function Li(e){let t=e.split(`/`);return t.length>=2?{provider:t[0],model:t.slice(1).join(`/`)}:{model:e}}function Ri(e){let t={};for(let n of e){let[e,...r]=n.split(`=`);if(!e||r.length===0)throw Error(`--metadata expects values in KEY=VALUE or KEY=JSON format`);t[e]=zi(r.join(`=`))}return t}function zi(e){try{return JSON.parse(e)}catch{return e}}function Bi(e,t){if(!(!e.gitUrl&&!e.gitRef&&!e.gitDepth&&!e.gitSparse&&!t)){if(!e.gitUrl||typeof e.gitUrl!=`string`)throw Error(`--git-url is required when using git provisioning options`);return{url:e.gitUrl,ref:typeof e.gitRef==`string`?e.gitRef:void 0,depth:typeof e.gitDepth==`string`?k(e.gitDepth,`--git-depth`):void 0,sparse:Array.isArray(e.gitSparse)?e.gitSparse:void 0,auth:t?{token:t}:void 0}}}function Vi(e,t){if(!(!e.storageType&&!e.storageBucket&&!e.storageEndpoint&&!e.storageRegion&&!e.storagePrefix&&!e.storageAccessKeyId&&!t)){if(typeof e.storageType!=`string`||typeof e.storageBucket!=`string`||typeof e.storageAccessKeyId!=`string`||!t)throw Error(`Storage config requires --storage-type, --storage-bucket, --storage-access-key-id, and one of --storage-secret-access-key-env / --storage-secret-access-key-stdin`);return{type:Hi(e.storageType),bucket:e.storageBucket,endpoint:typeof e.storageEndpoint==`string`?e.storageEndpoint:void 0,region:typeof e.storageRegion==`string`?e.storageRegion:void 0,prefix:typeof e.storagePrefix==`string`?e.storagePrefix:void 0,credentials:{accessKeyId:e.storageAccessKeyId,secretAccessKey:t}}}}function Hi(e){if(e===`s3`||e===`gcs`||e===`r2`)return e;throw Error(`--storage-type must be one of s3, gcs, or r2`)}function Ui(e){if(e===void 0)return;let t=[];for(let n of e){let e=n,r=`--proxy-secret <json>`;if(n.startsWith(`@`)){let t=n.slice(1);r=`--proxy-secret @${t}`;try{e=F(t,`utf8`)}catch{throw Error(`${r}: file could not be read`)}}let i;try{i=JSON.parse(e)}catch(e){throw Error(`${r}: not valid JSON (${e instanceof Error?e.message:String(e)})`)}if(Array.isArray(i))t.push(...i);else if(typeof i==`object`&&i)t.push(i);else throw Error(`${r}: expected a binding object or an array of bindings`)}let n=Ge.parse(t);return n.length>0?n:void 0}function Wi(e){c(` Status: ${e.status}`),c(` Provider: ${e.provider}`),c(` GPU: ${e.accelerator.kind} x ${e.accelerator.count}`),e.customerPricePerHourUsd!==void 0&&c(` Customer price: $${e.customerPricePerHourUsd}/hr`),e.estimatedCustomerCostUsd!==void 0&&c(` Max estimate: $${e.estimatedCustomerCostUsd}`),e.billing&&(c(` Billed seconds: ${e.billing.seconds}`),c(` Customer cost: $${e.billing.customerCostUsd}`))}function Gi(e){e.result.stdout&&process.stdout.write(e.result.stdout),e.result.stderr&&process.stderr.write(e.result.stderr),c(`Exit code: ${e.result.exitCode}`)}function Ki(r){let i=r.command(`gpu`).description(`Manage on-demand GPU leases for a sandbox`);i.command(`providers <id-or-name>`).description(`List GPU clouds, whether each credential works, and current prices`).option(`--accelerator-kind <kind>`,`Price this GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Checking GPU providers...`);o.start();let s=await(await G(a,i,n)).gpu.providers(r.acceleratorKind?{accelerator:_i({kind:r.acceleratorKind,count:r.acceleratorCount,memory:r.acceleratorMemory})}:{});if(o.stop(),r.json){e(s);return}t(s.statuses.map(e=>({provider:e.provider,state:e.state,gpu:e.estimate?.providerInstanceType??``,usdHr:e.estimate?e.estimate.customerPricePerHourUsd.toFixed(4):``,pricing:e.estimate?.pricingSource??``,needs:e.envVars.join(` `)})),[{key:`provider`,header:`Provider`},{key:`state`,header:`State`},{key:`gpu`,header:`GPU`},{key:`usdHr`,header:`$/hr`},{key:`pricing`,header:`Price`},{key:`needs`,header:`Needs`}]);for(let e of s.statuses){let t=e.state===`credential-invalid`?e.credential?.detail:e.estimateError;t&&c(`${e.provider}: ${t}`)}s.usable.length===0&&c(`No GPU provider is usable on this deployment: set the variables in Needs for one provider on the server.`)}),i.command(`attach <id-or-name>`).description(`Attach a temporary GPU worker to a sandbox`).requiredOption(`--accelerator-kind <kind>`,`GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--image <image>`,`GPU worker image override`).option(`--env <vars...>`,`Environment variables for the GPU worker (KEY=VALUE)`).requiredOption(`--max-spend-usd <usd>`,`Maximum customer spend for this lease`).requiredOption(`--max-lifetime <duration>`,`Maximum lease lifetime: seconds, or a duration like 30m or 2h`).option(`--idle-timeout <duration>`,`Idle time before destroy, e.g. 10m`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Attaching GPU lease...`);o.start();let s=await(await G(a,i,t)).gpu.attach(yi(r));o.stop(),r.json?e(s):(n(`GPU lease attached: ${s.id}`),Wi(s))}),i.command(`run <id-or-name> <command...>`).description(`Attach a GPU, run a command or script, then destroy it`).requiredOption(`--accelerator-kind <kind>`,`GPU kind, for example nvidia-h100`).option(`--accelerator-count <count>`,`GPU device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--image <image>`,`GPU worker image override`).option(`--env <vars...>`,`Environment variables for the GPU worker and command (KEY=VALUE)`).requiredOption(`--max-spend-usd <usd>`,`Maximum customer spend for this lease`).requiredOption(`--max-lifetime <duration>`,`Maximum lease lifetime: seconds, or a duration like 30m or 2h`).option(`--idle-timeout <duration>`,`Idle time before destroy, e.g. 10m`).option(`--timeout <ms>`,`Command timeout in milliseconds`).option(`--cwd <path>`,`Working directory`).action(async(t,r,i)=>{let a,o,s,c;try{let e=Si(i),{context:n,client:s}=D(i),c=await G(s,n,t),l=d(`Attaching GPU lease...`);l.start(),a=await c.gpu.attach(yi(i)),l.stop();let u=d(`Running GPU command...`);u.start(),o=await c.gpu.exec(a.id,{command:xi(r),...e,cwd:i.cwd}),u.stop(),i.json||Gi(o)}catch(e){s=e}finally{if(a)try{let{context:e,client:n}=D(i);a=await(await G(n,e,t)).gpu.detach(a.id)}catch(e){c=e}}if(s){f(s),c&&f(c);return}if(c){f(c);return}i.json?e({lease:a,result:o}):a&&n(`GPU lease detached: ${a.id}`);let l=o?.result.exitCode;l&&l!==0&&(process.exitCode=l)}),i.command(`list <id-or-name>`).description(`List GPU leases attached to a sandbox`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching GPU leases...`);o.start();let s=await(await G(a,i,n)).gpu.list();o.stop(),r.json?e(s):s.length===0?c(`No GPU leases attached.`):t(s.map(e=>({id:e.id,status:e.status,provider:e.provider,accelerator:`${e.accelerator.kind}x${e.accelerator.count}`,customerUsdHr:e.customerPricePerHourUsd??``})),[{key:`id`,header:`ID`,width:28},{key:`status`,header:`Status`,width:12},{key:`provider`,header:`Provider`,width:12},{key:`accelerator`,header:`GPU`,width:24},{key:`customerUsdHr`,header:`$/hr`,width:10}])}),i.command(`exec <id-or-name> <lease-id> <command...>`).description(`Run a command or script on an attached GPU lease`).option(`--timeout <ms>`,`Command timeout in milliseconds`).option(`--cwd <path>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=d(`Running GPU command...`);s.start();let c=await(await G(o,a,t)).gpu.exec(n,{command:xi(r),...Si(i),cwd:i.cwd});s.stop(),i.json?e(c):Gi(c)}),i.command(`detach <id-or-name> <lease-id>`).description(`Detach and destroy a GPU lease`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=d(`Detaching GPU lease...`);s.start();let c=await(await G(o,a,t)).gpu.detach(r);s.stop(),i.json?e(c):(n(`GPU lease detached: ${c.id}`),Wi(c))})}function qi(t,r){if(r){e(t);return}if(!t.id){t.kind===`snapshot`&&t.result?.snapshot?n(`Snapshot created: ${t.result.snapshot.snapshotId}`):n(`Sandbox ${t.sandboxId} stopped.`);return}n(`${t.kind===`snapshot`?`Snapshot`:`Stop`} of sandbox ${t.sandboxId} accepted.`),c(`Operation: ${t.id}`),c(`Status: ${t.statusUrl}`)}function Ji(e){return`${e.name} (${e.id})`}async function Yi(e,t){if(t.startsWith(`team_`))return e.teams.get(t);let n=(await e.teams.list()).filter(e=>e.name.toLowerCase()===t.toLowerCase());if(n.length===0)throw Error(`Team not found: ${t}`);if(n.length>1)throw Error(`Team name is ambiguous: ${t}. Use a team id instead.`);return n[0]}async function Y(e,t,n){if(t)return Yi(e,t);let r=te(n);if(!r.activeTeamId)throw Error("No active team. Run `tangle team switch <team>` or pass `--team <team>`.");return e.teams.get(r.activeTeamId)}function Xi(e,t){h({id:e.id,name:e.name},t)}function Zi(e){v(e)}async function Qi(e){if(e.explicitTeam&&e.personal)throw Error(`--team and --personal cannot be used together`);if(!e.personal)return e.explicitTeam?(await Yi(e.client,e.explicitTeam)).id:e.activeTeamId}async function $i(e){if([!!e.explicitTeam,!!e.personal,!!e.allScopes].filter(Boolean).length>1)throw Error(`--team, --personal, and --all-scopes are mutually exclusive`);if(e.allScopes)return`all`;if(e.personal)return`personal`;if(e.explicitTeam)return`team:${(await Yi(e.client,e.explicitTeam)).id}`;if(e.activeTeamId)return`team:${e.activeTeamId}`}function ea(e){if(!e)return e;let t={...e};for(let e of[`authToken`,`execToken`])t[e]!==void 0&&(t[e]=`[REDACTED]`);return t}function ta(r){r.command(`attestation <id-or-name>`).description(`Fetch TEE attestation evidence for a sandbox`).option(`--nonce <hex|auto>`,`Nonce to bind into a fresh attestation report; use auto to generate one`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=r.nonce===`auto`?Ae():r.nonce,s=d(`Fetching TEE attestation...`);s.start();let c=await(await G(a,i,t)).getTeeAttestation(o?{attestationNonce:o}:void 0);s.stop(),r.json?e(c):(n(`Attestation fetched for ${t}`),console.log(`TEE type: ${c.attestation.tee_type}`),console.log(`Evidence bytes: ${c.attestation.evidence.length}`),console.log(`Measurement bytes: ${c.attestation.measurement.length}`),console.log(`Timestamp: ${c.attestation.timestamp}`),c.attestationNonce&&console.log(`Nonce: ${c.attestationNonce}`))}),r.command(`list`).description(`List all sandboxes`).option(`-s, --status <status>`,`Filter by status (running, stopped, deleted, all)`).option(`-l, --limit <n>`,`Limit results`,`50`).option(`--team <team>`,`List sandboxes for a team by id or name`).option(`--personal`,`List personal sandboxes`).option(`--all-scopes`,`List personal and team sandboxes`).action(async n=>{let{context:r,client:i}=D(n),a=d(`Fetching sandboxes...`);a.start();let o=await $i({client:i,explicitTeam:n.team,personal:n.personal,allScopes:n.allScopes,activeTeamId:r.activeTeamId}),s=await i.list({status:n.status===`all`?void 0:n.status,limit:Number.parseInt(n.limit,10),scope:o});a.stop(),n.json?e(s):t(s.map(e=>({id:e.id,status:e.status,createdAt:e.createdAt,name:e.name??``})),[{key:`id`,header:`ID`,width:24},{key:`status`,header:`Status`,width:14},{key:`createdAt`,header:`Created`,width:16},{key:`name`,header:`Name`,width:20}])}),r.command(`get <id-or-name>`).description(`Get sandbox details`).option(`--profile`,`Show the active agent profile provenance (name, hash, skills)`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching sandbox...`);a.start();let o=await G(i,r,t);if(a.stop(),n.profile){let e=o.getProfileProvenance?.();e?(c(`Agent profile provenance:`),c(` Base profile: ${e.base.name??`(inline)`} (${e.base.sha256.slice(0,12)}...)`),c(` Effective: ${e.effective.name??`(inline)`} (${e.effective.sha256.slice(0,12)}...)`),c(` Materialized: ${e.materializedAt}`),e.base.sha256!==e.effective.sha256&&c(` ⚠ Profile changed since creation (base ≠ effective)`)):c(`No profile materialized (bare sandbox). Create with --profile <name> to install one.`);return}n.json?e(o):l({id:o.id,name:o.name,status:o.status,runtime:o.runtime,resources:o.resources,createdAt:o.createdAt?.toISOString(),expiresAt:o.expiresAt?.toISOString(),connection:o.connection})}),r.command(`shapes`).description(`List the named sandbox sizes, the default, and this account's ceiling`).action(async n=>{let{client:r}=D(n),i=await r.shapes();if(n.json){e(i);return}let o=e=>e.cpuCores<=i.ceiling.cpuCores&&e.memoryMB<=i.ceiling.memoryMB&&e.diskGB<=i.ceiling.diskGB;t(i.presets.map(e=>({name:e.name===i.default?`${e.name} (default)`:e.name,cpu:e.cpuCores,memory:`${e.memoryMB} MB`,disk:`${e.diskGB} GB`,available:o(e)?`yes`:e.name===i.default?`clamped to ceiling`:`above ceiling`})),[{key:`name`,header:`Shape`,width:18},{key:`cpu`,header:`vCPU`,width:6},{key:`memory`,header:`Memory`,width:10},{key:`disk`,header:`Disk`,width:8},{key:`available`,header:`Available`,width:14}]),c(`Ceiling for this account: ${a(i.ceiling)}`)}),r.command(`delete <id-or-name>`).description(`Delete a sandbox`).option(`-f, --force`,`Skip confirmation`).option(`--name`,`Treat the reference as a sandbox name`).addOption(new Be(`--until <state>`,`Wait for physical removal`).choices([`removed`])).option(`--retry-cleanup`,`Retry server-side cleanup after the sandbox disappeared from get/list`).action(async(e,t)=>{if(!t.force&&!await N(`Delete sandbox ${e}? [y/N] `,`--force`)){c(`Cancelled.`);return}let{context:r,client:i}=D(t),a=d(`Deleting sandbox...`);a.start();let o=await Bt(i,r,e,{retryCleanup:t.retryCleanup,name:t.name,until:t.until,beforeDelete:async e=>{let t=await e.listSnapshots().then(e=>e.length,()=>0);t!==0&&(a.clear(),console.error(`This sandbox has ${t} snapshot${t===1?``:`s`}. Deleting the sandbox keeps them until they retire.
141
+ List them and their retire date: tangle snapshot list ${e.id}\n Delete one before then: tangle snapshot delete ${e.id} <snapshot-id>`))}});a.stop(),n(o===`already_absent`?`Sandbox ${e} was already gone.`:`Sandbox ${e} deleted.`)}),r.command(`stop <id-or-name>`).description(`Stop a running sandbox`).option(`--name`,`Treat the reference as a sandbox name`).option(`--no-wait`,`Return once the stop is accepted and print the operation to poll`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Stopping sandbox...`);a.start();let o=await G(i,r,e,{nameOnly:t.name});if(t.wait===!1){let e=await o.stop({wait:!1});a.stop(),qi(e.info,!!t.json);return}await o.stop(),a.stop(),n(`Sandbox ${e} stopped.`)}),r.command(`resume <id-or-name>`).description(`Resume a stopped sandbox`).option(`--wait`,`Wait for sandbox to be running`,!0).option(`-t, --timeout <ms>`,`Resume timeout in milliseconds; a cold resume re-provisions the sandbox, so this defaults higher than other commands (default 120000)`,`120000`).action(async(e,t)=>{let r=O(t.timeout,`--timeout`,`ms`),i=x({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:r}),a=E(i),o=d(`Resuming sandbox...`);o.start();let s=await G(a,i,e);await s.resume({timeoutMs:r}),t.wait&&(o.text=`Waiting for sandbox to start...`,await s.waitFor(`running`,{timeoutMs:r})),o.stop(),n(`Sandbox ${s.id} resumed.`)})}const na=B.array(B.union([B.cidrv4(),B.cidrv6()])).min(1).max(100);B.strictObject({mode:B.enum([`open`,`strict`,`blocked`]),allowDomains:B.array(B.union([B.string().min(1).max(256),B.strictObject({domain:B.string().min(1).max(256),allowPrivateIps:na})])).max(100).optional(),includeImplicitDomains:B.boolean().optional()});function ra(e){return e===`sandbox`||e===`team`}const ia={mode:`strict`,includeImplicitDomains:!0};function aa(e,t){return e.mode!==`open`||ra(t)?e:ia}const oa=e=>typeof e==`string`?e:e.domain;function sa(e,t){if(!e)return{};if(t)throw Error(`--allow-domain is refused for a team sandbox: its own policy would replace the team's egress policy. Create it without the flag; a team owner or admin then runs tangle sandbox egress <id> --allow-domain <hosts>`);return{egressPolicy:{...ia,allowDomains:e}}}function ca(e){let t=e.toJSON().egressRefusedProxySecretHosts??[];if(t.length===0)return;let n=t.join(` `);s(`The egress policy refuses the proxy-secret host ${t.join(`, `)}: a binding does not open its host. Allow it with: tangle sandbox egress ${e.id} --allow-domain ${n} (or create with --allow-domain ${n})`)}async function la(e,t){for(let n=0;;n++){let r=await e.egress.get(),i=aa(r.policy,r.source);if(i.mode===`open`)return c(`Egress is open: every host is already reachable. Nothing changed.`),r;let a=i.mode===`strict`?i.allowDomains??[]:[],o=new Set(a.map(e=>oa(e).toLowerCase())),s=t.map(e=>e.toLowerCase()).filter(e=>!o.has(e));if(s.length===0)return r;let l={mode:`strict`,allowDomains:[...a,...new Set(s)],includeImplicitDomains:i.mode===`strict`&&i.includeImplicitDomains===!0};try{return await e.egress.update(l,{expectedUpdatedAt:r.updatedAt})}catch(e){if(n===0&&e.code===`CONFLICT`)continue;throw Ft(e,`tangle sandbox egress --help`)}}}function ua(t){t.command(`egress <id-or-name>`).description(`Show the egress policy a sandbox enforces, or add hosts to its strict allowlist`).option(`--allow-domain <domains...>`,`Add these hosts to the allowlist; the API judges them. An open policy is left open; a blocked one becomes strict with only these hosts`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=await G(i,r,t),{policy:o,source:s}=n.allowDomain?await la(a,n.allowDomain):await a.egress.get(),l=aa(o,s);if(n.json){e({policy:l,source:s});return}c(`Egress: ${l.mode} (source ${s})`),l.mode===`strict`&&(c(` Allowed: ${(l.allowDomains??[]).map(oa).join(`, `)||`none`}`),c(` Default registries, Git hosts and model endpoints: ${l.includeImplicitDomains?`included`:`not included`}`))}),t.command(`network <id-or-name>`).description("Show runtime network state (exposed ports) for a sandbox. Outbound policy: `tangle sandbox egress`.").action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Updating network configuration...`);a.start();let o=await G(i,r,t);a.stop();let s=await o.network.getConfig();n.json?e(s):(c(`Network Configuration:`),s.ports&&s.ports.length>0?c(` Exposed Ports: ${s.ports.join(`, `)}`):c(` No exposed ports`))}),t.command(`expose <id-or-name>`).description(`Expose a port and get a public URL`).option(`-p, --port <port>`,`Port to expose`,`8000`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=Number.parseInt(r.port,10);if(Number.isNaN(o)||o<1||o>65535)throw Error(`Port must be a number between 1 and 65535`);let s=d(`Exposing port ${o}...`);s.start();let l=await(await G(a,i,t)).network.exposePort(o);s.stop(),r.json?e({port:o,url:l}):(n(`Port ${o} exposed.`),c(` URL: ${l}`))}),t.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching exposed URLs...`);a.start();let o=await(await G(i,r,t)).network.listUrls();if(a.stop(),n.json)e(o);else{let e=Object.entries(o);if(e.length===0)c(`No ports exposed.`);else{c(`Exposed Ports:`);for(let[t,n]of e)c(` ${t}: ${n}`)}}})}function da(t){t.command(`create`).option(`--cpu-features <flags>`,`Required Linux CPU flags, comma-separated`).description(`Create a new sandbox`).option(`-n, --name <name>`,`Sandbox name`).option(`-e, --environment <environment>`,ma).addOption(ha()).option(`--bare`,`Create a bare sandbox without the agent runtime`).option(`--ssh`,`Enable SSH access`).option(`--ssh-key <key>`,`SSH public key for authentication`).option(`--ssh-keys <names...>`,`Stored SSH key names or IDs for authentication`).option(`--ssh-key-file <paths...>`,`SSH public key file paths for authentication`).option(`--web-terminal`,`Enable web terminal`).option(`--no-in-box-preview`,`Only your key may publish (public) preview links`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`--secret <names...>`,`Secrets selected by bare name for box delivery (value in the sandbox env). For proxy custody use --proxy-secret`).option(`--proxy-secret <bindings...>`,`Canonical proxy custody binding(s): one binding as inline JSON, or @file with a JSON array. The value stays at the egress proxy and is redeemed only within the binding's scope (hosts/methods/paths/TTL); the box reads a placeholder. Repeatable`).option(`--allow-domain <domains...>`,`Hostnames the sandbox may reach under strict egress, e.g. api.example.com or *.example.com; the platform's own required domains stay allowed. Personal sandboxes only: a team sandbox keeps the team's policy`).option(`--metadata <entries...>`,`Metadata entries (KEY=VALUE or KEY=JSON)`).option(`--cpu <cores>`,"CPU cores (omit for the platform default; see `sandbox shapes`)").option(`--memory <mb>`,`Memory in MB (omit for the platform default)`).option(`--disk <gb>`,`Disk size in GB (omit for the platform default)`).option(`--accelerator-kind <kind>`,`Accelerator kind, for example nvidia-h100 or amd-mi300x`).option(`--accelerator-count <count>`,`Accelerator device count`,`1`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--gpu-provider <provider>`,`GPU cloud provider; omitted picks the cheapest configured provider`).option(`--gpu-worker-image <image>`,`GPU worker image override`).option(`--gpu-env <vars...>`,`Environment variables for the GPU worker (KEY=VALUE)`).option(`--gpu-max-spend-usd <usd>`,`Maximum customer spend for the create-time GPU lease`).option(`--gpu-max-lifetime <duration>`,`Maximum create-time GPU lease lifetime: seconds, or a duration like 30m or 2h`).option(`--gpu-idle-timeout <duration>`,`Destroy the create-time GPU lease after this idle time: seconds, or a duration like 10m`).option(`--lifetime <duration>`,`Wall-clock lifetime before the sandbox is stopped (not deleted): seconds, or a duration like 90m or 2h; default 3600 = 1h`,`3600`).option(`--idle-timeout <duration>`,`Idle time before the sandbox is stopped (not deleted): seconds, or a duration like 60m; default 900 = 15m. It resumes on next use`,`900`).option(`--from-snapshot <id>`,`Create the sandbox from a snapshot`).option(`--public-template <id-or-slug>`,`Create the sandbox from a published public template`).option(`--public-template-version <id>`,`Pin creation to a specific published public-template version`).option(`--billing-owner <userId>`,`Platform user that pays for the sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).option(`--team <team>`,`Create in a team by id or name`).option(`--personal`,`Create a personal sandbox even when a team is active`).option(`--git-url <url>`,`Git repository URL to clone during provisioning`).option(`--git-ref <ref>`,`Git branch, tag, or commit to checkout`).option(`--git-depth <depth>`,`Git clone depth`).option(`--git-sparse <paths...>`,`Sparse checkout paths`).option(`--git-token-env <name>`,`Name of an environment variable containing the Git HTTPS auth token`).option(`--git-token-stdin`,`Read the Git HTTPS auth token from stdin`).option(`--storage-type <type>`,`BYOS3 storage type (s3, gcs, r2)`).option(`--storage-bucket <name>`,`BYOS3 bucket name`).option(`--storage-endpoint <url>`,`BYOS3 endpoint URL`).option(`--storage-region <region>`,`BYOS3 region`).option(`--storage-prefix <prefix>`,`BYOS3 path prefix`).option(`--storage-access-key-id <id>`,`BYOS3 access key ID`).option(`--storage-secret-access-key-env <name>`,`Name of an environment variable containing the BYOS3 secret access key`).option(`--storage-secret-access-key-stdin`,`Read the BYOS3 secret access key from stdin`).addOption(new Be(`--driver <type>`,`Run on Tangle network operators instead of the platform's hosts (--tee needs it)`).choices([`tangle`])).option(`--backend <type>`,`Backend agent type (${Se.join(`, `)}); amp needs your own Amp token via --backend-api-key-env or --backend-api-key-stdin`).option(`--backend-model <model>`,`Model override (format: provider/model)`).addOption(new Be(`--reasoning-effort <level>`,`Reasoning effort for the backend's model; overrides the profile's model.reasoningEffort`).choices(Ke)).option(`--backend-api-key-env <name>`,`Name of an environment variable containing the BYOK backend API key`).option(`--backend-api-key-stdin`,`Read the BYOK backend API key from stdin`).option(`--cli-auth <secret>`,"Run --backend claude-code or codex on your own subscription: the stored secret holding a `claude setup-token` token or a Codex auth.json (see `tangle secret create`)").option(`--profile <path>`,`Path to an AgentProfile JSON file to install as the sandbox's backend profile (carries skills, tools, MCP, model). Use with --backend; the profile's inline skills materialize into the harness's native skill directory on first turn`).option(`--profile-stdin`,`Read the AgentProfile JSON from stdin instead of a file (use with --profile)`).option(`--tee <type>`,`Require a TEE backend (any, tdx, nitro, sev-snp, phala-dstack)`).option(`--sealed`,`Request TEE sealed-secret support`).option(`--attestation-nonce <hex|auto>`,`Deploy-time attestation nonce; use auto to generate one`).option(`--attestation-refresh`,`Generate a fresh deploy-time attestation nonce when --tee is set`).option(`--require-attestation`,`Fail unless TEE attestation evidence is returned`).option(`--wait`,`Wait for sandbox to be running`,!0).option(`--timeout <ms>`,`HTTP timeout in milliseconds`,`30000`).action(async t=>{let n=await Mi({envVarName:t.gitTokenEnv,fromStdin:t.gitTokenStdin,flagPrefix:`--git-token`}),r=await Mi({envVarName:t.storageSecretAccessKeyEnv,fromStdin:t.storageSecretAccessKeyStdin,flagPrefix:`--storage-secret-access-key`}),i=await Mi({envVarName:t.backendApiKeyEnv,fromStdin:t.backendApiKeyStdin,flagPrefix:`--backend-api-key`}),a=Ni({secret:t.cliAuth,backend:t.backend,apiKeyGiven:i!==void 0}),o;if(t.profileStdin){let e=await pe(`--profile-stdin`,`the AgentProfile JSON`);try{o=JSON.parse(e)}catch{f(Error(`--profile-stdin: the input is not valid JSON`));return}}else if(t.profile){let e=String(t.profile);if(e.startsWith(`.`)||e.startsWith(`/`)||e.endsWith(`.json`))try{o=JSON.parse(F(e,`utf8`))}catch(t){f(_a(e,t));return}else try{o=await ji(e,t)}catch(t){f(_a(e,t));return}}o=va(o,t.reasoningEffort);let s=x({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:t.timeout?O(t.timeout,`--timeout`,`ms`):void 0}),c=E(s),l=d(`Creating sandbox...`);l.start();let u=await Qi({client:c,explicitTeam:t.team,personal:t.personal,activeTeamId:s.activeTeamId}),p=Ci(t.env??[],`--env`,`env`),m=t.metadata?Ri(t.metadata):void 0,h=Bi(t,n),g=Vi(t,r),_=t.acceleratorKind?_i({kind:String(t.acceleratorKind),count:String(t.acceleratorCount),memory:typeof t.acceleratorMemory==`string`?t.acceleratorMemory:void 0}):void 0,v=vi({provider:typeof t.gpuProvider==`string`?t.gpuProvider:void 0,image:typeof t.gpuWorkerImage==`string`?t.gpuWorkerImage:void 0,env:Array.isArray(t.gpuEnv)?t.gpuEnv:void 0,maxSpendUsd:typeof t.gpuMaxSpendUsd==`string`?t.gpuMaxSpendUsd:void 0,maxLifetime:typeof t.gpuMaxLifetime==`string`?t.gpuMaxLifetime:void 0,idleTimeout:typeof t.gpuIdleTimeout==`string`?t.gpuIdleTimeout:void 0},!!_,`Create-time GPU lease flags require --accelerator-kind`),y=t.driver?{type:`tangle`}:void 0,b=t.backend||t.backendModel||o?{...t.backend?{type:je(t.backend)}:{},...o?{profile:o}:{},model:t.backendModel||i||a?{...t.backendModel?Li(t.backendModel):{},apiKey:i,...a?{cliAuth:a}:{}}:void 0}:void 0,S=Pi(t.secret),ee=a?[...new Set([...S??[],a.secretEnv])]:S,C=Ui(t.proxySecret),te=Ii(t,_),w=t.sshKeyFile??(t.ssh&&!t.sshKey&&!t.sshKeys?.length?[ga()]:[]),T=[...t.sshKey?[t.sshKey]:[],...w.map(e=>F(e,`utf8`).trim())],D={name:t.name,environment:t.environment,runtime:t.runtime,cpuFeatures:t.cpuFeatures?.split(`,`).map(e=>e.trim()),bare:t.bare||void 0,sshEnabled:t.ssh||!!t.sshKey||T.length>0||!!t.sshKeys?.length,sshPublicKeys:T.length>0?T:void 0,sshKeyIds:t.sshKeys,webTerminalEnabled:t.webTerminal,inBoxPreviewPublishing:t.inBoxPreview?void 0:!1,env:Object.keys(p).length>0?p:void 0,git:h,...te?{resources:te}:{},gpuLease:v,...Fi(t),storage:g,fromSnapshot:t.fromSnapshot,publicTemplateId:t.publicTemplate,publicTemplateVersionId:t.publicTemplateVersion,teamId:u,...t.billingOwner?{billingOwnerId:t.billingOwner}:{},secrets:ee,...C?{proxySecrets:C}:{},...sa(t.allowDomain,u),metadata:m,driver:y,backend:b},ne=t.tee?{tee:t.tee,sealed:t.sealed||void 0,attestationRefresh:t.attestationRefresh||t.attestationNonce===`auto`||void 0}:void 0,k=ne?await ke(c,{...D,confidential:ne,attestationNonce:t.attestationNonce??(t.attestationRefresh?`auto`:void 0),requireAttestation:t.requireAttestation??!0}):void 0,A=k?.sandbox??await Pt(c,D);t.wait&&(l.text=`Waiting for sandbox to start...`,await A.waitFor(`running`,{timeoutMs:12e4}),await A.refresh()),l.stop();let re=fa(A);t.json?e({id:A.id,name:A.name,active:re.active,status:A.status,resources:A.resources,createdAt:A.createdAt,expiresAt:A.expiresAt,connection:ea(A.connection),teamId:u,gpuLease:A.gpuLease,confidential:ne,attestation:k?.attestation,attestationNonce:k?.attestationNonce}):pa(A,re.next,D,{teamId:u,tee:ne?.tee,proof:k}),ca(A)})}function fa(e){let t=y();return t||g(e.id),{active:!t,next:t?`Active sandbox is still ${t}. Use this one with: tangle use ${e.id}`:`Active sandbox set to ${e.name??e.id}. Next: tangle agent prompt "<task>"`}}function pa(e,t,r,i){n(`Sandbox created: ${e.id}`),l({id:e.id,name:e.name,status:e.status,runtime:e.runtime,resources:e.resources,createdAt:e.createdAt?.toISOString(),expiresAt:e.expiresAt?.toISOString(),connection:e.connection});for(let[e,t,n]of[[`Idle timeout (requested)`,r.idleTimeoutSeconds,900],[`Lifetime (requested)`,r.maxLifetimeSeconds,3600]])t&&t!==n&&console.log(`${e}: ${le(t)}`);i.teamId&&console.log(`Team: ${i.teamId}`),e.gpuLease&&(console.log(`GPU lease: ${e.gpuLease.id}`),Wi(e.gpuLease)),i.tee&&(console.log(`TEE: ${i.tee}`),console.log(`Attestation: ${i.proof?.attestation?`present`:`not returned`}`),i.proof?.attestationNonce&&console.log(`Attestation nonce: ${i.proof.attestationNonce}`)),c(t)}const ma="A catalog environment, a container image reference, or a built image ID. Firecracker runs only images pinned by repository@sha256 that the cell's Firecracker hosts carry; `tangle environments list` shows each image's runtimes";function ha(){return new Be(`--runtime <runtime>`,`Isolation on the platform's hosts: docker runs a container on the host kernel, firecracker a microVM with its own kernel. Omit for the platform default`).choices(Ee)}function ga(){let e=[`id_ed25519`,`id_ecdsa`,`id_rsa`].map(e=>`${H()}/.ssh/${e}.pub`),t=e.find(e=>P(e));if(!t)throw Error(`--ssh needs a public key and found none at ${e.join(`, `)}. Run ssh-keygen -t ed25519, or pass --ssh-key-file.`);return t}function _a(e,t){return t instanceof p?t:Error(`--profile ${e}: ${t.message}`)}function va(e,t){if(!t)return e;let n=e?.model??{};return{...e,model:{...n,reasoningEffort:t}}}function ya(e){if(e.spec){let t=JSON.parse(F(e.spec,`utf8`));return{base:{fleetId:e.fleetId,defaults:t.defaults,policy:t.policy,workspace:t.workspace,metadata:t.metadata},machines:t.machines??[]}}let t=Sa(e),n=Ca(e,!!t?.accelerator),r={...e.environment?{environment:e.environment}:{},...t?{resources:t}:{},...e.runtime?{runtime:e.runtime}:{},...n?{gpuLease:n}:{},...e.backend?{backend:{type:e.backend}}:{}},i=wa(e),a=Math.max(1,Number(e.count)||1),o=Array.from({length:a},(e,t)=>({machineId:`worker-${t+1}`}));return{base:{fleetId:e.fleetId,defaults:Object.keys(r).length>0?r:void 0,policy:i,workspace:{mode:e.workspace}},machines:o}}function ba(e){let{base:t,machines:n}=ya(e);return{...t,machines:n}}function xa(e){let{base:t,machines:n}=ya(e);return{...t,workers:n}}function Sa(e){let t={};if(e.cpu&&(t.cpuCores=k(e.cpu,`--cpu`)),e.memory&&(t.memoryMB=k(e.memory,`--memory`)),e.disk&&(t.diskGB=k(e.disk,`--disk`)),e.acceleratorKind)t.accelerator=_i({kind:e.acceleratorKind,count:e.acceleratorCount,memory:e.acceleratorMemory});else if(e.acceleratorCount||e.acceleratorMemory)throw Error(`--accelerator-count and --accelerator-memory require --accelerator-kind`);return Object.keys(t).length>0?t:void 0}function Ca(e,t){return vi({provider:e.gpuProvider,image:e.gpuWorkerImage,env:e.gpuEnv,maxSpendUsd:e.gpuMaxSpendUsd,maxLifetime:e.gpuMaxLifetime,idleTimeout:e.gpuIdleTimeout},t,`Fleet GPU lease flags require --accelerator-kind`)}function wa(e){let t={};return e.maxSpendUsd&&(t.maxSpendUsd=Number(e.maxSpendUsd)),e.maxLifetime&&(t.maxLifetimeSeconds=O(e.maxLifetime,`--max-lifetime`)),Object.keys(t).length>0?t:void 0}function Ta(r){r.command(`create`).description(`Create a sandbox fleet`).option(`--fleet-id <id>`,`Stable fleet id (generated when omitted)`).option(`--count <n>`,`Number of worker machines`,`1`).option(`--environment <environment>`,ma).addOption(ha()).option(`--cpu <cores>`,`CPU cores per machine`).option(`--memory <mb>`,`Memory in MB per machine`).option(`--disk <gb>`,`Disk in GB per machine`).option(`--accelerator-kind <kind>`,`Accelerator kind per machine, for example nvidia-l4 or nvidia-h100`).option(`--accelerator-count <count>`,`Accelerator devices per machine`).option(`--accelerator-memory <gb>`,`Minimum memory per GPU in decimal GB`).option(`--gpu-provider <provider>`,`GPU cloud provider per machine; omitted picks the cheapest configured provider`).option(`--gpu-worker-image <image>`,`GPU worker image override`).option(`--gpu-env <vars...>`,`Environment variables for each GPU worker (KEY=VALUE)`).option(`--gpu-max-spend-usd <usd>`,`Maximum spend per machine GPU lease`).option(`--gpu-max-lifetime <duration>`,`Maximum GPU lease lifetime per machine: seconds, or a duration like 2h`).option(`--gpu-idle-timeout <duration>`,`Destroy each GPU lease after this idle time: seconds, or a duration like 10m`).option(`--backend <id>`,`Agent backend type`).option(`--workspace <mode>`,`Workspace mode: isolated (no driver supports shared yet)`,`isolated`).option(`--max-spend-usd <n>`,`Fleet spend cap in USD (policy)`).option(`--max-lifetime <duration>`,`Max lifetime, e.g. 2h (policy)`).option(`--spec <file.json>`,`Path to a JSON file describing the fleet (overrides synthesized machines)`).option(`--coordinator`,`Create a coordinator + workers fleet (routes to createWithCoordinator)`).action(async r=>{let{client:i}=D(r),a=d(`Creating fleet...`);a.start();let o=r.coordinator?await i.fleets.createWithCoordinator(xa(r)):await i.fleets.create(ba(r));a.stop();let s=ki(o.machines);r.json?e({fleetId:o.fleetId,machines:s}):(n(`Fleet created: ${o.fleetId}`),t(s,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}]))})}function Ea(r){r.command(`exec <fleet-id> <command>`).description(`Run a shell command across the fleet's machines`).option(`--machine <id...>`,`Restrict to a subset of machine ids (default: all)`).option(`--cwd <dir>`,`Working directory for the command`).option(`--timeout <ms>`,`Per-machine timeout in milliseconds`).option(`--max-concurrent <n>`,`Max concurrent dispatches`).action(async(n,r,i)=>{let{client:a}=D(i),o=d(`Dispatching command...`);o.start();let s=await(await a.fleets.list({fleetId:n})).dispatchExecDetailed(r,{machines:i.machine,cwd:i.cwd,timeoutMs:i.timeout?O(i.timeout,`--timeout`,`ms`):void 0,maxConcurrent:i.maxConcurrent?Number(i.maxConcurrent):void 0});if(o.stop(),i.json)e(s);else{t(s.results.map(e=>({machineId:e.machineId,ok:e.ok,exitCode:e.result?.exitCode,durationMs:e.durationMs})),[{key:`machineId`,header:`Machine`,width:20},{key:`ok`,header:`OK`,width:6},{key:`exitCode`,header:`Exit`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14}]);for(let e of s.results){let t=e.result?.stdout,n=e.result?.stderr;t&&(console.log(`\n[${e.machineId}] stdout:`),console.log(t)),n&&(console.log(`\n[${e.machineId}] stderr:`),console.log(n)),e.error&&console.log(`\n[${e.machineId}] error: ${e.error.message}`)}}s.results.some(e=>e.ok===!1)&&(process.exitCode=1)}),r.command(`run [prompt]`).description(`Create a fleet of agents, run one turn on every agent, print each result, then delete the fleet`).requiredOption(`--agents <n|file>`,`Number of agents, or a JSON file with an array of agent specs (agentId, harness, model, profile or { profileId, revision }, task)`).option(`--placement <mode>`,`auto (pack by sandbox memory), dedicated (one sandbox per agent), or a number of agents per sandbox`,`auto`).option(`--model <id>`,`Model every agent runs, e.g. gpt-4.1-mini`).option(`--memory <mb>`,`Memory in MB per sandbox; auto placement packs by it`).option(`--environment <environment>`,`Environment for each sandbox`).option(`--max-spend-usd <usd>`,`Budget for the fleet in USD, enforced by the Platform on the fleet's own key`).option(`--timeout <ms>`,`Per-agent turn timeout in milliseconds`).option(`--fleet-id <id>`,`Stable fleet id (generated when omitted)`).option(`--parent-fleet <id>`,`Fleet that spawns this one; its cap must cover this cap`).option(`--parent-agent <id>`,`Agent of --parent-fleet that spawns this one`).option(`--keep`,`Keep the fleet after the run instead of deleting it`).action(async(t,r)=>{let i=/^\d+$/.test(r.agents)?Number(r.agents):JSON.parse(F(r.agents,`utf8`));if(!Array.isArray(i)&&t===void 0)throw Error(`A prompt is required unless --agents names a file whose agents carry tasks`);let{client:a}=D(r);if(!!r.parentFleet!=!!r.parentAgent)throw Error(`--parent-fleet and --parent-agent go together`);let s=r.placement===`auto`||r.placement===`dedicated`?r.placement:{agentsPerSandbox:Number(r.placement)},c=r.maxSpendUsd?Number(r.maxSpendUsd):void 0,l=r.timeout?O(r.timeout,`--timeout`,`ms`):void 0,u=d(`Creating fleet...`);u.start();let f=Date.now(),p=await a.fleets.create({fleetId:r.fleetId,agents:i,placement:s,defaults:{...r.environment?{environment:r.environment}:{},...r.memory?{resources:{memoryMB:k(r.memory,`--memory`)}}:{},...r.model?{backend:{type:`opencode`,model:{model:r.model}}}:{}},...c===void 0?{}:{budgetUsd:c},...r.parentFleet?{parent:{fleetId:r.parentFleet,agentId:r.parentAgent}}:{}}),m=Date.now()-f;u.stop(),r.json||n(`Fleet ${p.fleetId}: ${p.agents.length} agents on ${p.machines.size} sandboxes in ${m} ms`);let h=[],g;try{for await(let e of p.run(t,{timeoutMs:l})){if(e.type===`agent.finished`&&!r.json){let t=e.result;console.log(`[${t.agentId}] ${t.harness??`default`}/${t.model??`default`} ${t.status} ${t.durationMs}ms ${t.costUsd===void 0?`no cost reported`:`$${t.costUsd.toFixed(5)}`} ${t.result?.response??t.error??``}`)}e.type===`fleet.finished`&&(h=e.results,g=e.spend)}}finally{r.keep||await p.delete({continueOnError:!0})}r.json?e({fleetId:p.fleetId,createMs:m,sandboxes:p.machines.size,results:h,spend:g,deleted:!r.keep}):o({fleetId:p.fleetId,completed:h.filter(e=>e.status===`completed`).length,agents:h.length,spend:JSON.stringify(g),deleted:!r.keep}),h.some(e=>e.status!==`completed`)&&(process.exitCode=1)}),r.command(`cancel <fleet-id>`).description(`Interrupt every agent of a fleet and cancel its child fleets; sandboxes keep running`).action(async(t,r)=>{let{client:i}=D(r),a=await(await i.fleets.list({fleetId:t})).cancel();r.json?e({fleetId:t,...a}):n(`Fleet ${t}: interrupted ${a.interrupted} agents, cancelled ${a.children} child fleets`)})}const Da=[`list`,`create`,`delete`,`exec`,`prompt`,`read`,`write`];function Oa(e){if(!(!e||e.length===0)){for(let t of e)if(!Da.includes(t))throw Error(`Invalid token action '${t}'. Allowed: ${Da.join(`, `)}`);return e}}function ka(e){return e.length<=12?`****`:`${e.slice(0,6)}...${e.slice(-4)} (masked — use --json for full value)`}function Aa(t){t.command(`token <fleet-id>`).description(`Mint a scoped fleet bearer token (treated as a secret)`).option(`--action <a...>`,`Allowed actions: list create delete exec prompt read write (prompt grants nothing since fleet prompt dispatch was removed)`).option(`--ttl-minutes <n>`,`Token lifetime in minutes`).action(async(t,n)=>{let{client:r}=D(n),i=d(`Minting fleet token...`);i.start();let a=await r.fleets.createToken(t,{actions:Oa(n.action),ttlMinutes:n.ttlMinutes?k(n.ttlMinutes,`--ttl-minutes`):void 0});i.stop(),n.json?e(a):(o({"Fleet ID":a.fleetId,Token:ka(a.token),"Expires at":new Date(a.expiresAt).toISOString(),Actions:a.actions.join(`, `)}),console.log(`
142
+ Re-run with --json to print the full token value.`))})}function ja(){let r=new z(`workspace`).description(`Manage a fleet's shared workspace`);return r.command(`snapshot <fleet-id>`).description(`Snapshot the fleet's shared workspace`).action(async(t,r)=>{let{client:i}=D(r),a=d(`Creating workspace snapshot...`);a.start();let o=await i.fleets.createWorkspaceSnapshot(t);a.stop(),r.json?e(o):n(`Workspace snapshot created: ${o.snapshotId??o.id}`)}),r.command(`restore <fleet-id> <snapshot-id>`).description(`Restore the fleet's shared workspace from a snapshot`).action(async(t,r,i)=>{let{client:a}=D(i),o=d(`Restoring workspace...`);o.start();let s=await a.fleets.restoreWorkspaceSnapshot(t,r);o.stop(),i.json?e(s):n(`Workspace restored from ${s.snapshotId??r}`)}),r.command(`reconcile <fleet-id>`).description(`Re-mount the shared workspace on all fleet machines`).action(async(n,r)=>{let{client:i}=D(r),a=d(`Reconciling workspace...`);a.start();let s=await i.fleets.reconcileWorkspace(n);a.stop(),r.json?e(s):(o({"Fleet ID":s.fleetId,Checked:s.checked,"Orphaned mounts":s.orphanedMounts}),t(s.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`mounted`,header:`Mounted`,width:10}]))}),r}function Ma(){let e=new z(`fleet`).description(`Manage sandbox fleets`);return Ta(e),Ai(e),e.addCommand(ja()),Ea(e),Oi(e),Aa(e),e}function Na(){let t=new z(`fs`).description(`File system operations on sandboxes`);return t.command(`upload`).description(`Upload a file to a sandbox`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<local-path>`,`Local file path`).argument(`<remote-path>`,`Remote destination path`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);if(s=await K(s),!ge.existsSync(n))throw Error(`Local file not found: ${n}`);let c=ge.statSync(n),l=Date.now();i.json||console.error(`Uploading ${n} to ${r}...`),await s.fs.upload(n,r,{onProgress:e=>{if(i.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesUploaded}/${e.totalBytes} bytes)`)}});let u=Date.now()-l;i.json||console.error(``),i.json?e({success:!0,localPath:n,remotePath:r,size:c.size,durationMs:u}):console.log(`✓ Uploaded ${c.size} bytes in ${u}ms`)}),t.command(`download`).description(`Download a file from a sandbox`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<remote-path>`,`Remote file path`).argument(`<local-path>`,`Local destination path`).action(async(t,n,r,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);s=await K(s);let c=Date.now();i.json||console.error(`Downloading ${n} to ${r}...`),await s.fs.download(n,r,{onProgress:e=>{if(i.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesDownloaded}/${e.totalBytes} bytes)`)}});let l=Date.now()-c,u=ge.statSync(r);i.json||console.error(``),i.json?e({success:!0,remotePath:n,localPath:r,size:u.size,durationMs:l}):console.log(`✓ Downloaded ${u.size} bytes in ${l}ms`)}),t.command(`ls`).description(`List directory contents`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`[path]`,`Directory path`,`.`).option(`-l, --long`,`Show detailed information`).option(`-a, --all`,`Include hidden files`).action(async(t,n,i)=>{let{context:a,client:o}=D(i),s=await G(o,a,t);s=await K(s);let c=await s.fs.list(n,{all:i.all,long:i.long});if(i.json)e(c);else if(i.long)r([`Mode`,`Owner`,`Group`,`Size`,`Modified`,`Name`],c.map(e=>{let t=e.isDir?`d`:e.isSymlink?`l`:`-`,n=Pa(e.permissions),r=e.isDir?`<DIR>`:Fa(e.size),i=e.modTime.toLocaleDateString();return[t+n,e.owner,e.group,r,i,e.name]}));else{let e=c.map(e=>e.isDir?`${e.name}/`:e.name);console.log(e.join(` `))}}),t.command(`stat`).description(`Get file or directory information`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to file or directory`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.fs.stat(n);r.json?e(s):(console.log(` File: ${s.name}`),console.log(` Path: ${s.path}`),console.log(` Size: ${Fa(s.size)} (${s.size} bytes)`),console.log(` Type: ${s.isDir?`directory`:s.isSymlink?`symlink`:`file`}`),console.log(` Mode: ${Pa(s.permissions)} (${s.permissions.toString(8)})`),console.log(` Owner: ${s.owner}`),console.log(` Group: ${s.group}`),console.log(` Modified: ${s.modTime.toISOString()}`),console.log(` Accessed: ${s.accessTime.toISOString()}`))}),t.command(`cat`).description(`Print file contents`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to file`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.read(n);r.json?e({path:n,content:s}):console.log(s)}),t.command(`rm`).description(`Delete a file or directory`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to delete`).option(`-r, --recursive`,`Delete directories recursively`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o),await o.fs.delete(n,{recursive:r.recursive}),r.json?e({success:!0,path:n,deleted:!0}):console.log(`✓ Deleted: ${n}`)}),t.command(`mkdir`).description(`Create a directory`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Directory path to create`).option(`-p, --parents`,`Create parent directories as needed`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o),await o.fs.mkdir(n,{recursive:r.parents}),r.json?e({success:!0,path:n,created:!0}):console.log(`✓ Created: ${n}`)}),t.command(`exists`).description(`Check if a path exists`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to check`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.fs.exists(n);r.json?e({path:n,exists:s}):(console.log(s?`exists`:`not found`),process.exit(+!s))}),t}function Pa(e){let t=[`r`,`w`,`x`],n=``;for(let r=2;r>=0;r--){let i=r*3;for(let r=0;r<3;r++)n+=e>>i+(2-r)&1?t[r]:`-`}return n}function Fa(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return r===0?`${n}${t[r]}`:`${n.toFixed(1)}${t[r]}`}function Ia(){let t=new z(`git`).description(`Git operations in a sandbox workspace`);return t.command(`status`).description(`Show git repository status`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching status...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.status();if(a.stop(),n.json)e(s);else if(!s.isRepo)console.log(`No git repository in the sandbox workspace.`);else{if(console.log(`Branch: ${s.branch??`unknown`}`),console.log(`HEAD: ${s.head.slice(0,7)||`(no commits)`}`),console.log(`Dirty: ${s.isDirty?`yes`:`no`}`),s.ahead&&console.log(`Ahead: ${s.ahead}`),s.behind&&console.log(`Behind: ${s.behind}`),s.staged.length>0){console.log(`\nStaged (${s.staged.length}):`);for(let e of s.staged)console.log(` + ${e}`)}if(s.modified.length>0){console.log(`\nModified (${s.modified.length}):`);for(let e of s.modified)console.log(` M ${e}`)}if(s.untracked.length>0){console.log(`\nUntracked (${s.untracked.length}):`);for(let e of s.untracked)console.log(` ? ${e}`)}}}),t.command(`log`).description(`Show commit log`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`-n, --limit <count>`,`Max commits to show`,`10`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching log...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.log(Number.parseInt(n.limit,10));if(a.stop(),n.json)e(s);else if(s.length===0)console.log(`No commits found`);else for(let e of s)console.log(`${e.shortSha} ${e.message.split(`
143
+ `)[0]} (${e.author}, ${e.date.toLocaleDateString()})`)}),t.command(`diff`).description(`Show diff`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--ref <ref>`,`Ref to diff against`).action(async(t,n)=>{let{context:r,client:i}=D(n),a=d(`Fetching diff...`);n.json||a.start();let o=await G(i,r,t);o=await K(o);let s=await o.git.diff(n.ref);a.stop(),n.json?e(s):s.raw?console.log(s.raw):console.log(`${s.additions} additions, ${s.deletions} deletions across ${s.files.length} files`)}),t.command(`add`).description(`Stage files`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<paths...>`,`Paths to stage`).action(async(e,t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,e);o=await K(o),await o.git.add(t),n(`Staged: ${t.join(`, `)}`)}),t.command(`commit`).description(`Create a commit`).argument(`<id-or-name>`,`Sandbox ID or name`).requiredOption(`-m, --message <msg>`,`Commit message`).option(`--amend`,`Amend the previous commit`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,t);o=await K(o);let s=await o.git.commit(r.message,{amend:r.amend});r.json?e(s):n(`Committed: ${s.shortSha} ${s.message}`)}),t.command(`push`).description(`Push to remote`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--force`,`Force push`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Pushing...`);a.start();let o=await G(i,r,e);o=await K(o),await o.git.push({force:t.force}),a.stop(),n(`Pushed to remote`)}),t.command(`pull`).description(`Pull from remote`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--rebase`,`Rebase instead of merge`).action(async(e,t)=>{let{context:r,client:i}=D(t),a=d(`Pulling...`);a.start();let o=await G(i,r,e);o=await K(o),await o.git.pull({rebase:t.rebase}),a.stop(),n(`Pulled from remote`)}),t.command(`branches`).description(`List branches`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(t,n)=>{let{context:i,client:a}=D(n),o=d(`Fetching branches...`);n.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.git.branches();o.stop(),n.json?e(c):c.length===0?console.log(`No branches found`):r([`Name`,`Current`,`Remote`],c.map(e=>[e.name,e.current?`* `:` `,e.upstream??`-`]))}),t.command(`checkout`).description(`Checkout a branch or ref`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<ref>`,`Branch name or ref`).option(`-b, --create`,`Create a new branch`).action(async(e,t,r)=>{let{context:i,client:a}=D(r),o=await G(a,i,e);o=await K(o),await o.git.checkout(t,{create:r.create}),n(`Checked out: ${t}${r.create?` (new)`:``}`)}),t}function La(){let n=new z(`intelligence`).description(`Create and inspect trace intelligence reports`);return n.command(`connect [agent]`).alias(`connect-agent`).description(`Connect local agent CLIs to Tangle Intelligence`).option(`--endpoint <url>`,`OTLP endpoint base`,Dn).option(`--workspace <path>`,`Workspace to write hook files into`,`.`).option(`--service-name <name>`,`OTel service.name label`).option(`--environment <name>`,`OTel deployment.environment label`,`local`).option(`--dry-run`,`Print planned writes without changing files`).option(`--hook-command <command>`,`Command native hooks should run`,`tangle intelligence hook`).option(`--no-smoke`,`Skip the install smoke trace`).action(async(t,n)=>{let r=t??`local`;Mn(r);let i=za(n.apiKey),a=await Ln({selection:r,workspace:n.workspace,apiKey:i,endpoint:n.endpoint,serviceName:n.serviceName??Pn(n.workspace),environment:n.environment,smoke:n.smoke,dryRun:!!n.dryRun,hookCommand:n.hookCommand}),s={configPath:a.configPath,agents:a.agents,nativeAgents:a.nativeAgents,manual:a.manual,written:a.written,smokeTraceId:a.smokeTraceId};if(n.json){e(s);return}o({Config:a.configPath,Agents:a.agents.join(`, `),"Native Hooks":a.nativeAgents.join(`, `)||void 0,"Manual Setup":a.manual.length?a.manual.map(e=>`${e.label}: ${e.reason}`).join(` `):void 0,Files:a.written.join(`, `),"Smoke Trace":a.smokeTraceId})}),n.command(`doctor`).description(`Check whether your agent traces carry CONTENT or are metadata-only`).option(`--endpoint <url>`,`OTLP endpoint base`,Dn).action(async t=>{let n=In(),r=await Hn({endpoint:t.endpoint===`https://intelligence.tangle.tools/v1/otlp`?n?.endpoint??`https://intelligence.tangle.tools/v1/otlp`:t.endpoint,apiKey:za(t.apiKey??n?.apiKey)});t.json?e(r):Ra(r),r.contentSeen||(process.exitCode=1)}),n.command(`hook`).description(`Emit one local agent hook event to Tangle Intelligence`).requiredOption(`--agent <agent>`,`Agent surface`).requiredOption(`--event <event>`,`Hook event name`).option(`--payload <json>`,`Hook payload JSON`).option(`--endpoint <url>`,`OTLP endpoint base`).option(`--service-name <name>`,`OTel service.name label`).option(`--environment <name>`,`OTel deployment.environment label`).option(`--session-id <id>`,`Session id override`).option(`--dry-run`,`Build the OTLP request without sending it`).option(`--non-blocking`,`Do not fail the parent agent process`).action(async t=>{try{let n=Ba(t.agent),r=In(),i={agent:n,event:t.event,endpoint:t.endpoint??r?.endpoint??`https://intelligence.tangle.tools/v1/otlp`,apiKey:za(t.apiKey??r?.apiKey),serviceName:t.serviceName??r?.serviceName??Pn(process.cwd()),environment:t.environment??r?.environment??`local`,sessionId:t.sessionId,payload:t.payload===void 0?await Ha():Va(t.payload)};if(t.dryRun){let r=zn(i);if(t.json){e(r);return}o({Trace:r.traceId,Agent:n,Event:t.event});return}let a=await Bn(i);if(t.json){e({traceId:a});return}o({Trace:a,Agent:n,Event:t.event})}catch(n){if(t.nonBlocking){let r=n instanceof Error?n.message:String(n);t.json?e({ok:!1,error:r}):console.error(`Tangle Intelligence hook skipped: ${r}`);return}f(n)}}),n.command(`sandbox <sandbox-id>`).description(`Create an intelligence report for one sandbox`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async(e,t)=>{await Ua({type:`sandbox`,id:e},t)}),n.command(`fleet <fleet-id>`).description(`Create an intelligence report for a sandbox fleet`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async(e,t)=>{await Ua({type:`fleet`,id:e},t)}),n.command(`create`).description(`Create a trace intelligence report`).requiredOption(`--subject-type <type>`,`sandbox | fleet`).requiredOption(`--subject-id <id>`,`Subject identifier`).option(`--mode <mode>`,`deterministic | agentic`,`deterministic`).option(`--max-usd <amount>`,`Maximum customer charge for agentic analysis`).option(`--metadata <json>`,`Metadata JSON object`).action(async e=>{await Ua({type:Ga(e.subjectType),id:e.subjectId},e)}),n.command(`get <job-id>`).description(`Get an intelligence report`).action(async(t,n)=>{let{client:r}=D(n),i=n.json?null:d(`Fetching intelligence report...`);i?.start();let a=await r.intelligence.getReport(t);if(i?.stop(),n.json){e(a);return}Wa(a)}),n.command(`list`).description(`List intelligence reports`).option(`--subject-type <type>`,`sandbox | fleet`).option(`--subject-id <id>`,`Subject identifier`).option(`--limit <count>`,`Maximum reports to return`).action(async n=>{let{client:r}=D(n),i=n.json?null:d(`Fetching intelligence reports...`);i?.start();let a=await r.intelligence.listReports({subjectType:n.subjectType===void 0?void 0:Ga(n.subjectType),subjectId:n.subjectId,limit:n.limit===void 0?void 0:Ja(n.limit)});if(i?.stop(),n.json){e(a);return}t(a.map(e=>({jobId:e.jobId,subject:`${e.subject.type}:${e.subject.id}`,mode:e.mode,status:e.status,cost:`$${e.billing.costUsd.toFixed(2)}`,updatedAt:e.updatedAt})),[{key:`jobId`,header:`Job`,width:20},{key:`subject`,header:`Subject`,width:28},{key:`mode`,header:`Mode`,width:15},{key:`status`,header:`Status`,width:14},{key:`cost`,header:`Cost`,width:10},{key:`updatedAt`,header:`Updated`,width:18}])}),n}function Ra(e){o({Status:e.contentSeen?`content flowing`:e.tracesSeen?`metadata-only — a content gate is missing`:`no traces yet`,"Traces seen":e.tracesSeen?`yes`:`no`,"Content seen":e.contentSeen?`yes`:`no`,"Last seen":e.lastSeenAt??`never`,Window:`${e.windowDays}d`});let n=Object.entries(e.byAgent);n.length>0&&(console.log(),t(n.map(([e,t])=>({agent:e,traces:t.tracesSeen?`yes`:`no`,content:t.contentSeen?`yes`:`no`})),[{key:`agent`,header:`Agent`,width:18},{key:`traces`,header:`Traces`,width:10},{key:`content`,header:`Content`,width:10}]))}function za(e){let t=e??process.env.TANGLE_INTELLIGENCE_API_KEY??process.env.TANGLE_API_KEY;if(!t)throw Error(`--api-key, TANGLE_INTELLIGENCE_API_KEY, or TANGLE_API_KEY is required`);return t}function Ba(e){if(Nn(e))return e;throw Error(`agent must be a known Tangle Intelligence agent surface`)}function Va(e){try{return JSON.parse(e)}catch(e){throw Error(`--payload must be JSON: ${e instanceof Error?e.message:String(e)}`)}}async function Ha(){if(process.stdin.isTTY)return;let e=``;for await(let t of process.stdin)if(e+=typeof t==`string`?t:t.toString(`utf8`),e.length>65536)throw Error(`hook payload exceeds 65536 bytes`);let t=e.trim();if(t)try{return JSON.parse(t)}catch{return{body:t.slice(0,4096)}}}async function Ua(t,n){let r=Ka(n.mode),i=Ya(n.metadata),a=n.maxUsd===void 0?void 0:qa(n.maxUsd);if(r===`agentic`&&a===void 0)throw Error(`Agentic intelligence reports require --max-usd`);let{client:o}=D(n),s=n.json?null:d(`Creating intelligence report...`);s?.start();let c=await o.intelligence.createReport({subject:t,mode:r,...a===void 0?{}:{budget:{billTo:`customer`,maxUsd:a}},...i===void 0?{}:{metadata:i}});if(s?.stop(),n.json){e(c);return}Wa(c)}function Wa(t){o({Job:t.jobId,Subject:`${t.subject.type}:${t.subject.id}`,Mode:t.mode,Status:t.status,"Billed To":t.billing.billedTo,Cost:`$${t.billing.costUsd.toFixed(2)}`,Budget:t.billing.budgetMaxUsd===void 0?void 0:`$${t.billing.budgetMaxUsd.toFixed(2)}`,Updated:t.updatedAt}),t.result!==null&&(console.log(),e(t.result))}function Ga(e){if(e===`sandbox`||e===`fleet`)return e;throw Error(`subject type must be sandbox or fleet`)}function Ka(e){if(e===`deterministic`||e===`agentic`)return e;throw Error(`mode must be deterministic or agentic`)}function qa(e){let t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`--max-usd must be a non-negative number`);return t}function Ja(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Ya(e){if(e===void 0)return;let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`--metadata must be a JSON object`);return t}const Xa=[`router`,`sandbox`,`blueprint-agent`,`evals`,`agent-builder`];async function Za(e,t){let n=await ue({...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.platformUrl===void 0?{}:{baseUrl:e.platformUrl},...e.baseUrl===void 0?{}:{sandboxBaseUrl:e.baseUrl}});if(!t||!n.minted)return n;throw Error("This command needs a key you minted yourself. A browser login is exchanged for a short-lived key the platform will not accept for key management. Set TANGLE_API_KEY, run `tangle auth login --api-key sk-tan-…`, or mint the key in the web console. `tangle keys list` works from the login alone.")}async function Qa(e,t,n={}){let r=new Headers(n.headers);n.body&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await de(e,t,{...n,headers:r});if(n.expected!==void 0&&i.status!==n.expected)throw Error(await $a(i,t));return i}async function $a(e,t){let n=await e.text().catch(()=>``),r;try{let e=JSON.parse(n),t=typeof e?.error==`string`?e.error:e?.error?.message;typeof t==`string`&&t.trim()&&(r=t)}catch{}if(r)return`${r} (HTTP ${e.status})`;let i=n?`: ${n.slice(0,400)}`:``;return`Platform request to ${t} returned ${e.status}${i}`}const eo=[`ID`,`Prefix`,`Name`,`Product`,`Created`,`Last used`,`Expires`];function to(e){return[e.id,e.keyPrefix??``,e.name,e.product??`all`,e.createdAt,e.lastUsedAt??`—`,e.expiresAt??`—`]}function no(){let t=new z(`keys`).description(`Manage sk-tan-* API keys on id.tangle.tools`);return t.command(`list`).description(`List your active API keys`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async t=>{let n=await Za(t,!1),i=n.baseUrl,a=await(await Qa(n,`${i}/v1/keys`,{expected:200})).json();if(t.json){e(a);return}r(eo,a.data.map(to))}),t.command(`create`).description(`Create a new API key`).argument(`<name>`,`Human-readable name for the key`).option(`--product <product>`,`Restrict the key to one product (${Xa.join(`|`)}). Omit for all products.`).option(`--budget-usd <amount>`,`Hard budget cap in USD`).option(`--rpm-limit <limit>`,`Requests-per-minute cap`).option(`--expires-in-days <days>`,`Expire the key after N days (integer)`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async(t,r)=>{if(r.product!==void 0&&!Xa.includes(r.product))throw Error(`Invalid --product. Expected one of ${Xa.join(`, `)}`);let i=await Za(r,!0),a=i.baseUrl,o=r.expiresInDays===void 0?void 0:new Date(Date.now()+k(r.expiresInDays,`--expires-in-days`)*24*60*60*1e3).toISOString(),s=d(`Creating API key...`);s.start();let l=await Qa(i,`${a}/v1/keys`,{method:`POST`,expected:201,body:JSON.stringify({name:t,product:r.product,budgetUsd:r.budgetUsd?Number.parseFloat(r.budgetUsd):void 0,rpmLimit:r.rpmLimit?Number.parseInt(r.rpmLimit,10):void 0,expiresAt:o})});s.stop();let u=await l.json();if(r.json){e(u);return}n(`API key created: ${u.data.prefix}…`),c(`Copy this key now — it will never be shown again:\n${u.data.key}`)}),t.command(`revoke`).description(`Revoke an API key`).argument(`<keyId>`,"Key ID (from `tcloud keys list`)").option(`--yes`,`Skip the confirmation prompt`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async(t,r)=>{let i=await Za(r,!0),a=i.baseUrl;if(!r.yes&&!await N(`Revoke key ${t}? Any service still using it will start to fail.`,`--yes`)){c(`Aborted.`);return}let o=await(await Qa(i,`${a}/v1/keys/${encodeURIComponent(t)}`,{method:`DELETE`,expected:200})).json();if(r.json){e(o);return}n(`Revoked ${t}`)}),t}function X(e){if(b().token)throw Error(`A line relay cannot manage numbers or attachments. Use your owner CLI outside the agent box.`);return E(x(e))}function ro(e){if(!e.yes)throw Error(`Review the selected line and use --yes to authorize this change. Attaching enables metered agent work.`)}function io(e){if(e===`imessage`||e===`whatsapp`||e===`email`||e===`sms`||e===`voice`||e===`telegram`)return e;throw Error(`--transport must be imessage, whatsapp, email, sms, voice, or telegram`)}function Z(e){return e().catch(f)}async function ao(e){let t=await st(e,`r`);try{if(!(await t.stat()).isFile())throw Error(`Attachment input must be a regular JSON file`);let e=Buffer.alloc(131073),n=0;for(;n<e.length;){let{bytesRead:r}=await t.read(e,n,e.length-n,null);if(r===0)break;n+=r}if(n===e.length)throw Error(`Attachment JSON exceeds 128 KiB`);let r;try{r=JSON.parse(e.subarray(0,n).toString(`utf8`))}catch{throw Error(`Attachment file is not valid JSON`)}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Attachment JSON must be an object`);if(Object.hasOwn(r,`number`))throw Error(`Use the line ID argument, not a number field in the attachment file`);return r}finally{await t.close()}}function oo(t){t.command(`providers`).description(`List provider transports supported by this Hub deployment`).action(t=>Z(async()=>{e(await X(t).lines.providers())})),t.command(`list`).description(`List owned lines, optionally for a saved agent profile or sandbox`).option(`--profile-id <id>`,`Stored profile ID`).option(`--sandbox <id>`,`Existing sandbox ID`).action(t=>Z(async()=>{e(await X(t).lines.list({profileId:t.profileId,sandboxId:t.sandbox}))})),t.command(`get`).argument(`<line-id>`).description(`Inspect a line and its current attachment`).action((t,n)=>Z(async()=>{e(await X(n).lines.get(t))})),t.command(`numbers`).argument(`<connection-id>`).description(`Discover owned provider numbers; this does not purchase or reserve a number`).option(`--transport <transport>`,`imessage, whatsapp, or sms`,`imessage`).action((t,n)=>Z(async()=>{let r=io(n.transport);if(r===`email`)throw Error(`Email uses an owned mailbox, not phone inventory`);if(r===`voice`)throw Error(`Voice numbers are listed by ph0ny; provide the owned number ID to lines connect`);if(r===`telegram`)throw Error(`Telegram uses an owned bot, not phone inventory`);e(await X(n).lines.numbers(t,r))})),t.command(`connect`).argument(`<connection-id>`).description(`Bind an owned number or identity through Hub; no provider rental is purchased`).option(`--transport <transport>`,`imessage, whatsapp, sms, email, voice, or telegram`,`imessage`).option(`--number-id <id>`,`Exact owned provider number ID; required for voice, SMS, WhatsApp and Linq iMessage`).option(`--address <email>`,`Owned mailbox on a verified email domain`).requiredOption(`--reference <reference>`,`Stable client reference; keep it unchanged on retry`).option(`--label <label>`,`Line display name`).option(`--yes`,`Authorize provider webhook configuration and line binding`).action((t,n)=>Z(async()=>{ro(n);let r=io(n.transport);if(r!==`email`&&n.address)throw Error(`--address is email-only`);if((r===`email`||r===`telegram`)&&n.numberId)throw Error(`${r} does not take --number-id`);let i={connectionId:t,label:n.label,clientReference:n.reference},a;if(r===`email`)a={...i,transport:r,address:n.address};else if(r===`telegram`)a={...i,transport:r};else if(r===`imessage`)a={...i,transport:r,phoneNumberId:n.numberId};else{if(!n.numberId)throw Error(`${r} requires --number-id`);a={...i,transport:r,phoneNumberId:n.numberId}}e(await X(n).lines.fromConnection(a))})),t.command(`attach`).argument(`<line-id>`).description(`Attach a saved agent to any sandbox, or use an isolated on-demand member instance`).option(`--file <path>`,`Reviewed native attachment JSON (exclusive with quick-setup flags)`).option(`--profile-id <id>`,`Owner-scoped saved profile; each turn pins its source revision`).option(`--member <address>`,`The one allowed sender: E.164 phone or email`).option(`--sandbox <id>`,`Use an existing sandbox instead of an on-demand instance`).option(`--instance-prefix <prefix>`,`Stable instance namespace; defaults to profile:<profile-id>:`).option(`--tools <mode>`,`chat denies tools; act applies the profile's tools and permissions`).option(`--turns-per-day <count>`,`Per-member daily turn ceiling (default 30)`).option(`--yes`,`Authorize agent execution and spend against your key limits`).action((t,n)=>Z(async()=>{ro(n);let r=X(n),i;if(n.file){if(n.profileId||n.member||n.sandbox||n.instancePrefix||n.tools||n.turnsPerDay)throw Error(`Choose --file or quick-setup flags, not both`);i=await ao(n.file)}else{if(!n.profileId||!n.member)throw Error(`Provide --profile-id and --member, or --file`);if(n.sandbox&&n.instancePrefix)throw Error(`Choose --sandbox or --instance-prefix`);let e=n.tools??`chat`,t=Number(n.turnsPerDay??`30`);if(e!==`chat`&&e!==`act`)throw Error(`--tools must be chat or act`);if(!Number.isSafeInteger(t)||t<1||t>1e4)throw Error(`--turns-per-day must be 1–10000`);if(e===`act`&&n.sandbox)throw Error(`Acting tools require an isolated on-demand instance; omit --sandbox`);i={mode:`personal`,members:[{address:n.member,role:`owner`}],unknownSenders:`reject`,roles:{owner:{context:`own`,tools:e}},respond:{kind:`agent`,profileId:n.profileId,...e===`act`?{rolePolicy:{version:1,roles:{owner:{kind:`general`}},members:{}}}:{}},limits:{turnsPerMemberPerDay:t},...n.sandbox?{sandboxId:n.sandbox}:{instance:{keyPrefix:n.instancePrefix??`profile:${n.profileId}:`,create:{ownerContext:`isolated`,...e===`act`?{egressPolicy:{mode:`strict`,allowDomains:[new URL(_()).hostname],includeImplicitDomains:!1}}:{}}}}}}if(typeof i.sandboxId==`string`==(i.instance!==void 0))throw Error(`Attachment requires exactly one of sandboxId and instance`);let{sandboxId:a,instance:o,...s}=i,c;if(a){let e=await r.get(a);if(!e)throw Error(`Sandbox not found`);c=await e.lines.attach({...s,number:t})}else{if(!o)throw Error(`Attachment requires an instance`);c=await r.lines.attach({...s,number:t,instance:o})}e(c)}));for(let n of[`detach`,`release`])t.command(n).argument(`<line-id>`).description(n===`detach`?`Stop dispatch; preserve history and provider rental`:`Retire a detached Hub line; does not cancel provider rental`).option(`--yes`,`Authorize this change`).action((t,r)=>Z(async()=>{ro(r),e({[n]:await X(r).lines[n](t)})}));t.command(`threads`).argument(`<line-id>`).description(`List this line's separate participant threads`).action((t,n)=>Z(async()=>{e(await X(n).lines.threads(t).list())})),t.command(`messages`).argument(`<line-id>`).argument(`<thread-id>`).description(`Read one authorized participant thread`).action((t,n,r)=>Z(async()=>{e(await X(r).lines.threads(t).messages(n))}))}async function so(e){let{token:t,baseUrl:n}=b();if(t===void 0)return fe(e);if(!t.startsWith(`lrc_`)||!n)throw Error(`The line box needs TANGLE_LINE_TOKEN and TANGLE_HUB_URL`);if(e.apiKey||e.baseUrl&&new URL(e.baseUrl).origin!==new URL(n).origin)throw Error(`A line token cannot be sent to another Hub or combined with an API key`);return new $e({baseUrl:n,authHeaders:()=>({Authorization:`Bearer ${t}`})})}async function co(e,t){if(t)return t;if(!b().token)throw Error(`Provide --line <line-id>`);return(await e.lines.context()).line.id}function lo(e){return e().catch(f)}function uo(){return new z(`context`).description(`Show live line identity, members, consent, reminders and quotas`).action(t=>lo(async()=>{e(await(await so(t)).lines.context())}))}function fo(){let t=new z(`lines`).description(`Connect, manage, message and schedule on a Hub line`);return t.command(`members`).description(`List names, roles and consent on this line`).option(`--line <line-id>`,`Line ID; inferred in a line box`).action(t=>lo(async()=>{let n=await so(t);e(await n.lines.members.list(await co(n,t.line)))})),t.command(`send`).description(`Send to a consenting member through Hub`).argument(`<to-member>`,`Exact member ID for an owner; name, ID, or self in a line box`).argument(`<text>`,`Message text`).option(`--line <line-id>`,`Line ID; inferred in a line box`).option(`--on-behalf-of <member>`,`Verified sender for a member relay`).option(`--not-before <iso-time>`,`Delay delivery until this ISO time`).option(`--idempotency-key <key>`,`Stable key for a retry`).action((t,n,r)=>lo(async()=>{let i=await so(r),a=await co(i,r.line);if(!b().token){if(r.onBehalfOf)throw Error(`--on-behalf-of is only available inside a line box`);if(!r.idempotencyKey)throw Error(`Owner sends require --idempotency-key so a retry keeps the same message`);if(!(await i.lines.members.list(a)).some(e=>e.id===t))throw Error(`Owner sends require an exact member ID from tangle lines members`);e(await i.lines.send(a,{memberId:t,text:n,idempotencyKey:r.idempotencyKey,...r.notBefore?{notBefore:r.notBefore}:{}}));return}e(await i.lines.send(a,{toMember:t,text:n,...r.onBehalfOf?{onBehalfOf:r.onBehalfOf}:{},...r.notBefore?{notBefore:r.notBefore}:{},...r.idempotencyKey?{idempotencyKey:r.idempotencyKey}:{}}))})),t.command(`remind`).description(`Wake the agent at a future time to write your reminder`).argument(`<text>`,`What to remember`).requiredOption(`--at <iso-time>`,`Future ISO time`).option(`--line <line-id>`,`Line ID; inferred in a line box`).option(`--idempotency-key <key>`,`Stable key for a retry`).action((t,n)=>lo(async()=>{if(!n.at)throw Error(`--at is required`);let r=await so(n),i=n.idempotencyKey??Ve(`sha256`).update(JSON.stringify([t,n.at])).digest(`hex`).slice(0,32);e(await r.lines.remind(await co(r,n.line),{text:t,notBefore:n.at,idempotencyKey:i}))})),oo(t),t}function po(){let e=new z(`mcp`).description(`Model Context Protocol bridge commands.`);return e.command(`serve <id-or-name>`).description(`Run a local MCP server (stdio) backed by the given sandbox (ID or name). Pipe its stdio from an MCP client config to expose sandbox tools.`).option(`-s, --session <id>`,`Session id for kernel scoping`,`mcp-local`).option(`--name <name>`,`MCP server name reported to clients`,`tangle-sandbox`).action(async(e,t)=>{let n=x({apiKey:t.apiKey,baseUrl:t.baseUrl}),r=await G(E(n),n,e),i;try{i=(await import(`@modelcontextprotocol/sdk/server/stdio.js`)).StdioServerTransport}catch{throw Error("`@modelcontextprotocol/sdk` is not installed in this environment. Install it with: pnpm add -g @modelcontextprotocol/sdk (or as a dev dep in the project running this command).")}let{connect:a,close:o}=await(await import(`@tangle-network/sandbox/agent`)).createMcpServer(r,{sessionId:t.session,name:t.name});await a(new i),process.stdin.resume(),process.stdin.on(`end`,()=>{o().finally(()=>process.exit(0))});for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>{o().finally(()=>process.exit(0))})}),e}async function mo(e,t){if(t.self&&e)throw Error(`Use --self or an explicit sandbox, not both`);if(!t.self&&!e)throw Error(`Specify a sandbox id/name or --self`);let n=m(),r=t.baseUrl||n.tangleBaseUrl||n.sandboxBaseUrl,i=n.hubUrl;if(t.self&&!r&&i&&new URL(i).origin!==`https://id.tangle.tools`)throw Error(`This deployment must set SANDBOX_BASE_URL or pass --base-url for self preview access`);let a=t.self?t.apiKey??ee():t.apiKey;if(t.self&&!a)throw Error(`Self preview access requires the injected sandbox runtime credential; it never reads saved owner credentials`);let o=x({apiKey:a,baseUrl:r}),s=E(o);return t.self?dt(s):G(s,o,e)}async function ho(e,t,n){let r=d(e);t||r.start();try{return await n()}finally{r.stop()}}function go(e){return e}const _o=`
142
144
  A preview URL is reachable from outside the sandbox only. Inside the box, test
143
145
  the app on localhost:<port>; requests from the box to preview origins
144
146
  (<sandbox>-<port>.tangle.sh) are refused by the egress proxy (403 on CONNECT).
145
147
  lastProbe.httpStatus is whatever your app returned for the platform's probe
146
148
  path. Any status your app returns means the edge reached it; your app does not
147
- need to serve /.well-known/tangle-preview-readiness.`;function _o(){let t=new z(`preview`).description(`Manage sandbox preview links`);return ho(t.command(`start`).description(`Start/reuse a managed development server and publish its ready preview`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).option(`--cwd <directory>`,`Project directory in the selected workspace`).option(`--session <session-id>`,`Select the agent's session workspace`).option(`--name <name>`,`App/service label`).addHelpText(`after`,go)).action(async(t,r)=>{let i=await po(t,r),a=await mo(`Starting managed preview...`,r.json,()=>lt(i,{cwd:r.cwd,sessionId:r.session,name:r.name}));r.json?e(a):(n(`Preview ready: ${a.url}`),console.log(`Preview ID: ${a.previewId}`))}),ho(t.command(`list`).alias(`ls`).description(`List active preview links for a sandbox`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`)).action(async(t,n)=>{let i=await po(t,n),a=await mo(`Fetching preview links...`,n.json,()=>i.previewLinks.list());n.json?e(a):a.length===0?console.log(`No preview links found`):r([`App`,`Preview ID`,`Port`,`URL`,`Status`],a.map(e=>[vo(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),ho(t.command(`publish`).description(`Publish one existing HTTP service; never starts or replaces a process`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).requiredOption(`--port <port>`,`Existing service port`).option(`--name <name>`,`App/service label`).addHelpText(`after`,go)).action(async(t,r)=>{if(!r.port||!/^\d+$/.test(r.port))throw Error(`An integer service port is required`);let i=await po(t,r),a=await mo(`Publishing service...`,r.json,()=>ut(i,{port:Number(r.port),name:r.name}));r.json?e(a):n(`Preview ready: ${a.url}`)}),ho(t.command(`create`).description(`Create a preview link for a port`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<port>`,`Port number to preview`)).action(async(t,r,i)=>{if(!/^\d+$/.test(r)||Number(r)<1||Number(r)>65535)throw Error(`Port must be an integer between 1 and 65535`);let a=await po(t,i),o=await mo(`Creating preview for port ${r}...`,i.json,()=>a.previewLinks.create(Number(r)));i.json?e(o):(n(`Preview created: ${o.url}`),console.log(`Preview ID: ${o.previewId}`))}),ho(t.command(`remove`).alias(`rm`).description(`Remove a preview link`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<preview-id>`,`Preview link ID (from 'preview list')`)).action(async(t,r,i)=>{let a=await po(t,i);await mo(`Removing preview...`,i.json,()=>a.previewLinks.remove(r)),i.json?e({success:!0,previewId:r}):n(`Preview removed: ${r}`)}),t}function vo(e){let t=e?.app;if(!t||typeof t!=`object`)return``;let n=`name`in t?t.name:void 0,r=`cwd`in t?t.cwd:void 0;return typeof n==`string`?n:typeof r==`string`?r:``}function yo(){let t=new z(`process`).description(`Manage processes in a sandbox`);return t.command(`spawn`).description(`Spawn a process without blocking (returns PID)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command>`,`Command to execute`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`).option(`--blocking`,`Wait for completion (default: false)`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=Si(r.env??[],`--env`,`env`),s=r.timeout?O(r.timeout,`--timeout`,`ms`,0):void 0,c=d(`Spawning: ${n}`);r.json||c.start();let l=await G(a,i,t);if(l=await K(l),r.blocking){let t=await l.exec(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e(t):(t.stdout&&globalThis.process.stdout.write(t.stdout),t.stderr&&globalThis.process.stderr.write(t.stderr),t.exitCode!==0&&globalThis.process.exit(t.exitCode))}else{let i=await l.process.spawn(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e({pid:i.pid,command:i.command}):(console.log(`Process started with PID: ${i.pid}`),console.log(`Use 'tangle process logs ${t} ${i.pid}' to view output`))}}),t.command(`list`).alias(`ls`).description(`List all processes in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--running`,`Show only running processes`).action(async(t,n)=>{let{context:i,client:a}=D(n),o=d(`Fetching processes...`);n.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.list();n.running&&(c=c.filter(e=>e.running)),o.stop(),n.json?e(c):c.length===0?console.log(`No processes found`):r([`PID`,`Command`,`Status`,`Exit Code`,`Started`],c.map(e=>[String(e.pid),e.command.length>40?`${e.command.slice(0,37)}...`:e.command,e.running?`running`:`exited`,String(e.exitCode),e.startedAt.toLocaleString()]))}),t.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching process info...`);r.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.get(Number.parseInt(n,10));if(o.stop(),!c){console.error(`Process ${n} not found`),globalThis.process.exit(1);return}let l=await c.status();r.json?e(l):(console.log(`PID: ${l.pid}`),console.log(`Command: ${l.command}`),console.log(`CWD: ${l.cwd||`(default)`}`),console.log(`Status: ${l.running?`running`:`exited`}`),console.log(`Exit Code: ${l.exitCode}`),l.exitSignal&&console.log(`Signal: ${l.exitSignal}`),console.log(`Started: ${l.startedAt.toLocaleString()}`),l.exitedAt&&console.log(`Exited: ${l.exitedAt.toLocaleString()}`))}),t.command(`kill`).description(`Kill a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`-s, --signal <signal>`,`Signal to send (SIGTERM, SIGKILL, etc.)`,`SIGTERM`).option(`--tree`,`Also kill descendants of the tracked process`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=d(`Sending ${r.signal} to PID ${n}...`);r.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.get(Number.parseInt(n,10));if(!c){o.stop(),console.error(`Process ${n} not found`),globalThis.process.exit(1);return}r.tree?await c.kill(r.signal,{tree:!0}):await c.kill(r.signal),o.stop(),r.json?e({pid:Number.parseInt(n,10),signal:r.signal,...r.tree===!0?{tree:!0}:{},killed:!0}):console.log(r.tree?`Sent ${r.signal} to process tree ${n}`:`Sent ${r.signal} to process ${n}`)}),t.command(`logs`).description(`Stream buffered and live process logs until the process exits`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`--stdout-only`,`Only show stdout`).option(`--stderr-only`,`Only show stderr`).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=await G(i,r,e);a=await K(a);let o=await a.process.get(Number.parseInt(t,10));if(!o){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}for await(let e of o.logs())n.stdoutOnly&&e.type!==`stdout`||n.stderrOnly&&e.type!==`stderr`||(n.json?console.log(JSON.stringify(e)):e.type===`stdout`?globalThis.process.stdout.write(e.data):globalThis.process.stderr.write(e.data))}),t}const bo=[`python`,`node`,`typescript`,`bash`];function xo(e){switch(Le(e).toLowerCase()){case`.py`:return`python`;case`.js`:case`.mjs`:case`.cjs`:return`node`;case`.ts`:case`.tsx`:return`typescript`;case`.sh`:case`.bash`:return`bash`;default:return}}async function So(e){if(e===`-`){let e=[];for await(let t of process.stdin)e.push(typeof t==`string`?Buffer.from(t):t);return Buffer.concat(e).toString(`utf8`)}return await ct(Re(e),`utf8`)}async function Co(e,t,n=So){let r=t?bo.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${bo.join(`, `)}`)})():void 0;if(!e||e===`-`){if(!r)throw Error(`reading from stdin requires --lang. Example: tangle run <id> -l python -`);return{language:r,source:await n(`-`)}}let i=xo(e);return{language:r??i??(()=>{throw Error(`cannot infer language from "${e}". Pass it explicitly: tangle run <id> -l <python|node|typescript|bash> ${e}`)})(),source:await n(e)}}function wo(e){return R(Xe(),`tangle-run-images`,e)}function To(){return new z(`run`).description(`Run code in a persistent kernel inside a sandbox. Variables persist across calls in the same --session.`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`[file]`,`Path to source file. Language is inferred from extension. Use - for stdin (requires --lang).`).option(`-l, --lang <lang>`,`Force language: ${bo.join(` | `)}. Required for stdin.`).option(`-s, --session <id>`,`Session id for kernel scoping`).option(`-t, --timeout <ms>`,`Per-call timeout in ms (0 disables)`,`60000`).option(`--save-images <dir>`,`Write image results into this directory (default: $TMPDIR/tangle-run-images/<sandbox>/).`).option(`--no-save-images`,`Don't write image results to disk; print summary only`).action(async(t,n,r)=>{let{language:i,source:a}=await Co(n,r.lang),o=O(r.timeout,`--timeout`,`ms`,0),{context:s,client:c}=D(r),l=await G(c,s,t);l=await K(l);let u=d(`Running ${i} (${a.length}b)…`);r.json||u.start();let f=await l.runCode(i,a,{sessionId:r.session,timeoutMs:o});if(u.stop(),r.json){e(f),f.exitCode!==0&&process.exit(f.exitCode);return}f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr);let p=0;for(let e of f.results)if(e.type===`image`)if(r.saveImages!==!1){let n=typeof r.saveImages==`string`?r.saveImages:wo(t);ye(n,{recursive:!0});let i=`${n}/${Date.now()}-${p}.${e.format}`;I(i,Buffer.from(e.data,`base64`)),process.stderr.write(L.green(`✓ image → ${i}\n`)),p++}else process.stderr.write(L.gray(`[image: ${e.format}, ${e.data.length}b base64]\n`));else if(e.type===`dataframe`){let t=e.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(L.gray(`[dataframe ${e.rows.length}×${e.columns.length}${e.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${t}\n`);for(let t of e.rows.slice(0,20))process.stderr.write(`${t.map(e=>String(e)).join(` | `)}\n`);e.rows.length>20&&process.stderr.write(L.gray(`… ${e.rows.length-20} more rows\n`))}else e.type===`json`?(process.stderr.write(L.gray(`[json] `)),process.stderr.write(`${JSON.stringify(e.value,null,2)}\n`)):e.type===`html`?process.stderr.write(L.gray(`[html ${e.value.length}b]\n`)):e.type===`error`?(process.stderr.write(L.red(`✗ ${e.name}: ${e.message}\n`)),e.traceback&&process.stderr.write(`${e.traceback}\n`)):e.type===`text`&&process.stderr.write(`${e.value}\n`);f.error&&(process.stderr.write(L.red(`\n✗ ${f.error.name}: ${f.error.message}\n`)),f.error.traceback&&process.stderr.write(`${f.error.traceback}\n`)),f.exitCode!==0&&process.exit(f.exitCode)})}const Eo=(e,t=[])=>[...t,e];function Do(e){throw new p(`USAGE_INVALID`,e,e,`tangle sandbox run --help`)}function Oo(e){if(!e.length)return;let t={};for(let n of e){let e=n.indexOf(`=`);e<=0&&Do(`--env takes NAME=VALUE, got ${n}`),t[n.slice(0,e)]=n.slice(e+1)}return t}function ko(e){return e.status===`timed_out`?124:e.status===`cancelled`?130:e.status===`lost`||e.status===`expired`?75:typeof e.exitCode==`number`?e.exitCode:1}const Ao=e=>e===void 0?`-`:`${(e/1e3).toFixed(1)} s`;function jo(e){let t=e.receipt,n=Object.entries(t.stagesMs).filter(([e])=>e!==`total`).map(([e,t])=>`${e} ${Ao(t)}`).join(`, `),r=[`job ${t.jobId}: ${t.status}${t.exitCode===null?``:`, exit ${t.exitCode}`} in ${Ao(t.stagesMs.total)}`,` ${t.source.kind===`git`?`${t.source.url} @ ${t.source.sha??t.source.ref}`:`archive ${t.source.archiveSha256?.slice(0,12)} @ ${t.source.sha??`-`}`}`,` sandbox ${t.sandboxId??`-`} (${t.capacityClass}${t.cell?`, cell ${t.cell}`:``}${t.runtime?`, ${t.runtime}`:``})${t.boxDeleted?`, deleted`:`, NOT CONFIRMED DELETED`}`,` stages: ${n}`,...t.cache?[` cache: ${t.cache.hit?`hit`:`miss`}${t.cache.saved?`, saved`:``} (${t.cache.keyFiles.join(`, `)})${t.cache.note?`: ${t.cache.note}`:``}`]:[],...t.cost?[` cost: $${t.cost.usd.toFixed(4)} (${t.cost.seconds} s at $${t.cost.ratePerHourUsd}/h)`]:[],...t.note?[` note: ${t.note}`]:[]];console.error(L.dim(r.join(`
148
- `)))}function Mo(t){t.command(`run`).description(`Run a repository at a commit (or an archive) with one command in a fresh sandbox, stream its output, and exit with its exit code`).usage(`(--repo <url> --ref <sha> | --archive <file.tgz>) [options] -- <command...>`).option(`--repo <url>`,`https repository URL the sandbox clones`).option(`--ref <ref>`,`commit SHA, branch or tag of --repo`).option(`--archive <file>`,`gzip tar of the working tree to run`).option(`--cache-key-file <file>`,`file whose content keys the cache (repeatable; default: the first lockfile found)`,Eo,[]).option(`--cache-scope <scope>`,`cache namespace within your account (default: the repository)`).option(`--no-cache`,`run without restoring or saving a cache`).option(`--capacity <class>`,`spare or standard (internal accounts default to spare)`).option(`--timeout <duration>`,`longest the command may run, like 30m (default 30m)`).option(`--cpu <cores>`,`CPU cores (default 2)`).option(`--memory <mb>`,`memory in MB (default 4096)`).option(`--disk <gb>`,`disk in GB`).option(`--runtime <runtime>`,`docker or firecracker`).option(`--environment <environment>`,`catalog environment or image`).option(`-e, --env <NAME=VALUE>`,`environment variable for the command (repeatable)`,Eo,[]).option(`--egress-strict`,`reach only package registries, source hosts and --allow-domain`).option(`--allow-domain <domain>`,`domain a strict job may reach (repeatable)`,Eo,[]).option(`--name <name>`,`a name for the job`).option(`--receipt <file>`,`write the job's receipt to this file as JSON`).option(`--json`,`print the end event as JSON on stdout; the command's output goes to stderr`).argument(`<command...>`,`command after --`).action(async(t,n)=>{n.json&&i(!0),!!n.archive==!!n.repo&&Do(`Name exactly one source: --repo <url> --ref <sha>, or --archive <file.tgz>`),n.repo&&!n.ref&&Do(`--repo needs --ref`);let{client:r}=D(n),a={source:n.archive?{archive:new Uint8Array(F(n.archive))}:{git:{url:n.repo,ref:n.ref}},command:t.length===1?t[0]:t,...n.timeout?{timeoutMs:O(n.timeout,`--timeout`,`ms`)}:{},...n.capacity?{capacity:[`spare`,`standard`].includes(n.capacity)?n.capacity:Do(`--capacity is spare or standard`)}:{},...n.runtime?{runtime:n.runtime}:{},...n.environment?{environment:n.environment}:{},...n.cpu||n.memory||n.disk?{resources:{...n.cpu?{cpuCores:k(n.cpu,`--cpu`)}:{},...n.memory?{memoryMB:k(n.memory,`--memory`)}:{},...n.disk?{diskGB:k(n.disk,`--disk`)}:{}}}:{},...Oo(n.env)?{env:Oo(n.env)}:{},...n.egressStrict?{egress:{mode:`strict`,allowDomains:n.allowDomain}}:{},cache:n.cache===!1?!1:{...n.cacheKeyFile.length?{keyFiles:n.cacheKeyFile}:{},...n.cacheScope?{scope:n.cacheScope}:{}},...n.name?{name:n.name}:{}},o=n.json?process.stderr:process.stdout,s=new AbortController,c=()=>s.abort();process.once(`SIGINT`,c),process.once(`SIGTERM`,c);let l=e=>{e.type===`log`?(e.data.stream===`stderr`?process.stderr:o).write(e.data.text):e.type===`stage`&&e.data.state===`finished`&&process.stderr.write(L.dim(`tangle: ${e.data.stage} ${Ao(e.data.ms)}\n`))},u;try{u=await r.jobs.run(a,{onEvent:l,onCreated:e=>process.stderr.write(L.dim(`tangle: job ${e.id} (${e.capacityClass})\n`)),signal:s.signal,cancelOnAbort:!0})}catch(e){throw s.signal.aborted&&process.exit(130),e instanceof De&&e.retryable&&(console.error(L.red(`${e.message} (${e.code}, retryable)`)),process.exit(75)),e}finally{process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,c)}n.receipt&&I(n.receipt,`${JSON.stringify(u.receipt,null,2)}\n`),n.json?e(u):jo(u),process.exit(ko(u))})}function No(){let e=new z(`sandbox`).description(`Manage sandboxes`);return ua(e),ea(e),Gi(e),la(e),Mo(e),e}function Po(){return new z(`search`).description(`Search for text patterns in sandbox files (ripgrep)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pattern>`,`Search pattern (regex)`).option(`-g, --glob <pattern>`,`File glob filter (e.g. '**/*.ts')`).option(`-n, --max-results <count>`,`Max results to return`).option(`-i, --ignore-case`,`Case-insensitive search`).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=d(`Searching...`);n.json||a.start();let o=await G(i,r,e),s=0,c=n.maxResults?Number.parseInt(n.maxResults,10):void 0,l={};n.glob&&(l.glob=n.glob),n.ignoreCase&&(l.ignoreCase=!0),c&&(l.maxResults=c);for await(let e of o.search(t,l))if(s===0&&a.stop(),s++,n.json?console.log(JSON.stringify(e)):console.log(`${e.path}:${e.line}:${e.column??0}: ${e.text}`),c&&s>=c)break;a.stop(),s===0&&!n.json&&console.log(`No matches found`)})}function Fo(){let t=new z(`secret`).description(`Manage secrets`);return t.command(`create`).description(`Create a new secret`).argument(`<name>`,`Secret name (e.g., HF_TOKEN, AWS_ACCESS_KEY)`).argument(`[value]`,`Secret value`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,r,i)=>{let a=await D(i).client.secrets.create(t,await Io({value:r,valueStdin:i.valueStdin,prompt:`Enter value for secret '${t}': `}));i.json?e(a):(n(`Secret created: ${a.name}`),c(`Use --secret ${a.name} when creating a sandbox to select it for delivery.`))}),t.command(`list`).description(`List all secrets`).action(async t=>{let n=await D(t).client.secrets.list();t.json?e(n):n.length===0?(c(`No secrets found.`),c(`Use 'tangle secret create <name> [value]' to create one.`)):r([`Name`,`Created At`,`Updated At`],n.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),t.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=D(r).client;if(!r.force&&!await N(`Are you sure you want to delete secret '${t}'? This cannot be undone. (y/N) `,`--force`)){c(`Cancelled.`);return}await i.secrets.delete(t),r.json?e({success:!0,deleted:t}):n(`Secret deleted: ${t}`)}),t}async function Io(e){if(e.value!==void 0&&e.valueStdin)throw Error(`Provide either a secret value argument or --value-stdin, not both`);let t=e.value??(e.valueStdin?await pe():await me(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function Lo(){let e=new z(`skill`).description(`Print paths to shipped skill documentation`);return e.command(`path`).description(`Print the absolute path to the SKILL.md shipped with this CLI`).action(()=>{let e=Pe.dirname(ft(import.meta.url)),t=Pe.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function Ro(){let r=new z(`snapshot`).description(`Manage snapshots`);return r.command(`create <sandbox-id-or-name>`).description(`Create a snapshot of a sandbox`).option(`--tags <tags...>`,`Tags for the snapshot`).option(`--no-wait`,`Return once the snapshot is accepted and print the operation to poll`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Creating snapshot...`);o.start();let s=await G(a,i,t);if(r.wait===!1){let e=await s.snapshot({tags:r.tags,wait:!1});o.stop(),Ki(e.info,!!r.json);return}let c=await s.snapshot({tags:r.tags});o.stop(),r.json?e(c):(n(`Snapshot created: ${c.snapshotId}`),console.log(`Size: ${Bo(c.sizeBytes)}`))}),r.command(`list [sandbox-id-or-name]`).description(`List snapshots for a sandbox; with no sandbox, the snapshots you own, including your most recently deleted sandboxes'`).option(`--include-platform`,`Also list platform captures (they do not count toward your limit)`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching snapshots...`);o.start();let s=n?await G(a,i,n):void 0;if(!s||s.status===`deleted`){let n=await a.listSnapshots({includePlatform:!!r.includePlatform,...s?{sandboxId:s.id}:{}});if(o.stop(),r.json)return e(n);t(n.snapshots.map(e=>({...e,sandbox:e.sandboxExists?e.sandboxId:`${e.sandboxId} (deleted)`,removeAfter:e.sandboxExists?`kept while it exists`:e.removeAfter?`${e.removeAfter.toISOString().slice(0,16).replace(`T`,` `)} UTC`:`not scheduled`,note:e.countsTowardLimit?``:`not counted toward your limit`})),[{key:`snapshotId`,header:`ID`,width:24},{key:`sandbox`,header:`Sandbox`,width:32},{key:`createdAt`,header:`Created`,width:16},{key:`removeAfter`,header:`Removed after`,width:24},{key:`note`,header:``,width:30}]);let i=n.olderNotListed;i&&console.log(`${i} more deleted sandbox${i===1?``:`es`} not shown here. List one with: tangle snapshot list <sandbox-id> (ids from \`tangle sandbox list --status deleted\`)`);let c=n.excluded.platform;c.count&&console.log(`${c.count} platform capture${c.count===1?``:`s`} (${Bo(c.bytes)}) hidden; --include-platform to list`),n.retryable&&console.log(`Some snapshots could not be listed right now. Try again.`);return}let c=await s.listSnapshots();o.stop(),r.json?e(c):zo(c)}),r.command(`restore <sandbox-id> <snapshot-id>`).description(`Create a new sandbox from a snapshot`).option(`--billing-owner <userId>`,`Platform user that pays for the restored sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).action(async(t,r,i)=>{let{client:a}=D(i),o=d(`Restoring from snapshot...`);o.start();let s=await a.create({fromSnapshot:r,fromSandboxId:t,...i.billingOwner?{billingOwnerId:i.billingOwner}:{}});await s.waitFor(`running`,{timeoutMs:12e4}),o.stop(),i.json?e({sandboxId:s.id,restoredFrom:r,status:s.status}):(n(`New sandbox created: ${s.id}`),console.log(`Source snapshot: ${r}`))}),r.command(`revert <sandbox-id-or-name> [snapshot-id]`).description(`Revert an existing sandbox to a snapshot`).option(`--latest`,`Revert to the sandbox's newest snapshot`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=V(t);if(r&&i.latest)throw new p(`USAGE_INVALID`,`Pass a snapshot id or --latest, not both`,`Both ${r} and --latest were given`,`tangle snapshot revert ${s} ${V(r)}`);let c=await G(o,a,t),l=r;if(!l){let e=[...await c.listSnapshots()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime()),n=e[0];if(!n)throw new p(`SNAPSHOT_NONE`,`${t} has no snapshot to revert to`,`A revert goes back to a snapshot taken earlier, and none was taken for this sandbox`,`tangle snapshot create ${s}`);if(!i.latest)throw i.json||(console.log(`Snapshots of ${t}, newest first:`),zo(e)),new p(`USAGE_INVALID`,`No snapshot id given`,`The newest is ${n.snapshotId}. Pass an id, or --latest for the newest`,`tangle snapshot revert ${s} --latest`);l=n.snapshotId}let u=d(`Reverting sandbox to snapshot...`);u.start();let f=await c.revertToSnapshot(l);await c.refresh(),u.stop(),i.json?e({sandboxId:c.id,snapshotId:f.snapshotId,status:c.status}):(n(`Sandbox reverted: ${c.id}`),console.log(`Source snapshot: ${f.snapshotId}`))}),r.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=d(`Deleting snapshot...`);s.start();let c=await(await G(o,a,t)).deleteSnapshot(r);s.stop(),i.json?e({success:!0,sandboxId:t,snapshotId:r,outcome:c.outcome,...c.reclaim?{reclaim:c.reclaim}:{}}):c.reclaim===`pending`?console.log(`Deletion accepted. Storage removal is pending for snapshot ${r}.`):c.reclaim===`complete`?n(`Storage removal confirmed for snapshot ${r}.`):c.outcome===`unknown`?console.log(`The service could not confirm deletion of snapshot ${r}.`):c.outcome===`already_absent`?n(`Snapshot already gone: ${r}`):n(`Snapshot deleted: ${r}`)}),r}function zo(e){t(e.map(e=>({...e,size:Bo(e.sizeBytes)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}function Bo(e){if(!e)return`pending`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**r).toFixed(1))} ${n[r]}`}const Vo=()=>import(`./device-CO9C7dED.mjs`);function Ho(){let e=new z(`solve`).description(`Participate in Tangle Solve competitions`);e.command(`clone <competition>`).description(`Clone the pinned competition repository`).argument(`[directory]`,`Destination directory`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t,n)=>(await import(`./clone-Cpmvw-S0.mjs`)).cloneCompetition(e,t,n)),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(async(e,t)=>(await import(`./run-D7CkQK0a.mjs`)).runCompetition(e,t)),e.command(`submit [competition]`).description(`Submit checker evidence through the device account and Tempo`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).option(`--pr-url <url>`,`GitHub pull request containing the submission`).option(`--model <name>`,`Model used to produce the submission`).option(`--note <text>`,`Short note shown with the accepted submission`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await import(`./submit-DWUYkfp2.mjs`)).submitCompetition(e,t)),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(async e=>(await import(`./account-CC7wRKa1.mjs`)).showSolveAccount(e));let t=e.command(`device`).description(`List and revoke the Solve devices bound to your account`);return t.command(`list`).description(`List your devices and whether each may submit jobs on Tempo`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async e=>(await Vo()).listSolveDevices(e)),t.command(`revoke <address>`).description(`Permanently revoke a device; the local device is revoked with its own key`).option(`--reason <text>`,`Why the device is revoked (shown to the account)`).option(`--yes`,`Confirm the permanent revocation without a prompt`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await Vo()).revokeSolveDevice(e,t)),e}function Uo(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function Wo(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function Go(e){return`'${e.replace(/'/g,`''`)}'`}function Ko(e){return e===`win32`?`NUL`:`/dev/null`}function qo(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${Go(`<token>`)}; ssh ${e.map(Go).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${Wo(`<token>`)} ssh ${e.map(Wo).join(` `)}`}function Jo(e){return e.connection!==void 0&&!e.connection.ssh}function Yo(){u(`SSH is not enabled for this sandbox.`),c(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function Xo(e,t=[],n=process.platform){let r=Ko(n);return[`-o`,`ProxyCommand=${e.proxyCommand}`,`-o`,`StrictHostKeyChecking=no`,`-o`,`UserKnownHostsFile=${r}`,`-o`,`GlobalKnownHostsFile=${r}`,`-o`,`LogLevel=ERROR`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=4`,`-o`,`TCPKeepAlive=yes`,`${e.username}@localhost`,`-p`,String(e.port),...t]}function Zo(e,t=process.platform){return{stdio:`inherit`,cwd:re(void 0,t),env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:e}}}function Qo(){return new z(`ssh`).description(`Open SSH session to a sandbox`).argument(`<ref>`,`Sandbox ID or name`).argument(`[sshArgs...]`,`Extra args passed through to ssh`).option(`-i, --identity-file <path>`,`Private key file to pass to ssh`).option(`--print`,`Print SSH command instead of connecting`).allowUnknownOption(!0).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=d(`Getting SSH credentials...`);a.start();let o=await G(i,r,e);if(Jo(o)){a.stop(),Yo();return}o=await K(o);let s=await o.ssh();if(a.stop(),!s){Yo();return}let l={...s,proxyCommand:Uo(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let p=Xo(l,[...n.identityFile?[`-i`,Re(n.identityFile),`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(qo(p,process.platform));return}c(`Connecting via tunnel...`);let m=Qe(`ssh`,p,Zo(r.apiKey));m.on(`error`,e=>{e.code===`ENOENT`&&(u(`SSH client not found. Please install OpenSSH.`),process.exit(1)),f(e)}),m.on(`exit`,e=>{process.exit(e??0)})})}function $o(){let t=new z(`ssh-keys`).description(`Manage SSH keys`);return t.command(`list`).description(`List SSH keys`).action(async t=>{let n=d(`Fetching SSH keys...`);try{n.start();let i=await E(x(t)).sshKeys.list();n.stop(),t.json?e({sshKeys:i}):i.length===0?c(`No SSH keys found.`):r([`Name`,`Type`,`Fingerprint`,`Created`],i.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){n.stop(),f(e)}}),t.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(t,r)=>{let i=d(`Adding SSH key...`);try{let a=F(r.keyFile,`utf8`).trim();i.start();let o=await E(x(r)).sshKeys.create(t,a);i.stop(),r.json?e({sshKey:o}):n(`Added SSH key ${o.name} (${o.fingerprint})`)}catch(e){i.stop(),f(e)}}),t.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let r=d(`Deleting SSH key...`);try{r.start(),await E(x(t)).sshKeys.delete(e),r.stop(),n(`Deleted SSH key ${e}`)}catch(e){r.stop(),f(e)}}),t}function es(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function ts(){return new z(`ssh-proxy`).description(`SSH proxy helper that pipes stdin/stdout to WebSocket`).argument(`<runtime-url>`,`Runtime WebSocket URL`).action(async e=>{let t=process.env.TANGLE_SSH_PROXY_AUTH_TOKEN;t||es(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new URL(e.replace(/^http/,`ws`)),{default:r}=await import(`ws`),i=new r(n,{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),a;function o(){a&&=(clearInterval(a),void 0)}i.on(`open`,()=>{a=setInterval(()=>{i.readyState===r.OPEN&&i.ping()},15e3),a.unref?.(),process.stdin.on(`data`,e=>{i.readyState===r.OPEN&&i.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>i.close(1e3))}),i.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),i.on(`error`,e=>{o(),es(`WebSocket error: ${e.message}`)}),i.on(`close`,e=>{o(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>i.close())})}function ns(){let r=new z(`team`).description(`Manage teams`);return Q(r,`list`).description(`List teams for the current account`).action(async n=>{let r=x(n),i=E(r),a=n.json?null:d(`Fetching teams...`);a?.start();let o=await i.teams.list();if(a?.stop(),n.json){e({teams:o,activeTeamId:r.activeTeamId??null});return}t(o.map(e=>({active:e.id===r.activeTeamId,id:e.id,name:e.name,role:e.currentUserRole,members:e.memberCount})),[{key:`active`,header:`Active`,width:8},{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:24},{key:`role`,header:`Role`,width:10},{key:`members`,header:`Members`,width:10}])}),Q(r,`create <name>`).description(`Create a team`).option(`--org-id <id>`,`External organization id`).option(`--no-switch`,`Do not set the new team as active`).action(async(t,r)=>{let i=x(r),a=E(i),o=r.json?null:d(`Creating team...`);o?.start();let s=await a.teams.create({name:t,orgId:r.orgId});if(r.switch&&Yi(s,i.profile),o?.stop(),r.json){e({team:s,active:!!r.switch});return}n(`Team created: ${qi(s)}`),r.switch&&n(`Active team set to ${s.name}`)}),Q(r,`switch <team>`).description(`Set the active team for the current profile`).action(async(t,r)=>{let i=x(r),a=await Ji(E(i),t);if(Yi(a,i.profile),r.json){e({team:a,activeTeamId:a.id});return}n(`Active team set to ${qi(a)}`)}),r.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{let n=te(t.profile);if(t.json){e(n.activeTeamId?n:{activeTeamId:null});return}if(!n.activeTeamId){console.log(`No active team.`);return}o({ID:n.activeTeamId,Name:n.activeTeamName})}),r.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{if(Xi(t.profile),t.json){e({activeTeamId:null});return}n(`Active team cleared.`)}),Q(r,`members [team]`).description(`List team members`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listMembers(o.id);if(r.json){e({team:o,members:s});return}t(s,[{key:`id`,header:`ID`,width:36},{key:`customerEmail`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:10},{key:`joinedAt`,header:`Joined`,width:16}])}),Q(r,`update-member <member-id>`).description(`Update a team member role`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).requiredOption(`--role <role>`,`Role: admin, member, viewer`).action(async(t,r)=>{let i=x(r),a=E(i),s=await Y(a,r.team,i.profile),c=rs(r.role),l=await a.teams.updateMember(s.id,t,{role:c});if(r.json){e({team:s,member:l});return}n(`Member updated: ${l.customerEmail}`),o({Team:s.name,Role:l.role,Status:l.status})}),Q(r,`invite <email>`).description(`Invite a user to a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--role <role>`,`Role: admin, member, viewer`,`member`).option(`--ttl-hours <hours>`,`Invitation lifetime in hours`).action(async(t,r)=>{let i=x(r),a=E(i),s=await Y(a,r.team,i.profile),c=rs(r.role),l=await a.teams.invite(s.id,{email:t,role:c,ttlHours:r.ttlHours?k(r.ttlHours,`--ttl-hours`):void 0});if(r.json){e({team:s,invitation:l});return}n(`Invitation created for ${l.email}`),o({Team:s.name,Role:l.role,Expires:l.expiresAt,"Invitation ID":l.id}),n(`Re-run with --json to retrieve the invitation token for sharing.`)}),Q(r,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,t,i.profile);if(!(!r.force&&!r.json&&!await N(`Leave team '${o.name}'? (y/N) `,`--force`))){if(await a.teams.leave(o.id),i.activeTeamId===o.id&&Xi(i.profile),r.json){e({success:!0,teamId:o.id});return}n(`Left team: ${o.name}`)}}),Q(r,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,r,a.profile);if(!(!i.force&&!i.json&&!await N(`Transfer ownership of '${s.name}' to ${t}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await o.teams.transferOwnership(s.id,t),i.json){e({success:!0,teamId:s.id,newOwnerCustomerId:t});return}n(`Ownership transferred for ${s.name}`)}}),r.addCommand(is()),r.addCommand(as()),Q(r,`invitations [team]`).description(`List pending and historical team invitations`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listInvitations(o.id);if(r.json){e({team:o,invitations:s});return}t(s,[{key:`id`,header:`ID`,width:38},{key:`email`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:12},{key:`expiresAt`,header:`Expires`,width:16}])}),Q(r,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(t,r)=>{let i=x(r),a=E(i),o=await a.teams.acceptInvitation(t),s=r.switch===!1?null:await a.teams.get(o.teamId);if(s&&Yi(s,i.profile),r.json){e({member:o,activeTeamId:s?.id??null});return}n(`Invitation accepted for team ${o.teamId}`),s&&n(`Active team set to ${s.name}`)}),Q(r,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(t,r)=>{if(await E(x(r)).teams.revokeInvitation(t),r.json){e({success:!0,invitationId:t});return}n(`Invitation revoked: ${t}`)}),Q(r,`remove-member <member-id>`).description(`Remove a member from a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(await a.teams.removeMember(o.id,t),r.json){e({success:!0,teamId:o.id,memberId:t});return}n(`Member removed: ${t}`)}),r}function rs(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function is(){let r=new z(`secret`).description(`Manage team secrets`);return Q(r,`list [team]`).description(`List team secret names`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listSecrets(o.id);if(r.json){e({team:o,secrets:s});return}t(s,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),Q(r,`set <name> [value]`).description(`Create or replace a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,i.team,a.profile),c=await Io({value:r,valueStdin:i.valueStdin,prompt:`Enter value for team secret '${t}': `}),l=await o.teams.upsertSecret(s.id,t,c);if(i.json){e({team:s,secret:l});return}n(`Team secret saved: ${l.name}`)}),Q(r,`delete <name>`).description(`Delete a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(!(!r.force&&!r.json&&!await N(`Delete team secret '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteSecret(o.id,t),r.json){e({success:!0,teamId:o.id,name:t});return}n(`Team secret deleted: ${t}`)}}),Q(r,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let r=x(n),i=E(r),a=await Y(i,n.team,r.profile),o=await i.teams.revealSecret(a.id,t);if(n.json){e({teamId:a.id,...o});return}console.log(o.value)}),r}function as(){let r=new z(`templates`).description(`Manage team golden-path templates`);return Q(r,`list [team]`).description(`List a team's golden-path templates`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listTemplates(o.id);if(r.json){e({team:o,templates:s});return}if(s.length===0){console.log(`No templates yet for ${o.name}.`);return}t(s.map(e=>({id:e.id,name:e.name,environment:e.environment,snapshot:`${e.snapshotId.slice(0,12)}…`,updated:e.updatedAt})),[{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:28},{key:`environment`,header:`Env`,width:14},{key:`snapshot`,header:`Snapshot`,width:16},{key:`updated`,header:`Updated`,width:24}])}),Q(r,`create <name> <snapshot-id>`).description(`Create a golden-path template from a snapshot`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`-d, --description <description>`,`Human-readable description shown in the dashboard`).option(`-e, --environment <environment>`,`Default environment to apply (defaults to 'universal')`).option(`--config <json>`,`Optional JSON config object merged into sandboxes created from this template`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,i.team,a.profile),c;if(i.config)try{let e=JSON.parse(i.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);c=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let l=await o.teams.createTemplate(s.id,{name:t,snapshotId:r,description:i.description,environment:i.environment,config:c});if(i.json){e({team:s,template:l});return}n(`Team template created: ${l.name} (${l.id})`)}),Q(r,`delete <template-id>`).description(`Delete a team golden-path template`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(!(!r.force&&!r.json&&!await N(`Delete template '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteTemplate(o.id,t),r.json){e({success:!0,teamId:o.id,templateId:t});return}n(`Team template deleted: ${t}`)}}),r}function Q(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function os(t,r,i){let a=new AbortController,o=()=>a.abort();try{let i=E(x({...t,timeout:void 0}));process.once(`SIGINT`,o),process.once(`SIGTERM`,o);let s=await r(i,{...t.timeout===void 0?{}:{timeoutMs:O(t.timeout,`--timeout`,`s`,1,Math.floor((2**53-1)/1e3))*1e3},resumeJobId:t.resumeJob,signal:a.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,o)});t.json?e(s):n(`template`in s?`Published template: ${s.template.slug}`:`Published template version: ${s.version.id}`)}catch(e){if(e instanceof Te&&e.status!==401&&e.job&&[`pending`,`scanning`,`ready`].includes(e.job.status)){let t=[`tangle`,`template`,...i,`--resume-job`,e.job.id].map(V).join(` `);Object.assign(e,{fix:{command:t}})}f(e,t.json)}}function ss(){let n=new z(`template`).description(`Manage published public templates`);return n.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async n=>{let r=E(x(n)),i=n.featured?await r.publicTemplates.featured():await r.publicTemplates.list({query:n.query,tag:n.tag});if(n.json){e({templates:i});return}t(i,[{key:`slug`,header:`Slug`,width:28},{key:`name`,header:`Name`,width:28},{key:`forkCount`,header:`Forks`,width:8},{key:`sandboxCount`,header:`Sandboxes`,width:12},{key:`updatedAt`,header:`Updated`,width:24}])}),n.command(`get <id-or-slug>`).action(async(t,n)=>{let r=await E(x(n)).publicTemplates.get(t);if(n.json){e({template:r});return}e(r)}),n.command(`versions <id-or-slug>`).action(async(n,r)=>{let i=await E(x(r)).publicTemplates.versions(n);if(r.json){e({versions:i});return}t(i.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`createdAt`,header:`Created`,width:24}])}),n.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--slug <slug>`,`Stable public slug`).option(`-d, --description <description>`,`Template description`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).option(`--team-id <id>`,`Publish under a team`).option(`--forked-from <id>`,`Fork source template id`).action((e,t,n,r)=>os(r,async(i,a)=>({template:await i.publicTemplates.publish({name:e,slug:r.slug,description:r.description,snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes,teamId:r.teamId,forkedFromTemplateId:r.forkedFrom},a)}),[`publish`,e,t,n])),n.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).action((e,t,n,r)=>os(r,async(i,a)=>({version:await i.publicTemplates.publishVersion(e,{snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes},a)}),[`publish-version`,e,t,n])),n}function cs(){let t=new z(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return t.command(`list`).description(`List trace summaries (one row per trace), newest first`).option(`--from <iso>`,`ISO-8601 lower bound on received time (inclusive)`).option(`--to <iso>`,`ISO-8601 upper bound on received time (inclusive)`).option(`--model <model>`,`Exact model match (any span carried this model)`).option(`--run <runId>`,`Exact run id match`).option(`--status <status>`,`ERROR | OK`).option(`-q, --query <text>`,`Substring over span name`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size (clamped server-side to [1, 200])`).action(async t=>{try{let n={from:t.from,to:t.to,model:t.model,runId:t.run,status:t.status===void 0?void 0:ys(t.status),q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:ws(t.limit)},r=us(t),i=t.json?null:d(`Fetching traces...`);i?.start();let a=await r.listTraces(n);if(i?.stop(),t.json)return e(a);ps(a.items),_s(a.nextCursor)}catch(e){fs(e,t)}}),t.command(`get <traceId>`).description(`Show one trace's spans. Streams NDJSON to stdout with --ndjson.`).option(`--ndjson`,`Stream the full span set as NDJSON to stdout`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Spans per page`).action(async(t,n)=>{try{let r=us(n);if(n.ndjson){await ds(r,t);return}let i=n.json?null:d(`Fetching trace spans...`);i?.start();let a=await r.getTraceSpans(t,{cursor:n.cursor,limit:n.limit===void 0?void 0:ws(n.limit)});if(i?.stop(),!n.cursor&&a.items.length===0)throw new p(`TRACE_NOT_FOUND`,`No spans for trace ${t}`,`A turn's spans arrive about a minute after it ends, and a key reads only its own account's traces`,`tangle traces list --limit 5`);if(n.json)return e(a);ms(a.items),a.truncated&&o({Spans:`${a.items.length} of ${a.total} (truncated)`}),_s(a.nextCursor)}catch(e){fs(e,n)}}),t.addCommand(ls()),t}function ls(){let t=new z(`runs`).description(`Read eval-runs pivoted off the trace surface`);return t.command(`list`).description(`List eval-runs, newest first`).option(`--status <status>`,`Run status filter`).option(`--gate <decision>`,`Promotion-gate decision filter`).option(`--label <key:value>`,`Match over the run's labels`).option(`--from <iso>`,`ISO-8601 lower bound on received time`).option(`--to <iso>`,`ISO-8601 upper bound on received time`).option(`-q, --query <text>`,`Substring over run dir`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size`).action(async t=>{try{let n={status:t.status===void 0?void 0:xs(t.status),gate:t.gate===void 0?void 0:Cs(t.gate),label:t.label,from:t.from,to:t.to,q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:ws(t.limit)},r=us(t),i=t.json?null:d(`Fetching runs...`);i?.start();let a=await r.listRuns(n);if(i?.stop(),t.json)return e(a);hs(a.items),_s(a.nextCursor)}catch(e){fs(e,t)}}),t.command(`get <runId>`).description(`Show a single eval-run`).action(async(t,n)=>{try{let r=us(n),i=n.json?null:d(`Fetching run...`);i?.start();let a=await r.getRun(t);if(i?.stop(),n.json)return e(a);gs(a)}catch(e){fs(e,n)}}),t}function us(e){let t=e.baseUrl||process.env.TANGLE_INTELLIGENCE_BASE_URL||void 0,n=S(`intelligence`,t,e.apiKey);if(!n)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return pt({apiKey:n,baseUrl:t})}async function ds(e,t){let n=(await e.exportTraceSpansNdjson(t)).getReader();try{for(;;){let{value:e,done:t}=await n.read();if(t)break;e&&process.stdout.write(Buffer.from(e))}}finally{n.releaseLock()}}function fs(e,t){return f(e,t.json===!0)}function ps(e){t(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:vs(e.costUsd)})),[{key:`traceId`,header:`Trace`,width:36},{key:`root`,header:`Root`,width:24},{key:`model`,header:`Model`,width:22},{key:`spans`,header:`Spans`,width:8},{key:`errors`,header:`Errors`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14},{key:`cost`,header:`Cost`,width:10}])}function ms(e){t(e.map(e=>({spanId:e.id,name:e.name,model:e.model??`-`,status:e.statusCode??`-`,cost:e.costUsd===null?`-`:`$${e.costUsd}`})),[{key:`spanId`,header:`Span`,width:40},{key:`name`,header:`Name`,width:28},{key:`model`,header:`Model`,width:22},{key:`status`,header:`Status`,width:10},{key:`cost`,header:`Cost`,width:12}])}function hs(e){t(e.map(e=>({runId:e.id,status:e.status,gate:e.gateDecision??`-`,cost:e.totalCostUsd===null?`-`:`$${e.totalCostUsd}`,receivedAt:e.receivedAt})),[{key:`runId`,header:`Run`,width:24},{key:`status`,header:`Status`,width:22},{key:`gate`,header:`Gate`,width:18},{key:`cost`,header:`Cost`,width:12},{key:`receivedAt`,header:`Received`,width:18}])}function gs(e){o({Run:e.id,Status:e.status,Gate:e.gateDecision??void 0,"Run Dir":e.runDir??void 0,Cost:e.totalCostUsd===null?void 0:`$${e.totalCostUsd}`,Duration:e.totalDurationMs===null?void 0:`${e.totalDurationMs}ms`,"Holdout Lift":e.holdoutLift??void 0,Received:e.receivedAt})}function _s(e){e&&o({"Next page":`--cursor ${e}`})}function vs(e){return e===null?`-`:`$${e.toFixed(4)}`}function ys(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const bs=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function xs(e){let t=bs.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${bs.join(`, `)}`)}const Ss=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function Cs(e){let t=Ss.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Ss.join(`, `)}`)}function ws(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}const Ts=`@tangle-network/sandbox-cli`,Es=`curl -fsSL https://sandbox.tangle.tools/install.sh | sh`,Ds=/^\d+\.\d+\.\d+$/,Os=()=>process.env.TANGLE_CLI_HOME||R(H(),`.local/share/tangle-cli`);function ks(e){let t=R(Os(),`versions`);if(P(t)&&e.startsWith(be(t)+ze))return`tangle update`;let n=R(Os(),`node_modules`,Ts);if(P(n)&&be(n)===e)return`tangle update`;if(e.endsWith(R(`lib`,`node_modules`,Ts)))return`npm install -g ${Ts}@latest`;if(e.includes(R(`pnpm`,`global`,``)))return`pnpm add -g ${Ts}@latest`;if(e.includes(`${ze}node_modules${ze}`))return``}const As=()=>`${process.env.TANGLE_NPM_REGISTRY??`https://registry.npmjs.org`}/${Ts.replace(`/`,`%2F`)}/latest`,js=`const fs = require("node:fs");
149
+ need to serve /.well-known/tangle-preview-readiness.`;function vo(){let t=new z(`preview`).description(`Manage sandbox preview links`);return go(t.command(`start`).description(`Start/reuse a managed development server and publish its ready preview`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).option(`--cwd <directory>`,`Project directory in the selected workspace`).option(`--session <session-id>`,`Select the agent's session workspace`).option(`--name <name>`,`App/service label`).addHelpText(`after`,_o)).action(async(t,r)=>{let i=await mo(t,r),a=await ho(`Starting managed preview...`,r.json,()=>lt(i,{cwd:r.cwd,sessionId:r.session,name:r.name}));r.json?e(a):(n(`Preview ready: ${a.url}`),console.log(`Preview ID: ${a.previewId}`))}),go(t.command(`list`).alias(`ls`).description(`List active preview links for a sandbox`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`)).action(async(t,n)=>{let i=await mo(t,n),a=await ho(`Fetching preview links...`,n.json,()=>i.previewLinks.list());n.json?e(a):a.length===0?console.log(`No preview links found`):r([`App`,`Preview ID`,`Port`,`URL`,`Status`],a.map(e=>[yo(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),go(t.command(`publish`).description(`Publish one existing HTTP service; never starts or replaces a process`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).requiredOption(`--port <port>`,`Existing service port`).option(`--name <name>`,`App/service label`).addHelpText(`after`,_o)).action(async(t,r)=>{if(!r.port||!/^\d+$/.test(r.port))throw Error(`An integer service port is required`);let i=await mo(t,r),a=await ho(`Publishing service...`,r.json,()=>ut(i,{port:Number(r.port),name:r.name}));r.json?e(a):n(`Preview ready: ${a.url}`)}),go(t.command(`create`).description(`Create a preview link for a port`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<port>`,`Port number to preview`)).action(async(t,r,i)=>{if(!/^\d+$/.test(r)||Number(r)<1||Number(r)>65535)throw Error(`Port must be an integer between 1 and 65535`);let a=await mo(t,i),o=await ho(`Creating preview for port ${r}...`,i.json,()=>a.previewLinks.create(Number(r)));i.json?e(o):(n(`Preview created: ${o.url}`),console.log(`Preview ID: ${o.previewId}`))}),go(t.command(`remove`).alias(`rm`).description(`Remove a preview link`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<preview-id>`,`Preview link ID (from 'preview list')`)).action(async(t,r,i)=>{let a=await mo(t,i);await ho(`Removing preview...`,i.json,()=>a.previewLinks.remove(r)),i.json?e({success:!0,previewId:r}):n(`Preview removed: ${r}`)}),t}function yo(e){let t=e?.app;if(!t||typeof t!=`object`)return``;let n=`name`in t?t.name:void 0,r=`cwd`in t?t.cwd:void 0;return typeof n==`string`?n:typeof r==`string`?r:``}function bo(){let t=new z(`process`).description(`Manage processes in a sandbox`);return t.command(`spawn`).description(`Spawn a process without blocking (returns PID)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command>`,`Command to execute`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`).option(`--blocking`,`Wait for completion (default: false)`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=Ci(r.env??[],`--env`,`env`),s=r.timeout?O(r.timeout,`--timeout`,`ms`,0):void 0,c=d(`Spawning: ${n}`);r.json||c.start();let l=await G(a,i,t);if(l=await K(l),r.blocking){let t=await l.exec(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e(t):(t.stdout&&globalThis.process.stdout.write(t.stdout),t.stderr&&globalThis.process.stderr.write(t.stderr),t.exitCode!==0&&globalThis.process.exit(t.exitCode))}else{let i=await l.process.spawn(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e({pid:i.pid,command:i.command}):(console.log(`Process started with PID: ${i.pid}`),console.log(`Use 'tangle process logs ${t} ${i.pid}' to view output`))}}),t.command(`list`).alias(`ls`).description(`List all processes in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--running`,`Show only running processes`).action(async(t,n)=>{let{context:i,client:a}=D(n),o=d(`Fetching processes...`);n.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.list();n.running&&(c=c.filter(e=>e.running)),o.stop(),n.json?e(c):c.length===0?console.log(`No processes found`):r([`PID`,`Command`,`Status`,`Exit Code`,`Started`],c.map(e=>[String(e.pid),e.command.length>40?`${e.command.slice(0,37)}...`:e.command,e.running?`running`:`exited`,String(e.exitCode),e.startedAt.toLocaleString()]))}),t.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching process info...`);r.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.get(Number.parseInt(n,10));if(o.stop(),!c){console.error(`Process ${n} not found`),globalThis.process.exit(1);return}let l=await c.status();r.json?e(l):(console.log(`PID: ${l.pid}`),console.log(`Command: ${l.command}`),console.log(`CWD: ${l.cwd||`(default)`}`),console.log(`Status: ${l.running?`running`:`exited`}`),console.log(`Exit Code: ${l.exitCode}`),l.exitSignal&&console.log(`Signal: ${l.exitSignal}`),console.log(`Started: ${l.startedAt.toLocaleString()}`),l.exitedAt&&console.log(`Exited: ${l.exitedAt.toLocaleString()}`))}),t.command(`kill`).description(`Kill a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`-s, --signal <signal>`,`Signal to send (SIGTERM, SIGKILL, etc.)`,`SIGTERM`).option(`--tree`,`Also kill descendants of the tracked process`).action(async(t,n,r)=>{let{context:i,client:a}=D(r),o=d(`Sending ${r.signal} to PID ${n}...`);r.json||o.start();let s=await G(a,i,t);s=await K(s);let c=await s.process.get(Number.parseInt(n,10));if(!c){o.stop(),console.error(`Process ${n} not found`),globalThis.process.exit(1);return}r.tree?await c.kill(r.signal,{tree:!0}):await c.kill(r.signal),o.stop(),r.json?e({pid:Number.parseInt(n,10),signal:r.signal,...r.tree===!0?{tree:!0}:{},killed:!0}):console.log(r.tree?`Sent ${r.signal} to process tree ${n}`:`Sent ${r.signal} to process ${n}`)}),t.command(`logs`).description(`Stream buffered and live process logs until the process exits`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`--stdout-only`,`Only show stdout`).option(`--stderr-only`,`Only show stderr`).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=await G(i,r,e);a=await K(a);let o=await a.process.get(Number.parseInt(t,10));if(!o){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}for await(let e of o.logs())n.stdoutOnly&&e.type!==`stdout`||n.stderrOnly&&e.type!==`stderr`||(n.json?console.log(JSON.stringify(e)):e.type===`stdout`?globalThis.process.stdout.write(e.data):globalThis.process.stderr.write(e.data))}),t}const xo=[`python`,`node`,`typescript`,`bash`];function So(e){switch(Le(e).toLowerCase()){case`.py`:return`python`;case`.js`:case`.mjs`:case`.cjs`:return`node`;case`.ts`:case`.tsx`:return`typescript`;case`.sh`:case`.bash`:return`bash`;default:return}}async function Co(e){if(e===`-`){let e=[];for await(let t of process.stdin)e.push(typeof t==`string`?Buffer.from(t):t);return Buffer.concat(e).toString(`utf8`)}return await ct(Re(e),`utf8`)}async function wo(e,t,n=Co){let r=t?xo.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${xo.join(`, `)}`)})():void 0;if(!e||e===`-`){if(!r)throw Error(`reading from stdin requires --lang. Example: tangle run <id> -l python -`);return{language:r,source:await n(`-`)}}let i=So(e);return{language:r??i??(()=>{throw Error(`cannot infer language from "${e}". Pass it explicitly: tangle run <id> -l <python|node|typescript|bash> ${e}`)})(),source:await n(e)}}function To(e){return R(Xe(),`tangle-run-images`,e)}function Eo(){return new z(`run`).description(`Run code in a persistent kernel inside a sandbox. Variables persist across calls in the same --session.`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`[file]`,`Path to source file. Language is inferred from extension. Use - for stdin (requires --lang).`).option(`-l, --lang <lang>`,`Force language: ${xo.join(` | `)}. Required for stdin.`).option(`-s, --session <id>`,`Session id for kernel scoping`).option(`-t, --timeout <ms>`,`Per-call timeout in ms (0 disables)`,`60000`).option(`--save-images <dir>`,`Write image results into this directory (default: $TMPDIR/tangle-run-images/<sandbox>/).`).option(`--no-save-images`,`Don't write image results to disk; print summary only`).action(async(t,n,r)=>{let{language:i,source:a}=await wo(n,r.lang),o=O(r.timeout,`--timeout`,`ms`,0),{context:s,client:c}=D(r),l=await G(c,s,t);l=await K(l);let u=d(`Running ${i} (${a.length}b)…`);r.json||u.start();let f=await l.runCode(i,a,{sessionId:r.session,timeoutMs:o});if(u.stop(),r.json){e(f),f.exitCode!==0&&process.exit(f.exitCode);return}f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr);let p=0;for(let e of f.results)if(e.type===`image`)if(r.saveImages!==!1){let n=typeof r.saveImages==`string`?r.saveImages:To(t);ye(n,{recursive:!0});let i=`${n}/${Date.now()}-${p}.${e.format}`;I(i,Buffer.from(e.data,`base64`)),process.stderr.write(L.green(`✓ image → ${i}\n`)),p++}else process.stderr.write(L.gray(`[image: ${e.format}, ${e.data.length}b base64]\n`));else if(e.type===`dataframe`){let t=e.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(L.gray(`[dataframe ${e.rows.length}×${e.columns.length}${e.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${t}\n`);for(let t of e.rows.slice(0,20))process.stderr.write(`${t.map(e=>String(e)).join(` | `)}\n`);e.rows.length>20&&process.stderr.write(L.gray(`… ${e.rows.length-20} more rows\n`))}else e.type===`json`?(process.stderr.write(L.gray(`[json] `)),process.stderr.write(`${JSON.stringify(e.value,null,2)}\n`)):e.type===`html`?process.stderr.write(L.gray(`[html ${e.value.length}b]\n`)):e.type===`error`?(process.stderr.write(L.red(`✗ ${e.name}: ${e.message}\n`)),e.traceback&&process.stderr.write(`${e.traceback}\n`)):e.type===`text`&&process.stderr.write(`${e.value}\n`);f.error&&(process.stderr.write(L.red(`\n✗ ${f.error.name}: ${f.error.message}\n`)),f.error.traceback&&process.stderr.write(`${f.error.traceback}\n`)),f.exitCode!==0&&process.exit(f.exitCode)})}const Do=(e,t=[])=>[...t,e];function Oo(e){throw new p(`USAGE_INVALID`,e,e,`tangle sandbox run --help`)}function ko(e){if(!e.length)return;let t={};for(let n of e){let e=n.indexOf(`=`);e<=0&&Oo(`--env takes NAME=VALUE, got ${n}`),t[n.slice(0,e)]=n.slice(e+1)}return t}function Ao(e){return e.status===`timed_out`?124:e.status===`cancelled`?130:e.status===`lost`||e.status===`expired`?75:typeof e.exitCode==`number`?e.exitCode:1}const jo=e=>e===void 0?`-`:`${(e/1e3).toFixed(1)} s`;function Mo(e){let t=e.receipt,n=Object.entries(t.stagesMs).filter(([e])=>e!==`total`).map(([e,t])=>`${e} ${jo(t)}`).join(`, `),r=[`job ${t.jobId}: ${t.status}${t.exitCode===null?``:`, exit ${t.exitCode}`} in ${jo(t.stagesMs.total)}`,` ${t.source.kind===`git`?`${t.source.url} @ ${t.source.sha??t.source.ref}`:`archive ${t.source.archiveSha256?.slice(0,12)} @ ${t.source.sha??`-`}`}`,` sandbox ${t.sandboxId??`-`} (${t.capacityClass}${t.cell?`, cell ${t.cell}`:``}${t.runtime?`, ${t.runtime}`:``})${t.boxDeleted?`, deleted`:`, NOT CONFIRMED DELETED`}`,` stages: ${n}`,...t.cache?[` cache: ${t.cache.hit?`hit`:`miss`}${t.cache.saved?`, saved`:``} (${t.cache.keyFiles.join(`, `)})${t.cache.note?`: ${t.cache.note}`:``}`]:[],...t.cost?[` cost: $${t.cost.usd.toFixed(4)} (${t.cost.seconds} s at $${t.cost.ratePerHourUsd}/h)`]:[],...t.note?[` note: ${t.note}`]:[]];console.error(L.dim(r.join(`
150
+ `)))}function No(t){t.command(`run`).description(`Run a repository at a commit (or an archive) with one command in a fresh sandbox, stream its output, and exit with its exit code`).usage(`(--repo <url> --ref <sha> | --archive <file.tgz>) [options] -- <command...>`).option(`--repo <url>`,`https repository URL the sandbox clones`).option(`--ref <ref>`,`commit SHA, branch or tag of --repo`).option(`--archive <file>`,`gzip tar of the working tree to run`).option(`--cache-key-file <file>`,`file whose content keys the cache (repeatable; default: the first lockfile found)`,Do,[]).option(`--cache-scope <scope>`,`cache namespace within your account (default: the repository)`).option(`--no-cache`,`run without restoring or saving a cache`).option(`--capacity <class>`,`spare or standard (internal accounts default to spare)`).option(`--timeout <duration>`,`longest the command may run, like 30m (default 30m)`).option(`--cpu <cores>`,`CPU cores (default 2)`).option(`--memory <mb>`,`memory in MB (default 4096)`).option(`--disk <gb>`,`disk in GB`).option(`--runtime <runtime>`,`docker or firecracker`).option(`--environment <environment>`,`catalog environment or image`).option(`-e, --env <NAME=VALUE>`,`environment variable for the command (repeatable)`,Do,[]).option(`--egress-strict`,`reach only package registries, source hosts and --allow-domain`).option(`--allow-domain <domain>`,`domain a strict job may reach (repeatable)`,Do,[]).option(`--name <name>`,`a name for the job`).option(`--receipt <file>`,`write the job's receipt to this file as JSON`).option(`--json`,`print the end event as JSON on stdout; the command's output goes to stderr`).argument(`<command...>`,`command after --`).action(async(t,n)=>{n.json&&i(!0),!!n.archive==!!n.repo&&Oo(`Name exactly one source: --repo <url> --ref <sha>, or --archive <file.tgz>`),n.repo&&!n.ref&&Oo(`--repo needs --ref`);let{client:r}=D(n),a={source:n.archive?{archive:new Uint8Array(F(n.archive))}:{git:{url:n.repo,ref:n.ref}},command:t.length===1?t[0]:t,...n.timeout?{timeoutMs:O(n.timeout,`--timeout`,`ms`)}:{},...n.capacity?{capacity:[`spare`,`standard`].includes(n.capacity)?n.capacity:Oo(`--capacity is spare or standard`)}:{},...n.runtime?{runtime:n.runtime}:{},...n.environment?{environment:n.environment}:{},...n.cpu||n.memory||n.disk?{resources:{...n.cpu?{cpuCores:k(n.cpu,`--cpu`)}:{},...n.memory?{memoryMB:k(n.memory,`--memory`)}:{},...n.disk?{diskGB:k(n.disk,`--disk`)}:{}}}:{},...ko(n.env)?{env:ko(n.env)}:{},...n.egressStrict?{egress:{mode:`strict`,allowDomains:n.allowDomain}}:{},cache:n.cache===!1?!1:{...n.cacheKeyFile.length?{keyFiles:n.cacheKeyFile}:{},...n.cacheScope?{scope:n.cacheScope}:{}},...n.name?{name:n.name}:{}},o=n.json?process.stderr:process.stdout,s=new AbortController,c=()=>s.abort();process.once(`SIGINT`,c),process.once(`SIGTERM`,c);let l=e=>{e.type===`log`?(e.data.stream===`stderr`?process.stderr:o).write(e.data.text):e.type===`stage`&&e.data.state===`finished`&&process.stderr.write(L.dim(`tangle: ${e.data.stage} ${jo(e.data.ms)}\n`))},u;try{u=await r.jobs.run(a,{onEvent:l,onCreated:e=>process.stderr.write(L.dim(`tangle: job ${e.id} (${e.capacityClass})\n`)),signal:s.signal,cancelOnAbort:!0})}catch(e){throw s.signal.aborted&&process.exit(130),e instanceof De&&e.retryable&&(console.error(L.red(`${e.message} (${e.code}, retryable)`)),process.exit(75)),e}finally{process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,c)}n.receipt&&I(n.receipt,`${JSON.stringify(u.receipt,null,2)}\n`),n.json?e(u):Mo(u),process.exit(Ao(u))})}function Po(){let e=new z(`sandbox`).description(`Manage sandboxes`);return da(e),ta(e),Ki(e),ua(e),No(e),e}function Fo(){return new z(`search`).description(`Search for text patterns in sandbox files (ripgrep)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pattern>`,`Search pattern (regex)`).option(`-g, --glob <pattern>`,`File glob filter (e.g. '**/*.ts')`).option(`-n, --max-results <count>`,`Max results to return`).option(`-i, --ignore-case`,`Case-insensitive search`).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=d(`Searching...`);n.json||a.start();let o=await G(i,r,e),s=0,c=n.maxResults?Number.parseInt(n.maxResults,10):void 0,l={};n.glob&&(l.glob=n.glob),n.ignoreCase&&(l.ignoreCase=!0),c&&(l.maxResults=c);for await(let e of o.search(t,l))if(s===0&&a.stop(),s++,n.json?console.log(JSON.stringify(e)):console.log(`${e.path}:${e.line}:${e.column??0}: ${e.text}`),c&&s>=c)break;a.stop(),s===0&&!n.json&&console.log(`No matches found`)})}function Io(){let t=new z(`secret`).description(`Manage secrets`);return t.command(`create`).description(`Create a new secret`).argument(`<name>`,`Secret name (e.g., HF_TOKEN, AWS_ACCESS_KEY)`).argument(`[value]`,`Secret value`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,r,i)=>{let a=await D(i).client.secrets.create(t,await Lo({value:r,valueStdin:i.valueStdin,prompt:`Enter value for secret '${t}': `}));i.json?e(a):(n(`Secret created: ${a.name}`),c(`Use --secret ${a.name} when creating a sandbox to select it for delivery.`))}),t.command(`list`).description(`List all secrets`).action(async t=>{let n=await D(t).client.secrets.list();t.json?e(n):n.length===0?(c(`No secrets found.`),c(`Use 'tangle secret create <name> [value]' to create one.`)):r([`Name`,`Created At`,`Updated At`],n.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),t.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=D(r).client;if(!r.force&&!await N(`Are you sure you want to delete secret '${t}'? This cannot be undone. (y/N) `,`--force`)){c(`Cancelled.`);return}await i.secrets.delete(t),r.json?e({success:!0,deleted:t}):n(`Secret deleted: ${t}`)}),t}async function Lo(e){if(e.value!==void 0&&e.valueStdin)throw Error(`Provide either a secret value argument or --value-stdin, not both`);let t=e.value??(e.valueStdin?await pe():await me(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function Ro(){let e=new z(`skill`).description(`Print paths to shipped skill documentation`);return e.command(`path`).description(`Print the absolute path to the SKILL.md shipped with this CLI`).action(()=>{let e=Pe.dirname(ft(import.meta.url)),t=Pe.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function zo(){let r=new z(`snapshot`).description(`Manage snapshots`);return r.command(`create <sandbox-id-or-name>`).description(`Create a snapshot of a sandbox`).option(`--tags <tags...>`,`Tags for the snapshot`).option(`--no-wait`,`Return once the snapshot is accepted and print the operation to poll`).action(async(t,r)=>{let{context:i,client:a}=D(r),o=d(`Creating snapshot...`);o.start();let s=await G(a,i,t);if(r.wait===!1){let e=await s.snapshot({tags:r.tags,wait:!1});o.stop(),qi(e.info,!!r.json);return}let c=await s.snapshot({tags:r.tags});o.stop(),r.json?e(c):(n(`Snapshot created: ${c.snapshotId}`),console.log(`Size: ${Vo(c.sizeBytes)}`))}),r.command(`list [sandbox-id-or-name]`).description(`List snapshots for a sandbox; with no sandbox, the snapshots you own, including your most recently deleted sandboxes'`).option(`--include-platform`,`Also list platform captures (they do not count toward your limit)`).action(async(n,r)=>{let{context:i,client:a}=D(r),o=d(`Fetching snapshots...`);o.start();let s=n?await G(a,i,n):void 0;if(!s||s.status===`deleted`){let n=await a.listSnapshots({includePlatform:!!r.includePlatform,...s?{sandboxId:s.id}:{}});if(o.stop(),r.json)return e(n);t(n.snapshots.map(e=>({...e,sandbox:e.sandboxExists?e.sandboxId:`${e.sandboxId} (deleted)`,removeAfter:e.sandboxExists?`kept while it exists`:e.removeAfter?`${e.removeAfter.toISOString().slice(0,16).replace(`T`,` `)} UTC`:`not scheduled`,note:e.countsTowardLimit?``:`not counted toward your limit`})),[{key:`snapshotId`,header:`ID`,width:24},{key:`sandbox`,header:`Sandbox`,width:32},{key:`createdAt`,header:`Created`,width:16},{key:`removeAfter`,header:`Removed after`,width:24},{key:`note`,header:``,width:30}]);let i=n.olderNotListed;i&&console.log(`${i} more deleted sandbox${i===1?``:`es`} not shown here. List one with: tangle snapshot list <sandbox-id> (ids from \`tangle sandbox list --status deleted\`)`);let c=n.excluded.platform;c.count&&console.log(`${c.count} platform capture${c.count===1?``:`s`} (${Vo(c.bytes)}) hidden; --include-platform to list`),n.retryable&&console.log(`Some snapshots could not be listed right now. Try again.`);return}let c=await s.listSnapshots();o.stop(),r.json?e(c):Bo(c)}),r.command(`restore <sandbox-id> <snapshot-id>`).description(`Create a new sandbox from a snapshot`).option(`--billing-owner <userId>`,`Platform user that pays for the restored sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).action(async(t,r,i)=>{let{client:a}=D(i),o=d(`Restoring from snapshot...`);o.start();let s=await a.create({fromSnapshot:r,fromSandboxId:t,...i.billingOwner?{billingOwnerId:i.billingOwner}:{}});await s.waitFor(`running`,{timeoutMs:12e4}),o.stop(),i.json?e({sandboxId:s.id,restoredFrom:r,status:s.status}):(n(`New sandbox created: ${s.id}`),console.log(`Source snapshot: ${r}`))}),r.command(`revert <sandbox-id-or-name> [snapshot-id]`).description(`Revert an existing sandbox to a snapshot`).option(`--latest`,`Revert to the sandbox's newest snapshot`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=V(t);if(r&&i.latest)throw new p(`USAGE_INVALID`,`Pass a snapshot id or --latest, not both`,`Both ${r} and --latest were given`,`tangle snapshot revert ${s} ${V(r)}`);let c=await G(o,a,t),l=r;if(!l){let e=[...await c.listSnapshots()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime()),n=e[0];if(!n)throw new p(`SNAPSHOT_NONE`,`${t} has no snapshot to revert to`,`A revert goes back to a snapshot taken earlier, and none was taken for this sandbox`,`tangle snapshot create ${s}`);if(!i.latest)throw i.json||(console.log(`Snapshots of ${t}, newest first:`),Bo(e)),new p(`USAGE_INVALID`,`No snapshot id given`,`The newest is ${n.snapshotId}. Pass an id, or --latest for the newest`,`tangle snapshot revert ${s} --latest`);l=n.snapshotId}let u=d(`Reverting sandbox to snapshot...`);u.start();let f=await c.revertToSnapshot(l);await c.refresh(),u.stop(),i.json?e({sandboxId:c.id,snapshotId:f.snapshotId,status:c.status}):(n(`Sandbox reverted: ${c.id}`),console.log(`Source snapshot: ${f.snapshotId}`))}),r.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(t,r,i)=>{let{context:a,client:o}=D(i),s=d(`Deleting snapshot...`);s.start();let c=await(await G(o,a,t)).deleteSnapshot(r);s.stop(),i.json?e({success:!0,sandboxId:t,snapshotId:r,outcome:c.outcome,...c.reclaim?{reclaim:c.reclaim}:{}}):c.reclaim===`pending`?console.log(`Deletion accepted. Storage removal is pending for snapshot ${r}.`):c.reclaim===`complete`?n(`Storage removal confirmed for snapshot ${r}.`):c.outcome===`unknown`?console.log(`The service could not confirm deletion of snapshot ${r}.`):c.outcome===`already_absent`?n(`Snapshot already gone: ${r}`):n(`Snapshot deleted: ${r}`)}),r}function Bo(e){t(e.map(e=>({...e,size:Vo(e.sizeBytes)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}function Vo(e){if(!e)return`pending`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**r).toFixed(1))} ${n[r]}`}const Ho=()=>import(`./device-CO9C7dED.mjs`);function Uo(){let e=new z(`solve`).description(`Participate in Tangle Solve competitions`);e.command(`clone <competition>`).description(`Clone the pinned competition repository`).argument(`[directory]`,`Destination directory`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t,n)=>(await import(`./clone-Cpmvw-S0.mjs`)).cloneCompetition(e,t,n)),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(async(e,t)=>(await import(`./run-D7CkQK0a.mjs`)).runCompetition(e,t)),e.command(`submit [competition]`).description(`Submit checker evidence through the device account and Tempo`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).option(`--pr-url <url>`,`GitHub pull request containing the submission`).option(`--model <name>`,`Model used to produce the submission`).option(`--note <text>`,`Short note shown with the accepted submission`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await import(`./submit-DWUYkfp2.mjs`)).submitCompetition(e,t)),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(async e=>(await import(`./account-CC7wRKa1.mjs`)).showSolveAccount(e));let t=e.command(`device`).description(`List and revoke the Solve devices bound to your account`);return t.command(`list`).description(`List your devices and whether each may submit jobs on Tempo`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async e=>(await Ho()).listSolveDevices(e)),t.command(`revoke <address>`).description(`Permanently revoke a device; the local device is revoked with its own key`).option(`--reason <text>`,`Why the device is revoked (shown to the account)`).option(`--yes`,`Confirm the permanent revocation without a prompt`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await Ho()).revokeSolveDevice(e,t)),e}function Wo(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function Go(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function Ko(e){return`'${e.replace(/'/g,`''`)}'`}function qo(e){return e===`win32`?`NUL`:`/dev/null`}function Jo(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${Ko(`<token>`)}; ssh ${e.map(Ko).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${Go(`<token>`)} ssh ${e.map(Go).join(` `)}`}function Yo(e){return e.connection!==void 0&&!e.connection.ssh}function Xo(){u(`SSH is not enabled for this sandbox.`),c(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function Zo(e,t=[],n=process.platform){let r=qo(n);return[`-o`,`ProxyCommand=${e.proxyCommand}`,`-o`,`StrictHostKeyChecking=no`,`-o`,`UserKnownHostsFile=${r}`,`-o`,`GlobalKnownHostsFile=${r}`,`-o`,`LogLevel=ERROR`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=4`,`-o`,`TCPKeepAlive=yes`,`${e.username}@localhost`,`-p`,String(e.port),...t]}function Qo(e,t=process.platform){return{stdio:`inherit`,cwd:re(void 0,t),env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:e}}}function $o(){return new z(`ssh`).description(`Open SSH session to a sandbox`).argument(`<ref>`,`Sandbox ID or name`).argument(`[sshArgs...]`,`Extra args passed through to ssh`).option(`-i, --identity-file <path>`,`Private key file to pass to ssh`).option(`--print`,`Print SSH command instead of connecting`).allowUnknownOption(!0).action(async(e,t,n)=>{let{context:r,client:i}=D(n),a=d(`Getting SSH credentials...`);a.start();let o=await G(i,r,e);if(Yo(o)){a.stop(),Xo();return}o=await K(o);let s=await o.ssh();if(a.stop(),!s){Xo();return}let l={...s,proxyCommand:Wo(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let p=Zo(l,[...n.identityFile?[`-i`,Re(n.identityFile),`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(Jo(p,process.platform));return}c(`Connecting via tunnel...`);let m=Qe(`ssh`,p,Qo(r.apiKey));m.on(`error`,e=>{e.code===`ENOENT`&&(u(`SSH client not found. Please install OpenSSH.`),process.exit(1)),f(e)}),m.on(`exit`,e=>{process.exit(e??0)})})}function es(){let t=new z(`ssh-keys`).description(`Manage SSH keys`);return t.command(`list`).description(`List SSH keys`).action(async t=>{let n=d(`Fetching SSH keys...`);try{n.start();let i=await E(x(t)).sshKeys.list();n.stop(),t.json?e({sshKeys:i}):i.length===0?c(`No SSH keys found.`):r([`Name`,`Type`,`Fingerprint`,`Created`],i.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){n.stop(),f(e)}}),t.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(t,r)=>{let i=d(`Adding SSH key...`);try{let a=F(r.keyFile,`utf8`).trim();i.start();let o=await E(x(r)).sshKeys.create(t,a);i.stop(),r.json?e({sshKey:o}):n(`Added SSH key ${o.name} (${o.fingerprint})`)}catch(e){i.stop(),f(e)}}),t.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let r=d(`Deleting SSH key...`);try{r.start(),await E(x(t)).sshKeys.delete(e),r.stop(),n(`Deleted SSH key ${e}`)}catch(e){r.stop(),f(e)}}),t}function ts(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function ns(){return new z(`ssh-proxy`).description(`SSH proxy helper that pipes stdin/stdout to WebSocket`).argument(`<runtime-url>`,`Runtime WebSocket URL`).action(async e=>{let t=process.env.TANGLE_SSH_PROXY_AUTH_TOKEN;t||ts(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new URL(e.replace(/^http/,`ws`)),{default:r}=await import(`ws`),i=new r(n,{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),a;function o(){a&&=(clearInterval(a),void 0)}i.on(`open`,()=>{a=setInterval(()=>{i.readyState===r.OPEN&&i.ping()},15e3),a.unref?.(),process.stdin.on(`data`,e=>{i.readyState===r.OPEN&&i.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>i.close(1e3))}),i.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),i.on(`error`,e=>{o(),ts(`WebSocket error: ${e.message}`)}),i.on(`close`,e=>{o(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>i.close())})}function rs(){let r=new z(`team`).description(`Manage teams`);return Q(r,`list`).description(`List teams for the current account`).action(async n=>{let r=x(n),i=E(r),a=n.json?null:d(`Fetching teams...`);a?.start();let o=await i.teams.list();if(a?.stop(),n.json){e({teams:o,activeTeamId:r.activeTeamId??null});return}t(o.map(e=>({active:e.id===r.activeTeamId,id:e.id,name:e.name,role:e.currentUserRole,members:e.memberCount})),[{key:`active`,header:`Active`,width:8},{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:24},{key:`role`,header:`Role`,width:10},{key:`members`,header:`Members`,width:10}])}),Q(r,`create <name>`).description(`Create a team`).option(`--org-id <id>`,`External organization id`).option(`--no-switch`,`Do not set the new team as active`).action(async(t,r)=>{let i=x(r),a=E(i),o=r.json?null:d(`Creating team...`);o?.start();let s=await a.teams.create({name:t,orgId:r.orgId});if(r.switch&&Xi(s,i.profile),o?.stop(),r.json){e({team:s,active:!!r.switch});return}n(`Team created: ${Ji(s)}`),r.switch&&n(`Active team set to ${s.name}`)}),Q(r,`switch <team>`).description(`Set the active team for the current profile`).action(async(t,r)=>{let i=x(r),a=await Yi(E(i),t);if(Xi(a,i.profile),r.json){e({team:a,activeTeamId:a.id});return}n(`Active team set to ${Ji(a)}`)}),r.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{let n=te(t.profile);if(t.json){e(n.activeTeamId?n:{activeTeamId:null});return}if(!n.activeTeamId){console.log(`No active team.`);return}o({ID:n.activeTeamId,Name:n.activeTeamName})}),r.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{if(Zi(t.profile),t.json){e({activeTeamId:null});return}n(`Active team cleared.`)}),Q(r,`members [team]`).description(`List team members`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listMembers(o.id);if(r.json){e({team:o,members:s});return}t(s,[{key:`id`,header:`ID`,width:36},{key:`customerEmail`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:10},{key:`joinedAt`,header:`Joined`,width:16}])}),Q(r,`update-member <member-id>`).description(`Update a team member role`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).requiredOption(`--role <role>`,`Role: admin, member, viewer`).action(async(t,r)=>{let i=x(r),a=E(i),s=await Y(a,r.team,i.profile),c=is(r.role),l=await a.teams.updateMember(s.id,t,{role:c});if(r.json){e({team:s,member:l});return}n(`Member updated: ${l.customerEmail}`),o({Team:s.name,Role:l.role,Status:l.status})}),Q(r,`invite <email>`).description(`Invite a user to a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--role <role>`,`Role: admin, member, viewer`,`member`).option(`--ttl-hours <hours>`,`Invitation lifetime in hours`).action(async(t,r)=>{let i=x(r),a=E(i),s=await Y(a,r.team,i.profile),c=is(r.role),l=await a.teams.invite(s.id,{email:t,role:c,ttlHours:r.ttlHours?k(r.ttlHours,`--ttl-hours`):void 0});if(r.json){e({team:s,invitation:l});return}n(`Invitation created for ${l.email}`),o({Team:s.name,Role:l.role,Expires:l.expiresAt,"Invitation ID":l.id}),n(`Re-run with --json to retrieve the invitation token for sharing.`)}),Q(r,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,t,i.profile);if(!(!r.force&&!r.json&&!await N(`Leave team '${o.name}'? (y/N) `,`--force`))){if(await a.teams.leave(o.id),i.activeTeamId===o.id&&Zi(i.profile),r.json){e({success:!0,teamId:o.id});return}n(`Left team: ${o.name}`)}}),Q(r,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,r,a.profile);if(!(!i.force&&!i.json&&!await N(`Transfer ownership of '${s.name}' to ${t}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await o.teams.transferOwnership(s.id,t),i.json){e({success:!0,teamId:s.id,newOwnerCustomerId:t});return}n(`Ownership transferred for ${s.name}`)}}),r.addCommand(as()),r.addCommand(os()),Q(r,`invitations [team]`).description(`List pending and historical team invitations`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listInvitations(o.id);if(r.json){e({team:o,invitations:s});return}t(s,[{key:`id`,header:`ID`,width:38},{key:`email`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:12},{key:`expiresAt`,header:`Expires`,width:16}])}),Q(r,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(t,r)=>{let i=x(r),a=E(i),o=await a.teams.acceptInvitation(t),s=r.switch===!1?null:await a.teams.get(o.teamId);if(s&&Xi(s,i.profile),r.json){e({member:o,activeTeamId:s?.id??null});return}n(`Invitation accepted for team ${o.teamId}`),s&&n(`Active team set to ${s.name}`)}),Q(r,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(t,r)=>{if(await E(x(r)).teams.revokeInvitation(t),r.json){e({success:!0,invitationId:t});return}n(`Invitation revoked: ${t}`)}),Q(r,`remove-member <member-id>`).description(`Remove a member from a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(await a.teams.removeMember(o.id,t),r.json){e({success:!0,teamId:o.id,memberId:t});return}n(`Member removed: ${t}`)}),r}function is(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function as(){let r=new z(`secret`).description(`Manage team secrets`);return Q(r,`list [team]`).description(`List team secret names`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listSecrets(o.id);if(r.json){e({team:o,secrets:s});return}t(s,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),Q(r,`set <name> [value]`).description(`Create or replace a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,i.team,a.profile),c=await Lo({value:r,valueStdin:i.valueStdin,prompt:`Enter value for team secret '${t}': `}),l=await o.teams.upsertSecret(s.id,t,c);if(i.json){e({team:s,secret:l});return}n(`Team secret saved: ${l.name}`)}),Q(r,`delete <name>`).description(`Delete a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(!(!r.force&&!r.json&&!await N(`Delete team secret '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteSecret(o.id,t),r.json){e({success:!0,teamId:o.id,name:t});return}n(`Team secret deleted: ${t}`)}}),Q(r,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let r=x(n),i=E(r),a=await Y(i,n.team,r.profile),o=await i.teams.revealSecret(a.id,t);if(n.json){e({teamId:a.id,...o});return}console.log(o.value)}),r}function os(){let r=new z(`templates`).description(`Manage team golden-path templates`);return Q(r,`list [team]`).description(`List a team's golden-path templates`).action(async(n,r)=>{let i=x(r),a=E(i),o=await Y(a,n,i.profile),s=await a.teams.listTemplates(o.id);if(r.json){e({team:o,templates:s});return}if(s.length===0){console.log(`No templates yet for ${o.name}.`);return}t(s.map(e=>({id:e.id,name:e.name,environment:e.environment,snapshot:`${e.snapshotId.slice(0,12)}…`,updated:e.updatedAt})),[{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:28},{key:`environment`,header:`Env`,width:14},{key:`snapshot`,header:`Snapshot`,width:16},{key:`updated`,header:`Updated`,width:24}])}),Q(r,`create <name> <snapshot-id>`).description(`Create a golden-path template from a snapshot`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`-d, --description <description>`,`Human-readable description shown in the dashboard`).option(`-e, --environment <environment>`,`Default environment to apply (defaults to 'universal')`).option(`--config <json>`,`Optional JSON config object merged into sandboxes created from this template`).action(async(t,r,i)=>{let a=x(i),o=E(a),s=await Y(o,i.team,a.profile),c;if(i.config)try{let e=JSON.parse(i.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);c=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let l=await o.teams.createTemplate(s.id,{name:t,snapshotId:r,description:i.description,environment:i.environment,config:c});if(i.json){e({team:s,template:l});return}n(`Team template created: ${l.name} (${l.id})`)}),Q(r,`delete <template-id>`).description(`Delete a team golden-path template`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,r)=>{let i=x(r),a=E(i),o=await Y(a,r.team,i.profile);if(!(!r.force&&!r.json&&!await N(`Delete template '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteTemplate(o.id,t),r.json){e({success:!0,teamId:o.id,templateId:t});return}n(`Team template deleted: ${t}`)}}),r}function Q(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function ss(t,r,i){let a=new AbortController,o=()=>a.abort();try{let i=E(x({...t,timeout:void 0}));process.once(`SIGINT`,o),process.once(`SIGTERM`,o);let s=await r(i,{...t.timeout===void 0?{}:{timeoutMs:O(t.timeout,`--timeout`,`s`,1,Math.floor((2**53-1)/1e3))*1e3},resumeJobId:t.resumeJob,signal:a.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,o)});t.json?e(s):n(`template`in s?`Published template: ${s.template.slug}`:`Published template version: ${s.version.id}`)}catch(e){if(e instanceof Te&&e.status!==401&&e.job&&[`pending`,`scanning`,`ready`].includes(e.job.status)){let t=[`tangle`,`template`,...i,`--resume-job`,e.job.id].map(V).join(` `);Object.assign(e,{fix:{command:t}})}f(e,t.json)}}function cs(){let n=new z(`template`).description(`Manage published public templates`);return n.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async n=>{let r=E(x(n)),i=n.featured?await r.publicTemplates.featured():await r.publicTemplates.list({query:n.query,tag:n.tag});if(n.json){e({templates:i});return}t(i,[{key:`slug`,header:`Slug`,width:28},{key:`name`,header:`Name`,width:28},{key:`forkCount`,header:`Forks`,width:8},{key:`sandboxCount`,header:`Sandboxes`,width:12},{key:`updatedAt`,header:`Updated`,width:24}])}),n.command(`get <id-or-slug>`).action(async(t,n)=>{let r=await E(x(n)).publicTemplates.get(t);if(n.json){e({template:r});return}e(r)}),n.command(`versions <id-or-slug>`).action(async(n,r)=>{let i=await E(x(r)).publicTemplates.versions(n);if(r.json){e({versions:i});return}t(i.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`createdAt`,header:`Created`,width:24}])}),n.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--slug <slug>`,`Stable public slug`).option(`-d, --description <description>`,`Template description`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).option(`--team-id <id>`,`Publish under a team`).option(`--forked-from <id>`,`Fork source template id`).action((e,t,n,r)=>ss(r,async(i,a)=>({template:await i.publicTemplates.publish({name:e,slug:r.slug,description:r.description,snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes,teamId:r.teamId,forkedFromTemplateId:r.forkedFrom},a)}),[`publish`,e,t,n])),n.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).action((e,t,n,r)=>ss(r,async(i,a)=>({version:await i.publicTemplates.publishVersion(e,{snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes},a)}),[`publish-version`,e,t,n])),n}function ls(){let t=new z(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return t.command(`list`).description(`List trace summaries (one row per trace), newest first`).option(`--from <iso>`,`ISO-8601 lower bound on received time (inclusive)`).option(`--to <iso>`,`ISO-8601 upper bound on received time (inclusive)`).option(`--model <model>`,`Exact model match (any span carried this model)`).option(`--run <runId>`,`Exact run id match`).option(`--status <status>`,`ERROR | OK`).option(`-q, --query <text>`,`Substring over span name`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size (clamped server-side to [1, 200])`).action(async t=>{try{let n={from:t.from,to:t.to,model:t.model,runId:t.run,status:t.status===void 0?void 0:bs(t.status),q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:Ts(t.limit)},r=ds(t),i=t.json?null:d(`Fetching traces...`);i?.start();let a=await r.listTraces(n);if(i?.stop(),t.json)return e(a);ms(a.items),vs(a.nextCursor)}catch(e){ps(e,t)}}),t.command(`get <traceId>`).description(`Show one trace's spans. Streams NDJSON to stdout with --ndjson.`).option(`--ndjson`,`Stream the full span set as NDJSON to stdout`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Spans per page`).action(async(t,n)=>{try{let r=ds(n);if(n.ndjson){await fs(r,t);return}let i=n.json?null:d(`Fetching trace spans...`);i?.start();let a=await r.getTraceSpans(t,{cursor:n.cursor,limit:n.limit===void 0?void 0:Ts(n.limit)});if(i?.stop(),!n.cursor&&a.items.length===0)throw new p(`TRACE_NOT_FOUND`,`No spans for trace ${t}`,`A turn's spans arrive about a minute after it ends, and a key reads only its own account's traces`,`tangle traces list --limit 5`);if(n.json)return e(a);hs(a.items),a.truncated&&o({Spans:`${a.items.length} of ${a.total} (truncated)`}),vs(a.nextCursor)}catch(e){ps(e,n)}}),t.addCommand(us()),t}function us(){let t=new z(`runs`).description(`Read eval-runs pivoted off the trace surface`);return t.command(`list`).description(`List eval-runs, newest first`).option(`--status <status>`,`Run status filter`).option(`--gate <decision>`,`Promotion-gate decision filter`).option(`--label <key:value>`,`Match over the run's labels`).option(`--from <iso>`,`ISO-8601 lower bound on received time`).option(`--to <iso>`,`ISO-8601 upper bound on received time`).option(`-q, --query <text>`,`Substring over run dir`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size`).action(async t=>{try{let n={status:t.status===void 0?void 0:Ss(t.status),gate:t.gate===void 0?void 0:ws(t.gate),label:t.label,from:t.from,to:t.to,q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:Ts(t.limit)},r=ds(t),i=t.json?null:d(`Fetching runs...`);i?.start();let a=await r.listRuns(n);if(i?.stop(),t.json)return e(a);gs(a.items),vs(a.nextCursor)}catch(e){ps(e,t)}}),t.command(`get <runId>`).description(`Show a single eval-run`).action(async(t,n)=>{try{let r=ds(n),i=n.json?null:d(`Fetching run...`);i?.start();let a=await r.getRun(t);if(i?.stop(),n.json)return e(a);_s(a)}catch(e){ps(e,n)}}),t}function ds(e){let t=e.baseUrl||process.env.TANGLE_INTELLIGENCE_BASE_URL||void 0,n=S(`intelligence`,t,e.apiKey);if(!n)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return pt({apiKey:n,baseUrl:t})}async function fs(e,t){let n=(await e.exportTraceSpansNdjson(t)).getReader();try{for(;;){let{value:e,done:t}=await n.read();if(t)break;e&&process.stdout.write(Buffer.from(e))}}finally{n.releaseLock()}}function ps(e,t){return f(e,t.json===!0)}function ms(e){t(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:ys(e.costUsd)})),[{key:`traceId`,header:`Trace`,width:36},{key:`root`,header:`Root`,width:24},{key:`model`,header:`Model`,width:22},{key:`spans`,header:`Spans`,width:8},{key:`errors`,header:`Errors`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14},{key:`cost`,header:`Cost`,width:10}])}function hs(e){t(e.map(e=>({spanId:e.id,name:e.name,model:e.model??`-`,status:e.statusCode??`-`,cost:e.costUsd===null?`-`:`$${e.costUsd}`})),[{key:`spanId`,header:`Span`,width:40},{key:`name`,header:`Name`,width:28},{key:`model`,header:`Model`,width:22},{key:`status`,header:`Status`,width:10},{key:`cost`,header:`Cost`,width:12}])}function gs(e){t(e.map(e=>({runId:e.id,status:e.status,gate:e.gateDecision??`-`,cost:e.totalCostUsd===null?`-`:`$${e.totalCostUsd}`,receivedAt:e.receivedAt})),[{key:`runId`,header:`Run`,width:24},{key:`status`,header:`Status`,width:22},{key:`gate`,header:`Gate`,width:18},{key:`cost`,header:`Cost`,width:12},{key:`receivedAt`,header:`Received`,width:18}])}function _s(e){o({Run:e.id,Status:e.status,Gate:e.gateDecision??void 0,"Run Dir":e.runDir??void 0,Cost:e.totalCostUsd===null?void 0:`$${e.totalCostUsd}`,Duration:e.totalDurationMs===null?void 0:`${e.totalDurationMs}ms`,"Holdout Lift":e.holdoutLift??void 0,Received:e.receivedAt})}function vs(e){e&&o({"Next page":`--cursor ${e}`})}function ys(e){return e===null?`-`:`$${e.toFixed(4)}`}function bs(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const xs=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function Ss(e){let t=xs.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${xs.join(`, `)}`)}const Cs=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function ws(e){let t=Cs.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Cs.join(`, `)}`)}function Ts(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}const Es=`@tangle-network/sandbox-cli`,Ds=`curl -fsSL https://sandbox.tangle.tools/install.sh | sh`,Os=/^\d+\.\d+\.\d+$/,ks=()=>process.env.TANGLE_CLI_HOME||R(H(),`.local/share/tangle-cli`);function As(e){let t=R(ks(),`versions`);if(P(t)&&e.startsWith(be(t)+ze))return`tangle update`;let n=R(ks(),`node_modules`,Es);if(P(n)&&be(n)===e)return`tangle update`;if(e.endsWith(R(`lib`,`node_modules`,Es)))return`npm install -g ${Es}@latest`;if(e.includes(R(`pnpm`,`global`,``)))return`pnpm add -g ${Es}@latest`;if(e.includes(`${ze}node_modules${ze}`))return``}const js=()=>`${process.env.TANGLE_NPM_REGISTRY??`https://registry.npmjs.org`}/${Es.replace(`/`,`%2F`)}/latest`,Ms=`const fs = require("node:fs");
149
151
  const [file, url] = process.argv.slice(1);
150
152
  const record = (latest) => {
151
153
  const state = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -153,7 +155,7 @@ const record = (latest) => {
153
155
  };
154
156
  fetch(url, { signal: AbortSignal.timeout(30000) })
155
157
  .then((r) => r.json()).then((b) => b.version, () => null)
156
- .then((v) => record(${Ds}.test(v) ? v : null), () => {});`,Ms=(e,t)=>e.localeCompare(t,`en`,{numeric:!0})>0;function Ns(e,t){let n=ks(e);if(n===void 0||!process.stderr.isTTY||process.env.CI)return;let r=R(w,`update-check.json`),i=Math.floor(Date.now()/864e5);try{let e=P(r)?JSON.parse(F(r,`utf8`)):{},a=e.checked!==i,o=Ds.test(e.latest)&&Ms(e.latest,t);if(!a&&(!o||e.shown===i))return;ye(w,{mode:448,recursive:!0});let s={...e,checked:i,shown:o?i:e.shown};I(r,JSON.stringify(s)),a&&Qe(process.execPath,[`-e`,js,r,As()],{detached:!0,stdio:`ignore`}).unref(),o&&e.shown!==i&&console.error(`tangle ${t} is installed; ${e.latest} is latest.${n&&` Run: ${n}`}`)}catch{}}function Ps(e,t){return new z(`update`).description(`Install the latest published CLI`).action(async()=>{let n=ks(e);if(n!==`tangle update`)throw new p(`UPDATE_ELSEWHERE`,`install.sh did not install this tangle`,n===void 0?`it runs from source`:`another tool owns it`,n||Es);let r=(await fetch(As(),{signal:AbortSignal.timeout(1e4)}).then(e=>e.json()).catch(()=>({}))).version??``;if(!Ds.test(r))throw new p(`NETWORK_UNAVAILABLE`,`the npm registry gave no version`,`no published version was read`,`tangle update`);if(!Ms(r,t))return console.error(`tangle ${t} is already current`);try{Ze(`bash`,[`-c`,`set -o pipefail; ${Es}`],{stdio:[`ignore`,`ignore`,`inherit`],env:{...process.env,TANGLE_CLI_VERSION:void 0}})}catch{throw new p(`UPDATE_INSTALL_FAILED`,`install.sh failed`,`its error is above`,Es)}let i=R(Os(),`current`,`node_modules`,Ts),a=JSON.parse(F(R(P(i)?i:e,`package.json`),`utf8`));console.error(`tangle updated ${t} -> ${a.version}`)})}function Fs(){return new z(`usage`).description(`Show account usage and billing information`).action(async t=>{let{client:n}=D(t),r=t.json?null:d(`Fetching usage...`);r?.start();let[i,a]=await Promise.all([n.usage(),n.subscription().catch(()=>null)]);r?.stop(),t.json?e({...i,subscription:a}):(console.log(),console.log(`Account Usage`),console.log(`─`.repeat(40)),o({"Active Sandboxes":i.activeSandboxes,"Total Sandboxes":i.totalSandboxes,"Compute Minutes":Is(i.computeMinutes),"GPU Seconds":i.gpuSeconds,"GPU Spend":Ls(i.gpuCostUsd)}),a&&(console.log(),console.log(`Subscription`),console.log(`─`.repeat(40)),o({Plan:a.plan,Status:a.status,"Credits Available":Ls(a.creditsAvailableUsd),"Credits Used":Ls(a.creditsUsedUsd),"Monthly Balance":Ls(a.monthlyBalanceUsd)})),console.log(),console.log(`Billing Period`),console.log(`─`.repeat(40)),o({Start:i.periodStart.toLocaleDateString(),End:i.periodEnd.toLocaleDateString()}),console.log())})}function Is(e){if(e===void 0)return`-`;if(e<60)return`${e} min`;let t=Math.floor(e/60),n=e%60;return n===0?`${t} hr`:`${t} hr ${n} min`}function Ls(e){return e<0?`-$${(-e).toFixed(2)}`:`$${e.toFixed(2)}`}function Rs(){return new z(`use`).description(`Set or show the active sandbox (used when a command omits the id)`).argument(`[id]`,`Sandbox id to make active`).option(`--clear`,`Clear the active sandbox`).action((e,t)=>{if(t.clear){C(),c(`Cleared the active sandbox.`);return}if(e){g(e),c(`Active sandbox set to ${e}. Commands now default to it; override with --box or TANGLE_SANDBOX.`);return}let n=y();c(n?`Active sandbox: ${n}`:"No active sandbox. Set one with `tangle use <id>`.")})}function zs(e){t(e,[{key:`id`,header:`ID`},{key:`nodeId`,header:`Node`},{key:`name`,header:`Name`},{key:`contentType`,header:`Content Type`},{key:`byteSize`,header:`Bytes`},{key:`createdAt`,header:`Created`}])}function Bs(t){t.command(`artifacts`).description(`List a run's artifact metadata (never the bytes)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.listArtifacts(t,n);if(r.json)return e(i);zs(i.artifacts)}),t.command(`artifact-download`).description(`Download one run artifact's bytes to a file`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).argument(`<artifactId>`,`Artifact ID`).option(`--out <file>`,`Destination file (defaults to the artifact ID)`).action(async(t,n,r,i)=>{let a=await(await j(i)).workflows.downloadArtifact(t,n,r),o=i.out??r;try{I(o,a.bytes)}catch(e){throw Error(`Could not write artifact to "${o}": ${e instanceof Error?e.message:String(e)}`)}if(i.json)return e({file:o,contentType:a.contentType,bytes:a.bytes.length});c(`Wrote ${o} (${a.bytes.length} bytes, ${a.contentType}).`)})}function Vs(e){t(e.map(e=>({id:e.id,run:e.runId,title:e.title,options:e.options.join(`, `),requested:e.requestedAt,expires:e.expiresAt??``})),[{key:`id`,header:`ID`},{key:`run`,header:`Run`},{key:`title`,header:`Title`},{key:`options`,header:`Options`},{key:`requested`,header:`Requested`},{key:`expires`,header:`Expires`}])}function Hs(t){t.command(`decisions`).description(`List a workflow's pending human decisions`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=(await(await j(n)).workflows.listPendingDecisions()).decisions.filter(e=>e.workflowId===t);if(n.json)return e({decisions:r});Vs(r)}),t.command(`decision-resolve`).description(`Answer the decision a run is parked on and resume it`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).requiredOption(`--choice <choice>`,`The option to resolve with (one of the decision's options)`).action(async(t,n,r)=>{let i=await j(r),a=await i.workflows.getRunDecision(t,n),o=await i.workflows.resolveRunDecision(t,n,{decisionId:a.id,choice:r.choice});if(r.json)return e(o);if(o.resumed){c(`Resolved decision ${o.decisionId} with "${o.choice}" — run ${o.runId} resumed.`);return}c(`Resolved decision ${o.decisionId} with "${o.choice}", but run ${o.runId} had already finished — nothing to resume.`)})}function Us(e){try{return F(e,`utf8`)}catch(t){throw Error(`Could not read workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Ws(e){t(e.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,issues:e.validationErrors.length,updated:e.updatedAt})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`issues`,header:`Issues`},{key:`updated`,header:`Updated`}])}function Gs(e){let n=e.workflows.filter(e=>e.failed>0).length,r=e.workflows.filter(e=>e.failed===0&&e.waiting>0).length,i=e.workflows.filter(e=>e.failed===0&&e.waiting===0&&e.runsInWindow>0).length;c(`${n} failing · ${r} waiting · ${i} healthy · ${e.workflows.length} total over ${e.window}`),t(e.workflows.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,runs:e.runsInWindow,failed:e.failed,waiting:e.waiting,success:e.successRate===null?`—`:`${Math.round(e.successRate*100)}%`,lastRun:e.lastRunStatus??`—`,lastRunAt:e.lastRunAt??`—`})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`runs`,header:`Runs`},{key:`failed`,header:`Failed`},{key:`waiting`,header:`Waiting`},{key:`success`,header:`Success`},{key:`lastRun`,header:`Last Run`},{key:`lastRunAt`,header:`Last Run At`}])}function $(e){if(o({ID:e.id,Name:e.name,Description:e.description??``,Enabled:e.enabled?`yes`:`no`,Actions:e.actions.length}),e.triggers&&e.triggers.length>0&&(c(`Triggers`),Ks(e.triggers)),e.validationErrors.length>0){c(`Validation issues`);for(let t of e.validationErrors)console.log(` ${t.path}: ${t.message}`)}}function Ks(e){t(e.map(e=>({id:e.id,kind:e.kind,enabled:e.enabled?`yes`:`no`,detail:e.kind===`schedule`?`${e.cron??``} (${e.timezone??``})`:`${e.provider??``}:${e.eventFilter?.event??``}${e.eventFilter?.action?`.${e.eventFilter.action}`:``}`})),[{key:`id`,header:`ID`},{key:`kind`,header:`Kind`},{key:`enabled`,header:`Enabled`},{key:`detail`,header:`Detail`}])}function qs(t){t.command(`list`).description(`List your workflows`).action(async t=>{let n=await(await j(t)).workflows.list();if(t.json)return e(n);Ws(n)}),t.command(`fleet`).description(`Fleet overview: every workflow's run tallies over a trailing window, failing-first`).option(`--window <window>`,`Trailing window: 24h, 7d, or 30d`,`7d`).action(async t=>{let n=await(await j(t)).workflows.fleetInsights({window:t.window});if(t.json)return e(n);Gs(n)}),t.command(`get`).description(`Show a workflow's definition and compiled triggers`).argument(`<id>`,`Workflow ID`).option(`--yaml`,`Print only the raw definition YAML (the export path — pipe to a file)`).action(async(t,n)=>{let r=await(await j(n)).workflows.get(t);if(n.yaml){if(r.definitionYaml===null)throw Error(`Workflow ${r.id} has no stored definition YAML to export`);process.stdout.write(r.definitionYaml.endsWith(`
157
- `)?r.definitionYaml:`${r.definitionYaml}\n`);return}if(n.json)return e(r);$(r)}),t.command(`create`).description(`Create a workflow from a YAML file`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=Us(t),i=await(await j(n)).workflows.create(r);if(n.json)return e(i);c(`Created workflow ${i.id} (${i.name}).`),$(i)}),t.command(`apply`).description(`Create or update a workflow idempotently, matched by the definition's name`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=Us(t),i=await j(n),a=await i.workflows.validate(r,{structural:!0});if(!a.valid){if(process.exitCode=1,n.json)return e(a);c(`Invalid workflow:`);for(let e of a.errors)console.log(` ${e.path}: ${e.message}`);return}let o=(await i.workflows.list()).find(e=>e.name===a.name);if(o){let t=await i.workflows.update(o.id,r);if(n.json)return e({action:`updated`,workflow:t});c(`Updated workflow ${t.id} (${t.name}) — matched by name.`),$(t);return}let s=await i.workflows.create(r);if(n.json)return e({action:`created`,workflow:s});c(`Created workflow ${s.id} (${s.name}).`),$(s)}),t.command(`update`).description(`Replace a workflow's definition from a YAML file`).argument(`<id>`,`Workflow ID`).argument(`<file>`,`Path to the workflow YAML`).option(`--note <note>`,`Revision note recorded on the appended revision (why this change)`).action(async(t,n,r)=>{let i=Us(n),a=await(await j(r)).workflows.update(t,i,{...r.note===void 0?{}:{note:r.note}});if(r.json)return e(a);c(`Updated workflow ${a.id} (${a.name}).`),$(a)}),t.command(`delete`).description(`Delete a workflow and its triggers`).argument(`<id>`,`Workflow ID`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{if(!n.force&&!await N(`Delete workflow ${t}? `,`--force`)){c(`Delete cancelled.`);return}if(await(await j(n)).workflows.delete(t),n.json)return e({deleted:!0,id:t});c(`Deleted workflow ${t}.`)}),t.command(`validate`).description(`Validate a workflow YAML file without saving it`).argument(`<file>`,`Path to the workflow YAML`).option(`--structural`,`CI mode: compile + capability checks only, no connection resolution — the verdict is the same regardless of connected providers`).action(async(t,n)=>{let r=Us(t),i=await(await j(n)).workflows.validate(r,{...n.structural?{structural:!0}:{}});if(n.json)return e(i);if(i.valid)c(`Valid: ${i.name} (${i.actionCount} action(s), ${i.triggerCount} trigger(s)).`);else{c(`Invalid workflow:`);for(let e of i.errors)console.log(` ${e.path}: ${e.message}`);process.exitCode=1}}),t.command(`schema`).description(`Print the JSON Schema for the workflow YAML`).action(async t=>{e(await(await j(t)).workflows.schema())})}async function Js(t,n,r){let i=await(await j(r)).workflows.setEnabled(t,n);if(r.json)return e(i);c(`${n?`Enabled`:`Disabled`} workflow ${i.id}.`),$(i)}function Ys(e,t){try{return JSON.parse(e)}catch{throw Error(`Invalid ${t}: not valid JSON`)}}function Xs(e,t){try{I(e,t,`utf8`)}catch(t){throw Error(`Could not write workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Zs(e){t(e.map(e=>({id:e.id,name:e.name,category:e.category,providers:e.providers.join(`, `),summary:e.summary})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`category`,header:`Category`},{key:`providers`,header:`Providers`},{key:`summary`,header:`Summary`}])}function Qs(e,t){let n=e.kind===`github_app`,r=n?`${e.provider} (App installation)`:e.provider,i=e.connectUrl?` — ${n?`install`:`connect`}: ${e.connectUrl}`:``,a=e.prerequisite;return`${r}${i}${a&&t.some(e=>e.provider===a.provider&&e.kind===a.kind&&!e.connected)?` (after connecting ${a.provider})`:``}`}function $s(t){t.command(`enable`).description(`Enable a workflow so its triggers and manual runs fire`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Js(e,!0,t)}),t.command(`disable`).description(`Disable a workflow (pause its triggers and manual runs)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Js(e,!1,t)}),t.command(`templates`).description(`List the curated starter workflow templates`).action(async t=>{let n=await(await j(t)).workflows.listTemplates();if(t.json)return e(n);Zs(n)}),t.command(`init`).description(`Create a workflow from a gallery template and print (or save) its YAML`).argument(`<template-id>`,"Template ID from `workflows templates`").option(`--param <key=value>`,`Template parameter value. Repeatable.`,ce,[]).option(`--file <out>`,`Write the instantiated workflow YAML to this file instead of stdout`).action(async(t,n)=>{let r=ie(n.param,`param`)??{},i=await(await j(n)).workflows.instantiateTemplate(t,r);if(n.json)return e(i);if(!i.created){c(`Template ${t} needs provider connections before it can run:`);for(let e of i.connectionRequirements)console.log(` ${e.connected?`✓`:`✗`} ${Qs(e,i.connectionRequirements)}`);process.exitCode=1;return}let{workflow:a}=i;if(a.definitionYaml===null)throw Error(`Workflow ${a.id} was created but the server returned no definition YAML`);if(c(`Created workflow ${a.id} (${a.name}).`),n.file){Xs(n.file,a.definitionYaml),c(`Wrote ${n.file}.`);return}process.stdout.write(a.definitionYaml.endsWith(`
158
- `)?a.definitionYaml:`${a.definitionYaml}\n`)})}function ec(e){t(e,[{key:`key`,header:`Key`},{key:`version`,header:`Version`},{key:`updatedAt`,header:`Updated`}])}function tc(t){o({Key:t.key,Version:t.version,Updated:t.updatedAt}),c(`Value`),e(t.value)}function nc(t){let n=t.command(`kv`).description(`Read and write a workflow's cross-run KV state`);n.command(`list`).description(`List every KV entry of a workflow`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await j(n)).workflows.listKv(t);if(n.json)return e(r);ec(r.entries)}),n.command(`get`).description(`Show one KV entry (value and version)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.getKv(t,n);if(r.json)return e(i);tc(i)}),n.command(`set`).description(`Write a KV entry from a JSON value`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).argument(`<json>`,`Value as JSON (e.g. '{"cursor":123}' or '"abc"')`).option(`--cas <version>`,`Compare-and-swap: write only if the stored version still equals this`).action(async(t,n,r,i)=>{let a=Ys(r,`<json>`),o=i.cas===void 0?void 0:k(i.cas,`--cas`),s=await j(i),c=o===void 0?await s.workflows.putKv(t,n,a):await s.workflows.casKv(t,n,o,a);if(i.json)return e(c);tc(c)}),n.command(`delete`).description(`Delete a KV entry (idempotent)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.deleteKv(t,n);if(r.json)return e(i);c(i.deleted?`Deleted KV entry "${n}" of workflow ${t}.`:`No KV entry "${n}" on workflow ${t}.`)})}function rc(e){t(e.map(e=>({rev:e.rev,created:e.createdAt,by:e.createdBy,source:e.source,note:e.note??``})),[{key:`rev`,header:`Rev`},{key:`created`,header:`Created`},{key:`by`,header:`Created By`},{key:`source`,header:`Source`},{key:`note`,header:`Note`}])}function ic(t){t.command(`revisions`).description(`List a workflow's definition revision history (newest first)`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await j(n)).workflows.listRevisions(t);if(n.json)return e(r);rc(r)}),t.command(`revision`).description(`Show one revision's metadata and definition YAML`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number`).action(async(t,n,r)=>{let i=k(n,`<rev>`),a=await(await j(r)).workflows.getRevision(t,i);if(r.json)return e(a);o({Revision:a.rev,Created:a.createdAt,"Created by":a.createdBy,Source:a.source,Note:a.note??``}),process.stdout.write(a.yaml.endsWith(`
159
- `)?a.yaml:`${a.yaml}\n`)}),t.command(`rollback`).description(`Restore a prior revision's definition as a NEW head revision (re-validated)`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number to restore`).action(async(t,n,r)=>{let i=k(n,`<rev>`),a=await(await j(r)).workflows.rollback(t,i);if(r.json)return e(a);c(`Rolled back workflow ${a.id} to rev ${i}.`),$(a)})}function ac(){let e=new z(`workflows`).description(`Create and manage Tangle workflows`);return qs(e),oe(e),$s(e),ic(e),nc(e),Bs(e),Hs(e),e}function oc(e){for(let[t,n]of Object.entries(e.optsWithGlobals()))e.getOptionValue(t)===void 0&&n!==void 0&&e.setOptionValue(t,n)}const sc=he(import.meta.url),cc=sc(`../package.json`),lc=Ie(sc.resolve(`../package.json`)),uc=cc.version??`0.0.0`;function dc(){let e=new z,t=Ps(lc,uc);e.name(`tangle`).description(`CLI for Tangle Sandbox operations`).version(uc).option(`--json`,`Output JSON where supported, including errors`).option(`--api-key <key>`,`API key (or set TANGLE_API_KEY)`).option(`--base-url <url>`,`API base URL`),e.hook(`preAction`,(e,n)=>{oc(n);let r=n.opts(),a=r.json===!0||r.ndjson===!0;i(a),n!==t&&!a&&Ns(lc,uc)}),e.addCommand(se()),e.addCommand(No()),e.addCommand(Rs()),e.addCommand(Fo()),e.addCommand(to()),e.addCommand(lo()),e.addCommand(uo()),e.addCommand(Ei()),e.addCommand(Qo()),e.addCommand($o()),e.addCommand(ts()),e.addCommand(un()),e.addCommand(Ro()),e.addCommand(ja()),e.addCommand(Fs()),e.addCommand(ns()),e.addCommand(ss()),e.addCommand(fn()),e.addCommand(Cn()),e.addCommand(yo()),e.addCommand(Ma()),e.addCommand(Fa());let n=new z(`graph`).description(`Build and run portable agent graphs`);e.addCommand(n);let r=async()=>{n.commands.length||(await import(`./graph-CNZgbEhu.mjs`).then(e=>e.t)).registerGraphCommands(n)};e.hook(`preSubcommand`,async(e,t)=>{t===n&&await r()});let a=e.parseAsync.bind(e);e.parseAsync=async(e,t)=>{let n=(e??process.argv).slice(t?.from===`user`?0:2);return n[0]===`help`&&n[1]===`graph`&&await r(),a(e,t)},e.addCommand(A()),e.addCommand(ac()),e.addCommand(ci()),e.addCommand(Po()),e.addCommand(Ho()),e.addCommand(Lo()),e.addCommand(wn()),e.addCommand(_o()),e.addCommand(Ia()),e.addCommand(ti()),e.addCommand(ni()),e.addCommand(To()),e.addCommand(fo()),e.addCommand(cs()),e.addCommand(ne()),e.addCommand(t);function o(e){e.configureHelp({showGlobalOptions:!0}),e.configureOutput({writeErr:()=>{}}),e.exitOverride(t=>{t.exitCode===0&&process.exit(0),f(t,e.optsWithGlobals().json===!0)});for(let t of e.commands)o(t)}return o(e),e}try{let e=ve(`.env`),t=e.isFile()&&e.size<=65536?F(`.env`,`utf8`):``;/^\s*(export\s+)?(TANGLE|SANDBOX)_\w*\s*=/m.test(t)&&console.error(`The CLI no longer reads .env; export its TANGLE_ and SANDBOX_ variables in your shell.`)}catch{}const fc=dc();fc.parseAsync(process.argv).catch(e=>{f(e,fc.opts().json===!0)});export{};
158
+ .then((v) => record(${Os}.test(v) ? v : null), () => {});`,Ns=(e,t)=>e.localeCompare(t,`en`,{numeric:!0})>0;function Ps(e,t){let n=As(e);if(n===void 0||!process.stderr.isTTY||process.env.CI)return;let r=R(w,`update-check.json`),i=Math.floor(Date.now()/864e5);try{let e=P(r)?JSON.parse(F(r,`utf8`)):{},a=e.checked!==i,o=Os.test(e.latest)&&Ns(e.latest,t);if(!a&&(!o||e.shown===i))return;ye(w,{mode:448,recursive:!0});let s={...e,checked:i,shown:o?i:e.shown};I(r,JSON.stringify(s)),a&&Qe(process.execPath,[`-e`,Ms,r,js()],{detached:!0,stdio:`ignore`}).unref(),o&&e.shown!==i&&console.error(`tangle ${t} is installed; ${e.latest} is latest.${n&&` Run: ${n}`}`)}catch{}}function Fs(e,t){return new z(`update`).description(`Install the latest published CLI`).action(async()=>{let n=As(e);if(n!==`tangle update`)throw new p(`UPDATE_ELSEWHERE`,`install.sh did not install this tangle`,n===void 0?`it runs from source`:`another tool owns it`,n||Ds);let r=(await fetch(js(),{signal:AbortSignal.timeout(1e4)}).then(e=>e.json()).catch(()=>({}))).version??``;if(!Os.test(r))throw new p(`NETWORK_UNAVAILABLE`,`the npm registry gave no version`,`no published version was read`,`tangle update`);if(!Ns(r,t))return console.error(`tangle ${t} is already current`);try{Ze(`bash`,[`-c`,`set -o pipefail; ${Ds}`],{stdio:[`ignore`,`ignore`,`inherit`],env:{...process.env,TANGLE_CLI_VERSION:void 0}})}catch{throw new p(`UPDATE_INSTALL_FAILED`,`install.sh failed`,`its error is above`,Ds)}let i=R(ks(),`current`,`node_modules`,Es),a=JSON.parse(F(R(P(i)?i:e,`package.json`),`utf8`));console.error(`tangle updated ${t} -> ${a.version}`)})}function Is(){return new z(`usage`).description(`Show account usage and billing information`).action(async t=>{let{client:n}=D(t),r=t.json?null:d(`Fetching usage...`);r?.start();let[i,a]=await Promise.all([n.usage(),n.subscription().catch(()=>null)]);r?.stop(),t.json?e({...i,subscription:a}):(console.log(),console.log(`Account Usage`),console.log(`─`.repeat(40)),o({"Active Sandboxes":i.activeSandboxes,"Total Sandboxes":i.totalSandboxes,"Compute Minutes":Ls(i.computeMinutes),"GPU Seconds":i.gpuSeconds,"GPU Spend":Rs(i.gpuCostUsd)}),a&&(console.log(),console.log(`Subscription`),console.log(`─`.repeat(40)),o({Plan:a.plan,Status:a.status,"Credits Available":Rs(a.creditsAvailableUsd),"Credits Used":Rs(a.creditsUsedUsd),"Monthly Balance":Rs(a.monthlyBalanceUsd)})),console.log(),console.log(`Billing Period`),console.log(`─`.repeat(40)),o({Start:i.periodStart.toLocaleDateString(),End:i.periodEnd.toLocaleDateString()}),console.log())})}function Ls(e){if(e===void 0)return`-`;if(e<60)return`${e} min`;let t=Math.floor(e/60),n=e%60;return n===0?`${t} hr`:`${t} hr ${n} min`}function Rs(e){return e<0?`-$${(-e).toFixed(2)}`:`$${e.toFixed(2)}`}function zs(){return new z(`use`).description(`Set or show the active sandbox (used when a command omits the id)`).argument(`[id]`,`Sandbox id to make active`).option(`--clear`,`Clear the active sandbox`).action((e,t)=>{if(t.clear){C(),c(`Cleared the active sandbox.`);return}if(e){g(e),c(`Active sandbox set to ${e}. Commands now default to it; override with --box or TANGLE_SANDBOX.`);return}let n=y();c(n?`Active sandbox: ${n}`:"No active sandbox. Set one with `tangle use <id>`.")})}function Bs(e){t(e,[{key:`id`,header:`ID`},{key:`nodeId`,header:`Node`},{key:`name`,header:`Name`},{key:`contentType`,header:`Content Type`},{key:`byteSize`,header:`Bytes`},{key:`createdAt`,header:`Created`}])}function Vs(t){t.command(`artifacts`).description(`List a run's artifact metadata (never the bytes)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.listArtifacts(t,n);if(r.json)return e(i);Bs(i.artifacts)}),t.command(`artifact-download`).description(`Download one run artifact's bytes to a file`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).argument(`<artifactId>`,`Artifact ID`).option(`--out <file>`,`Destination file (defaults to the artifact ID)`).action(async(t,n,r,i)=>{let a=await(await j(i)).workflows.downloadArtifact(t,n,r),o=i.out??r;try{I(o,a.bytes)}catch(e){throw Error(`Could not write artifact to "${o}": ${e instanceof Error?e.message:String(e)}`)}if(i.json)return e({file:o,contentType:a.contentType,bytes:a.bytes.length});c(`Wrote ${o} (${a.bytes.length} bytes, ${a.contentType}).`)})}function Hs(e){t(e.map(e=>({id:e.id,run:e.runId,title:e.title,options:e.options.join(`, `),requested:e.requestedAt,expires:e.expiresAt??``})),[{key:`id`,header:`ID`},{key:`run`,header:`Run`},{key:`title`,header:`Title`},{key:`options`,header:`Options`},{key:`requested`,header:`Requested`},{key:`expires`,header:`Expires`}])}function Us(t){t.command(`decisions`).description(`List a workflow's pending human decisions`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=(await(await j(n)).workflows.listPendingDecisions()).decisions.filter(e=>e.workflowId===t);if(n.json)return e({decisions:r});Hs(r)}),t.command(`decision-resolve`).description(`Answer the decision a run is parked on and resume it`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).requiredOption(`--choice <choice>`,`The option to resolve with (one of the decision's options)`).action(async(t,n,r)=>{let i=await j(r),a=await i.workflows.getRunDecision(t,n),o=await i.workflows.resolveRunDecision(t,n,{decisionId:a.id,choice:r.choice});if(r.json)return e(o);if(o.resumed){c(`Resolved decision ${o.decisionId} with "${o.choice}" — run ${o.runId} resumed.`);return}c(`Resolved decision ${o.decisionId} with "${o.choice}", but run ${o.runId} had already finished — nothing to resume.`)})}function Ws(e){try{return F(e,`utf8`)}catch(t){throw Error(`Could not read workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Gs(e){t(e.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,issues:e.validationErrors.length,updated:e.updatedAt})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`issues`,header:`Issues`},{key:`updated`,header:`Updated`}])}function Ks(e){let n=e.workflows.filter(e=>e.failed>0).length,r=e.workflows.filter(e=>e.failed===0&&e.waiting>0).length,i=e.workflows.filter(e=>e.failed===0&&e.waiting===0&&e.runsInWindow>0).length;c(`${n} failing · ${r} waiting · ${i} healthy · ${e.workflows.length} total over ${e.window}`),t(e.workflows.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,runs:e.runsInWindow,failed:e.failed,waiting:e.waiting,success:e.successRate===null?`—`:`${Math.round(e.successRate*100)}%`,lastRun:e.lastRunStatus??`—`,lastRunAt:e.lastRunAt??`—`})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`runs`,header:`Runs`},{key:`failed`,header:`Failed`},{key:`waiting`,header:`Waiting`},{key:`success`,header:`Success`},{key:`lastRun`,header:`Last Run`},{key:`lastRunAt`,header:`Last Run At`}])}function $(e){if(o({ID:e.id,Name:e.name,Description:e.description??``,Enabled:e.enabled?`yes`:`no`,Actions:e.actions.length}),e.triggers&&e.triggers.length>0&&(c(`Triggers`),qs(e.triggers)),e.validationErrors.length>0){c(`Validation issues`);for(let t of e.validationErrors)console.log(` ${t.path}: ${t.message}`)}}function qs(e){t(e.map(e=>({id:e.id,kind:e.kind,enabled:e.enabled?`yes`:`no`,detail:e.kind===`schedule`?`${e.cron??``} (${e.timezone??``})`:`${e.provider??``}:${e.eventFilter?.event??``}${e.eventFilter?.action?`.${e.eventFilter.action}`:``}`})),[{key:`id`,header:`ID`},{key:`kind`,header:`Kind`},{key:`enabled`,header:`Enabled`},{key:`detail`,header:`Detail`}])}function Js(t){t.command(`list`).description(`List your workflows`).action(async t=>{let n=await(await j(t)).workflows.list();if(t.json)return e(n);Gs(n)}),t.command(`fleet`).description(`Fleet overview: every workflow's run tallies over a trailing window, failing-first`).option(`--window <window>`,`Trailing window: 24h, 7d, or 30d`,`7d`).action(async t=>{let n=await(await j(t)).workflows.fleetInsights({window:t.window});if(t.json)return e(n);Ks(n)}),t.command(`get`).description(`Show a workflow's definition and compiled triggers`).argument(`<id>`,`Workflow ID`).option(`--yaml`,`Print only the raw definition YAML (the export path — pipe to a file)`).action(async(t,n)=>{let r=await(await j(n)).workflows.get(t);if(n.yaml){if(r.definitionYaml===null)throw Error(`Workflow ${r.id} has no stored definition YAML to export`);process.stdout.write(r.definitionYaml.endsWith(`
159
+ `)?r.definitionYaml:`${r.definitionYaml}\n`);return}if(n.json)return e(r);$(r)}),t.command(`create`).description(`Create a workflow from a YAML file`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=Ws(t),i=await(await j(n)).workflows.create(r);if(n.json)return e(i);c(`Created workflow ${i.id} (${i.name}).`),$(i)}),t.command(`apply`).description(`Create or update a workflow idempotently, matched by the definition's name`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=Ws(t),i=await j(n),a=await i.workflows.validate(r,{structural:!0});if(!a.valid){if(process.exitCode=1,n.json)return e(a);c(`Invalid workflow:`);for(let e of a.errors)console.log(` ${e.path}: ${e.message}`);return}let o=(await i.workflows.list()).find(e=>e.name===a.name);if(o){let t=await i.workflows.update(o.id,r);if(n.json)return e({action:`updated`,workflow:t});c(`Updated workflow ${t.id} (${t.name}) — matched by name.`),$(t);return}let s=await i.workflows.create(r);if(n.json)return e({action:`created`,workflow:s});c(`Created workflow ${s.id} (${s.name}).`),$(s)}),t.command(`update`).description(`Replace a workflow's definition from a YAML file`).argument(`<id>`,`Workflow ID`).argument(`<file>`,`Path to the workflow YAML`).option(`--note <note>`,`Revision note recorded on the appended revision (why this change)`).action(async(t,n,r)=>{let i=Ws(n),a=await(await j(r)).workflows.update(t,i,{...r.note===void 0?{}:{note:r.note}});if(r.json)return e(a);c(`Updated workflow ${a.id} (${a.name}).`),$(a)}),t.command(`delete`).description(`Delete a workflow and its triggers`).argument(`<id>`,`Workflow ID`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{if(!n.force&&!await N(`Delete workflow ${t}? `,`--force`)){c(`Delete cancelled.`);return}if(await(await j(n)).workflows.delete(t),n.json)return e({deleted:!0,id:t});c(`Deleted workflow ${t}.`)}),t.command(`validate`).description(`Validate a workflow YAML file without saving it`).argument(`<file>`,`Path to the workflow YAML`).option(`--structural`,`CI mode: compile + capability checks only, no connection resolution — the verdict is the same regardless of connected providers`).action(async(t,n)=>{let r=Ws(t),i=await(await j(n)).workflows.validate(r,{...n.structural?{structural:!0}:{}});if(n.json)return e(i);if(i.valid)c(`Valid: ${i.name} (${i.actionCount} action(s), ${i.triggerCount} trigger(s)).`);else{c(`Invalid workflow:`);for(let e of i.errors)console.log(` ${e.path}: ${e.message}`);process.exitCode=1}}),t.command(`schema`).description(`Print the JSON Schema for the workflow YAML`).action(async t=>{e(await(await j(t)).workflows.schema())})}async function Ys(t,n,r){let i=await(await j(r)).workflows.setEnabled(t,n);if(r.json)return e(i);c(`${n?`Enabled`:`Disabled`} workflow ${i.id}.`),$(i)}function Xs(e,t){try{return JSON.parse(e)}catch{throw Error(`Invalid ${t}: not valid JSON`)}}function Zs(e,t){try{I(e,t,`utf8`)}catch(t){throw Error(`Could not write workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Qs(e){t(e.map(e=>({id:e.id,name:e.name,category:e.category,providers:e.providers.join(`, `),summary:e.summary})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`category`,header:`Category`},{key:`providers`,header:`Providers`},{key:`summary`,header:`Summary`}])}function $s(e,t){let n=e.kind===`github_app`,r=n?`${e.provider} (App installation)`:e.provider,i=e.connectUrl?` — ${n?`install`:`connect`}: ${e.connectUrl}`:``,a=e.prerequisite;return`${r}${i}${a&&t.some(e=>e.provider===a.provider&&e.kind===a.kind&&!e.connected)?` (after connecting ${a.provider})`:``}`}function ec(t){t.command(`enable`).description(`Enable a workflow so its triggers and manual runs fire`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Ys(e,!0,t)}),t.command(`disable`).description(`Disable a workflow (pause its triggers and manual runs)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Ys(e,!1,t)}),t.command(`templates`).description(`List the curated starter workflow templates`).action(async t=>{let n=await(await j(t)).workflows.listTemplates();if(t.json)return e(n);Qs(n)}),t.command(`init`).description(`Create a workflow from a gallery template and print (or save) its YAML`).argument(`<template-id>`,"Template ID from `workflows templates`").option(`--param <key=value>`,`Template parameter value. Repeatable.`,ce,[]).option(`--file <out>`,`Write the instantiated workflow YAML to this file instead of stdout`).action(async(t,n)=>{let r=ie(n.param,`param`)??{},i=await(await j(n)).workflows.instantiateTemplate(t,r);if(n.json)return e(i);if(!i.created){c(`Template ${t} needs provider connections before it can run:`);for(let e of i.connectionRequirements)console.log(` ${e.connected?`✓`:`✗`} ${$s(e,i.connectionRequirements)}`);process.exitCode=1;return}let{workflow:a}=i;if(a.definitionYaml===null)throw Error(`Workflow ${a.id} was created but the server returned no definition YAML`);if(c(`Created workflow ${a.id} (${a.name}).`),n.file){Zs(n.file,a.definitionYaml),c(`Wrote ${n.file}.`);return}process.stdout.write(a.definitionYaml.endsWith(`
160
+ `)?a.definitionYaml:`${a.definitionYaml}\n`)})}function tc(e){t(e,[{key:`key`,header:`Key`},{key:`version`,header:`Version`},{key:`updatedAt`,header:`Updated`}])}function nc(t){o({Key:t.key,Version:t.version,Updated:t.updatedAt}),c(`Value`),e(t.value)}function rc(t){let n=t.command(`kv`).description(`Read and write a workflow's cross-run KV state`);n.command(`list`).description(`List every KV entry of a workflow`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await j(n)).workflows.listKv(t);if(n.json)return e(r);tc(r.entries)}),n.command(`get`).description(`Show one KV entry (value and version)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.getKv(t,n);if(r.json)return e(i);nc(i)}),n.command(`set`).description(`Write a KV entry from a JSON value`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).argument(`<json>`,`Value as JSON (e.g. '{"cursor":123}' or '"abc"')`).option(`--cas <version>`,`Compare-and-swap: write only if the stored version still equals this`).action(async(t,n,r,i)=>{let a=Xs(r,`<json>`),o=i.cas===void 0?void 0:k(i.cas,`--cas`),s=await j(i),c=o===void 0?await s.workflows.putKv(t,n,a):await s.workflows.casKv(t,n,o,a);if(i.json)return e(c);nc(c)}),n.command(`delete`).description(`Delete a KV entry (idempotent)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await j(r)).workflows.deleteKv(t,n);if(r.json)return e(i);c(i.deleted?`Deleted KV entry "${n}" of workflow ${t}.`:`No KV entry "${n}" on workflow ${t}.`)})}function ic(e){t(e.map(e=>({rev:e.rev,created:e.createdAt,by:e.createdBy,source:e.source,note:e.note??``})),[{key:`rev`,header:`Rev`},{key:`created`,header:`Created`},{key:`by`,header:`Created By`},{key:`source`,header:`Source`},{key:`note`,header:`Note`}])}function ac(t){t.command(`revisions`).description(`List a workflow's definition revision history (newest first)`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await j(n)).workflows.listRevisions(t);if(n.json)return e(r);ic(r)}),t.command(`revision`).description(`Show one revision's metadata and definition YAML`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number`).action(async(t,n,r)=>{let i=k(n,`<rev>`),a=await(await j(r)).workflows.getRevision(t,i);if(r.json)return e(a);o({Revision:a.rev,Created:a.createdAt,"Created by":a.createdBy,Source:a.source,Note:a.note??``}),process.stdout.write(a.yaml.endsWith(`
161
+ `)?a.yaml:`${a.yaml}\n`)}),t.command(`rollback`).description(`Restore a prior revision's definition as a NEW head revision (re-validated)`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number to restore`).action(async(t,n,r)=>{let i=k(n,`<rev>`),a=await(await j(r)).workflows.rollback(t,i);if(r.json)return e(a);c(`Rolled back workflow ${a.id} to rev ${i}.`),$(a)})}function oc(){let e=new z(`workflows`).description(`Create and manage Tangle workflows`);return Js(e),oe(e),ec(e),ac(e),rc(e),Vs(e),Us(e),e}function sc(e){for(let[t,n]of Object.entries(e.optsWithGlobals()))e.getOptionValue(t)===void 0&&n!==void 0&&e.setOptionValue(t,n)}const cc=he(import.meta.url),lc=cc(`../package.json`),uc=Ie(cc.resolve(`../package.json`)),dc=lc.version??`0.0.0`;function fc(){let e=new z,t=Fs(uc,dc);e.name(`tangle`).description(`CLI for Tangle Sandbox operations`).version(dc).option(`--json`,`Output JSON where supported, including errors`).option(`--api-key <key>`,`API key (or set TANGLE_API_KEY)`).option(`--base-url <url>`,`API base URL`),e.hook(`preAction`,(e,n)=>{sc(n);let r=n.opts(),a=r.json===!0||r.ndjson===!0;i(a),n!==t&&!a&&Ps(uc,dc)}),e.addCommand(se()),e.addCommand(Po()),e.addCommand(zs()),e.addCommand(Io()),e.addCommand(no()),e.addCommand(uo()),e.addCommand(fo()),e.addCommand(Di()),e.addCommand($o()),e.addCommand(es()),e.addCommand(ns()),e.addCommand(dn()),e.addCommand(zo()),e.addCommand(Ma()),e.addCommand(Is()),e.addCommand(rs()),e.addCommand(cs()),e.addCommand(pn()),e.addCommand(wn()),e.addCommand(bo()),e.addCommand(Na()),e.addCommand(Ia());let n=new z(`graph`).description(`Build and run portable agent graphs`);e.addCommand(n);let r=async()=>{n.commands.length||(await import(`./graph-CNZgbEhu.mjs`).then(e=>e.t)).registerGraphCommands(n)};e.hook(`preSubcommand`,async(e,t)=>{t===n&&await r()});let a=e.parseAsync.bind(e);e.parseAsync=async(e,t)=>{let n=(e??process.argv).slice(t?.from===`user`?0:2);return n[0]===`help`&&n[1]===`graph`&&await r(),a(e,t)},e.addCommand(A()),e.addCommand(oc()),e.addCommand(li()),e.addCommand(Fo()),e.addCommand(Uo()),e.addCommand(Ro()),e.addCommand(Tn()),e.addCommand(vo()),e.addCommand(La()),e.addCommand(ni()),e.addCommand(ri()),e.addCommand(Eo()),e.addCommand(po()),e.addCommand(ls()),e.addCommand(ne()),e.addCommand(t);function o(e){e.configureHelp({showGlobalOptions:!0}),e.configureOutput({writeErr:()=>{}}),e.exitOverride(t=>{t.exitCode===0&&process.exit(0),f(t,e.optsWithGlobals().json===!0)});for(let t of e.commands)o(t)}return o(e),e}try{let e=ve(`.env`),t=e.isFile()&&e.size<=65536?F(`.env`,`utf8`):``;/^\s*(export\s+)?(TANGLE|SANDBOX)_\w*\s*=/m.test(t)&&console.error(`The CLI no longer reads .env; export its TANGLE_ and SANDBOX_ variables in your shell.`)}catch{}const pc=fc();pc.parseAsync(process.argv).catch(e=>{f(e,pc.opts().json===!0)});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.23.371",
3
+ "version": "0.23.372",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "engines": {
@@ -61,9 +61,9 @@
61
61
  "typescript": "^6.0.3",
62
62
  "vitest": "^4.1.12",
63
63
  "@repo/shared": "0.0.0",
64
+ "@tangle-network/runtime-contracts": "0.20.0",
64
65
  "@tangle-network/sdk-session-persistence": "0.7.0",
65
- "@repo/knowledge-host": "0.0.0",
66
- "@tangle-network/runtime-contracts": "0.20.0"
66
+ "@repo/knowledge-host": "0.0.0"
67
67
  },
68
68
  "publishConfig": {
69
69
  "access": "public",
@@ -87,8 +87,8 @@
87
87
  "author": "Tangle Network",
88
88
  "license": "MIT",
89
89
  "tangleRelease": {
90
- "sourceSha": "ed56ae52f27b83fa319df031bf81b17d3dd23013",
91
- "mergedAt": "2026-12-04T03:49:57-08:00"
90
+ "sourceSha": "c50c0bd912cffa27ffd3614f0a477fc7220df851",
91
+ "mergedAt": "2026-12-04T04:00:50-08:00"
92
92
  },
93
93
  "scripts": {
94
94
  "build": "tsdown",