@tangle-network/sandbox-cli 0.23.141 → 0.23.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -147,7 +147,7 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
|
|
|
147
147
|
`)?e:`${e}\n`}function qa(e){let t=E(He(),`.codex`,`config.toml`),{contents:n,changed:i}=Wa(wa(t),{endpoint:e.endpoint,apiKey:e.apiKey});if(!e.write){console.log(n.trimEnd());return}if(!i){r(`${t} already has the Tangle [otel] block — nothing to change.`);return}Ta(t,n),r(`Merged the Tangle [otel] block into ${t}.`),l("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."),l(`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 Ja(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`${Sa[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 Ya(e){let t=Date.now()+e.timeoutSeconds*1e3,n=3e3,r=Math.min(e.timeoutSeconds*1e3,1e4),i=f(`Checking whether content is flowing…`);i.start();let a;try{for(;;){try{a=await zi({endpoint:e.endpoint,apiKey:e.apiKey,timeoutMs:r})}catch(e){if(Date.now()>=t)throw e;await Ne(n);continue}if(a.contentSeen||Date.now()>=t)break;await Ne(n)}}finally{i.stop()}if(!a)throw Error(`onboarding status check returned no result`);Xa(a,e.agent),a.contentSeen||(process.exitCode=1)}function Xa(e,t){if(e.contentSeen){r(`Content flowing — Tangle Intelligence can analyze this feed.`),s({"Last seen":e.lastSeenAt??`just now`,Window:`${e.windowDays}d`});return}if(e.tracesSeen){c(`Metadata-only — traces are arriving but carry no content. You missed a content gate.`);let n=t?[t]:Object.keys(e.byAgent).filter(Ca),r=n.length>0?n:xa;for(let n of r){let r=e.byAgent[n];(t||!r||r.tracesSeen&&!r.contentSeen)&&l(Ja(n))}return}c(`No traces yet for your tenant. Run your agent once on a real task, then re-run --verify.`),t&&l(Ja(t))}function Za(e,t){let n=e??process.env.TANGLE_INTELLIGENCE_API_KEY??rn(`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 Qa(e){let t=q(e);if(/^https?:\/\/[A-Za-z0-9.-]+(:\d+)?(\/[A-Za-z0-9._~%/-]*)?$/.test(t))return t;throw new A(`USAGE_INVALID`,`--endpoint ${JSON.stringify(e)} is not a plain http(s) URL`,`letters, digits and . _ ~ % / - only, after the scheme`,`tangle connect --help`)}function $a(){return new D(`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`,wi).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=Qa(t.endpoint);if(t.run){if((e?to(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 ao({endpoint:n,apiKey:Za(t.apiKey,n),opencodeUrl:t.opencodeUrl});return}if(t.verify){await Ya({endpoint:n,apiKey:Za(t.apiKey,n),agent:e?to(e):void 0,timeoutSeconds:B(t.timeout,`--timeout`)});return}let r=e?to(e):await no(),i=t.inlineKey?Za(t.apiKey,n):void 0;r===`claude-code`?await Ra({endpoint:n,apiKey:i,projectKey:t.project,rcPath:t.rc,write:t.write!==!1,content:La(t.content),format:Ia(t.format)}):r===`codex`?qa({endpoint:n,apiKey:i,projectKey:t.project,write:t.write!==!1}):r===`opencode`?ro({endpoint:n}):io(r,{endpoint:n}),console.log(),l(`Run your agent on a real task, then verify content is flowing: tangle connect ${r} --verify`)})}function eo(){return new D(`opencode-exporter`).description(`Export a running OpenCode's content to Tangle Intelligence (standalone shim)`).option(`--endpoint <url>`,`OTLP endpoint base`,wi).option(`--opencode-url <url>`,`OpenCode server base URL (or set OPENCODE_BASE_URL)`).action(async e=>{let t=Qa(e.endpoint);await ao({endpoint:t,apiKey:Za(e.apiKey,t),opencodeUrl:e.opencodeUrl})})}function to(e){if(Ca(e))return e;throw Error(`Unknown agent '${e}'. Choose one of: ${xa.join(`, `)}`)}async function no(){if(!process.stdin.isTTY)throw Error(`Specify an agent: tangle connect <${xa.join(`|`)}>`);console.log(`Which coding agent are you connecting?`),xa.forEach((e,t)=>{console.log(` ${t+1}) ${Sa[e]} (${e})`)});let e=await K(`Enter a number or name`,`1`);return xa[Number.parseInt(e,10)-1]||to(e.trim())}function ro(e){let t=q(e.endpoint);c(`OpenCode has no native OTel exporter, so a standalone install emits nothing without a shim.`),console.log(),s({"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(),l(`Start OpenCode in server mode ('opencode serve'), then in another terminal run: tangle connect opencode --run`),l(`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`),l(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting the exporter.`)}function io(e,t){let n=q(t.endpoint),r=Sa[e];c(`${r} has no native OTel exporter, so a standalone install emits nothing without instrumentation.`),console.log(),s({"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(),l(`Label this project so Tangle rolls up + automates per-project: export OTEL_RESOURCE_ATTRIBUTES=tangle.subject.key=my-project before starting ${r}.`),l(`Verify content is flowing: tangle connect ${e} --verify`)}async function ao(e){let t=ga(e.opencodeUrl),n=new AbortController,i=()=>n.abort();process.on(`SIGINT`,i),process.on(`SIGTERM`,i),l(`Subscribing to OpenCode at ${t} — exporting content to Tangle.`),l(`Run OpenCode tasks now. Press Ctrl-C to stop.`),console.log();let a=0,o;try{o=await ba({endpoint:e.endpoint,apiKey:e.apiKey,opencodeBaseUrl:t,signal:n.signal,onExport:({eventType:e,records:t})=>{a+=t,l(`exported ${t} record(s) from ${e} (total ${a})`)}})}catch(e){if(e instanceof va){let{recordsExported:t,contentEventsExported:n}=e.partial;console.log(),c(`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){c(`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}r(`Exported ${o.recordsExported} content record(s) from ${o.contentEventsExported} event(s).`),l(`Verify it landed: tangle connect opencode --verify`)}function oo(){let t=new D(`environments`).alias(`env`).description(`Manage sandbox environments`);return t.command(`list`).alias(`ls`).description(`List available environments`).action(async t=>{let{client:n}=z(t),r=f(`Fetching environments...`);t.json||r.start();let a=await n.environments.list();r.stop(),t.json?e(a):a.length===0?console.log(`No environments found`):i([`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}=z(n),i=f(`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 so=O.string().trim().toLowerCase().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/),co=O.string().trim().toLowerCase().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/),lo=O.object({kind:co,count:O.number().int().positive().default(1),vramGb:O.number().positive().optional()}).strict();O.object({command:O.string().min(1).max(8192),timeoutMs:O.number().int().positive().max(2147453647).optional(),env:O.record(O.string(),O.string()).optional(),cwd:O.string().min(1).max(2048).optional()}).strict(),O.object({refresh:O.enum([`true`,`false`]).optional(),acceleratorKind:co.optional(),acceleratorCount:O.coerce.number().pipe(lo.shape.count.unwrap()).optional(),acceleratorVramGb:O.coerce.number().positive().optional()}).strict(),O.object({maxSpendUsd:O.number().positive().max(1e4).optional(),maxLifetimeSeconds:O.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 uo=O.object({provider:so.optional(),image:O.string().min(1).max(512).optional(),env:O.record(O.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),O.string()).optional(),diskGb:O.number().int().positive().optional(),volumeGb:O.number().int().nonnegative().optional(),volumeMountPath:O.string().startsWith(`/`).max(2048).optional(),region:O.string().min(1).max(128).optional(),manifest:O.record(O.string(),O.unknown()).optional(),command:O.array(O.string().max(8192)).min(1).max(256).optional(),ports:O.array(O.number().int().min(1).max(65535)).max(32).optional(),endpoint:O.object({port:O.number().int().min(1).max(65535),healthPath:O.string().regex(/^\/(?![/\\])/).refine(e=>![`\r`,`
|
|
148
148
|
`,` `].some(t=>e.includes(t))).max(2048).optional()}).strict().optional(),allowSpot:O.boolean().optional(),maxHourlyUsd:O.number().positive().optional(),weights:O.object({manifestSha:O.string().regex(/^[a-f0-9]{64}$/),sizeBytes:O.number().int().positive().safe()}).strict().optional(),arms:O.array(O.unknown()).min(1).max(256).optional(),maxSpendUsd:O.number().positive().max(1e4),maxLifetimeSeconds:O.number().int().positive().max(1440*60),idleTimeoutSeconds:O.number().int().positive().optional()}).strict();uo.extend({accelerator:lo});const fo=lo,po=so;O.object({...uo.omit({env:!0}).shape,id:O.string(),projectRef:O.string(),ownerUserId:O.string(),productId:O.string().optional(),provider:po,providerLeaseId:O.string().optional(),providerInstanceType:O.string().optional(),endpointUrl:O.string().optional(),status:O.enum([`provisioning`,`ready`,`detaching`,`destroyed`,`failed`]),accelerator:fo,providerCostPerHourUsd:O.number().optional(),customerPricePerHourUsd:O.number().optional(),estimatedProviderCostUsd:O.number().optional(),estimatedCustomerCostUsd:O.number().optional(),providerSelection:O.object({strategy:O.enum([`explicit`,`cheapest`,`ranked`]),selectedProvider:po,requestedProvider:po.optional(),candidates:O.array(O.object({provider:po,accelerator:fo,providerInstanceType:O.string().optional(),region:O.string().optional(),pricingSource:O.enum([`live`,`configured`]).optional(),providerCostPerHourUsd:O.number(),customerPricePerHourUsd:O.number(),maxLifetimeSeconds:O.number(),estimatedProviderCostUsd:O.number(),estimatedCustomerCostUsd:O.number()})),rejected:O.array(O.object({provider:po,error:O.string()}))}).optional(),createdAt:O.string(),updatedAt:O.string(),readyAt:O.string().optional(),startedAt:O.string().optional(),lastUsedAt:O.string().optional(),destroyedAt:O.string().optional(),failure:O.string().optional(),billing:O.object({seconds:O.number(),providerCostUsd:O.number(),customerCostUsd:O.number(),providerCostPerHourUsd:O.number(),customerPricePerHourUsd:O.number(),startedAt:O.string(),stoppedAt:O.string()}).optional()});function mo(e){return{kind:xo(e.kind),count:e.count?B(e.count,`--accelerator-count`):1,...e.memory?{vramGb:Co(e.memory,`--accelerator-memory`)}:{}}}function ho(e,t,n){if(!t&&Object.values(e).some(Boolean))throw Error(n);return t?_o(e,`--gpu-`):void 0}function go(e){return{..._o(e,`--`),accelerator:mo({kind:e.acceleratorKind,count:e.acceleratorCount,memory:e.acceleratorMemory})}}function _o(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:So(n,`${t}provider`)}:{},...r?{image:r}:{},...i?{env:bo(i,`${t}env`,`env`)}:{},maxSpendUsd:Co(a,`${t}max-spend-usd`),maxLifetimeSeconds:V(o,`${t}max-lifetime`),...s?{idleTimeoutSeconds:V(s,`${t}idle-timeout`)}:{}}}function vo(e){return e.length===1?e[0]:e.map(Be).join(` `)}function yo(e){return{timeoutMs:e.timeout?V(String(e.timeout),`--timeout`,`ms`):void 0,env:e.env?bo(e.env,`--env`,`env`):void 0}}function bo(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 xo(e){let t=co.safeParse(e);if(t.success)return t.data;throw Error(`--accelerator-kind must contain only letters, numbers, dots, underscores, or hyphens`)}function So(e,t){let n=so.safeParse(e);if(n.success)return n.data;throw Error(`${t} must start with a letter and contain only letters, numbers, or hyphens`)}function Co(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 wo(){return new D(`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}=z(r),o=vo(n),s=bo(r.env??[],`--env`,`env`),c=V(r.timeout,`--timeout`,`ms`,0),l=f(`Executing: ${o}`);r.json||l.start();let u=await U(a,i,t,{toRun:!0});u=await W(u);let d=await u.exec(o,{cwd:r.cwd,env:Object.keys(s).length>0?s:void 0,timeoutMs:c});l.stop(),r.json?e(d):(d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr)),d.exitCode!==0&&(process.exitCode=d.exitCode)}catch(e){if(e instanceof w){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 N(Error(t,{cause:e}))}N(e)}})}function To(n){n.command(`capabilities`).description(`List fleet drivers and their supported features`).action(async n=>{let{client:r}=z(n),i=f(`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}=z(n),i=f(`Fetching usage...`);i.start();let a=await r.fleets.usage(t);if(i.stop(),n.json)e(a);else if(s({"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(`
|
|
149
149
|
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}=z(n),i=f(`Estimating cost...`);i.start();let a=await r.fleets.cost(t);i.stop(),n.json?e(a):s({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 Eo(e){return[...e.entries()].map(([e,t])=>({machineId:e,sandboxId:t.id,status:t.status}))}function Do(n){n.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}=z(r),a=f(`Fetching fleet...`);a.start();let o=await i.fleets.list({fleetId:n,status:r.status});a.stop();let s=Eo(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}])}),n.command(`get <fleet-id>`).description(`Show one fleet's manifest (server record)`).action(async(n,r)=>{let{client:i}=z(r),a=f(`Fetching manifest...`);a.start();let o=await i.fleets.manifest(n);a.stop(),r.json?e(o):(s({"Fleet ID":o.fleetId??o.id,Machines:o.machines.length,"Workspace mode":o.workspace?.mode,"Workspace status":o.workspace?.status,"Max lifetime (s)":o.policy?.maxLifetimeSeconds,"Max spend (USD)":o.policy?.maxSpendUsd,Created:o.createdAt,Updated:o.updatedAt}),t(o.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}]))}),n.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,n)=>{let{client:i}=z(n),a=f(`Deleting fleet...`);a.start(),await i.fleets.delete(t,{continueOnError:n.continueOnError}),a.stop(),n.json?e({success:!0,fleetId:t}):r(`Fleet deleted: ${t}`)}),n.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}=z(n),i=f(`Reaping expired fleets...`);i.start();let a=await r.fleets.reapExpired({dryRun:n.dryRun});i.stop(),n.json?e(a):(s({"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}]))}),n.command(`reconcile`).description(`Drop fleet records whose underlying sandboxes vanished`).option(`--dry-run`,`Report orphans without removing them`).action(async n=>{let{client:r}=z(n),i=f(`Reconciling fleets...`);i.start();let a=await r.fleets.reconcile({dryRun:n.dryRun});i.stop(),n.json?e(a):(s({"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 Oo(e,t){let n=await Jn({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 ko(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 mr();if(t.length===0)throw Error(`${e.flagPrefix}-stdin received empty input on stdin`);return t}}function Ao(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 jo(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 Mo(e){return{maxLifetimeSeconds:V(e.lifetime,`--lifetime`),idleTimeoutSeconds:V(e.idleTimeout,`--idle-timeout`)}}function No(e,t){let n={};return e.cpu!==void 0&&(n.cpuCores=B(e.cpu,`--cpu`)),e.memory!==void 0&&(n.memoryMB=B(e.memory,`--memory`)),e.disk!==void 0&&(n.diskGB=B(e.disk,`--disk`)),t&&(n.accelerator=t),Object.keys(n).length>0?n:void 0}function Po(e){let t=e.split(`/`);return t.length>=2?{provider:t[0],model:t.slice(1).join(`/`)}:{model:e}}function Fo(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]=Io(r.join(`=`))}return t}function Io(e){try{return JSON.parse(e)}catch{return e}}function Lo(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`?B(e.gitDepth,`--git-depth`):void 0,sparse:Array.isArray(e.gitSparse)?e.gitSparse:void 0,auth:t?{token:t}:void 0}}}function Ro(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:zo(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 zo(e){if(e===`s3`||e===`gcs`||e===`r2`)return e;throw Error(`--storage-type must be one of s3, gcs, or r2`)}function Bo(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=x(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=Pe.parse(t);return n.length>0?n:void 0}function Vo(e){l(` Status: ${e.status}`),l(` Provider: ${e.provider}`),l(` GPU: ${e.accelerator.kind} x ${e.accelerator.count}`),e.customerPricePerHourUsd!==void 0&&l(` Customer price: $${e.customerPricePerHourUsd}/hr`),e.estimatedCustomerCostUsd!==void 0&&l(` Max estimate: $${e.estimatedCustomerCostUsd}`),e.billing&&(l(` Billed seconds: ${e.billing.seconds}`),l(` Customer cost: $${e.billing.customerCostUsd}`))}function Ho(e){e.result.stdout&&process.stdout.write(e.result.stdout),e.result.stderr&&process.stderr.write(e.result.stderr),l(`Exit code: ${e.result.exitCode}`)}function Uo(n){let i=n.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}=z(r),o=f(`Checking GPU providers...`);o.start();let s=await(await U(a,i,n)).gpu.providers(r.acceleratorKind?{accelerator:mo({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&&l(`${e.provider}: ${t}`)}s.usable.length===0&&l(`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,n)=>{let{context:i,client:a}=z(n),o=f(`Attaching GPU lease...`);o.start();let s=await(await U(a,i,t)).gpu.attach(go(n));o.stop(),n.json?e(s):(r(`GPU lease attached: ${s.id}`),Vo(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,n,i)=>{let a,o,s,c;try{let e=yo(i),{context:r,client:s}=z(i),c=await U(s,r,t),l=f(`Attaching GPU lease...`);l.start(),a=await c.gpu.attach(go(i)),l.stop();let u=f(`Running GPU command...`);u.start(),o=await c.gpu.exec(a.id,{command:vo(n),...e,cwd:i.cwd}),u.stop(),i.json||Ho(o)}catch(e){s=e}finally{if(a)try{let{context:e,client:n}=z(i);a=await(await U(n,e,t)).gpu.detach(a.id)}catch(e){c=e}}if(s){N(s),c&&N(c);return}if(c){N(c);return}i.json?e({lease:a,result:o}):a&&r(`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}=z(r),o=f(`Fetching GPU leases...`);o.start();let s=await(await U(a,i,n)).gpu.list();o.stop(),r.json?e(s):s.length===0?l(`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}=z(i),s=f(`Running GPU command...`);s.start();let c=await(await U(o,a,t)).gpu.exec(n,{command:vo(r),...yo(i),cwd:i.cwd});s.stop(),i.json?e(c):Ho(c)}),i.command(`detach <id-or-name> <lease-id>`).description(`Detach and destroy a GPU lease`).action(async(t,n,i)=>{let{context:a,client:o}=z(i),s=f(`Detaching GPU lease...`);s.start();let c=await(await U(o,a,t)).gpu.detach(n);s.stop(),i.json?e(c):(r(`GPU lease detached: ${c.id}`),Vo(c))})}function Wo(t,n){if(n){e(t);return}if(!t.id){t.kind===`snapshot`&&t.result?.snapshot?r(`Snapshot created: ${t.result.snapshot.snapshotId}`):r(`Sandbox ${t.sandboxId} stopped.`);return}r(`${t.kind===`snapshot`?`Snapshot`:`Stop`} of sandbox ${t.sandboxId} accepted.`),l(`Operation: ${t.id}`),l(`Status: ${t.statusUrl}`)}function Go(e){return`${e.name} (${e.id})`}async function Ko(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 Ko(e,t);let r=vn(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 qo(e,t){yn({id:e.id,name:e.name},t)}function Jo(e){bn(e)}async function Yo(e){if(e.explicitTeam&&e.personal)throw Error(`--team and --personal cannot be used together`);if(!e.personal)return e.explicitTeam?(await Ko(e.client,e.explicitTeam)).id:e.activeTeamId}async function Xo(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 Ko(e.client,e.explicitTeam)).id}`;if(e.activeTeamId)return`team:${e.activeTeamId}`}function Zo(e){if(!e)return e;let t={...e};for(let e of[`authToken`,`execToken`])t[e]!==void 0&&(t[e]=`[REDACTED]`);return t}function Qo(n){n.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,n)=>{let{context:i,client:a}=z(n),o=n.nonce===`auto`?ve():n.nonce,s=f(`Fetching TEE attestation...`);s.start();let c=await(await U(a,i,t)).getTeeAttestation(o?{attestationNonce:o}:void 0);s.stop(),n.json?e(c):(r(`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}`))}),n.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}=z(n),a=f(`Fetching sandboxes...`);a.start();let o=await Xo({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}])}),n.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}=z(n),a=f(`Fetching sandbox...`);a.start();let o=await U(i,r,t);if(a.stop(),n.profile){let e=o.getProfileProvenance?.();e?(l(`Agent profile provenance:`),l(` Base profile: ${e.base.name??`(inline)`} (${e.base.sha256.slice(0,12)}...)`),l(` Effective: ${e.effective.name??`(inline)`} (${e.effective.sha256.slice(0,12)}...)`),l(` Materialized: ${e.materializedAt}`),e.base.sha256!==e.effective.sha256&&l(` ⚠ Profile changed since creation (base ≠ effective)`)):l(`No profile materialized (bare sandbox). Create with --profile <name> to install one.`);return}n.json?e(o):u({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})}),n.command(`shapes`).description(`List the named sandbox sizes, the default, and this account's ceiling`).action(async n=>{let{client:r}=z(n),i=await r.shapes();if(n.json){e(i);return}let a=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:a(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}]),l(`Ceiling for this account: ${o(i.ceiling)}`)}),n.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 ke(`--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 G(`Delete sandbox ${e}? [y/N] `,`--force`)){l(`Cancelled.`);return}let{context:n,client:i}=z(t),a=f(`Deleting sandbox...`);a.start();let o=await sr(i,n,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.
|
|
150
|
-
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(),r(o===`already_absent`?`Sandbox ${e} was already gone.`:`Sandbox ${e} deleted.`)}),n.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:n,client:i}=z(t),a=f(`Stopping sandbox...`);a.start();let o=await U(i,n,e,{nameOnly:t.name});if(t.wait===!1){let e=await o.stop({wait:!1});a.stop(),Wo(e.info,!!t.json);return}await o.stop(),a.stop(),r(`Sandbox ${e} stopped.`)}),n.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 n=V(t.timeout,`--timeout`,`ms`),i=L({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:n}),a=R(i),o=f(`Resuming sandbox...`);o.start();let s=await U(a,i,e);await s.resume({timeoutMs:n}),t.wait&&(o.text=`Waiting for sandbox to start...`,await s.waitFor(`running`,{timeoutMs:n})),o.stop(),r(`Sandbox ${s.id} resumed.`)})}const $o=O.array(O.union([O.cidrv4(),O.cidrv6()])).min(1).max(100);O.strictObject({mode:O.enum([`open`,`strict`,`blocked`]),allowDomains:O.array(O.union([O.string().min(1).max(256),O.strictObject({domain:O.string().min(1).max(256),allowPrivateIps:$o})])).max(100).optional(),includeImplicitDomains:O.boolean().optional()});function es(e){return e===`sandbox`||e===`team`}const ts={mode:`strict`,includeImplicitDomains:!0};function ns(e,t){return e.mode!==`open`||es(t)?e:ts}const rs=e=>typeof e==`string`?e:e.domain;function is(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:{...ts,allowDomains:e}}}function as(e){let t=e.toJSON().egressRefusedProxySecretHosts??[];if(t.length===0)return;let n=t.join(` `);c(`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 os(e,t){for(let n=0;;n++){let r=await e.egress.get(),i=ns(r.policy,r.source);if(i.mode===`open`)return l(`Egress is open: every host is already reachable. Nothing changed.`),r;let a=i.mode===`strict`?i.allowDomains??[]:[],o=new Set(a.map(e=>rs(e).toLowerCase())),s=t.map(e=>e.toLowerCase()).filter(e=>!o.has(e));if(s.length===0)return r;let c={mode:`strict`,allowDomains:[...a,...new Set(s)],includeImplicitDomains:i.mode===`strict`&&i.includeImplicitDomains===!0};try{return await e.egress.update(c,{expectedUpdatedAt:r.updatedAt})}catch(e){if(n===0&&e.code===`CONFLICT`)continue;throw nr(e,`tangle sandbox egress --help`)}}}function ss(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}=z(n),a=await U(i,r,t),{policy:o,source:s}=n.allowDomain?await os(a,n.allowDomain):await a.egress.get(),c=ns(o,s);if(n.json){e({policy:c,source:s});return}l(`Egress: ${c.mode} (source ${s})`),c.mode===`strict`&&(l(` Allowed: ${(c.allowDomains??[]).map(rs).join(`, `)||`none`}`),l(` Default registries, Git hosts and model endpoints: ${c.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}=z(n),a=f(`Updating network configuration...`);a.start();let o=await U(i,r,t);a.stop();let s=await o.network.getConfig();n.json?e(s):(l(`Network Configuration:`),s.ports&&s.ports.length>0?l(` Exposed Ports: ${s.ports.join(`, `)}`):l(` 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,n)=>{let{context:i,client:a}=z(n),o=Number.parseInt(n.port,10);if(Number.isNaN(o)||o<1||o>65535)throw Error(`Port must be a number between 1 and 65535`);let s=f(`Exposing port ${o}...`);s.start();let c=await(await U(a,i,t)).network.exposePort(o);s.stop(),n.json?e({port:o,url:c}):(r(`Port ${o} exposed.`),l(` URL: ${c}`))}),t.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(t,n)=>{let{context:r,client:i}=z(n),a=f(`Fetching exposed URLs...`);a.start();let o=await(await U(i,r,t)).network.listUrls();if(a.stop(),n.json)e(o);else{let e=Object.entries(o);if(e.length===0)l(`No ports exposed.`);else{l(`Exposed Ports:`);for(let[t,n]of e)l(` ${t}: ${n}`)}}})}function cs(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>`,ds).addOption(fs()).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(`--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 ke(`--driver <type>`,`Run on Tangle network operators instead of the platform's hosts (--tee needs it)`).choices([`tangle`])).option(`--backend <type>`,`Backend agent type (${ie.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 ke(`--reasoning-effort <level>`,`Reasoning effort for the backend's model; overrides the profile's model.reasoningEffort`).choices(Fe)).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 ko({envVarName:t.gitTokenEnv,fromStdin:t.gitTokenStdin,flagPrefix:`--git-token`}),r=await ko({envVarName:t.storageSecretAccessKeyEnv,fromStdin:t.storageSecretAccessKeyStdin,flagPrefix:`--storage-secret-access-key`}),i=await ko({envVarName:t.backendApiKeyEnv,fromStdin:t.backendApiKeyStdin,flagPrefix:`--backend-api-key`}),a=Ao({secret:t.cliAuth,backend:t.backend,apiKeyGiven:i!==void 0}),o;if(t.profileStdin){let e=await mr(`--profile-stdin`,`the AgentProfile JSON`);try{o=JSON.parse(e)}catch{N(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(x(e,`utf8`))}catch(t){N(ms(e,t));return}else try{o=await Oo(e,t)}catch(t){N(ms(e,t));return}}o=hs(o,t.reasoningEffort);let s=L({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:t.timeout?V(t.timeout,`--timeout`,`ms`):void 0}),c=R(s),l=f(`Creating sandbox...`);l.start();let u=await Yo({client:c,explicitTeam:t.team,personal:t.personal,activeTeamId:s.activeTeamId}),d=bo(t.env??[],`--env`,`env`),p=t.metadata?Fo(t.metadata):void 0,m=Lo(t,n),h=Ro(t,r),g=t.acceleratorKind?mo({kind:String(t.acceleratorKind),count:String(t.acceleratorCount),memory:typeof t.acceleratorMemory==`string`?t.acceleratorMemory:void 0}):void 0,ee=ho({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},!!g,`Create-time GPU lease flags require --accelerator-kind`),_=t.driver?{type:`tangle`}:void 0,v=t.backend||t.backendModel||o?{...t.backend?{type:ye(t.backend)}:{},...o?{profile:o}:{},model:t.backendModel||i||a?{...t.backendModel?Po(t.backendModel):{},apiKey:i,...a?{cliAuth:a}:{}}:void 0}:void 0,y=jo(t.secret),te=a?[...new Set([...y??[],a.secretEnv])]:y,b=Bo(t.proxySecret),ne=No(t,g),re=t.sshKeyFile??(t.ssh&&!t.sshKey&&!t.sshKeys?.length?[ps()]:[]),S=[...t.sshKey?[t.sshKey]:[],...re.map(e=>x(e,`utf8`).trim())],ie={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||S.length>0||!!t.sshKeys?.length,sshPublicKeys:S.length>0?S:void 0,sshKeyIds:t.sshKeys,webTerminalEnabled:t.webTerminal,env:Object.keys(d).length>0?d:void 0,git:m,...ne?{resources:ne}:{},gpuLease:ee,...Mo(t),storage:h,fromSnapshot:t.fromSnapshot,publicTemplateId:t.publicTemplate,publicTemplateVersionId:t.publicTemplateVersion,teamId:u,...t.billingOwner?{billingOwnerId:t.billingOwner}:{},secrets:te,...b?{proxySecrets:b}:{},...is(t.allowDomain,u),metadata:p,driver:_,backend:v},C=t.tee?{tee:t.tee,sealed:t.sealed||void 0,attestationRefresh:t.attestationRefresh||t.attestationNonce===`auto`||void 0}:void 0,ae=C?await _e(c,{...ie,confidential:C,attestationNonce:t.attestationNonce??(t.attestationRefresh?`auto`:void 0),requireAttestation:t.requireAttestation??!0}):void 0,w=ae?.sandbox??await tr(c,ie);t.wait&&(l.text=`Waiting for sandbox to start...`,await w.waitFor(`running`,{timeoutMs:12e4}),await w.refresh()),l.stop();let oe=ls(w);t.json?e({id:w.id,name:w.name,active:oe.active,status:w.status,resources:w.resources,createdAt:w.createdAt,expiresAt:w.expiresAt,connection:Zo(w.connection),teamId:u,gpuLease:w.gpuLease,confidential:C,attestation:ae?.attestation,attestationNonce:ae?.attestationNonce}):us(w,oe.next,ie,{teamId:u,tee:C?.tee,proof:ae}),as(w)})}function ls(e){let t=Kt();return t||qt(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 us(e,t,n,i){r(`Sandbox created: ${e.id}`),u({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,r]of[[`Idle timeout (requested)`,n.idleTimeoutSeconds,900],[`Lifetime (requested)`,n.maxLifetimeSeconds,3600]])t&&t!==r&&console.log(`${e}: ${Rn(t)}`);i.teamId&&console.log(`Team: ${i.teamId}`),e.gpuLease&&(console.log(`GPU lease: ${e.gpuLease.id}`),Vo(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}`)),l(t)}const ds="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 fs(){return new ke(`--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(le)}function ps(){let e=[`id_ed25519`,`id_ecdsa`,`id_rsa`].map(e=>`${He()}/.ssh/${e}.pub`),t=e.find(e=>y(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 ms(e,t){return t instanceof A?t:Error(`--profile ${e}: ${t.message}`)}function hs(e,t){if(!t)return e;let n=e?.model??{};return{...e,model:{...n,reasoningEffort:t}}}function gs(e){if(e.spec){let t=JSON.parse(x(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=ys(e),n=bs(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=xs(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 _s(e){let{base:t,machines:n}=gs(e);return{...t,machines:n}}function vs(e){let{base:t,machines:n}=gs(e);return{...t,workers:n}}function ys(e){let t={};if(e.cpu&&(t.cpuCores=B(e.cpu,`--cpu`)),e.memory&&(t.memoryMB=B(e.memory,`--memory`)),e.disk&&(t.diskGB=B(e.disk,`--disk`)),e.acceleratorKind)t.accelerator=mo({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 bs(e,t){return ho({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 xs(e){let t={};return e.maxSpendUsd&&(t.maxSpendUsd=Number(e.maxSpendUsd)),e.maxLifetime&&(t.maxLifetimeSeconds=V(e.maxLifetime,`--max-lifetime`)),Object.keys(t).length>0?t:void 0}function Ss(n){n.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>`,ds).addOption(fs()).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 n=>{let{client:i}=z(n),a=f(`Creating fleet...`);a.start();let o=n.coordinator?await i.fleets.createWithCoordinator(vs(n)):await i.fleets.create(_s(n));a.stop();let s=Eo(o.machines);n.json?e({fleetId:o.fleetId,machines:s}):(r(`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 Cs(n){n.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}=z(i),o=f(`Dispatching command...`);o.start();let s=await(await a.fleets.list({fleetId:n})).dispatchExecDetailed(r,{machines:i.machine,cwd:i.cwd,timeoutMs:i.timeout?V(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)}),n.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,n)=>{let i=/^\d+$/.test(n.agents)?Number(n.agents):JSON.parse(x(n.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}=z(n);if(!!n.parentFleet!=!!n.parentAgent)throw Error(`--parent-fleet and --parent-agent go together`);let o=n.placement===`auto`||n.placement===`dedicated`?n.placement:{agentsPerSandbox:Number(n.placement)},c=n.maxSpendUsd?Number(n.maxSpendUsd):void 0,l=n.timeout?V(n.timeout,`--timeout`,`ms`):void 0,u=f(`Creating fleet...`);u.start();let d=Date.now(),p=await a.fleets.create({fleetId:n.fleetId,agents:i,placement:o,defaults:{...n.environment?{environment:n.environment}:{},...n.memory?{resources:{memoryMB:B(n.memory,`--memory`)}}:{},...n.model?{backend:{type:`opencode`,model:{model:n.model}}}:{}},...c===void 0?{}:{budgetUsd:c},...n.parentFleet?{parent:{fleetId:n.parentFleet,agentId:n.parentAgent}}:{}}),m=Date.now()-d;u.stop(),n.json||r(`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`&&!n.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{n.keep||await p.delete({continueOnError:!0})}n.json?e({fleetId:p.fleetId,createMs:m,sandboxes:p.machines.size,results:h,spend:g,deleted:!n.keep}):s({fleetId:p.fleetId,completed:h.filter(e=>e.status===`completed`).length,agents:h.length,spend:JSON.stringify(g),deleted:!n.keep}),h.some(e=>e.status!==`completed`)&&(process.exitCode=1)}),n.command(`cancel <fleet-id>`).description(`Interrupt every agent of a fleet and cancel its child fleets; sandboxes keep running`).action(async(t,n)=>{let{client:i}=z(n),a=await(await i.fleets.list({fleetId:t})).cancel();n.json?e({fleetId:t,...a}):r(`Fleet ${t}: interrupted ${a.interrupted} agents, cancelled ${a.children} child fleets`)})}const ws=[`list`,`create`,`delete`,`exec`,`prompt`,`read`,`write`];function Ts(e){if(!(!e||e.length===0)){for(let t of e)if(!ws.includes(t))throw Error(`Invalid token action '${t}'. Allowed: ${ws.join(`, `)}`);return e}}function Es(e){return e.length<=12?`****`:`${e.slice(0,6)}...${e.slice(-4)} (masked — use --json for full value)`}function Ds(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}=z(n),i=f(`Minting fleet token...`);i.start();let a=await r.fleets.createToken(t,{actions:Ts(n.action),ttlMinutes:n.ttlMinutes?B(n.ttlMinutes,`--ttl-minutes`):void 0});i.stop(),n.json?e(a):(s({"Fleet ID":a.fleetId,Token:Es(a.token),"Expires at":new Date(a.expiresAt).toISOString(),Actions:a.actions.join(`, `)}),console.log(`
|
|
150
|
+
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(),r(o===`already_absent`?`Sandbox ${e} was already gone.`:`Sandbox ${e} deleted.`)}),n.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:n,client:i}=z(t),a=f(`Stopping sandbox...`);a.start();let o=await U(i,n,e,{nameOnly:t.name});if(t.wait===!1){let e=await o.stop({wait:!1});a.stop(),Wo(e.info,!!t.json);return}await o.stop(),a.stop(),r(`Sandbox ${e} stopped.`)}),n.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 n=V(t.timeout,`--timeout`,`ms`),i=L({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:n}),a=R(i),o=f(`Resuming sandbox...`);o.start();let s=await U(a,i,e);await s.resume({timeoutMs:n}),t.wait&&(o.text=`Waiting for sandbox to start...`,await s.waitFor(`running`,{timeoutMs:n})),o.stop(),r(`Sandbox ${s.id} resumed.`)})}const $o=O.array(O.union([O.cidrv4(),O.cidrv6()])).min(1).max(100);O.strictObject({mode:O.enum([`open`,`strict`,`blocked`]),allowDomains:O.array(O.union([O.string().min(1).max(256),O.strictObject({domain:O.string().min(1).max(256),allowPrivateIps:$o})])).max(100).optional(),includeImplicitDomains:O.boolean().optional()});function es(e){return e===`sandbox`||e===`team`}const ts={mode:`strict`,includeImplicitDomains:!0};function ns(e,t){return e.mode!==`open`||es(t)?e:ts}const rs=e=>typeof e==`string`?e:e.domain;function is(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:{...ts,allowDomains:e}}}function as(e){let t=e.toJSON().egressRefusedProxySecretHosts??[];if(t.length===0)return;let n=t.join(` `);c(`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 os(e,t){for(let n=0;;n++){let r=await e.egress.get(),i=ns(r.policy,r.source);if(i.mode===`open`)return l(`Egress is open: every host is already reachable. Nothing changed.`),r;let a=i.mode===`strict`?i.allowDomains??[]:[],o=new Set(a.map(e=>rs(e).toLowerCase())),s=t.map(e=>e.toLowerCase()).filter(e=>!o.has(e));if(s.length===0)return r;let c={mode:`strict`,allowDomains:[...a,...new Set(s)],includeImplicitDomains:i.mode===`strict`&&i.includeImplicitDomains===!0};try{return await e.egress.update(c,{expectedUpdatedAt:r.updatedAt})}catch(e){if(n===0&&e.code===`CONFLICT`)continue;throw nr(e,`tangle sandbox egress --help`)}}}function ss(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}=z(n),a=await U(i,r,t),{policy:o,source:s}=n.allowDomain?await os(a,n.allowDomain):await a.egress.get(),c=ns(o,s);if(n.json){e({policy:c,source:s});return}l(`Egress: ${c.mode} (source ${s})`),c.mode===`strict`&&(l(` Allowed: ${(c.allowDomains??[]).map(rs).join(`, `)||`none`}`),l(` Default registries, Git hosts and model endpoints: ${c.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}=z(n),a=f(`Updating network configuration...`);a.start();let o=await U(i,r,t);a.stop();let s=await o.network.getConfig();n.json?e(s):(l(`Network Configuration:`),s.ports&&s.ports.length>0?l(` Exposed Ports: ${s.ports.join(`, `)}`):l(` 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,n)=>{let{context:i,client:a}=z(n),o=Number.parseInt(n.port,10);if(Number.isNaN(o)||o<1||o>65535)throw Error(`Port must be a number between 1 and 65535`);let s=f(`Exposing port ${o}...`);s.start();let c=await(await U(a,i,t)).network.exposePort(o);s.stop(),n.json?e({port:o,url:c}):(r(`Port ${o} exposed.`),l(` URL: ${c}`))}),t.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(t,n)=>{let{context:r,client:i}=z(n),a=f(`Fetching exposed URLs...`);a.start();let o=await(await U(i,r,t)).network.listUrls();if(a.stop(),n.json)e(o);else{let e=Object.entries(o);if(e.length===0)l(`No ports exposed.`);else{l(`Exposed Ports:`);for(let[t,n]of e)l(` ${t}: ${n}`)}}})}function cs(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>`,ds).addOption(fs()).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 ke(`--driver <type>`,`Run on Tangle network operators instead of the platform's hosts (--tee needs it)`).choices([`tangle`])).option(`--backend <type>`,`Backend agent type (${ie.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 ke(`--reasoning-effort <level>`,`Reasoning effort for the backend's model; overrides the profile's model.reasoningEffort`).choices(Fe)).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 ko({envVarName:t.gitTokenEnv,fromStdin:t.gitTokenStdin,flagPrefix:`--git-token`}),r=await ko({envVarName:t.storageSecretAccessKeyEnv,fromStdin:t.storageSecretAccessKeyStdin,flagPrefix:`--storage-secret-access-key`}),i=await ko({envVarName:t.backendApiKeyEnv,fromStdin:t.backendApiKeyStdin,flagPrefix:`--backend-api-key`}),a=Ao({secret:t.cliAuth,backend:t.backend,apiKeyGiven:i!==void 0}),o;if(t.profileStdin){let e=await mr(`--profile-stdin`,`the AgentProfile JSON`);try{o=JSON.parse(e)}catch{N(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(x(e,`utf8`))}catch(t){N(ms(e,t));return}else try{o=await Oo(e,t)}catch(t){N(ms(e,t));return}}o=hs(o,t.reasoningEffort);let s=L({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:t.timeout?V(t.timeout,`--timeout`,`ms`):void 0}),c=R(s),l=f(`Creating sandbox...`);l.start();let u=await Yo({client:c,explicitTeam:t.team,personal:t.personal,activeTeamId:s.activeTeamId}),d=bo(t.env??[],`--env`,`env`),p=t.metadata?Fo(t.metadata):void 0,m=Lo(t,n),h=Ro(t,r),g=t.acceleratorKind?mo({kind:String(t.acceleratorKind),count:String(t.acceleratorCount),memory:typeof t.acceleratorMemory==`string`?t.acceleratorMemory:void 0}):void 0,ee=ho({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},!!g,`Create-time GPU lease flags require --accelerator-kind`),_=t.driver?{type:`tangle`}:void 0,v=t.backend||t.backendModel||o?{...t.backend?{type:ye(t.backend)}:{},...o?{profile:o}:{},model:t.backendModel||i||a?{...t.backendModel?Po(t.backendModel):{},apiKey:i,...a?{cliAuth:a}:{}}:void 0}:void 0,y=jo(t.secret),te=a?[...new Set([...y??[],a.secretEnv])]:y,b=Bo(t.proxySecret),ne=No(t,g),re=t.sshKeyFile??(t.ssh&&!t.sshKey&&!t.sshKeys?.length?[ps()]:[]),S=[...t.sshKey?[t.sshKey]:[],...re.map(e=>x(e,`utf8`).trim())],ie={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||S.length>0||!!t.sshKeys?.length,sshPublicKeys:S.length>0?S:void 0,sshKeyIds:t.sshKeys,webTerminalEnabled:t.webTerminal,inBoxPreviewPublishing:t.inBoxPreview?void 0:!1,env:Object.keys(d).length>0?d:void 0,git:m,...ne?{resources:ne}:{},gpuLease:ee,...Mo(t),storage:h,fromSnapshot:t.fromSnapshot,publicTemplateId:t.publicTemplate,publicTemplateVersionId:t.publicTemplateVersion,teamId:u,...t.billingOwner?{billingOwnerId:t.billingOwner}:{},secrets:te,...b?{proxySecrets:b}:{},...is(t.allowDomain,u),metadata:p,driver:_,backend:v},C=t.tee?{tee:t.tee,sealed:t.sealed||void 0,attestationRefresh:t.attestationRefresh||t.attestationNonce===`auto`||void 0}:void 0,ae=C?await _e(c,{...ie,confidential:C,attestationNonce:t.attestationNonce??(t.attestationRefresh?`auto`:void 0),requireAttestation:t.requireAttestation??!0}):void 0,w=ae?.sandbox??await tr(c,ie);t.wait&&(l.text=`Waiting for sandbox to start...`,await w.waitFor(`running`,{timeoutMs:12e4}),await w.refresh()),l.stop();let oe=ls(w);t.json?e({id:w.id,name:w.name,active:oe.active,status:w.status,resources:w.resources,createdAt:w.createdAt,expiresAt:w.expiresAt,connection:Zo(w.connection),teamId:u,gpuLease:w.gpuLease,confidential:C,attestation:ae?.attestation,attestationNonce:ae?.attestationNonce}):us(w,oe.next,ie,{teamId:u,tee:C?.tee,proof:ae}),as(w)})}function ls(e){let t=Kt();return t||qt(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 us(e,t,n,i){r(`Sandbox created: ${e.id}`),u({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,r]of[[`Idle timeout (requested)`,n.idleTimeoutSeconds,900],[`Lifetime (requested)`,n.maxLifetimeSeconds,3600]])t&&t!==r&&console.log(`${e}: ${Rn(t)}`);i.teamId&&console.log(`Team: ${i.teamId}`),e.gpuLease&&(console.log(`GPU lease: ${e.gpuLease.id}`),Vo(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}`)),l(t)}const ds="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 fs(){return new ke(`--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(le)}function ps(){let e=[`id_ed25519`,`id_ecdsa`,`id_rsa`].map(e=>`${He()}/.ssh/${e}.pub`),t=e.find(e=>y(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 ms(e,t){return t instanceof A?t:Error(`--profile ${e}: ${t.message}`)}function hs(e,t){if(!t)return e;let n=e?.model??{};return{...e,model:{...n,reasoningEffort:t}}}function gs(e){if(e.spec){let t=JSON.parse(x(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=ys(e),n=bs(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=xs(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 _s(e){let{base:t,machines:n}=gs(e);return{...t,machines:n}}function vs(e){let{base:t,machines:n}=gs(e);return{...t,workers:n}}function ys(e){let t={};if(e.cpu&&(t.cpuCores=B(e.cpu,`--cpu`)),e.memory&&(t.memoryMB=B(e.memory,`--memory`)),e.disk&&(t.diskGB=B(e.disk,`--disk`)),e.acceleratorKind)t.accelerator=mo({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 bs(e,t){return ho({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 xs(e){let t={};return e.maxSpendUsd&&(t.maxSpendUsd=Number(e.maxSpendUsd)),e.maxLifetime&&(t.maxLifetimeSeconds=V(e.maxLifetime,`--max-lifetime`)),Object.keys(t).length>0?t:void 0}function Ss(n){n.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>`,ds).addOption(fs()).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 n=>{let{client:i}=z(n),a=f(`Creating fleet...`);a.start();let o=n.coordinator?await i.fleets.createWithCoordinator(vs(n)):await i.fleets.create(_s(n));a.stop();let s=Eo(o.machines);n.json?e({fleetId:o.fleetId,machines:s}):(r(`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 Cs(n){n.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}=z(i),o=f(`Dispatching command...`);o.start();let s=await(await a.fleets.list({fleetId:n})).dispatchExecDetailed(r,{machines:i.machine,cwd:i.cwd,timeoutMs:i.timeout?V(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)}),n.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,n)=>{let i=/^\d+$/.test(n.agents)?Number(n.agents):JSON.parse(x(n.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}=z(n);if(!!n.parentFleet!=!!n.parentAgent)throw Error(`--parent-fleet and --parent-agent go together`);let o=n.placement===`auto`||n.placement===`dedicated`?n.placement:{agentsPerSandbox:Number(n.placement)},c=n.maxSpendUsd?Number(n.maxSpendUsd):void 0,l=n.timeout?V(n.timeout,`--timeout`,`ms`):void 0,u=f(`Creating fleet...`);u.start();let d=Date.now(),p=await a.fleets.create({fleetId:n.fleetId,agents:i,placement:o,defaults:{...n.environment?{environment:n.environment}:{},...n.memory?{resources:{memoryMB:B(n.memory,`--memory`)}}:{},...n.model?{backend:{type:`opencode`,model:{model:n.model}}}:{}},...c===void 0?{}:{budgetUsd:c},...n.parentFleet?{parent:{fleetId:n.parentFleet,agentId:n.parentAgent}}:{}}),m=Date.now()-d;u.stop(),n.json||r(`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`&&!n.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{n.keep||await p.delete({continueOnError:!0})}n.json?e({fleetId:p.fleetId,createMs:m,sandboxes:p.machines.size,results:h,spend:g,deleted:!n.keep}):s({fleetId:p.fleetId,completed:h.filter(e=>e.status===`completed`).length,agents:h.length,spend:JSON.stringify(g),deleted:!n.keep}),h.some(e=>e.status!==`completed`)&&(process.exitCode=1)}),n.command(`cancel <fleet-id>`).description(`Interrupt every agent of a fleet and cancel its child fleets; sandboxes keep running`).action(async(t,n)=>{let{client:i}=z(n),a=await(await i.fleets.list({fleetId:t})).cancel();n.json?e({fleetId:t,...a}):r(`Fleet ${t}: interrupted ${a.interrupted} agents, cancelled ${a.children} child fleets`)})}const ws=[`list`,`create`,`delete`,`exec`,`prompt`,`read`,`write`];function Ts(e){if(!(!e||e.length===0)){for(let t of e)if(!ws.includes(t))throw Error(`Invalid token action '${t}'. Allowed: ${ws.join(`, `)}`);return e}}function Es(e){return e.length<=12?`****`:`${e.slice(0,6)}...${e.slice(-4)} (masked — use --json for full value)`}function Ds(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}=z(n),i=f(`Minting fleet token...`);i.start();let a=await r.fleets.createToken(t,{actions:Ts(n.action),ttlMinutes:n.ttlMinutes?B(n.ttlMinutes,`--ttl-minutes`):void 0});i.stop(),n.json?e(a):(s({"Fleet ID":a.fleetId,Token:Es(a.token),"Expires at":new Date(a.expiresAt).toISOString(),Actions:a.actions.join(`, `)}),console.log(`
|
|
151
151
|
Re-run with --json to print the full token value.`))})}function Os(){let n=new D(`workspace`).description(`Manage a fleet's shared workspace`);return n.command(`snapshot <fleet-id>`).description(`Snapshot the fleet's shared workspace`).action(async(t,n)=>{let{client:i}=z(n),a=f(`Creating workspace snapshot...`);a.start();let o=await i.fleets.createWorkspaceSnapshot(t);a.stop(),n.json?e(o):r(`Workspace snapshot created: ${o.snapshotId??o.id}`)}),n.command(`restore <fleet-id> <snapshot-id>`).description(`Restore the fleet's shared workspace from a snapshot`).action(async(t,n,i)=>{let{client:a}=z(i),o=f(`Restoring workspace...`);o.start();let s=await a.fleets.restoreWorkspaceSnapshot(t,n);o.stop(),i.json?e(s):r(`Workspace restored from ${s.snapshotId??n}`)}),n.command(`reconcile <fleet-id>`).description(`Re-mount the shared workspace on all fleet machines`).action(async(n,r)=>{let{client:i}=z(r),a=f(`Reconciling workspace...`);a.start();let o=await i.fleets.reconcileWorkspace(n);a.stop(),r.json?e(o):(s({"Fleet ID":o.fleetId,Checked:o.checked,"Orphaned mounts":o.orphanedMounts}),t(o.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`mounted`,header:`Mounted`,width:10}]))}),n}function ks(){let e=new D(`fleet`).description(`Manage sandbox fleets`);return Ss(e),Do(e),e.addCommand(Os()),Cs(e),To(e),Ds(e),e}function As(){let t=new D(`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}=z(i),s=await U(o,a,t);if(s=await W(s),!_.existsSync(n))throw Error(`Local file not found: ${n}`);let c=_.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}=z(i),s=await U(o,a,t);s=await W(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=_.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,r)=>{let{context:a,client:o}=z(r),s=await U(o,a,t);s=await W(s);let c=await s.fs.list(n,{all:r.all,long:r.long});if(r.json)e(c);else if(r.long)i([`Mode`,`Owner`,`Group`,`Size`,`Modified`,`Name`],c.map(e=>{let t=e.isDir?`d`:e.isSymlink?`l`:`-`,n=js(e.permissions),r=e.isDir?`<DIR>`:Ms(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}=z(r),o=await U(a,i,t);o=await W(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: ${Ms(s.size)} (${s.size} bytes)`),console.log(` Type: ${s.isDir?`directory`:s.isSymlink?`symlink`:`file`}`),console.log(` Mode: ${js(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}=z(r),o=await U(a,i,t);o=await W(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}=z(r),o=await U(a,i,t);o=await W(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}=z(r),o=await U(a,i,t);o=await W(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}=z(r),o=await U(a,i,t);o=await W(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 js(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 Ms(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 Ns(){let t=new D(`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}=z(n),a=f(`Fetching status...`);n.json||a.start();let o=await U(i,r,t);o=await W(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}=z(n),a=f(`Fetching log...`);n.json||a.start();let o=await U(i,r,t);o=await W(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(`
|
|
152
152
|
`)[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}=z(n),a=f(`Fetching diff...`);n.json||a.start();let o=await U(i,r,t);o=await W(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,n)=>{let{context:i,client:a}=z(n),o=await U(a,i,e);o=await W(o),await o.git.add(t),r(`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,n)=>{let{context:i,client:a}=z(n),o=await U(a,i,t);o=await W(o);let s=await o.git.commit(n.message,{amend:n.amend});n.json?e(s):r(`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:n,client:i}=z(t),a=f(`Pushing...`);a.start();let o=await U(i,n,e);o=await W(o),await o.git.push({force:t.force}),a.stop(),r(`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:n,client:i}=z(t),a=f(`Pulling...`);a.start();let o=await U(i,n,e);o=await W(o),await o.git.pull({rebase:t.rebase}),a.stop(),r(`Pulled from remote`)}),t.command(`branches`).description(`List branches`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(t,n)=>{let{context:r,client:a}=z(n),o=f(`Fetching branches...`);n.json||o.start();let s=await U(a,r,t);s=await W(s);let c=await s.git.branches();o.stop(),n.json?e(c):c.length===0?console.log(`No branches found`):i([`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,n)=>{let{context:i,client:a}=z(n),o=await U(a,i,e);o=await W(o),await o.git.checkout(t,{create:n.create}),r(`Checked out: ${t}${n.create?` (new)`:``}`)}),t}async function Ps(e){if(!nn(e.apiKey)){if(e.json||e.dryRun||!process.stdin.isTTY)return;await $r({baseUrl:e.sandboxBaseUrl,signal:e.signal})}return H(e)}async function Fs(t,n,r){let i=ic(n.parameter),a=r??await Ps(n);if(!a)throw new A(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured`,`tangle auth login`);if((await a.connections.providers().catch(()=>void 0))?.providers.some(e=>e.providerId===t&&e.authKind===`api_key`))throw new A(`USAGE_INVALID`,`${t} connects with an API key, not OAuth`,`Put the key in an environment variable and pass the variable's name`,`tangle hub connect ${t} --key-env <ENV_NAME>`);let o=await a.connections.start(t,{cli:!0,connectionParameters:i,...n.scope?.length?{requestedScopes:n.scope}:{}});return n.json?(e(oc(o)),o):(ac(o,n.browser===!1?!1:await Wr(o.redirectUrl),n.wait),o)}async function Is(e,t,n,r){let i=async()=>{n.signal?.throwIfAborted();let{connections:i}=await e.connections.list(),a=i.filter(e=>e.status===`active`&&e.providerId.toLowerCase()===t.trim().toLowerCase());return a.length?Je(a,r===void 0?t:`${t}:${r}`):void 0},a=await i();if(a||n.json||n.dryRun||!process.stdin.isTTY)return a;let o=await Fs(t,{...n,wait:!0},e);for(;!a&&Date.now()<Date.parse(o.expiresAt);)await Ne(1e3,void 0,{signal:n.signal}),a=await i();return a}function Ls(){let e=new D(`hub`).description(`Discover and run Tangle Hub tools`);return Rs(e),zs(e),Bs(e),Vs(e),Hs(e),e}function Rs(t){t.command(`connect`).description(`Connect a provider account`).argument(`provider`,`Provider to connect`).option(`--no-browser`,`Print the authorization URL instead of opening it`).option(`--key-env <name>`,`Connect an API-key provider using this environment variable; never prints the key`).option(`--metadata <json>`,`Provider setup metadata for API-key connections`).option(`--scope <scope>`,`Request an OAuth scope; repeatable, must stay within the host's grant`,(e,t)=>[...t,e],[]).option(`--parameter <key=value>`,`Provider-specific OAuth value. Repeatable.`,(e,t)=>[...t,e],[]).action(async(t,n)=>{if(n.keyEnv){if(n.scope?.length)throw Error(`--scope applies to OAuth connections, not --key-env.`);let r=process.env[n.keyEnv];if(!r?.trim())throw Error(`Environment variable '${n.keyEnv}' is empty or unavailable.`);let i=await Ps(n);if(!i)throw new A(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured`,`tangle auth login`);let a;if(n.metadata!==void 0)try{a=JSON.parse(n.metadata)}catch{throw Error(`--metadata must be valid JSON.`)}let o=await i.connections.connectApiKey(t,r,a);n.json?e(o):l(`Connected ${o.connection.providerId} as ${o.connection.id}.`);return}if(n.metadata!==void 0)throw Error(`--metadata requires --key-env.`);await Fs(t,n)});let n=new D(`connections`).description(`List Hub provider connections`).action(async t=>{let n=await(await H(t)).connections.list();t.json?e(n):rc(n.connections)});n.command(`revoke <connection-id>`).description(`Revoke a Hub provider connection`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let r=await H(n),i=await Dn(r,t);if(!n.force&&!await G(`Revoke Hub connection ${i}? `,`--force`)){l(`Revoke cancelled.`);return}let a=await r.connections.revoke(i);if(n.json){e(a);return}l(`Revoked Hub connection ${a.connection.id}.`)}),t.addCommand(n)}function zs(n){n.command(`providers [provider]`).description(`Show provider setup and action catalog; use hub events for trigger readiness`).action(async(n,r)=>{let i=await(await H(r)).connections.providers(),a=i.providers.filter(e=>!n||e.providerId===n.toLowerCase());if(n&&!a.length)throw Error(`Provider '${n}' is absent from this deployment's catalog.`);if(r.json)return e({...i,providers:a});t(a,[{key:`providerId`,header:`Provider`},{key:`authKind`,header:`Auth`},{key:`configured`,header:`Connect configured`},{key:`actionCount`,header:`Catalog actions`}])}),n.command(`events [provider]`).description(`Discover deployed trigger events and ingress readiness separately from callable tools`).action(async(n,r)=>{let i=await H(r),[a,o]=await Promise.all([i.connections.providers(),i.workflows.catalogs()]),s=[...new Set([...a.providers.map(e=>e.providerId),...o.providerEventProviders])];if(n&&!s.includes(n.toLowerCase()))throw Error(`Provider '${n}' is absent from this deployment's catalog.`);let c=s.filter(e=>!n||e===n.toLowerCase()).map(e=>({provider:e,supported:o.providerEventProviders.includes(e),ingressConfigured:a.providers.find(t=>t.providerId===e)?.eventIngressConfigured??null,catalog:o.triggerEvents[e]??null}));if(r.json)return e({providers:c});t(c.map(e=>({...e,ingress:e.ingressConfigured===null?`unknown`:e.ingressConfigured?`ready`:`setup required`,events:e.catalog?.events.map(e=>e.id).join(`, `)??`no published vocabulary`})),[{key:`provider`,header:`Provider`},{key:`supported`,header:`Event source supported`},{key:`ingress`,header:`Ingress`},{key:`events`,header:`Events`}])})}function Bs(t){let n=new D(`permissions`).description(`Manage Hub action permissions`);n.command(`list`).description(`List Hub permissions for a connection`).requiredOption(`--connection <ref>`,`Hub connection id, or provider[:account]`).action(async t=>{if(!t.connection)throw Error(`--connection is required.`);let n=await H(t),r=await Dn(n,t.connection),i=await n.permissions.list(r);t.json?e(i):Qs(i.policies)}),n.command(`set`).description(`Set Hub permission for one action`).requiredOption(`--connection <ref>`,`Hub connection id, or provider[:account]`).requiredOption(`--action <path>`,`Executor action path`).requiredOption(`--decision <allow|ask|deny>`,`Permission decision`).action(async t=>{if(!t.connection)throw Error(`--connection is required.`);if(!t.action)throw Error(`--action is required.`);let n=$s(t.decision),r=await H(t),i=await Dn(r,t.connection),a=await r.permissions.set({connectionId:i,actionPath:t.action,decision:n});t.json?e(a):Qs([a.policy])}),n.command(`revert-writes`).description("Revoke a bulk `--allow-writes` grant for a connection (deletes only the auto-granted write rows; manual permissions are untouched)").requiredOption(`--connection <ref>`,`Hub connection id, or provider[:account]`).action(async t=>{if(!t.connection)throw Error(`--connection is required.`);let n=await H(t),r=await Dn(n,t.connection),i=await n.permissions.revertWrites(r);if(t.json){e(i);return}l(`Reverted ${i.reverted} write permission${i.reverted===1?``:`s`} for connection ${i.connectionId}.`)}),t.addCommand(n),t.addCommand(Ws())}function Vs(t){let n=new D(`tools`).description(`Discover Hub tools`);n.command(`sources`).description(`List Hub tool sources`).action(async t=>{let n=await(await H(t)).tools.sources();t.json?e(n):ec(n.sources)}),n.command(`describe`).description(`Describe a Hub tool`).argument(`path`,`Executor tool path`).action(async(t,n)=>{let r=await(await H(n)).tools.describe(t);n.json?e(r):tc(r.tool)}),n.command(`search`).description(`Search Hub tools`).argument(`<query...>`,`Search query`).option(`--provider <provider>`,`Filter by provider/source ID`).action(async(t,n)=>{let r=await(await H(n)).tools.search(t.join(` `),{provider:n.provider});n.json?e(r):Zs(r.tools)}),t.addCommand(n),t.addCommand(Us(`call`)),t.addCommand(Us(`exec`))}function Hs(t){t.command(`resume`).description(`Resolve a Hub approval created by a paused execution`).argument(`approval-id`,`Hub approval ID from HUB_APPROVAL_REQUIRED`).option(`--accept`,`Approve the execution approval`).option(`--decline`,`Deny the execution approval`).option(`--cancel`,`Unsupported for approval-backed Hub resume`).action(async(e,t)=>{if(Ks(e),t.cancel)throw Error(`Hub approval resume does not support --cancel. Use --decline to deny the approval.`);if(t.accept&&t.decline)throw Error(`Choose only one of --accept or --decline.`);if(!t.accept&&!t.decline)throw Error(`Choose --accept to approve or --decline to deny the Hub approval.`);let n=await H(t);Js(t.decline?await n.approvals.deny(e):await n.approvals.approve(e),t.json===!0)}),t.command(`status`).description(`Show Hub auth and connection status`).action(async t=>{let n=await(await H(t)).status();t.json?e(n):sc(n)})}function Us(t){return new D(t).description(`Execute a Hub tool`).argument(`<args...>`,`Tool path tokens followed by JSON input`).option(`--connection <ref>`,`Hub connection id, or provider[:account]`).option(`--auto-approve`,`Approve a HUB_APPROVAL_REQUIRED execution and retry once`).option(`--approve`,`Alias for --auto-approve`).option(`--no-hub-key`,`Do not auto-mint a platform Hub key; use the stored credential as-is`).action(async(t,n)=>{let{args:r,approve:i}=Gs(t,n),{path:a,input:o}=Xs(r),s=await H(n),c=n.connection?await Dn(s,n.connection):void 0;e((await s.tools.invoke(a,o,{connectionId:c,approve:i})).result)})}function Ws(){let t=new D(`approvals`).description(`List and resolve Hub execution approvals`);t.command(`list`).description(`List pending Hub execution approvals`).action(async t=>{let n=await(await H(t)).approvals.list();t.json?e(n):qs(n.approvals)});for(let e of[`approve`,`deny`])t.command(e).description(`${e===`approve`?`Approve`:`Deny`} a pending Hub execution approval`).argument(`approval-id`,`Hub approval ID`).action(async(t,n)=>{Ks(t),Js(await(await H(n)).approvals[e](t),n.json===!0)});return t}function Gs(e,t){let n=t.autoApprove;return{args:e.filter(e=>e!==`--approve`&&e!==`--auto-approve`),approve:t.approve===!0||n===!0||e.includes(`--approve`)||e.includes(`--auto-approve`)}}function Ks(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`Hub approval ID must contain only letters, numbers, underscores, and dashes.`)}function qs(e){t(e,[{key:`id`,header:`ID`},{key:`providerId`,header:`Provider`},{key:`actionPath`,header:`Action`},{key:`connectionId`,header:`Connection`},{key:`status`,header:`Status`},{key:`expiresAt`,header:`Expires`}])}function Js(t,n){if(n){e(Ys(t));return}l(`Hub approval ${t.approval.id} ${t.approval.status}.`),t.capabilityToken&&l("Capability token minted. Re-run the original command with `--approve` to execute automatically.")}function Ys(e){return{approval:e.approval,...e.capabilityToken?{capabilityToken:{tokenId:e.capabilityToken.tokenId,expiresAt:e.capabilityToken.expiresAt}}:{}}}function Xs(e){if(e.length<2)throw Error(`Usage: tangle hub call <path> <json-input>`);let t=e[e.length-1];try{return{path:e.slice(0,-1).join(`.`),input:JSON.parse(t)}}catch{throw Error(`Hub call input must be valid JSON.`)}}function Zs(e){t(e.map(e=>({...e,provider:e.providerId??e.requiredConnectionProviderId,connection:nc(e)})),[{key:`path`,header:`Path`},{key:`provider`,header:`Provider`},{key:`title`,header:`Title`},{key:`description`,header:`Description`},{key:`connection`,header:`Connection`},{key:`policyState`,header:`Policy`}])}function Qs(e){t(e,[{key:`connectionId`,header:`Connection`},{key:`providerId`,header:`Provider`},{key:`actionPath`,header:`Action`},{key:`decision`,header:`Decision`},{key:`updatedAt`,header:`Updated`}])}function $s(e){if(e===`allow`||e===`ask`||e===`deny`)return e;throw Error(`--decision must be one of: allow, ask, deny.`)}function ec(e){t(e,[{key:`sourceId`,header:`Source`},{key:`displayName`,header:`Provider`},{key:`toolCount`,header:`Tools`},{key:`connectionStatus`,header:`Connection`},{key:`health`,header:`Health`},{key:`configured`,header:`Configured`}])}function tc(e){s({Path:e.path,Provider:e.providerId??e.requiredConnectionProviderId,Title:e.title,Description:e.description,Connection:nc(e),Policy:e.policyState}),e.inputSchema!==void 0&&(l(`Input schema`),console.log(JSON.stringify(e.inputSchema,null,2))),e.outputSchema!==void 0&&(l(`Output schema`),console.log(JSON.stringify(e.outputSchema,null,2)))}function nc(e){if(e.connectionRequired===!1)return`not required`;if(e.connectionStatus)return e.connectionStatus}function rc(e){t(e.map(e=>({...e,account:e.accountDisplay??e.displayName,scopes:e.scopes.join(`, `)})),[{key:`id`,header:`ID`},{key:`providerId`,header:`Provider`},{key:`account`,header:`Account`},{key:`scopes`,header:`Scopes`},{key:`status`,header:`Status`},{key:`health`,header:`Health`},{key:`lastUsedAt`,header:`Last Used`}])}function ic(e){if(!e||e.length===0)return;let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0||e===n.length-1)throw Error(`Invalid --parameter "${n}": expected key=value (for example subdomain=acme)`);let r=n.slice(0,e);if(Object.hasOwn(t,r))throw Error(`Duplicate --parameter key "${r}".`);t[r]=n.slice(e+1)}return t}function ac(e,t,n=!1){t?l(`Opened browser to connect ${e.provider}.`):(l(`Open this URL to connect ${e.provider}:`),console.log(e.redirectUrl)),l(n?`Finish authorization in the browser; this run resumes when connected.`:"Finish authorization in the browser, then rerun `tangle hub status`.")}function oc(e){return{provider:e.provider,redirectUrl:e.redirectUrl,expiresAt:e.expiresAt,scopes:e.scopes,cli:e.cli}}function sc(e){let{principal:t,connections:n}=e;l(`Hub status`),s({Principal:t.kind,"User ID":t.userId,"API Key ID":t.apiKeyId,"Sandbox ID":t.sandboxId,"Connected Providers":n.connectedProviderCount,"Unhealthy Providers":n.unhealthyProviderCount}),n.unhealthyProviderCount>0&&l(`Some providers require reconnect.`)}function cc(){let n=new D(`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`,wi).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`;ki(r);let i=uc(n.apiKey),a=await Pi({selection:r,workspace:n.workspace,apiKey:i,endpoint:n.endpoint,serviceName:n.serviceName??ji(n.workspace),environment:n.environment,smoke:n.smoke,dryRun:!!n.dryRun,hookCommand:n.hookCommand}),o={configPath:a.configPath,agents:a.agents,nativeAgents:a.nativeAgents,manual:a.manual,written:a.written,smokeTraceId:a.smokeTraceId};if(n.json){e(o);return}s({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`,wi).action(async t=>{let n=Ni(),r=await zi({endpoint:t.endpoint===`https://intelligence.tangle.tools/v1/otlp`?n?.endpoint??`https://intelligence.tangle.tools/v1/otlp`:t.endpoint,apiKey:uc(t.apiKey??n?.apiKey)});t.json?e(r):lc(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=dc(t.agent),r=Ni(),i={agent:n,event:t.event,endpoint:t.endpoint??r?.endpoint??`https://intelligence.tangle.tools/v1/otlp`,apiKey:uc(t.apiKey??r?.apiKey),serviceName:t.serviceName??r?.serviceName??ji(process.cwd()),environment:t.environment??r?.environment??`local`,sessionId:t.sessionId,payload:t.payload===void 0?await pc():fc(t.payload)};if(t.dryRun){let r=Ii(i);if(t.json){e(r);return}s({Trace:r.traceId,Agent:n,Event:t.event});return}let a=await Li(i);if(t.json){e({traceId:a});return}s({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}N(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 mc({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 mc({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 mc({type:gc(e.subjectType),id:e.subjectId},e)}),n.command(`get <job-id>`).description(`Get an intelligence report`).action(async(t,n)=>{let{client:r}=z(n),i=n.json?null:f(`Fetching intelligence report...`);i?.start();let a=await r.intelligence.getReport(t);if(i?.stop(),n.json){e(a);return}hc(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}=z(n),i=n.json?null:f(`Fetching intelligence reports...`);i?.start();let a=await r.intelligence.listReports({subjectType:n.subjectType===void 0?void 0:gc(n.subjectType),subjectId:n.subjectId,limit:n.limit===void 0?void 0:yc(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 lc(e){s({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 uc(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 dc(e){if(Ai(e))return e;throw Error(`agent must be a known Tangle Intelligence agent surface`)}function fc(e){try{return JSON.parse(e)}catch(e){throw Error(`--payload must be JSON: ${e instanceof Error?e.message:String(e)}`)}}async function pc(){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 mc(t,n){let r=_c(n.mode),i=bc(n.metadata),a=n.maxUsd===void 0?void 0:vc(n.maxUsd);if(r===`agentic`&&a===void 0)throw Error(`Agentic intelligence reports require --max-usd`);let{client:o}=z(n),s=n.json?null:f(`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}hc(c)}function hc(t){s({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 gc(e){if(e===`sandbox`||e===`fleet`)return e;throw Error(`subject type must be sandbox or fleet`)}function _c(e){if(e===`deterministic`||e===`agentic`)return e;throw Error(`mode must be deterministic or agentic`)}function vc(e){let t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`--max-usd must be a non-negative number`);return t}function yc(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function bc(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 xc=[`router`,`sandbox`,`blueprint-agent`,`evals`,`agent-builder`];async function Sc(e,t){let n=await Jn({...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 Cc(e,t,n={}){let r=new Headers(n.headers);n.body&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await Yn(e,t,{...n,headers:r});if(n.expected!==void 0&&i.status!==n.expected)throw Error(await wc(i,t));return i}async function wc(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 Tc=[`ID`,`Prefix`,`Name`,`Product`,`Created`,`Last used`,`Expires`];function Ec(e){return[e.id,e.keyPrefix??``,e.name,e.product??`all`,e.createdAt,e.lastUsedAt??`—`,e.expiresAt??`—`]}function Dc(){let t=new D(`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 Sc(t,!1),r=n.baseUrl,a=await(await Cc(n,`${r}/v1/keys`,{expected:200})).json();if(t.json){e(a);return}i(Tc,a.data.map(Ec))}),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 (${xc.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,n)=>{if(n.product!==void 0&&!xc.includes(n.product))throw Error(`Invalid --product. Expected one of ${xc.join(`, `)}`);let i=await Sc(n,!0),a=i.baseUrl,o=n.expiresInDays===void 0?void 0:new Date(Date.now()+B(n.expiresInDays,`--expires-in-days`)*24*60*60*1e3).toISOString(),s=f(`Creating API key...`);s.start();let c=await Cc(i,`${a}/v1/keys`,{method:`POST`,expected:201,body:JSON.stringify({name:t,product:n.product,budgetUsd:n.budgetUsd?Number.parseFloat(n.budgetUsd):void 0,rpmLimit:n.rpmLimit?Number.parseInt(n.rpmLimit,10):void 0,expiresAt:o})});s.stop();let u=await c.json();if(n.json){e(u);return}r(`API key created: ${u.data.prefix}…`),l(`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,n)=>{let i=await Sc(n,!0),a=i.baseUrl;if(!n.yes&&!await G(`Revoke key ${t}? Any service still using it will start to fail.`,`--yes`)){l(`Aborted.`);return}let o=await(await Cc(i,`${a}/v1/keys/${encodeURIComponent(t)}`,{method:`DELETE`,expected:200})).json();if(n.json){e(o);return}r(`Revoked ${t}`)}),t}function X(e){if(Gt().token)throw Error(`A line relay cannot manage numbers or attachments. Use your owner CLI outside the agent box.`);return R(L(e))}function Oc(e){if(!e.yes)throw Error(`Review the selected line and use --yes to authorize this change. Attaching enables metered agent work.`)}function kc(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(N)}async function Ac(e){let t=await at(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 jc(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=kc(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()=>{Oc(n);let r=kc(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()=>{Oc(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 Ac(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(pn()).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()=>{Oc(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 Mc(e){let{token:t,baseUrl:n}=Gt();if(t===void 0)return H(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 Ke({baseUrl:n,authHeaders:()=>({Authorization:`Bearer ${t}`})})}async function Nc(e,t){if(t)return t;if(!Gt().token)throw Error(`Provide --line <line-id>`);return(await e.lines.context()).line.id}function Pc(e){return e().catch(N)}function Fc(){return new D(`context`).description(`Show live line identity, members, consent, reminders and quotas`).action(t=>Pc(async()=>{e(await(await Mc(t)).lines.context())}))}function Ic(){let t=new D(`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=>Pc(async()=>{let n=await Mc(t);e(await n.lines.members.list(await Nc(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)=>Pc(async()=>{let i=await Mc(r),a=await Nc(i,r.line);if(!Gt().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)=>Pc(async()=>{if(!n.at)throw Error(`--at is required`);let r=await Mc(n),i=n.idempotencyKey??Ae(`sha256`).update(JSON.stringify([t,n.at])).digest(`hex`).slice(0,32);e(await r.lines.remind(await Nc(r,n.line),{text:t,notBefore:n.at,idempotencyKey:i}))})),jc(t),t}function Lc(){let e=new D(`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=L({apiKey:t.apiKey,baseUrl:t.baseUrl}),r=await U(R(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 Rc(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=Rt(),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??en():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=L({apiKey:a,baseUrl:r}),s=R(o);return t.self?lt(s):U(s,o,e)}async function zc(e,t,n){let r=f(e);t||r.start();try{return await n()}finally{r.stop()}}function Bc(e){return e}const Vc=`
|
|
153
153
|
A preview URL is reachable from outside the sandbox only. Inside the box, test
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/sandbox-cli",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.142",
|
|
4
4
|
"description": "CLI for Tangle Sandbox operations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"@tangle-network/agent-runtime": "^10.0.12",
|
|
27
27
|
"@tangle-network/harness-sessions": "^1.0.13",
|
|
28
28
|
"@tangle-network/hub-sdk": "1.0.33",
|
|
29
|
-
"@tangle-network/sandbox": "^1.0.
|
|
29
|
+
"@tangle-network/sandbox": "^1.0.575",
|
|
30
30
|
"@tangle-network/sdk-cli-runner": "^0.3.17",
|
|
31
31
|
"chalk": "^5.6.2",
|
|
32
|
-
"cli-bridge": "https://codeload.github.com/drewstone/cli-bridge/tar.gz/
|
|
32
|
+
"cli-bridge": "https://codeload.github.com/drewstone/cli-bridge/tar.gz/6adac862f7ef7ae326b2e9fe6d016ee1b52d423f",
|
|
33
33
|
"commander": "12.1.0",
|
|
34
34
|
"ora": "^9.4.1",
|
|
35
35
|
"proper-lockfile": "4.1.2",
|
|
@@ -87,8 +87,8 @@
|
|
|
87
87
|
"author": "Tangle Network",
|
|
88
88
|
"license": "MIT",
|
|
89
89
|
"tangleRelease": {
|
|
90
|
-
"sourceSha": "
|
|
91
|
-
"mergedAt": "2026-11-
|
|
90
|
+
"sourceSha": "7584788903d697718ed04f67900632a928c43326",
|
|
91
|
+
"mergedAt": "2026-11-23T15:44:27-08:00"
|
|
92
92
|
},
|
|
93
93
|
"scripts": {
|
|
94
94
|
"build": "tsdown",
|