@tangle-network/sandbox-cli 0.23.135 → 0.23.136
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/SKILL.md +1 -0
- package/dist/index.mjs +11 -5
- package/package.json +6 -6
package/SKILL.md
CHANGED
|
@@ -457,6 +457,7 @@ tangle mcp serve <id>
|
|
|
457
457
|
# Preview links
|
|
458
458
|
tangle preview ls <id>
|
|
459
459
|
tangle preview create <id> 3000
|
|
460
|
+
tangle preview publish --self --port 3000 # from inside the box; the URL is reachable from outside only (test on localhost:3000; preview origins <sandbox>-<port>.tangle.sh get 403 on CONNECT). Any lastProbe.httpStatus means the edge reached the app
|
|
460
461
|
tangle preview rm <id> <preview-id>
|
|
461
462
|
```
|
|
462
463
|
|
package/dist/index.mjs
CHANGED
|
@@ -149,7 +149,13 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
|
|
|
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
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(`
|
|
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
|
-
`)[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}function Vc(){let t=new D(`preview`).description(`Manage sandbox preview links`);return Bc(t.command(`start`).description(`Start/reuse a managed development server and publish its ready preview`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).option(`--cwd <directory>`,`Project directory in the selected workspace`).option(`--session <session-id>`,`Select the agent's session workspace`).option(`--name <name>`,`App/service label`)).action(async(t,n)=>{let i=await Rc(t,n),a=await zc(`Starting managed preview...`,n.json,()=>st(i,{cwd:n.cwd,sessionId:n.session,name:n.name}));n.json?e(a):(r(`Preview ready: ${a.url}`),console.log(`Preview ID: ${a.previewId}`))}),Bc(t.command(`list`).alias(`ls`).description(`List active preview links for a sandbox`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`)).action(async(t,n)=>{let r=await Rc(t,n),a=await zc(`Fetching preview links...`,n.json,()=>r.previewLinks.list());n.json?e(a):a.length===0?console.log(`No preview links found`):i([`App`,`Preview ID`,`Port`,`URL`,`Status`],a.map(e=>[Hc(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),Bc(t.command(`publish`).description(`Publish one existing HTTP service; never starts or replaces a process`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).requiredOption(`--port <port>`,`Existing service port`).option(`--name <name>`,`App/service label`)).action(async(t,n)=>{if(!n.port||!/^\d+$/.test(n.port))throw Error(`An integer service port is required`);let i=await Rc(t,n),a=await zc(`Publishing service...`,n.json,()=>ct(i,{port:Number(n.port),name:n.name}));n.json?e(a):r(`Preview ready: ${a.url}`)}),Bc(t.command(`create`).description(`Create a preview link for a port`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<port>`,`Port number to preview`)).action(async(t,n,i)=>{if(!/^\d+$/.test(n)||Number(n)<1||Number(n)>65535)throw Error(`Port must be an integer between 1 and 65535`);let a=await Rc(t,i),o=await zc(`Creating preview for port ${n}...`,i.json,()=>a.previewLinks.create(Number(n)));i.json?e(o):(r(`Preview created: ${o.url}`),console.log(`Preview ID: ${o.previewId}`))}),Bc(t.command(`remove`).alias(`rm`).description(`Remove a preview link`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<preview-id>`,`Preview link ID (from 'preview list')`)).action(async(t,n,i)=>{let a=await Rc(t,i);await zc(`Removing preview...`,i.json,()=>a.previewLinks.remove(n)),i.json?e({success:!0,previewId:n}):r(`Preview removed: ${n}`)}),t}function Hc(e){let t=e?.app;if(!t||typeof t!=`object`)return``;let n=`name`in t?t.name:void 0,r=`cwd`in t?t.cwd:void 0;return typeof n==`string`?n:typeof r==`string`?r:``}function Uc(){let t=new D(`process`).description(`Manage processes in a sandbox`);return t.command(`spawn`).description(`Spawn a process without blocking (returns PID)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command>`,`Command to execute`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`).option(`--blocking`,`Wait for completion (default: false)`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=bo(r.env??[],`--env`,`env`),s=r.timeout?V(r.timeout,`--timeout`,`ms`,0):void 0,c=f(`Spawning: ${n}`);r.json||c.start();let l=await U(a,i,t);if(l=await W(l),r.blocking){let t=await l.exec(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e(t):(t.stdout&&globalThis.process.stdout.write(t.stdout),t.stderr&&globalThis.process.stderr.write(t.stderr),t.exitCode!==0&&globalThis.process.exit(t.exitCode))}else{let i=await l.process.spawn(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e({pid:i.pid,command:i.command}):(console.log(`Process started with PID: ${i.pid}`),console.log(`Use 'tangle process logs ${t} ${i.pid}' to view output`))}}),t.command(`list`).alias(`ls`).description(`List all processes in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--running`,`Show only running processes`).action(async(t,n)=>{let{context:r,client:a}=z(n),o=f(`Fetching processes...`);n.json||o.start();let s=await U(a,r,t);s=await W(s);let c=await s.process.list();n.running&&(c=c.filter(e=>e.running)),o.stop(),n.json?e(c):c.length===0?console.log(`No processes found`):i([`PID`,`Command`,`Status`,`Exit Code`,`Started`],c.map(e=>[String(e.pid),e.command.length>40?`${e.command.slice(0,37)}...`:e.command,e.running?`running`:`exited`,String(e.exitCode),e.startedAt.toLocaleString()]))}),t.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching process info...`);r.json||o.start();let s=await U(a,i,t);s=await W(s);let c=await s.process.get(Number.parseInt(n,10));if(o.stop(),!c){console.error(`Process ${n} not found`),globalThis.process.exit(1);return}let l=await c.status();r.json?e(l):(console.log(`PID: ${l.pid}`),console.log(`Command: ${l.command}`),console.log(`CWD: ${l.cwd||`(default)`}`),console.log(`Status: ${l.running?`running`:`exited`}`),console.log(`Exit Code: ${l.exitCode}`),l.exitSignal&&console.log(`Signal: ${l.exitSignal}`),console.log(`Started: ${l.startedAt.toLocaleString()}`),l.exitedAt&&console.log(`Exited: ${l.exitedAt.toLocaleString()}`))}),t.command(`kill`).description(`Kill a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`-s, --signal <signal>`,`Signal to send (SIGTERM, SIGKILL, etc.)`,`SIGTERM`).option(`--tree`,`Also kill descendants of the tracked process`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=f(`Sending ${r.signal} to PID ${n}...`);r.json||o.start();let s=await U(a,i,t);s=await W(s);let c=await s.process.get(Number.parseInt(n,10));if(!c){o.stop(),console.error(`Process ${n} not found`),globalThis.process.exit(1);return}r.tree?await c.kill(r.signal,{tree:!0}):await c.kill(r.signal),o.stop(),r.json?e({pid:Number.parseInt(n,10),signal:r.signal,...r.tree===!0?{tree:!0}:{},killed:!0}):console.log(r.tree?`Sent ${r.signal} to process tree ${n}`:`Sent ${r.signal} to process ${n}`)}),t.command(`logs`).description(`Stream buffered and live process logs until the process exits`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`--stdout-only`,`Only show stdout`).option(`--stderr-only`,`Only show stderr`).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=await U(i,r,e);a=await W(a);let o=await a.process.get(Number.parseInt(t,10));if(!o){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}for await(let e of o.logs())n.stdoutOnly&&e.type!==`stdout`||n.stderrOnly&&e.type!==`stderr`||(n.json?console.log(JSON.stringify(e)):e.type===`stdout`?globalThis.process.stdout.write(e.data):globalThis.process.stderr.write(e.data))}),t}const Wc=[`python`,`node`,`typescript`,`bash`];function Gc(e){switch(Te(e).toLowerCase()){case`.py`:return`python`;case`.js`:case`.mjs`:case`.cjs`:return`node`;case`.ts`:case`.tsx`:return`typescript`;case`.sh`:case`.bash`:return`bash`;default:return}}async function Kc(e){if(e===`-`){let e=[];for await(let t of process.stdin)e.push(typeof t==`string`?Buffer.from(t):t);return Buffer.concat(e).toString(`utf8`)}return await ot(Ee(e),`utf8`)}async function qc(e,t,n=Kc){let r=t?Wc.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${Wc.join(`, `)}`)})():void 0;if(!e||e===`-`){if(!r)throw Error(`reading from stdin requires --lang. Example: tangle run <id> -l python -`);return{language:r,source:await n(`-`)}}let i=Gc(e);return{language:r??i??(()=>{throw Error(`cannot infer language from "${e}". Pass it explicitly: tangle run <id> -l <python|node|typescript|bash> ${e}`)})(),source:await n(e)}}function Jc(e){return E(Ue(),`tangle-run-images`,e)}function Yc(){return new D(`run`).description(`Run code in a persistent kernel inside a sandbox. Variables persist across calls in the same --session.`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`[file]`,`Path to source file. Language is inferred from extension. Use - for stdin (requires --lang).`).option(`-l, --lang <lang>`,`Force language: ${Wc.join(` | `)}. Required for stdin.`).option(`-s, --session <id>`,`Session id for kernel scoping`).option(`-t, --timeout <ms>`,`Per-call timeout in ms (0 disables)`,`60000`).option(`--save-images <dir>`,`Write image results into this directory (default: $TMPDIR/tangle-run-images/<sandbox>/).`).option(`--no-save-images`,`Don't write image results to disk; print summary only`).action(async(t,n,r)=>{let{language:i,source:a}=await qc(n,r.lang),o=V(r.timeout,`--timeout`,`ms`,0),{context:s,client:c}=z(r),l=await U(c,s,t);l=await W(l);let u=f(`Running ${i} (${a.length}b)…`);r.json||u.start();let d=await l.runCode(i,a,{sessionId:r.session,timeoutMs:o});if(u.stop(),r.json){e(d),d.exitCode!==0&&process.exit(d.exitCode);return}d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr);let p=0;for(let e of d.results)if(e.type===`image`)if(r.saveImages!==!1){let n=typeof r.saveImages==`string`?r.saveImages:Jc(t);b(n,{recursive:!0});let i=`${n}/${Date.now()}-${p}.${e.format}`;S(i,Buffer.from(e.data,`base64`)),process.stderr.write(T.green(`✓ image → ${i}\n`)),p++}else process.stderr.write(T.gray(`[image: ${e.format}, ${e.data.length}b base64]\n`));else if(e.type===`dataframe`){let t=e.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(T.gray(`[dataframe ${e.rows.length}×${e.columns.length}${e.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${t}\n`);for(let t of e.rows.slice(0,20))process.stderr.write(`${t.map(e=>String(e)).join(` | `)}\n`);e.rows.length>20&&process.stderr.write(T.gray(`… ${e.rows.length-20} more rows\n`))}else e.type===`json`?(process.stderr.write(T.gray(`[json] `)),process.stderr.write(`${JSON.stringify(e.value,null,2)}\n`)):e.type===`html`?process.stderr.write(T.gray(`[html ${e.value.length}b]\n`)):e.type===`error`?(process.stderr.write(T.red(`✗ ${e.name}: ${e.message}\n`)),e.traceback&&process.stderr.write(`${e.traceback}\n`)):e.type===`text`&&process.stderr.write(`${e.value}\n`);d.error&&(process.stderr.write(T.red(`\n✗ ${d.error.name}: ${d.error.message}\n`)),d.error.traceback&&process.stderr.write(`${d.error.traceback}\n`)),d.exitCode!==0&&process.exit(d.exitCode)})}function Xc(){let e=new D(`sandbox`).description(`Manage sandboxes`);return cs(e),Qo(e),Uo(e),ss(e),e}function Zc(){return new D(`search`).description(`Search for text patterns in sandbox files (ripgrep)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pattern>`,`Search pattern (regex)`).option(`-g, --glob <pattern>`,`File glob filter (e.g. '**/*.ts')`).option(`-n, --max-results <count>`,`Max results to return`).option(`-i, --ignore-case`,`Case-insensitive search`).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=f(`Searching...`);n.json||a.start();let o=await U(i,r,e),s=0,c=n.maxResults?Number.parseInt(n.maxResults,10):void 0,l={};n.glob&&(l.glob=n.glob),n.ignoreCase&&(l.ignoreCase=!0),c&&(l.maxResults=c);for await(let e of o.search(t,l))if(s===0&&a.stop(),s++,n.json?console.log(JSON.stringify(e)):console.log(`${e.path}:${e.line}:${e.column??0}: ${e.text}`),c&&s>=c)break;a.stop(),s===0&&!n.json&&console.log(`No matches found`)})}function Qc(){let t=new D(`secret`).description(`Manage secrets`);return t.command(`create`).description(`Create a new secret`).argument(`<name>`,`Secret name (e.g., HF_TOKEN, AWS_ACCESS_KEY)`).argument(`[value]`,`Secret value`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,n,i)=>{let a=await z(i).client.secrets.create(t,await $c({value:n,valueStdin:i.valueStdin,prompt:`Enter value for secret '${t}': `}));i.json?e(a):(r(`Secret created: ${a.name}`),l(`Use --secret ${a.name} when creating a sandbox to select it for delivery.`))}),t.command(`list`).description(`List all secrets`).action(async t=>{let n=await z(t).client.secrets.list();t.json?e(n):n.length===0?(l(`No secrets found.`),l(`Use 'tangle secret create <name> [value]' to create one.`)):i([`Name`,`Created At`,`Updated At`],n.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),t.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=z(n).client;if(!n.force&&!await G(`Are you sure you want to delete secret '${t}'? This cannot be undone. (y/N) `,`--force`)){l(`Cancelled.`);return}await i.secrets.delete(t),n.json?e({success:!0,deleted:t}):r(`Secret deleted: ${t}`)}),t}async function $c(e){if(e.value!==void 0&&e.valueStdin)throw Error(`Provide either a secret value argument or --value-stdin, not both`);let t=e.value??(e.valueStdin?await mr():await pr(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function el(){let e=new D(`skill`).description(`Print paths to shipped skill documentation`);return e.command(`path`).description(`Print the absolute path to the SKILL.md shipped with this CLI`).action(()=>{let e=Se.dirname(ut(import.meta.url)),t=Se.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function tl(){let n=new D(`snapshot`).description(`Manage snapshots`);return n.command(`create <sandbox-id-or-name>`).description(`Create a snapshot of a sandbox`).option(`--tags <tags...>`,`Tags for the snapshot`).option(`--no-wait`,`Return once the snapshot is accepted and print the operation to poll`).action(async(t,n)=>{let{context:i,client:a}=z(n),o=f(`Creating snapshot...`);o.start();let s=await U(a,i,t);if(n.wait===!1){let e=await s.snapshot({tags:n.tags,wait:!1});o.stop(),Wo(e.info,!!n.json);return}let c=await s.snapshot({tags:n.tags});o.stop(),n.json?e(c):(r(`Snapshot created: ${c.snapshotId}`),console.log(`Size: ${rl(c.sizeBytes)}`))}),n.command(`list [sandbox-id-or-name]`).description(`List snapshots for a sandbox; with no sandbox, the snapshots you own, including your most recently deleted sandboxes'`).option(`--include-platform`,`Also list platform captures (they do not count toward your limit)`).action(async(n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching snapshots...`);o.start();let s=n?await U(a,i,n):void 0;if(!s||s.status===`deleted`){let n=await a.listSnapshots({includePlatform:!!r.includePlatform,...s?{sandboxId:s.id}:{}});if(o.stop(),r.json)return e(n);t(n.snapshots.map(e=>({...e,sandbox:e.sandboxExists?e.sandboxId:`${e.sandboxId} (deleted)`,removeAfter:e.sandboxExists?`kept while it exists`:e.removeAfter?`${e.removeAfter.toISOString().slice(0,16).replace(`T`,` `)} UTC`:`not scheduled`,note:e.countsTowardLimit?``:`not counted toward your limit`})),[{key:`snapshotId`,header:`ID`,width:24},{key:`sandbox`,header:`Sandbox`,width:32},{key:`createdAt`,header:`Created`,width:16},{key:`removeAfter`,header:`Removed after`,width:24},{key:`note`,header:``,width:30}]);let i=n.olderNotListed;i&&console.log(`${i} more deleted sandbox${i===1?``:`es`} not shown here. List one with: tangle snapshot list <sandbox-id> (ids from \`tangle sandbox list --status deleted\`)`);let c=n.excluded.platform;c.count&&console.log(`${c.count} platform capture${c.count===1?``:`s`} (${rl(c.bytes)}) hidden; --include-platform to list`),n.retryable&&console.log(`Some snapshots could not be listed right now. Try again.`);return}let c=await s.listSnapshots();o.stop(),r.json?e(c):nl(c)}),n.command(`restore <sandbox-id> <snapshot-id>`).description(`Create a new sandbox from a snapshot`).option(`--billing-owner <userId>`,`Platform user that pays for the restored sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).action(async(t,n,i)=>{let{client:a}=z(i),o=f(`Restoring from snapshot...`);o.start();let s=await a.create({fromSnapshot:n,fromSandboxId:t,...i.billingOwner?{billingOwnerId:i.billingOwner}:{}});await s.waitFor(`running`,{timeoutMs:12e4}),o.stop(),i.json?e({sandboxId:s.id,restoredFrom:n,status:s.status}):(r(`New sandbox created: ${s.id}`),console.log(`Source snapshot: ${n}`))}),n.command(`revert <sandbox-id-or-name> [snapshot-id]`).description(`Revert an existing sandbox to a snapshot`).option(`--latest`,`Revert to the sandbox's newest snapshot`).action(async(t,n,i)=>{let{context:a,client:o}=z(i),s=Be(t);if(n&&i.latest)throw new A(`USAGE_INVALID`,`Pass a snapshot id or --latest, not both`,`Both ${n} and --latest were given`,`tangle snapshot revert ${s} ${Be(n)}`);let c=await U(o,a,t),l=n;if(!l){let e=[...await c.listSnapshots()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime()),n=e[0];if(!n)throw new A(`SNAPSHOT_NONE`,`${t} has no snapshot to revert to`,`A revert goes back to a snapshot taken earlier, and none was taken for this sandbox`,`tangle snapshot create ${s}`);if(!i.latest)throw i.json||(console.log(`Snapshots of ${t}, newest first:`),nl(e)),new A(`USAGE_INVALID`,`No snapshot id given`,`The newest is ${n.snapshotId}. Pass an id, or --latest for the newest`,`tangle snapshot revert ${s} --latest`);l=n.snapshotId}let u=f(`Reverting sandbox to snapshot...`);u.start();let d=await c.revertToSnapshot(l);await c.refresh(),u.stop(),i.json?e({sandboxId:c.id,snapshotId:d.snapshotId,status:c.status}):(r(`Sandbox reverted: ${c.id}`),console.log(`Source snapshot: ${d.snapshotId}`))}),n.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(t,n,i)=>{let{context:a,client:o}=z(i),s=f(`Deleting snapshot...`);s.start();let c=await(await U(o,a,t)).deleteSnapshot(n);s.stop(),i.json?e({success:!0,sandboxId:t,snapshotId:n,outcome:c.outcome}):c.outcome===`already_absent`?r(`Snapshot already gone: ${n}`):r(`Snapshot deleted: ${n}`)}),n}function nl(e){t(e.map(e=>({...e,size:rl(e.sizeBytes)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}function rl(e){if(!e)return`pending`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**r).toFixed(1))} ${n[r]}`}const il=()=>import(`./device-DL5SWx0P.mjs`);function al(){let e=new D(`solve`).description(`Participate in Tangle Solve competitions`);e.command(`clone <competition>`).description(`Clone the pinned competition repository`).argument(`[directory]`,`Destination directory`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t,n)=>(await import(`./clone-Cq83-HQa.mjs`)).cloneCompetition(e,t,n)),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(async(e,t)=>(await import(`./run-DXc2ylL9.mjs`)).runCompetition(e,t)),e.command(`submit [competition]`).description(`Submit checker evidence through the device account and Tempo`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).option(`--pr-url <url>`,`GitHub pull request containing the submission`).option(`--model <name>`,`Model used to produce the submission`).option(`--note <text>`,`Short note shown with the accepted submission`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await import(`./submit-SOtFQfrb.mjs`)).submitCompetition(e,t)),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(async e=>(await import(`./account-710v_GcH.mjs`)).showSolveAccount(e));let t=e.command(`device`).description(`List and revoke the Solve devices bound to your account`);return t.command(`list`).description(`List your devices and whether each may submit jobs on Tempo`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async e=>(await il()).listSolveDevices(e)),t.command(`revoke <address>`).description(`Permanently revoke a device; the local device is revoked with its own key`).option(`--reason <text>`,`Why the device is revoked (shown to the account)`).option(`--yes`,`Confirm the permanent revocation without a prompt`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await il()).revokeSolveDevice(e,t)),e}function ol(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function sl(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function cl(e){return`'${e.replace(/'/g,`''`)}'`}function ll(e){return e===`win32`?`NUL`:`/dev/null`}function ul(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${cl(`<token>`)}; ssh ${e.map(cl).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${sl(`<token>`)} ssh ${e.map(sl).join(` `)}`}function dl(e){return e.connection!==void 0&&!e.connection.ssh}function fl(){d(`SSH is not enabled for this sandbox.`),l(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function pl(e,t=[],n=process.platform){let r=ll(n);return[`-o`,`ProxyCommand=${e.proxyCommand}`,`-o`,`StrictHostKeyChecking=no`,`-o`,`UserKnownHostsFile=${r}`,`-o`,`GlobalKnownHostsFile=${r}`,`-o`,`LogLevel=ERROR`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=4`,`-o`,`TCPKeepAlive=yes`,`${e.username}@localhost`,`-p`,String(e.port),...t]}function ml(e,t=process.platform){return{stdio:`inherit`,cwd:Lr(void 0,t),env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:e}}}function hl(){return new D(`ssh`).description(`Open SSH session to a sandbox`).argument(`<ref>`,`Sandbox ID or name`).argument(`[sshArgs...]`,`Extra args passed through to ssh`).option(`-i, --identity-file <path>`,`Private key file to pass to ssh`).option(`--print`,`Print SSH command instead of connecting`).allowUnknownOption(!0).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=f(`Getting SSH credentials...`);a.start();let o=await U(i,r,e);if(dl(o)){a.stop(),fl();return}o=await W(o);let s=await o.ssh();if(a.stop(),!s){fl();return}let c={...s,proxyCommand:ol(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let u=pl(c,[...n.identityFile?[`-i`,Ee(n.identityFile),`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(ul(u,process.platform));return}l(`Connecting via tunnel...`);let p=Ge(`ssh`,u,ml(r.apiKey));p.on(`error`,e=>{e.code===`ENOENT`&&(d(`SSH client not found. Please install OpenSSH.`),process.exit(1)),N(e)}),p.on(`exit`,e=>{process.exit(e??0)})})}function gl(){let t=new D(`ssh-keys`).description(`Manage SSH keys`);return t.command(`list`).description(`List SSH keys`).action(async t=>{let n=f(`Fetching SSH keys...`);try{n.start();let r=await R(L(t)).sshKeys.list();n.stop(),t.json?e({sshKeys:r}):r.length===0?l(`No SSH keys found.`):i([`Name`,`Type`,`Fingerprint`,`Created`],r.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){n.stop(),N(e)}}),t.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(t,n)=>{let i=f(`Adding SSH key...`);try{let a=x(n.keyFile,`utf8`).trim();i.start();let o=await R(L(n)).sshKeys.create(t,a);i.stop(),n.json?e({sshKey:o}):r(`Added SSH key ${o.name} (${o.fingerprint})`)}catch(e){i.stop(),N(e)}}),t.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let n=f(`Deleting SSH key...`);try{n.start(),await R(L(t)).sshKeys.delete(e),n.stop(),r(`Deleted SSH key ${e}`)}catch(e){n.stop(),N(e)}}),t}function _l(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function vl(){return new D(`ssh-proxy`).description(`SSH proxy helper that pipes stdin/stdout to WebSocket`).argument(`<runtime-url>`,`Runtime WebSocket URL`).action(async e=>{let t=process.env.TANGLE_SSH_PROXY_AUTH_TOKEN;t||_l(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new URL(e.replace(/^http/,`ws`)),{default:r}=await import(`ws`),i=new r(n,{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),a;function o(){a&&=(clearInterval(a),void 0)}i.on(`open`,()=>{a=setInterval(()=>{i.readyState===r.OPEN&&i.ping()},15e3),a.unref?.(),process.stdin.on(`data`,e=>{i.readyState===r.OPEN&&i.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>i.close(1e3))}),i.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),i.on(`error`,e=>{o(),_l(`WebSocket error: ${e.message}`)}),i.on(`close`,e=>{o(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>i.close())})}const yl=[`claude-code`,`opencode`,`codex`,`kimi-code`,`prime`],bl=process.env.TANGLE_ROUTER_URL||`https://router.tangle.tools/v1`;function xl(e){let t=ze(e);if(t)return t;throw Error(`--model '${e}' has no provider. Pass a canonical id, for example 'google/${e}'.`)}function Sl(e){let t=e.harness??`claude-code`;if(!yl.includes(t))throw Error(`Unknown --harness '${t}'. Supported: ${yl.join(`, `)}.`);let n=Cl(e.maxTokens,2e5,`--max-tokens`),r=Cl(e.maxIterations,50,`--max-iterations`),i=e.maxWorkers===void 0?void 0:Cl(e.maxWorkers,0,`--max-workers`);return{harness:t,...e.model?{model:e.model}:{},maxTokens:n,maxIterations:r,...i===void 0?{}:{maxWorkers:i}}}function Cl(e,t,n){if(e===void 0)return t;let r=Number.parseInt(e,10);if(!Number.isFinite(r)||r<=0)throw Error(`${n} must be a positive integer, got '${e}'.`);return r}function wl(e){let t={maxTokens:e.maxTokens,maxIterations:e.maxIterations};return e.maxWorkers===void 0?{budget:t}:{budget:t,perWorker:{maxTokens:Math.max(1,Math.floor(e.maxTokens/e.maxWorkers)),maxIterations:Math.max(1,Math.floor(e.maxIterations/e.maxWorkers))}}}function Tl(e){let t=e.spentTotal,n=e.kind===`no-winner`?``:e.out;return{text:typeof n==`string`?n:typeof n==`object`&&n&&`content`in n&&typeof n.content==`string`?n.content:JSON.stringify(n),tokenUsage:{input:t.tokensKnown===!1?null:t.tokens.input,output:t.tokensKnown===!1?null:t.tokens.output},costUsd:t.usdKnown===!1?null:t.usd,status:e.kind===`no-winner`?`no-winner (${e.reason})`:`winner`}}let El=null;function Dl(){return El??=import(`@tangle-network/agent-runtime/kernel`).catch(e=>{throw El=null,e?.code===`ERR_MODULE_NOT_FOUND`?new A(`RUNTIME_UNAVAILABLE`,`Agent Runtime could not be loaded`,e.message,`npm install -g @tangle-network/sandbox-cli@latest`):e}),El}async function Ol(e,t,n){let r=L({apiKey:n.apiKey,baseUrl:n.baseUrl}),i=rn(`router`,process.env.TANGLE_ROUTER_URL||void 0,n.apiKey)??r.apiKey,a=R(r),{budget:o,perWorker:s}=wl(t),c=[],u={async create(e){let{TANGLE_API_KEY:t,...r}=e?.env??{},i=await a.create(e?.env?{...e,env:r}:e);return c.push({id:i.id,status:`spawned`}),n.json||l(`worker ${i.id} spawned`),i}},d=await Dl(),f=d.workerFromBackend({backend:`sandbox`,sandboxClient:u,maxIterations:1}),p=(e,n)=>f({...e,harness:t.harness},n),m={name:`supervisor`,harness:`cli-base`,model:{default:t.model??`gemini-3.5-flash-lite`,provider:t.model?xl(t.model):`google`},tools:{agent_runtime_coordination_spawn_worker:!0,agent_runtime_coordination_observe_agent:!0}},h={routerBaseUrl:bl,routerKey:i},g=Tl(await d.supervise(m,{goal:e},{budget:o,makeWorkerAgent:p,router:h,...s?{perWorker:s}:{},...t.model?{allowedModels:[t.model]}:{},runId:`supervise-${Me()}`})),ee=g.status===`winner`?`settled`:`failed`;for(let e of c)e.status=ee,n.json||l(`worker ${e.id} settled (${e.status})`);return{task:e,result:g.text,workers:c,tokenUsage:g.tokenUsage,costUsd:g.costUsd,status:g.status}}function kl(){let t=new D(`supervise`);return t.description(`Run a budget-conserving supervisor that spawns isolated sandbox workers to deliver a task.`).argument(`<task>`,`What the supervisor should accomplish`).option(`--harness <name>`,`Worker harness (${yl.join(` | `)})`,`claude-code`).option(`--model <id>`,`Model for the supervisor + workers`).option(`--max-tokens <n>`,`Conserved token budget for the whole run`,`200000`).option(`--max-iterations <n>`,`Conserved iteration budget for the whole run`,`50`).option(`--max-workers <n>`,`Bound the fanout; each worker reserves floor(max-tokens / n) tokens and floor(max-iterations / n) iterations`).action(async(t,n)=>{let r=Sl({harness:n.harness,model:n.model,maxTokens:n.maxTokens,maxIterations:n.maxIterations,maxWorkers:n.maxWorkers});n.json||(l(`Supervising: ${t}`),l(`harness=${r.harness} budget=${r.maxTokens}tok/${r.maxIterations}it`),console.log());let i=await Ol(t,r,{apiKey:n.apiKey,baseUrl:n.baseUrl,json:n.json});if(n.json){e(i),i.status!==`winner`&&(process.exitCode=1);return}if(console.log(),i.result&&(console.log(i.result),console.log()),s({"Input Tokens":i.tokenUsage.input??`Unavailable`,"Output Tokens":i.tokenUsage.output??`Unavailable`,Cost:i.costUsd===null?`Unavailable`:`$${i.costUsd.toFixed(4)}`}),i.status!==`winner`)throw Error(`Supervisor finished without a winner: ${i.status}`)}),t}function Al(){let n=new D(`team`).description(`Manage teams`);return Q(n,`list`).description(`List teams for the current account`).action(async n=>{let r=L(n),i=R(r),a=n.json?null:f(`Fetching teams...`);a?.start();let o=await i.teams.list();if(a?.stop(),n.json){e({teams:o,activeTeamId:r.activeTeamId??null});return}t(o.map(e=>({active:e.id===r.activeTeamId,id:e.id,name:e.name,role:e.currentUserRole,members:e.memberCount})),[{key:`active`,header:`Active`,width:8},{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:24},{key:`role`,header:`Role`,width:10},{key:`members`,header:`Members`,width:10}])}),Q(n,`create <name>`).description(`Create a team`).option(`--org-id <id>`,`External organization id`).option(`--no-switch`,`Do not set the new team as active`).action(async(t,n)=>{let i=L(n),a=R(i),o=n.json?null:f(`Creating team...`);o?.start();let s=await a.teams.create({name:t,orgId:n.orgId});if(n.switch&&qo(s,i.profile),o?.stop(),n.json){e({team:s,active:!!n.switch});return}r(`Team created: ${Go(s)}`),n.switch&&r(`Active team set to ${s.name}`)}),Q(n,`switch <team>`).description(`Set the active team for the current profile`).action(async(t,n)=>{let i=L(n),a=await Ko(R(i),t);if(qo(a,i.profile),n.json){e({team:a,activeTeamId:a.id});return}r(`Active team set to ${Go(a)}`)}),n.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{let n=vn(t.profile);if(t.json){e(n.activeTeamId?n:{activeTeamId:null});return}if(!n.activeTeamId){console.log(`No active team.`);return}s({ID:n.activeTeamId,Name:n.activeTeamName})}),n.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{if(Jo(t.profile),t.json){e({activeTeamId:null});return}r(`Active team cleared.`)}),Q(n,`members [team]`).description(`List team members`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listMembers(o.id);if(r.json){e({team:o,members:s});return}t(s,[{key:`id`,header:`ID`,width:36},{key:`customerEmail`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:10},{key:`joinedAt`,header:`Joined`,width:16}])}),Q(n,`update-member <member-id>`).description(`Update a team member role`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).requiredOption(`--role <role>`,`Role: admin, member, viewer`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile),c=jl(n.role),l=await a.teams.updateMember(o.id,t,{role:c});if(n.json){e({team:o,member:l});return}r(`Member updated: ${l.customerEmail}`),s({Team:o.name,Role:l.role,Status:l.status})}),Q(n,`invite <email>`).description(`Invite a user to a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--role <role>`,`Role: admin, member, viewer`,`member`).option(`--ttl-hours <hours>`,`Invitation lifetime in hours`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile),c=jl(n.role),l=await a.teams.invite(o.id,{email:t,role:c,ttlHours:n.ttlHours?B(n.ttlHours,`--ttl-hours`):void 0});if(n.json){e({team:o,invitation:l});return}r(`Invitation created for ${l.email}`),s({Team:o.name,Role:l.role,Expires:l.expiresAt,"Invitation ID":l.id}),r(`Re-run with --json to retrieve the invitation token for sharing.`)}),Q(n,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,t,i.profile);if(!(!n.force&&!n.json&&!await G(`Leave team '${o.name}'? (y/N) `,`--force`))){if(await a.teams.leave(o.id),i.activeTeamId===o.id&&Jo(i.profile),n.json){e({success:!0,teamId:o.id});return}r(`Left team: ${o.name}`)}}),Q(n,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,n,a.profile);if(!(!i.force&&!i.json&&!await G(`Transfer ownership of '${s.name}' to ${t}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await o.teams.transferOwnership(s.id,t),i.json){e({success:!0,teamId:s.id,newOwnerCustomerId:t});return}r(`Ownership transferred for ${s.name}`)}}),n.addCommand(Ml()),n.addCommand(Nl()),Q(n,`invitations [team]`).description(`List pending and historical team invitations`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listInvitations(o.id);if(r.json){e({team:o,invitations:s});return}t(s,[{key:`id`,header:`ID`,width:38},{key:`email`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:12},{key:`expiresAt`,header:`Expires`,width:16}])}),Q(n,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(t,n)=>{let i=L(n),a=R(i),o=await a.teams.acceptInvitation(t),s=n.switch===!1?null:await a.teams.get(o.teamId);if(s&&qo(s,i.profile),n.json){e({member:o,activeTeamId:s?.id??null});return}r(`Invitation accepted for team ${o.teamId}`),s&&r(`Active team set to ${s.name}`)}),Q(n,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(t,n)=>{if(await R(L(n)).teams.revokeInvitation(t),n.json){e({success:!0,invitationId:t});return}r(`Invitation revoked: ${t}`)}),Q(n,`remove-member <member-id>`).description(`Remove a member from a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(await a.teams.removeMember(o.id,t),n.json){e({success:!0,teamId:o.id,memberId:t});return}r(`Member removed: ${t}`)}),n}function jl(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function Ml(){let n=new D(`secret`).description(`Manage team secrets`);return Q(n,`list [team]`).description(`List team secret names`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listSecrets(o.id);if(r.json){e({team:o,secrets:s});return}t(s,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),Q(n,`set <name> [value]`).description(`Create or replace a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,i.team,a.profile),c=await $c({value:n,valueStdin:i.valueStdin,prompt:`Enter value for team secret '${t}': `}),l=await o.teams.upsertSecret(s.id,t,c);if(i.json){e({team:s,secret:l});return}r(`Team secret saved: ${l.name}`)}),Q(n,`delete <name>`).description(`Delete a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(!(!n.force&&!n.json&&!await G(`Delete team secret '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteSecret(o.id,t),n.json){e({success:!0,teamId:o.id,name:t});return}r(`Team secret deleted: ${t}`)}}),Q(n,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let r=L(n),i=R(r),a=await Y(i,n.team,r.profile),o=await i.teams.revealSecret(a.id,t);if(n.json){e({teamId:a.id,...o});return}console.log(o.value)}),n}function Nl(){let n=new D(`templates`).description(`Manage team golden-path templates`);return Q(n,`list [team]`).description(`List a team's golden-path templates`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listTemplates(o.id);if(r.json){e({team:o,templates:s});return}if(s.length===0){console.log(`No templates yet for ${o.name}.`);return}t(s.map(e=>({id:e.id,name:e.name,environment:e.environment,snapshot:`${e.snapshotId.slice(0,12)}…`,updated:e.updatedAt})),[{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:28},{key:`environment`,header:`Env`,width:14},{key:`snapshot`,header:`Snapshot`,width:16},{key:`updated`,header:`Updated`,width:24}])}),Q(n,`create <name> <snapshot-id>`).description(`Create a golden-path template from a snapshot`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`-d, --description <description>`,`Human-readable description shown in the dashboard`).option(`-e, --environment <environment>`,`Default environment to apply (defaults to 'universal')`).option(`--config <json>`,`Optional JSON config object merged into sandboxes created from this template`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,i.team,a.profile),c;if(i.config)try{let e=JSON.parse(i.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);c=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let l=await o.teams.createTemplate(s.id,{name:t,snapshotId:n,description:i.description,environment:i.environment,config:c});if(i.json){e({team:s,template:l});return}r(`Team template created: ${l.name} (${l.id})`)}),Q(n,`delete <template-id>`).description(`Delete a team golden-path template`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(!(!n.force&&!n.json&&!await G(`Delete template '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteTemplate(o.id,t),n.json){e({success:!0,teamId:o.id,templateId:t});return}r(`Team template deleted: ${t}`)}}),n}function Q(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function Pl(t,n,i){let a=new AbortController,o=()=>a.abort();try{let i=R(L({...t,timeout:void 0}));process.once(`SIGINT`,o),process.once(`SIGTERM`,o);let s=await n(i,{...t.timeout===void 0?{}:{timeoutMs:V(t.timeout,`--timeout`)*1e3},resumeJobId:t.resumeJob,signal:a.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,o)});t.json?e(s):r(`template`in s?`Published template: ${s.template.slug}`:`Published template version: ${s.version.id}`)}catch(e){if(e instanceof se&&e.status!==401&&e.job&&[`pending`,`scanning`,`ready`].includes(e.job.status)){let t=[`tangle`,`template`,...i,`--resume-job`,e.job.id].map(Be).join(` `);Object.assign(e,{fix:{command:t}})}N(e,t.json)}}function Fl(){let n=new D(`template`).description(`Manage published public templates`);return n.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async n=>{let r=R(L(n)),i=n.featured?await r.publicTemplates.featured():await r.publicTemplates.list({query:n.query,tag:n.tag});if(n.json){e({templates:i});return}t(i,[{key:`slug`,header:`Slug`,width:28},{key:`name`,header:`Name`,width:28},{key:`forkCount`,header:`Forks`,width:8},{key:`sandboxCount`,header:`Sandboxes`,width:12},{key:`updatedAt`,header:`Updated`,width:24}])}),n.command(`get <id-or-slug>`).action(async(t,n)=>{let r=await R(L(n)).publicTemplates.get(t);if(n.json){e({template:r});return}e(r)}),n.command(`versions <id-or-slug>`).action(async(n,r)=>{let i=await R(L(r)).publicTemplates.versions(n);if(r.json){e({versions:i});return}t(i.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`createdAt`,header:`Created`,width:24}])}),n.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--slug <slug>`,`Stable public slug`).option(`-d, --description <description>`,`Template description`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).option(`--team-id <id>`,`Publish under a team`).option(`--forked-from <id>`,`Fork source template id`).action((e,t,n,r)=>Pl(r,async(i,a)=>({template:await i.publicTemplates.publish({name:e,slug:r.slug,description:r.description,snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes,teamId:r.teamId,forkedFromTemplateId:r.forkedFrom},a)}),[`publish`,e,t,n])),n.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).action((e,t,n,r)=>Pl(r,async(i,a)=>({version:await i.publicTemplates.publishVersion(e,{snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes},a)}),[`publish-version`,e,t,n])),n}function Il(){let t=new D(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return t.command(`list`).description(`List trace summaries (one row per trace), newest first`).option(`--from <iso>`,`ISO-8601 lower bound on received time (inclusive)`).option(`--to <iso>`,`ISO-8601 upper bound on received time (inclusive)`).option(`--model <model>`,`Exact model match (any span carried this model)`).option(`--run <runId>`,`Exact run id match`).option(`--status <status>`,`ERROR | OK`).option(`-q, --query <text>`,`Substring over span name`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size (clamped server-side to [1, 200])`).action(async t=>{try{let n={from:t.from,to:t.to,model:t.model,runId:t.run,status:t.status===void 0?void 0:ql(t.status),q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:Ql(t.limit)},r=Rl(t),i=t.json?null:f(`Fetching traces...`);i?.start();let a=await r.listTraces(n);if(i?.stop(),t.json)return e(a);Vl(a.items),Gl(a.nextCursor)}catch(e){Bl(e,t)}}),t.command(`get <traceId>`).description(`Show one trace's spans. Streams NDJSON to stdout with --ndjson.`).option(`--ndjson`,`Stream the full span set as NDJSON to stdout`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Spans per page`).action(async(t,n)=>{try{let r=Rl(n);if(n.ndjson){await zl(r,t);return}let i=n.json?null:f(`Fetching trace spans...`);i?.start();let a=await r.getTraceSpans(t,{cursor:n.cursor,limit:n.limit===void 0?void 0:Ql(n.limit)});if(i?.stop(),!n.cursor&&a.items.length===0)throw new A(`TRACE_NOT_FOUND`,`No spans for trace ${t}`,`A turn's spans arrive about a minute after it ends, and a key reads only its own account's traces`,`tangle traces list --limit 5`);if(n.json)return e(a);Hl(a.items),a.truncated&&s({Spans:`${a.items.length} of ${a.total} (truncated)`}),Gl(a.nextCursor)}catch(e){Bl(e,n)}}),t.addCommand(Ll()),t}function Ll(){let t=new D(`runs`).description(`Read eval-runs pivoted off the trace surface`);return t.command(`list`).description(`List eval-runs, newest first`).option(`--status <status>`,`Run status filter`).option(`--gate <decision>`,`Promotion-gate decision filter`).option(`--label <key:value>`,`Match over the run's labels`).option(`--from <iso>`,`ISO-8601 lower bound on received time`).option(`--to <iso>`,`ISO-8601 upper bound on received time`).option(`-q, --query <text>`,`Substring over run dir`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size`).action(async t=>{try{let n={status:t.status===void 0?void 0:Yl(t.status),gate:t.gate===void 0?void 0:Zl(t.gate),label:t.label,from:t.from,to:t.to,q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:Ql(t.limit)},r=Rl(t),i=t.json?null:f(`Fetching runs...`);i?.start();let a=await r.listRuns(n);if(i?.stop(),t.json)return e(a);Ul(a.items),Gl(a.nextCursor)}catch(e){Bl(e,t)}}),t.command(`get <runId>`).description(`Show a single eval-run`).action(async(t,n)=>{try{let r=Rl(n),i=n.json?null:f(`Fetching run...`);i?.start();let a=await r.getRun(t);if(i?.stop(),n.json)return e(a);Wl(a)}catch(e){Bl(e,n)}}),t}function Rl(e){let t=e.baseUrl||process.env.TANGLE_INTELLIGENCE_BASE_URL||void 0,n=rn(`intelligence`,t,e.apiKey);if(!n)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return dt({apiKey:n,baseUrl:t})}async function zl(e,t){let n=(await e.exportTraceSpansNdjson(t)).getReader();try{for(;;){let{value:e,done:t}=await n.read();if(t)break;e&&process.stdout.write(Buffer.from(e))}}finally{n.releaseLock()}}function Bl(e,t){return N(e,t.json===!0)}function Vl(e){t(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:Kl(e.costUsd)})),[{key:`traceId`,header:`Trace`,width:36},{key:`root`,header:`Root`,width:24},{key:`model`,header:`Model`,width:22},{key:`spans`,header:`Spans`,width:8},{key:`errors`,header:`Errors`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14},{key:`cost`,header:`Cost`,width:10}])}function Hl(e){t(e.map(e=>({spanId:e.id,name:e.name,model:e.model??`-`,status:e.statusCode??`-`,cost:e.costUsd===null?`-`:`$${e.costUsd}`})),[{key:`spanId`,header:`Span`,width:40},{key:`name`,header:`Name`,width:28},{key:`model`,header:`Model`,width:22},{key:`status`,header:`Status`,width:10},{key:`cost`,header:`Cost`,width:12}])}function Ul(e){t(e.map(e=>({runId:e.id,status:e.status,gate:e.gateDecision??`-`,cost:e.totalCostUsd===null?`-`:`$${e.totalCostUsd}`,receivedAt:e.receivedAt})),[{key:`runId`,header:`Run`,width:24},{key:`status`,header:`Status`,width:22},{key:`gate`,header:`Gate`,width:18},{key:`cost`,header:`Cost`,width:12},{key:`receivedAt`,header:`Received`,width:18}])}function Wl(e){s({Run:e.id,Status:e.status,Gate:e.gateDecision??void 0,"Run Dir":e.runDir??void 0,Cost:e.totalCostUsd===null?void 0:`$${e.totalCostUsd}`,Duration:e.totalDurationMs===null?void 0:`${e.totalDurationMs}ms`,"Holdout Lift":e.holdoutLift??void 0,Received:e.receivedAt})}function Gl(e){e&&s({"Next page":`--cursor ${e}`})}function Kl(e){return e===null?`-`:`$${e.toFixed(4)}`}function ql(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const Jl=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function Yl(e){let t=Jl.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${Jl.join(`, `)}`)}const Xl=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function Zl(e){let t=Xl.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Xl.join(`, `)}`)}function Ql(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}const $l=`@tangle-network/sandbox-cli`,eu=`curl -fsSL https://sandbox.tangle.tools/install.sh | sh`,tu=/^\d+\.\d+\.\d+$/,nu=()=>process.env.TANGLE_CLI_HOME||E(He(),`.local/share/tangle-cli`);function ru(e){let t=E(nu(),`versions`);if(y(t)&&e.startsWith(ne(t)+De))return`tangle update`;let n=E(nu(),`node_modules`,$l);if(y(n)&&ne(n)===e)return`tangle update`;if(e.endsWith(E(`lib`,`node_modules`,$l)))return`npm install -g ${$l}@latest`;if(e.includes(E(`pnpm`,`global`,``)))return`pnpm add -g ${$l}@latest`;if(e.includes(`${De}node_modules${De}`))return``}const iu=()=>`${process.env.TANGLE_NPM_REGISTRY??`https://registry.npmjs.org`}/${$l.replace(`/`,`%2F`)}/latest`,au=`const fs = require("node:fs");
|
|
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
|
+
A preview URL is reachable from outside the sandbox only. Inside the box, test
|
|
154
|
+
the app on localhost:<port>; requests from the box to preview origins
|
|
155
|
+
(<sandbox>-<port>.tangle.sh) are refused by the egress proxy (403 on CONNECT).
|
|
156
|
+
lastProbe.httpStatus is whatever your app returned for the platform's probe
|
|
157
|
+
path. Any status your app returns means the edge reached it; your app does not
|
|
158
|
+
need to serve /.well-known/tangle-preview-readiness.`;function Hc(){let t=new D(`preview`).description(`Manage sandbox preview links`);return Bc(t.command(`start`).description(`Start/reuse a managed development server and publish its ready preview`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).option(`--cwd <directory>`,`Project directory in the selected workspace`).option(`--session <session-id>`,`Select the agent's session workspace`).option(`--name <name>`,`App/service label`).addHelpText(`after`,Vc)).action(async(t,n)=>{let i=await Rc(t,n),a=await zc(`Starting managed preview...`,n.json,()=>st(i,{cwd:n.cwd,sessionId:n.session,name:n.name}));n.json?e(a):(r(`Preview ready: ${a.url}`),console.log(`Preview ID: ${a.previewId}`))}),Bc(t.command(`list`).alias(`ls`).description(`List active preview links for a sandbox`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`)).action(async(t,n)=>{let r=await Rc(t,n),a=await zc(`Fetching preview links...`,n.json,()=>r.previewLinks.list());n.json?e(a):a.length===0?console.log(`No preview links found`):i([`App`,`Preview ID`,`Port`,`URL`,`Status`],a.map(e=>[Uc(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),Bc(t.command(`publish`).description(`Publish one existing HTTP service; never starts or replaces a process`).argument(`[id-or-name]`,`Sandbox ID or name`).option(`--self`,`Use only the sandbox bound to the runtime credential`).requiredOption(`--port <port>`,`Existing service port`).option(`--name <name>`,`App/service label`).addHelpText(`after`,Vc)).action(async(t,n)=>{if(!n.port||!/^\d+$/.test(n.port))throw Error(`An integer service port is required`);let i=await Rc(t,n),a=await zc(`Publishing service...`,n.json,()=>ct(i,{port:Number(n.port),name:n.name}));n.json?e(a):r(`Preview ready: ${a.url}`)}),Bc(t.command(`create`).description(`Create a preview link for a port`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<port>`,`Port number to preview`)).action(async(t,n,i)=>{if(!/^\d+$/.test(n)||Number(n)<1||Number(n)>65535)throw Error(`Port must be an integer between 1 and 65535`);let a=await Rc(t,i),o=await zc(`Creating preview for port ${n}...`,i.json,()=>a.previewLinks.create(Number(n)));i.json?e(o):(r(`Preview created: ${o.url}`),console.log(`Preview ID: ${o.previewId}`))}),Bc(t.command(`remove`).alias(`rm`).description(`Remove a preview link`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<preview-id>`,`Preview link ID (from 'preview list')`)).action(async(t,n,i)=>{let a=await Rc(t,i);await zc(`Removing preview...`,i.json,()=>a.previewLinks.remove(n)),i.json?e({success:!0,previewId:n}):r(`Preview removed: ${n}`)}),t}function Uc(e){let t=e?.app;if(!t||typeof t!=`object`)return``;let n=`name`in t?t.name:void 0,r=`cwd`in t?t.cwd:void 0;return typeof n==`string`?n:typeof r==`string`?r:``}function Wc(){let t=new D(`process`).description(`Manage processes in a sandbox`);return t.command(`spawn`).description(`Spawn a process without blocking (returns PID)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<command>`,`Command to execute`).option(`--cwd <dir>`,`Working directory`).option(`--env <vars...>`,`Environment variables (KEY=VALUE)`).option(`-t, --timeout <ms>`,`Timeout in milliseconds`).option(`--blocking`,`Wait for completion (default: false)`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=bo(r.env??[],`--env`,`env`),s=r.timeout?V(r.timeout,`--timeout`,`ms`,0):void 0,c=f(`Spawning: ${n}`);r.json||c.start();let l=await U(a,i,t);if(l=await W(l),r.blocking){let t=await l.exec(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e(t):(t.stdout&&globalThis.process.stdout.write(t.stdout),t.stderr&&globalThis.process.stderr.write(t.stderr),t.exitCode!==0&&globalThis.process.exit(t.exitCode))}else{let i=await l.process.spawn(n,{cwd:r.cwd,env:Object.keys(o).length>0?o:void 0,timeoutMs:s});c.stop(),r.json?e({pid:i.pid,command:i.command}):(console.log(`Process started with PID: ${i.pid}`),console.log(`Use 'tangle process logs ${t} ${i.pid}' to view output`))}}),t.command(`list`).alias(`ls`).description(`List all processes in a sandbox`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--running`,`Show only running processes`).action(async(t,n)=>{let{context:r,client:a}=z(n),o=f(`Fetching processes...`);n.json||o.start();let s=await U(a,r,t);s=await W(s);let c=await s.process.list();n.running&&(c=c.filter(e=>e.running)),o.stop(),n.json?e(c):c.length===0?console.log(`No processes found`):i([`PID`,`Command`,`Status`,`Exit Code`,`Started`],c.map(e=>[String(e.pid),e.command.length>40?`${e.command.slice(0,37)}...`:e.command,e.running?`running`:`exited`,String(e.exitCode),e.startedAt.toLocaleString()]))}),t.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching process info...`);r.json||o.start();let s=await U(a,i,t);s=await W(s);let c=await s.process.get(Number.parseInt(n,10));if(o.stop(),!c){console.error(`Process ${n} not found`),globalThis.process.exit(1);return}let l=await c.status();r.json?e(l):(console.log(`PID: ${l.pid}`),console.log(`Command: ${l.command}`),console.log(`CWD: ${l.cwd||`(default)`}`),console.log(`Status: ${l.running?`running`:`exited`}`),console.log(`Exit Code: ${l.exitCode}`),l.exitSignal&&console.log(`Signal: ${l.exitSignal}`),console.log(`Started: ${l.startedAt.toLocaleString()}`),l.exitedAt&&console.log(`Exited: ${l.exitedAt.toLocaleString()}`))}),t.command(`kill`).description(`Kill a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`-s, --signal <signal>`,`Signal to send (SIGTERM, SIGKILL, etc.)`,`SIGTERM`).option(`--tree`,`Also kill descendants of the tracked process`).action(async(t,n,r)=>{let{context:i,client:a}=z(r),o=f(`Sending ${r.signal} to PID ${n}...`);r.json||o.start();let s=await U(a,i,t);s=await W(s);let c=await s.process.get(Number.parseInt(n,10));if(!c){o.stop(),console.error(`Process ${n} not found`),globalThis.process.exit(1);return}r.tree?await c.kill(r.signal,{tree:!0}):await c.kill(r.signal),o.stop(),r.json?e({pid:Number.parseInt(n,10),signal:r.signal,...r.tree===!0?{tree:!0}:{},killed:!0}):console.log(r.tree?`Sent ${r.signal} to process tree ${n}`:`Sent ${r.signal} to process ${n}`)}),t.command(`logs`).description(`Stream buffered and live process logs until the process exits`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).option(`--stdout-only`,`Only show stdout`).option(`--stderr-only`,`Only show stderr`).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=await U(i,r,e);a=await W(a);let o=await a.process.get(Number.parseInt(t,10));if(!o){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}for await(let e of o.logs())n.stdoutOnly&&e.type!==`stdout`||n.stderrOnly&&e.type!==`stderr`||(n.json?console.log(JSON.stringify(e)):e.type===`stdout`?globalThis.process.stdout.write(e.data):globalThis.process.stderr.write(e.data))}),t}const Gc=[`python`,`node`,`typescript`,`bash`];function Kc(e){switch(Te(e).toLowerCase()){case`.py`:return`python`;case`.js`:case`.mjs`:case`.cjs`:return`node`;case`.ts`:case`.tsx`:return`typescript`;case`.sh`:case`.bash`:return`bash`;default:return}}async function qc(e){if(e===`-`){let e=[];for await(let t of process.stdin)e.push(typeof t==`string`?Buffer.from(t):t);return Buffer.concat(e).toString(`utf8`)}return await ot(Ee(e),`utf8`)}async function Jc(e,t,n=qc){let r=t?Gc.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${Gc.join(`, `)}`)})():void 0;if(!e||e===`-`){if(!r)throw Error(`reading from stdin requires --lang. Example: tangle run <id> -l python -`);return{language:r,source:await n(`-`)}}let i=Kc(e);return{language:r??i??(()=>{throw Error(`cannot infer language from "${e}". Pass it explicitly: tangle run <id> -l <python|node|typescript|bash> ${e}`)})(),source:await n(e)}}function Yc(e){return E(Ue(),`tangle-run-images`,e)}function Xc(){return new D(`run`).description(`Run code in a persistent kernel inside a sandbox. Variables persist across calls in the same --session.`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`[file]`,`Path to source file. Language is inferred from extension. Use - for stdin (requires --lang).`).option(`-l, --lang <lang>`,`Force language: ${Gc.join(` | `)}. Required for stdin.`).option(`-s, --session <id>`,`Session id for kernel scoping`).option(`-t, --timeout <ms>`,`Per-call timeout in ms (0 disables)`,`60000`).option(`--save-images <dir>`,`Write image results into this directory (default: $TMPDIR/tangle-run-images/<sandbox>/).`).option(`--no-save-images`,`Don't write image results to disk; print summary only`).action(async(t,n,r)=>{let{language:i,source:a}=await Jc(n,r.lang),o=V(r.timeout,`--timeout`,`ms`,0),{context:s,client:c}=z(r),l=await U(c,s,t);l=await W(l);let u=f(`Running ${i} (${a.length}b)…`);r.json||u.start();let d=await l.runCode(i,a,{sessionId:r.session,timeoutMs:o});if(u.stop(),r.json){e(d),d.exitCode!==0&&process.exit(d.exitCode);return}d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr);let p=0;for(let e of d.results)if(e.type===`image`)if(r.saveImages!==!1){let n=typeof r.saveImages==`string`?r.saveImages:Yc(t);b(n,{recursive:!0});let i=`${n}/${Date.now()}-${p}.${e.format}`;S(i,Buffer.from(e.data,`base64`)),process.stderr.write(T.green(`✓ image → ${i}\n`)),p++}else process.stderr.write(T.gray(`[image: ${e.format}, ${e.data.length}b base64]\n`));else if(e.type===`dataframe`){let t=e.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(T.gray(`[dataframe ${e.rows.length}×${e.columns.length}${e.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${t}\n`);for(let t of e.rows.slice(0,20))process.stderr.write(`${t.map(e=>String(e)).join(` | `)}\n`);e.rows.length>20&&process.stderr.write(T.gray(`… ${e.rows.length-20} more rows\n`))}else e.type===`json`?(process.stderr.write(T.gray(`[json] `)),process.stderr.write(`${JSON.stringify(e.value,null,2)}\n`)):e.type===`html`?process.stderr.write(T.gray(`[html ${e.value.length}b]\n`)):e.type===`error`?(process.stderr.write(T.red(`✗ ${e.name}: ${e.message}\n`)),e.traceback&&process.stderr.write(`${e.traceback}\n`)):e.type===`text`&&process.stderr.write(`${e.value}\n`);d.error&&(process.stderr.write(T.red(`\n✗ ${d.error.name}: ${d.error.message}\n`)),d.error.traceback&&process.stderr.write(`${d.error.traceback}\n`)),d.exitCode!==0&&process.exit(d.exitCode)})}function Zc(){let e=new D(`sandbox`).description(`Manage sandboxes`);return cs(e),Qo(e),Uo(e),ss(e),e}function Qc(){return new D(`search`).description(`Search for text patterns in sandbox files (ripgrep)`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pattern>`,`Search pattern (regex)`).option(`-g, --glob <pattern>`,`File glob filter (e.g. '**/*.ts')`).option(`-n, --max-results <count>`,`Max results to return`).option(`-i, --ignore-case`,`Case-insensitive search`).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=f(`Searching...`);n.json||a.start();let o=await U(i,r,e),s=0,c=n.maxResults?Number.parseInt(n.maxResults,10):void 0,l={};n.glob&&(l.glob=n.glob),n.ignoreCase&&(l.ignoreCase=!0),c&&(l.maxResults=c);for await(let e of o.search(t,l))if(s===0&&a.stop(),s++,n.json?console.log(JSON.stringify(e)):console.log(`${e.path}:${e.line}:${e.column??0}: ${e.text}`),c&&s>=c)break;a.stop(),s===0&&!n.json&&console.log(`No matches found`)})}function $c(){let t=new D(`secret`).description(`Manage secrets`);return t.command(`create`).description(`Create a new secret`).argument(`<name>`,`Secret name (e.g., HF_TOKEN, AWS_ACCESS_KEY)`).argument(`[value]`,`Secret value`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,n,i)=>{let a=await z(i).client.secrets.create(t,await el({value:n,valueStdin:i.valueStdin,prompt:`Enter value for secret '${t}': `}));i.json?e(a):(r(`Secret created: ${a.name}`),l(`Use --secret ${a.name} when creating a sandbox to select it for delivery.`))}),t.command(`list`).description(`List all secrets`).action(async t=>{let n=await z(t).client.secrets.list();t.json?e(n):n.length===0?(l(`No secrets found.`),l(`Use 'tangle secret create <name> [value]' to create one.`)):i([`Name`,`Created At`,`Updated At`],n.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),t.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=z(n).client;if(!n.force&&!await G(`Are you sure you want to delete secret '${t}'? This cannot be undone. (y/N) `,`--force`)){l(`Cancelled.`);return}await i.secrets.delete(t),n.json?e({success:!0,deleted:t}):r(`Secret deleted: ${t}`)}),t}async function el(e){if(e.value!==void 0&&e.valueStdin)throw Error(`Provide either a secret value argument or --value-stdin, not both`);let t=e.value??(e.valueStdin?await mr():await pr(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function tl(){let e=new D(`skill`).description(`Print paths to shipped skill documentation`);return e.command(`path`).description(`Print the absolute path to the SKILL.md shipped with this CLI`).action(()=>{let e=Se.dirname(ut(import.meta.url)),t=Se.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function nl(){let n=new D(`snapshot`).description(`Manage snapshots`);return n.command(`create <sandbox-id-or-name>`).description(`Create a snapshot of a sandbox`).option(`--tags <tags...>`,`Tags for the snapshot`).option(`--no-wait`,`Return once the snapshot is accepted and print the operation to poll`).action(async(t,n)=>{let{context:i,client:a}=z(n),o=f(`Creating snapshot...`);o.start();let s=await U(a,i,t);if(n.wait===!1){let e=await s.snapshot({tags:n.tags,wait:!1});o.stop(),Wo(e.info,!!n.json);return}let c=await s.snapshot({tags:n.tags});o.stop(),n.json?e(c):(r(`Snapshot created: ${c.snapshotId}`),console.log(`Size: ${il(c.sizeBytes)}`))}),n.command(`list [sandbox-id-or-name]`).description(`List snapshots for a sandbox; with no sandbox, the snapshots you own, including your most recently deleted sandboxes'`).option(`--include-platform`,`Also list platform captures (they do not count toward your limit)`).action(async(n,r)=>{let{context:i,client:a}=z(r),o=f(`Fetching snapshots...`);o.start();let s=n?await U(a,i,n):void 0;if(!s||s.status===`deleted`){let n=await a.listSnapshots({includePlatform:!!r.includePlatform,...s?{sandboxId:s.id}:{}});if(o.stop(),r.json)return e(n);t(n.snapshots.map(e=>({...e,sandbox:e.sandboxExists?e.sandboxId:`${e.sandboxId} (deleted)`,removeAfter:e.sandboxExists?`kept while it exists`:e.removeAfter?`${e.removeAfter.toISOString().slice(0,16).replace(`T`,` `)} UTC`:`not scheduled`,note:e.countsTowardLimit?``:`not counted toward your limit`})),[{key:`snapshotId`,header:`ID`,width:24},{key:`sandbox`,header:`Sandbox`,width:32},{key:`createdAt`,header:`Created`,width:16},{key:`removeAfter`,header:`Removed after`,width:24},{key:`note`,header:``,width:30}]);let i=n.olderNotListed;i&&console.log(`${i} more deleted sandbox${i===1?``:`es`} not shown here. List one with: tangle snapshot list <sandbox-id> (ids from \`tangle sandbox list --status deleted\`)`);let c=n.excluded.platform;c.count&&console.log(`${c.count} platform capture${c.count===1?``:`s`} (${il(c.bytes)}) hidden; --include-platform to list`),n.retryable&&console.log(`Some snapshots could not be listed right now. Try again.`);return}let c=await s.listSnapshots();o.stop(),r.json?e(c):rl(c)}),n.command(`restore <sandbox-id> <snapshot-id>`).description(`Create a new sandbox from a snapshot`).option(`--billing-owner <userId>`,`Platform user that pays for the restored sandbox. The API accepts this only from a first-party service key that is listed as a billing delegate, and refuses such a key that names no payer.`).action(async(t,n,i)=>{let{client:a}=z(i),o=f(`Restoring from snapshot...`);o.start();let s=await a.create({fromSnapshot:n,fromSandboxId:t,...i.billingOwner?{billingOwnerId:i.billingOwner}:{}});await s.waitFor(`running`,{timeoutMs:12e4}),o.stop(),i.json?e({sandboxId:s.id,restoredFrom:n,status:s.status}):(r(`New sandbox created: ${s.id}`),console.log(`Source snapshot: ${n}`))}),n.command(`revert <sandbox-id-or-name> [snapshot-id]`).description(`Revert an existing sandbox to a snapshot`).option(`--latest`,`Revert to the sandbox's newest snapshot`).action(async(t,n,i)=>{let{context:a,client:o}=z(i),s=Be(t);if(n&&i.latest)throw new A(`USAGE_INVALID`,`Pass a snapshot id or --latest, not both`,`Both ${n} and --latest were given`,`tangle snapshot revert ${s} ${Be(n)}`);let c=await U(o,a,t),l=n;if(!l){let e=[...await c.listSnapshots()].sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime()),n=e[0];if(!n)throw new A(`SNAPSHOT_NONE`,`${t} has no snapshot to revert to`,`A revert goes back to a snapshot taken earlier, and none was taken for this sandbox`,`tangle snapshot create ${s}`);if(!i.latest)throw i.json||(console.log(`Snapshots of ${t}, newest first:`),rl(e)),new A(`USAGE_INVALID`,`No snapshot id given`,`The newest is ${n.snapshotId}. Pass an id, or --latest for the newest`,`tangle snapshot revert ${s} --latest`);l=n.snapshotId}let u=f(`Reverting sandbox to snapshot...`);u.start();let d=await c.revertToSnapshot(l);await c.refresh(),u.stop(),i.json?e({sandboxId:c.id,snapshotId:d.snapshotId,status:c.status}):(r(`Sandbox reverted: ${c.id}`),console.log(`Source snapshot: ${d.snapshotId}`))}),n.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(t,n,i)=>{let{context:a,client:o}=z(i),s=f(`Deleting snapshot...`);s.start();let c=await(await U(o,a,t)).deleteSnapshot(n);s.stop(),i.json?e({success:!0,sandboxId:t,snapshotId:n,outcome:c.outcome}):c.outcome===`already_absent`?r(`Snapshot already gone: ${n}`):r(`Snapshot deleted: ${n}`)}),n}function rl(e){t(e.map(e=>({...e,size:il(e.sizeBytes)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}function il(e){if(!e)return`pending`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**r).toFixed(1))} ${n[r]}`}const al=()=>import(`./device-DL5SWx0P.mjs`);function ol(){let e=new D(`solve`).description(`Participate in Tangle Solve competitions`);e.command(`clone <competition>`).description(`Clone the pinned competition repository`).argument(`[directory]`,`Destination directory`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t,n)=>(await import(`./clone-Cq83-HQa.mjs`)).cloneCompetition(e,t,n)),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(async(e,t)=>(await import(`./run-DXc2ylL9.mjs`)).runCompetition(e,t)),e.command(`submit [competition]`).description(`Submit checker evidence through the device account and Tempo`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).option(`--pr-url <url>`,`GitHub pull request containing the submission`).option(`--model <name>`,`Model used to produce the submission`).option(`--note <text>`,`Short note shown with the accepted submission`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await import(`./submit-SOtFQfrb.mjs`)).submitCompetition(e,t)),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(async e=>(await import(`./account-710v_GcH.mjs`)).showSolveAccount(e));let t=e.command(`device`).description(`List and revoke the Solve devices bound to your account`);return t.command(`list`).description(`List your devices and whether each may submit jobs on Tempo`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async e=>(await al()).listSolveDevices(e)),t.command(`revoke <address>`).description(`Permanently revoke a device; the local device is revoked with its own key`).option(`--reason <text>`,`Why the device is revoked (shown to the account)`).option(`--yes`,`Confirm the permanent revocation without a prompt`).option(`--api-url <url>`,`Solve API base URL`).option(`--profile <name>`,`Tangle profile`,`solve`).action(async(e,t)=>(await al()).revokeSolveDevice(e,t)),e}function sl(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function cl(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function ll(e){return`'${e.replace(/'/g,`''`)}'`}function ul(e){return e===`win32`?`NUL`:`/dev/null`}function dl(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${ll(`<token>`)}; ssh ${e.map(ll).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${cl(`<token>`)} ssh ${e.map(cl).join(` `)}`}function fl(e){return e.connection!==void 0&&!e.connection.ssh}function pl(){d(`SSH is not enabled for this sandbox.`),l(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function ml(e,t=[],n=process.platform){let r=ul(n);return[`-o`,`ProxyCommand=${e.proxyCommand}`,`-o`,`StrictHostKeyChecking=no`,`-o`,`UserKnownHostsFile=${r}`,`-o`,`GlobalKnownHostsFile=${r}`,`-o`,`LogLevel=ERROR`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=4`,`-o`,`TCPKeepAlive=yes`,`${e.username}@localhost`,`-p`,String(e.port),...t]}function hl(e,t=process.platform){return{stdio:`inherit`,cwd:Lr(void 0,t),env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:e}}}function gl(){return new D(`ssh`).description(`Open SSH session to a sandbox`).argument(`<ref>`,`Sandbox ID or name`).argument(`[sshArgs...]`,`Extra args passed through to ssh`).option(`-i, --identity-file <path>`,`Private key file to pass to ssh`).option(`--print`,`Print SSH command instead of connecting`).allowUnknownOption(!0).action(async(e,t,n)=>{let{context:r,client:i}=z(n),a=f(`Getting SSH credentials...`);a.start();let o=await U(i,r,e);if(fl(o)){a.stop(),pl();return}o=await W(o);let s=await o.ssh();if(a.stop(),!s){pl();return}let c={...s,proxyCommand:sl(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let u=ml(c,[...n.identityFile?[`-i`,Ee(n.identityFile),`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(dl(u,process.platform));return}l(`Connecting via tunnel...`);let p=Ge(`ssh`,u,hl(r.apiKey));p.on(`error`,e=>{e.code===`ENOENT`&&(d(`SSH client not found. Please install OpenSSH.`),process.exit(1)),N(e)}),p.on(`exit`,e=>{process.exit(e??0)})})}function _l(){let t=new D(`ssh-keys`).description(`Manage SSH keys`);return t.command(`list`).description(`List SSH keys`).action(async t=>{let n=f(`Fetching SSH keys...`);try{n.start();let r=await R(L(t)).sshKeys.list();n.stop(),t.json?e({sshKeys:r}):r.length===0?l(`No SSH keys found.`):i([`Name`,`Type`,`Fingerprint`,`Created`],r.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){n.stop(),N(e)}}),t.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(t,n)=>{let i=f(`Adding SSH key...`);try{let a=x(n.keyFile,`utf8`).trim();i.start();let o=await R(L(n)).sshKeys.create(t,a);i.stop(),n.json?e({sshKey:o}):r(`Added SSH key ${o.name} (${o.fingerprint})`)}catch(e){i.stop(),N(e)}}),t.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let n=f(`Deleting SSH key...`);try{n.start(),await R(L(t)).sshKeys.delete(e),n.stop(),r(`Deleted SSH key ${e}`)}catch(e){n.stop(),N(e)}}),t}function vl(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function yl(){return new D(`ssh-proxy`).description(`SSH proxy helper that pipes stdin/stdout to WebSocket`).argument(`<runtime-url>`,`Runtime WebSocket URL`).action(async e=>{let t=process.env.TANGLE_SSH_PROXY_AUTH_TOKEN;t||vl(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new URL(e.replace(/^http/,`ws`)),{default:r}=await import(`ws`),i=new r(n,{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),a;function o(){a&&=(clearInterval(a),void 0)}i.on(`open`,()=>{a=setInterval(()=>{i.readyState===r.OPEN&&i.ping()},15e3),a.unref?.(),process.stdin.on(`data`,e=>{i.readyState===r.OPEN&&i.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>i.close(1e3))}),i.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),i.on(`error`,e=>{o(),vl(`WebSocket error: ${e.message}`)}),i.on(`close`,e=>{o(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>i.close())})}const bl=[`claude-code`,`opencode`,`codex`,`kimi-code`,`prime`],xl=process.env.TANGLE_ROUTER_URL||`https://router.tangle.tools/v1`;function Sl(e){let t=ze(e);if(t)return t;throw Error(`--model '${e}' has no provider. Pass a canonical id, for example 'google/${e}'.`)}function Cl(e){let t=e.harness??`claude-code`;if(!bl.includes(t))throw Error(`Unknown --harness '${t}'. Supported: ${bl.join(`, `)}.`);let n=wl(e.maxTokens,2e5,`--max-tokens`),r=wl(e.maxIterations,50,`--max-iterations`),i=e.maxWorkers===void 0?void 0:wl(e.maxWorkers,0,`--max-workers`);return{harness:t,...e.model?{model:e.model}:{},maxTokens:n,maxIterations:r,...i===void 0?{}:{maxWorkers:i}}}function wl(e,t,n){if(e===void 0)return t;let r=Number.parseInt(e,10);if(!Number.isFinite(r)||r<=0)throw Error(`${n} must be a positive integer, got '${e}'.`);return r}function Tl(e){let t={maxTokens:e.maxTokens,maxIterations:e.maxIterations};return e.maxWorkers===void 0?{budget:t}:{budget:t,perWorker:{maxTokens:Math.max(1,Math.floor(e.maxTokens/e.maxWorkers)),maxIterations:Math.max(1,Math.floor(e.maxIterations/e.maxWorkers))}}}function El(e){let t=e.spentTotal,n=e.kind===`no-winner`?``:e.out;return{text:typeof n==`string`?n:typeof n==`object`&&n&&`content`in n&&typeof n.content==`string`?n.content:JSON.stringify(n),tokenUsage:{input:t.tokensKnown===!1?null:t.tokens.input,output:t.tokensKnown===!1?null:t.tokens.output},costUsd:t.usdKnown===!1?null:t.usd,status:e.kind===`no-winner`?`no-winner (${e.reason})`:`winner`}}let Dl=null;function Ol(){return Dl??=import(`@tangle-network/agent-runtime/kernel`).catch(e=>{throw Dl=null,e?.code===`ERR_MODULE_NOT_FOUND`?new A(`RUNTIME_UNAVAILABLE`,`Agent Runtime could not be loaded`,e.message,`npm install -g @tangle-network/sandbox-cli@latest`):e}),Dl}async function kl(e,t,n){let r=L({apiKey:n.apiKey,baseUrl:n.baseUrl}),i=rn(`router`,process.env.TANGLE_ROUTER_URL||void 0,n.apiKey)??r.apiKey,a=R(r),{budget:o,perWorker:s}=Tl(t),c=[],u={async create(e){let{TANGLE_API_KEY:t,...r}=e?.env??{},i=await a.create(e?.env?{...e,env:r}:e);return c.push({id:i.id,status:`spawned`}),n.json||l(`worker ${i.id} spawned`),i}},d=await Ol(),f=d.workerFromBackend({backend:`sandbox`,sandboxClient:u,maxIterations:1}),p=(e,n)=>f({...e,harness:t.harness},n),m={name:`supervisor`,harness:`cli-base`,model:{default:t.model??`gemini-3.5-flash-lite`,provider:t.model?Sl(t.model):`google`},tools:{agent_runtime_coordination_spawn_worker:!0,agent_runtime_coordination_observe_agent:!0}},h={routerBaseUrl:xl,routerKey:i},g=El(await d.supervise(m,{goal:e},{budget:o,makeWorkerAgent:p,router:h,...s?{perWorker:s}:{},...t.model?{allowedModels:[t.model]}:{},runId:`supervise-${Me()}`})),ee=g.status===`winner`?`settled`:`failed`;for(let e of c)e.status=ee,n.json||l(`worker ${e.id} settled (${e.status})`);return{task:e,result:g.text,workers:c,tokenUsage:g.tokenUsage,costUsd:g.costUsd,status:g.status}}function Al(){let t=new D(`supervise`);return t.description(`Run a budget-conserving supervisor that spawns isolated sandbox workers to deliver a task.`).argument(`<task>`,`What the supervisor should accomplish`).option(`--harness <name>`,`Worker harness (${bl.join(` | `)})`,`claude-code`).option(`--model <id>`,`Model for the supervisor + workers`).option(`--max-tokens <n>`,`Conserved token budget for the whole run`,`200000`).option(`--max-iterations <n>`,`Conserved iteration budget for the whole run`,`50`).option(`--max-workers <n>`,`Bound the fanout; each worker reserves floor(max-tokens / n) tokens and floor(max-iterations / n) iterations`).action(async(t,n)=>{let r=Cl({harness:n.harness,model:n.model,maxTokens:n.maxTokens,maxIterations:n.maxIterations,maxWorkers:n.maxWorkers});n.json||(l(`Supervising: ${t}`),l(`harness=${r.harness} budget=${r.maxTokens}tok/${r.maxIterations}it`),console.log());let i=await kl(t,r,{apiKey:n.apiKey,baseUrl:n.baseUrl,json:n.json});if(n.json){e(i),i.status!==`winner`&&(process.exitCode=1);return}if(console.log(),i.result&&(console.log(i.result),console.log()),s({"Input Tokens":i.tokenUsage.input??`Unavailable`,"Output Tokens":i.tokenUsage.output??`Unavailable`,Cost:i.costUsd===null?`Unavailable`:`$${i.costUsd.toFixed(4)}`}),i.status!==`winner`)throw Error(`Supervisor finished without a winner: ${i.status}`)}),t}function jl(){let n=new D(`team`).description(`Manage teams`);return Q(n,`list`).description(`List teams for the current account`).action(async n=>{let r=L(n),i=R(r),a=n.json?null:f(`Fetching teams...`);a?.start();let o=await i.teams.list();if(a?.stop(),n.json){e({teams:o,activeTeamId:r.activeTeamId??null});return}t(o.map(e=>({active:e.id===r.activeTeamId,id:e.id,name:e.name,role:e.currentUserRole,members:e.memberCount})),[{key:`active`,header:`Active`,width:8},{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:24},{key:`role`,header:`Role`,width:10},{key:`members`,header:`Members`,width:10}])}),Q(n,`create <name>`).description(`Create a team`).option(`--org-id <id>`,`External organization id`).option(`--no-switch`,`Do not set the new team as active`).action(async(t,n)=>{let i=L(n),a=R(i),o=n.json?null:f(`Creating team...`);o?.start();let s=await a.teams.create({name:t,orgId:n.orgId});if(n.switch&&qo(s,i.profile),o?.stop(),n.json){e({team:s,active:!!n.switch});return}r(`Team created: ${Go(s)}`),n.switch&&r(`Active team set to ${s.name}`)}),Q(n,`switch <team>`).description(`Set the active team for the current profile`).action(async(t,n)=>{let i=L(n),a=await Ko(R(i),t);if(qo(a,i.profile),n.json){e({team:a,activeTeamId:a.id});return}r(`Active team set to ${Go(a)}`)}),n.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{let n=vn(t.profile);if(t.json){e(n.activeTeamId?n:{activeTeamId:null});return}if(!n.activeTeamId){console.log(`No active team.`);return}s({ID:n.activeTeamId,Name:n.activeTeamName})}),n.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(t=>{if(Jo(t.profile),t.json){e({activeTeamId:null});return}r(`Active team cleared.`)}),Q(n,`members [team]`).description(`List team members`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listMembers(o.id);if(r.json){e({team:o,members:s});return}t(s,[{key:`id`,header:`ID`,width:36},{key:`customerEmail`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:10},{key:`joinedAt`,header:`Joined`,width:16}])}),Q(n,`update-member <member-id>`).description(`Update a team member role`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).requiredOption(`--role <role>`,`Role: admin, member, viewer`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile),c=Ml(n.role),l=await a.teams.updateMember(o.id,t,{role:c});if(n.json){e({team:o,member:l});return}r(`Member updated: ${l.customerEmail}`),s({Team:o.name,Role:l.role,Status:l.status})}),Q(n,`invite <email>`).description(`Invite a user to a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--role <role>`,`Role: admin, member, viewer`,`member`).option(`--ttl-hours <hours>`,`Invitation lifetime in hours`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile),c=Ml(n.role),l=await a.teams.invite(o.id,{email:t,role:c,ttlHours:n.ttlHours?B(n.ttlHours,`--ttl-hours`):void 0});if(n.json){e({team:o,invitation:l});return}r(`Invitation created for ${l.email}`),s({Team:o.name,Role:l.role,Expires:l.expiresAt,"Invitation ID":l.id}),r(`Re-run with --json to retrieve the invitation token for sharing.`)}),Q(n,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,t,i.profile);if(!(!n.force&&!n.json&&!await G(`Leave team '${o.name}'? (y/N) `,`--force`))){if(await a.teams.leave(o.id),i.activeTeamId===o.id&&Jo(i.profile),n.json){e({success:!0,teamId:o.id});return}r(`Left team: ${o.name}`)}}),Q(n,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,n,a.profile);if(!(!i.force&&!i.json&&!await G(`Transfer ownership of '${s.name}' to ${t}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await o.teams.transferOwnership(s.id,t),i.json){e({success:!0,teamId:s.id,newOwnerCustomerId:t});return}r(`Ownership transferred for ${s.name}`)}}),n.addCommand(Nl()),n.addCommand(Pl()),Q(n,`invitations [team]`).description(`List pending and historical team invitations`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listInvitations(o.id);if(r.json){e({team:o,invitations:s});return}t(s,[{key:`id`,header:`ID`,width:38},{key:`email`,header:`Email`,width:28},{key:`role`,header:`Role`,width:10},{key:`status`,header:`Status`,width:12},{key:`expiresAt`,header:`Expires`,width:16}])}),Q(n,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(t,n)=>{let i=L(n),a=R(i),o=await a.teams.acceptInvitation(t),s=n.switch===!1?null:await a.teams.get(o.teamId);if(s&&qo(s,i.profile),n.json){e({member:o,activeTeamId:s?.id??null});return}r(`Invitation accepted for team ${o.teamId}`),s&&r(`Active team set to ${s.name}`)}),Q(n,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(t,n)=>{if(await R(L(n)).teams.revokeInvitation(t),n.json){e({success:!0,invitationId:t});return}r(`Invitation revoked: ${t}`)}),Q(n,`remove-member <member-id>`).description(`Remove a member from a team`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(await a.teams.removeMember(o.id,t),n.json){e({success:!0,teamId:o.id,memberId:t});return}r(`Member removed: ${t}`)}),n}function Ml(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function Nl(){let n=new D(`secret`).description(`Manage team secrets`);return Q(n,`list [team]`).description(`List team secret names`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listSecrets(o.id);if(r.json){e({team:o,secrets:s});return}t(s,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),Q(n,`set <name> [value]`).description(`Create or replace a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--value-stdin`,`Read secret value from stdin`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,i.team,a.profile),c=await el({value:n,valueStdin:i.valueStdin,prompt:`Enter value for team secret '${t}': `}),l=await o.teams.upsertSecret(s.id,t,c);if(i.json){e({team:s,secret:l});return}r(`Team secret saved: ${l.name}`)}),Q(n,`delete <name>`).description(`Delete a team secret`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(!(!n.force&&!n.json&&!await G(`Delete team secret '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteSecret(o.id,t),n.json){e({success:!0,teamId:o.id,name:t});return}r(`Team secret deleted: ${t}`)}}),Q(n,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(t,n)=>{let r=L(n),i=R(r),a=await Y(i,n.team,r.profile),o=await i.teams.revealSecret(a.id,t);if(n.json){e({teamId:a.id,...o});return}console.log(o.value)}),n}function Pl(){let n=new D(`templates`).description(`Manage team golden-path templates`);return Q(n,`list [team]`).description(`List a team's golden-path templates`).action(async(n,r)=>{let i=L(r),a=R(i),o=await Y(a,n,i.profile),s=await a.teams.listTemplates(o.id);if(r.json){e({team:o,templates:s});return}if(s.length===0){console.log(`No templates yet for ${o.name}.`);return}t(s.map(e=>({id:e.id,name:e.name,environment:e.environment,snapshot:`${e.snapshotId.slice(0,12)}…`,updated:e.updatedAt})),[{key:`id`,header:`ID`,width:38},{key:`name`,header:`Name`,width:28},{key:`environment`,header:`Env`,width:14},{key:`snapshot`,header:`Snapshot`,width:16},{key:`updated`,header:`Updated`,width:24}])}),Q(n,`create <name> <snapshot-id>`).description(`Create a golden-path template from a snapshot`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`-d, --description <description>`,`Human-readable description shown in the dashboard`).option(`-e, --environment <environment>`,`Default environment to apply (defaults to 'universal')`).option(`--config <json>`,`Optional JSON config object merged into sandboxes created from this template`).action(async(t,n,i)=>{let a=L(i),o=R(a),s=await Y(o,i.team,a.profile),c;if(i.config)try{let e=JSON.parse(i.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);c=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let l=await o.teams.createTemplate(s.id,{name:t,snapshotId:n,description:i.description,environment:i.environment,config:c});if(i.json){e({team:s,template:l});return}r(`Team template created: ${l.name} (${l.id})`)}),Q(n,`delete <template-id>`).description(`Delete a team golden-path template`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{let i=L(n),a=R(i),o=await Y(a,n.team,i.profile);if(!(!n.force&&!n.json&&!await G(`Delete template '${t}' from '${o.name}'? (y/N) `,`--force`))){if(await a.teams.deleteTemplate(o.id,t),n.json){e({success:!0,teamId:o.id,templateId:t});return}r(`Team template deleted: ${t}`)}}),n}function Q(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function Fl(t,n,i){let a=new AbortController,o=()=>a.abort();try{let i=R(L({...t,timeout:void 0}));process.once(`SIGINT`,o),process.once(`SIGTERM`,o);let s=await n(i,{...t.timeout===void 0?{}:{timeoutMs:V(t.timeout,`--timeout`)*1e3},resumeJobId:t.resumeJob,signal:a.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,o)});t.json?e(s):r(`template`in s?`Published template: ${s.template.slug}`:`Published template version: ${s.version.id}`)}catch(e){if(e instanceof se&&e.status!==401&&e.job&&[`pending`,`scanning`,`ready`].includes(e.job.status)){let t=[`tangle`,`template`,...i,`--resume-job`,e.job.id].map(Be).join(` `);Object.assign(e,{fix:{command:t}})}N(e,t.json)}}function Il(){let n=new D(`template`).description(`Manage published public templates`);return n.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async n=>{let r=R(L(n)),i=n.featured?await r.publicTemplates.featured():await r.publicTemplates.list({query:n.query,tag:n.tag});if(n.json){e({templates:i});return}t(i,[{key:`slug`,header:`Slug`,width:28},{key:`name`,header:`Name`,width:28},{key:`forkCount`,header:`Forks`,width:8},{key:`sandboxCount`,header:`Sandboxes`,width:12},{key:`updatedAt`,header:`Updated`,width:24}])}),n.command(`get <id-or-slug>`).action(async(t,n)=>{let r=await R(L(n)).publicTemplates.get(t);if(n.json){e({template:r});return}e(r)}),n.command(`versions <id-or-slug>`).action(async(n,r)=>{let i=await R(L(r)).publicTemplates.versions(n);if(r.json){e({versions:i});return}t(i.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`createdAt`,header:`Created`,width:24}])}),n.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--slug <slug>`,`Stable public slug`).option(`-d, --description <description>`,`Template description`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).option(`--team-id <id>`,`Publish under a team`).option(`--forked-from <id>`,`Fork source template id`).action((e,t,n,r)=>Fl(r,async(i,a)=>({template:await i.publicTemplates.publish({name:e,slug:r.slug,description:r.description,snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes,teamId:r.teamId,forkedFromTemplateId:r.forkedFrom},a)}),[`publish`,e,t,n])),n.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <duration>`,`Maximum wait for publication, e.g. 5m`).option(`--resume-job <id>`,`Resume an accepted publication for this snapshot`).option(`--readme <markdown>`,`README markdown`).option(`--tags <tags...>`,`Template tags`).option(`--release-notes <text>`,`Release notes`).action((e,t,n,r)=>Fl(r,async(i,a)=>({version:await i.publicTemplates.publishVersion(e,{snapshotId:t,sourceSandboxId:n,readmeMarkdown:r.readme,tags:r.tags,releaseNotes:r.releaseNotes},a)}),[`publish-version`,e,t,n])),n}function Ll(){let t=new D(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return t.command(`list`).description(`List trace summaries (one row per trace), newest first`).option(`--from <iso>`,`ISO-8601 lower bound on received time (inclusive)`).option(`--to <iso>`,`ISO-8601 upper bound on received time (inclusive)`).option(`--model <model>`,`Exact model match (any span carried this model)`).option(`--run <runId>`,`Exact run id match`).option(`--status <status>`,`ERROR | OK`).option(`-q, --query <text>`,`Substring over span name`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size (clamped server-side to [1, 200])`).action(async t=>{try{let n={from:t.from,to:t.to,model:t.model,runId:t.run,status:t.status===void 0?void 0:Jl(t.status),q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:$l(t.limit)},r=zl(t),i=t.json?null:f(`Fetching traces...`);i?.start();let a=await r.listTraces(n);if(i?.stop(),t.json)return e(a);Hl(a.items),Kl(a.nextCursor)}catch(e){Vl(e,t)}}),t.command(`get <traceId>`).description(`Show one trace's spans. Streams NDJSON to stdout with --ndjson.`).option(`--ndjson`,`Stream the full span set as NDJSON to stdout`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Spans per page`).action(async(t,n)=>{try{let r=zl(n);if(n.ndjson){await Bl(r,t);return}let i=n.json?null:f(`Fetching trace spans...`);i?.start();let a=await r.getTraceSpans(t,{cursor:n.cursor,limit:n.limit===void 0?void 0:$l(n.limit)});if(i?.stop(),!n.cursor&&a.items.length===0)throw new A(`TRACE_NOT_FOUND`,`No spans for trace ${t}`,`A turn's spans arrive about a minute after it ends, and a key reads only its own account's traces`,`tangle traces list --limit 5`);if(n.json)return e(a);Ul(a.items),a.truncated&&s({Spans:`${a.items.length} of ${a.total} (truncated)`}),Kl(a.nextCursor)}catch(e){Vl(e,n)}}),t.addCommand(Rl()),t}function Rl(){let t=new D(`runs`).description(`Read eval-runs pivoted off the trace surface`);return t.command(`list`).description(`List eval-runs, newest first`).option(`--status <status>`,`Run status filter`).option(`--gate <decision>`,`Promotion-gate decision filter`).option(`--label <key:value>`,`Match over the run's labels`).option(`--from <iso>`,`ISO-8601 lower bound on received time`).option(`--to <iso>`,`ISO-8601 upper bound on received time`).option(`-q, --query <text>`,`Substring over run dir`).option(`--cursor <cursor>`,`Opaque pagination cursor from a prior page`).option(`--limit <count>`,`Page size`).action(async t=>{try{let n={status:t.status===void 0?void 0:Xl(t.status),gate:t.gate===void 0?void 0:Ql(t.gate),label:t.label,from:t.from,to:t.to,q:t.query,cursor:t.cursor,limit:t.limit===void 0?void 0:$l(t.limit)},r=zl(t),i=t.json?null:f(`Fetching runs...`);i?.start();let a=await r.listRuns(n);if(i?.stop(),t.json)return e(a);Wl(a.items),Kl(a.nextCursor)}catch(e){Vl(e,t)}}),t.command(`get <runId>`).description(`Show a single eval-run`).action(async(t,n)=>{try{let r=zl(n),i=n.json?null:f(`Fetching run...`);i?.start();let a=await r.getRun(t);if(i?.stop(),n.json)return e(a);Gl(a)}catch(e){Vl(e,n)}}),t}function zl(e){let t=e.baseUrl||process.env.TANGLE_INTELLIGENCE_BASE_URL||void 0,n=rn(`intelligence`,t,e.apiKey);if(!n)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return dt({apiKey:n,baseUrl:t})}async function Bl(e,t){let n=(await e.exportTraceSpansNdjson(t)).getReader();try{for(;;){let{value:e,done:t}=await n.read();if(t)break;e&&process.stdout.write(Buffer.from(e))}}finally{n.releaseLock()}}function Vl(e,t){return N(e,t.json===!0)}function Hl(e){t(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:ql(e.costUsd)})),[{key:`traceId`,header:`Trace`,width:36},{key:`root`,header:`Root`,width:24},{key:`model`,header:`Model`,width:22},{key:`spans`,header:`Spans`,width:8},{key:`errors`,header:`Errors`,width:8},{key:`durationMs`,header:`Duration(ms)`,width:14},{key:`cost`,header:`Cost`,width:10}])}function Ul(e){t(e.map(e=>({spanId:e.id,name:e.name,model:e.model??`-`,status:e.statusCode??`-`,cost:e.costUsd===null?`-`:`$${e.costUsd}`})),[{key:`spanId`,header:`Span`,width:40},{key:`name`,header:`Name`,width:28},{key:`model`,header:`Model`,width:22},{key:`status`,header:`Status`,width:10},{key:`cost`,header:`Cost`,width:12}])}function Wl(e){t(e.map(e=>({runId:e.id,status:e.status,gate:e.gateDecision??`-`,cost:e.totalCostUsd===null?`-`:`$${e.totalCostUsd}`,receivedAt:e.receivedAt})),[{key:`runId`,header:`Run`,width:24},{key:`status`,header:`Status`,width:22},{key:`gate`,header:`Gate`,width:18},{key:`cost`,header:`Cost`,width:12},{key:`receivedAt`,header:`Received`,width:18}])}function Gl(e){s({Run:e.id,Status:e.status,Gate:e.gateDecision??void 0,"Run Dir":e.runDir??void 0,Cost:e.totalCostUsd===null?void 0:`$${e.totalCostUsd}`,Duration:e.totalDurationMs===null?void 0:`${e.totalDurationMs}ms`,"Holdout Lift":e.holdoutLift??void 0,Received:e.receivedAt})}function Kl(e){e&&s({"Next page":`--cursor ${e}`})}function ql(e){return e===null?`-`:`$${e.toFixed(4)}`}function Jl(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const Yl=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function Xl(e){let t=Yl.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${Yl.join(`, `)}`)}const Zl=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function Ql(e){let t=Zl.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Zl.join(`, `)}`)}function $l(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}const eu=`@tangle-network/sandbox-cli`,tu=`curl -fsSL https://sandbox.tangle.tools/install.sh | sh`,nu=/^\d+\.\d+\.\d+$/,ru=()=>process.env.TANGLE_CLI_HOME||E(He(),`.local/share/tangle-cli`);function iu(e){let t=E(ru(),`versions`);if(y(t)&&e.startsWith(ne(t)+De))return`tangle update`;let n=E(ru(),`node_modules`,eu);if(y(n)&&ne(n)===e)return`tangle update`;if(e.endsWith(E(`lib`,`node_modules`,eu)))return`npm install -g ${eu}@latest`;if(e.includes(E(`pnpm`,`global`,``)))return`pnpm add -g ${eu}@latest`;if(e.includes(`${De}node_modules${De}`))return``}const au=()=>`${process.env.TANGLE_NPM_REGISTRY??`https://registry.npmjs.org`}/${eu.replace(`/`,`%2F`)}/latest`,ou=`const fs = require("node:fs");
|
|
153
159
|
const [file, url] = process.argv.slice(1);
|
|
154
160
|
const record = (latest) => {
|
|
155
161
|
const state = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
@@ -157,7 +163,7 @@ const record = (latest) => {
|
|
|
157
163
|
};
|
|
158
164
|
fetch(url, { signal: AbortSignal.timeout(30000) })
|
|
159
165
|
.then((r) => r.json()).then((b) => b.version, () => null)
|
|
160
|
-
.then((v) => record(${
|
|
161
|
-
`)?r.definitionYaml:`${r.definitionYaml}\n`);return}if(n.json)return e(r);bu(r)}),t.command(`create`).description(`Create a workflow from a YAML file`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=_u(t),i=await(await $(n)).workflows.create(r);if(n.json)return e(i);l(`Created workflow ${i.id} (${i.name}).`),bu(i)}),t.command(`apply`).description(`Create or update a workflow idempotently, matched by the definition's name`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=_u(t),i=await $(n),a=await i.workflows.validate(r,{structural:!0});if(!a.valid){if(process.exitCode=1,n.json)return e(a);l(`Invalid workflow:`);for(let e of a.errors)console.log(` ${e.path}: ${e.message}`);return}let o=(await i.workflows.list()).find(e=>e.name===a.name);if(o){let t=await i.workflows.update(o.id,r);if(n.json)return e({action:`updated`,workflow:t});l(`Updated workflow ${t.id} (${t.name}) — matched by name.`),bu(t);return}let s=await i.workflows.create(r);if(n.json)return e({action:`created`,workflow:s});l(`Created workflow ${s.id} (${s.name}).`),bu(s)}),t.command(`update`).description(`Replace a workflow's definition from a YAML file`).argument(`<id>`,`Workflow ID`).argument(`<file>`,`Path to the workflow YAML`).option(`--note <note>`,`Revision note recorded on the appended revision (why this change)`).action(async(t,n,r)=>{let i=_u(n),a=await(await $(r)).workflows.update(t,i,{...r.note===void 0?{}:{note:r.note}});if(r.json)return e(a);l(`Updated workflow ${a.id} (${a.name}).`),bu(a)}),t.command(`delete`).description(`Delete a workflow and its triggers`).argument(`<id>`,`Workflow ID`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{if(!n.force&&!await G(`Delete workflow ${t}? `,`--force`)){l(`Delete cancelled.`);return}if(await(await $(n)).workflows.delete(t),n.json)return e({deleted:!0,id:t});l(`Deleted workflow ${t}.`)}),t.command(`validate`).description(`Validate a workflow YAML file without saving it`).argument(`<file>`,`Path to the workflow YAML`).option(`--structural`,`CI mode: compile + capability checks only, no connection resolution — the verdict is the same regardless of connected providers`).action(async(t,n)=>{let r=_u(t),i=await(await $(n)).workflows.validate(r,{...n.structural?{structural:!0}:{}});if(n.json)return e(i);if(i.valid)l(`Valid: ${i.name} (${i.actionCount} action(s), ${i.triggerCount} trigger(s)).`);else{l(`Invalid workflow:`);for(let e of i.errors)console.log(` ${e.path}: ${e.message}`);process.exitCode=1}}),t.command(`schema`).description(`Print the JSON Schema for the workflow YAML`).action(async t=>{e(await(await $(t)).workflows.schema())})}const Cu=1e3;function wu(e,t){return[...t,e]}function Tu(e,t=`input`,n){if(n===void 0&&!e?.length)return;let r={};if(n!==void 0)try{if(r=JSON.parse(x(n,`utf8`)),!r||typeof r!=`object`||Array.isArray(r)||Object.entries(r).some(([e,t])=>!e.length||typeof t!=`string`))throw Error(`Invalid input map`)}catch{throw new A(`WORKFLOW_INPUT_FILE_INVALID`,`Could not load --input-file '${n}'`,`Expected a readable JSON object with nonempty keys and string values`,`tangle workflows run --help`)}let i=Object.entries(r);for(let n of e??[]){let e=n.indexOf(`=`);if(e<=0)throw Error(`Invalid --${t} "${n}": expected key=value (e.g. pull_request.number=123)`);i.push([n.slice(0,e),n.slice(e+1)])}return Object.fromEntries(i)}function Eu(e){t(e.map(e=>({id:e.id,status:e.status,attempts:e.attempts,created:e.createdAt,completed:e.completedAt??``})),[{key:`id`,header:`Run ID`},{key:`status`,header:`Status`},{key:`attempts`,header:`Attempts`},{key:`created`,header:`Created`},{key:`completed`,header:`Completed`}])}function Du(e){if(s({"Run ID":e.id,Workflow:e.workflowId,Status:e.status,Error:e.error??``,Attempts:e.attempts,Created:e.createdAt,Started:e.startedAt??``,Completed:e.completedAt??``}),e.actionResults.length>0){l(`Actions`);let n=e.actionResults.some(e=>e.nodeId!==void 0||e.visit!==void 0);t(e.actionResults.map(e=>({index:e.index,...n?{node:e.nodeId??``,visit:e.visit??``}:{},kind:e.kind,status:e.status,error:e.error??``,cost:e.costUsd??``})),[{key:`index`,header:`#`},...n?[{key:`node`,header:`Node`},{key:`visit`,header:`Visit`}]:[],{key:`kind`,header:`Kind`},{key:`status`,header:`Status`},{key:`error`,header:`Error`},{key:`cost`,header:`Cost (USD)`}])}e.graph&&(l(`Graph`),s({Nodes:e.graph.nodes.length,Edges:e.graph.edges.length,"Max node visits":e.graph.maxNodeVisits}),t(e.graph.edges.map(e=>({from:e.from,to:e.to,guard:e.when===void 0?``:JSON.stringify(e.when)})),[{key:`from`,header:`From`},{key:`to`,header:`To`},{key:`guard`,header:`Guard`}])),e.edgeVerdicts&&e.edgeVerdicts.length>0&&(l(`Edge verdicts`),t(e.edgeVerdicts.flatMap(e=>Object.entries(e.verdicts).map(([t,n])=>({node:e.nodeId,edge:t,verdict:n?`taken`:`not taken`}))),[{key:`node`,header:`Node`},{key:`edge`,header:`Edge`},{key:`verdict`,header:`Verdict`}]))}function Ou(e){if(e.status===`cancelled`){l(`Cancelled run ${e.runId}.`);return}if(e.signalled){l(`Cancelling run ${e.runId} — signalled the worker; it will stop shortly.`);return}l(`Requested cancellation of run ${e.runId}, but couldn't confirm it — the run may have just finished, or it's running on another instance and will stop on its own.`)}function ku(e){switch(e.type){case`snapshot`:l(`snapshot: ${e.run.status} (${e.run.actionResults.length} action(s))`);break;case`action.started`:console.log(`→ action[${e.index}] ${e.kind} started`);break;case`action.finished`:{let t=e.status===`succeeded`?`✓`:e.status===`skipped`?`⊘`:`✗`;console.log(`${t} action[${e.index}] ${e.kind} ${e.status}${e.error?`: ${e.error}`:``}`);break}case`iteration.started`:console.log(` · action[${e.actionIndex}] iteration ${e.iterationIndex} started`);break;case`iteration.ended`:console.log(` · action[${e.actionIndex}] iteration ${e.iterationIndex} ${e.status}`);break;case`token`:typeof e.delta==`string`&&process.stdout.write(e.delta);break;case`ping`:break;case`run.done`:console.log(`\nrun.done: ${e.status}${e.error?`: ${e.error}`:``}`);break;case`run.waiting`:console.log(`\nrun.waiting: parked on a human decision (${e.decisionId}) — resolve it to resume`);break}}function Au(t){t.command(`run`).description(`Trigger an immediate run of a workflow`).argument(`<id>`,`Workflow ID`).option(`--input-file <file>`,`Trigger inputs from a flat JSON string map; --input overrides its keys`).option(`--input <key=value>`,`Trigger input as key=value (e.g. pull_request.number=123). Repeatable.`,wu,[]).option(`--wait`,`Wait for the run to finish and print its result`).option(`--timeout <ms>`,`With --wait, fail if the run has not finished after this many milliseconds`).option(`--poll-interval <ms>`,`With --wait, how often to poll for completion (default 2000)`).action(async(t,n)=>{let r=Tu(n.input,`input`,n.inputFile),i=n.timeout===void 0?void 0:B(n.timeout,`--timeout`),a=n.pollInterval===void 0?void 0:B(n.pollInterval,`--poll-interval`),o=await $(n),{runId:s}=await o.workflows.run(t,r);if(!n.wait){if(n.json)return e({runId:s});l(`Started run ${s} for workflow ${t}.`),l(`Inspect it with: tangle workflows run-detail ${t} ${s}`);return}let c=n.json?null:f(`Waiting for run ${s} to finish...`).start(),u;try{u=await o.workflows.waitForRun(t,s,{...i===void 0?{}:{timeoutMs:i},...a===void 0?{}:{pollIntervalMs:a}})}finally{c?.stop()}if(u.status===`failed`&&(process.exitCode=1),n.json)return e(u);Du(u)}),t.command(`runs`).description(`List a workflow's run history (newest first)`).argument(`<id>`,`Workflow ID`).option(`--limit <n>`,`Runs per page (1-100)`).option(`--cursor <cursor>`,`Pagination cursor from a previous page`).option(`--all`,`Fetch every page, not just the first`).action(async(t,n)=>{let r=await $(n),i=n.limit===void 0?void 0:B(n.limit,`--limit`);if(n.all){let a=[],o=n.cursor,s=0,c=null;for(;;){let e=await r.workflows.listRuns(t,{...i===void 0?{}:{limit:i},...o===void 0?{}:{cursor:o}});if(a.push(...e.runs),s+=1,!e.nextCursor)break;if(s>=Cu){c=e.nextCursor,n.json||l(`Stopped after ${Cu} pages (${a.length} runs); more may exist — resume with --cursor ${e.nextCursor}`);break}o=e.nextCursor}if(n.json)return e({runs:a,nextCursor:c});Eu(a);return}let a=await r.workflows.listRuns(t,{...i===void 0?{}:{limit:i},...n.cursor===void 0?{}:{cursor:n.cursor}});if(n.json)return e(a);Eu(a.runs),a.nextCursor&&l(`More runs available — next page: --cursor ${a.nextCursor}`)}),t.command(`run-detail`).description(`Show a single run's detail (per-action output and errors)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.getRun(t,n);if(r.json)return e(i);Du(i)}),t.command(`cancel`).description(`Cancel a queued or in-progress run`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.cancel(t,n);if(r.json)return e(i);Ou(i)}),t.command(`retry`).description(`Re-run a failed or cancelled run (a fresh run with the same trigger context)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID of the failed/cancelled run to retry`).option(`--wait`,`Wait for the new run to finish and print its result`).option(`--timeout <ms>`,`With --wait, fail if the run has not finished after this many milliseconds`).option(`--poll-interval <ms>`,`With --wait, how often to poll for completion (default 2000)`).action(async(t,n,r)=>{let i=r.timeout===void 0?void 0:B(r.timeout,`--timeout`),a=r.pollInterval===void 0?void 0:B(r.pollInterval,`--poll-interval`),o=await $(r),s=await o.workflows.retryRun(t,n);if(!r.wait){if(r.json)return e(s);l(`Started run ${s.runId} (retry of ${n}).`),l(`Inspect it with: tangle workflows run-detail ${t} ${s.runId}`);return}let c=r.json?null:f(`Waiting for run ${s.runId} to finish...`).start(),u;try{u=await o.workflows.waitForRun(t,s.runId,{...i===void 0?{}:{timeoutMs:i},...a===void 0?{}:{pollIntervalMs:a}})}finally{c?.stop()}if(u.status===`failed`&&(process.exitCode=1),r.json)return e(u);Du(u)}),t.command(`events`).description(`Tail a run's live progress events until it finishes`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(e,t,n)=>{let r=await $(n);for await(let i of r.workflows.watchRun(e,t))n.json?console.log(JSON.stringify(i)):ku(i),i.type===`run.done`&&i.status===`failed`&&(process.exitCode=1)})}async function ju(t,n,r){let i=await(await $(r)).workflows.setEnabled(t,n);if(r.json)return e(i);l(`${n?`Enabled`:`Disabled`} workflow ${i.id}.`),bu(i)}function Mu(e,t){try{return JSON.parse(e)}catch{throw Error(`Invalid ${t}: not valid JSON`)}}function Nu(e,t){try{S(e,t,`utf8`)}catch(t){throw Error(`Could not write workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Pu(e){t(e.map(e=>({id:e.id,name:e.name,category:e.category,providers:e.providers.join(`, `),summary:e.summary})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`category`,header:`Category`},{key:`providers`,header:`Providers`},{key:`summary`,header:`Summary`}])}function Fu(e,t){let n=e.kind===`github_app`,r=n?`${e.provider} (App installation)`:e.provider,i=e.connectUrl?` — ${n?`install`:`connect`}: ${e.connectUrl}`:``,a=e.prerequisite;return`${r}${i}${a&&t.some(e=>e.provider===a.provider&&e.kind===a.kind&&!e.connected)?` (after connecting ${a.provider})`:``}`}function Iu(t){t.command(`enable`).description(`Enable a workflow so its triggers and manual runs fire`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await ju(e,!0,t)}),t.command(`disable`).description(`Disable a workflow (pause its triggers and manual runs)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await ju(e,!1,t)}),t.command(`templates`).description(`List the curated starter workflow templates`).action(async t=>{let n=await(await $(t)).workflows.listTemplates();if(t.json)return e(n);Pu(n)}),t.command(`init`).description(`Create a workflow from a gallery template and print (or save) its YAML`).argument(`<template-id>`,"Template ID from `workflows templates`").option(`--param <key=value>`,`Template parameter value. Repeatable.`,wu,[]).option(`--file <out>`,`Write the instantiated workflow YAML to this file instead of stdout`).action(async(t,n)=>{let r=Tu(n.param,`param`)??{},i=await(await $(n)).workflows.instantiateTemplate(t,r);if(n.json)return e(i);if(!i.created){l(`Template ${t} needs provider connections before it can run:`);for(let e of i.connectionRequirements)console.log(` ${e.connected?`✓`:`✗`} ${Fu(e,i.connectionRequirements)}`);process.exitCode=1;return}let{workflow:a}=i;if(a.definitionYaml===null)throw Error(`Workflow ${a.id} was created but the server returned no definition YAML`);if(l(`Created workflow ${a.id} (${a.name}).`),n.file){Nu(n.file,a.definitionYaml),l(`Wrote ${n.file}.`);return}process.stdout.write(a.definitionYaml.endsWith(`
|
|
162
|
-
`)?a.definitionYaml:`${a.definitionYaml}\n`)})}function
|
|
163
|
-
`)?a.yaml:`${a.yaml}\n`)}),t.command(`rollback`).description(`Restore a prior revision's definition as a NEW head revision (re-validated)`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number to restore`).action(async(t,n,r)=>{let i=B(n,`<rev>`),a=await(await $(r)).workflows.rollback(t,i);if(r.json)return e(a);l(`Rolled back workflow ${a.id} to rev ${i}.`),
|
|
166
|
+
.then((v) => record(${nu}.test(v) ? v : null), () => {});`,su=(e,t)=>e.localeCompare(t,`en`,{numeric:!0})>0;function cu(e,t){let n=iu(e);if(n===void 0||!process.stderr.isTTY||process.env.CI)return;let r=E(Nt,`update-check.json`),i=Math.floor(Date.now()/864e5);try{let e=y(r)?JSON.parse(x(r,`utf8`)):{},a=e.checked!==i,o=nu.test(e.latest)&&su(e.latest,t);if(!a&&(!o||e.shown===i))return;b(Nt,{mode:448,recursive:!0});let s={...e,checked:i,shown:o?i:e.shown};S(r,JSON.stringify(s)),a&&Ge(process.execPath,[`-e`,ou,r,au()],{detached:!0,stdio:`ignore`}).unref(),o&&e.shown!==i&&console.error(`tangle ${t} is installed; ${e.latest} is latest.${n&&` Run: ${n}`}`)}catch{}}function lu(e,t){return new D(`update`).description(`Install the latest published CLI`).action(async()=>{let n=iu(e);if(n!==`tangle update`)throw new A(`UPDATE_ELSEWHERE`,`install.sh did not install this tangle`,n===void 0?`it runs from source`:`another tool owns it`,n||tu);let r=(await fetch(au(),{signal:AbortSignal.timeout(1e4)}).then(e=>e.json()).catch(()=>({}))).version??``;if(!nu.test(r))throw new A(`NETWORK_UNAVAILABLE`,`the npm registry gave no version`,`no published version was read`,`tangle update`);if(!su(r,t))return console.error(`tangle ${t} is already current`);try{We(`bash`,[`-c`,`set -o pipefail; ${tu}`],{stdio:[`ignore`,`ignore`,`inherit`],env:{...process.env,TANGLE_CLI_VERSION:void 0}})}catch{throw new A(`UPDATE_INSTALL_FAILED`,`install.sh failed`,`its error is above`,tu)}let i=E(ru(),`current`,`node_modules`,eu),a=JSON.parse(x(E(y(i)?i:e,`package.json`),`utf8`));console.error(`tangle updated ${t} -> ${a.version}`)})}function uu(){return new D(`usage`).description(`Show account usage and billing information`).action(async t=>{let{client:n}=z(t),r=t.json?null:f(`Fetching usage...`);r?.start();let[i,a]=await Promise.all([n.usage(),n.subscription().catch(()=>null)]);r?.stop(),t.json?e({...i,subscription:a}):(console.log(),console.log(`Account Usage`),console.log(`─`.repeat(40)),s({"Active Sandboxes":i.activeSandboxes,"Total Sandboxes":i.totalSandboxes,"Compute Minutes":du(i.computeMinutes),"GPU Seconds":i.gpuSeconds,"GPU Spend":fu(i.gpuCostUsd)}),a&&(console.log(),console.log(`Subscription`),console.log(`─`.repeat(40)),s({Plan:a.plan,Status:a.status,"Credits Available":fu(a.creditsAvailableUsd),"Credits Used":fu(a.creditsUsedUsd),"Monthly Balance":fu(a.monthlyBalanceUsd)})),console.log(),console.log(`Billing Period`),console.log(`─`.repeat(40)),s({Start:i.periodStart.toLocaleDateString(),End:i.periodEnd.toLocaleDateString()}),console.log())})}function du(e){if(e===void 0)return`-`;if(e<60)return`${e} min`;let t=Math.floor(e/60),n=e%60;return n===0?`${t} hr`:`${t} hr ${n} min`}function fu(e){return e<0?`-$${(-e).toFixed(2)}`:`$${e.toFixed(2)}`}function pu(){return new D(`use`).description(`Set or show the active sandbox (used when a command omits the id)`).argument(`[id]`,`Sandbox id to make active`).option(`--clear`,`Clear the active sandbox`).action((e,t)=>{if(t.clear){Jt(),l(`Cleared the active sandbox.`);return}if(e){qt(e),l(`Active sandbox set to ${e}. Commands now default to it; override with --box or TANGLE_SANDBOX.`);return}let n=Kt();l(n?`Active sandbox: ${n}`:"No active sandbox. Set one with `tangle use <id>`.")})}function $(e){return Qn({signal:e.signal,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl}})}function mu(e){t(e,[{key:`id`,header:`ID`},{key:`nodeId`,header:`Node`},{key:`name`,header:`Name`},{key:`contentType`,header:`Content Type`},{key:`byteSize`,header:`Bytes`},{key:`createdAt`,header:`Created`}])}function hu(t){t.command(`artifacts`).description(`List a run's artifact metadata (never the bytes)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.listArtifacts(t,n);if(r.json)return e(i);mu(i.artifacts)}),t.command(`artifact-download`).description(`Download one run artifact's bytes to a file`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).argument(`<artifactId>`,`Artifact ID`).option(`--out <file>`,`Destination file (defaults to the artifact ID)`).action(async(t,n,r,i)=>{let a=await(await $(i)).workflows.downloadArtifact(t,n,r),o=i.out??r;try{S(o,a.bytes)}catch(e){throw Error(`Could not write artifact to "${o}": ${e instanceof Error?e.message:String(e)}`)}if(i.json)return e({file:o,contentType:a.contentType,bytes:a.bytes.length});l(`Wrote ${o} (${a.bytes.length} bytes, ${a.contentType}).`)})}function gu(e){t(e.map(e=>({id:e.id,run:e.runId,title:e.title,options:e.options.join(`, `),requested:e.requestedAt,expires:e.expiresAt??``})),[{key:`id`,header:`ID`},{key:`run`,header:`Run`},{key:`title`,header:`Title`},{key:`options`,header:`Options`},{key:`requested`,header:`Requested`},{key:`expires`,header:`Expires`}])}function _u(t){t.command(`decisions`).description(`List a workflow's pending human decisions`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=(await(await $(n)).workflows.listPendingDecisions()).decisions.filter(e=>e.workflowId===t);if(n.json)return e({decisions:r});gu(r)}),t.command(`decision-resolve`).description(`Answer the decision a run is parked on and resume it`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).requiredOption(`--choice <choice>`,`The option to resolve with (one of the decision's options)`).action(async(t,n,r)=>{let i=await $(r),a=await i.workflows.getRunDecision(t,n),o=await i.workflows.resolveRunDecision(t,n,{decisionId:a.id,choice:r.choice});if(r.json)return e(o);if(o.resumed){l(`Resolved decision ${o.decisionId} with "${o.choice}" — run ${o.runId} resumed.`);return}l(`Resolved decision ${o.decisionId} with "${o.choice}", but run ${o.runId} had already finished — nothing to resume.`)})}function vu(e){try{return x(e,`utf8`)}catch(t){throw Error(`Could not read workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function yu(e){t(e.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,issues:e.validationErrors.length,updated:e.updatedAt})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`issues`,header:`Issues`},{key:`updated`,header:`Updated`}])}function bu(e){let n=e.workflows.filter(e=>e.failed>0).length,r=e.workflows.filter(e=>e.failed===0&&e.waiting>0).length,i=e.workflows.filter(e=>e.failed===0&&e.waiting===0&&e.runsInWindow>0).length;l(`${n} failing · ${r} waiting · ${i} healthy · ${e.workflows.length} total over ${e.window}`),t(e.workflows.map(e=>({id:e.id,name:e.name,enabled:e.enabled?`yes`:`no`,runs:e.runsInWindow,failed:e.failed,waiting:e.waiting,success:e.successRate===null?`—`:`${Math.round(e.successRate*100)}%`,lastRun:e.lastRunStatus??`—`,lastRunAt:e.lastRunAt??`—`})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`enabled`,header:`Enabled`},{key:`runs`,header:`Runs`},{key:`failed`,header:`Failed`},{key:`waiting`,header:`Waiting`},{key:`success`,header:`Success`},{key:`lastRun`,header:`Last Run`},{key:`lastRunAt`,header:`Last Run At`}])}function xu(e){if(s({ID:e.id,Name:e.name,Description:e.description??``,Enabled:e.enabled?`yes`:`no`,Actions:e.actions.length}),e.triggers&&e.triggers.length>0&&(l(`Triggers`),Su(e.triggers)),e.validationErrors.length>0){l(`Validation issues`);for(let t of e.validationErrors)console.log(` ${t.path}: ${t.message}`)}}function Su(e){t(e.map(e=>({id:e.id,kind:e.kind,enabled:e.enabled?`yes`:`no`,detail:e.kind===`schedule`?`${e.cron??``} (${e.timezone??``})`:`${e.provider??``}:${e.eventFilter?.event??``}${e.eventFilter?.action?`.${e.eventFilter.action}`:``}`})),[{key:`id`,header:`ID`},{key:`kind`,header:`Kind`},{key:`enabled`,header:`Enabled`},{key:`detail`,header:`Detail`}])}function Cu(t){t.command(`list`).description(`List your workflows`).action(async t=>{let n=await(await $(t)).workflows.list();if(t.json)return e(n);yu(n)}),t.command(`fleet`).description(`Fleet overview: every workflow's run tallies over a trailing window, failing-first`).option(`--window <window>`,`Trailing window: 24h, 7d, or 30d`,`7d`).action(async t=>{let n=await(await $(t)).workflows.fleetInsights({window:t.window});if(t.json)return e(n);bu(n)}),t.command(`get`).description(`Show a workflow's definition and compiled triggers`).argument(`<id>`,`Workflow ID`).option(`--yaml`,`Print only the raw definition YAML (the export path — pipe to a file)`).action(async(t,n)=>{let r=await(await $(n)).workflows.get(t);if(n.yaml){if(r.definitionYaml===null)throw Error(`Workflow ${r.id} has no stored definition YAML to export`);process.stdout.write(r.definitionYaml.endsWith(`
|
|
167
|
+
`)?r.definitionYaml:`${r.definitionYaml}\n`);return}if(n.json)return e(r);xu(r)}),t.command(`create`).description(`Create a workflow from a YAML file`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=vu(t),i=await(await $(n)).workflows.create(r);if(n.json)return e(i);l(`Created workflow ${i.id} (${i.name}).`),xu(i)}),t.command(`apply`).description(`Create or update a workflow idempotently, matched by the definition's name`).argument(`<file>`,`Path to the workflow YAML`).action(async(t,n)=>{let r=vu(t),i=await $(n),a=await i.workflows.validate(r,{structural:!0});if(!a.valid){if(process.exitCode=1,n.json)return e(a);l(`Invalid workflow:`);for(let e of a.errors)console.log(` ${e.path}: ${e.message}`);return}let o=(await i.workflows.list()).find(e=>e.name===a.name);if(o){let t=await i.workflows.update(o.id,r);if(n.json)return e({action:`updated`,workflow:t});l(`Updated workflow ${t.id} (${t.name}) — matched by name.`),xu(t);return}let s=await i.workflows.create(r);if(n.json)return e({action:`created`,workflow:s});l(`Created workflow ${s.id} (${s.name}).`),xu(s)}),t.command(`update`).description(`Replace a workflow's definition from a YAML file`).argument(`<id>`,`Workflow ID`).argument(`<file>`,`Path to the workflow YAML`).option(`--note <note>`,`Revision note recorded on the appended revision (why this change)`).action(async(t,n,r)=>{let i=vu(n),a=await(await $(r)).workflows.update(t,i,{...r.note===void 0?{}:{note:r.note}});if(r.json)return e(a);l(`Updated workflow ${a.id} (${a.name}).`),xu(a)}),t.command(`delete`).description(`Delete a workflow and its triggers`).argument(`<id>`,`Workflow ID`).option(`--force`,`Skip confirmation prompt`).action(async(t,n)=>{if(!n.force&&!await G(`Delete workflow ${t}? `,`--force`)){l(`Delete cancelled.`);return}if(await(await $(n)).workflows.delete(t),n.json)return e({deleted:!0,id:t});l(`Deleted workflow ${t}.`)}),t.command(`validate`).description(`Validate a workflow YAML file without saving it`).argument(`<file>`,`Path to the workflow YAML`).option(`--structural`,`CI mode: compile + capability checks only, no connection resolution — the verdict is the same regardless of connected providers`).action(async(t,n)=>{let r=vu(t),i=await(await $(n)).workflows.validate(r,{...n.structural?{structural:!0}:{}});if(n.json)return e(i);if(i.valid)l(`Valid: ${i.name} (${i.actionCount} action(s), ${i.triggerCount} trigger(s)).`);else{l(`Invalid workflow:`);for(let e of i.errors)console.log(` ${e.path}: ${e.message}`);process.exitCode=1}}),t.command(`schema`).description(`Print the JSON Schema for the workflow YAML`).action(async t=>{e(await(await $(t)).workflows.schema())})}const wu=1e3;function Tu(e,t){return[...t,e]}function Eu(e,t=`input`,n){if(n===void 0&&!e?.length)return;let r={};if(n!==void 0)try{if(r=JSON.parse(x(n,`utf8`)),!r||typeof r!=`object`||Array.isArray(r)||Object.entries(r).some(([e,t])=>!e.length||typeof t!=`string`))throw Error(`Invalid input map`)}catch{throw new A(`WORKFLOW_INPUT_FILE_INVALID`,`Could not load --input-file '${n}'`,`Expected a readable JSON object with nonempty keys and string values`,`tangle workflows run --help`)}let i=Object.entries(r);for(let n of e??[]){let e=n.indexOf(`=`);if(e<=0)throw Error(`Invalid --${t} "${n}": expected key=value (e.g. pull_request.number=123)`);i.push([n.slice(0,e),n.slice(e+1)])}return Object.fromEntries(i)}function Du(e){t(e.map(e=>({id:e.id,status:e.status,attempts:e.attempts,created:e.createdAt,completed:e.completedAt??``})),[{key:`id`,header:`Run ID`},{key:`status`,header:`Status`},{key:`attempts`,header:`Attempts`},{key:`created`,header:`Created`},{key:`completed`,header:`Completed`}])}function Ou(e){if(s({"Run ID":e.id,Workflow:e.workflowId,Status:e.status,Error:e.error??``,Attempts:e.attempts,Created:e.createdAt,Started:e.startedAt??``,Completed:e.completedAt??``}),e.actionResults.length>0){l(`Actions`);let n=e.actionResults.some(e=>e.nodeId!==void 0||e.visit!==void 0);t(e.actionResults.map(e=>({index:e.index,...n?{node:e.nodeId??``,visit:e.visit??``}:{},kind:e.kind,status:e.status,error:e.error??``,cost:e.costUsd??``})),[{key:`index`,header:`#`},...n?[{key:`node`,header:`Node`},{key:`visit`,header:`Visit`}]:[],{key:`kind`,header:`Kind`},{key:`status`,header:`Status`},{key:`error`,header:`Error`},{key:`cost`,header:`Cost (USD)`}])}e.graph&&(l(`Graph`),s({Nodes:e.graph.nodes.length,Edges:e.graph.edges.length,"Max node visits":e.graph.maxNodeVisits}),t(e.graph.edges.map(e=>({from:e.from,to:e.to,guard:e.when===void 0?``:JSON.stringify(e.when)})),[{key:`from`,header:`From`},{key:`to`,header:`To`},{key:`guard`,header:`Guard`}])),e.edgeVerdicts&&e.edgeVerdicts.length>0&&(l(`Edge verdicts`),t(e.edgeVerdicts.flatMap(e=>Object.entries(e.verdicts).map(([t,n])=>({node:e.nodeId,edge:t,verdict:n?`taken`:`not taken`}))),[{key:`node`,header:`Node`},{key:`edge`,header:`Edge`},{key:`verdict`,header:`Verdict`}]))}function ku(e){if(e.status===`cancelled`){l(`Cancelled run ${e.runId}.`);return}if(e.signalled){l(`Cancelling run ${e.runId} — signalled the worker; it will stop shortly.`);return}l(`Requested cancellation of run ${e.runId}, but couldn't confirm it — the run may have just finished, or it's running on another instance and will stop on its own.`)}function Au(e){switch(e.type){case`snapshot`:l(`snapshot: ${e.run.status} (${e.run.actionResults.length} action(s))`);break;case`action.started`:console.log(`→ action[${e.index}] ${e.kind} started`);break;case`action.finished`:{let t=e.status===`succeeded`?`✓`:e.status===`skipped`?`⊘`:`✗`;console.log(`${t} action[${e.index}] ${e.kind} ${e.status}${e.error?`: ${e.error}`:``}`);break}case`iteration.started`:console.log(` · action[${e.actionIndex}] iteration ${e.iterationIndex} started`);break;case`iteration.ended`:console.log(` · action[${e.actionIndex}] iteration ${e.iterationIndex} ${e.status}`);break;case`token`:typeof e.delta==`string`&&process.stdout.write(e.delta);break;case`ping`:break;case`run.done`:console.log(`\nrun.done: ${e.status}${e.error?`: ${e.error}`:``}`);break;case`run.waiting`:console.log(`\nrun.waiting: parked on a human decision (${e.decisionId}) — resolve it to resume`);break}}function ju(t){t.command(`run`).description(`Trigger an immediate run of a workflow`).argument(`<id>`,`Workflow ID`).option(`--input-file <file>`,`Trigger inputs from a flat JSON string map; --input overrides its keys`).option(`--input <key=value>`,`Trigger input as key=value (e.g. pull_request.number=123). Repeatable.`,Tu,[]).option(`--wait`,`Wait for the run to finish and print its result`).option(`--timeout <ms>`,`With --wait, fail if the run has not finished after this many milliseconds`).option(`--poll-interval <ms>`,`With --wait, how often to poll for completion (default 2000)`).action(async(t,n)=>{let r=Eu(n.input,`input`,n.inputFile),i=n.timeout===void 0?void 0:B(n.timeout,`--timeout`),a=n.pollInterval===void 0?void 0:B(n.pollInterval,`--poll-interval`),o=await $(n),{runId:s}=await o.workflows.run(t,r);if(!n.wait){if(n.json)return e({runId:s});l(`Started run ${s} for workflow ${t}.`),l(`Inspect it with: tangle workflows run-detail ${t} ${s}`);return}let c=n.json?null:f(`Waiting for run ${s} to finish...`).start(),u;try{u=await o.workflows.waitForRun(t,s,{...i===void 0?{}:{timeoutMs:i},...a===void 0?{}:{pollIntervalMs:a}})}finally{c?.stop()}if(u.status===`failed`&&(process.exitCode=1),n.json)return e(u);Ou(u)}),t.command(`runs`).description(`List a workflow's run history (newest first)`).argument(`<id>`,`Workflow ID`).option(`--limit <n>`,`Runs per page (1-100)`).option(`--cursor <cursor>`,`Pagination cursor from a previous page`).option(`--all`,`Fetch every page, not just the first`).action(async(t,n)=>{let r=await $(n),i=n.limit===void 0?void 0:B(n.limit,`--limit`);if(n.all){let a=[],o=n.cursor,s=0,c=null;for(;;){let e=await r.workflows.listRuns(t,{...i===void 0?{}:{limit:i},...o===void 0?{}:{cursor:o}});if(a.push(...e.runs),s+=1,!e.nextCursor)break;if(s>=wu){c=e.nextCursor,n.json||l(`Stopped after ${wu} pages (${a.length} runs); more may exist — resume with --cursor ${e.nextCursor}`);break}o=e.nextCursor}if(n.json)return e({runs:a,nextCursor:c});Du(a);return}let a=await r.workflows.listRuns(t,{...i===void 0?{}:{limit:i},...n.cursor===void 0?{}:{cursor:n.cursor}});if(n.json)return e(a);Du(a.runs),a.nextCursor&&l(`More runs available — next page: --cursor ${a.nextCursor}`)}),t.command(`run-detail`).description(`Show a single run's detail (per-action output and errors)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.getRun(t,n);if(r.json)return e(i);Ou(i)}),t.command(`cancel`).description(`Cancel a queued or in-progress run`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.cancel(t,n);if(r.json)return e(i);ku(i)}),t.command(`retry`).description(`Re-run a failed or cancelled run (a fresh run with the same trigger context)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID of the failed/cancelled run to retry`).option(`--wait`,`Wait for the new run to finish and print its result`).option(`--timeout <ms>`,`With --wait, fail if the run has not finished after this many milliseconds`).option(`--poll-interval <ms>`,`With --wait, how often to poll for completion (default 2000)`).action(async(t,n,r)=>{let i=r.timeout===void 0?void 0:B(r.timeout,`--timeout`),a=r.pollInterval===void 0?void 0:B(r.pollInterval,`--poll-interval`),o=await $(r),s=await o.workflows.retryRun(t,n);if(!r.wait){if(r.json)return e(s);l(`Started run ${s.runId} (retry of ${n}).`),l(`Inspect it with: tangle workflows run-detail ${t} ${s.runId}`);return}let c=r.json?null:f(`Waiting for run ${s.runId} to finish...`).start(),u;try{u=await o.workflows.waitForRun(t,s.runId,{...i===void 0?{}:{timeoutMs:i},...a===void 0?{}:{pollIntervalMs:a}})}finally{c?.stop()}if(u.status===`failed`&&(process.exitCode=1),r.json)return e(u);Ou(u)}),t.command(`events`).description(`Tail a run's live progress events until it finishes`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(e,t,n)=>{let r=await $(n);for await(let i of r.workflows.watchRun(e,t))n.json?console.log(JSON.stringify(i)):Au(i),i.type===`run.done`&&i.status===`failed`&&(process.exitCode=1)})}async function Mu(t,n,r){let i=await(await $(r)).workflows.setEnabled(t,n);if(r.json)return e(i);l(`${n?`Enabled`:`Disabled`} workflow ${i.id}.`),xu(i)}function Nu(e,t){try{return JSON.parse(e)}catch{throw Error(`Invalid ${t}: not valid JSON`)}}function Pu(e,t){try{S(e,t,`utf8`)}catch(t){throw Error(`Could not write workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Fu(e){t(e.map(e=>({id:e.id,name:e.name,category:e.category,providers:e.providers.join(`, `),summary:e.summary})),[{key:`id`,header:`ID`},{key:`name`,header:`Name`},{key:`category`,header:`Category`},{key:`providers`,header:`Providers`},{key:`summary`,header:`Summary`}])}function Iu(e,t){let n=e.kind===`github_app`,r=n?`${e.provider} (App installation)`:e.provider,i=e.connectUrl?` — ${n?`install`:`connect`}: ${e.connectUrl}`:``,a=e.prerequisite;return`${r}${i}${a&&t.some(e=>e.provider===a.provider&&e.kind===a.kind&&!e.connected)?` (after connecting ${a.provider})`:``}`}function Lu(t){t.command(`enable`).description(`Enable a workflow so its triggers and manual runs fire`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Mu(e,!0,t)}),t.command(`disable`).description(`Disable a workflow (pause its triggers and manual runs)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await Mu(e,!1,t)}),t.command(`templates`).description(`List the curated starter workflow templates`).action(async t=>{let n=await(await $(t)).workflows.listTemplates();if(t.json)return e(n);Fu(n)}),t.command(`init`).description(`Create a workflow from a gallery template and print (or save) its YAML`).argument(`<template-id>`,"Template ID from `workflows templates`").option(`--param <key=value>`,`Template parameter value. Repeatable.`,Tu,[]).option(`--file <out>`,`Write the instantiated workflow YAML to this file instead of stdout`).action(async(t,n)=>{let r=Eu(n.param,`param`)??{},i=await(await $(n)).workflows.instantiateTemplate(t,r);if(n.json)return e(i);if(!i.created){l(`Template ${t} needs provider connections before it can run:`);for(let e of i.connectionRequirements)console.log(` ${e.connected?`✓`:`✗`} ${Iu(e,i.connectionRequirements)}`);process.exitCode=1;return}let{workflow:a}=i;if(a.definitionYaml===null)throw Error(`Workflow ${a.id} was created but the server returned no definition YAML`);if(l(`Created workflow ${a.id} (${a.name}).`),n.file){Pu(n.file,a.definitionYaml),l(`Wrote ${n.file}.`);return}process.stdout.write(a.definitionYaml.endsWith(`
|
|
168
|
+
`)?a.definitionYaml:`${a.definitionYaml}\n`)})}function Ru(e){t(e,[{key:`key`,header:`Key`},{key:`version`,header:`Version`},{key:`updatedAt`,header:`Updated`}])}function zu(t){s({Key:t.key,Version:t.version,Updated:t.updatedAt}),l(`Value`),e(t.value)}function Bu(t){let n=t.command(`kv`).description(`Read and write a workflow's cross-run KV state`);n.command(`list`).description(`List every KV entry of a workflow`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await $(n)).workflows.listKv(t);if(n.json)return e(r);Ru(r.entries)}),n.command(`get`).description(`Show one KV entry (value and version)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.getKv(t,n);if(r.json)return e(i);zu(i)}),n.command(`set`).description(`Write a KV entry from a JSON value`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).argument(`<json>`,`Value as JSON (e.g. '{"cursor":123}' or '"abc"')`).option(`--cas <version>`,`Compare-and-swap: write only if the stored version still equals this`).action(async(t,n,r,i)=>{let a=Nu(r,`<json>`),o=i.cas===void 0?void 0:B(i.cas,`--cas`),s=await $(i),c=o===void 0?await s.workflows.putKv(t,n,a):await s.workflows.casKv(t,n,o,a);if(i.json)return e(c);zu(c)}),n.command(`delete`).description(`Delete a KV entry (idempotent)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(t,n,r)=>{let i=await(await $(r)).workflows.deleteKv(t,n);if(r.json)return e(i);l(i.deleted?`Deleted KV entry "${n}" of workflow ${t}.`:`No KV entry "${n}" on workflow ${t}.`)})}function Vu(e){t(e.map(e=>({rev:e.rev,created:e.createdAt,by:e.createdBy,source:e.source,note:e.note??``})),[{key:`rev`,header:`Rev`},{key:`created`,header:`Created`},{key:`by`,header:`Created By`},{key:`source`,header:`Source`},{key:`note`,header:`Note`}])}function Hu(t){t.command(`revisions`).description(`List a workflow's definition revision history (newest first)`).argument(`<id>`,`Workflow ID`).action(async(t,n)=>{let r=await(await $(n)).workflows.listRevisions(t);if(n.json)return e(r);Vu(r)}),t.command(`revision`).description(`Show one revision's metadata and definition YAML`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number`).action(async(t,n,r)=>{let i=B(n,`<rev>`),a=await(await $(r)).workflows.getRevision(t,i);if(r.json)return e(a);s({Revision:a.rev,Created:a.createdAt,"Created by":a.createdBy,Source:a.source,Note:a.note??``}),process.stdout.write(a.yaml.endsWith(`
|
|
169
|
+
`)?a.yaml:`${a.yaml}\n`)}),t.command(`rollback`).description(`Restore a prior revision's definition as a NEW head revision (re-validated)`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number to restore`).action(async(t,n,r)=>{let i=B(n,`<rev>`),a=await(await $(r)).workflows.rollback(t,i);if(r.json)return e(a);l(`Rolled back workflow ${a.id} to rev ${i}.`),xu(a)})}function Uu(){let e=new D(`workflows`).description(`Create and manage Tangle workflows`);return Cu(e),ju(e),Lu(e),Hu(e),Bu(e),hu(e),_u(e),e}function Wu(e){for(let[t,n]of Object.entries(e.optsWithGlobals()))e.getOptionValue(t)===void 0&&n!==void 0&&e.setOptionValue(t,n)}const Gu=ee(import.meta.url),Ku=Gu(`../package.json`),qu=we(Gu.resolve(`../package.json`)),Ju=Ku.version??`0.0.0`;function Yu(){let e=new D,t=lu(qu,Ju);e.name(`tangle`).description(`CLI for Tangle Sandbox operations`).version(Ju).option(`--json`,`Output JSON where supported, including errors`).option(`--api-key <key>`,`API key (or set TANGLE_API_KEY)`).option(`--base-url <url>`,`API base URL`),e.hook(`preAction`,(e,n)=>{Wu(n);let r=n.opts(),i=r.json===!0||r.ndjson===!0;a(i),n!==t&&!i&&cu(qu,Ju)}),e.addCommand(ei()),e.addCommand(Zc()),e.addCommand(pu()),e.addCommand($c()),e.addCommand(Dc()),e.addCommand(Fc()),e.addCommand(Ic()),e.addCommand(wo()),e.addCommand(gl()),e.addCommand(_l()),e.addCommand(yl()),e.addCommand(Mr()),e.addCommand(nl()),e.addCommand(ks()),e.addCommand(uu()),e.addCommand(jl()),e.addCommand(Il()),e.addCommand(ui()),e.addCommand(xi()),e.addCommand(Wc()),e.addCommand(As()),e.addCommand(Ns());let n=new D(`graph`).description(`Build and run portable agent graphs`);e.addCommand(n);let r=async()=>{n.commands.length||(await import(`./graph-x45OtpHj.mjs`)).registerGraphCommands(n)};e.hook(`preSubcommand`,async(e,t)=>{t===n&&await r()});let i=e.parseAsync.bind(e);e.parseAsync=async(e,t)=>{let n=(e??process.argv).slice(t?.from===`user`?0:2);return n[0]===`help`&&n[1]===`graph`&&await r(),i(e,t)},e.addCommand(Ls()),e.addCommand(Uu()),e.addCommand(oo()),e.addCommand(Qc()),e.addCommand(ol()),e.addCommand(tl()),e.addCommand(Si()),e.addCommand(Hc()),e.addCommand(cc()),e.addCommand($a()),e.addCommand(eo()),e.addCommand(Xc()),e.addCommand(Lc()),e.addCommand(Ll()),e.addCommand(Al()),e.addCommand(t);function o(e){e.configureHelp({showGlobalOptions:!0}),e.configureOutput({writeErr:()=>{}}),e.exitOverride(t=>{t.exitCode===0&&process.exit(0),N(t,e.optsWithGlobals().json===!0)});for(let t of e.commands)o(t)}return o(e),e}try{let e=te(`.env`),t=e.isFile()&&e.size<=65536?x(`.env`,`utf8`):``;/^\s*(export\s+)?(TANGLE|SANDBOX)_\w*\s*=/m.test(t)&&console.error(`The CLI no longer reads .env; export its TANGLE_ and SANDBOX_ variables in your shell.`)}catch{}const Xu=Yu();Xu.parseAsync(process.argv).catch(e=>{N(e,Xu.opts().json===!0)});export{xt as _,Ps as a,Lr as c,Jn as d,on as f,A as g,gn as h,El as i,G as l,zt as m,$ as n,Is as o,P as p,Ol as r,Wr as s,Eu as t,K as u,N as v};
|
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.136",
|
|
4
4
|
"description": "CLI for Tangle Sandbox operations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -60,10 +60,10 @@
|
|
|
60
60
|
"tsx": "^4.23.15",
|
|
61
61
|
"typescript": "^6.0.3",
|
|
62
62
|
"vitest": "^4.1.12",
|
|
63
|
-
"@repo/shared": "0.0.0",
|
|
64
|
-
"@tangle-network/runtime-contracts": "0.20.0",
|
|
65
63
|
"@tangle-network/sdk-session-persistence": "0.7.0",
|
|
66
|
-
"@repo/knowledge-host": "0.0.0"
|
|
64
|
+
"@repo/knowledge-host": "0.0.0",
|
|
65
|
+
"@tangle-network/runtime-contracts": "0.20.0",
|
|
66
|
+
"@repo/shared": "0.0.0"
|
|
67
67
|
},
|
|
68
68
|
"publishConfig": {
|
|
69
69
|
"access": "public",
|
|
@@ -87,8 +87,8 @@
|
|
|
87
87
|
"author": "Tangle Network",
|
|
88
88
|
"license": "MIT",
|
|
89
89
|
"tangleRelease": {
|
|
90
|
-
"sourceSha": "
|
|
91
|
-
"mergedAt": "2026-11-
|
|
90
|
+
"sourceSha": "8be756bba1dfe4488d9d55c9dc20233e198980dc",
|
|
91
|
+
"mergedAt": "2026-11-23T07:46:14-08:00"
|
|
92
92
|
},
|
|
93
93
|
"scripts": {
|
|
94
94
|
"build": "tsdown",
|