@tangle-network/sandbox-cli 0.22.0-develop.20260814044321.7b71e30 → 0.22.0-develop.20260814062836.bb3da78

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 +3 -3
package/dist/index.mjs CHANGED
@@ -122,7 +122,7 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
122
122
  }
123
123
  }
124
124
  }`}}function Pn(e){return{anthropic:`Anthropic Messages API (Claude)`,openai:`OpenAI Chat Completions (function calling)`,"vercel-ai":`Vercel AI SDK (generateText / streamText)`,mastra:`Mastra agent framework`,"mcp-local":`Local MCP server bridge (stdio)`,"claude-desktop":`Claude Desktop config (uses local MCP)`,cursor:`Cursor config (uses local MCP)`,zed:`Zed config (uses local MCP)`}[e]}function Fn(){return new t(`connect`).description(`Print a copy-paste SDK integration snippet for one of: ${Mn.join(`, `)} (to stream a local agent's telemetry to Intelligence, see 'tangle connect')`).argument(`<framework>`,Mn.join(` | `)).option(`-i, --sandbox <id>`,`Sandbox ID to embed in the snippet`,`<SANDBOX_ID>`).option(`-s, --session <id>`,`Session ID to embed in the snippet`,`default`).action((e,t)=>{Mn.includes(e)||(console.error(a.red(`unknown framework: ${e}`),`\nsupported: ${Mn.join(`, `)}`),process.exit(2));let n=e;process.stdout.write(a.cyan(`# ${Pn(n)}\n\n`)),process.stdout.write(`${Nn(n,t.sandbox,t.session)}\n`)})}async function In(e){let{Writable:t}=await import(`node:stream`),n=await import(`node:readline`),r=!1,i=new t({write(e,t,n){r||process.stdout.write(e,t),n()}}),a=n.createInterface({input:process.stdin,output:i,terminal:!0});return process.stdout.write(e),r=!0,await new Promise(e=>{a.question(``,t=>{r=!1,a.close(),process.stdout.write(`
125
- `),e(t.trim())})})}async function V(e){let t=(await import(`node:readline`)).createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(n=>{t.question(e,e=>{t.close(),n(e.trim().toLowerCase())})});return n===`y`||n===`yes`}async function H(e,t){let n=(await import(`node:readline`)).createInterface({input:process.stdin,output:process.stdout}),r=t?` [${t}]`:``;return await new Promise(t=>{n.question(`${e}${r}: `,e=>{n.close(),t(e.trim())})})||t||``}async function Ln(){if(process.stdin.isTTY)throw Error(`Cannot read secret from stdin when stdin is a TTY`);let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(e).toString(`utf8`).replace(/\r?\n$/,``)}function Rn(){let e=new t(`profile`).description(`Create, inspect, and validate portable agent profiles`);return e.command(`create [output]`).description(`Create a profile — interactively (a wizard), or fully via flags`).option(`--name <name>`,`Profile name (when set, skips the wizard)`).option(`--description <text>`,`Profile description`).option(`--model <model>`,`Model (provider/model)`).option(`--system-prompt <text>`,`System prompt`).option(`--skills <ref...>`,`Skill refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--tools <ref...>`,`Tool refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--harness <name>`,`Harness hint shown in the run command`).option(`--json`,`Print the profile as JSON instead of writing a file`).action(async(e,t)=>{try{let n=t.name,r=t.description,i=t.harness,a=t.model,o=t.systemPrompt,s=t.skills??[],c=t.tools??[];if(!n&&process.stdin.isTTY&&(n=await H(`Profile name`,`my-agent`),r=await H(`Description (optional)`)||void 0,i=await H(`Harness`,`claude-code`)||void 0,a=await H(`Model (optional, provider/model)`)||void 0,o=await H(`System prompt (optional)`)||void 0,s=await zn(`Skill ref (local path or github:..., blank to finish)`),c=await zn(`Tool ref (blank to finish)`)),!n)throw Error(process.stdin.isTTY?`Profile name is required.`:"`agent profile create` needs at least --name in a non-interactive shell (no TTY to prompt). Pass --name <name> (and optionally --model/--skills/--tools/--system-prompt).");let l=Be({model:a,systemPrompt:o,skills:s,tools:c}),u={...n?{name:n}:{},...r?{description:r}:{},...l??{}};if(t.json){D(u);return}let d=e??`agent-profile.json`;f(d,`${JSON.stringify(u,null,2)}\n`),j(`Wrote ${d}`),j(`Run it: tangle agent prompt <box> --profile ${d}${i?` --harness ${i}`:``}`)}catch(e){L(e,t.json)}}),e.command(`show <source>`).description(`Load and print a profile (local path, https URL, or github:owner/repo/path[@ref])`).action(async e=>{try{D(await Ve(e))}catch(e){L(e,!0)}}),e.command(`validate <source>`).description(`Check a profile loads and is a well-formed object`).action(async e=>{try{let t=await Ve(e);j(`OK — "${typeof t.name==`string`?t.name:`(unnamed)`}" loaded as a valid profile object`)}catch(e){L(e)}}),e}async function zn(e){let t=[];for(;;){let n=await H(e);if(!n)break;t.push(n)}return t}function Bn(e){return([process.env.SANDBOX_WEB_URL,process.env.TANGLE_SANDBOX_WEB_URL].map(e=>e?.trim()).find(e=>!!e)??e).replace(/\/+$/,``)}function Vn(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(a.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(a.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({ ... }).`);return}console.error(a.red(`✗ ${e.error&&e.error.length>0?e.error:t}`))}function Hn(e,t){return process.exitCode=1,t&&D({status:`awaiting_question`,needsInput:e}),`Agent is awaiting an answer (questionId: ${e.questionId??`unknown`}). Re-run with --interactive to answer, or answer via box.session(<id>).answer({ ... }).`}function Un(e){let t=e.part;if(t?.type===`text`)return t.text??t.content??void 0}function Wn(e){return e.finalText??e.response??e.output??e.content??e.text??void 0}function Gn(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??``}catch{return String(e)}}function Kn(e,t=0){if(t>6||typeof e!=`object`||!e)return;let n=e,r=n.approval;if(r&&typeof r.id==`string`)return r.id;for(let e of Object.values(n)){let n=Kn(e,t+1);if(n)return n}}function qn(e){let t=e?.toolInvocations;if(!Array.isArray(t))return;let n=t.find(e=>e?.isError===!0);if(n){if(Gn(n.result).includes(`HUB_APPROVAL_REQUIRED`)){let e=Kn(n.result);return e?`Blocked on hub approval — approve with: tangle hub approvals approve ${e}`:"Blocked on hub approval — approve the pending request (`tangle hub approvals`) then re-run."}return`Tool "${n.toolName??`unknown`}" failed`}}function Jn(e){if(e.sawError){console.error(a.red(`✗ ${e.errorMsg??`Agent run failed`}`)),process.exitCode=1;return}let t=Date.now()-e.startedAt,n=e.tokenUsage,r=[`${t}ms`,n?.inputTokens===void 0?void 0:`${n.inputTokens} in`,n?.outputTokens===void 0?void 0:`${n.outputTokens} out`].filter(e=>!!e);console.log(a.green(`✓ Done`),a.dim(`(${r.join(`, `)})`))}async function Yn(e,t){let n=``,r=!1,i,a,o,s=e=>{if(e.startsWith(n)){let t=e.slice(n.length);t&&process.stdout.write(t)}else process.stdout.write(e);n=e};try{for await(let t of e){switch(t.type){case`token`:{let e=t.data?.value;typeof e==`string`&&(process.stdout.write(e),n+=e);break}case`message.part.updated`:{let e=Un(t.data);typeof e==`string`&&e.length>0&&s(e);break}case`raw`:break;case`result`:a=t.data;break;case`question`:{let e=t.data;o={questionId:e.questionId,questions:e.questions};break}case`error`:r=!0,i=t.data.message??JSON.stringify(t.data);break}if(o)break}}catch(e){r=!0,i=e instanceof Error?e.message:String(e)}if(o)return{awaitingQuestion:o,printed:n.length};if(n.length===0&&a){let e=Wn(a);typeof e==`string`&&e.length>0&&(process.stdout.write(e),n=e)}if(!r){let e=qn(a);e&&(r=!0,i=e)}return{outcome:{sawError:r,errorMsg:i,startedAt:t,tokenUsage:a?.tokenUsage},resultData:a,printed:n.length}}function Xn(e){let t=en(e??[]);if(t.length!==0)return{profile:{connections:t}}}async function Zn(e){let t=en(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 R({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||j(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||j(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function Qn(e){!e.connection||e.connection.length===0||(e.connection=await $t(e.connection,()=>R({hubKey:e.hubKey})))}async function $n(e,t){let n=process.stdin,r=process.stdout,i=null,a=!1,o=!1,s,c=new Promise(e=>{s=e}),l=()=>{try{n.setRawMode(!1)}catch{}n.pause()},u=()=>{a||(a=!0,l(),n.off(`data`,p),process.off(`SIGWINCH`,f),process.off(`SIGINT`,d),process.off(`SIGTERM`,d),process.off(`exit`,l),s())},d=e=>{(i?.close()??Promise.resolve()).finally(()=>{u(),process.exit(e===`SIGTERM`?143:130)})},f=()=>{i?.isOpen&&i.resize(r.columns||80,r.rows||24)},p=e=>{if(!i)return;let t=e.indexOf(29);if(t===-1){i.write(e);return}t>0&&i.write(e.subarray(0,t)),i.close().finally(u)};if(i=await e.attach({cols:r.columns||80,rows:r.rows||24,handlers:{onData:e=>{r.write(Buffer.from(e.buffer,e.byteOffset,e.byteLength))},onExit:e=>{o=!0;let t=e.exitCode===void 0?``:` (code ${e.exitCode})`;r.write(`\r\n[interactive session exited${t}]\r\n`),i?.close().finally(u)},onError:e=>{r.write(`\r\n[terminal stream error: ${e.message}]\r\n`)},onClose:()=>u()}}),n.setRawMode(!0),n.resume(),n.on(`data`,p),process.on(`SIGWINCH`,f),process.on(`SIGINT`,d),process.on(`SIGTERM`,d),process.on(`exit`,l),await c,console.log(),o){j(`Interactive session ended.`);return}j(`Detached — the session keeps running.`),N({"Watch & drive":t})}function er(){let e=new t(`agent`).description(`Interact with AI agent`);return e.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>.").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`,`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, amp, hermes). Defaults to the sandbox's configured backend. The box ships all harnesses, 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>`.",Qt,[]).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`).option(`--json`,`Output as JSON`).option(`--api-key <key>`,`API key`).option(`--base-url <url>`,`API base URL`).action(async(e,t,n)=>{try{let r=t===void 0?e:t,o=t===void 0?At(n.box):e,s=C({apiKey:n.apiKey,baseUrl:n.baseUrl}),c=T(s);if(n.interactive){let e=[n.profile?`--profile`:null,n.skills?.length?`--skills`:null,n.tools?.length?`--tools`:null,n.systemPrompt?`--system-prompt`:null,n.connection?.length?`--connection`:null,n.allowWrites?`--allow-writes`:null].filter(e=>e!==null);if(e.length>0)throw Error(`${e.join(`, `)} ${e.length===1?`is`:`are`} not supported with --interactive: the interactive harness launches its own TUI and is configured by --harness/--model. Drop --interactive to run with a profile, or bake the agent into the box with \`tangle backend configure\`.`)}let l=await Xe({profileSource:n.profile,systemPrompt:n.systemPrompt,skills:n.skills,tools:n.tools});await Qn(n);let u=Xn(n.connection);n.allowWrites&&await Zn(n);let d=l||u?{...l??{},...u?.profile??{}}:void 0,f=n.harness,p=d||f||n.model?{...f?{type:f}:{},...d?{profile:d}:{},...n.model?{model:{model:n.model}}:{}}:void 0,m=await z(c,s,o);if(m=await B(m),n.interactive){let e=n.session??`int-${i()}`,t=f??(await m.backend.status()).type,a=m.session(e).interactive(),c=M(`Starting interactive ${t} session...`);c.start();let l;try{l=await a.start({harness:t,...n.model?{model:n.model}:{}})}finally{c.stop()}try{await a.sendPrompt(r)}catch(e){throw await a.stop().catch(()=>void 0),e}let u=`${Bn(s.baseUrl)}/dashboard/sandbox/${encodeURIComponent(o)}?interactive=${encodeURIComponent(l.sessionId)}`;if(n.json){D({sessionId:l.sessionId,harness:l.harness,streamUrl:l.streamUrl,webUrl:u});return}j(`Interactive ${l.harness} session started — prompt sent.`),console.log(),N({"Watch & drive":u,Session:l.sessionId}),console.log(),j(`Open the link to watch the agent and type to take over. Send more prompts with --session ${l.sessionId} --interactive.`),process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&(console.log(),j(`Attaching to the live session — press Ctrl-] to detach.`),await $n(a,u));return}if(n.stream){j(`Streaming response...`),console.log();let e=Date.now(),t=await Yn(m.streamPrompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...p?{backend:p}:{}}),e);if(`awaitingQuestion`in t){t.printed>0&&console.log();let e=Hn(t.awaitingQuestion,n.json);n.json||console.error(a.yellow(`⚠ ${e}`));return}t.printed>0&&console.log(),Jn(t.outcome)}else{let e=M(`Processing prompt...`);e.start();let t=await m.prompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...p?{backend:p}:{}});e.stop(),n.json?(D(t),t.success===!1&&(process.exitCode=1)):t.success===!1?Vn(t,`Agent prompt failed`):(console.log(t.response),console.log(),N({Duration:`${t.durationMs}ms`,"Input Tokens":t.usage?.inputTokens,"Output Tokens":t.usage?.outputTokens}))}}catch(e){L(e,n.json)}}),e.addCommand(Fn()),e.addCommand(Rn()),e}async function tr(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 rr(n);throw n.status===401||n.status===403?new re(e||`Invalid API key`):n.status>=500?new oe(e||`Sandbox API returned an unexpected error`,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,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof re||e instanceof oe||e instanceof ce?e:e instanceof Error&&e.name===`AbortError`?new ce(t,`Timed out validating credentials against ${n}`):e instanceof Error&&!(e instanceof TypeError)?e:new g(`Failed to reach ${n}`,nr(e))}}function nr(e){return e instanceof Error?e:void 0}async function rr(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 ir(e){if(!or(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 ar(e){let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),i=await import(`node:http`),a=r(32).toString(`hex`),o=null,s=null,c=new Promise((e,t)=>{o=e,s=t}),l=i.createServer((e,t)=>{try{let n=ir({hostHeader:e.headers.host,requestUrl:e.url,expectedState:a});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(dr(`State mismatch — refusing login`)),s?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(dr(n.reason)),s?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(dr(null)),s?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(dr(null)),o?.(n.token);return}}catch(e){s?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{l.once(`error`,t),l.listen(0,`127.0.0.1`,()=>e())});try{let r=l.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let i=new URL(`http://127.0.0.1:${r.port}/callback`);i.searchParams.set(`state`,a);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,i.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let s=await lr(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:s});let u=await cr({baseUrl:n,grantToken:await sr(c,t),timeoutMs:t});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{await new Promise((e,t)=>{l.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function or(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 sr(e,t){return await new Promise((n,r)=>{let i=setTimeout(()=>{r(new ce(t,`Timed out waiting for browser login to complete`))},t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}async function cr(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.timeout(e.timeoutMs)}).catch(t=>{throw new g(`Failed to reach ${e.baseUrl}`,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 lr(e){let{spawn:t}=await import(`node:child_process`),n=process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`cmd`,`/c`,`start`,``,e]:[`xdg-open`,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 ur(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function dr(e){return`<!doctype html>
125
+ `),e(t.trim())})})}async function V(e){let t=(await import(`node:readline`)).createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(n=>{t.question(e,e=>{t.close(),n(e.trim().toLowerCase())})});return n===`y`||n===`yes`}async function H(e,t){let n=(await import(`node:readline`)).createInterface({input:process.stdin,output:process.stdout}),r=t?` [${t}]`:``;return await new Promise(t=>{n.question(`${e}${r}: `,e=>{n.close(),t(e.trim())})})||t||``}async function Ln(){if(process.stdin.isTTY)throw Error(`Cannot read secret from stdin when stdin is a TTY`);let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(e).toString(`utf8`).replace(/\r?\n$/,``)}function Rn(){let e=new t(`profile`).description(`Create, inspect, and validate portable agent profiles`);return e.command(`create [output]`).description(`Create a profile — interactively (a wizard), or fully via flags`).option(`--name <name>`,`Profile name (when set, skips the wizard)`).option(`--description <text>`,`Profile description`).option(`--model <model>`,`Model (provider/model)`).option(`--system-prompt <text>`,`System prompt`).option(`--skills <ref...>`,`Skill refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--tools <ref...>`,`Tool refs: local path or github:<owner>/<repo>/<path>[@<ref>]`).option(`--harness <name>`,`Harness hint shown in the run command`).option(`--json`,`Print the profile as JSON instead of writing a file`).action(async(e,t)=>{try{let n=t.name,r=t.description,i=t.harness,a=t.model,o=t.systemPrompt,s=t.skills??[],c=t.tools??[];if(!n&&process.stdin.isTTY&&(n=await H(`Profile name`,`my-agent`),r=await H(`Description (optional)`)||void 0,i=await H(`Harness`,`claude-code`)||void 0,a=await H(`Model (optional, provider/model)`)||void 0,o=await H(`System prompt (optional)`)||void 0,s=await zn(`Skill ref (local path or github:..., blank to finish)`),c=await zn(`Tool ref (blank to finish)`)),!n)throw Error(process.stdin.isTTY?`Profile name is required.`:"`agent profile create` needs at least --name in a non-interactive shell (no TTY to prompt). Pass --name <name> (and optionally --model/--skills/--tools/--system-prompt).");let l=Be({model:a,systemPrompt:o,skills:s,tools:c}),u={...n?{name:n}:{},...r?{description:r}:{},...l??{}};if(t.json){D(u);return}let d=e??`agent-profile.json`;f(d,`${JSON.stringify(u,null,2)}\n`),j(`Wrote ${d}`),j(`Run it: tangle agent prompt <box> --profile ${d}${i?` --harness ${i}`:``}`)}catch(e){L(e,t.json)}}),e.command(`show <source>`).description(`Load and print a profile (local path, https URL, or github:owner/repo/path[@ref])`).action(async e=>{try{D(await Ve(e))}catch(e){L(e,!0)}}),e.command(`validate <source>`).description(`Check a profile loads and is a well-formed object`).action(async e=>{try{let t=await Ve(e);j(`OK — "${typeof t.name==`string`?t.name:`(unnamed)`}" loaded as a valid profile object`)}catch(e){L(e)}}),e}async function zn(e){let t=[];for(;;){let n=await H(e);if(!n)break;t.push(n)}return t}function Bn(e){return([process.env.SANDBOX_WEB_URL,process.env.TANGLE_SANDBOX_WEB_URL].map(e=>e?.trim()).find(e=>!!e)??e).replace(/\/+$/,``)}function Vn(e,t){if(process.exitCode=1,e.status===`blocked_on_approval`){console.error(a.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(a.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}console.error(a.red(`✗ ${e.error&&e.error.length>0?e.error:t}`))}function Hn(e,t){return process.exitCode=1,t&&D({status:`awaiting_question`,needsInput:e}),`Agent is awaiting an answer (questionId: ${e.questionId??`unknown`}). Re-run with --interactive to answer, or answer via box.session(<id>).answer(<questionId>, { ... }).`}function Un(e){let t=e.part;if(t?.type===`text`)return t.text??t.content??void 0}function Wn(e){return e.finalText??e.response??e.output??e.content??e.text??void 0}function Gn(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??``}catch{return String(e)}}function Kn(e,t=0){if(t>6||typeof e!=`object`||!e)return;let n=e,r=n.approval;if(r&&typeof r.id==`string`)return r.id;for(let e of Object.values(n)){let n=Kn(e,t+1);if(n)return n}}function qn(e){let t=e?.toolInvocations;if(!Array.isArray(t))return;let n=t.find(e=>e?.isError===!0);if(n){if(Gn(n.result).includes(`HUB_APPROVAL_REQUIRED`)){let e=Kn(n.result);return e?`Blocked on hub approval — approve with: tangle hub approvals approve ${e}`:"Blocked on hub approval — approve the pending request (`tangle hub approvals`) then re-run."}return`Tool "${n.toolName??`unknown`}" failed`}}function Jn(e){if(e.sawError){console.error(a.red(`✗ ${e.errorMsg??`Agent run failed`}`)),process.exitCode=1;return}let t=Date.now()-e.startedAt,n=e.tokenUsage,r=[`${t}ms`,n?.inputTokens===void 0?void 0:`${n.inputTokens} in`,n?.outputTokens===void 0?void 0:`${n.outputTokens} out`].filter(e=>!!e);console.log(a.green(`✓ Done`),a.dim(`(${r.join(`, `)})`))}async function Yn(e,t){let n=``,r=!1,i,a,o,s=e=>{if(e.startsWith(n)){let t=e.slice(n.length);t&&process.stdout.write(t)}else process.stdout.write(e);n=e};try{for await(let t of e){switch(t.type){case`token`:{let e=t.data?.value;typeof e==`string`&&(process.stdout.write(e),n+=e);break}case`message.part.updated`:{let e=Un(t.data);typeof e==`string`&&e.length>0&&s(e);break}case`raw`:break;case`result`:a=t.data;break;case`question`:{let e=t.data;o={questionId:e.questionId,questions:e.questions};break}case`error`:r=!0,i=t.data.message??JSON.stringify(t.data);break}if(o)break}}catch(e){r=!0,i=e instanceof Error?e.message:String(e)}if(o)return{awaitingQuestion:o,printed:n.length};if(n.length===0&&a){let e=Wn(a);typeof e==`string`&&e.length>0&&(process.stdout.write(e),n=e)}if(!r){let e=qn(a);e&&(r=!0,i=e)}return{outcome:{sawError:r,errorMsg:i,startedAt:t,tokenUsage:a?.tokenUsage},resultData:a,printed:n.length}}function Xn(e){let t=en(e??[]);if(t.length!==0)return{profile:{connections:t}}}async function Zn(e){let t=en(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 R({hubKey:e.hubKey});for(let r of t){let t=await n.permissions.allowWrites(r.connectionId);e.json||j(`Allowed ${t.writeActions} write action${t.writeActions===1?``:`s`} for connection ${r.connectionId} (${t.granted} newly granted).`)}e.json||j(`Revert anytime: ${t.map(e=>`tangle hub permissions revert-writes --connection ${e.connectionId}`).join(` · `)}`)}async function Qn(e){!e.connection||e.connection.length===0||(e.connection=await $t(e.connection,()=>R({hubKey:e.hubKey})))}async function $n(e,t){let n=process.stdin,r=process.stdout,i=null,a=!1,o=!1,s,c=new Promise(e=>{s=e}),l=()=>{try{n.setRawMode(!1)}catch{}n.pause()},u=()=>{a||(a=!0,l(),n.off(`data`,p),process.off(`SIGWINCH`,f),process.off(`SIGINT`,d),process.off(`SIGTERM`,d),process.off(`exit`,l),s())},d=e=>{(i?.close()??Promise.resolve()).finally(()=>{u(),process.exit(e===`SIGTERM`?143:130)})},f=()=>{i?.isOpen&&i.resize(r.columns||80,r.rows||24)},p=e=>{if(!i)return;let t=e.indexOf(29);if(t===-1){i.write(e);return}t>0&&i.write(e.subarray(0,t)),i.close().finally(u)};if(i=await e.attach({cols:r.columns||80,rows:r.rows||24,handlers:{onData:e=>{r.write(Buffer.from(e.buffer,e.byteOffset,e.byteLength))},onExit:e=>{o=!0;let t=e.exitCode===void 0?``:` (code ${e.exitCode})`;r.write(`\r\n[interactive session exited${t}]\r\n`),i?.close().finally(u)},onError:e=>{r.write(`\r\n[terminal stream error: ${e.message}]\r\n`)},onClose:()=>u()}}),n.setRawMode(!0),n.resume(),n.on(`data`,p),process.on(`SIGWINCH`,f),process.on(`SIGINT`,d),process.on(`SIGTERM`,d),process.on(`exit`,l),await c,console.log(),o){j(`Interactive session ended.`);return}j(`Detached — the session keeps running.`),N({"Watch & drive":t})}function er(){let e=new t(`agent`).description(`Interact with AI agent`);return e.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>.").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`,`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, amp, hermes). Defaults to the sandbox's configured backend. The box ships all harnesses, 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>`.",Qt,[]).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`).option(`--json`,`Output as JSON`).option(`--api-key <key>`,`API key`).option(`--base-url <url>`,`API base URL`).action(async(e,t,n)=>{try{let r=t===void 0?e:t,o=t===void 0?At(n.box):e,s=C({apiKey:n.apiKey,baseUrl:n.baseUrl}),c=T(s);if(n.interactive){let e=[n.profile?`--profile`:null,n.skills?.length?`--skills`:null,n.tools?.length?`--tools`:null,n.systemPrompt?`--system-prompt`:null,n.connection?.length?`--connection`:null,n.allowWrites?`--allow-writes`:null].filter(e=>e!==null);if(e.length>0)throw Error(`${e.join(`, `)} ${e.length===1?`is`:`are`} not supported with --interactive: the interactive harness launches its own TUI and is configured by --harness/--model. Drop --interactive to run with a profile, or bake the agent into the box with \`tangle backend configure\`.`)}let l=await Xe({profileSource:n.profile,systemPrompt:n.systemPrompt,skills:n.skills,tools:n.tools});await Qn(n);let u=Xn(n.connection);n.allowWrites&&await Zn(n);let d=l||u?{...l??{},...u?.profile??{}}:void 0,f=n.harness,p=d||f||n.model?{...f?{type:f}:{},...d?{profile:d}:{},...n.model?{model:{model:n.model}}:{}}:void 0,m=await z(c,s,o);if(m=await B(m),n.interactive){let e=n.session??`int-${i()}`,t=f??(await m.backend.status()).type,a=m.session(e).interactive(),c=M(`Starting interactive ${t} session...`);c.start();let l;try{l=await a.start({harness:t,...n.model?{model:n.model}:{}})}finally{c.stop()}try{await a.sendPrompt(r)}catch(e){throw await a.stop().catch(()=>void 0),e}let u=`${Bn(s.baseUrl)}/dashboard/sandbox/${encodeURIComponent(o)}?interactive=${encodeURIComponent(l.sessionId)}`;if(n.json){D({sessionId:l.sessionId,harness:l.harness,streamUrl:l.streamUrl,webUrl:u});return}j(`Interactive ${l.harness} session started — prompt sent.`),console.log(),N({"Watch & drive":u,Session:l.sessionId}),console.log(),j(`Open the link to watch the agent and type to take over. Send more prompts with --session ${l.sessionId} --interactive.`),process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&(console.log(),j(`Attaching to the live session — press Ctrl-] to detach.`),await $n(a,u));return}if(n.stream){j(`Streaming response...`),console.log();let e=Date.now(),t=await Yn(m.streamPrompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...p?{backend:p}:{}}),e);if(`awaitingQuestion`in t){t.printed>0&&console.log();let e=Hn(t.awaitingQuestion,n.json);n.json||console.error(a.yellow(`⚠ ${e}`));return}t.printed>0&&console.log(),Jn(t.outcome)}else{let e=M(`Processing prompt...`);e.start();let t=await m.prompt(r,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10),...p?{backend:p}:{}});e.stop(),n.json?(D(t),t.success===!1&&(process.exitCode=1)):t.success===!1?Vn(t,`Agent prompt failed`):(console.log(t.response),console.log(),N({Duration:`${t.durationMs}ms`,"Input Tokens":t.usage?.inputTokens,"Output Tokens":t.usage?.outputTokens}))}}catch(e){L(e,n.json)}}),e.addCommand(Fn()),e.addCommand(Rn()),e}async function tr(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 rr(n);throw n.status===401||n.status===403?new re(e||`Invalid API key`):n.status>=500?new oe(e||`Sandbox API returned an unexpected error`,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,email:i.data.email,name:i.data.name,tier:i.data.tier,createdAt:i.data.created_at}}catch(e){throw e instanceof re||e instanceof oe||e instanceof ce?e:e instanceof Error&&e.name===`AbortError`?new ce(t,`Timed out validating credentials against ${n}`):e instanceof Error&&!(e instanceof TypeError)?e:new g(`Failed to reach ${n}`,nr(e))}}function nr(e){return e instanceof Error?e:void 0}async function rr(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 ir(e){if(!or(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 ar(e){let t=e.timeoutMs??12e4,n=e.baseUrl.replace(/\/$/,``),i=await import(`node:http`),a=r(32).toString(`hex`),o=null,s=null,c=new Promise((e,t)=>{o=e,s=t}),l=i.createServer((e,t)=>{try{let n=ir({hostHeader:e.headers.host,requestUrl:e.url,expectedState:a});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(dr(`State mismatch — refusing login`)),s?.(Error(`Browser login state mismatch — refusing potentially hijacked callback`));return;case`error`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(dr(n.reason)),s?.(Error(`Browser login failed: ${n.reason}`));return;case`missing-token`:t.writeHead(400,{"content-type":`text/html; charset=utf-8`}),t.end(dr(null)),s?.(Error(`Browser login did not return a grant token`));return;case`ok`:t.writeHead(200,{"content-type":`text/html; charset=utf-8`}),t.end(dr(null)),o?.(n.token);return}}catch(e){s?.(e instanceof Error?e:Error(`Browser login callback failed`))}});await new Promise((e,t)=>{l.once(`error`,t),l.listen(0,`127.0.0.1`,()=>e())});try{let r=l.address();if(!r||typeof r==`string`)throw Error(`Failed to bind local callback server`);let i=new URL(`http://127.0.0.1:${r.port}/callback`);i.searchParams.set(`state`,a);let o=new URL(`${n}/auth/cli/login`);o.searchParams.set(`callback_url`,i.toString()),e.provider&&o.searchParams.set(`provider`,e.provider);let s=await lr(o.toString());e.onLoginUrl?.({loginUrl:o.toString(),browserOpened:s});let u=await cr({baseUrl:n,grantToken:await sr(c,t),timeoutMs:t});return{apiKey:u.apiKey,email:u.email,name:u.name,tier:u.tier}}finally{await new Promise((e,t)=>{l.close(n=>{if(n){t(n);return}e()})}).catch(()=>void 0)}}function or(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 sr(e,t){return await new Promise((n,r)=>{let i=setTimeout(()=>{r(new ce(t,`Timed out waiting for browser login to complete`))},t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}async function cr(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.timeout(e.timeoutMs)}).catch(t=>{throw new g(`Failed to reach ${e.baseUrl}`,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 lr(e){let{spawn:t}=await import(`node:child_process`),n=process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`cmd`,`/c`,`start`,``,e]:[`xdg-open`,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 ur(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function dr(e){return`<!doctype html>
126
126
  <html lang="en">
127
127
  <head>
128
128
  <meta charset="utf-8" />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.22.0-develop.20260814044321.7b71e30",
3
+ "version": "0.22.0-develop.20260814062836.bb3da78",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,8 +24,8 @@
24
24
  "dotenv": "17.2.3",
25
25
  "ora": "^9.4.0",
26
26
  "ws": "^8.20.0",
27
- "@tangle-network/hub-sdk": "0.22.0-develop.20260814044321.7b71e30",
28
- "@tangle-network/sandbox": "0.22.0-develop.20260814044321.7b71e30"
27
+ "@tangle-network/hub-sdk": "0.22.0-develop.20260814062836.bb3da78",
28
+ "@tangle-network/sandbox": "0.22.0-develop.20260814062836.bb3da78"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "25.6.0",