@tangle-network/sandbox-cli 0.23.17 → 0.23.18

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 +1 -1
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -126,7 +126,7 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
126
126
  `))},d=e=>{t&&(process.stderr.write(`${o?`
127
127
  `:``}${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(`
128
128
  `)&&u(`
129
- `),u(t);l.set(e,t)};try{for await(let t of e)switch(a.observe(t),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=zr(t.data);e&&f(e);let n=Br(t.data);n&&!c.has(n.call)&&(c.add(n.call),d(n.line));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=Vr(i);typeof e==`string`&&u(e)}return{outcome:{result:a.finish(),tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{}}}function Ur(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function Wr(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(j.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(j.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(j.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(j.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(j.red(`✗ ${Kr(e.error)??(e.error||t)}`))}const Gr={model_not_allowed:`Fix the field the message names and send the request again.`};function Kr(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=Gr[i];return`The model router refused this ${a?`${a} `:``}turn (${i}): ${r}${o?` ${o}`:``}`}async function qr(e,t,n,r){if(n.errorCode!==`TIMEOUT`)return;let i=n.executionId,a=We(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=Me(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 ${We(e.id)} 'continue' --session ${a} --timeout ${r*2}`}}function Jr(e,t){if(!e.result.success){Wr(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(j.green(`✓ Done`),j.dim(`(${a.join(`, `)})`))}function Yr(e){let t=Yn(e??[]);if(t.length!==0)return{profile:{connections:t}}}function Xr(e,t,n){if(!Ut(e)||Vt.has(e))return;let r=`Harness "${e}" takes no opening prompt, so it has no interactive session; run the task headless.`;throw new z(`USAGE_INVALID`,r,r,`tangle agent prompt ${t?`${We(t)} `:``}${We(n)} --harness ${e}`)}function Zr(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:ze(o),initialPrompt:a};return{...s,run:Le({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function Qr(e){let t=Yn(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 q({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||l(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||l(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function $r(e){!e.connection||e.connection.length===0||(e.connection=await Jn(e.connection,()=>q({hubKey:e.hubKey})))}function ei(){let t=new N(`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>`.",qn,[]).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,o=rr(r.timeout,`--timeout`,`ms`),{context:c,client:u}=G(r),d=n===void 0?r.box||process.env.TANGLE_SANDBOX||void 0:t,p=d?void 0:H().currentSandbox,m=d??p,h=await Yt({profileSource:r.profile,systemPrompt:r.systemPrompt,skills:r.skills,tools:r.tools});await $r(r);let g=Yr(r.connection);r.allowWrites&&await Qr(r);let _=h||g?{...h,...g?.profile}:void 0,v=r.harness;r.interactive&&v&&Xr(v,m,a);let y=_||v||r.model?{...v?{type:v}:{},..._?{profile:_}:{},...r.model?{model:{model:r.model}}:{}}:void 0,b=d?await J(u,c,d,{toRun:!0}):await wr(u,c,p);if(b=await Y(b),r.interactive){let t=r.session??`int-${je()}`,n=v??(await b.backend.status()).type;Xr(n,b.id,a);let i=Zr(b.id,t,n,_,r.model,a),o=b.session(t).interactive(),u=f(`Starting interactive ${n} session...`);u.start();let d;try{d=await o.start(i)}finally{u.stop()}let p=d.ref.preparationReceipt.harness,m=d.state===`running`?d.streamUrl:void 0,h=`${Ur(c.baseUrl)}/dashboard/sandbox/${encodeURIComponent(b.id)}?interactive=${encodeURIComponent(d.ref.run.sessionId)}`;if(r.json){e({state:d.state,sessionId:d.ref.run.sessionId,harness:p,...m?{streamUrl:m}:{},webUrl:h});return}let g=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,y=()=>{s({"Watch & drive":h}),console.log()};if(l(`Interactive ${p} session ${d.state}.`),console.log(),d.state===`running`&&!g&&y(),d.state===`exited`){l(`The initial prompt completed with reason: ${d.reason}.`);return}if(!g){l(`Open the link to watch the agent and type to take over.`);return}l(`Attaching to the live session — press Ctrl-] to detach.`),await er(o,Number.parseInt(r.timeout,10)),y();return}if(r.stream){r.json||(l(`Streaming response...`),console.log());let t=Date.now(),n=performance.now(),s=await Hr(b.streamPrompt(a,{sessionId:r.session,timeoutMs:o,...y?{backend:y}:{}}),!r.json,v);r.json?(e({...s.outcome.result,...s.response?{response:s.response}:{},...s.outcome.tokenUsage?{tokenUsage:s.outcome.tokenUsage}:{},durationMs:Date.now()-t}),s.outcome.result.success||(process.exitCode=1)):(s.printed>0&&console.log(),Jr(s.outcome,{commandStartedAt:i,agentStartedAt:n}))}else{let t=f(`Processing prompt...`);t.start();let n=r.session??`prompt-${je()}`,i=await b.prompt(a,{sessionId:n,timeoutMs:o,...y?{backend:y}:{}}),c=await qr(b,n,i,o);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);Wr(i,`Agent prompt failed`),c&&console.error(c.note),c?.next&&console.error(`Continue it: ${c.next}`)}else console.log(i.response),console.log(),s({Duration:`${i.durationMs}ms`,"Input Tokens":i.usage?.inputTokens,"Output Tokens":i.usage?.outputTokens})}}),t.addCommand(jr()),t.addCommand(Lr()),t}async function ti(e){let t=e.timeoutMs??1e4,n=e.baseUrl.replace(/\/$/,``),r=`${n}/v1/account/me`;try{let n=await fetch(r,{headers:{Accept:`application/json`,Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)});if(!n.ok){let e=await ri(n);throw n.status===401||n.status===403?new A(e||`Invalid API key`):n.status>=500?new ce(e||`Sandbox API returned an unexpected error`,{status:n.status}):Error(e||`Credential validation failed with status ${n.status}`)}let i=await n.json();if(!i.success||!i.data)throw Error(`Sandbox API returned an invalid account response`);return{customerId:i.data.customer_id,billingOwnerId:typeof i.data.billing_owner_id==`string`?i.data.billing_owner_id:void 0,apiKeyId:typeof i.data.api_key_id==`string`||i.data.api_key_id===null?i.data.api_key_id:void 0,billingDelegationAuthorized:typeof i.data.billing_delegation_authorized==`boolean`?i.data.billing_delegation_authorized:void 0,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof A||e instanceof ce||e instanceof ue?e:e instanceof Error&&e.name===`AbortError`?new ue(`Timed out validating credentials against ${n}`,{timeoutMs:t}):e instanceof Error&&!(e instanceof TypeError)?e:new te(`Failed to reach ${n}`,{cause:ni(e)})}}function ni(e){return e instanceof Error?e:void 0}async function ri(e){let t=await e.text();if(t)try{let e=JSON.parse(t);return e.error?.message??e.message??t}catch{return t}}function ii(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function ai(e,t=process.platform){return t===`win32`?I():e}function oi(e,t=process.platform){if(t===`darwin`)return[`open`,e];if(t!==`win32`)return[`xdg-open`,e];let n=process.env.SystemRoot??`C:\\Windows`;return[De.join(n,`System32`,`rundll32.exe`),`url.dll,FileProtocolHandler`,e]}function si(e){if(!li(e.hostHeader))return{kind:`host-mismatch`};let t;try{t=new URL(e.requestUrl??`/`,`http://127.0.0.1`)}catch{return{kind:`not-found`}}if(t.pathname!==`/callback`)return{kind:`not-found`};if(t.searchParams.get(`state`)!==e.expectedState)return{kind:`state-mismatch`};let n=t.searchParams.get(`error`);if(n)return{kind:`error`,reason:n};let r=t.searchParams.get(`grant_token`);return r?{kind:`ok`,token:r}:{kind:`missing-token`}}async function ci(e){e.signal?.throwIfAborted();let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),r=await import(`node:http`),i=Ae(32).toString(`hex`),a=null,o=null,s=new Promise((e,t)=>{a=e,o=t}),c=r.createServer((e,t)=>{try{let n=si({hostHeader:e.headers.host,requestUrl:e.url,expectedState:i});switch(n.kind){case`host-mismatch`:t.writeHead(421,{"content-type":`text/plain; charset=utf-8`}),t.end(`Misdirected request`);return;case`not-found`:t.writeHead(404,{"content-type":`text/plain; charset=utf-8`}),t.end(`Not found`);return;case`state-mismatch`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(`State mismatch — refusing login`)),o?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(n.reason)),o?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(null)),o?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(pi(null)),a?.(n.token);return}}catch(e){o?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{c.once(`error`,t),c.listen(0,`127.0.0.1`,()=>e())});try{let r=c.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let a=new URL(`http://127.0.0.1:${r.port}/callback`);a.searchParams.set(`state`,i);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,a.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let l=await fi(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:l});let u=await di({baseUrl:n,grantToken:await ui(s,t,e.signal),timeoutMs:t,signal:e.signal});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{e.signal?.aborted&&c.closeAllConnections(),await new Promise((e,t)=>{c.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function li(e){if(!e)return!1;let t=e.toLowerCase().match(/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/);if(!t)return!1;let n=t[1];return n===`127.0.0.1`||n===`localhost`||n===`[::1]`}async function ui(e,t,n){let r=new AbortController;try{return await Promise.race([e,Me(t,void 0,{signal:AbortSignal.any([r.signal,...n?[n]:[]])}).then(()=>{throw new ue(`Timed out waiting for browser login to complete`,{timeoutMs:t})})])}finally{r.abort()}}async function di(e){let t=await fetch(`${e.baseUrl}/auth/cli/exchange`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({grant_token:e.grantToken}),signal:AbortSignal.any([AbortSignal.timeout(e.timeoutMs),...e.signal?[e.signal]:[]])}).catch(t=>{throw new te(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.success||!n.data?.api_key)throw Error(n?.error?.message||`Failed to exchange browser login grant`);return{apiKey:n.data.api_key,email:n.data.email,name:n.data.name,tier:n.data.tier}}async function fi(e){let{spawn:t}=await import(`node:child_process`),n=oi(e);return await new Promise(e=>{let r=t(n[0],n.slice(1),{detached:!0,stdio:`ignore`});r.once(`error`,()=>e(!1)),r.once(`spawn`,()=>{r.unref(),e(!0)})})}function pi(e){return`<!doctype html>
129
+ `),u(t);l.set(e,t)};try{for await(let t of e)switch(a.observe(t),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=zr(t.data);e&&f(e);let n=Br(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=Vr(i);typeof e==`string`&&u(e)}return{outcome:{result:a.finish(),tokenUsage:i?.tokenUsage},resultData:i,printed:r.length,...r.length>0?{response:r}:{}}}function Ur(e){return(process.env.TANGLE_SANDBOX_WEB_URL?.trim()||e).replace(/\/+$/,``)}function Wr(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(j.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(j.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(j.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(j.yellow(`⚠ Agent is awaiting a plan decision.`)),console.error(`Approve or reject the pending plan before continuing.`);return}console.error(j.red(`✗ ${Kr(e.error)??(e.error||t)}`))}const Gr={model_not_allowed:`Fix the field the message names and send the request again.`};function Kr(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=Gr[i];return`The model router refused this ${a?`${a} `:``}turn (${i}): ${r}${o?` ${o}`:``}`}async function qr(e,t,n,r){if(n.errorCode!==`TIMEOUT`)return;let i=n.executionId,a=We(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=Me(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 ${We(e.id)} 'continue' --session ${a} --timeout ${r*2}`}}function Jr(e,t){if(!e.result.success){Wr(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(j.green(`✓ Done`),j.dim(`(${a.join(`, `)})`))}function Yr(e){let t=Yn(e??[]);if(t.length!==0)return{profile:{connections:t}}}function Xr(e,t,n){if(!Ut(e)||Vt.has(e))return;let r=`Harness "${e}" takes no opening prompt, so it has no interactive session; run the task headless.`;throw new z(`USAGE_INVALID`,r,r,`tangle agent prompt ${t?`${We(t)} `:``}${We(n)} --harness ${e}`)}function Zr(e,t,n,r,i,a){let o={...r??{},harness:n,...i?{model:{...r?.model??{},default:i}}:{}},s={profile:o,requestedProfileDigest:ze(o),initialPrompt:a};return{...s,run:Le({provider:`tangle-sandbox`,environmentId:e,sessionId:t,executionId:`interactive-execution-${t}`},s)}}async function Qr(e){let t=Yn(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 q({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||l(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||l(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function $r(e){!e.connection||e.connection.length===0||(e.connection=await Jn(e.connection,()=>q({hubKey:e.hubKey})))}function ei(){let t=new N(`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>`.",qn,[]).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,o=rr(r.timeout,`--timeout`,`ms`),{context:c,client:u}=G(r),d=n===void 0?r.box||process.env.TANGLE_SANDBOX||void 0:t,p=d?void 0:H().currentSandbox,m=d??p,h=await Yt({profileSource:r.profile,systemPrompt:r.systemPrompt,skills:r.skills,tools:r.tools});await $r(r);let g=Yr(r.connection);r.allowWrites&&await Qr(r);let _=h||g?{...h,...g?.profile}:void 0,v=r.harness;r.interactive&&v&&Xr(v,m,a);let y=_||v||r.model?{...v?{type:v}:{},..._?{profile:_}:{},...r.model?{model:{model:r.model}}:{}}:void 0,b=d?await J(u,c,d,{toRun:!0}):await wr(u,c,p);if(b=await Y(b),r.interactive){let t=r.session??`int-${je()}`,n=v??(await b.backend.status()).type;Xr(n,b.id,a);let i=Zr(b.id,t,n,_,r.model,a),o=b.session(t).interactive(),u=f(`Starting interactive ${n} session...`);u.start();let d;try{d=await o.start(i)}finally{u.stop()}let p=d.ref.preparationReceipt.harness,m=d.state===`running`?d.streamUrl:void 0,h=`${Ur(c.baseUrl)}/dashboard/sandbox/${encodeURIComponent(b.id)}?interactive=${encodeURIComponent(d.ref.run.sessionId)}`;if(r.json){e({state:d.state,sessionId:d.ref.run.sessionId,harness:p,...m?{streamUrl:m}:{},webUrl:h});return}let g=process.stdin.isTTY===!0&&process.stdout.isTTY===!0,y=()=>{s({"Watch & drive":h}),console.log()};if(l(`Interactive ${p} session ${d.state}.`),console.log(),d.state===`running`&&!g&&y(),d.state===`exited`){l(`The initial prompt completed with reason: ${d.reason}.`);return}if(!g){l(`Open the link to watch the agent and type to take over.`);return}l(`Attaching to the live session — press Ctrl-] to detach.`),await er(o,Number.parseInt(r.timeout,10)),y();return}if(r.stream){r.json||(l(`Streaming response...`),console.log());let t=Date.now(),n=performance.now(),s=await Hr(b.streamPrompt(a,{sessionId:r.session,timeoutMs:o,...y?{backend:y}:{}}),!r.json,v);r.json?(e({...s.outcome.result,...s.response?{response:s.response}:{},...s.outcome.tokenUsage?{tokenUsage:s.outcome.tokenUsage}:{},durationMs:Date.now()-t}),s.outcome.result.success||(process.exitCode=1)):(s.printed>0&&console.log(),Jr(s.outcome,{commandStartedAt:i,agentStartedAt:n}))}else{let t=f(`Processing prompt...`);t.start();let n=r.session??`prompt-${je()}`,i=await b.prompt(a,{sessionId:n,timeoutMs:o,...y?{backend:y}:{}}),c=await qr(b,n,i,o);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);Wr(i,`Agent prompt failed`),c&&console.error(c.note),c?.next&&console.error(`Continue it: ${c.next}`)}else console.log(i.response),console.log(),s({Duration:`${i.durationMs}ms`,"Input Tokens":i.usage?.inputTokens,"Output Tokens":i.usage?.outputTokens})}}),t.addCommand(jr()),t.addCommand(Lr()),t}async function ti(e){let t=e.timeoutMs??1e4,n=e.baseUrl.replace(/\/$/,``),r=`${n}/v1/account/me`;try{let n=await fetch(r,{headers:{Accept:`application/json`,Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)});if(!n.ok){let e=await ri(n);throw n.status===401||n.status===403?new A(e||`Invalid API key`):n.status>=500?new ce(e||`Sandbox API returned an unexpected error`,{status:n.status}):Error(e||`Credential validation failed with status ${n.status}`)}let i=await n.json();if(!i.success||!i.data)throw Error(`Sandbox API returned an invalid account response`);return{customerId:i.data.customer_id,billingOwnerId:typeof i.data.billing_owner_id==`string`?i.data.billing_owner_id:void 0,apiKeyId:typeof i.data.api_key_id==`string`||i.data.api_key_id===null?i.data.api_key_id:void 0,billingDelegationAuthorized:typeof i.data.billing_delegation_authorized==`boolean`?i.data.billing_delegation_authorized:void 0,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof A||e instanceof ce||e instanceof ue?e:e instanceof Error&&e.name===`AbortError`?new ue(`Timed out validating credentials against ${n}`,{timeoutMs:t}):e instanceof Error&&!(e instanceof TypeError)?e:new te(`Failed to reach ${n}`,{cause:ni(e)})}}function ni(e){return e instanceof Error?e:void 0}async function ri(e){let t=await e.text();if(t)try{let e=JSON.parse(t);return e.error?.message??e.message??t}catch{return t}}function ii(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function ai(e,t=process.platform){return t===`win32`?I():e}function oi(e,t=process.platform){if(t===`darwin`)return[`open`,e];if(t!==`win32`)return[`xdg-open`,e];let n=process.env.SystemRoot??`C:\\Windows`;return[De.join(n,`System32`,`rundll32.exe`),`url.dll,FileProtocolHandler`,e]}function si(e){if(!li(e.hostHeader))return{kind:`host-mismatch`};let t;try{t=new URL(e.requestUrl??`/`,`http://127.0.0.1`)}catch{return{kind:`not-found`}}if(t.pathname!==`/callback`)return{kind:`not-found`};if(t.searchParams.get(`state`)!==e.expectedState)return{kind:`state-mismatch`};let n=t.searchParams.get(`error`);if(n)return{kind:`error`,reason:n};let r=t.searchParams.get(`grant_token`);return r?{kind:`ok`,token:r}:{kind:`missing-token`}}async function ci(e){e.signal?.throwIfAborted();let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),r=await import(`node:http`),i=Ae(32).toString(`hex`),a=null,o=null,s=new Promise((e,t)=>{a=e,o=t}),c=r.createServer((e,t)=>{try{let n=si({hostHeader:e.headers.host,requestUrl:e.url,expectedState:i});switch(n.kind){case`host-mismatch`:t.writeHead(421,{"content-type":`text/plain; charset=utf-8`}),t.end(`Misdirected request`);return;case`not-found`:t.writeHead(404,{"content-type":`text/plain; charset=utf-8`}),t.end(`Not found`);return;case`state-mismatch`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(`State mismatch — refusing login`)),o?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(n.reason)),o?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(pi(null)),o?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(pi(null)),a?.(n.token);return}}catch(e){o?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{c.once(`error`,t),c.listen(0,`127.0.0.1`,()=>e())});try{let r=c.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let a=new URL(`http://127.0.0.1:${r.port}/callback`);a.searchParams.set(`state`,i);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,a.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let l=await fi(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:l});let u=await di({baseUrl:n,grantToken:await ui(s,t,e.signal),timeoutMs:t,signal:e.signal});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{e.signal?.aborted&&c.closeAllConnections(),await new Promise((e,t)=>{c.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function li(e){if(!e)return!1;let t=e.toLowerCase().match(/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/);if(!t)return!1;let n=t[1];return n===`127.0.0.1`||n===`localhost`||n===`[::1]`}async function ui(e,t,n){let r=new AbortController;try{return await Promise.race([e,Me(t,void 0,{signal:AbortSignal.any([r.signal,...n?[n]:[]])}).then(()=>{throw new ue(`Timed out waiting for browser login to complete`,{timeoutMs:t})})])}finally{r.abort()}}async function di(e){let t=await fetch(`${e.baseUrl}/auth/cli/exchange`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({grant_token:e.grantToken}),signal:AbortSignal.any([AbortSignal.timeout(e.timeoutMs),...e.signal?[e.signal]:[]])}).catch(t=>{throw new te(`Failed to reach ${e.baseUrl}`,{cause:t instanceof Error?t:void 0})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.success||!n.data?.api_key)throw Error(n?.error?.message||`Failed to exchange browser login grant`);return{apiKey:n.data.api_key,email:n.data.email,name:n.data.name,tier:n.data.tier}}async function fi(e){let{spawn:t}=await import(`node:child_process`),n=oi(e);return await new Promise(e=>{let r=t(n[0],n.slice(1),{detached:!0,stdio:`ignore`});r.once(`error`,()=>e(!1)),r.once(`spawn`,()=>{r.unref(),e(!0)})})}function pi(e){return`<!doctype html>
130
130
  <html lang="en">
131
131
  <head>
132
132
  <meta charset="utf-8" />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.23.17",
3
+ "version": "0.23.18",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "engines": {
@@ -60,9 +60,9 @@
60
60
  "typescript": "^6.0.3",
61
61
  "vitest": "^4.1.12",
62
62
  "@repo/shared": "0.0.0",
63
- "@tangle-network/sdk-session-persistence": "0.7.0",
63
+ "@tangle-network/runtime-contracts": "0.20.0",
64
64
  "@repo/knowledge-host": "0.0.0",
65
- "@tangle-network/runtime-contracts": "0.20.0"
65
+ "@tangle-network/sdk-session-persistence": "0.7.0"
66
66
  },
67
67
  "publishConfig": {
68
68
  "access": "public",
@@ -86,8 +86,8 @@
86
86
  "author": "Tangle Network",
87
87
  "license": "MIT",
88
88
  "tangleRelease": {
89
- "sourceSha": "5eba40d4387108715563fbcea3aa4337391131ab",
90
- "mergedAt": "2026-11-16T15:38:34-08:00"
89
+ "sourceSha": "1492dce054e8bb4820bcfb0139e1014c5f4b59de",
90
+ "mergedAt": "2026-11-16T15:40:22-08:00"
91
91
  },
92
92
  "scripts": {
93
93
  "build": "tsdown",