@tangle-network/sandbox-cli 0.22.16 → 0.22.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +3 -3
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -146,9 +146,9 @@ await connect(new StdioServerTransport());`;case`claude-desktop`:return`// Add t
|
|
|
146
146
|
Recommended actions:`);for(let e of i.insights.recommendedActions)console.log(` - ${e}`)}}),e.command(`cost <fleet-id>`).description(`Show the fleet's cost estimate`).action(async(e,t)=>{let{client:n}=W(t),r=L(`Estimating cost...`);r.start();let i=await n.fleets.cost(e);r.stop(),t.json?P(i):R({Plan:i.plan,Currency:i.currency,"Hourly (USD)":i.hourlyUsd,"Max lifetime (s)":i.maxLifetimeSeconds,"Estimated max lifetime (USD)":i.estimatedMaxLifetimeUsd,Machines:i.requestedResources.machines,"Total CPU":i.requestedResources.totalCpu,"Total memory (MB)":i.requestedResources.totalMemoryMb})})}function as(e){return[...e.entries()].map(([e,t])=>({machineId:e,sandboxId:t.id,status:t.status}))}function os(e){e.command(`list <fleet-id>`).description(`List the machines of one fleet (fleet id is required)`).option(`--status <status>`,`Filter machines by status`).action(async(e,t)=>{let{client:n}=W(t),r=L(`Fetching fleet...`);r.start();let i=await n.fleets.list({fleetId:e,status:t.status});r.stop();let a=as(i.machines);t.json?P({fleetId:i.fleetId,machines:a}):N(a,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}])}),e.command(`get <fleet-id>`).description(`Show one fleet's manifest (server record)`).action(async(e,t)=>{let{client:n}=W(t),r=L(`Fetching manifest...`);r.start();let i=await n.fleets.manifest(e);r.stop(),t.json?P(i):(R({"Fleet ID":i.fleetId??i.id,Machines:i.machines.length,"Workspace mode":i.workspace?.mode,"Workspace status":i.workspace?.status,"Max lifetime (s)":i.policy?.maxLifetimeSeconds,"Max spend (USD)":i.policy?.maxSpendUsd,Created:i.createdAt,Updated:i.updatedAt}),N(i.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}]))}),e.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(e,t)=>{let{client:n}=W(t),r=L(`Deleting fleet...`);r.start(),await n.fleets.delete(e,{continueOnError:t.continueOnError}),r.stop(),t.json?P({success:!0,fleetId:e}):F(`Fleet deleted: ${e}`)}),e.command(`reap`).description(`TTL cleanup of all expired fleets (fleet-wide)`).option(`--dry-run`,`Report what would be reaped without deleting`).action(async e=>{let{client:t}=W(e),n=L(`Reaping expired fleets...`);n.start();let r=await t.fleets.reapExpired({dryRun:e.dryRun});n.stop(),e.json?P(r):(R({"Dry run":r.dryRun,Expired:r.expired,Deleted:r.deleted}),N(r.fleets,[{key:`fleetId`,header:`Fleet`,width:24},{key:`expiredAt`,header:`Expired`,width:18},{key:`deleted`,header:`Deleted`,width:10}]))}),e.command(`reconcile`).description(`Drop fleet records whose underlying sandboxes vanished`).option(`--dry-run`,`Report orphans without removing them`).action(async e=>{let{client:t}=W(e),n=L(`Reconciling fleets...`);n.start();let r=await t.fleets.reconcile({dryRun:e.dryRun});n.stop(),e.json?P(r):(R({"Dry run":r.dryRun,Checked:r.checked,Orphaned:r.orphaned,Removed:r.removed}),N(r.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 ss(e,t){let n=await Lr({apiKey:t.apiKey,baseUrl:t.baseUrl??ur()}),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 cs(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 ti();if(t.length===0)throw Error(`${e.flagPrefix}-stdin received empty input on stdin`);return t}}function ls(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 us(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 ds(e,t){let n={};return e.cpu!==void 0&&(n.cpuCores=ts(e.cpu,`--cpu`)),e.memory!==void 0&&(n.memoryMB=ts(e.memory,`--memory`)),e.disk!==void 0&&(n.diskGB=ts(e.disk,`--disk`)),t&&(n.accelerator=t),Object.keys(n).length>0?n:void 0}function fs(e){let t=e.split(`/`);return t.length>=2?{provider:t[0],model:t.slice(1).join(`/`)}:{model:e}}function ps(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]=ms(r.join(`=`))}return t}function ms(e){try{return JSON.parse(e)}catch{return e}}function hs(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`?ts(e.gitDepth,`--git-depth`):void 0,sparse:Array.isArray(e.gitSparse)?e.gitSparse:void 0,auth:t?{token:t}:void 0}}}function gs(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:_s(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 _s(e){if(e===`s3`||e===`gcs`||e===`r2`)return e;throw Error(`--storage-type must be one of s3, gcs, or r2`)}function vs(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=pe(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=re.parse(t);return n.length>0?n:void 0}function ys(e){I(` Status: ${e.status}`),I(` Provider: ${e.provider}`),I(` GPU: ${e.accelerator.kind} x ${e.accelerator.count}`),e.customerPricePerHourUsd!==void 0&&I(` Customer price: $${e.customerPricePerHourUsd}/hr`),e.estimatedCustomerCostUsd!==void 0&&I(` Max estimate: $${e.estimatedCustomerCostUsd}`),e.billing&&(I(` Billed seconds: ${e.billing.seconds}`),I(` Customer cost: $${e.billing.customerCostUsd}`))}function bs(e){e.result.stdout&&process.stdout.write(e.result.stdout),e.result.stderr&&process.stderr.write(e.result.stderr),I(`Exit code: ${e.result.exitCode}`)}function xs(e){let t=e.command(`gpu`).description(`Manage on-demand GPU leases for a sandbox`);t.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Checking GPU providers...`);i.start();let a=await(await K(r,n,e)).gpu.providers(t.acceleratorKind?{accelerator:Yo({kind:t.acceleratorKind,count:t.acceleratorCount,memory:t.acceleratorMemory})}:{});if(i.stop(),t.json){P(a);return}N(a.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 a.statuses){let t=e.state===`credential-invalid`?e.credential?.detail:e.estimateError;t&&I(`${e.provider}: ${t}`)}a.usable.length===0&&I(`No GPU provider is usable on this deployment: set the variables in Needs for one provider on the server.`)}),t.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 <seconds>`,`Maximum lease lifetime in seconds`).option(`--idle-timeout <seconds>`,`Destroy after this many idle seconds`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Attaching GPU lease...`);i.start();let a=await(await K(r,n,e)).gpu.attach(Zo(t));i.stop(),t.json?P(a):(F(`GPU lease attached: ${a.id}`),ys(a))}),t.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 <seconds>`,`Maximum lease lifetime in seconds`).option(`--idle-timeout <seconds>`,`Destroy after this many idle seconds`).option(`--timeout <ms>`,`Command timeout in milliseconds`).option(`--cwd <path>`,`Working directory`).action(async(e,t,n)=>{let r,i,a,o;try{let{context:a,client:o}=W(n),s=await K(o,a,e),c=L(`Attaching GPU lease...`);c.start(),r=await s.gpu.attach(Zo(n)),c.stop();let l=L(`Running GPU command...`);l.start(),i=await s.gpu.exec(r.id,{command:Qo(t),...$o(n),cwd:n.cwd}),l.stop(),n.json||bs(i)}catch(e){a=e}finally{if(r)try{let{context:t,client:i}=W(n);r=await(await K(i,t,e)).gpu.detach(r.id)}catch(e){o=e}}if(a){V(a),o&&V(o);return}if(o){V(o);return}n.json?P({lease:r,result:i}):r&&F(`GPU lease detached: ${r.id}`);let s=i?.result.exitCode;s&&s!==0&&(process.exitCode=s)}),t.command(`list <id-or-name>`).description(`List GPU leases attached to a sandbox`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching GPU leases...`);i.start();let a=await(await K(r,n,e)).gpu.list();i.stop(),t.json?P(a):a.length===0?I(`No GPU leases attached.`):N(a.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}])}),t.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(e,t,n,r)=>{let{context:i,client:a}=W(r),o=L(`Running GPU command...`);o.start();let s=await(await K(a,i,e)).gpu.exec(t,{command:Qo(n),...$o(r),cwd:r.cwd});o.stop(),r.json?P(s):bs(s)}),t.command(`detach <id-or-name> <lease-id>`).description(`Detach and destroy a GPU lease`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Detaching GPU lease...`);a.start();let o=await(await K(i,r,e)).gpu.detach(t);a.stop(),n.json?P(o):(F(`GPU lease detached: ${o.id}`),ys(o))})}function Ss(e,t){if(t){P(e);return}if(!e.id){e.kind===`snapshot`&&e.result?.snapshot?F(`Snapshot created: ${e.result.snapshot.snapshotId}`):F(`Sandbox ${e.sandboxId} stopped.`);return}F(`${e.kind===`snapshot`?`Snapshot`:`Stop`} of sandbox ${e.sandboxId} accepted.`),I(`Operation: ${e.id}`),I(`Status: ${e.statusUrl}`)}function Cs(e){return`${e.name} (${e.id})`}async function ws(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 Ts(e,t,n){if(t)return ws(e,t);let r=pr(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 Es(e,t){mr({id:e.id,name:e.name},t)}function Ds(e){hr(e)}async function Os(e){if(e.explicitTeam&&e.personal)throw Error(`--team and --personal cannot be used together`);if(!e.personal)return e.explicitTeam?(await ws(e.client,e.explicitTeam)).id:e.activeTeamId}async function ks(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 ws(e.client,e.explicitTeam)).id}`;if(e.activeTeamId)return`team:${e.activeTeamId}`}function As(e){if(!e)return e;let t={...e};for(let e of[`authToken`,`execToken`])t[e]!==void 0&&(t[e]=`[REDACTED]`);return t}function js(e){e.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(e,t)=>{let{context:n,client:r}=W(t),i=t.nonce===`auto`?g():t.nonce,a=L(`Fetching TEE attestation...`);a.start();let o=await(await K(r,n,e)).getTeeAttestation(i?{attestationNonce:i}:void 0);a.stop(),t.json?P(o):(F(`Attestation fetched for ${e}`),console.log(`TEE type: ${o.attestation.tee_type}`),console.log(`Evidence bytes: ${o.attestation.evidence.length}`),console.log(`Measurement bytes: ${o.attestation.measurement.length}`),console.log(`Timestamp: ${o.attestation.timestamp}`),o.attestationNonce&&console.log(`Nonce: ${o.attestationNonce}`))}),e.command(`list`).description(`List all sandboxes`).option(`-s, --status <status>`,`Filter by status (running, stopped, 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 e=>{let{context:t,client:n}=W(e),r=L(`Fetching sandboxes...`);r.start();let i=await ks({client:n,explicitTeam:e.team,personal:e.personal,allScopes:e.allScopes,activeTeamId:t.activeTeamId}),a=await n.list({status:e.status===`all`?void 0:e.status,limit:Number.parseInt(e.limit,10),scope:i});r.stop(),e.json?P(a):N(a.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}])}),e.command(`get <id-or-name>`).description(`Get sandbox details`).option(`--profile`,`Show the active agent profile provenance (name, hash, skills)`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching sandbox...`);i.start();let a=await K(r,n,e);if(i.stop(),t.profile){let e=a.getProfileProvenance?.();e?(I(`Agent profile provenance:`),I(` Base profile: ${e.base.name??`(inline)`} (${e.base.sha256.slice(0,12)}...)`),I(` Effective: ${e.effective.name??`(inline)`} (${e.effective.sha256.slice(0,12)}...)`),I(` Materialized: ${e.materializedAt}`),e.base.sha256!==e.effective.sha256&&I(` ⚠ Profile changed since creation (base ≠ effective)`)):I(`No profile materialized (bare sandbox). Create with --profile <name> to install one.`);return}t.json?P(a):zt({id:a.id,name:a.name,status:a.status,resources:a.resources,createdAt:a.createdAt?.toISOString(),expiresAt:a.expiresAt?.toISOString(),connection:a.connection})}),e.command(`shapes`).description(`List the named sandbox sizes, the default, and this account's ceiling`).action(async e=>{let{client:t}=W(e),n=await t.shapes();if(e.json){P(n);return}let r=e=>e.cpuCores<=n.ceiling.cpuCores&&e.memoryMB<=n.ceiling.memoryMB&&e.diskGB<=n.ceiling.diskGB;N(n.presets.map(e=>({name:e.name===n.default?`${e.name} (default)`:e.name,cpu:e.cpuCores,memory:`${e.memoryMB} MB`,disk:`${e.diskGB} GB`,available:r(e)?`yes`:e.name===n.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}]),I(`Ceiling for this account: ${Rt(n.ceiling)}`)}),e.command(`delete <id-or-name>`).description(`Delete a sandbox`).option(`-f, --force`,`Skip confirmation`).option(`--name`,`Treat the reference as a sandbox name`).option(`--retry-cleanup`,`Retry server-side cleanup after the sandbox disappeared from get/list`).action(async(e,t)=>{if(!t.force&&!await $r(`Delete sandbox ${e}? [y/N] `,`--force`)){I(`Cancelled.`);return}let{context:n,client:r}=W(t),i=L(`Deleting sandbox...`);i.start();let a=await Kr(r,n,e,{retryCleanup:t.retryCleanup,name:t.name});i.stop(),F(a===`already_absent`?`Sandbox ${e} was already gone.`:`Sandbox ${e} deleted.`)}),e.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:r}=W(t),i=L(`Stopping sandbox...`);i.start();let a=await K(r,n,e,{nameOnly:t.name});if(t.wait===!1){let e=await a.stop({wait:!1});i.stop(),Ss(e.info,!!t.json);return}await a.stop(),i.stop(),F(`Sandbox ${e} stopped.`)}),e.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=Number.parseInt(t.timeout,10);if(!Number.isFinite(n)||n<=0)throw Error(`--timeout must be a positive number of milliseconds`);let r=H({apiKey:t.apiKey,baseUrl:t.baseUrl,timeout:n}),i=U(r),a=L(`Resuming sandbox...`);a.start();let o=await K(i,r,e);await o.resume({timeoutMs:n}),t.wait&&(a.text=`Waiting for sandbox to start...`,await o.waitFor(`running`,{timeoutMs:n})),a.stop(),F(`Sandbox ${o.id} resumed.`)})}function Ms(e){e.command(`create`).description(`Create a new sandbox`).option(`-n, --name <name>`,`Sandbox name`).option(`-e, --environment <environment>`,Ns).addOption(Ps()).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(`--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 <seconds>`,`Maximum create-time GPU lease lifetime in seconds`).option(`--gpu-idle-timeout <seconds>`,`Destroy the create-time GPU lease after this many idle seconds`).option(`--lifetime <seconds>`,`Max wall-clock lifetime before the sandbox is suspended — stopped, not deleted; resume it within the cold window (default 3600 = 1h). Raise it for long sessions, e.g. --lifetime 7200`,`3600`).option(`--idle-timeout <seconds>`,"Idle time before the sandbox is stopped — not deleted (default 900 = 15m). Resume it later with `tangle sandbox resume <id-or-name>`, or it auto-resumes on next use. Raise it for demos, e.g. --idle-timeout 3600",`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 x(`--driver <type>`,`Run on Tangle network operators instead of the platform's hosts (--tee needs it)`).choices([`tangle`])).option(`--backend <type>`,`Backend agent type (${n.join(`, `)})`).option(`--backend-model <model>`,`Model override (format: provider/model)`).addOption(new x(`--reasoning-effort <level>`,`Reasoning effort for the backend's model; overrides the profile's model.reasoningEffort`).choices(w)).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 e=>{let t=await cs({envVarName:e.gitTokenEnv,fromStdin:e.gitTokenStdin,flagPrefix:`--git-token`}),n=await cs({envVarName:e.storageSecretAccessKeyEnv,fromStdin:e.storageSecretAccessKeyStdin,flagPrefix:`--storage-secret-access-key`}),r=await cs({envVarName:e.backendApiKeyEnv,fromStdin:e.backendApiKeyStdin,flagPrefix:`--backend-api-key`}),i=ls({secret:e.cliAuth,backend:e.backend,apiKeyGiven:r!==void 0}),a;if(e.profileStdin){let e=await ti(`--profile-stdin`,`the AgentProfile JSON`);try{a=JSON.parse(e)}catch{V(Error(`--profile-stdin: the input is not valid JSON`));return}}else if(e.profile){let t=String(e.profile);if(t.startsWith(`.`)||t.startsWith(`/`)||t.endsWith(`.json`))try{a=JSON.parse(pe(t,`utf8`))}catch(e){V(Error(`--profile ${t}: ${e.message}`));return}else try{a=await ss(t,e)}catch(e){V(Error(`--profile ${t}: ${e.message}`));return}}a=Is(a,e.reasoningEffort);let o=H({apiKey:e.apiKey,baseUrl:e.baseUrl,timeout:e.timeout?Number.parseInt(e.timeout,10):void 0}),s=U(o),c=L(`Creating sandbox...`);c.start();let l=await Os({client:s,explicitTeam:e.team,personal:e.personal,activeTeamId:o.activeTeamId}),u=es(e.env??[],`--env`,`env`),d=e.metadata?ps(e.metadata):void 0,f=hs(e,t),p=gs(e,n),m=e.acceleratorKind?Yo({kind:String(e.acceleratorKind),count:String(e.acceleratorCount),memory:typeof e.acceleratorMemory==`string`?e.acceleratorMemory:void 0}):void 0,g=Xo({provider:typeof e.gpuProvider==`string`?e.gpuProvider:void 0,image:typeof e.gpuWorkerImage==`string`?e.gpuWorkerImage:void 0,env:Array.isArray(e.gpuEnv)?e.gpuEnv:void 0,maxSpendUsd:typeof e.gpuMaxSpendUsd==`string`?e.gpuMaxSpendUsd:void 0,maxLifetime:typeof e.gpuMaxLifetime==`string`?e.gpuMaxLifetime:void 0,idleTimeout:typeof e.gpuIdleTimeout==`string`?e.gpuIdleTimeout:void 0},!!m,`Create-time GPU lease flags require --accelerator-kind`),v=e.driver?{type:`tangle`}:void 0,ee=e.backend||e.backendModel||a?{...e.backend?{type:_(e.backend)}:{},...a?{profile:a}:{},model:e.backendModel||r||i?{...e.backendModel?fs(e.backendModel):{},apiKey:r,...i?{cliAuth:i}:{}}:void 0}:void 0,y=us(e.secret),te=i?[...new Set([...y??[],i.secretEnv])]:y,b=vs(e.proxySecret),x=ds(e,m),S=e.sshKeyFile??(e.ssh&&!e.sshKey&&!e.sshKeys?.length?[Fs()]:[]),ne=[...e.sshKey?[e.sshKey]:[],...S.map(e=>pe(e,`utf8`).trim())],C={name:e.name,environment:e.environment,runtime:e.runtime,bare:e.bare||void 0,sshEnabled:e.ssh||!!e.sshKey||ne.length>0||!!e.sshKeys?.length,sshPublicKeys:ne.length>0?ne:void 0,sshKeyIds:e.sshKeys,webTerminalEnabled:e.webTerminal,env:Object.keys(u).length>0?u:void 0,git:f,...x?{resources:x}:{},gpuLease:g,maxLifetimeSeconds:Number.parseInt(e.lifetime,10),idleTimeoutSeconds:Number.parseInt(e.idleTimeout,10),storage:p,fromSnapshot:e.fromSnapshot,publicTemplateId:e.publicTemplate,publicTemplateVersionId:e.publicTemplateVersion,teamId:l,...e.billingOwner?{billingOwnerId:e.billingOwner}:{},secrets:te,...b?{proxySecrets:b}:{},metadata:d,driver:v,backend:ee},re=e.tee?{tee:e.tee,sealed:e.sealed||void 0,attestationRefresh:e.attestationRefresh||e.attestationNonce===`auto`||void 0}:void 0,w=re?await h(s,{...C,confidential:re,attestationNonce:e.attestationNonce??(e.attestationRefresh?`auto`:void 0),requireAttestation:e.requireAttestation??!0}):void 0,T=w?.sandbox??await s.create(C);e.wait&&(c.text=`Waiting for sandbox to start...`,await T.waitFor(`running`,{timeoutMs:12e4}),await T.refresh()),c.stop(),e.json?P({id:T.id,name:T.name,status:T.status,resources:T.resources,createdAt:T.createdAt,expiresAt:T.expiresAt,connection:As(T.connection),teamId:l,gpuLease:T.gpuLease,confidential:re,attestation:w?.attestation,attestationNonce:w?.attestationNonce}):(F(`Sandbox created: ${T.id}`),zt({id:T.id,name:T.name,status:T.status,resources:T.resources,createdAt:T.createdAt?.toISOString(),expiresAt:T.expiresAt?.toISOString(),connection:T.connection}),l&&console.log(`Team: ${l}`),T.gpuLease&&(console.log(`GPU lease: ${T.gpuLease.id}`),ys(T.gpuLease)),re&&(console.log(`TEE: ${re.tee}`),console.log(`Attestation: ${w?.attestation?`present`:`not returned`}`),w?.attestationNonce&&console.log(`Attestation nonce: ${w.attestationNonce}`)))})}const Ns="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; `environments list` shows each image's runtimes";function Ps(){return new x(`--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(c)}function Fs(){let e=[`id_ed25519`,`id_ecdsa`,`id_rsa`].map(e=>`${k()}/.ssh/${e}.pub`),t=e.find(e=>de(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 Is(e,t){if(!t)return e;let n=e?.model??{};return{...e,model:{...n,reasoningEffort:t}}}function Ls(e){if(e.spec){let t=JSON.parse(pe(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=Bs(e),n=Vs(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=Hs(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 Rs(e){let{base:t,machines:n}=Ls(e);return{...t,machines:n}}function zs(e){let{base:t,machines:n}=Ls(e);return{...t,workers:n}}function Bs(e){let t={};if(e.cpu&&(t.cpuCores=Number(e.cpu)),e.memory&&(t.memoryMB=Number(e.memory)),e.disk&&(t.diskGB=Number(e.disk)),e.acceleratorKind)t.accelerator=Yo({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 Vs(e,t){return Xo({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 Hs(e){let t={};return e.maxSpendUsd&&(t.maxSpendUsd=Number(e.maxSpendUsd)),e.maxLifetime&&(t.maxLifetimeSeconds=Number(e.maxLifetime)),Object.keys(t).length>0?t:void 0}function Us(e){e.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>`,Ns).addOption(Ps()).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 <seconds>`,`Maximum GPU lease lifetime per machine in seconds`).option(`--gpu-idle-timeout <seconds>`,`Destroy each GPU lease after this many idle seconds`).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 <s>`,`Max machine lifetime in seconds (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 e=>{let{client:t}=W(e),n=L(`Creating fleet...`);n.start();let r=e.coordinator?await t.fleets.createWithCoordinator(zs(e)):await t.fleets.create(Rs(e));n.stop();let i=as(r.machines);e.json?P({fleetId:r.fleetId,machines:i}):(F(`Fleet created: ${r.fleetId}`),N(i,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`status`,header:`Status`,width:14}]))})}function Ws(e){e.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(e,t,n)=>{let{client:r}=W(n),i=L(`Dispatching command...`);i.start();let a=await(await r.fleets.list({fleetId:e})).dispatchExecDetailed(t,{machines:n.machine,cwd:n.cwd,timeoutMs:n.timeout?Number(n.timeout):void 0,maxConcurrent:n.maxConcurrent?Number(n.maxConcurrent):void 0});if(i.stop(),n.json)P(a);else{N(a.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 a.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}`)}}a.results.some(e=>e.ok===!1)&&(process.exitCode=1)}),e.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(e,t)=>{let n=/^\d+$/.test(t.agents)?Number(t.agents):JSON.parse(pe(t.agents,`utf8`));if(!Array.isArray(n)&&e===void 0)throw Error(`A prompt is required unless --agents names a file whose agents carry tasks`);let{client:r}=W(t);if(!!t.parentFleet!=!!t.parentAgent)throw Error(`--parent-fleet and --parent-agent go together`);let i=t.placement===`auto`||t.placement===`dedicated`?t.placement:{agentsPerSandbox:Number(t.placement)},a=t.maxSpendUsd?Number(t.maxSpendUsd):void 0,o=L(`Creating fleet...`);o.start();let s=Date.now(),c=await r.fleets.create({fleetId:t.fleetId,agents:n,placement:i,defaults:{...t.environment?{environment:t.environment}:{},...t.memory?{resources:{memoryMB:Number(t.memory)}}:{},...t.model?{backend:{type:`opencode`,model:{model:t.model}}}:{}},...a===void 0?{}:{budgetUsd:a},...t.parentFleet?{parent:{fleetId:t.parentFleet,agentId:t.parentAgent}}:{}}),l=Date.now()-s;o.stop(),t.json||F(`Fleet ${c.fleetId}: ${c.agents.length} agents on ${c.machines.size} sandboxes in ${l} ms`);let u=[],d;try{for await(let n of c.run(e,{timeoutMs:t.timeout?Number(t.timeout):void 0})){if(n.type===`agent.finished`&&!t.json){let e=n.result;console.log(`[${e.agentId}] ${e.harness??`default`}/${e.model??`default`} ${e.status} ${e.durationMs}ms ${e.costUsd===void 0?`no cost reported`:`$${e.costUsd.toFixed(5)}`} ${e.result?.response??e.error??``}`)}n.type===`fleet.finished`&&(u=n.results,d=n.spend)}}finally{t.keep||await c.delete({continueOnError:!0})}t.json?P({fleetId:c.fleetId,createMs:l,sandboxes:c.machines.size,results:u,spend:d,deleted:!t.keep}):R({fleetId:c.fleetId,completed:u.filter(e=>e.status===`completed`).length,agents:u.length,spend:JSON.stringify(d),deleted:!t.keep}),u.some(e=>e.status!==`completed`)&&(process.exitCode=1)}),e.command(`cancel <fleet-id>`).description(`Interrupt every agent of a fleet and cancel its child fleets; sandboxes keep running`).action(async(e,t)=>{let{client:n}=W(t),r=await(await n.fleets.list({fleetId:e})).cancel();t.json?P({fleetId:e,...r}):F(`Fleet ${e}: interrupted ${r.interrupted} agents, cancelled ${r.children} child fleets`)})}const Gs=[`list`,`create`,`delete`,`exec`,`prompt`,`read`,`write`];function Ks(e){if(!(!e||e.length===0)){for(let t of e)if(!Gs.includes(t))throw Error(`Invalid token action '${t}'. Allowed: ${Gs.join(`, `)}`);return e}}function qs(e){return e.length<=12?`****`:`${e.slice(0,6)}...${e.slice(-4)} (masked — use --json for full value)`}function Js(e){e.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(e,t)=>{let{client:n}=W(t),r=L(`Minting fleet token...`);r.start();let i=await n.fleets.createToken(e,{actions:Ks(t.action),ttlMinutes:t.ttlMinutes?Number(t.ttlMinutes):void 0});r.stop(),t.json?P(i):(R({"Fleet ID":i.fleetId,Token:qs(i.token),"Expires at":new Date(i.expiresAt).toISOString(),Actions:i.actions.join(`, `)}),console.log(`
|
|
147
147
|
Re-run with --json to print the full token value.`))})}function Ys(){let e=new b(`workspace`).description(`Manage a fleet's shared workspace`);return e.command(`snapshot <fleet-id>`).description(`Snapshot the fleet's shared workspace`).action(async(e,t)=>{let{client:n}=W(t),r=L(`Creating workspace snapshot...`);r.start();let i=await n.fleets.createWorkspaceSnapshot(e);r.stop(),t.json?P(i):F(`Workspace snapshot created: ${i.snapshotId??i.id}`)}),e.command(`restore <fleet-id> <snapshot-id>`).description(`Restore the fleet's shared workspace from a snapshot`).action(async(e,t,n)=>{let{client:r}=W(n),i=L(`Restoring workspace...`);i.start();let a=await r.fleets.restoreWorkspaceSnapshot(e,t);i.stop(),n.json?P(a):F(`Workspace restored from ${a.snapshotId??t}`)}),e.command(`reconcile <fleet-id>`).description(`Re-mount the shared workspace on all fleet machines`).action(async(e,t)=>{let{client:n}=W(t),r=L(`Reconciling workspace...`);r.start();let i=await n.fleets.reconcileWorkspace(e);r.stop(),t.json?P(i):(R({"Fleet ID":i.fleetId,Checked:i.checked,"Orphaned mounts":i.orphanedMounts}),N(i.machines,[{key:`machineId`,header:`Machine`,width:20},{key:`sandboxId`,header:`Sandbox`,width:24},{key:`mounted`,header:`Mounted`,width:10}]))}),e}function Xs(){let e=new b(`fleet`).description(`Manage sandbox fleets`);return Us(e),os(e),e.addCommand(Ys()),Ws(e),is(e),Js(e),e}function Zs(){let e=new b(`fs`).description(`File system operations on sandboxes`);return e.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(e,t,n,r)=>{let{context:i,client:a}=W(r),o=await K(a,i,e);if(o=await q(o),!E.existsSync(t))throw Error(`Local file not found: ${t}`);let s=E.statSync(t),c=Date.now();r.json||console.error(`Uploading ${t} to ${n}...`),await o.fs.upload(t,n,{onProgress:e=>{if(r.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesUploaded}/${e.totalBytes} bytes)`)}});let l=Date.now()-c;r.json||console.error(``),r.json?P({success:!0,localPath:t,remotePath:n,size:s.size,durationMs:l}):console.log(`✓ Uploaded ${s.size} bytes in ${l}ms`)}),e.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(e,t,n,r)=>{let{context:i,client:a}=W(r),o=await K(a,i,e);o=await q(o);let s=Date.now();r.json||console.error(`Downloading ${t} to ${n}...`),await o.fs.download(t,n,{onProgress:e=>{if(r.json)return;let t=e.percentage.toFixed(1);process.stderr.write(`\rProgress: ${t}% (${e.bytesDownloaded}/${e.totalBytes} bytes)`)}});let c=Date.now()-s,l=E.statSync(n);r.json||console.error(``),r.json?P({success:!0,remotePath:t,localPath:n,size:l.size,durationMs:c}):console.log(`✓ Downloaded ${l.size} bytes in ${c}ms`)}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a);let o=await a.fs.list(t,{all:n.all,long:n.long});if(n.json)P(o);else if(n.long)Bt([`Mode`,`Owner`,`Group`,`Size`,`Modified`,`Name`],o.map(e=>{let t=e.isDir?`d`:e.isSymlink?`l`:`-`,n=Qs(e.permissions),r=e.isDir?`<DIR>`:$s(e.size),i=e.modTime.toLocaleDateString();return[t+n,e.owner,e.group,r,i,e.name]}));else{let e=o.map(e=>e.isDir?`${e.name}/`:e.name);console.log(e.join(` `))}}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a);let o=await a.fs.stat(t);n.json?P(o):(console.log(` File: ${o.name}`),console.log(` Path: ${o.path}`),console.log(` Size: ${$s(o.size)} (${o.size} bytes)`),console.log(` Type: ${o.isDir?`directory`:o.isSymlink?`symlink`:`file`}`),console.log(` Mode: ${Qs(o.permissions)} (${o.permissions.toString(8)})`),console.log(` Owner: ${o.owner}`),console.log(` Group: ${o.group}`),console.log(` Modified: ${o.modTime.toISOString()}`),console.log(` Accessed: ${o.accessTime.toISOString()}`))}),e.command(`cat`).description(`Print file contents`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to file`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a);let o=await a.read(t);n.json?P({path:t,content:o}):console.log(o)}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a),await a.fs.delete(t,{recursive:n.recursive}),n.json?P({success:!0,path:t,deleted:!0}):console.log(`✓ Deleted: ${t}`)}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a),await a.fs.mkdir(t,{recursive:n.parents}),n.json?P({success:!0,path:t,created:!0}):console.log(`✓ Created: ${t}`)}),e.command(`exists`).description(`Check if a path exists`).argument(`<sandbox-id-or-name>`,`Sandbox ID or name`).argument(`<path>`,`Path to check`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=await K(i,r,e);a=await q(a);let o=await a.fs.exists(t);n.json?P({path:t,exists:o}):(console.log(o?`exists`:`not found`),process.exit(+!o))}),e}function Qs(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 $s(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 ec(){let e=new b(`git`).description(`Git operations in a sandbox workspace`);return e.command(`status`).description(`Show git repository status`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching status...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.git.status();if(i.stop(),t.json)P(o);else if(!o.isRepo)console.log(`No git repository in the sandbox workspace.`);else{if(console.log(`Branch: ${o.branch??`unknown`}`),console.log(`HEAD: ${o.head.slice(0,7)||`(no commits)`}`),console.log(`Dirty: ${o.isDirty?`yes`:`no`}`),o.ahead&&console.log(`Ahead: ${o.ahead}`),o.behind&&console.log(`Behind: ${o.behind}`),o.staged.length>0){console.log(`\nStaged (${o.staged.length}):`);for(let e of o.staged)console.log(` + ${e}`)}if(o.modified.length>0){console.log(`\nModified (${o.modified.length}):`);for(let e of o.modified)console.log(` M ${e}`)}if(o.untracked.length>0){console.log(`\nUntracked (${o.untracked.length}):`);for(let e of o.untracked)console.log(` ? ${e}`)}}}),e.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching log...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.git.log(Number.parseInt(t.limit,10));if(i.stop(),t.json)P(o);else if(o.length===0)console.log(`No commits found`);else for(let e of o)console.log(`${e.shortSha} ${e.message.split(`
|
|
148
148
|
`)[0]} (${e.author}, ${e.date.toLocaleDateString()})`)}),e.command(`diff`).description(`Show diff`).argument(`<id-or-name>`,`Sandbox ID or name`).option(`--ref <ref>`,`Ref to diff against`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching diff...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.git.diff(t.ref);i.stop(),t.json?P(o):o.raw?console.log(o.raw):console.log(`${o.additions} additions, ${o.deletions} deletions across ${o.files.length} files`)}),e.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:r,client:i}=W(n),a=await K(i,r,e);a=await q(a),await a.git.add(t),F(`Staged: ${t.join(`, `)}`)}),e.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(e,t)=>{let{context:n,client:r}=W(t),i=await K(r,n,e);i=await q(i);let a=await i.git.commit(t.message,{amend:t.amend});t.json?P(a):F(`Committed: ${a.shortSha} ${a.message}`)}),e.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:r}=W(t),i=L(`Pushing...`);i.start();let a=await K(r,n,e);a=await q(a),await a.git.push({force:t.force}),i.stop(),F(`Pushed to remote`)}),e.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:r}=W(t),i=L(`Pulling...`);i.start();let a=await K(r,n,e);a=await q(a),await a.git.pull({rebase:t.rebase}),i.stop(),F(`Pulled from remote`)}),e.command(`branches`).description(`List branches`).argument(`<id-or-name>`,`Sandbox ID or name`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching branches...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.git.branches();i.stop(),t.json?P(o):o.length===0?console.log(`No branches found`):Bt([`Name`,`Current`,`Remote`],o.map(e=>[e.name,e.current?`* `:` `,e.upstream??`-`]))}),e.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:r,client:i}=W(n),a=await K(i,r,e);a=await q(a),await a.git.checkout(t,{create:n.create}),F(`Checked out: ${t}${n.create?` (new)`:``}`)}),e}function tc(e,t=16){if(!Number.isInteger(t)||t<=0||t>64)throw TypeError(`stableHashHex: lengthHex must be in [1, 64] (got ${t})`);let n=typeof e==`string`?e:JSON.stringify(e,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e={},n=t;for(let t of Object.keys(n).sort())e[t]=n[t];return e}return t});return S(`sha256`).update(n).digest(`hex`).slice(0,t)}Object.freeze([`HS256`]),Object.freeze([`RS256`]);async function nc(e,t,n=`tangle --help`){let r=new AbortController,i=e??r.signal,a=()=>{r.abort(),process.stderr.write(`Stopping…
|
|
149
|
-
`)};e||(process.once(`SIGINT`,a),process.once(`SIGTERM`,a));try{return i.throwIfAborted(),await t(i)}catch(e){if(!i.aborted||e instanceof z&&e.code===`RUN_STOPPED`)throw e;let t=new z(`RUN_STOPPED`,`Command interrupted`,`A stop request ended this execution`,n);throw e instanceof Error&&`runId`in e&&typeof e.runId==`string`&&Object.assign(t,{runId:e.runId}),t}finally{e||(process.off(`SIGINT`,a),process.off(`SIGTERM`,a))}}function rc(e,t){for(let[n,r]of Object.entries(t)){let t=e.gates?.find(e=>e.id===n);if(!t||!t.choices.includes(r))throw new z(`GATE_CHOICE_INVALID`,`Invalid choice for gate '${n}'`,t?`Choose one of: ${t.choices.join(`, `)}`:`The graph does not declare this gate`,`tangle graph run --help`)}}function ic(e,t){let n=t.signal;return async r=>{let i=Object.hasOwn(e,r.gate)?e[r.gate]:void 0,a=`--param ${He(`gate.${r.gate}=<choice>`)}`,o=`${r.question} Choose one of: ${r.choices.join(`, `)}`,s=()=>new z(`GATE_ANSWER_REQUIRED`,`Gate '${r.gate}' needs an answer. ${o}. Pass ${a}`,o,`tangle graph run <graph> ${a}`);if(i!==void 0)return{kind:`choose`,choice:i,by:`cli:param`};if(t.json||!process.stdin.isTTY)throw s();let c;try{c=await ei(`${r.question} [${r.choices.join(` / `)}]`,void 0,n)}catch{if(n.aborted)return{kind:`stop`,reason:`Gate input interrupted or timed out`,by:`cli:terminal`};throw s()}if(!r.choices.includes(c))throw s();return{kind:`choose`,choice:c,by:`cli:terminal`}}}const ac=j.string().regex(/^[a-f0-9]{64}$/),oc=j.strictObject({version:j.literal(1),runId:j.uuid(),file:j.string().refine(ye),cwd:j.string().refine(ye),sourceDigest:ac,graphDigest:ac,params:j.record(j.string(),j.unknown()),gateChoices:j.record(j.string(),j.string()).optional(),startedAt:j.iso.datetime(),seat:j.string().optional()});function Y(e){throw new z(`GRAPH_RESUME_REFUSED`,`The graph run cannot be resumed`,e,`tangle graph run --help`)}async function sc(e){j.uuid().safeParse(e).success||Y(`Use a recorded graph run ID`);let t;try{let n=O(await qe(O(k(),`.tangle`)),`runs`,e);await qe(n)!==n&&Y(`The run directory redirects elsewhere`),t=await Ge(O(n,`input.json`),ue.O_RDONLY|ue.O_NOFOLLOW),(await t.stat()).isFile()||Y(`The run input is not a regular file`);let r=oc.parse(JSON.parse(await t.readFile(`utf8`)));return(r.runId!==e||await qe(r.cwd)!==r.cwd)&&Y(`The recorded run or workspace identity changed`),r}catch(e){if(e instanceof z)throw e;return Y(`The private recorded run input is missing or invalid`)}finally{await t?.close()}}async function cc(e,t){await Je(O(e,`input.json`),JSON.stringify(t),{flag:`wx`,mode:384,flush:!0})}function lc(e,t,n,r,i={}){e.sourceDigest!==n&&Y(`The authored graph source changed`),t.cloud&&Y(`A local run cannot move to cloud execution`),Object.entries(r).some(([t,n])=>!Object.hasOwn(e.params,t)||oe(n)!==oe(e.params[t]))&&Y(`A recorded graph parameter changed`),Object.entries(i).some(([t,n])=>e.gateChoices?.[t]!==n)&&Y(`A recorded gate choice changed`),t.seat!==void 0&&t.seat!==e.seat&&Y(`The recorded graph seat override changed`)}const uc=`claude,codex,kimi,opencode,gemini,pi`;function dc(e,t){let n;return async(r,{node:i,lastCandidate:a})=>{t.throwIfAborted();let o;try{o=r===void 0?void 0:ce(r)}catch(e){throw e instanceof Error&&Object.assign(e,{node:i,seat:r,fixCommand:`tangle graph run --help`}),e}n??=Ye({cwd:e,signal:t,config:Xe({...process.env,BRIDGE_BACKENDS:uc,BRIDGE_SUBSCRIPTIONS_ONLY:`1`})});let s=await n;t.throwIfAborted();let c=e=>e.authentication?.status===`authenticated`&&e.authentication.authMode===`subscription`,l=o?.harness??s.find(e=>e.provider&&c(e))?.backend,u=s.filter(e=>e.backend===l),d=u.filter(c),f=o?u.find(e=>e.id===`${o.harness}/${o.model}`)??d.find(e=>e.provider===o.provider):d.find(e=>e.default)??d.find(e=>e.recommended)??d[0];if(!f||!c(f)){if(a===!1)return;let e=f?.authentication??u[0]?.authentication??(o?void 0:s.find(e=>e.authentication?.fix)?.authentication);throw Object.assign(new z(o?`SEAT_NOT_LOGGED_IN`:`SEAT_NONE_DETECTED`,`Node '${i}' has no available subscription${o?` for ${o.harness}`:``}`,e?`Selected provider: ${e.status} (${e.authMode})`:`No authenticated subscription route was detected`,e?.fix??`tangle graph run --help`),{node:i,seat:r})}let p=o?.harness??ce(f.id).harness,m=o?.provider??f.provider,h=o?.model??f.id.slice(p.length+1);if(!m||!h)throw new z(`MODEL_PROVIDER_MISMATCH`,`Node '${i}' has an unresolved model provider`,`Bridge has no configured provider for ${r??p}`,`tangle graph run --help`);return{harness:p,provider:m,model:h,selector:{kind:`all-eligible`},...o?.reasoningEffort===void 0?{}:{reasoningEffort:o.reasoningEffort}}}}function X(e){return Vr({signal:e.signal,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl}})}const fc=j.object({version:j.literal(1),type:j.enum([`state`,`ack`,`error`,`event`]),requestId:j.string().optional(),operationId:j.string().optional(),command:j.string().optional(),code:j.string().optional(),message:j.string().optional(),result:j.unknown().optional()}).passthrough(),pc=j.object({state:j.object({runConfiguration:j.unknown()}),view:j.object({capabilities:j.record(j.string(),j.object({available:j.boolean(),reason:j.string().optional()}))})}),mc=j.object({status:j.enum([`completed`,`failed`,`cancelled`]),analysis:j.object({id:j.string().min(1)}).passthrough(),source:j.object({runtimeRun:j.unknown()}).passthrough()}).passthrough(),hc=`TANGLE_GRAPH_ANALYSIS_SOURCE`;async function gc(e,t,n){if(!e.startsWith(`wfrun_`)){let t=O(await qe(O(k(),`.tangle`)),`runs`,e);if(await qe(t)!==t)throw new z(`RUN_NOT_FOUND`,`The run directory redirects elsewhere`,`Use the recorded local run directory`,`tangle graph inspect --help`);return{source:`runtime:${e}@${t}`,env:{},schema:j.object({runId:j.literal(e),runDir:j.literal(t)})}}let r={signal:n,...t.apiKey===void 0?{}:{apiKey:t.apiKey},...t.baseUrl===void 0?{}:{baseUrl:t.baseUrl}},i=await X(r),a=j.object({id:j.literal(e),workflowId:j.string(),revUsed:j.number().int(),execution:j.object({kind:j.literal(`graph`),sourceSha:j.string(),authoredGraphDigest:j.string(),graphDigest:j.string()}),runtime:j.object({snapshot:j.object({supervisors:j.tuple([j.object({id:j.string()})])})})}).parse(await i.workflows.getRun(e,{signal:n})),o=a.runtime.snapshot.supervisors[0];if(!o)throw new z(`BRAID_RPC_FAILED`,`The cloud run has no retained Runtime root`,`Wait for execution evidence before analysis`,`tangle graph inspect ${e}`);let s=await Lr(r);if(new URL(s.baseUrl.replace(/\/+$/,``)).href!==new URL(i.baseUrl.replace(/\/+$/,``)).href)throw new z(`AUTH_REQUIRED`,`The analysis source origin changed`,`Use the same authenticated platform origin`,`tangle auth status --json`);return{source:`runtime:${e}@${hc}`,env:{[hc]:JSON.stringify({url:`${s.baseUrl.replace(/\/+$/,``)}/v1/workflows/runs/${encodeURIComponent(e)}`,headers:{Authorization:`Bearer ${s.token}`}})},schema:j.object({runId:j.literal(e),remoteEndpointEnv:j.literal(hc),checkpoint:j.object({workflowId:j.literal(a.workflowId),runtimeRunId:j.literal(o.id),revUsed:j.literal(a.revUsed),sourceSha:j.literal(a.execution.sourceSha),authoredGraphDigest:j.literal(a.execution.authoredGraphDigest),graphDigest:j.literal(a.execution.graphDigest)})})}}async function _c(e,t){if(!e.startsWith(`wfrun_`)&&!j.uuid().safeParse(e).success)throw new z(`RUN_NOT_FOUND`,`Use a recorded graph run ID`,`The run identifier is invalid`,`tangle graph inspect --help`);if(!Number.isSafeInteger(t.timeout)||t.timeout<1)throw new z(`INVALID_TIMEOUT`,`Use a positive analysis timeout`,`The timeout must be an integer number of milliseconds`,`tangle graph analyze --help`);let n=t.profile;if(!n?.trim())throw new z(`USAGE_INVALID`,`Select the canonical analysis profile`,`Graph analysis requires an existing canonical AgentProfile reference`,`tangle graph analyze `+e+` --profile <name|path>`);let r=/^(?:\.\.?)[/\\]/.test(n)?xe(process.cwd(),n):n;return nc(t.signal,async n=>{let i=await gc(e,t,n),a=i.source;return Ol({signal:n,errorRunId:e},async n=>{let o=await n.bridge(),s=await We(O(n.runDir,`analysis-`)),c=O(s,`config.json`),l=O(s,`database.key`),u=O(s,`state.sqlite`),d=`connection-owned-graph-bridge`,f=new Date().toISOString();await Je(l,ne(32),{mode:384,flag:`wx`}),await Je(c,JSON.stringify({format:`braid-startup-config`,schemaVersion:2,profile:r,connectionId:d,connections:[{id:d,name:`Graph analysis`,kind:`cli-bridge`,endpoint:o.bridgeUrl,providerOptions:{transport:`local`},createdAt:f,updatedAt:f,lastHealth:{status:`unknown`}}]}),{mode:384,flag:`wx`});let p=n.signal,m=`op-${C()}`,h=`op-${C()}`,g=`${m}:initialize`,_=`${m}:analyze`,v=`${m}:shutdown`,ee={version:1,requestId:g,command:`initialize`,params:{workspace:n.cwd,subscribe:!1}},y={version:1,requestId:_,operationId:m,command:`analyze`,params:{source:a,recipe:`all`,
|
|
149
|
+
`)};e||(process.once(`SIGINT`,a),process.once(`SIGTERM`,a));try{return i.throwIfAborted(),await t(i)}catch(e){if(!i.aborted||e instanceof z&&e.code===`RUN_STOPPED`)throw e;let t=new z(`RUN_STOPPED`,`Command interrupted`,`A stop request ended this execution`,n);throw e instanceof Error&&`runId`in e&&typeof e.runId==`string`&&Object.assign(t,{runId:e.runId}),t}finally{e||(process.off(`SIGINT`,a),process.off(`SIGTERM`,a))}}function rc(e,t){for(let[n,r]of Object.entries(t)){let t=e.gates?.find(e=>e.id===n);if(!t||!t.choices.includes(r))throw new z(`GATE_CHOICE_INVALID`,`Invalid choice for gate '${n}'`,t?`Choose one of: ${t.choices.join(`, `)}`:`The graph does not declare this gate`,`tangle graph run --help`)}}function ic(e,t){let n=t.signal;return async r=>{let i=Object.hasOwn(e,r.gate)?e[r.gate]:void 0,a=`--param ${He(`gate.${r.gate}=<choice>`)}`,o=`${r.question} Choose one of: ${r.choices.join(`, `)}`,s=()=>new z(`GATE_ANSWER_REQUIRED`,`Gate '${r.gate}' needs an answer. ${o}. Pass ${a}`,o,`tangle graph run <graph> ${a}`);if(i!==void 0)return{kind:`choose`,choice:i,by:`cli:param`};if(t.json||!process.stdin.isTTY)throw s();let c;try{c=await ei(`${r.question} [${r.choices.join(` / `)}]`,void 0,n)}catch{if(n.aborted)return{kind:`stop`,reason:`Gate input interrupted or timed out`,by:`cli:terminal`};throw s()}if(!r.choices.includes(c))throw s();return{kind:`choose`,choice:c,by:`cli:terminal`}}}const ac=j.string().regex(/^[a-f0-9]{64}$/),oc=j.strictObject({version:j.literal(1),runId:j.uuid(),file:j.string().refine(ye),cwd:j.string().refine(ye),sourceDigest:ac,graphDigest:ac,params:j.record(j.string(),j.unknown()),gateChoices:j.record(j.string(),j.string()).optional(),startedAt:j.iso.datetime(),seat:j.string().optional()});function Y(e){throw new z(`GRAPH_RESUME_REFUSED`,`The graph run cannot be resumed`,e,`tangle graph run --help`)}async function sc(e){j.uuid().safeParse(e).success||Y(`Use a recorded graph run ID`);let t;try{let n=O(await qe(O(k(),`.tangle`)),`runs`,e);await qe(n)!==n&&Y(`The run directory redirects elsewhere`),t=await Ge(O(n,`input.json`),ue.O_RDONLY|ue.O_NOFOLLOW),(await t.stat()).isFile()||Y(`The run input is not a regular file`);let r=oc.parse(JSON.parse(await t.readFile(`utf8`)));return(r.runId!==e||await qe(r.cwd)!==r.cwd)&&Y(`The recorded run or workspace identity changed`),r}catch(e){if(e instanceof z)throw e;return Y(`The private recorded run input is missing or invalid`)}finally{await t?.close()}}async function cc(e,t){await Je(O(e,`input.json`),JSON.stringify(t),{flag:`wx`,mode:384,flush:!0})}function lc(e,t,n,r,i={}){e.sourceDigest!==n&&Y(`The authored graph source changed`),t.cloud&&Y(`A local run cannot move to cloud execution`),Object.entries(r).some(([t,n])=>!Object.hasOwn(e.params,t)||oe(n)!==oe(e.params[t]))&&Y(`A recorded graph parameter changed`),Object.entries(i).some(([t,n])=>e.gateChoices?.[t]!==n)&&Y(`A recorded gate choice changed`),t.seat!==void 0&&t.seat!==e.seat&&Y(`The recorded graph seat override changed`)}const uc=`claude,codex,kimi,opencode,gemini,pi`;function dc(e,t){let n;return async(r,{node:i,lastCandidate:a})=>{t.throwIfAborted();let o;try{o=r===void 0?void 0:ce(r)}catch(e){throw e instanceof Error&&Object.assign(e,{node:i,seat:r,fixCommand:`tangle graph run --help`}),e}n??=Ye({cwd:e,signal:t,config:Xe({...process.env,BRIDGE_BACKENDS:uc,BRIDGE_SUBSCRIPTIONS_ONLY:`1`})});let s=await n;t.throwIfAborted();let c=e=>e.authentication?.status===`authenticated`&&e.authentication.authMode===`subscription`,l=o?.harness??s.find(e=>e.provider&&c(e))?.backend,u=s.filter(e=>e.backend===l),d=u.filter(c),f=o?u.find(e=>e.id===`${o.harness}/${o.model}`)??d.find(e=>e.provider===o.provider):d.find(e=>e.default)??d.find(e=>e.recommended)??d[0];if(!f||!c(f)){if(a===!1)return;let e=f?.authentication??u[0]?.authentication??(o?void 0:s.find(e=>e.authentication?.fix)?.authentication);throw Object.assign(new z(o?`SEAT_NOT_LOGGED_IN`:`SEAT_NONE_DETECTED`,`Node '${i}' has no available subscription${o?` for ${o.harness}`:``}`,e?`Selected provider: ${e.status} (${e.authMode})`:`No authenticated subscription route was detected`,e?.fix??`tangle graph run --help`),{node:i,seat:r})}let p=o?.harness??ce(f.id).harness,m=o?.provider??f.provider,h=o?.model??f.id.slice(p.length+1);if(!m||!h)throw new z(`MODEL_PROVIDER_MISMATCH`,`Node '${i}' has an unresolved model provider`,`Bridge has no configured provider for ${r??p}`,`tangle graph run --help`);return{harness:p,provider:m,model:h,selector:{kind:`all-eligible`},...o?.reasoningEffort===void 0?{}:{reasoningEffort:o.reasoningEffort}}}}function X(e){return Vr({signal:e.signal,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl}})}const fc=j.object({version:j.literal(1),type:j.enum([`state`,`ack`,`error`,`event`]),requestId:j.string().optional(),operationId:j.string().optional(),command:j.string().optional(),code:j.string().optional(),message:j.string().optional(),result:j.unknown().optional()}).passthrough(),pc=j.object({state:j.object({runConfiguration:j.unknown()}),view:j.object({capabilities:j.record(j.string(),j.object({available:j.boolean(),reason:j.string().optional()}))})}),mc=j.object({status:j.enum([`completed`,`failed`,`cancelled`]),analysis:j.object({id:j.string().min(1)}).passthrough(),source:j.object({runtimeRun:j.unknown()}).passthrough()}).passthrough(),hc=`TANGLE_GRAPH_ANALYSIS_SOURCE`;async function gc(e,t,n){if(!e.startsWith(`wfrun_`)){let t=O(await qe(O(k(),`.tangle`)),`runs`,e);if(await qe(t)!==t)throw new z(`RUN_NOT_FOUND`,`The run directory redirects elsewhere`,`Use the recorded local run directory`,`tangle graph inspect --help`);return{source:`runtime:${e}@${t}`,env:{},schema:j.object({runId:j.literal(e),runDir:j.literal(t)})}}let r={signal:n,...t.apiKey===void 0?{}:{apiKey:t.apiKey},...t.baseUrl===void 0?{}:{baseUrl:t.baseUrl}},i=await X(r),a=j.object({id:j.literal(e),workflowId:j.string(),revUsed:j.number().int(),execution:j.object({kind:j.literal(`graph`),sourceSha:j.string(),authoredGraphDigest:j.string(),graphDigest:j.string()}),runtime:j.object({snapshot:j.object({supervisors:j.tuple([j.object({id:j.string()})])})})}).parse(await i.workflows.getRun(e,{signal:n})),o=a.runtime.snapshot.supervisors[0];if(!o)throw new z(`BRAID_RPC_FAILED`,`The cloud run has no retained Runtime root`,`Wait for execution evidence before analysis`,`tangle graph inspect ${e}`);let s=await Lr(r);if(new URL(s.baseUrl.replace(/\/+$/,``)).href!==new URL(i.baseUrl.replace(/\/+$/,``)).href)throw new z(`AUTH_REQUIRED`,`The analysis source origin changed`,`Use the same authenticated platform origin`,`tangle auth status --json`);return{source:`runtime:${e}@${hc}`,env:{[hc]:JSON.stringify({url:`${s.baseUrl.replace(/\/+$/,``)}/v1/workflows/runs/${encodeURIComponent(e)}`,headers:{Authorization:`Bearer ${s.token}`}})},schema:j.object({runId:j.literal(e),remoteEndpointEnv:j.literal(hc),checkpoint:j.object({workflowId:j.literal(a.workflowId),runtimeRunId:j.literal(o.id),revUsed:j.literal(a.revUsed),sourceSha:j.literal(a.execution.sourceSha),authoredGraphDigest:j.literal(a.execution.authoredGraphDigest),graphDigest:j.literal(a.execution.graphDigest)})})}}async function _c(e,t){if(!e.startsWith(`wfrun_`)&&!j.uuid().safeParse(e).success)throw new z(`RUN_NOT_FOUND`,`Use a recorded graph run ID`,`The run identifier is invalid`,`tangle graph inspect --help`);if(!Number.isSafeInteger(t.timeout)||t.timeout<1)throw new z(`INVALID_TIMEOUT`,`Use a positive analysis timeout`,`The timeout must be an integer number of milliseconds`,`tangle graph analyze --help`);let n=t.profile;if(!n?.trim())throw new z(`USAGE_INVALID`,`Select the canonical analysis profile`,`Graph analysis requires an existing canonical AgentProfile reference`,`tangle graph analyze `+e+` --profile <name|path>`);let r=/^(?:\.\.?)[/\\]/.test(n)?xe(process.cwd(),n):n;return nc(t.signal,async n=>{let i=await gc(e,t,n),a=i.source;return Ol({signal:n,errorRunId:e},async n=>{let o=await n.bridge(),s=await We(O(n.runDir,`analysis-`)),c=O(s,`config.json`),l=O(s,`database.key`),u=O(s,`state.sqlite`),d=`connection-owned-graph-bridge`,f=new Date().toISOString();await Je(l,ne(32),{mode:384,flag:`wx`}),await Je(c,JSON.stringify({format:`braid-startup-config`,schemaVersion:2,profile:r,connectionId:d,connections:[{id:d,name:`Graph analysis`,kind:`cli-bridge`,endpoint:o.bridgeUrl,providerOptions:{transport:`local`},createdAt:f,updatedAt:f,lastHealth:{status:`unknown`}}]}),{mode:384,flag:`wx`});let p=n.signal,m=`op-${C()}`,h=`op-${C()}`,g=`${m}:initialize`,_=`${m}:analyze`,v=`${m}:shutdown`,ee={version:1,requestId:g,command:`initialize`,params:{workspace:n.cwd,subscribe:!1}},y={version:1,requestId:_,operationId:m,command:`analyze`,params:{source:a,recipe:`all`,totalTimeoutMs:t.timeout}},te={version:1,requestId:v,operationId:h,command:`shutdown`,params:{mode:`wait`}},b,x,S,re,w={transform:e=>{let t=fc.parse(e);return t.type===`error`||t.type===`state`&&t.requestId===g||t.type===`ack`&&[_,v].includes(t.requestId??``)?t:null},onError:e=>{re??=e},onEvent:e=>{e.type===`error`&&(re??=new z(e.code??`BRAID_RPC_FAILED`,`Braid refused graph analysis`,e.message??`The RPC response omitted its cause`,`tangle graph analyze --help`)),e.requestId===g&&e.type===`state`&&(b??=e),e.requestId===_&&e.type===`ack`&&(x??=e),e.requestId===v&&e.type===`ack`&&(S??=e)}},T=await Ve({command:process.env.BRAID_BIN??`braid`,args:[`rpc`,`--workspace`,n.cwd,`--config`,c,`--profile`,r,`--database-key-file`,l],cwd:n.cwd,env:{...i.env,BRAID_STATE_PATH:u,BRAID_CLI_BRIDGE_ENDPOINT:o.bridgeUrl,BRAID_CLI_BRIDGE_AUTH:o.bridgeBearer},timeoutMs:t.timeout,signal:p,ownProcessGroup:!0},w,{stdin:[ee,...t.dryRun?[]:[y],te].map(e=>JSON.stringify(e)).join(`
|
|
150
150
|
`)+`
|
|
151
|
-
`});if(re)throw re;let ie=T.exit;if(!ie.success||!b||!S||S.operationId!==h||S.command!==`shutdown`)throw new z(`BRAID_RPC_FAILED`,`Braid graph analysis did not finish`,ie.spawnError??ie.timeoutDiagnostic??ie.stdinError??ie.processGroupError??ie.captureError??ie.terminateError??(T.stderr||`Exit ${ie.code}, signal ${ie.signal}; complete shutdown acknowledgement: ${!!S}`),`npm install --global @tangle-network/braid`);let ae=pc.parse(b),oe=ae.view.capabilities[`analysis.recipe`];if(t.dryRun)return{source:a,statePath:u,configuration:ae.state.runConfiguration,capability:oe
|
|
151
|
+
`});if(re)throw re;let ie=T.exit;if(!ie.success||!b||!S||S.operationId!==h||S.command!==`shutdown`)throw new z(`BRAID_RPC_FAILED`,`Braid graph analysis did not finish`,ie.spawnError??ie.timeoutDiagnostic??ie.stdinError??ie.processGroupError??ie.captureError??ie.terminateError??(T.stderr||`Exit ${ie.code}, signal ${ie.signal}; complete shutdown acknowledgement: ${!!S}`),`npm install --global @tangle-network/braid`);let ae=pc.parse(b),oe=ae.view.capabilities[`analysis.recipe`];if(t.dryRun)return{source:a,statePath:u,configuration:ae.state.runConfiguration,capability:oe};if(!x||x.operationId!==m||x.command!==`analyze`)throw Error(`Braid did not acknowledge this analysis operation`);let se=mc.parse(x.result);if(!i.schema.safeParse(se.source.runtimeRun).success)throw new z(`BRAID_RPC_FAILED`,`Braid returned analysis of another source`,`Its saved run or immutable checkpoint identity does not match this request`,`tangle graph inspect ${e}`);return{...se,statePath:u}})},`tangle graph analyze ${e}`)}function vc(e){e.command(`analyze <run>`).description(`Analyze retained graph evidence through Braid`).addHelpText(`after`,`
|
|
152
152
|
Requires the Braid companion CLI: npm install --global @tangle-network/braid.
|
|
153
153
|
BRAID_BIN may select its installed executable. Select an existing canonical AgentProfile with --profile. Analysis uses the owned subscription-only Bridge.
|
|
154
154
|
`).requiredOption(`--profile <name|path>`,`Use a canonical analysis AgentProfile, distinct from the Tangle account profile`).option(`--dry-run`,`Inspect Braid's selected analysis configuration without dispatch`).option(`--timeout <ms>`,`Bound the analysis process in milliseconds`,Number,3e5).action(async(e,t)=>{let n=await _c(e,t);P(n),`status`in n&&n.status!==`completed`&&(process.exitCode=1)})}const yc=1e3;function bc(e,t){return[...t,e]}function xc(e,t=`input`,n){if(n===void 0&&!e?.length)return;let r={};if(n!==void 0)try{if(r=JSON.parse(pe(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 z(`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 Sc(e){N(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 Cc(e){if(R({"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){I(`Actions`);let t=e.actionResults.some(e=>e.nodeId!==void 0||e.visit!==void 0);N(e.actionResults.map(e=>({index:e.index,...t?{node:e.nodeId??``,visit:e.visit??``}:{},kind:e.kind,status:e.status,error:e.error??``,cost:e.costUsd??``})),[{key:`index`,header:`#`},...t?[{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&&(I(`Graph`),R({Nodes:e.graph.nodes.length,Edges:e.graph.edges.length,"Max node visits":e.graph.maxNodeVisits}),N(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&&(I(`Edge verdicts`),N(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 wc(e){if(e.status===`cancelled`){I(`Cancelled run ${e.runId}.`);return}if(e.signalled){I(`Cancelling run ${e.runId} — signalled the worker; it will stop shortly.`);return}I(`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 Tc(e){switch(e.type){case`snapshot`:I(`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 Ec(e){e.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.`,bc,[]).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(e,t)=>{let n=xc(t.input,`input`,t.inputFile),r=t.timeout===void 0?void 0:no(t.timeout,`--timeout`),i=t.pollInterval===void 0?void 0:no(t.pollInterval,`--poll-interval`),a=await X(t),{runId:o}=await a.workflows.run(e,n);if(!t.wait){if(t.json)return P({runId:o});I(`Started run ${o} for workflow ${e}.`),I(`Inspect it with: tangle workflows run-detail ${e} ${o}`);return}let s=t.json?null:L(`Waiting for run ${o} to finish...`).start(),c;try{c=await a.workflows.waitForRun(e,o,{...r===void 0?{}:{timeoutMs:r},...i===void 0?{}:{pollIntervalMs:i}})}finally{s?.stop()}if(c.status===`failed`&&(process.exitCode=1),t.json)return P(c);Cc(c)}),e.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(e,t)=>{let n=await X(t),r=t.limit===void 0?void 0:no(t.limit,`--limit`);if(t.all){let i=[],a=t.cursor,o=0,s=null;for(;;){let c=await n.workflows.listRuns(e,{...r===void 0?{}:{limit:r},...a===void 0?{}:{cursor:a}});if(i.push(...c.runs),o+=1,!c.nextCursor)break;if(o>=yc){s=c.nextCursor,t.json||I(`Stopped after ${yc} pages (${i.length} runs); more may exist — resume with --cursor ${c.nextCursor}`);break}a=c.nextCursor}if(t.json)return P({runs:i,nextCursor:s});Sc(i);return}let i=await n.workflows.listRuns(e,{...r===void 0?{}:{limit:r},...t.cursor===void 0?{}:{cursor:t.cursor}});if(t.json)return P(i);Sc(i.runs),i.nextCursor&&I(`More runs available — next page: --cursor ${i.nextCursor}`)}),e.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(e,t,n)=>{let r=await(await X(n)).workflows.getRun(e,t);if(n.json)return P(r);Cc(r)}),e.command(`cancel`).description(`Cancel a queued or in-progress run`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(e,t,n)=>{let r=await(await X(n)).workflows.cancel(e,t);if(n.json)return P(r);wc(r)}),e.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(e,t,n)=>{let r=n.timeout===void 0?void 0:no(n.timeout,`--timeout`),i=n.pollInterval===void 0?void 0:no(n.pollInterval,`--poll-interval`),a=await X(n),o=await a.workflows.retryRun(e,t);if(!n.wait){if(n.json)return P(o);I(`Started run ${o.runId} (retry of ${t}).`),I(`Inspect it with: tangle workflows run-detail ${e} ${o.runId}`);return}let s=n.json?null:L(`Waiting for run ${o.runId} to finish...`).start(),c;try{c=await a.workflows.waitForRun(e,o.runId,{...r===void 0?{}:{timeoutMs:r},...i===void 0?{}:{pollIntervalMs:i}})}finally{s?.stop()}if(c.status===`failed`&&(process.exitCode=1),n.json)return P(c);Cc(c)}),e.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 X(n);for await(let i of r.workflows.watchRun(e,t))n.json?console.log(JSON.stringify(i)):Tc(i),i.type===`run.done`&&i.status===`failed`&&(process.exitCode=1)})}async function Dc(e,t,n,r){let i=await X({...n,signal:r}),a=Tl(t),o=xc(n.param,`param`),s={name:ge(e).replace(/(\.graph)?\.(yaml|yml|json)$/i,``),...o?{params:o}:{},...n.seat?{seat:n.seat}:{}},c,l;if(n.resume){let e=await i.workflows.getRun(n.resume,{signal:r});e.id!==n.resume&&Y(`The cloud owner returned another run identity`);let t=e.execution;if((t?.kind!==`graph`||t.sourceSha!==a)&&Y(`The authored cloud graph source changed`),Object.entries(o??{}).some(([e,n])=>!Object.hasOwn(t.params,e)||oe(t.params[e])!==oe(n))&&Y(`A recorded cloud graph parameter changed`),n.seat!==void 0&&n.seat!==t.deploy.seat&&Y(`The recorded cloud seat override changed`),n.dryRun)return{run:e};if((e.status===`cancelled`||e.status===`failed`)&&Y(`The cloud run is terminal: ${e.status}`),e.status===`succeeded`)return e.graphResult||Y(`The settled cloud run has no retained Runtime result`),{workflowId:e.workflowId,runId:e.id,sourceDigest:a,result:e.graphResult,replayed:!0,viewerUrl:`${i.baseUrl}/app/workflows/${encodeURIComponent(e.workflowId)}/runs/${encodeURIComponent(e.id)}`};if(e.recovery?.state===`running`)return{workflowId:e.workflowId,runId:e.id,sourceDigest:a,run:e,attached:!0,viewerUrl:`${i.baseUrl}/app/workflows/${encodeURIComponent(e.workflowId)}/runs/${encodeURIComponent(e.id)}`};e.recovery?.state!==`queued`&&e.recovery?.state!==`recoverable`&&Y(`The owner has not confirmed recovery eligibility`),c=e.workflowId,l=e.revUsed??Y(`The captured cloud revision is unavailable`)}else{if(n.dryRun)return i.workflows.validate(t,{format:`graph`,deploy:s});let e=await i.workflows.create(t,{format:`graph`,deploy:s});c=e.id,l=e.headRev??Y(`The cloud workflow has no retained revision`)}r.throwIfAborted();let u=await i.workflows.run(c,void 0,{signal:r,sourceSha:a,expectedRev:l,...n.resume?{resumeRunId:n.resume}:{}});return n.resume&&u.runId!==n.resume&&Y(`The cloud owner recovered another run identity`),{...u,workflowId:c,sourceDigest:a,viewerUrl:`${i.baseUrl}/app/workflows/${encodeURIComponent(c)}/runs/${encodeURIComponent(u.runId)}`}}const Oc=1e5;function Z(e){throw new z(`GRAPH_INVALID`,`Graph creation failed`,e,`tangle graph new --help`)}function kc(e){return typeof e==`string`&&/^[a-z0-9][a-z0-9-]{0,62}$/i.test(e)}const Ac={maxBarren:2,failures:`verbatim`,panel:`off`,bar:`on`,profile:{id:`graph-new-v1`,opening:`The graph has not passed its outside check.`,plan:`Repair the concrete diagnostics with write_graph, run the saved file and submit the actual evidence.`,rules:`Completion requires a successful host run and unchanged YAML. Retain working graph content when blocked.`,headings:{failures:`Failures`,protected:`Passing checks`,changed:`Changes`,findings:`Findings`,bar:`Acceptance`,plan:`Next`,rules:`Rules`}}};var jc=class{owned;lastFailure;pending=Promise.resolve();revision=0;sealed=!1;constructor(e,t,n){this.directory=e,this.options=t,this.cwd=n}async digest(e=this.owned){e||Z(`No graph file was saved`);let t=await Ge(e.file,ue.O_RDONLY|ue.O_NOFOLLOW);try{let[n,r]=await Promise.all([t.stat(),e.handle.stat()]);return(!n.isFile()||n.dev!==r.dev||n.ino!==r.ino)&&Z(`The owned graph file was replaced`),Tl(await t.readFile())}finally{await t.close()}}enqueue(e){let t=++this.revision,n=this.pending.then(()=>e(t));return this.pending=n.then(()=>void 0,()=>void 0),n}check=()=>this.enqueue(async e=>{let t=this.owned;if(!t?.result)return!1;let{digest:n,result:r}=t,i=await this.digest(t),a=this.revision===e&&this.owned===t&&t.digest===n&&t.result===r&&i===n;return a&&(this.sealed=!0),a});receipt(){this.owned?.result||Z(`No successful graph run was recorded`);let{file:e,digest:t,result:n}=this.owned;return{file:e,digest:t,result:n}}invoke(e,t){return this.sealed&&Z(`The graph is accepted; submit its recorded successful run`),this.enqueue(()=>this.write(e,t)).catch(e=>(this.lastFailure=e,{ok:!1,diagnostic:Zt(e)}))}async write(e,t){t.throwIfAborted(),this.lastFailure=void 0;let n=e;(!n||!kc(n.name)||typeof n.source!=`string`||typeof n.run!=`boolean`||Object.keys(n).some(e=>![`name`,`source`,`run`].includes(e)))&&Z(`Expected only name, source and boolean run`),this.options.name!==void 0&&n.name!==this.options.name&&Z(`The graph name must match --name`),this.owned&&(this.owned.result=void 0);let r=O(this.directory,`${n.name}.yaml`);if(this.owned&&this.owned.file!==r&&Z(`This invocation owns one named graph file`),!this.owned)try{this.owned={file:r,handle:await Ge(r,ue.O_RDWR|ue.O_CREAT|ue.O_EXCL|ue.O_NOFOLLOW,384),digest:Tl(``)}}catch(e){throw e.code===`EEXIST`&&Z(`Graph already exists: ${r}; choose another --name`),e}let i=this.owned;await this.digest()!==i.digest&&Z(`The owned graph was changed`);let a=Buffer.from(n.source);for(let e=0;e<a.length;){let{bytesWritten:t}=await i.handle.write(a,e,a.length-e,e);if(!t)throw Error(`Graph file write made no progress`);e+=t}await i.handle.truncate(a.length),await i.handle.sync(),i.digest=Tl(a);let o={...this.options,param:[]},s={cwd:this.cwd,signal:t,source:n.source},c=await kl(r,{...o,dryRun:!0},{...s,connectNeeds:!0});`graph`in c||Z(`No canonical graph was returned`),c.graph.deliverable.checkRef===`command`&&Z(`Host command checks need a jailed verifier node`);let{nodes:l,edges:u,budget:d}=c.graph,f=u.reduce((e,t)=>e+(`maxTraversals`in t?(t.maxTraversals??1)-1:0),l.length),p=(f+1)*Oc;if(d?.maxTokens!==void 0&&d.maxTokens<p&&Z(`budget.maxTokens ${d.maxTokens} is below ${p}: ${f} agent spawns plus one reservation at ${Oc} tokens per native turn`),await this.digest()!==i.digest&&Z(`Graph changed during validation`),!n.run)return{file:r,graphDigest:c.graph.digest,validated:!0};let m=await kl(r,o,{...s,graphDigest:c.graph.digest});return(!(`status`in m)||m.status!==`winner`||m.graphDigest!==c.graph.digest||await this.digest()!==i.digest)&&Z(`The graph must succeed with unchanged YAML`),i.result=m,this.receipt()}async close(){await this.pending,await this.owned?.handle.close()}};async function Mc(e,t,n){let{runId:r,runDir:i,cwd:a,bridge:o,signal:s}=e,c=await o(),l=O(await qe(O(k(),`.tangle`)),`graphs`);(El(a,l)||El(l,a))&&Z(`The graph store must be outside the agent workspace; choose another working directory`);try{await Ue(l,{mode:448})}catch(e){if(e.code!==`EEXIST`)throw e}await qe(l)!==l&&Z(`The graph store redirects outside its canonical location`);let u=n.seat??Hn().seat,d=await dc(a,s)(u,{node:`graph-designer`,cwd:a,signal:s,lastCandidate:!0});d||Z(`No authenticated native subscription is available`);let{graphDesignerProfile:f}=await import(`@tangle-network/agent-runtime/profiles`),{supervisePursuit:p}=await import(`@tangle-network/agent-runtime/durable`),m=f({profile:{name:`graph-designer`,harness:d.harness,model:{provider:d.provider,default:d.model,...d.reasoningEffort===void 0?{}:{reasoningEffort:d.reasoningEffort}},prompt:{instructions:[`You are the sole graph designer. Author a canonical YAML graph for the requested intent, then qualify and run it using write_graph. Its nodes are complete AgentProfiles with a real independent verifier and declarative route/data outside check. Command checks execute on the host and are refused here; put executable verification in the verifier node's normal native tools. Read the supplied skills and preserve the user's task and authority.`,`Call write_graph with name, complete YAML source and run:false to validate; repair its concrete diagnostics, then call it with the identical source and run:true. The graph schema and executor are owned by the installed loader. Supply defaults for parameters needed by the first run. Only a real successful host run of the unchanged saved file passes. Submit that evidence using submit_result; explain concrete blockers using report_blocked.`]},tools:{agent_runtime_coordination_write_graph:!0,agent_runtime_coordination_submit_result:!0,agent_runtime_coordination_read_continuation:!0,agent_runtime_coordination_report_blocked:!0}}}),h=ae(m),g=new jc(l,{...n,seat:u},a),_={maxIterations:6,maxTokens:2e6,deadlineMs:9e5};try{let e=await p(m,{intent:t,name:n.name},{pursuitId:r,runId:r,runDir:i,signal:s,backend:{...c,timeoutMs:_.deadlineMs},budget:_,maxDepth:0,coordination:{authentication:!0,requestTimeoutMs:_.deadlineMs},deliverable:{describe:`The saved graph succeeds with unchanged YAML`,check:g.check,checkState:g.check},continuation:Ac,resolveSupervisorTools:e=>e.runId!==r||e.nodeId!==r||e.depth!==0||e.identity.profileDigest!==h?[]:[{name:`write_graph`,description:`Save, validate and run this graph.`,inputSchema:{type:`object`,properties:{name:{type:`string`},source:{type:`string`},run:{type:`boolean`}},required:[`name`,`source`,`run`],additionalProperties:!1},handler:(t,n)=>((n.nodeId!==e.nodeId||n.ownerId!==e.ownerId||n.runId!==e.runId)&&Z(`Wrong graph tool owner`),g.invoke(t,n.signal))}]});if(e.result.kind===`no-winner`||!await g.check()){if(g.lastFailure)throw g.lastFailure;let t=e.result.kind===`no-winner`?e.result.error?.message??e.result.reason:`The graph file changed after its successful run`;throw Object.assign(new z(`GRAPH_DESIGN_FAILED`,`Graph design did not finish`,t,`tangle graph new --help`),{runId:r,node:`graph-designer`})}return g.receipt()}finally{await g.close()}}function Nc(e){e.command(`new <intent>`).description(`Design, validate and run one portable graph`).option(`--seat <seat>`,`Use harness/model@effort for the designer and graph`).option(`--name <name>`,`Save this graph name`).action(async(e,t)=>{process.env.BRIDGE_JAIL_RW_PATHS?.trim()&&Z(`Remove BRIDGE_JAIL_RW_PATHS before graph new; extra native write roots cannot contain its host store`),t.name!==void 0&&!kc(t.name)&&Z(`Use letters, numbers and hyphens in --name`);let n=await Ol({},n=>Mc(n,e,t));t.json?P(n):I(`Created ${n.file} · run ${n.result.runId}`)})}const Pc=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).map(String),Fc=(e=``)=>{let t=e.replace(/\s+/g,` `).trim(),n=t.match(/^.+?[.!?](?=\s|$)/)?.[0]??t;return n.length>90?`${n.slice(0,89)}…`:n},Ic=e=>e&&(e.all??[e]).map(e=>{let t=`equals`in e?`= ${JSON.stringify(e.equals)}`:`in`in e?`∈ ${JSON.stringify(e.in)}`:e.exists===!1?`absent`:`exists`;return`${e.node??``}${e.pointer||`/`} ${t}`}).join(` and `);function Lc(e,t){try{let n=tt(t,{uniqueKeys:!0,strict:!0}),r=[...n.errors,...n.warnings][0];if(r)throw r;let i=ve(e)===`.json`?JSON.parse(t):n.toJS();if(Array.isArray(i?.nodes)&&Array.isArray(i.edges))return i;throw Error(`A graph needs nodes and edges lists`)}catch(t){throw new z(`GRAPH_INVALID`,`Graph file ${e} cannot be read`,t.message,`tangle graph show --help`)}}function Rc(e,t){let n=Lc(e,t),r=e=>{let t=String(e).match(/^\$\{params\.([\w-]+)\}$/)?.[1];return t?`${n.params?.[t]?.default??`?`} (params.${t})`:e},i=n.nodes.map(e=>{if(e.check){let t=String(e.check.command??``),n=t.match(RegExp(`#\\s*${e.id}:\\s*(.+)`))?.[1],r=t.split(`
|
|
@@ -159,7 +159,7 @@ BRAID_BIN may select its installed executable. Select an existing canonical Agen
|
|
|
159
159
|
<meta name="description" content="${(e.describe??o).replace(/[&<>"]/g,``)}">
|
|
160
160
|
<style>${i}html,body,#root{margin:0;height:100%;font-family:ui-sans-serif,system-ui,sans-serif}</style></head>
|
|
161
161
|
<body><div id="root"></div><script id="graph" type="application/json">${JSON.stringify(e).replace(/</g,`\\u003c`)}<\/script>
|
|
162
|
-
<script>${a(r)}<\/script></body></html>`,c=O(await We(O(we(),`tangle-graph-`)),`${o}.html`);return await Je(c,s,{mode:384}),c}function Hc(e,t,n){e.command(`show <name-or-file>`).description(`Draw a graph file: labelled nodes, routes, loops and stops`).option(`--open`,`Write one offline page and open it in the browser`).action(async(e,r)=>{let i=await qe(t(e,process.cwd())),a=Rc(i,await Ke(i,`utf8`));if(r.json)return P(a);if(!r.open)return console.log(Bc(a));let o=await Vc(a,n);I(await Ti(Qe(o).href)?`Opened ${o}`:`Open ${o}`)})}async function Uc(e){if(!rr(e.apiKey)){if(e.json||e.dryRun||!process.stdin.isTTY)return;await Pi({baseUrl:e.sandboxBaseUrl,signal:e.signal})}return G(e)}async function Wc(e,t,n){let r=cl(t.parameter),i=n??await Uc(t);if(!i)throw new z(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured`,`tangle auth login`);let a=await i.connections.start(e,{cli:!0,connectionParameters:r});return t.json?(P(ul(a)),a):(ll(a,t.browser===!1?!1:await Ti(a.redirectUrl),t.wait),a)}async function Gc(e,t,n){let r=async()=>{n.signal?.throwIfAborted();let{connections:r}=await e.connections.list(),i=r.filter(e=>e.status===`active`&&e.providerId.toLowerCase()===t.trim().toLowerCase());return i.length?Cr(i,t):void 0},i=await r();if(i||n.json||n.dryRun||!process.stdin.isTTY)return i;let a=await Wc(t,{...n,wait:!0},e);for(;!i&&Date.now()<Date.parse(a.expiresAt);)await Ne(1e3,void 0,{signal:n.signal}),i=await r();return i}function Kc(){let e=new b(`hub`).description(`Discover and run Tangle Hub tools`);e.command(`connect`).description(`Connect a provider account`).argument(`provider`,`Provider to connect`).option(`--no-browser`,`Print the authorization URL instead of opening it`).option(`--parameter <key=value>`,`Provider-specific OAuth value. Repeatable.`,(e,t)=>[...t,e],[]).action(async(e,t)=>{await Wc(e,t)});let t=new b(`connections`).description(`List Hub provider connections`).action(async e=>{let t=await(await G(e)).connections.list();if(e.json){P(t);return}sl(t.connections)});t.command(`revoke <connection-id>`).description(`Revoke a Hub provider connection`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await G(t),r=await Sr(n,e);if(!t.force&&!await $r(`Revoke Hub connection ${r}? `,`--force`)){I(`Revoke cancelled.`);return}let i=await n.connections.revoke(r);if(t.json){P(i);return}I(`Revoked Hub connection ${i.connection.id}.`)}),e.addCommand(t);let n=new b(`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 e=>{if(!e.connection)throw Error(`--connection is required.`);let t=await G(e),n=await Sr(t,e.connection),r=await t.permissions.list(n);if(e.json){P(r);return}nl(r.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 e=>{if(!e.connection)throw Error(`--connection is required.`);if(!e.action)throw Error(`--action is required.`);let t=rl(e.decision),n=await G(e),r=await Sr(n,e.connection),i=await n.permissions.set({connectionId:r,actionPath:e.action,decision:t});if(e.json){P(i);return}nl([i.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 e=>{if(!e.connection)throw Error(`--connection is required.`);let t=await G(e),n=await Sr(t,e.connection),r=await t.permissions.revertWrites(n);if(e.json){P(r);return}I(`Reverted ${r.reverted} write permission${r.reverted===1?``:`s`} for connection ${r.connectionId}.`)}),e.addCommand(n),e.addCommand(Jc());let r=new b(`tools`).description(`Discover Hub tools`);return r.command(`sources`).description(`List Hub tool sources`).action(async e=>{let t=await(await G(e)).tools.sources();if(e.json){P(t);return}il(t.sources)}),r.command(`describe`).description(`Describe a Hub tool`).argument(`path`,`Executor tool path`).action(async(e,t)=>{let n=await(await G(t)).tools.describe(e);if(t.json){P(n);return}al(n.tool)}),r.command(`search`).description(`Search Hub tools`).argument(`<query...>`,`Search query`).option(`--provider <provider>`,`Filter by provider/source ID`).action(async(e,t)=>{let n=await(await G(t)).tools.search(e.join(` `),{provider:t.provider});if(t.json){P(n);return}tl(n.tools)}),e.addCommand(r),e.addCommand(qc(`call`)),e.addCommand(qc(`exec`)),e.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(Xc(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 G(t);Qc(t.decline?await n.approvals.deny(e):await n.approvals.approve(e),t.json===!0)}),e.command(`status`).description(`Show Hub auth and connection status`).action(async e=>{let t=await(await G(e)).status();if(e.json){P(t);return}dl(t)}),e}function qc(e){return new b(e).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(e,t)=>{let{args:n,approve:r}=Yc(e,t),{path:i,input:a}=el(n),o=await G(t),s=t.connection?await Sr(o,t.connection):void 0;P((await o.tools.invoke(i,a,{connectionId:s,approve:r})).result)})}function Jc(){let e=new b(`approvals`).description(`List and resolve Hub execution approvals`);e.command(`list`).description(`List pending Hub execution approvals`).action(async e=>{let t=await(await G(e)).approvals.list();if(e.json){P(t);return}Zc(t.approvals)});for(let t of[`approve`,`deny`])e.command(t).description(`${t===`approve`?`Approve`:`Deny`} a pending Hub execution approval`).argument(`approval-id`,`Hub approval ID`).action(async(e,n)=>{Xc(e),Qc(await(await G(n)).approvals[t](e),n.json===!0)});return e}function Yc(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 Xc(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`Hub approval ID must contain only letters, numbers, underscores, and dashes.`)}function Zc(e){N(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 Qc(e,t){if(t){P($c(e));return}I(`Hub approval ${e.approval.id} ${e.approval.status}.`),e.capabilityToken&&I("Capability token minted. Re-run the original command with `--approve` to execute automatically.")}function $c(e){return{approval:e.approval,...e.capabilityToken?{capabilityToken:{tokenId:e.capabilityToken.tokenId,expiresAt:e.capabilityToken.expiresAt}}:{}}}function el(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 tl(e){N(e.map(e=>({...e,provider:e.providerId??e.requiredConnectionProviderId,connection:ol(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 nl(e){N(e,[{key:`connectionId`,header:`Connection`},{key:`providerId`,header:`Provider`},{key:`actionPath`,header:`Action`},{key:`decision`,header:`Decision`},{key:`updatedAt`,header:`Updated`}])}function rl(e){if(e===`allow`||e===`ask`||e===`deny`)return e;throw Error(`--decision must be one of: allow, ask, deny.`)}function il(e){N(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 al(e){R({Path:e.path,Provider:e.providerId??e.requiredConnectionProviderId,Title:e.title,Description:e.description,Connection:ol(e),Policy:e.policyState}),e.inputSchema!==void 0&&(I(`Input schema`),console.log(JSON.stringify(e.inputSchema,null,2))),e.outputSchema!==void 0&&(I(`Output schema`),console.log(JSON.stringify(e.outputSchema,null,2)))}function ol(e){if(e.connectionRequired===!1)return`not required`;if(e.connectionStatus)return e.connectionStatus}function sl(e){N(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 cl(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 ll(e,t,n=!1){t?I(`Opened browser to connect ${e.provider}.`):(I(`Open this URL to connect ${e.provider}:`),console.log(e.redirectUrl)),I(n?`Finish authorization in the browser; this run resumes when connected.`:"Finish authorization in the browser, then rerun `tangle hub status`.")}function ul(e){return{provider:e.provider,redirectUrl:e.redirectUrl,expiresAt:e.expiresAt,scopes:e.scopes,cli:e.cli}}function dl(e){let{principal:t,connections:n}=e;I(`Hub status`),R({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&&I(`Some providers require reconnect.`)}const fl=[`claude-code`,`opencode`,`codex`,`kimi-code`,`prime`],pl=process.env.TANGLE_ROUTER_URL??`https://router.tangle.tools/v1`;function ml(e){let t=se(e);if(t)return t;throw Error(`--model '${e}' has no provider. Pass a canonical id, for example 'google/${e}'.`)}function hl(e){let t=e.harness??`claude-code`;if(!fl.includes(t))throw Error(`Unknown --harness '${t}'. Supported: ${fl.join(`, `)}.`);let n=gl(e.maxTokens,2e5,`--max-tokens`),r=gl(e.maxIterations,50,`--max-iterations`),i=e.maxWorkers===void 0?void 0:gl(e.maxWorkers,0,`--max-workers`);return{harness:t,...e.model?{model:e.model}:{},maxTokens:n,maxIterations:r,...i===void 0?{}:{maxWorkers:i}}}function gl(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 _l(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 vl(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 yl=null;function bl(){return yl??=import(`@tangle-network/agent-runtime/kernel`).catch(e=>{throw yl=null,e?.code===`ERR_MODULE_NOT_FOUND`?new z(`RUNTIME_UNAVAILABLE`,`Agent Runtime could not be loaded`,e.message,`npm install -g @tangle-network/sandbox-cli@latest`):e}),yl}async function xl(e,t,n){let r=H({apiKey:n.apiKey,baseUrl:n.baseUrl}),i=U(r),{budget:a,perWorker:o}=_l(t),s=[],c={async create(e){let{TANGLE_API_KEY:t,...r}=e?.env??{},a=await i.create(e?.env?{...e,env:r}:e);return s.push({id:a.id,status:`spawned`}),n.json||I(`worker ${a.id} spawned`),a}},l=await bl(),u=l.workerFromBackend({backend:`sandbox`,sandboxClient:c,maxIterations:1}),d=(e,n)=>u({...e,harness:t.harness},n),f={name:`supervisor`,harness:`cli-base`,model:{default:t.model??`gemini-2.5-flash-lite`,provider:t.model?ml(t.model):`google`},tools:{agent_runtime_coordination_spawn_worker:!0,agent_runtime_coordination_observe_agent:!0}},p={routerBaseUrl:pl,routerKey:r.apiKey},m=vl(await l.supervise(f,{goal:e},{budget:a,makeWorkerAgent:d,router:p,...o?{perWorker:o}:{},...t.model?{allowedModels:[t.model]}:{},runId:`supervise-${C()}`})),h=m.status===`winner`?`settled`:`failed`;for(let e of s)e.status=h,n.json||I(`worker ${e.id} settled (${e.status})`);return{task:e,result:m.text,workers:s,tokenUsage:m.tokenUsage,costUsd:m.costUsd,status:m.status}}function Sl(){let e=new b(`supervise`);return e.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 (${fl.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(e,t)=>{let n=hl({harness:t.harness,model:t.model,maxTokens:t.maxTokens,maxIterations:t.maxIterations,maxWorkers:t.maxWorkers});t.json||(I(`Supervising: ${e}`),I(`harness=${n.harness} budget=${n.maxTokens}tok/${n.maxIterations}it`),console.log());let r=await xl(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,json:t.json});if(t.json){P(r),r.status!==`winner`&&(process.exitCode=1);return}if(console.log(),r.result&&(console.log(r.result),console.log()),R({"Input Tokens":r.tokenUsage.input??`Unavailable`,"Output Tokens":r.tokenUsage.output??`Unavailable`,Cost:r.costUsd===null?`Unavailable`:`$${r.costUsd.toFixed(4)}`}),r.status!==`winner`)throw Error(`Supervisor finished without a winner: ${r.status}`)}),e}const Cl=t(import.meta.url);if(!Cl)throw Error(`Tangle CLI package metadata was not found`);const wl=_e(Cl),Tl=e=>S(`sha256`).update(e).digest(`hex`);function El(e,t){let n=be(e,t);return n!==`..`&&!n.startsWith(`..${Se}`)&&!ye(n)}function Dl(e,t){if(/[\\/]/.test(e)||/\.(yaml|yml|json)$/.test(e))return xe(t,e);let n=t;for(;!de(O(n,`.git`))&&_e(n)!==n;)n=_e(n);de(O(n,`.git`))||(n=t);let r=[`yaml`,`yml`,`json`].flatMap(e=>[`graph.${e}`,e]),i=[n,k()].flatMap(t=>r.map(n=>O(t,`.tangle/graphs/${e}.${n}`))),a=i.find(de);if(a)return a;throw new z(`GRAPH_NOT_FOUND`,`Graph '${e}' was not found`,`Looked in ${i.join(`, `)}`,`tangle graph --help`)}async function Ol(e,t){return nc(e.signal,async n=>{let r=e.runId??C(),i;try{let a=O(k(),`.tangle`,`runs`,r);await Ue(a,{recursive:!0,mode:448});let o=await qe(O(k(),`.tangle`)),s=await qe(e.cwd??process.cwd()),c=[`runs`,`graph-registry`,`graphs`].some(e=>El(s,O(o,e))||El(O(o,e),s))?O(k(),`.tangle`,`workspaces`,r):s;await Ue(c,{recursive:!0,mode:448});let l;return await t({runId:r,runDir:a,cwd:c,bridge:e=>l??=(async()=>{n.throwIfAborted();let t=ne(32).toString(`hex`),{loadConfig:r,startServer:o}=await import(`cli-bridge`),s=O(wl,`dist`,`stdio.mjs`),l=r({...process.env,BRIDGE_HOST:`127.0.0.1`,BRIDGE_PORT:`3344`,BRIDGE_BEARER:t,BRIDGE_DATA_DIR:O(a,`bridge`),BRIDGE_BACKENDS:uc,BRIDGE_JAIL_MODE:`fs-jail`,BRIDGE_JAIL_FALLBACK:`deny`,BRIDGE_SUBSCRIPTIONS_ONLY:`1`});e&&l.jailReadablePaths.push(s),i=await o({cwd:c,config:{...l,port:0},handleSignals:!1,quiet:!0,hub:e?{client:e,hash:tc,serverForGrant:e=>{if(!i)throw Error(`Hub host is not ready`);return{transport:`stdio`,command:process.execPath,args:[{kind:`public`,value:s}],env:{TANGLE_HUB_MCP_ENDPOINT:{kind:`public`,value:`${i.url}/hub/mcp/grants/${e}`}}}}}:void 0});let{graphNativeCapture:u}=await import(`./graph-native-af-gs1TS.mjs`);return{harnessTranscript:u({bridgeUrl:i.url,bridgeBearer:t,cwd:c}),backend:`bridge`,bridgeUrl:i.url,bridgeBearer:t,cwd:c}})(),signal:n})}catch(t){throw t instanceof Error&&Object.assign(t,{runId:e.errorRunId??r}),t}finally{await i?.close()}},e.fix??`tangle graph --help`)}async function kl(e,t,n={}){let r=[`tangle graph run`,He(e),...t.dryRun?[`--dry-run`]:[],...t.cloud?[`--cloud`]:[],...t.resume?[`--resume`,He(t.resume)]:[],...t.seat?[`--seat`,He(t.seat)]:[],...t.param.flatMap(e=>[`--param`,He(e)])].join(` `);return await nc(n.signal,async i=>{i.throwIfAborted();let a=await qe(Dl(e,n.cwd??process.cwd())),o=n.source??await Ke(a,`utf8`);if(!t.resume&&t.cloud||t.resume?.startsWith(`wfrun_`))return Dc(a,o,t,i);let s=await bl(),c=Tl(o),l=Object.entries(xc(t.param,`param`)??{}),u=Object.fromEntries(l.filter(([e])=>!e.startsWith(`gate.`))),d=Object.fromEntries(l.filter(([e])=>e.startsWith(`gate.`)).map(([e,t])=>[e.slice(5),t])),f=t.resume?await sc(t.resume):void 0,p=s.graphRegistry(O(k(),`.tangle`,`graph-registry`)),m;if(f){f.file!==a&&Y(`The recorded graph source path changed`);let e=await s.loadGraph(p,f.graphDigest);e||Y(`The recorded executable graph is unavailable`),m=s.validateStoredGraph(e),lc(f,t,c,u,d)}let h={apiKey:t.apiKey,sandboxBaseUrl:t.baseUrl,signal:i,json:t.json,dryRun:t.dryRun&&!n.connectNeeds},g,_=()=>g??=Uc(h),v=new Map,ee=e=>{let t=e.trim().toLowerCase(),n=v.get(t)??(async()=>{let e=await _(),n=e&&await Gc(e,t,h);return n?{connectionId:n,capabilities:[`*`]}:void 0})();return v.set(t,n),n},y=async e=>{if(i.throwIfAborted(),f&&m)return rc(m,f.gateChoices??{}),{graph:m,params:f.params};let r=await s.loadGraphFile(a,{source:o,seat:t.seat??Hn().seat,resolveSeat:dc(e,i),resolveNeed:ee,params:u,cwd:e,signal:i});if(i.throwIfAborted(),rc(r.graph,d),n.graphDigest&&r.graph.digest!==n.graphDigest)throw new z(`GRAPH_CHANGED`,`The validated graph changed before execution`,`Its compiled graph digest no longer matches validation`,`tangle graph run --help`);return r},te=n.cwd??process.cwd(),b=await y(f?.cwd??te);if(t.dryRun)return b;let x=f?.runId??n.runId??C(),S=f?.cwd??await s.graphWorkspace(b.graph,{cwd:te,runId:x});return Ol({...n,runId:x,cwd:S,signal:i,fix:r},async({runId:e,runDir:n,cwd:r,bridge:o})=>{let{superviseGraphPursuit:l,readSettleRecord:u}=await import(`@tangle-network/agent-runtime/durable`),m=await s.recordStoredGraphRun(p,b.graph),h=f??{version:1,runId:e,cwd:r,file:a,graphDigest:m.digest,sourceDigest:c,params:b.params,...Object.keys(d).length?{gateChoices:d}:{},startedAt:new Date().toISOString(),...t.seat===void 0?{}:{seat:t.seat}};f||await cc(n,h);let g=f?await u(n):void 0;if(g&&g.tree.root!==e&&Y(`The settlement names another run`),g?.kind===`no-winner`&&Y(`The local run is terminal: ${g.reason}`),g)return{runId:e,graphDigest:m.digest,sourceDigest:c,...vl(g),replayed:!0};let v=s.graphFromStored(m),ee=m.nodes.some(e=>e.profile.connections?.length),y=ee?await _():void 0;if(ee&&!y)throw new z(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured for this local graph`,`tangle auth login`);let te=await o(y),x=h.startedAt;I(`Run ${e} · ${ge(a)} · ${r}`);let S=await Al(n);I(`Viewer ${S.url}`);let ne=new AbortController,C=await l(v,{pursuitId:m.digest,runDir:n,runId:e,backend:te,...v.entry===void 0?{driverBackend:te}:{},...m.gates?.length?{decideGate:ic(h.gateChoices??{},{json:t.json,signal:AbortSignal.any([i,ne.signal])})}:{},resume:!!f,signal:i,profileSecurity:{allowConnections:ee,allowLocalMcp:!1,allowHooks:!1,allowedMcpHosts:[]}}).finally(async()=>{ne.abort(),await S.close()}),re={runId:e,graphDigest:m.digest,sourceDigest:c,...vl(C.result.result)},w=C.result.result,{tokens:T,tokensKnown:ie,iterations:ae,ms:oe}=w.spentTotal;if(await s.recordStoredGraphRun(p,m,{graphDigest:m.digest,evidence:[{kind:`authored-graph`,url:`urn:sha256:${m.digest}`},{kind:`authored-yaml`,url:`urn:sha256:${c}`}],taskDigest:s.taskShapeDigest({graph:ge(a),params:b.params}),startedAt:x,finishedAt:new Date().toISOString(),outcome:w.kind===`no-winner`?{kind:`no-winner`,reason:w.reason}:{kind:`delivered`,summary:re.text},cost:{iterations:ae,ms:oe,...ie===!1?{}:{tokens:T.input+T.output},...re.costUsd===null?{}:{usd:re.costUsd}},traversals:C.result.ledger.length,exhaustedEdges:C.result.exhaustedEdges,source:{kind:`tangle-cli-graph`,id:e}}),w.kind===`no-winner`)throw Object.assign(new z(`GRAPH_RUN_FAILED`,`Graph '${ge(a)}' finished without a result`,C.result.stopped?.reason||C.result.ledger.filter(e=>e.outcome===`unpropagated`&&e.reason).pop()?.reason||w.reason,`tangle graph inspect ${e}`),{runId:e,runtimeFailures:[...w.tree.nodes.filter(e=>e.failure).map(e=>({node:e.label,failure:e.failure})),...w.reason===`driver-failed`&&w.error.failure?[{node:`root`,failure:w.error.failure}]:[]]});return re})},r)}async function Al(e){let{serveTopWeb:t}=await import(`@tangle-network/agent-runtime/tui`),{readGraphSessions:n}=await import(`./graph-native-af-gs1TS.mjs`);return t({roots:[e],assets:O(wl,`dist`,`graph-viewer`),readSessions:n})}async function jl(e,t){if(e.startsWith(`wfrun_`)){let n=await X(t),r=await n.workflows.getRun(e);return t.json?P(r):I(`Run ${e} · ${n.baseUrl}/app/workflows/${encodeURIComponent(r.workflowId)}/runs/${encodeURIComponent(e)}`)}let n=O(k(),`.tangle`,`runs`,e);if(!/^[a-f0-9-]{36}$/i.test(e)||!de(n))throw new z(`RUN_NOT_FOUND`,`Run '${e}' was not found`,`Use a run ID printed by tangle graph run`,`tangle graph inspect --help`);let{loadTopSnapshot:r}=await import(`@tangle-network/agent-runtime/tui`);if(t.json)return P(await r(process.cwd(),{runDir:n}));I(`Run ${e} · ${(await Al(n)).url}`)}function Ml(){let e=new b(`graph`).description(`Build and run portable agent graphs`);return Nc(e),vc(e),Hc(e,Dl,wl),e.command(`inspect <run>`).description(`Inspect a live or retained graph run`).action(jl),e.command(`run <name-or-file>`).description(`Run a saved graph over native subscriptions`).option(`--cloud`,`Run through Tangle's durable cloud workflow owner`).option(`--resume <run>`,`Resume this run's saved graph and durable execution`).option(`--seat <seat>`,`Use harness/model@effort for every node`).option(`--param <key=value>`,`Graph parameter or gate.<id>=<choice>; repeatable`,(e,t)=>[...t,e],[]).option(`--dry-run`,`Validate and print the graph without starting agents`).action(async(e,t)=>{let n=await kl(e,t);t.json||t.dryRun?P(n):`status`in n?(I(`${n.status} · ${n.runId}`),n.text&&console.log(n.text)):`viewerUrl`in n&&I(`Run ${n.runId} · ${n.viewerUrl}`)}),e}function Nl(){let e=new b(`intelligence`).description(`Create and inspect trace intelligence reports`);return e.command(`connect [agent]`).alias(`connect-agent`).description(`Connect local agent CLIs to Tangle Intelligence`).option(`--endpoint <url>`,`OTLP endpoint base`,ia).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(e,t)=>{let n=e??`local`;la(n);let r=Fl(t.apiKey),i=await ma({selection:n,workspace:t.workspace,apiKey:r,endpoint:t.endpoint,serviceName:t.serviceName??da(t.workspace),environment:t.environment,smoke:t.smoke,dryRun:!!t.dryRun,hookCommand:t.hookCommand}),a={configPath:i.configPath,agents:i.agents,nativeAgents:i.nativeAgents,manual:i.manual,written:i.written,smokeTraceId:i.smokeTraceId};if(t.json){P(a);return}R({Config:i.configPath,Agents:i.agents.join(`, `),"Native Hooks":i.nativeAgents.join(`, `)||void 0,"Manual Setup":i.manual.length?i.manual.map(e=>`${e.label}: ${e.reason}`).join(` `):void 0,Files:i.written.join(`, `),"Smoke Trace":i.smokeTraceId})}),e.command(`doctor`).description(`Check whether your agent traces carry CONTENT or are metadata-only`).option(`--endpoint <url>`,`OTLP endpoint base`,ia).action(async e=>{let t=pa(),n=await ya({endpoint:e.endpoint===`https://intelligence.tangle.tools/v1/otlp`?t?.endpoint??`https://intelligence.tangle.tools/v1/otlp`:e.endpoint,apiKey:Fl(e.apiKey??t?.apiKey)});e.json?P(n):Pl(n),n.contentSeen||(process.exitCode=1)}),e.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 e=>{try{let t=Il(e.agent),n=pa(),r={agent:t,event:e.event,endpoint:e.endpoint??n?.endpoint??`https://intelligence.tangle.tools/v1/otlp`,apiKey:Fl(e.apiKey??n?.apiKey),serviceName:e.serviceName??n?.serviceName??da(process.cwd()),environment:e.environment??n?.environment??`local`,sessionId:e.sessionId,payload:e.payload===void 0?await Rl():Ll(e.payload)};if(e.dryRun){let n=ga(r);if(e.json){P(n);return}R({Trace:n.traceId,Agent:t,Event:e.event});return}let i=await _a(r);if(e.json){P({traceId:i});return}R({Trace:i,Agent:t,Event:e.event})}catch(t){if(e.nonBlocking){let n=t instanceof Error?t.message:String(t);e.json?P({ok:!1,error:n}):console.error(`Tangle Intelligence hook skipped: ${n}`);return}V(t)}}),e.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 zl({type:`sandbox`,id:e},t)}),e.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 zl({type:`fleet`,id:e},t)}),e.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 zl({type:Vl(e.subjectType),id:e.subjectId},e)}),e.command(`get <job-id>`).description(`Get an intelligence report`).action(async(e,t)=>{let{client:n}=W(t),r=t.json?null:L(`Fetching intelligence report...`);r?.start();let i=await n.intelligence.getReport(e);if(r?.stop(),t.json){P(i);return}Bl(i)}),e.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 e=>{let{client:t}=W(e),n=e.json?null:L(`Fetching intelligence reports...`);n?.start();let r=await t.intelligence.listReports({subjectType:e.subjectType===void 0?void 0:Vl(e.subjectType),subjectId:e.subjectId,limit:e.limit===void 0?void 0:Wl(e.limit)});if(n?.stop(),e.json){P(r);return}N(r.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}])}),e}function Pl(e){R({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 t=Object.entries(e.byAgent);t.length>0&&(console.log(),N(t.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 Fl(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 Il(e){if(ua(e))return e;throw Error(`agent must be a known Tangle Intelligence agent surface`)}function Ll(e){try{return JSON.parse(e)}catch(e){throw Error(`--payload must be JSON: ${e instanceof Error?e.message:String(e)}`)}}async function Rl(){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 zl(e,t){let n=Hl(t.mode),r=Gl(t.metadata),i=t.maxUsd===void 0?void 0:Ul(t.maxUsd);if(n===`agentic`&&i===void 0)throw Error(`Agentic intelligence reports require --max-usd`);let{client:a}=W(t),o=t.json?null:L(`Creating intelligence report...`);o?.start();let s=await a.intelligence.createReport({subject:e,mode:n,...i===void 0?{}:{budget:{billTo:`customer`,maxUsd:i}},...r===void 0?{}:{metadata:r}});if(o?.stop(),t.json){P(s);return}Bl(s)}function Bl(e){R({Job:e.jobId,Subject:`${e.subject.type}:${e.subject.id}`,Mode:e.mode,Status:e.status,"Billed To":e.billing.billedTo,Cost:`$${e.billing.costUsd.toFixed(2)}`,Budget:e.billing.budgetMaxUsd===void 0?void 0:`$${e.billing.budgetMaxUsd.toFixed(2)}`,Updated:e.updatedAt}),e.result!==null&&(console.log(),P(e.result))}function Vl(e){if(e===`sandbox`||e===`fleet`)return e;throw Error(`subject type must be sandbox or fleet`)}function Hl(e){if(e===`deterministic`||e===`agentic`)return e;throw Error(`mode must be deterministic or agentic`)}function Ul(e){let t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`--max-usd must be a non-negative number`);return t}function Wl(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Gl(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 Kl=[`router`,`sandbox`,`blueprint-agent`,`evals`,`agent-builder`];async function ql(e,t){let n=await Lr({...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 Jl(e,t,n={}){let r=new Headers(n.headers);n.body&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await Rr(e,t,{...n,headers:r});if(n.expected!==void 0&&i.status!==n.expected)throw Error(await Yl(i,t));return i}async function Yl(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 Xl=[`ID`,`Prefix`,`Name`,`Product`,`Created`,`Last used`,`Expires`];function Zl(e){return[e.id,e.keyPrefix??``,e.name,e.product??`all`,e.createdAt,e.lastUsedAt??`—`,e.expiresAt??`—`]}function Ql(){let e=new b(`keys`).description(`Manage sk-tan-* API keys on id.tangle.tools`);return e.command(`list`).description(`List your active API keys`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async e=>{let t=await ql(e,!1),n=t.baseUrl,r=await(await Jl(t,`${n}/v1/keys`,{expected:200})).json();if(e.json){P(r);return}Bt(Xl,r.data.map(Zl))}),e.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 (${Kl.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(e,t)=>{if(t.product!==void 0&&!Kl.includes(t.product))throw Error(`Invalid --product. Expected one of ${Kl.join(`, `)}`);let n=await ql(t,!0),r=n.baseUrl,i=t.expiresInDays===void 0?void 0:new Date(Date.now()+Number.parseInt(t.expiresInDays,10)*24*60*60*1e3).toISOString(),a=L(`Creating API key...`);a.start();let o=await Jl(n,`${r}/v1/keys`,{method:`POST`,expected:201,body:JSON.stringify({name:e,product:t.product,budgetUsd:t.budgetUsd?Number.parseFloat(t.budgetUsd):void 0,rpmLimit:t.rpmLimit?Number.parseInt(t.rpmLimit,10):void 0,expiresAt:i})});a.stop();let s=await o.json();if(t.json){P(s);return}F(`API key created: ${s.data.prefix}…`),I(`Copy this key now — it will never be shown again:\n${s.data.key}`)}),e.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(e,t)=>{let n=await ql(t,!0),r=n.baseUrl;if(!t.yes&&!await $r(`Revoke key ${e}? Any service still using it will start to fail.`,`--yes`)){I(`Aborted.`);return}let i=await(await Jl(n,`${r}/v1/keys/${encodeURIComponent(e)}`,{method:`DELETE`,expected:200})).json();if(t.json){P(i);return}F(`Revoked ${e}`)}),e}function $l(e){if(Kn().token)throw Error(`A line relay cannot manage numbers or attachments. Use your owner CLI outside the agent box.`);return U(H(e))}function eu(e){if(!e.yes)throw Error(`Review the selected line and use --yes to authorize this change. Attaching enables metered agent work.`)}function tu(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 nu(e){return e().catch(V)}async function ru(e){let t=await Ge(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 iu(e){e.command(`providers`).description(`List provider transports supported by this Hub deployment`).action(e=>nu(async()=>{P(await $l(e).lines.providers())})),e.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(e=>nu(async()=>{P(await $l(e).lines.list({profileId:e.profileId,sandboxId:e.sandbox}))})),e.command(`get`).argument(`<line-id>`).description(`Inspect a line and its current attachment`).action((e,t)=>nu(async()=>{P(await $l(t).lines.get(e))})),e.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((e,t)=>nu(async()=>{let n=tu(t.transport);if(n===`email`)throw Error(`Email uses an owned mailbox, not phone inventory`);if(n===`voice`)throw Error(`Voice numbers are listed by ph0ny; provide the owned number ID to lines connect`);if(n===`telegram`)throw Error(`Telegram uses an owned bot, not phone inventory`);P(await $l(t).lines.numbers(e,n))})),e.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((e,t)=>nu(async()=>{eu(t);let n=tu(t.transport);if(n!==`email`&&t.address)throw Error(`--address is email-only`);if((n===`email`||n===`telegram`)&&t.numberId)throw Error(`${n} does not take --number-id`);let r={connectionId:e,label:t.label,clientReference:t.reference},i;if(n===`email`)i={...r,transport:n,address:t.address};else if(n===`telegram`)i={...r,transport:n};else if(n===`imessage`)i={...r,transport:n,phoneNumberId:t.numberId};else{if(!t.numberId)throw Error(`${n} requires --number-id`);i={...r,transport:n,phoneNumberId:t.numberId}}P(await $l(t).lines.fromConnection(i))})),e.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((e,t)=>nu(async()=>{eu(t);let n=$l(t),r;if(t.file){if(t.profileId||t.member||t.sandbox||t.instancePrefix||t.tools||t.turnsPerDay)throw Error(`Choose --file or quick-setup flags, not both`);r=await ru(t.file)}else{if(!t.profileId||!t.member)throw Error(`Provide --profile-id and --member, or --file`);if(t.sandbox&&t.instancePrefix)throw Error(`Choose --sandbox or --instance-prefix`);let e=t.tools??`chat`,n=Number(t.turnsPerDay??`30`);if(e!==`chat`&&e!==`act`)throw Error(`--tools must be chat or act`);if(!Number.isSafeInteger(n)||n<1||n>1e4)throw Error(`--turns-per-day must be 1–10000`);if(e===`act`&&t.sandbox)throw Error(`Acting tools require an isolated on-demand instance; omit --sandbox`);r={mode:`personal`,members:[{address:t.member,role:`owner`}],unknownSenders:`reject`,roles:{owner:{context:`own`,tools:e}},respond:{kind:`agent`,profileId:t.profileId,...e===`act`?{rolePolicy:{version:1,roles:{owner:{kind:`general`}},members:{}}}:{}},limits:{turnsPerMemberPerDay:n},...t.sandbox?{sandboxId:t.sandbox}:{instance:{keyPrefix:t.instancePrefix??`profile:${t.profileId}:`,create:{ownerContext:`isolated`,...e===`act`?{egressPolicy:{mode:`strict`,allowDomains:[new URL(ur()).hostname],includeImplicitDomains:!1}}:{}}}}}}if(typeof r.sandboxId==`string`==(r.instance!==void 0))throw Error(`Attachment requires exactly one of sandboxId and instance`);let{sandboxId:i,instance:a,...o}=r,s;if(i){let t=await n.get(i);if(!t)throw Error(`Sandbox not found`);s=await t.lines.attach({...o,number:e})}else{if(!a)throw Error(`Attachment requires an instance`);s=await n.lines.attach({...o,number:e,instance:a})}P(s)}));for(let t of[`detach`,`release`])e.command(t).argument(`<line-id>`).description(t===`detach`?`Stop dispatch; preserve history and provider rental`:`Retire a detached Hub line; does not cancel provider rental`).option(`--yes`,`Authorize this change`).action((e,n)=>nu(async()=>{eu(n),P({[t]:await $l(n).lines[t](e)})}));e.command(`threads`).argument(`<line-id>`).description(`List this line's separate participant threads`).action((e,t)=>nu(async()=>{P(await $l(t).lines.threads(e).list())})),e.command(`messages`).argument(`<line-id>`).argument(`<thread-id>`).description(`Read one authorized participant thread`).action((e,t,n)=>nu(async()=>{P(await $l(n).lines.threads(e).messages(t))}))}async function au(e){let{token:t,baseUrl:n}=Kn();if(t===void 0)return G(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 ou(e,t){if(t)return t;if(!Kn().token)throw Error(`Provide --line <line-id>`);return(await e.lines.context()).line.id}function su(e){return e().catch(V)}function cu(){return new b(`context`).description(`Show live line identity, members, consent, reminders and quotas`).action(e=>su(async()=>{P(await(await au(e)).lines.context())}))}function lu(){let e=new b(`lines`).description(`Connect, manage, message and schedule on a Hub line`);return e.command(`members`).description(`List names, roles and consent on this line`).option(`--line <line-id>`,`Line ID; inferred in a line box`).action(e=>su(async()=>{let t=await au(e);P(await t.lines.members.list(await ou(t,e.line)))})),e.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((e,t,n)=>su(async()=>{let r=await au(n),i=await ou(r,n.line);if(!Kn().token){if(n.onBehalfOf)throw Error(`--on-behalf-of is only available inside a line box`);if(!n.idempotencyKey)throw Error(`Owner sends require --idempotency-key so a retry keeps the same message`);if(!(await r.lines.members.list(i)).some(t=>t.id===e))throw Error(`Owner sends require an exact member ID from tangle lines members`);P(await r.lines.send(i,{memberId:e,text:t,idempotencyKey:n.idempotencyKey,...n.notBefore?{notBefore:n.notBefore}:{}}));return}P(await r.lines.send(i,{toMember:e,text:t,...n.onBehalfOf?{onBehalfOf:n.onBehalfOf}:{},...n.notBefore?{notBefore:n.notBefore}:{},...n.idempotencyKey?{idempotencyKey:n.idempotencyKey}:{}}))})),e.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((e,t)=>su(async()=>{if(!t.at)throw Error(`--at is required`);let n=await au(t),r=t.idempotencyKey??S(`sha256`).update(JSON.stringify([e,t.at])).digest(`hex`).slice(0,32);P(await n.lines.remind(await ou(n,t.line),{text:e,notBefore:t.at,idempotencyKey:r}))})),iu(e),e}function uu(){let e=new b(`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=H({apiKey:t.apiKey,baseUrl:t.baseUrl}),r=await K(U(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 nt(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 du(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=Ln(),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??nr():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=H({apiKey:a,baseUrl:r}),s=U(o);return t.self?at(s):K(s,o,e)}async function fu(e,t,n){let r=L(e);t||r.start();try{return await n()}finally{r.stop()}}function pu(e){return e}function mu(){let e=new b(`preview`).description(`Manage sandbox preview links`);return pu(e.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(e,t)=>{let n=await du(e,t),r=await fu(`Starting managed preview...`,t.json,()=>rt(n,{cwd:t.cwd,sessionId:t.session,name:t.name}));t.json?P(r):(F(`Preview ready: ${r.url}`),console.log(`Preview ID: ${r.previewId}`))}),pu(e.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(e,t)=>{let n=await du(e,t),r=await fu(`Fetching preview links...`,t.json,()=>n.previewLinks.list());t.json?P(r):r.length===0?console.log(`No preview links found`):Bt([`App`,`Preview ID`,`Port`,`URL`,`Status`],r.map(e=>[hu(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),pu(e.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(e,t)=>{if(!t.port||!/^\d+$/.test(t.port))throw Error(`An integer service port is required`);let n=await du(e,t),r=await fu(`Publishing service...`,t.json,()=>it(n,{port:Number(t.port),name:t.name}));t.json?P(r):F(`Preview ready: ${r.url}`)}),pu(e.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(e,t,n)=>{if(!/^\d+$/.test(t)||Number(t)<1||Number(t)>65535)throw Error(`Port must be an integer between 1 and 65535`);let r=await du(e,n),i=await fu(`Creating preview for port ${t}...`,n.json,()=>r.previewLinks.create(Number(t)));n.json?P(i):(F(`Preview created: ${i.url}`),console.log(`Preview ID: ${i.previewId}`))}),pu(e.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(e,t,n)=>{let r=await du(e,n);await fu(`Removing preview...`,n.json,()=>r.previewLinks.remove(t)),n.json?P({success:!0,previewId:t}):F(`Preview removed: ${t}`)}),e}function hu(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 gu(){let e=new b(`process`).description(`Manage processes in a sandbox`);return e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=es(n.env??[],`--env`,`env`),o=L(`Spawning: ${t}`);n.json||o.start();let s=await K(i,r,e);if(s=await q(s),n.blocking){let e=await s.exec(t,{cwd:n.cwd,env:Object.keys(a).length>0?a:void 0,timeoutMs:n.timeout?Number.parseInt(n.timeout,10):void 0});o.stop(),n.json?P(e):(e.stdout&&globalThis.process.stdout.write(e.stdout),e.stderr&&globalThis.process.stderr.write(e.stderr),e.exitCode!==0&&globalThis.process.exit(e.exitCode))}else{let r=await s.process.spawn(t,{cwd:n.cwd,env:Object.keys(a).length>0?a:void 0,timeoutMs:n.timeout?Number.parseInt(n.timeout,10):void 0});o.stop(),n.json?P({pid:r.pid,command:r.command}):(console.log(`Process started with PID: ${r.pid}`),console.log(`Use 'tangle process logs ${e} ${r.pid}' to view output`))}}),e.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching processes...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.process.list();t.running&&(o=o.filter(e=>e.running)),i.stop(),t.json?P(o):o.length===0?console.log(`No processes found`):Bt([`PID`,`Command`,`Status`,`Exit Code`,`Started`],o.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()]))}),e.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Fetching process info...`);n.json||a.start();let o=await K(i,r,e);o=await q(o);let s=await o.process.get(Number.parseInt(t,10));if(a.stop(),!s){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}let c=await s.status();n.json?P(c):(console.log(`PID: ${c.pid}`),console.log(`Command: ${c.command}`),console.log(`CWD: ${c.cwd||`(default)`}`),console.log(`Status: ${c.running?`running`:`exited`}`),console.log(`Exit Code: ${c.exitCode}`),c.exitSignal&&console.log(`Signal: ${c.exitSignal}`),console.log(`Started: ${c.startedAt.toLocaleString()}`),c.exitedAt&&console.log(`Exited: ${c.exitedAt.toLocaleString()}`))}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Sending ${n.signal} to PID ${t}...`);n.json||a.start();let o=await K(i,r,e);o=await q(o);let s=await o.process.get(Number.parseInt(t,10));if(!s){a.stop(),console.error(`Process ${t} not found`),globalThis.process.exit(1);return}n.tree?await s.kill(n.signal,{tree:!0}):await s.kill(n.signal),a.stop(),n.json?P({pid:Number.parseInt(t,10),signal:n.signal,...n.tree===!0?{tree:!0}:{},killed:!0}):console.log(n.tree?`Sent ${n.signal} to process tree ${t}`:`Sent ${n.signal} to process ${t}`)}),e.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}=W(n),a=await K(i,r,e);a=await q(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))}),e}const _u=[`python`,`node`,`typescript`,`bash`];function vu(e){switch(ve(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 yu(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 Ke(xe(e),`utf8`)}async function bu(e,t,n=yu){let r=t?_u.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${_u.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=vu(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 xu(e){return O(we(),`tangle-run-images`,e)}function Su(){return new b(`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: ${_u.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(e,t,n)=>{let{language:r,source:i}=await bu(t,n.lang),{context:a,client:o}=W(n),s=await K(o,a,e);s=await q(s);let c=L(`Running ${r} (${i.length}b)…`);n.json||c.start();let l=await s.runCode(r,i,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10)});if(c.stop(),n.json){P(l),l.exitCode!==0&&process.exit(l.exitCode);return}l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr);let u=0;for(let t of l.results)if(t.type===`image`)if(n.saveImages!==!1){let r=typeof n.saveImages==`string`?n.saveImages:xu(e);fe(r,{recursive:!0});let i=`${r}/${Date.now()}-${u}.${t.format}`;he(i,Buffer.from(t.data,`base64`)),process.stderr.write(y.green(`✓ image → ${i}\n`)),u++}else process.stderr.write(y.gray(`[image: ${t.format}, ${t.data.length}b base64]\n`));else if(t.type===`dataframe`){let e=t.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(y.gray(`[dataframe ${t.rows.length}×${t.columns.length}${t.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${e}\n`);for(let e of t.rows.slice(0,20))process.stderr.write(`${e.map(e=>String(e)).join(` | `)}\n`);t.rows.length>20&&process.stderr.write(y.gray(`… ${t.rows.length-20} more rows\n`))}else t.type===`json`?(process.stderr.write(y.gray(`[json] `)),process.stderr.write(`${JSON.stringify(t.value,null,2)}\n`)):t.type===`html`?process.stderr.write(y.gray(`[html ${t.value.length}b]\n`)):t.type===`error`?(process.stderr.write(y.red(`✗ ${t.name}: ${t.message}\n`)),t.traceback&&process.stderr.write(`${t.traceback}\n`)):t.type===`text`&&process.stderr.write(`${t.value}\n`);l.error&&(process.stderr.write(y.red(`\n✗ ${l.error.name}: ${l.error.message}\n`)),l.error.traceback&&process.stderr.write(`${l.error.traceback}\n`)),l.exitCode!==0&&process.exit(l.exitCode)})}function Cu(e){e.command(`network <id-or-name>`).description(`Show runtime network state (exposed ports) for a sandbox. Outbound policy is the sandbox's egress policy.`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Updating network configuration...`);i.start();let a=await K(r,n,e);i.stop();let o=await a.network.getConfig();t.json?P(o):(I(`Network Configuration:`),o.ports&&o.ports.length>0?I(` Exposed Ports: ${o.ports.join(`, `)}`):I(` No exposed ports`))}),e.command(`expose <id-or-name>`).description(`Expose a port and get a public URL`).option(`-p, --port <port>`,`Port to expose`,`8000`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=Number.parseInt(t.port,10);if(Number.isNaN(i)||i<1||i>65535)throw Error(`Port must be a number between 1 and 65535`);let a=L(`Exposing port ${i}...`);a.start();let o=await(await K(r,n,e)).network.exposePort(i);a.stop(),t.json?P({port:i,url:o}):(F(`Port ${i} exposed.`),I(` URL: ${o}`))}),e.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching exposed URLs...`);i.start();let a=await(await K(r,n,e)).network.listUrls();if(i.stop(),t.json)P(a);else{let e=Object.entries(a);if(e.length===0)I(`No ports exposed.`);else{I(`Exposed Ports:`);for(let[t,n]of e)I(` ${t}: ${n}`)}}})}function wu(){let e=new b(`sandbox`).description(`Manage sandboxes`);return Ms(e),js(e),xs(e),Cu(e),e}function Tu(){return new b(`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}=W(n),a=L(`Searching...`);n.json||a.start();let o=await K(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 Eu(){let e=new b(`secret`).description(`Manage secrets`);return e.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(e,t,n)=>{let r=await W(n).client.secrets.create(e,await Du({value:t,valueStdin:n.valueStdin,prompt:`Enter value for secret '${e}': `}));n.json?P(r):(F(`Secret created: ${r.name}`),I(`Use --secret ${r.name} when creating a sandbox to select it for delivery.`))}),e.command(`list`).description(`List all secrets`).action(async e=>{let t=await W(e).client.secrets.list();e.json?P(t):t.length===0?(I(`No secrets found.`),I(`Use 'tangle secret create <name> [value]' to create one.`)):Bt([`Name`,`Created At`,`Updated At`],t.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),e.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=W(t).client;if(!t.force&&!await $r(`Are you sure you want to delete secret '${e}'? This cannot be undone. (y/N) `,`--force`)){I(`Cancelled.`);return}await n.secrets.delete(e),t.json?P({success:!0,deleted:e}):F(`Secret deleted: ${e}`)}),e}async function Du(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 ti():await Qr(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function Ou(){let e=new b(`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=D.dirname(Ze(import.meta.url)),t=D.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function ku(){let e=new b(`snapshot`).description(`Manage snapshots`);return e.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Creating snapshot...`);i.start();let a=await K(r,n,e);if(t.wait===!1){let e=await a.snapshot({tags:t.tags,wait:!1});i.stop(),Ss(e.info,!!t.json);return}let o=await a.snapshot({tags:t.tags});i.stop(),t.json?P(o):(F(`Snapshot created: ${o.snapshotId}`),console.log(`Size: ${Au(o.sizeBytes??0)}`))}),e.command(`list <sandbox-id-or-name>`).description(`List snapshots for a sandbox`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching snapshots...`);i.start();let a=await(await K(r,n,e)).listSnapshots();i.stop(),t.json?P(a):N(a.map(e=>({...e,size:Au(e.sizeBytes??0)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}),e.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(e,t,n)=>{let{client:r}=W(n),i=L(`Restoring from snapshot...`);i.start();let a=await r.create({fromSnapshot:t,fromSandboxId:e,...n.billingOwner?{billingOwnerId:n.billingOwner}:{}});await a.waitFor(`running`,{timeoutMs:12e4}),i.stop(),n.json?P({sandboxId:a.id,restoredFrom:t,status:a.status}):(F(`New sandbox created: ${a.id}`),console.log(`Source snapshot: ${t}`))}),e.command(`revert <sandbox-id-or-name> <snapshot-id>`).description(`Revert an existing sandbox to a snapshot`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Reverting sandbox to snapshot...`);a.start();let o=await K(i,r,e),s=await o.revertToSnapshot(t);await o.refresh(),a.stop(),n.json?P({sandboxId:o.id,snapshotId:s.snapshotId,status:o.status}):(F(`Sandbox reverted: ${o.id}`),console.log(`Source snapshot: ${s.snapshotId}`))}),e.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Deleting snapshot...`);a.start();let o=await(await K(i,r,e)).deleteSnapshot(t);a.stop(),n.json?P({success:!0,sandboxId:e,snapshotId:t,outcome:o.outcome}):o.outcome===`already_absent`?F(`Snapshot already gone: ${t}`):F(`Snapshot deleted: ${t}`)}),e}function Au(e){if(e===0)return`0 B`;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 ju=`solve:device:secp256k1`,Mu=/^0x[0-9a-f]{64}$/i;function Nu(e){return e&&Mu.test(e)?e:void 0}function Pu(){let e=mn(ju),t=Nu(e.value);if(!(!t||e.source===`none`))return{account:st(t),source:e.source}}function Fu(){let e=Pu();if(e)return e;let t=ot(),n=hn(ju,t);return{account:st(t),source:n}}function Iu(e){let t=Nu(mn(ju).value);if(!t||st(t).address!==e.account.address)throw Error(`The local Solve device key changed; it was not retired`);let n=`${ju}:retired:${e.account.address.toLowerCase()}`;if(hn(n,t),mn(n).value!==t)throw Error(`The revoked device key could not be retired safely`);return _n(ju),n}function Lu(e){let t=e.create?Fu():Pu();if(!t)throw Error("No Solve device signer found. Run `tangle solve account --create`");e.json?P({address:t.account.address,source:t.source}):R({Address:t.account.address,Source:t.source})}const Ru=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;function zu(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function Bu(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Vu(e,t,n=2048){if(typeof e!=`string`||!e.trim()||e.length>n)throw Error(`${t} is missing or invalid`);if(zu(e))throw Error(`${t} contains control characters`);return e.trim()}function Hu(e,t){let n=Vu(e,t,64).toLowerCase();if(!Ru.test(n))throw Error(`${t} must be a 40 or 64 character Git revision`);return n}function Uu(e,t,n=!1){let r=typeof e==`number`&&Number.isSafeInteger(e)?String(e):Vu(e,t,80);if(!/^\d+$/.test(r)||!n&&r===`0`)throw Error(`${t} must be an unsigned integer`);return BigInt(r).toString()}function Wu(e,t){let n=Vu(e,t,2048),r=new URL(n);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&(r.hostname===`localhost`||r.hostname===`127.0.0.1`)))throw Error(`${t} must use HTTPS outside local development`);return n.replace(/\/$/,``)}function Gu(e,t){let n=Wu(e,t).replace(/\.git$/,``),r=new URL(n),i=r.pathname.split(`/`).filter(Boolean);if(r.hostname!==`github.com`||r.username||r.password||r.search||r.hash||i.length!==2)throw Error(`${t} must be an HTTPS GitHub repository URL`);return`https://github.com/${i.join(`/`)}`}function Ku(e,t){let n=Vu(e,t,42);if(!ht(n,{strict:!1}))throw Error(`${t} must be an EVM address`);return pt(n)}function qu(e,t){let n=Uu(e,t),r=Number(n);if(!Number.isSafeInteger(r)||r<=0)throw Error(`${t} is out of range`);return r}function Ju(...e){for(let t of e)if(typeof t==`string`&&t.trim())return t.trim()}function Yu(e){let t=e.trim().replace(/\.git$/,``);return t.startsWith(`git@github.com:`)?`https://github.com/${t.slice(15)}`:t.startsWith(`ssh://git@github.com/`)?`https://github.com/${t.slice(21)}`:t}function Xu(e){if(e===void 0)return;let t=Vu(e,`pull request URL`,2048);if(!/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:\/[^\s]*)?$/i.test(t))throw Error(`pull request URL must point to a GitHub pull request`);return t}function Zu(e,t){if(!/^https:\/\/[^\s]+$/i.test(e)&&!/^\/(?!\/).*$/.test(e)&&!/^[a-z][a-z0-9+.-]*:[^\s]+$/i.test(e))throw Error(`${t} must be an HTTPS URL or an absolute repository path`);if(e.split(/[?#]/,1)[0].split(`/`).includes(`..`))throw Error(`${t} cannot contain parent-directory segments`);return e}function Qu(e){return Rn(`solve`,e.profile)}function $u(e){let t=Qu(e),n=ir(void 0,t);if(!n)throw Error(`No Solve credential found for profile '${t}'. Run: tangle auth login --provider github --app solve`);return n}async function ed(e){let t=dr(e.apiUrl),n=await fetch(`${t}${e.path}`,{method:e.method??`GET`,headers:{Accept:`application/json`,...e.body===void 0?{}:{"Content-Type":`application/json`},Authorization:`Bearer ${$u(e)}`},...e.body===void 0?{}:{body:JSON.stringify(e.body)},signal:AbortSignal.timeout(3e4)}),r=await n.json().catch(()=>null);if(!n.ok||!r?.success||r.data===void 0){let e=r?.error?.message??`Solve API request failed with HTTP ${n.status}`;throw Error(r?.error?.code?`${r.error.code}: ${e}`:e)}return r.data}function td(e){return ed({path:`/v1/wallet/challenges`,method:`POST`,apiUrl:e.apiUrl,profile:e.profile,body:{deviceAddress:e.deviceAddress,...e.purpose?{purpose:e.purpose}:{}}})}function nd(e){return ed({path:`/v1/devices`,apiUrl:e.apiUrl,profile:e.profile})}function rd(e){return ed({path:`/v1/devices/revoke`,method:`POST`,apiUrl:e.apiUrl,profile:e.profile,body:{deviceAddress:e.deviceAddress,...e.reason?{reason:e.reason}:{},...e.challengeId&&e.signature?{challengeId:e.challengeId,signature:e.signature}:{}}})}const Q={chainId:42431,rpcUrl:`https://rpc.moderato.tempo.xyz`,sponsorUrl:`https://drew-gtr-pro.taild10bfc.ts.net/solve-sponsor`,tangleAddress:`0xff137B9C879c47C28ce389e84501925438AB4cdA`,managerAddress:`0x5271732F893B622ac6793d6DBA5B2626CCa4EA14`,paymentAsset:`0x20C0000000000000000000000000000000000000`,blueprintId:15n,serviceId:9n,competitionId:1n,minStakeWei:0n};function id(e,t){return e.toLowerCase()===t.toLowerCase()}function ad(e){if(e.chainId!==Q.chainId)throw Error(`Solve submissions require Tempo Moderato (chain ${Q.chainId}); received ${e.chainId}`);if(e.rpcUrl!==Q.rpcUrl)throw Error(`Solve metadata RPC does not match the trusted deployment`);if(e.sponsorUrl!==Q.sponsorUrl)throw Error(`Solve metadata sponsor does not match the trusted deployment`);if(!id(e.tangleAddress,Q.tangleAddress))throw Error(`Solve metadata Tangle contract does not match the trusted deployment`);if(!id(e.managerAddress,Q.managerAddress))throw Error(`Solve metadata competition manager does not match the trusted deployment`);if(!id(e.paymentAsset,Q.paymentAsset))throw Error(`Solve metadata payment asset does not match the trusted deployment`);if(e.blueprintId!==Q.blueprintId)throw Error(`Solve submissions require blueprint ${Q.blueprintId}; received ${e.blueprintId}`);if(e.serviceId!==Q.serviceId)throw Error(`Solve submissions require service ${Q.serviceId}; received ${e.serviceId}`);if(e.competitionId!==Q.competitionId)throw Error(`Solve submissions require competition ${Q.competitionId}; received ${e.competitionId}`);if(e.minStakeWei!==Q.minStakeWei)throw Error(`Solve submissions require zero stake for the trusted deployment`)}function od(e,t){let n=Bu(t.check??e.check,`competition.participation.check`),r=Vu(n.command,`competition.participation.check.command`,512);if(!Array.isArray(n.args)||n.args.some(e=>typeof e!=`string`))throw Error(`competition.participation.check.args must be an array of strings`);let i=n.args.map(e=>Vu(e,`competition checker argument`,2048)),a=Ju(n.result_file,n.resultFile),o=n.timeout_ms??n.timeoutMs,s=o===void 0?void 0:qu(o,`competition checker timeout`);return{command:r,args:i,...a?{result_file:a}:{},...s?{timeout_ms:s}:{}}}function sd(e){if(e.provenance===void 0)return;let t=Bu(e.provenance,`competition.participation.provenance`);if(t.mode!==`github_pull_request`)throw Error(`competition.participation.provenance.mode is unsupported`);if(t.required!==void 0&&typeof t.required!=`boolean`)throw Error(`competition.participation.provenance.required must be a boolean`);return{mode:`github_pull_request`,required:t.required===!0}}function cd(e){let t=Bu(e.chain??e.network??{},`competition.chain`),n=e.rewards&&typeof e.rewards==`object`&&!Array.isArray(e.rewards)?Bu(e.rewards,`competition.rewards`):{},r=n.minStake&&typeof n.minStake==`object`&&!Array.isArray(n.minStake)?Bu(n.minStake,`competition.rewards.minStake`).raw:void 0,i=Ju(t.minStakeWei,t.min_stake_wei,e.minStakeWei,e.min_stake_wei,r),a=t.chainId??t.chain_id??e.chainId??e.chain_id,o=Ju(t.chainName,t.chain_name,e.chainName,e.chain_name)??`Tempo`,s=Ju(t.nativeSymbol,t.native_symbol,e.nativeSymbol,e.native_symbol)??`TNT`,c=Ju(t.rpcUrl,t.rpc_url,e.rpcUrl,e.rpc_url,process.env.TANGLE_SOLVE_RPC_URL),l=Ju(t.sponsorUrl,t.sponsor_url,e.sponsorUrl,e.sponsor_url,process.env.TANGLE_SOLVE_SPONSOR_URL),u=Ju(t.tangleAddress,t.tangle_address,t.coreAddress,t.core_address,e.tangleAddress,e.tangle_address,e.coreAddress,e.core_address),d=Ju(t.managerAddress,t.manager_address,e.managerAddress,e.manager_address),f=Ju(t.paymentAsset,t.payment_asset,t.servicePaymentAsset,t.service_payment_asset,e.paymentAsset,e.payment_asset,e.servicePaymentAsset,e.service_payment_asset),p=Ju(t.blueprintId,t.blueprint_id,e.blueprintId,e.blueprint_id),m=Ju(t.serviceId,t.service_id,e.serviceId,e.service_id),h=Ju(t.competitionId,t.competition_id,e.competitionId,e.competition_id,e.id);if(!c||!l||!u||!d||!p||!m||!h||!i||a===void 0)throw Error(`Solve competition metadata must include complete Tempo chain configuration`);return{chainId:qu(a,`chain.chainId`),chainName:o,nativeSymbol:s,rpcUrl:Wu(c,`chain.rpcUrl`),sponsorUrl:Wu(l,`chain.sponsorUrl`),tangleAddress:Ku(u,`chain.tangleAddress`),managerAddress:Ku(d,`chain.managerAddress`),paymentAsset:Ku(f??Q.paymentAsset,`chain.paymentAsset`),blueprintId:Uu(p,`chain.blueprintId`),serviceId:Uu(m,`chain.serviceId`),competitionId:Uu(h,`chain.competitionId`,!0),minStakeWei:Uu(i,`chain.minStakeWei`,!0)}}function ld(e){let t=Bu(e,`competition`),n=Bu(t.participation??t.task,`competition.task`),r={...t,participation:{...n,...n.repositoryRevision===void 0&&n.revision!==void 0?{repositoryRevision:n.revision}:{}}},i=r.participation,a=Gu(Ju(r.repository,r.repo_url,i.repository)??``,`competition.repository`),o=Hu(Ju(r.repositoryRevision,r.repository_revision,i.revision,i.repositoryRevision,i.repository_revision),`competition.repositoryRevision`),s=Vu(r.slug??r.id,`competition.slug`,128),c=Vu(r.name??r.title??s,`competition.name`,256),l=od(r,i),u=sd(i);return{version:1,slug:s,title:c,repository:a,taskRevision:o,checker:l,chain:cd(r),...u?{provenance:u}:{}}}function ud(e){return{chainId:e.chain.chainId,chainName:e.chain.chainName,nativeSymbol:e.chain.nativeSymbol,rpcUrl:e.chain.rpcUrl,sponsorUrl:e.chain.sponsorUrl,tangleAddress:e.chain.tangleAddress,managerAddress:e.chain.managerAddress,paymentAsset:e.chain.paymentAsset,blueprintId:BigInt(e.chain.blueprintId),serviceId:BigInt(e.chain.serviceId),competitionId:BigInt(e.chain.competitionId),minStakeWei:BigInt(e.chain.minStakeWei)}}async function dd(e){let t=Bu(JSON.parse(await M.readFile(D.join(e,`.tangle-solve.json`),`utf8`)),`.tangle-solve.json`);if(t.version!==1)throw Error(`.tangle-solve.json has an unsupported version`);let n=Bu(t.checker,`.tangle-solve.json.checker`),r=Bu(t.chain,`.tangle-solve.json.chain`);return ld({slug:t.slug,name:t.title,repository:t.repository,repositoryRevision:t.taskRevision,participation:{check:n,provenance:t.provenance},chain:r,competitionId:r.competitionId})}const fd=$e(Te),pd=`.tangle-solve-run.json`,md=`.tangle-solve.json`,hd=`tangle.solve.manifestSha256`,gd=new Set([md,pd]),_d=`upstream`;async function vd(e,t){let n=await fd(`git`,[`-C`,e,...t],{encoding:`utf8`,maxBuffer:1e6});return String(n.stdout).trim()}async function yd(e,t){let n=D.resolve(t??process.cwd()),r=await dd(n);if(e&&e!==r.slug&&e!==r.chain.competitionId)throw Error(`This directory contains '${r.slug}', not '${e}'`);return{root:n,manifest:r}}async function bd(e){let t=D.join(e,md),n;try{n=await M.lstat(t)}catch{throw Error(`${md} is missing`)}if(n.isSymbolicLink()||!n.isFile())throw Error(`${md} must be a regular file`);return S(`sha256`).update(await M.readFile(t)).digest(`hex`)}async function xd(e){let t=await bd(e);return await vd(e,[`config`,`--local`,`--replace-all`,hd,t]),t}async function Sd(e){let t;try{t=await vd(e,[`config`,`--local`,`--get`,hd])}catch{throw Error(`The local Git metadata has no ${hd} pin; run tangle solve clone again`)}if(!/^[0-9a-f]{64}$/i.test(t))throw Error(`The local ${hd} pin is invalid`);if(await bd(e)!==t.toLowerCase())throw Error(`${md} changed after clone; run tangle solve clone again`)}async function Cd(e,t){try{return await vd(e,[`ls-files`,`--error-unmatch`,`--`,t]),!0}catch{return!1}}async function wd(e){await Sd(e);for(let t of gd)if(await Cd(e,t))throw Error(`${t} must remain untracked and local to this Solve workspace`);let t=await fd(`git`,[`-C`,e,`status`,`--porcelain=v1`,`--untracked-files=all`,`--ignored=matching`],{encoding:`utf8`,maxBuffer:1e6});if(String(t.stdout).split(/\r?\n/).filter(Boolean).filter(e=>{let t=e.slice(0,2),n=e.slice(3);return!((t===`??`||t===`!!`)&&gd.has(n))}).length>0)throw Error(`Commit the candidate before running Solve. Only the local manifest and run record may remain uncommitted.`);return Hu(await vd(e,[`rev-parse`,`HEAD`]),`submission revision`)}async function Td(e,t,n,r={}){let i=await Ed(e,t,r);if(i)return{taskRepository:t.repository,taskRevision:t.taskRevision,submissionRepository:i,submissionRevision:n}}async function Ed(e,t,n={}){let r;try{r=Yu(await vd(e,[`config`,`--get`,`remote.origin.pushurl`]))}catch{try{r=Yu(await vd(e,[`config`,`--get`,`remote.origin.url`]))}catch{if(n.allowMissing)return;throw Error(`Add your GitHub fork as the 'origin' remote before submitting. The task repository is available as '${_d}'.`)}}let i=Gu(r,`git remote.origin.url`);if(i.toLowerCase()===t.repository.toLowerCase()){if(n.allowMissing)return;throw Error(`The 'origin' remote is the task repository. Add your GitHub fork as 'origin'; keep the task repository as '${_d}' before submitting.`)}return i}function Dd(e,t){return!e||!t?!1:e.taskRepository.toLowerCase()===t.taskRepository.toLowerCase()&&e.taskRevision.toLowerCase()===t.taskRevision.toLowerCase()&&e.submissionRepository.toLowerCase()===t.submissionRepository.toLowerCase()&&e.submissionRevision.toLowerCase()===t.submissionRevision.toLowerCase()}function Od(e,t){return`${e}/commit/${t}`}function kd(e,t,n,r,i={}){let a=e.evidenceRefs.map(e=>Zu(e.trim(),`checker evidence reference`));if(n){if(!t){if(i.allowMissingSource)return{evidence:e.evidence,evidenceRefs:a};throw Error(`Provenance policy requires a submission source`)}let o=Xu(r);if(n.required&&(i.requirePullRequest??!0)&&!o)throw Error(`This competition requires a GitHub pull request`);a.push(Od(t.taskRepository,t.taskRevision),Od(t.submissionRepository,t.submissionRevision),...o?[o]:[])}return{evidence:e.evidence,evidenceRefs:[...new Set(a)]}}async function Ad(e,t){let n=`${e}.${process.pid}.tmp`;await M.writeFile(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await M.rename(n,e)}async function jd(e){let t=JSON.parse(await M.readFile(D.join(e,pd),`utf8`));if(t.version!==1||typeof t.competition!=`string`)throw Error(`${pd} has an unsupported format`);return t}async function Md(e){let t=Xu(e.pullRequest);if(!t)throw Error(`A pull request URL is required`);let n=new URL(t).pathname.split(`/`).filter(Boolean),r=await fetch(`https://api.github.com/repos/${n[0]}/${n[1]}/pulls/${n[3]}`,{headers:{Accept:`application/vnd.github+json`,"User-Agent":`tangle-solve-cli`},signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>null),a=e=>e.replace(/\/$/,``).toLowerCase();if(!r.ok||a(i?.base?.repo?.html_url??``)!==a(e.taskRepository)||i?.head?.sha?.toLowerCase()!==e.submissionRevision.toLowerCase()||a(i?.head?.repo?.html_url??``)!==a(e.submissionRepository))throw Error(`GitHub pull request must target the pinned task repository and contain the current committed submission`)}function Nd(e){return{...e.authorization?{authorization:e.authorization}:{},...e.stake?{stake:e.stake}:{},join:e.join,commit:e.commit,reveal:e.reveal,report:e.report,evaluation:e.evaluation}}const Pd=$e(Te);function Fd(){return`Task source is '${_d}'. Add your fork as 'origin', commit your candidate, push it, and open a pull request before submitting.`}async function Id(e,t,n){try{let r=Bu(await ed({path:`/v1/competitions/${encodeURIComponent(e)}`,apiUrl:n.apiUrl,profile:n.profile}),`competition response`),i=ld(r.competition??r),a=D.resolve(t??i.slug),o=L(`Cloning ${i.slug}…`);n.json||o.start();try{await Pd(`git`,[`clone`,`--no-tags`,`--origin`,_d,i.repository,a],{encoding:`utf8`,maxBuffer:1e6}),await vd(a,[`checkout`,`--detach`,i.taskRevision]);let e=await vd(a,[`rev-parse`,`HEAD`]);if(e.toLowerCase()!==i.taskRevision.toLowerCase())throw Error(`Pinned checkout resolved to ${e}, expected ${i.taskRevision}`);await Ad(D.join(a,`.tangle-solve.json`),i),await xd(a)}finally{o.stop()}n.json?P({competition:i,directory:a}):(F(`Cloned ${i.slug} at ${i.taskRevision.slice(0,12)}`),i.provenance&&I(Fd()),I(`Run the pinned checker with: cd ${a} && tangle solve run`))}catch(e){V(e)}}const Ld=12e4,Rd=vt(`event JobSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint8 jobIndex, address caller, bytes inputs)`),zd=vt(`event JobCompleted(uint64 indexed serviceId, uint64 indexed callId)`),Bd=vt(`event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)`),Vd=vt(`event AggregatedResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint256 signerBitmap, bytes output)`),Hd=vt(`event EvaluationAccepted(uint64 indexed serviceId, uint64 indexed competitionId, address indexed researcher, bytes32 candidateId, bytes32 submissionRefHash, bytes32 evaluationDigest, bytes32 metricsHash, bytes32 evidenceRefsHash)`),Ud=[..._t([`function submitJob(uint64 serviceId, uint8 jobIndex, bytes inputs) payable returns (uint64 callId)`,`function getJobEventRate(uint64 blueprintId, uint8 jobIndex) view returns (uint256 rate)`,`function getServicePaymentAsset(uint64 serviceId) view returns (address)`,`function isPermittedCaller(uint64 serviceId, address caller) view returns (bool)`]),Rd,zd,Bd,Vd],Wd=_t([`function authorizeSelf(uint64 serviceId)`,`function revokeSelf(uint64 serviceId)`,`function isDeviceRevoked(address device) view returns (bool)`,`function postStake(uint64 serviceId, uint64 competitionId) payable`,`function stakes(uint64 serviceId, uint64 competitionId, address researcher) view returns (uint256)`,`function pendingResults(uint64 serviceId, uint64 jobCallId) view returns (uint8 job, bytes32 outputHash, uint256 signerBitmap, bool exists, bool executed)`,`function executePendingResult(uint64 serviceId, uint64 jobCallId, bytes output)`,`function acceptedCandidates(uint64 serviceId, uint64 competitionId, address researcher, bytes32 candidateId) view returns (bool)`]),Gd=_t([`function allowance(address owner, address spender) view returns (uint256)`,`function approve(address spender, uint256 amount) returns (bool)`]),Kd=yt(`uint64 competitionId, uint256 stakeWei`),qd=yt(`uint64 competitionId, bytes32 commitment`),Jd=yt(`uint64 competitionId, bytes32 commitment, string artifactRef, bytes32 salt`),Yd=yt(`string artifactRef, bytes32 salt`),Xd=yt(`uint64 competitionId, bytes32 candidateId, string submissionRef, string evidenceJson, string evidenceRefsJson`),Zd=yt(`string status, string detail`),Qd=/^0x[0-9a-f]{64}$/i;function $d(e,t){if(e!==t)throw Error(`Tempo RPC returned chain ${e}; expected ${t}`)}function ef(e,t,n){return{...e,feePayer:!0,nonceKey:t,nonce:n}}function tf(e,t){if(e!==`success`)throw Error(`${t} transaction reverted`)}function nf(e,t,n,r){if(!Qd.test(t))throw Error(`${n} transaction hash is invalid`);if(typeof e.transactionHash!=`string`||e.transactionHash.toLowerCase()!==t.toLowerCase())throw Error(`${n} receipt hash does not match the saved transaction`);if(tf(e.status??``,n),typeof e.from!=`string`||e.from.toLowerCase()!==r.from.toLowerCase())throw Error(`${n} receipt sender does not match the Solve device`);if(typeof e.to!=`string`||e.to.toLowerCase()!==r.to.toLowerCase())throw Error(`${n} receipt destination does not match the expected contract`)}function rf(e,t){return e>=t?[]:e>0n?[0n,t]:[t]}function af(e,t,n=Date.now()){return n>=e+t}function of(e,t){return e.filter(e=>e.args?.candidateId?.toLowerCase()===t.toLowerCase()).at(-1)?.transactionHash}function sf(e,t,n,r,i){for(let a of e.logs)if(a.address.toLowerCase()===t.tangleAddress.toLowerCase())try{let e=dt({abi:[Rd],eventName:`JobSubmitted`,data:a.data,topics:a.topics});if(e.args.serviceId===t.serviceId&&e.args.jobIndex===n&&e.args.caller.toLowerCase()===r.toLowerCase()&&(!i||e.args.inputs.toLowerCase()===i.toLowerCase()))return e.args.callId}catch{}throw Error(`Tangle did not emit job ${n} for ${r}`)}function cf(e,t,n,r){for(let i of e.logs)if(i.address.toLowerCase()===t.managerAddress.toLowerCase())try{let e=dt({abi:[Hd],eventName:`EvaluationAccepted`,data:i.data,topics:i.topics}).args;if(e.serviceId===t.serviceId&&e.competitionId===t.competitionId&&e.researcher.toLowerCase()===n.address.toLowerCase()&&e.candidateId.toLowerCase()===r.toLowerCase())return!0}catch{}return!1}function lf(e){if(e.chainId!==St.id)throw Error(`Solve submissions require Tempo Moderato (chain ${St.id}); received ${e.chainId}`);if(!e.sponsorUrl)throw Error(`Solve submissions require a Tempo sponsor relay URL; unsponsored writes are disabled`);return{...St,name:e.chainName,nativeCurrency:{name:e.nativeSymbol,symbol:e.nativeSymbol,decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}}async function uf(e,t){ad(e);let n=lf(e),r=ct({chain:n,transport:mt(e.rpcUrl)});return $d(await r.getChainId(),e.chainId),await df({publicClient:r},e),{publicClient:r,walletClient:lt({account:t,chain:n,transport:wt(mt(e.rpcUrl),mt(e.sponsorUrl))}),account:t}}async function df(e,t){let n=await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getServicePaymentAsset`,args:[t.serviceId]});if(n.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo service payment asset ${n} does not match the trusted Solve asset ${t.paymentAsset}`)}async function ff(e,t,n){let[r,i]=await Promise.all([e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getJobEventRate`,args:[t.blueprintId,n]}),e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getServicePaymentAsset`,args:[t.serviceId]})]);if(i.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo job payment asset ${i} does not match the trusted Solve asset ${t.paymentAsset}`);return{asset:i,amount:r,value:i===`0x0000000000000000000000000000000000000000`?r:0n}}async function pf(e,t,n){return await e.publicClient.readContract({address:t,abi:Gd,functionName:`allowance`,args:[e.account.address,n.tangleAddress]})}async function mf(e,t,n,r,i,a){let o=Date.now();for(;!af(o,a);){if((await e.publicClient.getLogs({address:t.tangleAddress,event:zd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`})).length>0){let a=(await e.publicClient.getLogs({address:t.tangleAddress,event:Bd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.result;if(!a)throw Error(`Tangle job ${n} completed without a result`);let[o,s]=ut(Zd,a);if(o!==i)throw Error(`Tangle job ${n} ${o}: ${s}`);return{status:o,detail:s}}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not complete within 120 seconds`)}async function hf(e,t,n,r,i){let a=Date.now();for(;!af(a,i);){let i=(await e.publicClient.getLogs({address:t.tangleAddress,event:Vd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.output;if(i)return i;await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not produce an aggregate within 120 seconds`)}async function gf(e,t,n){return!!await e.publicClient.readContract({address:t.managerAddress,abi:Wd,functionName:`acceptedCandidates`,args:[t.serviceId,t.competitionId,e.account.address,n]})}const _f=BigInt(gt(bt(`tangle.solve.v1`)));async function vf(e,t){let n=await Ct.nonce.getNonce(e.publicClient,{account:e.account.address,nonceKey:_f});if(n>BigInt(2**53-1))throw Error(`The Solve transaction nonce exceeds the safe range`);return e.walletClient.writeContract(ef(t,_f,Number(n)))}async function yf(e,t,n,r){if(!await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))try{let i=r??await vf(e,{address:t.managerAddress,abi:Wd,functionName:`authorizeSelf`,args:[t.serviceId]});if(r||await n?.(`authorization`,i),nf(await e.publicClient.waitForTransactionReceipt({hash:i}),i,`Authorization`,{from:e.account.address,to:t.managerAddress}),!await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))throw Error(`authorization transaction did not add the device`);return i}catch(e){let t=e instanceof Error?e.message:`unknown chain error`;throw Error(`The competition manager did not authorize this device. The deployed manager must expose authorizeSelf(uint64): ${t}`)}}async function bf(e,t){let n=await vf(e,{address:t.managerAddress,abi:Wd,functionName:`revokeSelf`,args:[t.serviceId]});return nf(await e.publicClient.waitForTransactionReceipt({hash:n}),n,`Revocation`,{from:e.account.address,to:t.managerAddress}),n}async function xf(e,t,n,r,i=`allowance`,a={}){if(t.amount===0n||t.asset===`0x0000000000000000000000000000000000000000`)return;let o=await pf(e,t.asset,n);for(let s of rf(o,t.amount)){let o=s===0n?`${i}:reset`:`${i}:approval`,c=a[o];if(c){if(nf(await e.publicClient.waitForTransactionReceipt({hash:c}),c,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset}),await pf(e,t.asset,n)!==s)throw Error(`${s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`} did not set the expected allowance`);continue}let l=await vf(e,{address:t.asset,abi:Gd,functionName:`approve`,args:[n.tangleAddress,s]});await r?.(o,l),nf(await e.publicClient.waitForTransactionReceipt({hash:l}),l,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset})}}async function Sf(e,t,n,r,i,a=`job:${n}`,o={}){let s=await ff(e,t,n);await xf(e,s,t,i,`allowance:${a}`,o);let c=o[a],l=c??await vf(e,{address:t.tangleAddress,abi:Ud,functionName:`submitJob`,args:[t.serviceId,n,r],value:s.value});c||await i?.(a,l);let u=await e.publicClient.waitForTransactionReceipt({hash:l});return nf(u,l,`Job ${n}`,{from:e.account.address,to:t.tangleAddress}),{hash:l,callId:sf(u,t,n,e.account.address,r),blockNumber:u.blockNumber}}async function Cf(e,t,n,r,i,a,o=`job:${n}`,s={}){let c=await Sf(e,t,n,r,a,o,s),l=await mf(e,t,c.callId,c.blockNumber,i,Ld);return{...c,acknowledgement:l}}const wf={...Q,chainName:`Tempo Moderato`,nativeSymbol:`TNT`},Tf={async read(e){let t=ct({chain:St,transport:mt(wf.rpcUrl,{timeout:15e3})}),n=e=>e.catch(()=>null),r=await Promise.all(e.map(async e=>{let[r,i]=await Promise.all([n(t.readContract({address:wf.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[wf.serviceId,e]})),n(t.readContract({address:wf.managerAddress,abi:Wd,functionName:`isDeviceRevoked`,args:[e]}))]);return[e.toLowerCase(),{permitted:r,revoked:i}]}));return new Map(r)},async revokeSelf(e){return bf(await uf(wf,e),wf)}},Ef={permitted:null,revoked:null};function Df(e){return e.revoked?`revoked`:e.permitted===null?`unknown`:e.permitted?`permitted`:`not permitted`}async function Of(e,t=Tf){try{let{devices:n}=await nd({apiUrl:e.apiUrl,profile:e.profile}),r=Pu()?.account.address.toLowerCase(),i=n.map(e=>({...e,local:e.address===r,status:e.revokedAt?`revoked`:`active`}));r&&!i.some(e=>e.local)&&i.push({address:r,local:!0,status:`unbound`,boundAt:null,lastUsedAt:null,revokedAt:null,revocationMethod:null,revocationReason:null});let a=await t.read(i.map(e=>pt(e.address))),o=i.map(e=>({...e,onChain:a.get(e.address)??Ef}));if(e.json){P({serviceId:wf.serviceId.toString(),devices:o});return}Bt([`Address`,`Status`,`Local`,`Service ${wf.serviceId}`,`Last used`,`Revoked`],o.map(e=>[e.address,e.status,e.local?`yes`:``,Df(e.onChain),e.lastUsedAt??``,e.revokedAt?`${e.revokedAt} (${e.revocationMethod})`:``]))}catch(t){V(t,e.json)}}async function kf(e,t,n=Tf){try{if(!ht(e))throw Error(`${e} is not an EVM address`);let r=pt(e),i=Pu(),a=i?.account.address===r;if(!t.yes){if(!process.stdin.isTTY)throw Error(`Revoking a device is permanent. Re-run with --yes to confirm`);if(!await $r(`Permanently revoke Solve device ${r}${a?` (this machine's device)`:``}? [y/N] `,`--yes`)){I(`Revocation cancelled`);return}}let o;if(i&&a){let e=await td({deviceAddress:r,purpose:`revoke`,apiUrl:t.apiUrl,profile:t.profile});o={challengeId:e.challengeId,signature:await i.account.signMessage({message:e.message})}}let s=await rd({deviceAddress:r,reason:t.reason,...o,apiUrl:t.apiUrl,profile:t.profile}),c=r.toLowerCase(),l=(await n.read([r])).get(c)??Ef,u;if(i&&a&&!l.revoked){try{u=await n.revokeSelf(i.account)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`The Solve API revoked ${r}, but the on-chain revocation failed and the local key was kept: ${t}. Run the command again to retry`)}l=(await n.read([r])).get(c)??Ef}let d=i&&a&&l.revoked?Iu(i):void 0;if(t.json){P({...s,serviceId:wf.serviceId.toString(),onChain:l,...u?{revocationTransaction:u}:{},localKeyRetired:!!d});return}F(s.alreadyRevoked?`${r} was already revoked in the Solve API`:`Revoked ${r}; the Solve API refuses its signatures`),u&&F(`Revoked on Tempo in ${u}; service ${wf.serviceId} refuses its jobs`),d&&I("The local device key was moved aside because its address may still hold stake or rewards. Run `tangle solve account --create` for a new device"),!a&&l.permitted&&Ft(`The device can still submit jobs to service ${wf.serviceId}. Only its key, or the Solve blueprint owner, can revoke it on chain`)}catch(e){V(e,t.json)}}function Af(e,t){return gt(ft(Yd,[e.trim(),t]))}function jf(e){let t=/^submission=(\S+)/.exec(e);if(!t?.[1])throw Error(`COMMIT_CANDIDATE did not return a submission reference`);return t[1]}async function Mf(e,t,n,r,i){let a=i.resumeTransactions?.evaluation;if(a){let n=await e.publicClient.waitForTransactionReceipt({hash:a});if(nf(n,a,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!cf(n,t,e.account,r))throw Error(`Saved evaluation transaction did not emit EvaluationAccepted for this candidate`);return a}let o=Date.now();for(;!af(o,Ld);){if(await gf(e,t,r)){let i=of(await e.publicClient.getLogs({address:t.managerAddress,event:Hd,args:{serviceId:t.serviceId,competitionId:t.competitionId,researcher:e.account.address},fromBlock:n.blockNumber,toBlock:`latest`}),r);if(i)return i;throw Error(`Candidate is already accepted, but its EvaluationAccepted transaction is unavailable`)}let[a,o,,s,c]=await e.publicClient.readContract({address:t.managerAddress,abi:Wd,functionName:`pendingResults`,args:[t.serviceId,n.callId]});if(s&&a!==4)throw Error(`Manager pending result ${n.callId} has unexpected job ${a}`);if(s&&c)throw Error(`Manager executed the report without EvaluationAccepted`);if(s&&!c){if(o.toLowerCase()!==gt(n.output).toLowerCase())throw Error(`Manager pending report output does not match the aggregate`);let a=await vf(e,{address:t.managerAddress,abi:Wd,functionName:`executePendingResult`,args:[t.serviceId,n.callId,n.output]});await i.onTransaction?.(`evaluation`,a);let s=await e.publicClient.waitForTransactionReceipt({hash:a});if(nf(s,a,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!cf(s,t,e.account,r))throw Error(`Evaluation transaction did not emit EvaluationAccepted for this candidate`);return a}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Manager did not emit EvaluationAccepted within 120 seconds`)}async function Nf(e,t,n,r={}){if(ad(e),!/^0x[0-9a-f]{64}$/i.test(n.salt))throw Error(`Reveal salt must be bytes32`);if(!n.artifactRef.trim())throw Error(`Candidate reference is required`);if(!n.evidenceJson.trim()||n.evidenceRefs.length===0)throw Error(`Checker evidence is required`);let i=await uf(e,t),a=await yf(i,e,r.onTransaction,r.resumeTransactions?.authorization),o,s=await i.publicClient.readContract({address:e.managerAddress,abi:Wd,functionName:`stakes`,args:[e.serviceId,e.competitionId,i.account.address]});s<e.minStakeWei&&(o=await vf(i,{address:e.managerAddress,abi:Wd,functionName:`postStake`,args:[e.serviceId,e.competitionId],value:e.minStakeWei-s}),await r.onTransaction?.(`stake`,o),nf(await i.publicClient.waitForTransactionReceipt({hash:o}),o,`Stake`,{from:i.account.address,to:e.managerAddress}));let c=Af(n.artifactRef,n.salt),l=ft(Kd,[e.competitionId,e.minStakeWei]),u=ft(qd,[e.competitionId,c]),d=ft(Jd,[e.competitionId,c,n.artifactRef.trim(),n.salt]),f=await Cf(i,e,1,l,`joined`,r.onTransaction,`join`,r.resumeTransactions),p=await Cf(i,e,2,u,`committed`,r.onTransaction,`commit`,r.resumeTransactions),m=jf(p.acknowledgement.detail),h=await Cf(i,e,3,d,`revealed`,r.onTransaction,`reveal`,r.resumeTransactions),g=await Sf(i,e,4,ft(Xd,[e.competitionId,c,m,n.evidenceJson,JSON.stringify(n.evidenceRefs)]),r.onTransaction,`report`,r.resumeTransactions),_=await hf(i,e,g.callId,g.blockNumber,Ld),v=await Mf(i,e,{callId:g.callId,output:_,blockNumber:g.blockNumber},c,r);return{address:i.account.address,...a?{authorization:a}:{},...o?{stake:o}:{},join:f.hash,commit:p.hash,reveal:h.hash,report:g.hash,evaluation:v,candidateId:c,submissionRef:m}}const Pf=$e(Te),Ff=`/usr/bin/bwrap`,If=[`/usr`,`/bin`,`/sbin`,`/lib`,`/lib64`];function Lf(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function Rf(e,t){if(!e||e.length>2048||Lf(e))throw Error(`${t} contains invalid control characters or is too long`)}function zf(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]??``);)n+=1;return n}function Bf(e,t){if(e[t]!==`"`)throw Error(`Checker output must be valid JSON`);let n=t+1;for(;n<e.length;){let t=e[n];if(t===`\\`){n+=2;continue}if(t===`"`)return n+1;if((t?.charCodeAt(0)??0)<32)throw Error(`Checker output must be valid JSON`);n+=1}throw Error(`Checker output must be valid JSON`)}function Vf(e,t,n){let r=new Set,i=zf(e,t+1);if(e[i]===`}`)return i+1;for(;i<e.length;){let t=Bf(e,i),a=JSON.parse(e.slice(i,t));if(r.has(a))throw Error(`Checker output must not contain duplicate object keys`);if(r.add(a),i=zf(e,t),e[i]!==`:`)throw Error(`Checker output must be valid JSON`);let o=zf(e,i+1),s=Uf(e,o);if(n?.(a,o,s),i=zf(e,s),e[i]===`}`)return i+1;if(e[i]!==`,`)throw Error(`Checker output must be valid JSON`);i=zf(e,i+1)}throw Error(`Checker output must be valid JSON`)}function Hf(e,t){let n=zf(e,t+1);if(e[n]===`]`)return n+1;for(;n<e.length;){if(n=zf(e,Uf(e,n)),e[n]===`]`)return n+1;if(e[n]!==`,`)throw Error(`Checker output must be valid JSON`);n=zf(e,n+1)}throw Error(`Checker output must be valid JSON`)}function Uf(e,t){if(e[t]===`"`)return Bf(e,t);if(e[t]===`{`)return Vf(e,t);if(e[t]===`[`)return Hf(e,t);let n=t;for(;n<e.length&&!/[\s,\]}]/.test(e[n]??``);)n+=1;return n}function Wf(e){let t=e.trim();if(zf(t,Uf(t,0))!==t.length)throw Error(`Checker output must be valid JSON`)}function Gf(e,t){let n=e.trim();if(n[0]!==`{`)return;let r;return Vf(n,0,(e,i,a)=>{e===t&&(r=n.slice(i,a).trim())}),r}function Kf(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Checker output must be one JSON object`)}if(Wf(e),!t||typeof t!=`object`||Array.isArray(t))throw Error(`Checker output must be a JSON object`);let n=t,r=n.candidate_ref;if(typeof r!=`string`||!r.trim())throw Error(`Checker output must include candidate_ref`);let i=r.trim(),a=n.evidence_refs;if(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`||!e.trim()))throw Error(`Checker output must include a non-empty evidence_refs array`);Rf(i,`candidate_ref`);for(let e of a)Rf(e.trim(),`evidence_refs`);if(!n.evidence_json||typeof n.evidence_json!=`object`||Array.isArray(n.evidence_json))throw Error(`Checker output must include an evidence_json object`);let o={...n.evidence_json},s=Gf(e,`evidence_json`);if(!s)throw Error(`Checker evidence_json source text is missing`);if(o.candidate_ref!==i)throw Error(`Checker evidence_json candidate_ref must match candidate_ref`);return{candidateRef:i,evidenceRefs:a.map(e=>e.trim()),evidence:o,evidenceJson:s}}async function qf(e,t,n){let r=n.trim();if(r.startsWith(`{`)&&r.endsWith(`}`)||!t.result_file)return r;let i=await $f(e),a=D.resolve(i,t.result_file),o=D.relative(i,a);if(o.startsWith(`..`)||D.isAbsolute(o))throw Error(`Checker result_file must stay inside the competition repository`);let s;try{s=await M.lstat(a)}catch{throw Error(`Checker result_file must be an existing regular file inside the competition repository`)}if(s.isSymbolicLink())throw Error(`Checker result_file must not be a symbolic link`);if(!s.isFile())throw Error(`Checker result_file must be an existing regular file inside the competition repository`);let c;try{c=await M.realpath(a)}catch{throw Error(`Checker result_file must resolve to a regular file inside the competition repository`)}let l=D.relative(i,c);if(l.startsWith(`..`)||D.isAbsolute(l))throw Error(`Checker result_file must stay inside the competition repository`);return(await M.readFile(c,`utf8`)).trim()}function Jf(e,t){let n=D.relative(e,t);return n===``||!n.startsWith(`..`)&&!D.isAbsolute(n)}function Yf(e){return If.some(t=>Jf(t,e))}async function Xf(e,t,n){let r=e.includes(`/`)?[D.resolve(t,e)]:(process.env.PATH??``).split(D.delimiter).filter(Boolean).map(t=>D.join(t,e));for(let i of r){let r;try{r=await M.realpath(i),await M.access(r,M.constants.X_OK)}catch{continue}if(!Jf(t,r)&&!Yf(r)&&r!==n)throw Error(`Checker executable '${e}' must resolve inside the competition repository or a trusted runtime directory`);return r}throw Error(`Checker executable '${e}' was not found`)}async function Zf(e){let t=[];for(let n of e)try{(await M.stat(n)).isDirectory()&&t.push(n)}catch{}return t}async function Qf(e){let t=await M.realpath(Ce.homedir());if(e===D.parse(e).root||e===t)throw Error(`Solve checker repository must be a dedicated directory, not the filesystem or home root`)}async function $f(e){let t=await M.realpath(e);return await Qf(t),t}async function ep(e){let t=D.join(e,`.git`),n;try{n=await M.lstat(t)}catch{return}if(n.isSymbolicLink())throw Error(`Solve checker repository .git must not be a symbolic link`);if(!n.isDirectory()&&!n.isFile())return;let r;try{let t={...process.env};for(let e of[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_CONFIG_COUNT`,`GIT_CONFIG_PARAMETERS`])delete t[e];let n=await Pf(`/usr/bin/git`,[`-C`,e,`rev-parse`,`--verify`,`HEAD^{commit}`],{encoding:`utf8`,maxBuffer:1e5,env:{...t,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_CONFIG_SYSTEM:`/dev/null`,GIT_CONFIG_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}),i=String(n.stdout).trim();/^[0-9a-f]{40}$/i.test(i)&&(r=i.toLowerCase())}catch{}return{kind:n.isDirectory()?`directory`:`file`,...r?{commit:r}:{}}}async function tp(e,t,n){let r=await $f(e);if(process.platform!==`linux`)throw Error(`Solve checkers require the Linux sandbox runtime (bubblewrap) with network isolation`);try{await M.access(Ff,M.constants.X_OK)}catch{throw Error(`Solve checkers require /usr/bin/bwrap; install bubblewrap or run the checker in a Tangle sandbox`)}let i=await Xf(t,r,await M.realpath(process.execPath)),a=await ep(r),o=(await Zf(If)).flatMap(e=>[`--ro-bind`,e,e]),s=Jf(r,i)?`/work/${D.relative(r,i)}`:Yf(i)?i:`/checker/node`;!Jf(r,i)&&!Yf(i)&&o.push(`--ro-bind`,i,`/checker/node`);let c=a?.kind===`directory`?[`--tmpfs`,`/work/.git`]:a?.kind===`file`?[`--ro-bind`,`/dev/null`,`/work/.git`]:[];return{executable:Ff,args:[`--die-with-parent`,`--new-session`,`--unshare-all`,`--clearenv`,...o,`--proc`,`/proc`,`--dev`,`/dev`,`--tmpfs`,`/tmp`,`--dir`,`/tmp/home`,`--bind`,r,`/work`,...c,`--chdir`,`/work`,`--setenv`,`HOME`,`/tmp/home`,...a?.commit?[`--setenv`,`TANGLE_SOLVE_COMMIT`,a.commit]:[],`--setenv`,`TMPDIR`,`/tmp`,`--setenv`,`PATH`,`/checker:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,`--setenv`,`LANG`,`C.UTF-8`,`--setenv`,`PYTHONDONTWRITEBYTECODE`,`1`,`--setenv`,`XDG_CONFIG_HOME`,`/tmp/home/.config`,`--setenv`,`XDG_CACHE_HOME`,`/tmp/home/.cache`,`--setenv`,`XDG_DATA_HOME`,`/tmp/home/.local/share`,`--setenv`,`GIT_CONFIG_GLOBAL`,`/dev/null`,`--setenv`,`GIT_CONFIG_SYSTEM`,`/dev/null`,`--setenv`,`NPM_CONFIG_USERCONFIG`,`/dev/null`,s,...n]}}async function np(e,t){if(!t.command||t.command.includes(`/../`)||Lf(t.command))throw Error(`The competition checker command is invalid`);if(!Array.isArray(t.args))throw Error(`The competition checker arguments must be an array`);for(let e of t.args)Rf(e,`Checker argument`);let n=t.timeout_ms??15*6e4;if(!Number.isSafeInteger(n)||n<1e3||n>60*6e4)throw Error(`Checker timeout must be between one second and one hour`);let r=await $f(e),i;try{let e=await tp(r,t.command,t.args);i=await Pf(e.executable,e.args,{cwd:r,timeout:n,maxBuffer:4194304,encoding:`utf8`})}catch(e){let t=e,n=t.stderr?.trim()||t.stdout?.trim()||t.message||`checker failed`;throw Error(`Pinned checker failed: ${n}`)}let a=String(i.stdout),o=String(i.stderr);return{...Kf(await qf(r,t,a)),stdout:a,stderr:o}}async function rp(e,t){try{let{root:n,manifest:r}=await yd(e,t.directory),i=await wd(n),a=r.provenance?await Td(n,r,i,{allowMissing:!0}):void 0,o=Fu(),s=L(`Running ${r.title} checker…`);t.json||s.start();let c;try{c=await np(n,r.checker)}finally{s.stop()}let l=kd(c,a,r.provenance,void 0,{allowMissingSource:!0,requirePullRequest:!1}),u=xt(ne(32)),d=Af(c.candidateRef,u),f={version:1,competition:r.slug,candidateRef:c.candidateRef,evidence:l.evidence,evidenceJson:c.evidenceJson,evidenceRefs:l.evidenceRefs,salt:u,candidateId:d,...a?{source:a}:{},deviceAddress:o.account.address,clientSubmissionId:C(),createdAt:new Date().toISOString()};await Ad(D.join(n,`.tangle-solve-run.json`),f),t.json?P({localRun:f}):(F(`Checker output recorded locally for operator evaluation`),R({Competition:r.slug,Candidate:c.candidateRef,"Device address":o.account.address,"Evidence refs":l.evidenceRefs.length}),I("Commit any changes, then run `tangle solve submit` from this directory."),r.provenance&&!a&&I(`Add your GitHub fork as 'origin' before submitting. The task repository is available as '${_d}'.`))}catch(e){V(e)}}const ip=/^0x[0-9a-f]{64}$/i;async function ap(e){let t=await td({deviceAddress:e.deviceAddress,apiUrl:e.apiUrl,profile:e.profile}),n=await e.signer.signMessage({message:t.message});return{walletChallengeId:t.challengeId,walletSignature:n}}async function op(e,t){try{let{root:n,manifest:r}=await yd(e,t.directory);Qu({profile:t.profile});let i=await wd(n),a=await jd(n);if(a.competition!==r.slug)throw Error(`.tangle-solve-run.json does not match this competition`);if(!ip.test(a.salt)||!ip.test(a.candidateId))throw Error("This run predates durable candidate identity. Run `tangle solve run` again");let o=r.provenance?await Td(n,r,i):void 0;if(r.provenance&&a.source&&!Dd(a.source,o))throw Error("The saved run points to a different repository or revision. Keep your fork as 'origin' and run `tangle solve run` again before submitting");let s=Pu();if(!s)throw Error("No Solve device signer found. Run `tangle solve run` first");if(s.account.address.toLowerCase()!==a.deviceAddress.toLowerCase())throw Error("The local Solve device account changed after `tangle solve run`; run the checker again");let c=L(`Checking the committed candidate…`);t.json||c.start();let l;try{l=await np(n,r.checker)}finally{c.stop()}if(l.candidateRef!==a.candidateRef||l.evidenceJson!==a.evidenceJson)throw Error("The committed checker output changed after `tangle solve run`; run the checker again");if(Af(l.candidateRef,a.salt).toLowerCase()!==a.candidateId.toLowerCase())throw Error(`The saved candidate identity does not match the checker output; run the checker again`);let u=Xu(t.prUrl);if(!r.provenance&&u)throw Error(`This competition does not accept GitHub pull request provenance`);if(u){if(!o)throw Error(`A provenance policy is required for a pull request`);await Md({pullRequest:u,taskRepository:o.taskRepository,submissionRepository:o.submissionRepository,submissionRevision:i})}let d=kd(l,o,r.provenance,u,{requirePullRequest:!0}),f={...a,...o?{source:o}:{},chainState:{status:`submitting`,transactions:{...a.chainState?.transactions??{}}}},p=D.join(n,`.tangle-solve-run.json`);await Ad(p,f);let m=L(`Submitting candidate to Tempo…`);t.json||m.start();let h;try{h=await Nf(ud(r),s.account,{artifactRef:l.candidateRef,salt:a.salt,evidenceJson:l.evidenceJson,evidenceRefs:d.evidenceRefs},{resumeTransactions:f.chainState?.transactions,onTransaction:async(e,t)=>{f={...f,chainState:{status:`submitting`,transactions:{...f.chainState?.transactions??{},[e]:t}}},await Ad(p,f)}})}finally{m.stop()}f={...f,chainReceipt:h,chainState:{status:`accepted`,transactions:{...f.chainState?.transactions??{},...Nd(h)}}},await Ad(p,f);let g=await ap({deviceAddress:h.address,signer:s.account,apiUrl:t.apiUrl,profile:t.profile}),_=await ed({path:`/v1/submissions`,method:`POST`,apiUrl:t.apiUrl,profile:t.profile,body:{competition:r.slug,candidateRef:l.candidateRef,candidateId:h.candidateId,evidenceJson:l.evidenceJson,evidenceRefs:d.evidenceRefs,deviceAddress:h.address,reportTxHash:h.report,evaluationTxHash:h.evaluation,transactions:Nd(h),...r.provenance&&o?{source:{...o,...u?{pullRequest:u}:{}}}:{},clientSubmissionId:a.clientSubmissionId,...g,...t.model?{model:t.model}:{},...t.note?{note:t.note}:{}}});t.json?P({..._,transactions:Nd(h),candidateId:h.candidateId}):(F(`Submission accepted on Tempo`),R({Competition:r.slug,Candidate:h.candidateId,"Device address":h.address,"Report transaction":h.report,"Evaluation transaction":h.evaluation,"Submission ID":typeof _.id==`string`?_.id:_.submission?.id}))}catch(e){V(e)}}function sp(){let e=new b(`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(Id),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(rp),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(op),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(Lu);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(e=>Of(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((e,t)=>kf(e,t)),e}function cp(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function lp(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function up(e){return`'${e.replace(/'/g,`''`)}'`}function dp(e){return e===`win32`?`NUL`:`/dev/null`}function fp(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${up(`<token>`)}; ssh ${e.map(up).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${lp(`<token>`)} ssh ${e.map(lp).join(` `)}`}function pp(e){return e.connection!==void 0&&!e.connection.ssh}function mp(){Pt(`SSH is not enabled for this sandbox.`),I(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function hp(e,t=[],n=process.platform){let r=dp(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 gp(){return new b(`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}=W(n),a=L(`Getting SSH credentials...`);a.start();let o=await K(i,r,e);if(pp(o)){a.stop(),mp();return}o=await q(o);let s=await o.ssh();if(a.stop(),!s){mp();return}let c={...s,proxyCommand:cp(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let l=hp(c,[...n.identityFile?[`-i`,n.identityFile,`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(fp(l,process.platform));return}I(`Connecting via tunnel...`);let u=De(`ssh`,l,{stdio:`inherit`,env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:r.apiKey}});u.on(`error`,e=>{e.code===`ENOENT`&&(Pt(`SSH client not found. Please install OpenSSH.`),process.exit(1)),V(e)}),u.on(`exit`,e=>{process.exit(e??0)})})}function _p(){let e=new b(`ssh-keys`).description(`Manage SSH keys`);return e.command(`list`).description(`List SSH keys`).action(async e=>{let t=L(`Fetching SSH keys...`);try{t.start();let n=await U(H(e)).sshKeys.list();t.stop(),e.json?P({sshKeys:n}):n.length===0?I(`No SSH keys found.`):Bt([`Name`,`Type`,`Fingerprint`,`Created`],n.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){t.stop(),V(e)}}),e.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(e,t)=>{let n=L(`Adding SSH key...`);try{let r=pe(t.keyFile,`utf8`).trim();n.start();let i=await U(H(t)).sshKeys.create(e,r);n.stop(),t.json?P({sshKey:i}):F(`Added SSH key ${i.name} (${i.fingerprint})`)}catch(e){n.stop(),V(e)}}),e.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let n=L(`Deleting SSH key...`);try{n.start(),await U(H(t)).sshKeys.delete(e),n.stop(),F(`Deleted SSH key ${e}`)}catch(e){n.stop(),V(e)}}),e}function vp(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function yp(){return new b(`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||vp(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new Tt(new URL(e.replace(/^http/,`ws`)),{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),r;function i(){r&&=(clearInterval(r),void 0)}n.on(`open`,()=>{r=setInterval(()=>{n.readyState===Tt.OPEN&&n.ping()},15e3),r.unref?.(),process.stdin.on(`data`,e=>{n.readyState===Tt.OPEN&&n.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>n.close(1e3))}),n.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),n.on(`error`,e=>{i(),vp(`WebSocket error: ${e.message}`)}),n.on(`close`,e=>{i(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>n.close())})}function bp(){let e=new b(`team`).description(`Manage teams`);return $(e,`list`).description(`List teams for the current account`).action(async e=>{let t=H(e),n=U(t),r=e.json?null:L(`Fetching teams...`);r?.start();let i=await n.teams.list();if(r?.stop(),e.json){P({teams:i,activeTeamId:t.activeTeamId??null});return}N(i.map(e=>({active:e.id===t.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}])}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=t.json?null:L(`Creating team...`);i?.start();let a=await r.teams.create({name:e,orgId:t.orgId});if(t.switch&&Es(a,n.profile),i?.stop(),t.json){P({team:a,active:!!t.switch});return}F(`Team created: ${Cs(a)}`),t.switch&&F(`Active team set to ${a.name}`)}),$(e,`switch <team>`).description(`Set the active team for the current profile`).action(async(e,t)=>{let n=H(t),r=await ws(U(n),e);if(Es(r,n.profile),t.json){P({team:r,activeTeamId:r.id});return}F(`Active team set to ${Cs(r)}`)}),e.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(e=>{let t=pr(e.profile);if(e.json){P(t.activeTeamId?t:{activeTeamId:null});return}if(!t.activeTeamId){console.log(`No active team.`);return}R({ID:t.activeTeamId,Name:t.activeTeamName})}),e.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(e=>{if(Ds(e.profile),e.json){P({activeTeamId:null});return}F(`Active team cleared.`)}),$(e,`members [team]`).description(`List team members`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listMembers(i.id);if(t.json){P({team:i,members:a});return}N(a,[{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}])}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=xp(t.role),o=await r.teams.updateMember(i.id,e,{role:a});if(t.json){P({team:i,member:o});return}F(`Member updated: ${o.customerEmail}`),R({Team:i.name,Role:o.role,Status:o.status})}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=xp(t.role),o=await r.teams.invite(i.id,{email:e,role:a,ttlHours:t.ttlHours?Number.parseInt(t.ttlHours,10):void 0});if(t.json){P({team:i,invitation:o});return}F(`Invitation created for ${o.email}`),R({Team:i.name,Role:o.role,Expires:o.expiresAt,"Invitation ID":o.id}),F(`Re-run with --json to retrieve the invitation token for sharing.`)}),$(e,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile);if(!(!t.force&&!t.json&&!await $r(`Leave team '${i.name}'? (y/N) `,`--force`))){if(await r.teams.leave(i.id),n.activeTeamId===i.id&&Ds(n.profile),t.json){P({success:!0,teamId:i.id});return}F(`Left team: ${i.name}`)}}),$(e,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,t,r.profile);if(!(!n.force&&!n.json&&!await $r(`Transfer ownership of '${a.name}' to ${e}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await i.teams.transferOwnership(a.id,e),n.json){P({success:!0,teamId:a.id,newOwnerCustomerId:e});return}F(`Ownership transferred for ${a.name}`)}}),e.addCommand(Sp()),e.addCommand(Cp()),$(e,`invitations [team]`).description(`List pending and historical team invitations`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listInvitations(i.id);if(t.json){P({team:i,invitations:a});return}N(a,[{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}])}),$(e,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(e,t)=>{let n=H(t),r=U(n),i=await r.teams.acceptInvitation(e),a=t.switch===!1?null:await r.teams.get(i.teamId);if(a&&Es(a,n.profile),t.json){P({member:i,activeTeamId:a?.id??null});return}F(`Invitation accepted for team ${i.teamId}`),a&&F(`Active team set to ${a.name}`)}),$(e,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(e,t)=>{if(await U(H(t)).teams.revokeInvitation(e),t.json){P({success:!0,invitationId:e});return}F(`Invitation revoked: ${e}`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(await r.teams.removeMember(i.id,e),t.json){P({success:!0,teamId:i.id,memberId:e});return}F(`Member removed: ${e}`)}),e}function xp(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function Sp(){let e=new b(`secret`).description(`Manage team secrets`);return $(e,`list [team]`).description(`List team secret names`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listSecrets(i.id);if(t.json){P({team:i,secrets:a});return}N(a,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),$(e,`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(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,n.team,r.profile),o=await Du({value:t,valueStdin:n.valueStdin,prompt:`Enter value for team secret '${e}': `}),s=await i.teams.upsertSecret(a.id,e,o);if(n.json){P({team:a,secret:s});return}F(`Team secret saved: ${s.name}`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(!(!t.force&&!t.json&&!await $r(`Delete team secret '${e}' from '${i.name}'? (y/N) `,`--force`))){if(await r.teams.deleteSecret(i.id,e),t.json){P({success:!0,teamId:i.id,name:e});return}F(`Team secret deleted: ${e}`)}}),$(e,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=await r.teams.revealSecret(i.id,e);if(t.json){P({teamId:i.id,...a});return}console.log(a.value)}),e}function Cp(){let e=new b(`templates`).description(`Manage team golden-path templates`);return $(e,`list [team]`).description(`List a team's golden-path templates`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listTemplates(i.id);if(t.json){P({team:i,templates:a});return}if(a.length===0){console.log(`No templates yet for ${i.name}.`);return}N(a.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}])}),$(e,`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(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,n.team,r.profile),o;if(n.config)try{let e=JSON.parse(n.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);o=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let s=await i.teams.createTemplate(a.id,{name:e,snapshotId:t,description:n.description,environment:n.environment,config:o});if(n.json){P({team:a,template:s});return}F(`Team template created: ${s.name} (${s.id})`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(!(!t.force&&!t.json&&!await $r(`Delete template '${e}' from '${i.name}'? (y/N) `,`--force`))){if(await r.teams.deleteTemplate(i.id,e),t.json){P({success:!0,teamId:i.id,templateId:e});return}F(`Team template deleted: ${e}`)}}),e}function $(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function wp(e,t,n){let r=new AbortController,i=()=>r.abort();try{let n=U(H({...e,timeout:void 0}));process.once(`SIGINT`,i),process.once(`SIGTERM`,i);let a=await t(n,{...e.timeout===void 0?{}:{timeoutMs:Number(e.timeout)*1e3},resumeJobId:e.resumeJob,signal:r.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,i),process.off(`SIGTERM`,i)});e.json?P(a):F(`template`in a?`Published template: ${a.template.slug}`:`Published template version: ${a.version.id}`)}catch(t){if(t instanceof o&&t.status!==401&&t.job&&[`pending`,`scanning`,`ready`].includes(t.job.status)){let e=[`tangle`,`template`,...n,`--resume-job`,t.job.id].map(He).join(` `);Object.assign(t,{fix:{command:e}})}V(t,e.json)}}function Tp(){let e=new b(`template`).description(`Manage published public templates`);return e.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async e=>{let t=U(H(e)),n=e.featured?await t.publicTemplates.featured():await t.publicTemplates.list({query:e.query,tag:e.tag});if(e.json){P({templates:n});return}N(n,[{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}])}),e.command(`get <id-or-slug>`).action(async(e,t)=>{let n=await U(H(t)).publicTemplates.get(e);if(t.json){P({template:n});return}P(n)}),e.command(`versions <id-or-slug>`).action(async(e,t)=>{let n=await U(H(t)).publicTemplates.versions(e);if(t.json){P({versions:n});return}N(n.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`snapshotId`,header:`Snapshot`,width:20},{key:`createdAt`,header:`Created`,width:24}])}),e.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <seconds>`,`Maximum wait for publication`).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)=>wp(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])),e.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <seconds>`,`Maximum wait for publication`).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)=>wp(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])),e}function Ep(){let e=new b(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return e.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 e=>{try{let t={from:e.from,to:e.to,model:e.model,runId:e.run,status:e.status===void 0?void 0:Lp(e.status),q:e.query,cursor:e.cursor,limit:e.limit===void 0?void 0:Hp(e.limit)},n=Op(e),r=e.json?null:L(`Fetching traces...`);r?.start();let i=await n.listTraces(t);if(r?.stop(),e.json)return P(i);jp(i.items),Fp(i.nextCursor)}catch(t){Ap(t,e)}}),e.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(e,t)=>{try{let n=Op(t);if(t.ndjson){await kp(n,e);return}let r=t.json?null:L(`Fetching trace spans...`);r?.start();let i=await n.getTraceSpans(e,{cursor:t.cursor,limit:t.limit===void 0?void 0:Hp(t.limit)});if(r?.stop(),t.json)return P(i);Mp(i.items),i.truncated&&R({Spans:`${i.items.length} of ${i.total} (truncated)`}),Fp(i.nextCursor)}catch(e){Ap(e,t)}}),e.addCommand(Dp()),e}function Dp(){let e=new b(`runs`).description(`Read eval-runs pivoted off the trace surface`);return e.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 e=>{try{let t={status:e.status===void 0?void 0:zp(e.status),gate:e.gate===void 0?void 0:Vp(e.gate),label:e.label,from:e.from,to:e.to,q:e.query,cursor:e.cursor,limit:e.limit===void 0?void 0:Hp(e.limit)},n=Op(e),r=e.json?null:L(`Fetching runs...`);r?.start();let i=await n.listRuns(t);if(r?.stop(),e.json)return P(i);Np(i.items),Fp(i.nextCursor)}catch(t){Ap(t,e)}}),e.command(`get <runId>`).description(`Show a single eval-run`).action(async(e,t)=>{try{let n=Op(t),r=t.json?null:L(`Fetching run...`);r?.start();let i=await n.getRun(e);if(r?.stop(),t.json)return P(i);Pp(i)}catch(e){Ap(e,t)}}),e}function Op(e){let t=rr(e.apiKey);if(!t)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return Et({apiKey:t,baseUrl:e.baseUrl??process.env.TANGLE_INTELLIGENCE_BASE_URL})}async function kp(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 Ap(e,t){return V(e,t.json===!0)}function jp(e){N(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:Ip(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 Mp(e){N(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 Np(e){N(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 Pp(e){R({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 Fp(e){e&&R({"Next page":`--cursor ${e}`})}function Ip(e){return e===null?`-`:`$${e.toFixed(4)}`}function Lp(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const Rp=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function zp(e){let t=Rp.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${Rp.join(`, `)}`)}const Bp=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function Vp(e){let t=Bp.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Bp.join(`, `)}`)}function Hp(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Up(){return new b(`usage`).description(`Show account usage and billing information`).action(async e=>{let{client:t}=W(e),n=e.json?null:L(`Fetching usage...`);n?.start();let[r,i]=await Promise.all([t.usage(),t.subscription().catch(()=>null)]);n?.stop(),e.json?P({...r,subscription:i}):(console.log(),console.log(`Account Usage`),console.log(`─`.repeat(40)),R({"Active Sandboxes":r.activeSandboxes,"Total Sandboxes":r.totalSandboxes,"Compute Minutes":Wp(r.computeMinutes),"GPU Seconds":r.gpuSeconds,"GPU Spend":Gp(r.gpuCostUsd)}),i&&(console.log(),console.log(`Subscription`),console.log(`─`.repeat(40)),R({Plan:i.plan,Status:i.status,"Credits Available":Gp(i.creditsAvailableUsd),"Credits Used":Gp(i.creditsUsedUsd),"Monthly Balance":Gp(i.monthlyBalanceUsd)})),console.log(),console.log(`Billing Period`),console.log(`─`.repeat(40)),R({Start:r.periodStart.toLocaleDateString(),End:r.periodEnd.toLocaleDateString()}),console.log())})}function Wp(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 Gp(e){return e<0?`-$${(-e).toFixed(2)}`:`$${e.toFixed(2)}`}function Kp(){return new b(`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){Yn(),I(`Cleared the active sandbox.`);return}if(e){Jn(e),I(`Active sandbox set to ${e}. Commands now default to it; override with --box or TANGLE_SANDBOX.`);return}let n=qn();I(n?`Active sandbox: ${n}`:"No active sandbox. Set one with `tangle use <id>`.")})}function qp(e){N(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 Jp(e){e.command(`artifacts`).description(`List a run's artifact metadata (never the bytes)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(e,t,n)=>{let r=await(await X(n)).workflows.listArtifacts(e,t);if(n.json)return P(r);qp(r.artifacts)}),e.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(e,t,n,r)=>{let i=await(await X(r)).workflows.downloadArtifact(e,t,n),a=r.out??n;try{he(a,i.bytes)}catch(e){throw Error(`Could not write artifact to "${a}": ${e instanceof Error?e.message:String(e)}`)}if(r.json)return P({file:a,contentType:i.contentType,bytes:i.bytes.length});I(`Wrote ${a} (${i.bytes.length} bytes, ${i.contentType}).`)})}function Yp(e){N(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 Xp(e){e.command(`decisions`).description(`List a workflow's pending human decisions`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{let n=(await(await X(t)).workflows.listPendingDecisions()).decisions.filter(t=>t.workflowId===e);if(t.json)return P({decisions:n});Yp(n)}),e.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(e,t,n)=>{let r=await X(n),i=await r.workflows.getRunDecision(e,t),a=await r.workflows.resolveRunDecision(e,t,{decisionId:i.id,choice:n.choice});if(n.json)return P(a);if(a.resumed){I(`Resolved decision ${a.decisionId} with "${a.choice}" — run ${a.runId} resumed.`);return}I(`Resolved decision ${a.decisionId} with "${a.choice}", but run ${a.runId} had already finished — nothing to resume.`)})}function Zp(e){try{return pe(e,`utf8`)}catch(t){throw Error(`Could not read workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Qp(e){N(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 $p(e){let t=e.workflows.filter(e=>e.failed>0).length,n=e.workflows.filter(e=>e.failed===0&&e.waiting>0).length,r=e.workflows.filter(e=>e.failed===0&&e.waiting===0&&e.runsInWindow>0).length;I(`${t} failing · ${n} waiting · ${r} healthy · ${e.workflows.length} total over ${e.window}`),N(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 em(e){if(R({ID:e.id,Name:e.name,Description:e.description??``,Enabled:e.enabled?`yes`:`no`,Actions:e.actions.length}),e.triggers&&e.triggers.length>0&&(I(`Triggers`),tm(e.triggers)),e.validationErrors.length>0){I(`Validation issues`);for(let t of e.validationErrors)console.log(` ${t.path}: ${t.message}`)}}function tm(e){N(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 nm(e){e.command(`list`).description(`List your workflows`).action(async e=>{let t=await(await X(e)).workflows.list();if(e.json)return P(t);Qp(t)}),e.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 e=>{let t=await(await X(e)).workflows.fleetInsights({window:e.window});if(e.json)return P(t);$p(t)}),e.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(e,t)=>{let n=await(await X(t)).workflows.get(e);if(t.yaml){if(n.definitionYaml===null)throw Error(`Workflow ${n.id} has no stored definition YAML to export`);process.stdout.write(n.definitionYaml.endsWith(`
|
|
162
|
+
<script>${a(r)}<\/script></body></html>`,c=O(await We(O(we(),`tangle-graph-`)),`${o}.html`);return await Je(c,s,{mode:384}),c}function Hc(e,t,n){e.command(`show <name-or-file>`).description(`Draw a graph file: labelled nodes, routes, loops and stops`).option(`--open`,`Write one offline page and open it in the browser`).action(async(e,r)=>{let i=await qe(t(e,process.cwd())),a=Rc(i,await Ke(i,`utf8`));if(r.json)return P(a);if(!r.open)return console.log(Bc(a));let o=await Vc(a,n);I(await Ti(Qe(o).href)?`Opened ${o}`:`Open ${o}`)})}async function Uc(e){if(!rr(e.apiKey)){if(e.json||e.dryRun||!process.stdin.isTTY)return;await Pi({baseUrl:e.sandboxBaseUrl,signal:e.signal})}return G(e)}async function Wc(e,t,n){let r=cl(t.parameter),i=n??await Uc(t);if(!i)throw new z(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured`,`tangle auth login`);let a=await i.connections.start(e,{cli:!0,connectionParameters:r});return t.json?(P(ul(a)),a):(ll(a,t.browser===!1?!1:await Ti(a.redirectUrl),t.wait),a)}async function Gc(e,t,n){let r=async()=>{n.signal?.throwIfAborted();let{connections:r}=await e.connections.list(),i=r.filter(e=>e.status===`active`&&e.providerId.toLowerCase()===t.trim().toLowerCase());return i.length?Cr(i,t):void 0},i=await r();if(i||n.json||n.dryRun||!process.stdin.isTTY)return i;let a=await Wc(t,{...n,wait:!0},e);for(;!i&&Date.now()<Date.parse(a.expiresAt);)await Ne(1e3,void 0,{signal:n.signal}),i=await r();return i}function Kc(){let e=new b(`hub`).description(`Discover and run Tangle Hub tools`);e.command(`connect`).description(`Connect a provider account`).argument(`provider`,`Provider to connect`).option(`--no-browser`,`Print the authorization URL instead of opening it`).option(`--parameter <key=value>`,`Provider-specific OAuth value. Repeatable.`,(e,t)=>[...t,e],[]).action(async(e,t)=>{await Wc(e,t)});let t=new b(`connections`).description(`List Hub provider connections`).action(async e=>{let t=await(await G(e)).connections.list();if(e.json){P(t);return}sl(t.connections)});t.command(`revoke <connection-id>`).description(`Revoke a Hub provider connection`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await G(t),r=await Sr(n,e);if(!t.force&&!await $r(`Revoke Hub connection ${r}? `,`--force`)){I(`Revoke cancelled.`);return}let i=await n.connections.revoke(r);if(t.json){P(i);return}I(`Revoked Hub connection ${i.connection.id}.`)}),e.addCommand(t);let n=new b(`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 e=>{if(!e.connection)throw Error(`--connection is required.`);let t=await G(e),n=await Sr(t,e.connection),r=await t.permissions.list(n);if(e.json){P(r);return}nl(r.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 e=>{if(!e.connection)throw Error(`--connection is required.`);if(!e.action)throw Error(`--action is required.`);let t=rl(e.decision),n=await G(e),r=await Sr(n,e.connection),i=await n.permissions.set({connectionId:r,actionPath:e.action,decision:t});if(e.json){P(i);return}nl([i.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 e=>{if(!e.connection)throw Error(`--connection is required.`);let t=await G(e),n=await Sr(t,e.connection),r=await t.permissions.revertWrites(n);if(e.json){P(r);return}I(`Reverted ${r.reverted} write permission${r.reverted===1?``:`s`} for connection ${r.connectionId}.`)}),e.addCommand(n),e.addCommand(Jc());let r=new b(`tools`).description(`Discover Hub tools`);return r.command(`sources`).description(`List Hub tool sources`).action(async e=>{let t=await(await G(e)).tools.sources();if(e.json){P(t);return}il(t.sources)}),r.command(`describe`).description(`Describe a Hub tool`).argument(`path`,`Executor tool path`).action(async(e,t)=>{let n=await(await G(t)).tools.describe(e);if(t.json){P(n);return}al(n.tool)}),r.command(`search`).description(`Search Hub tools`).argument(`<query...>`,`Search query`).option(`--provider <provider>`,`Filter by provider/source ID`).action(async(e,t)=>{let n=await(await G(t)).tools.search(e.join(` `),{provider:t.provider});if(t.json){P(n);return}tl(n.tools)}),e.addCommand(r),e.addCommand(qc(`call`)),e.addCommand(qc(`exec`)),e.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(Xc(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 G(t);Qc(t.decline?await n.approvals.deny(e):await n.approvals.approve(e),t.json===!0)}),e.command(`status`).description(`Show Hub auth and connection status`).action(async e=>{let t=await(await G(e)).status();if(e.json){P(t);return}dl(t)}),e}function qc(e){return new b(e).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(e,t)=>{let{args:n,approve:r}=Yc(e,t),{path:i,input:a}=el(n),o=await G(t),s=t.connection?await Sr(o,t.connection):void 0;P((await o.tools.invoke(i,a,{connectionId:s,approve:r})).result)})}function Jc(){let e=new b(`approvals`).description(`List and resolve Hub execution approvals`);e.command(`list`).description(`List pending Hub execution approvals`).action(async e=>{let t=await(await G(e)).approvals.list();if(e.json){P(t);return}Zc(t.approvals)});for(let t of[`approve`,`deny`])e.command(t).description(`${t===`approve`?`Approve`:`Deny`} a pending Hub execution approval`).argument(`approval-id`,`Hub approval ID`).action(async(e,n)=>{Xc(e),Qc(await(await G(n)).approvals[t](e),n.json===!0)});return e}function Yc(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 Xc(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`Hub approval ID must contain only letters, numbers, underscores, and dashes.`)}function Zc(e){N(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 Qc(e,t){if(t){P($c(e));return}I(`Hub approval ${e.approval.id} ${e.approval.status}.`),e.capabilityToken&&I("Capability token minted. Re-run the original command with `--approve` to execute automatically.")}function $c(e){return{approval:e.approval,...e.capabilityToken?{capabilityToken:{tokenId:e.capabilityToken.tokenId,expiresAt:e.capabilityToken.expiresAt}}:{}}}function el(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 tl(e){N(e.map(e=>({...e,provider:e.providerId??e.requiredConnectionProviderId,connection:ol(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 nl(e){N(e,[{key:`connectionId`,header:`Connection`},{key:`providerId`,header:`Provider`},{key:`actionPath`,header:`Action`},{key:`decision`,header:`Decision`},{key:`updatedAt`,header:`Updated`}])}function rl(e){if(e===`allow`||e===`ask`||e===`deny`)return e;throw Error(`--decision must be one of: allow, ask, deny.`)}function il(e){N(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 al(e){R({Path:e.path,Provider:e.providerId??e.requiredConnectionProviderId,Title:e.title,Description:e.description,Connection:ol(e),Policy:e.policyState}),e.inputSchema!==void 0&&(I(`Input schema`),console.log(JSON.stringify(e.inputSchema,null,2))),e.outputSchema!==void 0&&(I(`Output schema`),console.log(JSON.stringify(e.outputSchema,null,2)))}function ol(e){if(e.connectionRequired===!1)return`not required`;if(e.connectionStatus)return e.connectionStatus}function sl(e){N(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 cl(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 ll(e,t,n=!1){t?I(`Opened browser to connect ${e.provider}.`):(I(`Open this URL to connect ${e.provider}:`),console.log(e.redirectUrl)),I(n?`Finish authorization in the browser; this run resumes when connected.`:"Finish authorization in the browser, then rerun `tangle hub status`.")}function ul(e){return{provider:e.provider,redirectUrl:e.redirectUrl,expiresAt:e.expiresAt,scopes:e.scopes,cli:e.cli}}function dl(e){let{principal:t,connections:n}=e;I(`Hub status`),R({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&&I(`Some providers require reconnect.`)}const fl=[`claude-code`,`opencode`,`codex`,`kimi-code`,`prime`],pl=process.env.TANGLE_ROUTER_URL??`https://router.tangle.tools/v1`;function ml(e){let t=se(e);if(t)return t;throw Error(`--model '${e}' has no provider. Pass a canonical id, for example 'google/${e}'.`)}function hl(e){let t=e.harness??`claude-code`;if(!fl.includes(t))throw Error(`Unknown --harness '${t}'. Supported: ${fl.join(`, `)}.`);let n=gl(e.maxTokens,2e5,`--max-tokens`),r=gl(e.maxIterations,50,`--max-iterations`),i=e.maxWorkers===void 0?void 0:gl(e.maxWorkers,0,`--max-workers`);return{harness:t,...e.model?{model:e.model}:{},maxTokens:n,maxIterations:r,...i===void 0?{}:{maxWorkers:i}}}function gl(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 _l(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 vl(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 yl=null;function bl(){return yl??=import(`@tangle-network/agent-runtime/kernel`).catch(e=>{throw yl=null,e?.code===`ERR_MODULE_NOT_FOUND`?new z(`RUNTIME_UNAVAILABLE`,`Agent Runtime could not be loaded`,e.message,`npm install -g @tangle-network/sandbox-cli@latest`):e}),yl}async function xl(e,t,n){let r=H({apiKey:n.apiKey,baseUrl:n.baseUrl}),i=U(r),{budget:a,perWorker:o}=_l(t),s=[],c={async create(e){let{TANGLE_API_KEY:t,...r}=e?.env??{},a=await i.create(e?.env?{...e,env:r}:e);return s.push({id:a.id,status:`spawned`}),n.json||I(`worker ${a.id} spawned`),a}},l=await bl(),u=l.workerFromBackend({backend:`sandbox`,sandboxClient:c,maxIterations:1}),d=(e,n)=>u({...e,harness:t.harness},n),f={name:`supervisor`,harness:`cli-base`,model:{default:t.model??`gemini-2.5-flash-lite`,provider:t.model?ml(t.model):`google`},tools:{agent_runtime_coordination_spawn_worker:!0,agent_runtime_coordination_observe_agent:!0}},p={routerBaseUrl:pl,routerKey:r.apiKey},m=vl(await l.supervise(f,{goal:e},{budget:a,makeWorkerAgent:d,router:p,...o?{perWorker:o}:{},...t.model?{allowedModels:[t.model]}:{},runId:`supervise-${C()}`})),h=m.status===`winner`?`settled`:`failed`;for(let e of s)e.status=h,n.json||I(`worker ${e.id} settled (${e.status})`);return{task:e,result:m.text,workers:s,tokenUsage:m.tokenUsage,costUsd:m.costUsd,status:m.status}}function Sl(){let e=new b(`supervise`);return e.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 (${fl.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(e,t)=>{let n=hl({harness:t.harness,model:t.model,maxTokens:t.maxTokens,maxIterations:t.maxIterations,maxWorkers:t.maxWorkers});t.json||(I(`Supervising: ${e}`),I(`harness=${n.harness} budget=${n.maxTokens}tok/${n.maxIterations}it`),console.log());let r=await xl(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,json:t.json});if(t.json){P(r),r.status!==`winner`&&(process.exitCode=1);return}if(console.log(),r.result&&(console.log(r.result),console.log()),R({"Input Tokens":r.tokenUsage.input??`Unavailable`,"Output Tokens":r.tokenUsage.output??`Unavailable`,Cost:r.costUsd===null?`Unavailable`:`$${r.costUsd.toFixed(4)}`}),r.status!==`winner`)throw Error(`Supervisor finished without a winner: ${r.status}`)}),e}const Cl=t(import.meta.url);if(!Cl)throw Error(`Tangle CLI package metadata was not found`);const wl=_e(Cl),Tl=e=>S(`sha256`).update(e).digest(`hex`);function El(e,t){let n=be(e,t);return n!==`..`&&!n.startsWith(`..${Se}`)&&!ye(n)}function Dl(e,t){if(/[\\/]/.test(e)||/\.(yaml|yml|json)$/.test(e))return xe(t,e);let n=t;for(;!de(O(n,`.git`))&&_e(n)!==n;)n=_e(n);de(O(n,`.git`))||(n=t);let r=[`yaml`,`yml`,`json`].flatMap(e=>[`graph.${e}`,e]),i=[n,k()].flatMap(t=>r.map(n=>O(t,`.tangle/graphs/${e}.${n}`))),a=i.find(de);if(a)return a;throw new z(`GRAPH_NOT_FOUND`,`Graph '${e}' was not found`,`Looked in ${i.join(`, `)}`,`tangle graph --help`)}async function Ol(e,t){return nc(e.signal,async n=>{let r=e.runId??C(),i;try{let a=O(k(),`.tangle`,`runs`,r);await Ue(a,{recursive:!0,mode:448});let o=await qe(O(k(),`.tangle`)),s=await qe(e.cwd??process.cwd()),c=[`runs`,`graph-registry`,`graphs`].some(e=>El(s,O(o,e))||El(O(o,e),s))?O(k(),`.tangle`,`workspaces`,r):s;await Ue(c,{recursive:!0,mode:448});let l;return await t({runId:r,runDir:a,cwd:c,bridge:e=>l??=(async()=>{n.throwIfAborted();let t=ne(32).toString(`hex`),{loadConfig:r,startServer:o}=await import(`cli-bridge`),s=O(wl,`dist`,`stdio.mjs`),l=r({...process.env,BRIDGE_HOST:`127.0.0.1`,BRIDGE_BEARER:t,BRIDGE_DATA_DIR:O(a,`bridge`),BRIDGE_BACKENDS:uc,BRIDGE_JAIL_MODE:`fs-jail`,BRIDGE_JAIL_FALLBACK:`deny`,BRIDGE_JAIL_NETWORK:`relay`,BRIDGE_SUBSCRIPTIONS_ONLY:`1`});e&&l.jailReadablePaths.push(s),i=await o({cwd:c,config:{...l,port:0},handleSignals:!1,quiet:!0,hub:e?{client:e,hash:tc,serverForGrant:e=>{if(!i)throw Error(`Hub host is not ready`);return{transport:`stdio`,command:process.execPath,args:[{kind:`public`,value:s}],env:{TANGLE_HUB_MCP_ENDPOINT:{kind:`public`,value:`${i.url}/hub/mcp/grants/${e}`}}}}}:void 0});let{graphNativeCapture:u}=await import(`./graph-native-af-gs1TS.mjs`);return{harnessTranscript:u({bridgeUrl:i.url,bridgeBearer:t,cwd:c}),backend:`bridge`,bridgeUrl:i.url,bridgeBearer:t,cwd:c}})(),signal:n})}catch(t){throw t instanceof Error&&Object.assign(t,{runId:e.errorRunId??r}),t}finally{await i?.close()}},e.fix??`tangle graph --help`)}async function kl(e,t,n={}){let r=[`tangle graph run`,He(e),...t.dryRun?[`--dry-run`]:[],...t.cloud?[`--cloud`]:[],...t.resume?[`--resume`,He(t.resume)]:[],...t.seat?[`--seat`,He(t.seat)]:[],...t.param.flatMap(e=>[`--param`,He(e)])].join(` `);return await nc(n.signal,async i=>{i.throwIfAborted();let a=await qe(Dl(e,n.cwd??process.cwd())),o=n.source??await Ke(a,`utf8`);if(!t.resume&&t.cloud||t.resume?.startsWith(`wfrun_`))return Dc(a,o,t,i);let s=await bl(),c=Tl(o),l=Object.entries(xc(t.param,`param`)??{}),u=Object.fromEntries(l.filter(([e])=>!e.startsWith(`gate.`))),d=Object.fromEntries(l.filter(([e])=>e.startsWith(`gate.`)).map(([e,t])=>[e.slice(5),t])),f=t.resume?await sc(t.resume):void 0,p=s.graphRegistry(O(k(),`.tangle`,`graph-registry`)),m;if(f){f.file!==a&&Y(`The recorded graph source path changed`);let e=await s.loadGraph(p,f.graphDigest);e||Y(`The recorded executable graph is unavailable`),m=s.validateStoredGraph(e),lc(f,t,c,u,d)}let h={apiKey:t.apiKey,sandboxBaseUrl:t.baseUrl,signal:i,json:t.json,dryRun:t.dryRun&&!n.connectNeeds},g,_=()=>g??=Uc(h),v=new Map,ee=e=>{let t=e.trim().toLowerCase(),n=v.get(t)??(async()=>{let e=await _(),n=e&&await Gc(e,t,h);return n?{connectionId:n,capabilities:[`*`]}:void 0})();return v.set(t,n),n},y=async e=>{if(i.throwIfAborted(),f&&m)return rc(m,f.gateChoices??{}),{graph:m,params:f.params};let r=await s.loadGraphFile(a,{source:o,seat:t.seat??Hn().seat,resolveSeat:dc(e,i),resolveNeed:ee,params:u,cwd:e,signal:i});if(i.throwIfAborted(),rc(r.graph,d),n.graphDigest&&r.graph.digest!==n.graphDigest)throw new z(`GRAPH_CHANGED`,`The validated graph changed before execution`,`Its compiled graph digest no longer matches validation`,`tangle graph run --help`);return r},te=n.cwd??process.cwd(),b=await y(f?.cwd??te);if(t.dryRun)return b;let x=f?.runId??n.runId??C(),S=f?.cwd??await s.graphWorkspace(b.graph,{cwd:te,runId:x});return Ol({...n,runId:x,cwd:S,signal:i,fix:r},async({runId:e,runDir:n,cwd:r,bridge:o})=>{let{superviseGraphPursuit:l,readSettleRecord:u}=await import(`@tangle-network/agent-runtime/durable`),m=await s.recordStoredGraphRun(p,b.graph),h=f??{version:1,runId:e,cwd:r,file:a,graphDigest:m.digest,sourceDigest:c,params:b.params,...Object.keys(d).length?{gateChoices:d}:{},startedAt:new Date().toISOString(),...t.seat===void 0?{}:{seat:t.seat}};f||await cc(n,h);let g=f?await u(n):void 0;if(g&&g.tree.root!==e&&Y(`The settlement names another run`),g?.kind===`no-winner`&&Y(`The local run is terminal: ${g.reason}`),g)return{runId:e,graphDigest:m.digest,sourceDigest:c,...vl(g),replayed:!0};let v=s.graphFromStored(m),ee=m.nodes.some(e=>e.profile.connections?.length),y=ee?await _():void 0;if(ee&&!y)throw new z(`AUTH_REQUIRED`,`Hub authentication is required`,`No Tangle credential is configured for this local graph`,`tangle auth login`);let te=await o(y),x=h.startedAt;I(`Run ${e} · ${ge(a)} · ${r}`);let S=await Al(n);I(`Viewer ${S.url}`);let ne=new AbortController,C=await l(v,{pursuitId:m.digest,runDir:n,runId:e,backend:te,...v.entry===void 0?{driverBackend:te}:{},...m.gates?.length?{decideGate:ic(h.gateChoices??{},{json:t.json,signal:AbortSignal.any([i,ne.signal])})}:{},resume:!!f,signal:i,profileSecurity:{allowConnections:ee,allowLocalMcp:!1,allowHooks:!1,allowedMcpHosts:[]}}).finally(async()=>{ne.abort(),await S.close()}),re={runId:e,graphDigest:m.digest,sourceDigest:c,...vl(C.result.result)},w=C.result.result,{tokens:T,tokensKnown:ie,iterations:ae,ms:oe}=w.spentTotal;if(await s.recordStoredGraphRun(p,m,{graphDigest:m.digest,evidence:[{kind:`authored-graph`,url:`urn:sha256:${m.digest}`},{kind:`authored-yaml`,url:`urn:sha256:${c}`}],taskDigest:s.taskShapeDigest({graph:ge(a),params:b.params}),startedAt:x,finishedAt:new Date().toISOString(),outcome:w.kind===`no-winner`?{kind:`no-winner`,reason:w.reason}:{kind:`delivered`,summary:re.text},cost:{iterations:ae,ms:oe,...ie===!1?{}:{tokens:T.input+T.output},...re.costUsd===null?{}:{usd:re.costUsd}},traversals:C.result.ledger.length,exhaustedEdges:C.result.exhaustedEdges,source:{kind:`tangle-cli-graph`,id:e}}),w.kind===`no-winner`)throw Object.assign(new z(`GRAPH_RUN_FAILED`,`Graph '${ge(a)}' finished without a result`,C.result.stopped?.reason||C.result.ledger.filter(e=>e.outcome===`unpropagated`&&e.reason).pop()?.reason||w.reason,`tangle graph inspect ${e}`),{runId:e,runtimeFailures:[...w.tree.nodes.filter(e=>e.failure).map(e=>({node:e.label,failure:e.failure})),...w.reason===`driver-failed`&&w.error.failure?[{node:`root`,failure:w.error.failure}]:[]]});return re})},r)}async function Al(e){let{serveTopWeb:t}=await import(`@tangle-network/agent-runtime/tui`),{readGraphSessions:n}=await import(`./graph-native-af-gs1TS.mjs`);return t({roots:[e],assets:O(wl,`dist`,`graph-viewer`),readSessions:n})}async function jl(e,t){if(e.startsWith(`wfrun_`)){let n=await X(t),r=await n.workflows.getRun(e);return t.json?P(r):I(`Run ${e} · ${n.baseUrl}/app/workflows/${encodeURIComponent(r.workflowId)}/runs/${encodeURIComponent(e)}`)}let n=O(k(),`.tangle`,`runs`,e);if(!/^[a-f0-9-]{36}$/i.test(e)||!de(n))throw new z(`RUN_NOT_FOUND`,`Run '${e}' was not found`,`Use a run ID printed by tangle graph run`,`tangle graph inspect --help`);let{loadTopSnapshot:r}=await import(`@tangle-network/agent-runtime/tui`);if(t.json)return P(await r(process.cwd(),{runDir:n}));I(`Run ${e} · ${(await Al(n)).url}`)}function Ml(){let e=new b(`graph`).description(`Build and run portable agent graphs`);return Nc(e),vc(e),Hc(e,Dl,wl),e.command(`inspect <run>`).description(`Inspect a live or retained graph run`).action(jl),e.command(`run <name-or-file>`).description(`Run a saved graph over native subscriptions`).option(`--cloud`,`Run through Tangle's durable cloud workflow owner`).option(`--resume <run>`,`Resume this run's saved graph and durable execution`).option(`--seat <seat>`,`Use harness/model@effort for every node`).option(`--param <key=value>`,`Graph parameter or gate.<id>=<choice>; repeatable`,(e,t)=>[...t,e],[]).option(`--dry-run`,`Validate and print the graph without starting agents`).action(async(e,t)=>{let n=await kl(e,t);t.json||t.dryRun?P(n):`status`in n?(I(`${n.status} · ${n.runId}`),n.text&&console.log(n.text)):`viewerUrl`in n&&I(`Run ${n.runId} · ${n.viewerUrl}`)}),e}function Nl(){let e=new b(`intelligence`).description(`Create and inspect trace intelligence reports`);return e.command(`connect [agent]`).alias(`connect-agent`).description(`Connect local agent CLIs to Tangle Intelligence`).option(`--endpoint <url>`,`OTLP endpoint base`,ia).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(e,t)=>{let n=e??`local`;la(n);let r=Fl(t.apiKey),i=await ma({selection:n,workspace:t.workspace,apiKey:r,endpoint:t.endpoint,serviceName:t.serviceName??da(t.workspace),environment:t.environment,smoke:t.smoke,dryRun:!!t.dryRun,hookCommand:t.hookCommand}),a={configPath:i.configPath,agents:i.agents,nativeAgents:i.nativeAgents,manual:i.manual,written:i.written,smokeTraceId:i.smokeTraceId};if(t.json){P(a);return}R({Config:i.configPath,Agents:i.agents.join(`, `),"Native Hooks":i.nativeAgents.join(`, `)||void 0,"Manual Setup":i.manual.length?i.manual.map(e=>`${e.label}: ${e.reason}`).join(` `):void 0,Files:i.written.join(`, `),"Smoke Trace":i.smokeTraceId})}),e.command(`doctor`).description(`Check whether your agent traces carry CONTENT or are metadata-only`).option(`--endpoint <url>`,`OTLP endpoint base`,ia).action(async e=>{let t=pa(),n=await ya({endpoint:e.endpoint===`https://intelligence.tangle.tools/v1/otlp`?t?.endpoint??`https://intelligence.tangle.tools/v1/otlp`:e.endpoint,apiKey:Fl(e.apiKey??t?.apiKey)});e.json?P(n):Pl(n),n.contentSeen||(process.exitCode=1)}),e.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 e=>{try{let t=Il(e.agent),n=pa(),r={agent:t,event:e.event,endpoint:e.endpoint??n?.endpoint??`https://intelligence.tangle.tools/v1/otlp`,apiKey:Fl(e.apiKey??n?.apiKey),serviceName:e.serviceName??n?.serviceName??da(process.cwd()),environment:e.environment??n?.environment??`local`,sessionId:e.sessionId,payload:e.payload===void 0?await Rl():Ll(e.payload)};if(e.dryRun){let n=ga(r);if(e.json){P(n);return}R({Trace:n.traceId,Agent:t,Event:e.event});return}let i=await _a(r);if(e.json){P({traceId:i});return}R({Trace:i,Agent:t,Event:e.event})}catch(t){if(e.nonBlocking){let n=t instanceof Error?t.message:String(t);e.json?P({ok:!1,error:n}):console.error(`Tangle Intelligence hook skipped: ${n}`);return}V(t)}}),e.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 zl({type:`sandbox`,id:e},t)}),e.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 zl({type:`fleet`,id:e},t)}),e.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 zl({type:Vl(e.subjectType),id:e.subjectId},e)}),e.command(`get <job-id>`).description(`Get an intelligence report`).action(async(e,t)=>{let{client:n}=W(t),r=t.json?null:L(`Fetching intelligence report...`);r?.start();let i=await n.intelligence.getReport(e);if(r?.stop(),t.json){P(i);return}Bl(i)}),e.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 e=>{let{client:t}=W(e),n=e.json?null:L(`Fetching intelligence reports...`);n?.start();let r=await t.intelligence.listReports({subjectType:e.subjectType===void 0?void 0:Vl(e.subjectType),subjectId:e.subjectId,limit:e.limit===void 0?void 0:Wl(e.limit)});if(n?.stop(),e.json){P(r);return}N(r.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}])}),e}function Pl(e){R({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 t=Object.entries(e.byAgent);t.length>0&&(console.log(),N(t.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 Fl(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 Il(e){if(ua(e))return e;throw Error(`agent must be a known Tangle Intelligence agent surface`)}function Ll(e){try{return JSON.parse(e)}catch(e){throw Error(`--payload must be JSON: ${e instanceof Error?e.message:String(e)}`)}}async function Rl(){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 zl(e,t){let n=Hl(t.mode),r=Gl(t.metadata),i=t.maxUsd===void 0?void 0:Ul(t.maxUsd);if(n===`agentic`&&i===void 0)throw Error(`Agentic intelligence reports require --max-usd`);let{client:a}=W(t),o=t.json?null:L(`Creating intelligence report...`);o?.start();let s=await a.intelligence.createReport({subject:e,mode:n,...i===void 0?{}:{budget:{billTo:`customer`,maxUsd:i}},...r===void 0?{}:{metadata:r}});if(o?.stop(),t.json){P(s);return}Bl(s)}function Bl(e){R({Job:e.jobId,Subject:`${e.subject.type}:${e.subject.id}`,Mode:e.mode,Status:e.status,"Billed To":e.billing.billedTo,Cost:`$${e.billing.costUsd.toFixed(2)}`,Budget:e.billing.budgetMaxUsd===void 0?void 0:`$${e.billing.budgetMaxUsd.toFixed(2)}`,Updated:e.updatedAt}),e.result!==null&&(console.log(),P(e.result))}function Vl(e){if(e===`sandbox`||e===`fleet`)return e;throw Error(`subject type must be sandbox or fleet`)}function Hl(e){if(e===`deterministic`||e===`agentic`)return e;throw Error(`mode must be deterministic or agentic`)}function Ul(e){let t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`--max-usd must be a non-negative number`);return t}function Wl(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Gl(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 Kl=[`router`,`sandbox`,`blueprint-agent`,`evals`,`agent-builder`];async function ql(e,t){let n=await Lr({...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 Jl(e,t,n={}){let r=new Headers(n.headers);n.body&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await Rr(e,t,{...n,headers:r});if(n.expected!==void 0&&i.status!==n.expected)throw Error(await Yl(i,t));return i}async function Yl(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 Xl=[`ID`,`Prefix`,`Name`,`Product`,`Created`,`Last used`,`Expires`];function Zl(e){return[e.id,e.keyPrefix??``,e.name,e.product??`all`,e.createdAt,e.lastUsedAt??`—`,e.expiresAt??`—`]}function Ql(){let e=new b(`keys`).description(`Manage sk-tan-* API keys on id.tangle.tools`);return e.command(`list`).description(`List your active API keys`).option(`--platform-url <url>`,`Override the platform URL (id.tangle.tools)`).action(async e=>{let t=await ql(e,!1),n=t.baseUrl,r=await(await Jl(t,`${n}/v1/keys`,{expected:200})).json();if(e.json){P(r);return}Bt(Xl,r.data.map(Zl))}),e.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 (${Kl.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(e,t)=>{if(t.product!==void 0&&!Kl.includes(t.product))throw Error(`Invalid --product. Expected one of ${Kl.join(`, `)}`);let n=await ql(t,!0),r=n.baseUrl,i=t.expiresInDays===void 0?void 0:new Date(Date.now()+Number.parseInt(t.expiresInDays,10)*24*60*60*1e3).toISOString(),a=L(`Creating API key...`);a.start();let o=await Jl(n,`${r}/v1/keys`,{method:`POST`,expected:201,body:JSON.stringify({name:e,product:t.product,budgetUsd:t.budgetUsd?Number.parseFloat(t.budgetUsd):void 0,rpmLimit:t.rpmLimit?Number.parseInt(t.rpmLimit,10):void 0,expiresAt:i})});a.stop();let s=await o.json();if(t.json){P(s);return}F(`API key created: ${s.data.prefix}…`),I(`Copy this key now — it will never be shown again:\n${s.data.key}`)}),e.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(e,t)=>{let n=await ql(t,!0),r=n.baseUrl;if(!t.yes&&!await $r(`Revoke key ${e}? Any service still using it will start to fail.`,`--yes`)){I(`Aborted.`);return}let i=await(await Jl(n,`${r}/v1/keys/${encodeURIComponent(e)}`,{method:`DELETE`,expected:200})).json();if(t.json){P(i);return}F(`Revoked ${e}`)}),e}function $l(e){if(Kn().token)throw Error(`A line relay cannot manage numbers or attachments. Use your owner CLI outside the agent box.`);return U(H(e))}function eu(e){if(!e.yes)throw Error(`Review the selected line and use --yes to authorize this change. Attaching enables metered agent work.`)}function tu(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 nu(e){return e().catch(V)}async function ru(e){let t=await Ge(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 iu(e){e.command(`providers`).description(`List provider transports supported by this Hub deployment`).action(e=>nu(async()=>{P(await $l(e).lines.providers())})),e.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(e=>nu(async()=>{P(await $l(e).lines.list({profileId:e.profileId,sandboxId:e.sandbox}))})),e.command(`get`).argument(`<line-id>`).description(`Inspect a line and its current attachment`).action((e,t)=>nu(async()=>{P(await $l(t).lines.get(e))})),e.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((e,t)=>nu(async()=>{let n=tu(t.transport);if(n===`email`)throw Error(`Email uses an owned mailbox, not phone inventory`);if(n===`voice`)throw Error(`Voice numbers are listed by ph0ny; provide the owned number ID to lines connect`);if(n===`telegram`)throw Error(`Telegram uses an owned bot, not phone inventory`);P(await $l(t).lines.numbers(e,n))})),e.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((e,t)=>nu(async()=>{eu(t);let n=tu(t.transport);if(n!==`email`&&t.address)throw Error(`--address is email-only`);if((n===`email`||n===`telegram`)&&t.numberId)throw Error(`${n} does not take --number-id`);let r={connectionId:e,label:t.label,clientReference:t.reference},i;if(n===`email`)i={...r,transport:n,address:t.address};else if(n===`telegram`)i={...r,transport:n};else if(n===`imessage`)i={...r,transport:n,phoneNumberId:t.numberId};else{if(!t.numberId)throw Error(`${n} requires --number-id`);i={...r,transport:n,phoneNumberId:t.numberId}}P(await $l(t).lines.fromConnection(i))})),e.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((e,t)=>nu(async()=>{eu(t);let n=$l(t),r;if(t.file){if(t.profileId||t.member||t.sandbox||t.instancePrefix||t.tools||t.turnsPerDay)throw Error(`Choose --file or quick-setup flags, not both`);r=await ru(t.file)}else{if(!t.profileId||!t.member)throw Error(`Provide --profile-id and --member, or --file`);if(t.sandbox&&t.instancePrefix)throw Error(`Choose --sandbox or --instance-prefix`);let e=t.tools??`chat`,n=Number(t.turnsPerDay??`30`);if(e!==`chat`&&e!==`act`)throw Error(`--tools must be chat or act`);if(!Number.isSafeInteger(n)||n<1||n>1e4)throw Error(`--turns-per-day must be 1–10000`);if(e===`act`&&t.sandbox)throw Error(`Acting tools require an isolated on-demand instance; omit --sandbox`);r={mode:`personal`,members:[{address:t.member,role:`owner`}],unknownSenders:`reject`,roles:{owner:{context:`own`,tools:e}},respond:{kind:`agent`,profileId:t.profileId,...e===`act`?{rolePolicy:{version:1,roles:{owner:{kind:`general`}},members:{}}}:{}},limits:{turnsPerMemberPerDay:n},...t.sandbox?{sandboxId:t.sandbox}:{instance:{keyPrefix:t.instancePrefix??`profile:${t.profileId}:`,create:{ownerContext:`isolated`,...e===`act`?{egressPolicy:{mode:`strict`,allowDomains:[new URL(ur()).hostname],includeImplicitDomains:!1}}:{}}}}}}if(typeof r.sandboxId==`string`==(r.instance!==void 0))throw Error(`Attachment requires exactly one of sandboxId and instance`);let{sandboxId:i,instance:a,...o}=r,s;if(i){let t=await n.get(i);if(!t)throw Error(`Sandbox not found`);s=await t.lines.attach({...o,number:e})}else{if(!a)throw Error(`Attachment requires an instance`);s=await n.lines.attach({...o,number:e,instance:a})}P(s)}));for(let t of[`detach`,`release`])e.command(t).argument(`<line-id>`).description(t===`detach`?`Stop dispatch; preserve history and provider rental`:`Retire a detached Hub line; does not cancel provider rental`).option(`--yes`,`Authorize this change`).action((e,n)=>nu(async()=>{eu(n),P({[t]:await $l(n).lines[t](e)})}));e.command(`threads`).argument(`<line-id>`).description(`List this line's separate participant threads`).action((e,t)=>nu(async()=>{P(await $l(t).lines.threads(e).list())})),e.command(`messages`).argument(`<line-id>`).argument(`<thread-id>`).description(`Read one authorized participant thread`).action((e,t,n)=>nu(async()=>{P(await $l(n).lines.threads(e).messages(t))}))}async function au(e){let{token:t,baseUrl:n}=Kn();if(t===void 0)return G(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 ou(e,t){if(t)return t;if(!Kn().token)throw Error(`Provide --line <line-id>`);return(await e.lines.context()).line.id}function su(e){return e().catch(V)}function cu(){return new b(`context`).description(`Show live line identity, members, consent, reminders and quotas`).action(e=>su(async()=>{P(await(await au(e)).lines.context())}))}function lu(){let e=new b(`lines`).description(`Connect, manage, message and schedule on a Hub line`);return e.command(`members`).description(`List names, roles and consent on this line`).option(`--line <line-id>`,`Line ID; inferred in a line box`).action(e=>su(async()=>{let t=await au(e);P(await t.lines.members.list(await ou(t,e.line)))})),e.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((e,t,n)=>su(async()=>{let r=await au(n),i=await ou(r,n.line);if(!Kn().token){if(n.onBehalfOf)throw Error(`--on-behalf-of is only available inside a line box`);if(!n.idempotencyKey)throw Error(`Owner sends require --idempotency-key so a retry keeps the same message`);if(!(await r.lines.members.list(i)).some(t=>t.id===e))throw Error(`Owner sends require an exact member ID from tangle lines members`);P(await r.lines.send(i,{memberId:e,text:t,idempotencyKey:n.idempotencyKey,...n.notBefore?{notBefore:n.notBefore}:{}}));return}P(await r.lines.send(i,{toMember:e,text:t,...n.onBehalfOf?{onBehalfOf:n.onBehalfOf}:{},...n.notBefore?{notBefore:n.notBefore}:{},...n.idempotencyKey?{idempotencyKey:n.idempotencyKey}:{}}))})),e.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((e,t)=>su(async()=>{if(!t.at)throw Error(`--at is required`);let n=await au(t),r=t.idempotencyKey??S(`sha256`).update(JSON.stringify([e,t.at])).digest(`hex`).slice(0,32);P(await n.lines.remind(await ou(n,t.line),{text:e,notBefore:t.at,idempotencyKey:r}))})),iu(e),e}function uu(){let e=new b(`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=H({apiKey:t.apiKey,baseUrl:t.baseUrl}),r=await K(U(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 nt(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 du(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=Ln(),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??nr():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=H({apiKey:a,baseUrl:r}),s=U(o);return t.self?at(s):K(s,o,e)}async function fu(e,t,n){let r=L(e);t||r.start();try{return await n()}finally{r.stop()}}function pu(e){return e}function mu(){let e=new b(`preview`).description(`Manage sandbox preview links`);return pu(e.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(e,t)=>{let n=await du(e,t),r=await fu(`Starting managed preview...`,t.json,()=>rt(n,{cwd:t.cwd,sessionId:t.session,name:t.name}));t.json?P(r):(F(`Preview ready: ${r.url}`),console.log(`Preview ID: ${r.previewId}`))}),pu(e.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(e,t)=>{let n=await du(e,t),r=await fu(`Fetching preview links...`,t.json,()=>n.previewLinks.list());t.json?P(r):r.length===0?console.log(`No preview links found`):Bt([`App`,`Preview ID`,`Port`,`URL`,`Status`],r.map(e=>[hu(e.metadata),e.previewId.slice(0,12),String(e.port),e.url,e.status]))}),pu(e.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(e,t)=>{if(!t.port||!/^\d+$/.test(t.port))throw Error(`An integer service port is required`);let n=await du(e,t),r=await fu(`Publishing service...`,t.json,()=>it(n,{port:Number(t.port),name:t.name}));t.json?P(r):F(`Preview ready: ${r.url}`)}),pu(e.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(e,t,n)=>{if(!/^\d+$/.test(t)||Number(t)<1||Number(t)>65535)throw Error(`Port must be an integer between 1 and 65535`);let r=await du(e,n),i=await fu(`Creating preview for port ${t}...`,n.json,()=>r.previewLinks.create(Number(t)));n.json?P(i):(F(`Preview created: ${i.url}`),console.log(`Preview ID: ${i.previewId}`))}),pu(e.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(e,t,n)=>{let r=await du(e,n);await fu(`Removing preview...`,n.json,()=>r.previewLinks.remove(t)),n.json?P({success:!0,previewId:t}):F(`Preview removed: ${t}`)}),e}function hu(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 gu(){let e=new b(`process`).description(`Manage processes in a sandbox`);return e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=es(n.env??[],`--env`,`env`),o=L(`Spawning: ${t}`);n.json||o.start();let s=await K(i,r,e);if(s=await q(s),n.blocking){let e=await s.exec(t,{cwd:n.cwd,env:Object.keys(a).length>0?a:void 0,timeoutMs:n.timeout?Number.parseInt(n.timeout,10):void 0});o.stop(),n.json?P(e):(e.stdout&&globalThis.process.stdout.write(e.stdout),e.stderr&&globalThis.process.stderr.write(e.stderr),e.exitCode!==0&&globalThis.process.exit(e.exitCode))}else{let r=await s.process.spawn(t,{cwd:n.cwd,env:Object.keys(a).length>0?a:void 0,timeoutMs:n.timeout?Number.parseInt(n.timeout,10):void 0});o.stop(),n.json?P({pid:r.pid,command:r.command}):(console.log(`Process started with PID: ${r.pid}`),console.log(`Use 'tangle process logs ${e} ${r.pid}' to view output`))}}),e.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching processes...`);t.json||i.start();let a=await K(r,n,e);a=await q(a);let o=await a.process.list();t.running&&(o=o.filter(e=>e.running)),i.stop(),t.json?P(o):o.length===0?console.log(`No processes found`):Bt([`PID`,`Command`,`Status`,`Exit Code`,`Started`],o.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()]))}),e.command(`get`).description(`Get detailed info about a process`).argument(`<id-or-name>`,`Sandbox ID or name`).argument(`<pid>`,`Process ID`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Fetching process info...`);n.json||a.start();let o=await K(i,r,e);o=await q(o);let s=await o.process.get(Number.parseInt(t,10));if(a.stop(),!s){console.error(`Process ${t} not found`),globalThis.process.exit(1);return}let c=await s.status();n.json?P(c):(console.log(`PID: ${c.pid}`),console.log(`Command: ${c.command}`),console.log(`CWD: ${c.cwd||`(default)`}`),console.log(`Status: ${c.running?`running`:`exited`}`),console.log(`Exit Code: ${c.exitCode}`),c.exitSignal&&console.log(`Signal: ${c.exitSignal}`),console.log(`Started: ${c.startedAt.toLocaleString()}`),c.exitedAt&&console.log(`Exited: ${c.exitedAt.toLocaleString()}`))}),e.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(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Sending ${n.signal} to PID ${t}...`);n.json||a.start();let o=await K(i,r,e);o=await q(o);let s=await o.process.get(Number.parseInt(t,10));if(!s){a.stop(),console.error(`Process ${t} not found`),globalThis.process.exit(1);return}n.tree?await s.kill(n.signal,{tree:!0}):await s.kill(n.signal),a.stop(),n.json?P({pid:Number.parseInt(t,10),signal:n.signal,...n.tree===!0?{tree:!0}:{},killed:!0}):console.log(n.tree?`Sent ${n.signal} to process tree ${t}`:`Sent ${n.signal} to process ${t}`)}),e.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}=W(n),a=await K(i,r,e);a=await q(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))}),e}const _u=[`python`,`node`,`typescript`,`bash`];function vu(e){switch(ve(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 yu(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 Ke(xe(e),`utf8`)}async function bu(e,t,n=yu){let r=t?_u.find(e=>e===t)??(()=>{throw Error(`unknown --lang ${t}: must be one of ${_u.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=vu(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 xu(e){return O(we(),`tangle-run-images`,e)}function Su(){return new b(`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: ${_u.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(e,t,n)=>{let{language:r,source:i}=await bu(t,n.lang),{context:a,client:o}=W(n),s=await K(o,a,e);s=await q(s);let c=L(`Running ${r} (${i.length}b)…`);n.json||c.start();let l=await s.runCode(r,i,{sessionId:n.session,timeoutMs:Number.parseInt(n.timeout,10)});if(c.stop(),n.json){P(l),l.exitCode!==0&&process.exit(l.exitCode);return}l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr);let u=0;for(let t of l.results)if(t.type===`image`)if(n.saveImages!==!1){let r=typeof n.saveImages==`string`?n.saveImages:xu(e);fe(r,{recursive:!0});let i=`${r}/${Date.now()}-${u}.${t.format}`;he(i,Buffer.from(t.data,`base64`)),process.stderr.write(y.green(`✓ image → ${i}\n`)),u++}else process.stderr.write(y.gray(`[image: ${t.format}, ${t.data.length}b base64]\n`));else if(t.type===`dataframe`){let e=t.columns.map(e=>`${e.name}:${e.dtype}`).join(` | `);process.stderr.write(y.gray(`[dataframe ${t.rows.length}×${t.columns.length}${t.truncated?` (truncated)`:``}]\n`)),process.stderr.write(`${e}\n`);for(let e of t.rows.slice(0,20))process.stderr.write(`${e.map(e=>String(e)).join(` | `)}\n`);t.rows.length>20&&process.stderr.write(y.gray(`… ${t.rows.length-20} more rows\n`))}else t.type===`json`?(process.stderr.write(y.gray(`[json] `)),process.stderr.write(`${JSON.stringify(t.value,null,2)}\n`)):t.type===`html`?process.stderr.write(y.gray(`[html ${t.value.length}b]\n`)):t.type===`error`?(process.stderr.write(y.red(`✗ ${t.name}: ${t.message}\n`)),t.traceback&&process.stderr.write(`${t.traceback}\n`)):t.type===`text`&&process.stderr.write(`${t.value}\n`);l.error&&(process.stderr.write(y.red(`\n✗ ${l.error.name}: ${l.error.message}\n`)),l.error.traceback&&process.stderr.write(`${l.error.traceback}\n`)),l.exitCode!==0&&process.exit(l.exitCode)})}function Cu(e){e.command(`network <id-or-name>`).description(`Show runtime network state (exposed ports) for a sandbox. Outbound policy is the sandbox's egress policy.`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Updating network configuration...`);i.start();let a=await K(r,n,e);i.stop();let o=await a.network.getConfig();t.json?P(o):(I(`Network Configuration:`),o.ports&&o.ports.length>0?I(` Exposed Ports: ${o.ports.join(`, `)}`):I(` No exposed ports`))}),e.command(`expose <id-or-name>`).description(`Expose a port and get a public URL`).option(`-p, --port <port>`,`Port to expose`,`8000`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=Number.parseInt(t.port,10);if(Number.isNaN(i)||i<1||i>65535)throw Error(`Port must be a number between 1 and 65535`);let a=L(`Exposing port ${i}...`);a.start();let o=await(await K(r,n,e)).network.exposePort(i);a.stop(),t.json?P({port:i,url:o}):(F(`Port ${i} exposed.`),I(` URL: ${o}`))}),e.command(`urls <id-or-name>`).description(`List exposed port URLs for a sandbox`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching exposed URLs...`);i.start();let a=await(await K(r,n,e)).network.listUrls();if(i.stop(),t.json)P(a);else{let e=Object.entries(a);if(e.length===0)I(`No ports exposed.`);else{I(`Exposed Ports:`);for(let[t,n]of e)I(` ${t}: ${n}`)}}})}function wu(){let e=new b(`sandbox`).description(`Manage sandboxes`);return Ms(e),js(e),xs(e),Cu(e),e}function Tu(){return new b(`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}=W(n),a=L(`Searching...`);n.json||a.start();let o=await K(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 Eu(){let e=new b(`secret`).description(`Manage secrets`);return e.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(e,t,n)=>{let r=await W(n).client.secrets.create(e,await Du({value:t,valueStdin:n.valueStdin,prompt:`Enter value for secret '${e}': `}));n.json?P(r):(F(`Secret created: ${r.name}`),I(`Use --secret ${r.name} when creating a sandbox to select it for delivery.`))}),e.command(`list`).description(`List all secrets`).action(async e=>{let t=await W(e).client.secrets.list();e.json?P(t):t.length===0?(I(`No secrets found.`),I(`Use 'tangle secret create <name> [value]' to create one.`)):Bt([`Name`,`Created At`,`Updated At`],t.map(e=>[e.name,e.createdAt.toLocaleString(),e.updatedAt.toLocaleString()]))}),e.command(`delete`).description(`Delete a secret`).argument(`<name>`,`Secret name`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=W(t).client;if(!t.force&&!await $r(`Are you sure you want to delete secret '${e}'? This cannot be undone. (y/N) `,`--force`)){I(`Cancelled.`);return}await n.secrets.delete(e),t.json?P({success:!0,deleted:e}):F(`Secret deleted: ${e}`)}),e}async function Du(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 ti():await Qr(e.prompt));if(!t.length)throw Error(e.valueStdin?`Secret value from stdin cannot be empty`:`Secret value cannot be empty`);return t}function Ou(){let e=new b(`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=D.dirname(Ze(import.meta.url)),t=D.resolve(e,`..`,`SKILL.md`);console.log(t)}),e}function ku(){let e=new b(`snapshot`).description(`Manage snapshots`);return e.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(e,t)=>{let{context:n,client:r}=W(t),i=L(`Creating snapshot...`);i.start();let a=await K(r,n,e);if(t.wait===!1){let e=await a.snapshot({tags:t.tags,wait:!1});i.stop(),Ss(e.info,!!t.json);return}let o=await a.snapshot({tags:t.tags});i.stop(),t.json?P(o):(F(`Snapshot created: ${o.snapshotId}`),console.log(`Size: ${Au(o.sizeBytes??0)}`))}),e.command(`list <sandbox-id-or-name>`).description(`List snapshots for a sandbox`).action(async(e,t)=>{let{context:n,client:r}=W(t),i=L(`Fetching snapshots...`);i.start();let a=await(await K(r,n,e)).listSnapshots();i.stop(),t.json?P(a):N(a.map(e=>({...e,size:Au(e.sizeBytes??0)})),[{key:`snapshotId`,header:`ID`,width:24},{key:`createdAt`,header:`Created`,width:16},{key:`size`,header:`Size`,width:12},{key:`sandboxId`,header:`Sandbox`,width:20}])}),e.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(e,t,n)=>{let{client:r}=W(n),i=L(`Restoring from snapshot...`);i.start();let a=await r.create({fromSnapshot:t,fromSandboxId:e,...n.billingOwner?{billingOwnerId:n.billingOwner}:{}});await a.waitFor(`running`,{timeoutMs:12e4}),i.stop(),n.json?P({sandboxId:a.id,restoredFrom:t,status:a.status}):(F(`New sandbox created: ${a.id}`),console.log(`Source snapshot: ${t}`))}),e.command(`revert <sandbox-id-or-name> <snapshot-id>`).description(`Revert an existing sandbox to a snapshot`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Reverting sandbox to snapshot...`);a.start();let o=await K(i,r,e),s=await o.revertToSnapshot(t);await o.refresh(),a.stop(),n.json?P({sandboxId:o.id,snapshotId:s.snapshotId,status:o.status}):(F(`Sandbox reverted: ${o.id}`),console.log(`Source snapshot: ${s.snapshotId}`))}),e.command(`delete <sandbox-id-or-name> <snapshot-id>`).description(`Delete a sandbox snapshot`).action(async(e,t,n)=>{let{context:r,client:i}=W(n),a=L(`Deleting snapshot...`);a.start();let o=await(await K(i,r,e)).deleteSnapshot(t);a.stop(),n.json?P({success:!0,sandboxId:e,snapshotId:t,outcome:o.outcome}):o.outcome===`already_absent`?F(`Snapshot already gone: ${t}`):F(`Snapshot deleted: ${t}`)}),e}function Au(e){if(e===0)return`0 B`;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 ju=`solve:device:secp256k1`,Mu=/^0x[0-9a-f]{64}$/i;function Nu(e){return e&&Mu.test(e)?e:void 0}function Pu(){let e=mn(ju),t=Nu(e.value);if(!(!t||e.source===`none`))return{account:st(t),source:e.source}}function Fu(){let e=Pu();if(e)return e;let t=ot(),n=hn(ju,t);return{account:st(t),source:n}}function Iu(e){let t=Nu(mn(ju).value);if(!t||st(t).address!==e.account.address)throw Error(`The local Solve device key changed; it was not retired`);let n=`${ju}:retired:${e.account.address.toLowerCase()}`;if(hn(n,t),mn(n).value!==t)throw Error(`The revoked device key could not be retired safely`);return _n(ju),n}function Lu(e){let t=e.create?Fu():Pu();if(!t)throw Error("No Solve device signer found. Run `tangle solve account --create`");e.json?P({address:t.account.address,source:t.source}):R({Address:t.account.address,Source:t.source})}const Ru=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;function zu(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function Bu(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Vu(e,t,n=2048){if(typeof e!=`string`||!e.trim()||e.length>n)throw Error(`${t} is missing or invalid`);if(zu(e))throw Error(`${t} contains control characters`);return e.trim()}function Hu(e,t){let n=Vu(e,t,64).toLowerCase();if(!Ru.test(n))throw Error(`${t} must be a 40 or 64 character Git revision`);return n}function Uu(e,t,n=!1){let r=typeof e==`number`&&Number.isSafeInteger(e)?String(e):Vu(e,t,80);if(!/^\d+$/.test(r)||!n&&r===`0`)throw Error(`${t} must be an unsigned integer`);return BigInt(r).toString()}function Wu(e,t){let n=Vu(e,t,2048),r=new URL(n);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&(r.hostname===`localhost`||r.hostname===`127.0.0.1`)))throw Error(`${t} must use HTTPS outside local development`);return n.replace(/\/$/,``)}function Gu(e,t){let n=Wu(e,t).replace(/\.git$/,``),r=new URL(n),i=r.pathname.split(`/`).filter(Boolean);if(r.hostname!==`github.com`||r.username||r.password||r.search||r.hash||i.length!==2)throw Error(`${t} must be an HTTPS GitHub repository URL`);return`https://github.com/${i.join(`/`)}`}function Ku(e,t){let n=Vu(e,t,42);if(!ht(n,{strict:!1}))throw Error(`${t} must be an EVM address`);return pt(n)}function qu(e,t){let n=Uu(e,t),r=Number(n);if(!Number.isSafeInteger(r)||r<=0)throw Error(`${t} is out of range`);return r}function Ju(...e){for(let t of e)if(typeof t==`string`&&t.trim())return t.trim()}function Yu(e){let t=e.trim().replace(/\.git$/,``);return t.startsWith(`git@github.com:`)?`https://github.com/${t.slice(15)}`:t.startsWith(`ssh://git@github.com/`)?`https://github.com/${t.slice(21)}`:t}function Xu(e){if(e===void 0)return;let t=Vu(e,`pull request URL`,2048);if(!/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:\/[^\s]*)?$/i.test(t))throw Error(`pull request URL must point to a GitHub pull request`);return t}function Zu(e,t){if(!/^https:\/\/[^\s]+$/i.test(e)&&!/^\/(?!\/).*$/.test(e)&&!/^[a-z][a-z0-9+.-]*:[^\s]+$/i.test(e))throw Error(`${t} must be an HTTPS URL or an absolute repository path`);if(e.split(/[?#]/,1)[0].split(`/`).includes(`..`))throw Error(`${t} cannot contain parent-directory segments`);return e}function Qu(e){return Rn(`solve`,e.profile)}function $u(e){let t=Qu(e),n=ir(void 0,t);if(!n)throw Error(`No Solve credential found for profile '${t}'. Run: tangle auth login --provider github --app solve`);return n}async function ed(e){let t=dr(e.apiUrl),n=await fetch(`${t}${e.path}`,{method:e.method??`GET`,headers:{Accept:`application/json`,...e.body===void 0?{}:{"Content-Type":`application/json`},Authorization:`Bearer ${$u(e)}`},...e.body===void 0?{}:{body:JSON.stringify(e.body)},signal:AbortSignal.timeout(3e4)}),r=await n.json().catch(()=>null);if(!n.ok||!r?.success||r.data===void 0){let e=r?.error?.message??`Solve API request failed with HTTP ${n.status}`;throw Error(r?.error?.code?`${r.error.code}: ${e}`:e)}return r.data}function td(e){return ed({path:`/v1/wallet/challenges`,method:`POST`,apiUrl:e.apiUrl,profile:e.profile,body:{deviceAddress:e.deviceAddress,...e.purpose?{purpose:e.purpose}:{}}})}function nd(e){return ed({path:`/v1/devices`,apiUrl:e.apiUrl,profile:e.profile})}function rd(e){return ed({path:`/v1/devices/revoke`,method:`POST`,apiUrl:e.apiUrl,profile:e.profile,body:{deviceAddress:e.deviceAddress,...e.reason?{reason:e.reason}:{},...e.challengeId&&e.signature?{challengeId:e.challengeId,signature:e.signature}:{}}})}const Q={chainId:42431,rpcUrl:`https://rpc.moderato.tempo.xyz`,sponsorUrl:`https://drew-gtr-pro.taild10bfc.ts.net/solve-sponsor`,tangleAddress:`0xff137B9C879c47C28ce389e84501925438AB4cdA`,managerAddress:`0x5271732F893B622ac6793d6DBA5B2626CCa4EA14`,paymentAsset:`0x20C0000000000000000000000000000000000000`,blueprintId:15n,serviceId:9n,competitionId:1n,minStakeWei:0n};function id(e,t){return e.toLowerCase()===t.toLowerCase()}function ad(e){if(e.chainId!==Q.chainId)throw Error(`Solve submissions require Tempo Moderato (chain ${Q.chainId}); received ${e.chainId}`);if(e.rpcUrl!==Q.rpcUrl)throw Error(`Solve metadata RPC does not match the trusted deployment`);if(e.sponsorUrl!==Q.sponsorUrl)throw Error(`Solve metadata sponsor does not match the trusted deployment`);if(!id(e.tangleAddress,Q.tangleAddress))throw Error(`Solve metadata Tangle contract does not match the trusted deployment`);if(!id(e.managerAddress,Q.managerAddress))throw Error(`Solve metadata competition manager does not match the trusted deployment`);if(!id(e.paymentAsset,Q.paymentAsset))throw Error(`Solve metadata payment asset does not match the trusted deployment`);if(e.blueprintId!==Q.blueprintId)throw Error(`Solve submissions require blueprint ${Q.blueprintId}; received ${e.blueprintId}`);if(e.serviceId!==Q.serviceId)throw Error(`Solve submissions require service ${Q.serviceId}; received ${e.serviceId}`);if(e.competitionId!==Q.competitionId)throw Error(`Solve submissions require competition ${Q.competitionId}; received ${e.competitionId}`);if(e.minStakeWei!==Q.minStakeWei)throw Error(`Solve submissions require zero stake for the trusted deployment`)}function od(e,t){let n=Bu(t.check??e.check,`competition.participation.check`),r=Vu(n.command,`competition.participation.check.command`,512);if(!Array.isArray(n.args)||n.args.some(e=>typeof e!=`string`))throw Error(`competition.participation.check.args must be an array of strings`);let i=n.args.map(e=>Vu(e,`competition checker argument`,2048)),a=Ju(n.result_file,n.resultFile),o=n.timeout_ms??n.timeoutMs,s=o===void 0?void 0:qu(o,`competition checker timeout`);return{command:r,args:i,...a?{result_file:a}:{},...s?{timeout_ms:s}:{}}}function sd(e){if(e.provenance===void 0)return;let t=Bu(e.provenance,`competition.participation.provenance`);if(t.mode!==`github_pull_request`)throw Error(`competition.participation.provenance.mode is unsupported`);if(t.required!==void 0&&typeof t.required!=`boolean`)throw Error(`competition.participation.provenance.required must be a boolean`);return{mode:`github_pull_request`,required:t.required===!0}}function cd(e){let t=Bu(e.chain??e.network??{},`competition.chain`),n=e.rewards&&typeof e.rewards==`object`&&!Array.isArray(e.rewards)?Bu(e.rewards,`competition.rewards`):{},r=n.minStake&&typeof n.minStake==`object`&&!Array.isArray(n.minStake)?Bu(n.minStake,`competition.rewards.minStake`).raw:void 0,i=Ju(t.minStakeWei,t.min_stake_wei,e.minStakeWei,e.min_stake_wei,r),a=t.chainId??t.chain_id??e.chainId??e.chain_id,o=Ju(t.chainName,t.chain_name,e.chainName,e.chain_name)??`Tempo`,s=Ju(t.nativeSymbol,t.native_symbol,e.nativeSymbol,e.native_symbol)??`TNT`,c=Ju(t.rpcUrl,t.rpc_url,e.rpcUrl,e.rpc_url,process.env.TANGLE_SOLVE_RPC_URL),l=Ju(t.sponsorUrl,t.sponsor_url,e.sponsorUrl,e.sponsor_url,process.env.TANGLE_SOLVE_SPONSOR_URL),u=Ju(t.tangleAddress,t.tangle_address,t.coreAddress,t.core_address,e.tangleAddress,e.tangle_address,e.coreAddress,e.core_address),d=Ju(t.managerAddress,t.manager_address,e.managerAddress,e.manager_address),f=Ju(t.paymentAsset,t.payment_asset,t.servicePaymentAsset,t.service_payment_asset,e.paymentAsset,e.payment_asset,e.servicePaymentAsset,e.service_payment_asset),p=Ju(t.blueprintId,t.blueprint_id,e.blueprintId,e.blueprint_id),m=Ju(t.serviceId,t.service_id,e.serviceId,e.service_id),h=Ju(t.competitionId,t.competition_id,e.competitionId,e.competition_id,e.id);if(!c||!l||!u||!d||!p||!m||!h||!i||a===void 0)throw Error(`Solve competition metadata must include complete Tempo chain configuration`);return{chainId:qu(a,`chain.chainId`),chainName:o,nativeSymbol:s,rpcUrl:Wu(c,`chain.rpcUrl`),sponsorUrl:Wu(l,`chain.sponsorUrl`),tangleAddress:Ku(u,`chain.tangleAddress`),managerAddress:Ku(d,`chain.managerAddress`),paymentAsset:Ku(f??Q.paymentAsset,`chain.paymentAsset`),blueprintId:Uu(p,`chain.blueprintId`),serviceId:Uu(m,`chain.serviceId`),competitionId:Uu(h,`chain.competitionId`,!0),minStakeWei:Uu(i,`chain.minStakeWei`,!0)}}function ld(e){let t=Bu(e,`competition`),n=Bu(t.participation??t.task,`competition.task`),r={...t,participation:{...n,...n.repositoryRevision===void 0&&n.revision!==void 0?{repositoryRevision:n.revision}:{}}},i=r.participation,a=Gu(Ju(r.repository,r.repo_url,i.repository)??``,`competition.repository`),o=Hu(Ju(r.repositoryRevision,r.repository_revision,i.revision,i.repositoryRevision,i.repository_revision),`competition.repositoryRevision`),s=Vu(r.slug??r.id,`competition.slug`,128),c=Vu(r.name??r.title??s,`competition.name`,256),l=od(r,i),u=sd(i);return{version:1,slug:s,title:c,repository:a,taskRevision:o,checker:l,chain:cd(r),...u?{provenance:u}:{}}}function ud(e){return{chainId:e.chain.chainId,chainName:e.chain.chainName,nativeSymbol:e.chain.nativeSymbol,rpcUrl:e.chain.rpcUrl,sponsorUrl:e.chain.sponsorUrl,tangleAddress:e.chain.tangleAddress,managerAddress:e.chain.managerAddress,paymentAsset:e.chain.paymentAsset,blueprintId:BigInt(e.chain.blueprintId),serviceId:BigInt(e.chain.serviceId),competitionId:BigInt(e.chain.competitionId),minStakeWei:BigInt(e.chain.minStakeWei)}}async function dd(e){let t=Bu(JSON.parse(await M.readFile(D.join(e,`.tangle-solve.json`),`utf8`)),`.tangle-solve.json`);if(t.version!==1)throw Error(`.tangle-solve.json has an unsupported version`);let n=Bu(t.checker,`.tangle-solve.json.checker`),r=Bu(t.chain,`.tangle-solve.json.chain`);return ld({slug:t.slug,name:t.title,repository:t.repository,repositoryRevision:t.taskRevision,participation:{check:n,provenance:t.provenance},chain:r,competitionId:r.competitionId})}const fd=$e(Te),pd=`.tangle-solve-run.json`,md=`.tangle-solve.json`,hd=`tangle.solve.manifestSha256`,gd=new Set([md,pd]),_d=`upstream`;async function vd(e,t){let n=await fd(`git`,[`-C`,e,...t],{encoding:`utf8`,maxBuffer:1e6});return String(n.stdout).trim()}async function yd(e,t){let n=D.resolve(t??process.cwd()),r=await dd(n);if(e&&e!==r.slug&&e!==r.chain.competitionId)throw Error(`This directory contains '${r.slug}', not '${e}'`);return{root:n,manifest:r}}async function bd(e){let t=D.join(e,md),n;try{n=await M.lstat(t)}catch{throw Error(`${md} is missing`)}if(n.isSymbolicLink()||!n.isFile())throw Error(`${md} must be a regular file`);return S(`sha256`).update(await M.readFile(t)).digest(`hex`)}async function xd(e){let t=await bd(e);return await vd(e,[`config`,`--local`,`--replace-all`,hd,t]),t}async function Sd(e){let t;try{t=await vd(e,[`config`,`--local`,`--get`,hd])}catch{throw Error(`The local Git metadata has no ${hd} pin; run tangle solve clone again`)}if(!/^[0-9a-f]{64}$/i.test(t))throw Error(`The local ${hd} pin is invalid`);if(await bd(e)!==t.toLowerCase())throw Error(`${md} changed after clone; run tangle solve clone again`)}async function Cd(e,t){try{return await vd(e,[`ls-files`,`--error-unmatch`,`--`,t]),!0}catch{return!1}}async function wd(e){await Sd(e);for(let t of gd)if(await Cd(e,t))throw Error(`${t} must remain untracked and local to this Solve workspace`);let t=await fd(`git`,[`-C`,e,`status`,`--porcelain=v1`,`--untracked-files=all`,`--ignored=matching`],{encoding:`utf8`,maxBuffer:1e6});if(String(t.stdout).split(/\r?\n/).filter(Boolean).filter(e=>{let t=e.slice(0,2),n=e.slice(3);return!((t===`??`||t===`!!`)&&gd.has(n))}).length>0)throw Error(`Commit the candidate before running Solve. Only the local manifest and run record may remain uncommitted.`);return Hu(await vd(e,[`rev-parse`,`HEAD`]),`submission revision`)}async function Td(e,t,n,r={}){let i=await Ed(e,t,r);if(i)return{taskRepository:t.repository,taskRevision:t.taskRevision,submissionRepository:i,submissionRevision:n}}async function Ed(e,t,n={}){let r;try{r=Yu(await vd(e,[`config`,`--get`,`remote.origin.pushurl`]))}catch{try{r=Yu(await vd(e,[`config`,`--get`,`remote.origin.url`]))}catch{if(n.allowMissing)return;throw Error(`Add your GitHub fork as the 'origin' remote before submitting. The task repository is available as '${_d}'.`)}}let i=Gu(r,`git remote.origin.url`);if(i.toLowerCase()===t.repository.toLowerCase()){if(n.allowMissing)return;throw Error(`The 'origin' remote is the task repository. Add your GitHub fork as 'origin'; keep the task repository as '${_d}' before submitting.`)}return i}function Dd(e,t){return!e||!t?!1:e.taskRepository.toLowerCase()===t.taskRepository.toLowerCase()&&e.taskRevision.toLowerCase()===t.taskRevision.toLowerCase()&&e.submissionRepository.toLowerCase()===t.submissionRepository.toLowerCase()&&e.submissionRevision.toLowerCase()===t.submissionRevision.toLowerCase()}function Od(e,t){return`${e}/commit/${t}`}function kd(e,t,n,r,i={}){let a=e.evidenceRefs.map(e=>Zu(e.trim(),`checker evidence reference`));if(n){if(!t){if(i.allowMissingSource)return{evidence:e.evidence,evidenceRefs:a};throw Error(`Provenance policy requires a submission source`)}let o=Xu(r);if(n.required&&(i.requirePullRequest??!0)&&!o)throw Error(`This competition requires a GitHub pull request`);a.push(Od(t.taskRepository,t.taskRevision),Od(t.submissionRepository,t.submissionRevision),...o?[o]:[])}return{evidence:e.evidence,evidenceRefs:[...new Set(a)]}}async function Ad(e,t){let n=`${e}.${process.pid}.tmp`;await M.writeFile(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await M.rename(n,e)}async function jd(e){let t=JSON.parse(await M.readFile(D.join(e,pd),`utf8`));if(t.version!==1||typeof t.competition!=`string`)throw Error(`${pd} has an unsupported format`);return t}async function Md(e){let t=Xu(e.pullRequest);if(!t)throw Error(`A pull request URL is required`);let n=new URL(t).pathname.split(`/`).filter(Boolean),r=await fetch(`https://api.github.com/repos/${n[0]}/${n[1]}/pulls/${n[3]}`,{headers:{Accept:`application/vnd.github+json`,"User-Agent":`tangle-solve-cli`},signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>null),a=e=>e.replace(/\/$/,``).toLowerCase();if(!r.ok||a(i?.base?.repo?.html_url??``)!==a(e.taskRepository)||i?.head?.sha?.toLowerCase()!==e.submissionRevision.toLowerCase()||a(i?.head?.repo?.html_url??``)!==a(e.submissionRepository))throw Error(`GitHub pull request must target the pinned task repository and contain the current committed submission`)}function Nd(e){return{...e.authorization?{authorization:e.authorization}:{},...e.stake?{stake:e.stake}:{},join:e.join,commit:e.commit,reveal:e.reveal,report:e.report,evaluation:e.evaluation}}const Pd=$e(Te);function Fd(){return`Task source is '${_d}'. Add your fork as 'origin', commit your candidate, push it, and open a pull request before submitting.`}async function Id(e,t,n){try{let r=Bu(await ed({path:`/v1/competitions/${encodeURIComponent(e)}`,apiUrl:n.apiUrl,profile:n.profile}),`competition response`),i=ld(r.competition??r),a=D.resolve(t??i.slug),o=L(`Cloning ${i.slug}…`);n.json||o.start();try{await Pd(`git`,[`clone`,`--no-tags`,`--origin`,_d,i.repository,a],{encoding:`utf8`,maxBuffer:1e6}),await vd(a,[`checkout`,`--detach`,i.taskRevision]);let e=await vd(a,[`rev-parse`,`HEAD`]);if(e.toLowerCase()!==i.taskRevision.toLowerCase())throw Error(`Pinned checkout resolved to ${e}, expected ${i.taskRevision}`);await Ad(D.join(a,`.tangle-solve.json`),i),await xd(a)}finally{o.stop()}n.json?P({competition:i,directory:a}):(F(`Cloned ${i.slug} at ${i.taskRevision.slice(0,12)}`),i.provenance&&I(Fd()),I(`Run the pinned checker with: cd ${a} && tangle solve run`))}catch(e){V(e)}}const Ld=12e4,Rd=vt(`event JobSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint8 jobIndex, address caller, bytes inputs)`),zd=vt(`event JobCompleted(uint64 indexed serviceId, uint64 indexed callId)`),Bd=vt(`event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)`),Vd=vt(`event AggregatedResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint256 signerBitmap, bytes output)`),Hd=vt(`event EvaluationAccepted(uint64 indexed serviceId, uint64 indexed competitionId, address indexed researcher, bytes32 candidateId, bytes32 submissionRefHash, bytes32 evaluationDigest, bytes32 metricsHash, bytes32 evidenceRefsHash)`),Ud=[..._t([`function submitJob(uint64 serviceId, uint8 jobIndex, bytes inputs) payable returns (uint64 callId)`,`function getJobEventRate(uint64 blueprintId, uint8 jobIndex) view returns (uint256 rate)`,`function getServicePaymentAsset(uint64 serviceId) view returns (address)`,`function isPermittedCaller(uint64 serviceId, address caller) view returns (bool)`]),Rd,zd,Bd,Vd],Wd=_t([`function authorizeSelf(uint64 serviceId)`,`function revokeSelf(uint64 serviceId)`,`function isDeviceRevoked(address device) view returns (bool)`,`function postStake(uint64 serviceId, uint64 competitionId) payable`,`function stakes(uint64 serviceId, uint64 competitionId, address researcher) view returns (uint256)`,`function pendingResults(uint64 serviceId, uint64 jobCallId) view returns (uint8 job, bytes32 outputHash, uint256 signerBitmap, bool exists, bool executed)`,`function executePendingResult(uint64 serviceId, uint64 jobCallId, bytes output)`,`function acceptedCandidates(uint64 serviceId, uint64 competitionId, address researcher, bytes32 candidateId) view returns (bool)`]),Gd=_t([`function allowance(address owner, address spender) view returns (uint256)`,`function approve(address spender, uint256 amount) returns (bool)`]),Kd=yt(`uint64 competitionId, uint256 stakeWei`),qd=yt(`uint64 competitionId, bytes32 commitment`),Jd=yt(`uint64 competitionId, bytes32 commitment, string artifactRef, bytes32 salt`),Yd=yt(`string artifactRef, bytes32 salt`),Xd=yt(`uint64 competitionId, bytes32 candidateId, string submissionRef, string evidenceJson, string evidenceRefsJson`),Zd=yt(`string status, string detail`),Qd=/^0x[0-9a-f]{64}$/i;function $d(e,t){if(e!==t)throw Error(`Tempo RPC returned chain ${e}; expected ${t}`)}function ef(e,t,n){return{...e,feePayer:!0,nonceKey:t,nonce:n}}function tf(e,t){if(e!==`success`)throw Error(`${t} transaction reverted`)}function nf(e,t,n,r){if(!Qd.test(t))throw Error(`${n} transaction hash is invalid`);if(typeof e.transactionHash!=`string`||e.transactionHash.toLowerCase()!==t.toLowerCase())throw Error(`${n} receipt hash does not match the saved transaction`);if(tf(e.status??``,n),typeof e.from!=`string`||e.from.toLowerCase()!==r.from.toLowerCase())throw Error(`${n} receipt sender does not match the Solve device`);if(typeof e.to!=`string`||e.to.toLowerCase()!==r.to.toLowerCase())throw Error(`${n} receipt destination does not match the expected contract`)}function rf(e,t){return e>=t?[]:e>0n?[0n,t]:[t]}function af(e,t,n=Date.now()){return n>=e+t}function of(e,t){return e.filter(e=>e.args?.candidateId?.toLowerCase()===t.toLowerCase()).at(-1)?.transactionHash}function sf(e,t,n,r,i){for(let a of e.logs)if(a.address.toLowerCase()===t.tangleAddress.toLowerCase())try{let e=dt({abi:[Rd],eventName:`JobSubmitted`,data:a.data,topics:a.topics});if(e.args.serviceId===t.serviceId&&e.args.jobIndex===n&&e.args.caller.toLowerCase()===r.toLowerCase()&&(!i||e.args.inputs.toLowerCase()===i.toLowerCase()))return e.args.callId}catch{}throw Error(`Tangle did not emit job ${n} for ${r}`)}function cf(e,t,n,r){for(let i of e.logs)if(i.address.toLowerCase()===t.managerAddress.toLowerCase())try{let e=dt({abi:[Hd],eventName:`EvaluationAccepted`,data:i.data,topics:i.topics}).args;if(e.serviceId===t.serviceId&&e.competitionId===t.competitionId&&e.researcher.toLowerCase()===n.address.toLowerCase()&&e.candidateId.toLowerCase()===r.toLowerCase())return!0}catch{}return!1}function lf(e){if(e.chainId!==St.id)throw Error(`Solve submissions require Tempo Moderato (chain ${St.id}); received ${e.chainId}`);if(!e.sponsorUrl)throw Error(`Solve submissions require a Tempo sponsor relay URL; unsponsored writes are disabled`);return{...St,name:e.chainName,nativeCurrency:{name:e.nativeSymbol,symbol:e.nativeSymbol,decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}}async function uf(e,t){ad(e);let n=lf(e),r=ct({chain:n,transport:mt(e.rpcUrl)});return $d(await r.getChainId(),e.chainId),await df({publicClient:r},e),{publicClient:r,walletClient:lt({account:t,chain:n,transport:wt(mt(e.rpcUrl),mt(e.sponsorUrl))}),account:t}}async function df(e,t){let n=await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getServicePaymentAsset`,args:[t.serviceId]});if(n.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo service payment asset ${n} does not match the trusted Solve asset ${t.paymentAsset}`)}async function ff(e,t,n){let[r,i]=await Promise.all([e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getJobEventRate`,args:[t.blueprintId,n]}),e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`getServicePaymentAsset`,args:[t.serviceId]})]);if(i.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo job payment asset ${i} does not match the trusted Solve asset ${t.paymentAsset}`);return{asset:i,amount:r,value:i===`0x0000000000000000000000000000000000000000`?r:0n}}async function pf(e,t,n){return await e.publicClient.readContract({address:t,abi:Gd,functionName:`allowance`,args:[e.account.address,n.tangleAddress]})}async function mf(e,t,n,r,i,a){let o=Date.now();for(;!af(o,a);){if((await e.publicClient.getLogs({address:t.tangleAddress,event:zd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`})).length>0){let a=(await e.publicClient.getLogs({address:t.tangleAddress,event:Bd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.result;if(!a)throw Error(`Tangle job ${n} completed without a result`);let[o,s]=ut(Zd,a);if(o!==i)throw Error(`Tangle job ${n} ${o}: ${s}`);return{status:o,detail:s}}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not complete within 120 seconds`)}async function hf(e,t,n,r,i){let a=Date.now();for(;!af(a,i);){let i=(await e.publicClient.getLogs({address:t.tangleAddress,event:Vd,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.output;if(i)return i;await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not produce an aggregate within 120 seconds`)}async function gf(e,t,n){return!!await e.publicClient.readContract({address:t.managerAddress,abi:Wd,functionName:`acceptedCandidates`,args:[t.serviceId,t.competitionId,e.account.address,n]})}const _f=BigInt(gt(bt(`tangle.solve.v1`)));async function vf(e,t){let n=await Ct.nonce.getNonce(e.publicClient,{account:e.account.address,nonceKey:_f});if(n>BigInt(2**53-1))throw Error(`The Solve transaction nonce exceeds the safe range`);return e.walletClient.writeContract(ef(t,_f,Number(n)))}async function yf(e,t,n,r){if(!await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))try{let i=r??await vf(e,{address:t.managerAddress,abi:Wd,functionName:`authorizeSelf`,args:[t.serviceId]});if(r||await n?.(`authorization`,i),nf(await e.publicClient.waitForTransactionReceipt({hash:i}),i,`Authorization`,{from:e.account.address,to:t.managerAddress}),!await e.publicClient.readContract({address:t.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))throw Error(`authorization transaction did not add the device`);return i}catch(e){let t=e instanceof Error?e.message:`unknown chain error`;throw Error(`The competition manager did not authorize this device. The deployed manager must expose authorizeSelf(uint64): ${t}`)}}async function bf(e,t){let n=await vf(e,{address:t.managerAddress,abi:Wd,functionName:`revokeSelf`,args:[t.serviceId]});return nf(await e.publicClient.waitForTransactionReceipt({hash:n}),n,`Revocation`,{from:e.account.address,to:t.managerAddress}),n}async function xf(e,t,n,r,i=`allowance`,a={}){if(t.amount===0n||t.asset===`0x0000000000000000000000000000000000000000`)return;let o=await pf(e,t.asset,n);for(let s of rf(o,t.amount)){let o=s===0n?`${i}:reset`:`${i}:approval`,c=a[o];if(c){if(nf(await e.publicClient.waitForTransactionReceipt({hash:c}),c,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset}),await pf(e,t.asset,n)!==s)throw Error(`${s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`} did not set the expected allowance`);continue}let l=await vf(e,{address:t.asset,abi:Gd,functionName:`approve`,args:[n.tangleAddress,s]});await r?.(o,l),nf(await e.publicClient.waitForTransactionReceipt({hash:l}),l,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset})}}async function Sf(e,t,n,r,i,a=`job:${n}`,o={}){let s=await ff(e,t,n);await xf(e,s,t,i,`allowance:${a}`,o);let c=o[a],l=c??await vf(e,{address:t.tangleAddress,abi:Ud,functionName:`submitJob`,args:[t.serviceId,n,r],value:s.value});c||await i?.(a,l);let u=await e.publicClient.waitForTransactionReceipt({hash:l});return nf(u,l,`Job ${n}`,{from:e.account.address,to:t.tangleAddress}),{hash:l,callId:sf(u,t,n,e.account.address,r),blockNumber:u.blockNumber}}async function Cf(e,t,n,r,i,a,o=`job:${n}`,s={}){let c=await Sf(e,t,n,r,a,o,s),l=await mf(e,t,c.callId,c.blockNumber,i,Ld);return{...c,acknowledgement:l}}const wf={...Q,chainName:`Tempo Moderato`,nativeSymbol:`TNT`},Tf={async read(e){let t=ct({chain:St,transport:mt(wf.rpcUrl,{timeout:15e3})}),n=e=>e.catch(()=>null),r=await Promise.all(e.map(async e=>{let[r,i]=await Promise.all([n(t.readContract({address:wf.tangleAddress,abi:Ud,functionName:`isPermittedCaller`,args:[wf.serviceId,e]})),n(t.readContract({address:wf.managerAddress,abi:Wd,functionName:`isDeviceRevoked`,args:[e]}))]);return[e.toLowerCase(),{permitted:r,revoked:i}]}));return new Map(r)},async revokeSelf(e){return bf(await uf(wf,e),wf)}},Ef={permitted:null,revoked:null};function Df(e){return e.revoked?`revoked`:e.permitted===null?`unknown`:e.permitted?`permitted`:`not permitted`}async function Of(e,t=Tf){try{let{devices:n}=await nd({apiUrl:e.apiUrl,profile:e.profile}),r=Pu()?.account.address.toLowerCase(),i=n.map(e=>({...e,local:e.address===r,status:e.revokedAt?`revoked`:`active`}));r&&!i.some(e=>e.local)&&i.push({address:r,local:!0,status:`unbound`,boundAt:null,lastUsedAt:null,revokedAt:null,revocationMethod:null,revocationReason:null});let a=await t.read(i.map(e=>pt(e.address))),o=i.map(e=>({...e,onChain:a.get(e.address)??Ef}));if(e.json){P({serviceId:wf.serviceId.toString(),devices:o});return}Bt([`Address`,`Status`,`Local`,`Service ${wf.serviceId}`,`Last used`,`Revoked`],o.map(e=>[e.address,e.status,e.local?`yes`:``,Df(e.onChain),e.lastUsedAt??``,e.revokedAt?`${e.revokedAt} (${e.revocationMethod})`:``]))}catch(t){V(t,e.json)}}async function kf(e,t,n=Tf){try{if(!ht(e))throw Error(`${e} is not an EVM address`);let r=pt(e),i=Pu(),a=i?.account.address===r;if(!t.yes){if(!process.stdin.isTTY)throw Error(`Revoking a device is permanent. Re-run with --yes to confirm`);if(!await $r(`Permanently revoke Solve device ${r}${a?` (this machine's device)`:``}? [y/N] `,`--yes`)){I(`Revocation cancelled`);return}}let o;if(i&&a){let e=await td({deviceAddress:r,purpose:`revoke`,apiUrl:t.apiUrl,profile:t.profile});o={challengeId:e.challengeId,signature:await i.account.signMessage({message:e.message})}}let s=await rd({deviceAddress:r,reason:t.reason,...o,apiUrl:t.apiUrl,profile:t.profile}),c=r.toLowerCase(),l=(await n.read([r])).get(c)??Ef,u;if(i&&a&&!l.revoked){try{u=await n.revokeSelf(i.account)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`The Solve API revoked ${r}, but the on-chain revocation failed and the local key was kept: ${t}. Run the command again to retry`)}l=(await n.read([r])).get(c)??Ef}let d=i&&a&&l.revoked?Iu(i):void 0;if(t.json){P({...s,serviceId:wf.serviceId.toString(),onChain:l,...u?{revocationTransaction:u}:{},localKeyRetired:!!d});return}F(s.alreadyRevoked?`${r} was already revoked in the Solve API`:`Revoked ${r}; the Solve API refuses its signatures`),u&&F(`Revoked on Tempo in ${u}; service ${wf.serviceId} refuses its jobs`),d&&I("The local device key was moved aside because its address may still hold stake or rewards. Run `tangle solve account --create` for a new device"),!a&&l.permitted&&Ft(`The device can still submit jobs to service ${wf.serviceId}. Only its key, or the Solve blueprint owner, can revoke it on chain`)}catch(e){V(e,t.json)}}function Af(e,t){return gt(ft(Yd,[e.trim(),t]))}function jf(e){let t=/^submission=(\S+)/.exec(e);if(!t?.[1])throw Error(`COMMIT_CANDIDATE did not return a submission reference`);return t[1]}async function Mf(e,t,n,r,i){let a=i.resumeTransactions?.evaluation;if(a){let n=await e.publicClient.waitForTransactionReceipt({hash:a});if(nf(n,a,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!cf(n,t,e.account,r))throw Error(`Saved evaluation transaction did not emit EvaluationAccepted for this candidate`);return a}let o=Date.now();for(;!af(o,Ld);){if(await gf(e,t,r)){let i=of(await e.publicClient.getLogs({address:t.managerAddress,event:Hd,args:{serviceId:t.serviceId,competitionId:t.competitionId,researcher:e.account.address},fromBlock:n.blockNumber,toBlock:`latest`}),r);if(i)return i;throw Error(`Candidate is already accepted, but its EvaluationAccepted transaction is unavailable`)}let[a,o,,s,c]=await e.publicClient.readContract({address:t.managerAddress,abi:Wd,functionName:`pendingResults`,args:[t.serviceId,n.callId]});if(s&&a!==4)throw Error(`Manager pending result ${n.callId} has unexpected job ${a}`);if(s&&c)throw Error(`Manager executed the report without EvaluationAccepted`);if(s&&!c){if(o.toLowerCase()!==gt(n.output).toLowerCase())throw Error(`Manager pending report output does not match the aggregate`);let a=await vf(e,{address:t.managerAddress,abi:Wd,functionName:`executePendingResult`,args:[t.serviceId,n.callId,n.output]});await i.onTransaction?.(`evaluation`,a);let s=await e.publicClient.waitForTransactionReceipt({hash:a});if(nf(s,a,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!cf(s,t,e.account,r))throw Error(`Evaluation transaction did not emit EvaluationAccepted for this candidate`);return a}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Manager did not emit EvaluationAccepted within 120 seconds`)}async function Nf(e,t,n,r={}){if(ad(e),!/^0x[0-9a-f]{64}$/i.test(n.salt))throw Error(`Reveal salt must be bytes32`);if(!n.artifactRef.trim())throw Error(`Candidate reference is required`);if(!n.evidenceJson.trim()||n.evidenceRefs.length===0)throw Error(`Checker evidence is required`);let i=await uf(e,t),a=await yf(i,e,r.onTransaction,r.resumeTransactions?.authorization),o,s=await i.publicClient.readContract({address:e.managerAddress,abi:Wd,functionName:`stakes`,args:[e.serviceId,e.competitionId,i.account.address]});s<e.minStakeWei&&(o=await vf(i,{address:e.managerAddress,abi:Wd,functionName:`postStake`,args:[e.serviceId,e.competitionId],value:e.minStakeWei-s}),await r.onTransaction?.(`stake`,o),nf(await i.publicClient.waitForTransactionReceipt({hash:o}),o,`Stake`,{from:i.account.address,to:e.managerAddress}));let c=Af(n.artifactRef,n.salt),l=ft(Kd,[e.competitionId,e.minStakeWei]),u=ft(qd,[e.competitionId,c]),d=ft(Jd,[e.competitionId,c,n.artifactRef.trim(),n.salt]),f=await Cf(i,e,1,l,`joined`,r.onTransaction,`join`,r.resumeTransactions),p=await Cf(i,e,2,u,`committed`,r.onTransaction,`commit`,r.resumeTransactions),m=jf(p.acknowledgement.detail),h=await Cf(i,e,3,d,`revealed`,r.onTransaction,`reveal`,r.resumeTransactions),g=await Sf(i,e,4,ft(Xd,[e.competitionId,c,m,n.evidenceJson,JSON.stringify(n.evidenceRefs)]),r.onTransaction,`report`,r.resumeTransactions),_=await hf(i,e,g.callId,g.blockNumber,Ld),v=await Mf(i,e,{callId:g.callId,output:_,blockNumber:g.blockNumber},c,r);return{address:i.account.address,...a?{authorization:a}:{},...o?{stake:o}:{},join:f.hash,commit:p.hash,reveal:h.hash,report:g.hash,evaluation:v,candidateId:c,submissionRef:m}}const Pf=$e(Te),Ff=`/usr/bin/bwrap`,If=[`/usr`,`/bin`,`/sbin`,`/lib`,`/lib64`];function Lf(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function Rf(e,t){if(!e||e.length>2048||Lf(e))throw Error(`${t} contains invalid control characters or is too long`)}function zf(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]??``);)n+=1;return n}function Bf(e,t){if(e[t]!==`"`)throw Error(`Checker output must be valid JSON`);let n=t+1;for(;n<e.length;){let t=e[n];if(t===`\\`){n+=2;continue}if(t===`"`)return n+1;if((t?.charCodeAt(0)??0)<32)throw Error(`Checker output must be valid JSON`);n+=1}throw Error(`Checker output must be valid JSON`)}function Vf(e,t,n){let r=new Set,i=zf(e,t+1);if(e[i]===`}`)return i+1;for(;i<e.length;){let t=Bf(e,i),a=JSON.parse(e.slice(i,t));if(r.has(a))throw Error(`Checker output must not contain duplicate object keys`);if(r.add(a),i=zf(e,t),e[i]!==`:`)throw Error(`Checker output must be valid JSON`);let o=zf(e,i+1),s=Uf(e,o);if(n?.(a,o,s),i=zf(e,s),e[i]===`}`)return i+1;if(e[i]!==`,`)throw Error(`Checker output must be valid JSON`);i=zf(e,i+1)}throw Error(`Checker output must be valid JSON`)}function Hf(e,t){let n=zf(e,t+1);if(e[n]===`]`)return n+1;for(;n<e.length;){if(n=zf(e,Uf(e,n)),e[n]===`]`)return n+1;if(e[n]!==`,`)throw Error(`Checker output must be valid JSON`);n=zf(e,n+1)}throw Error(`Checker output must be valid JSON`)}function Uf(e,t){if(e[t]===`"`)return Bf(e,t);if(e[t]===`{`)return Vf(e,t);if(e[t]===`[`)return Hf(e,t);let n=t;for(;n<e.length&&!/[\s,\]}]/.test(e[n]??``);)n+=1;return n}function Wf(e){let t=e.trim();if(zf(t,Uf(t,0))!==t.length)throw Error(`Checker output must be valid JSON`)}function Gf(e,t){let n=e.trim();if(n[0]!==`{`)return;let r;return Vf(n,0,(e,i,a)=>{e===t&&(r=n.slice(i,a).trim())}),r}function Kf(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Checker output must be one JSON object`)}if(Wf(e),!t||typeof t!=`object`||Array.isArray(t))throw Error(`Checker output must be a JSON object`);let n=t,r=n.candidate_ref;if(typeof r!=`string`||!r.trim())throw Error(`Checker output must include candidate_ref`);let i=r.trim(),a=n.evidence_refs;if(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`||!e.trim()))throw Error(`Checker output must include a non-empty evidence_refs array`);Rf(i,`candidate_ref`);for(let e of a)Rf(e.trim(),`evidence_refs`);if(!n.evidence_json||typeof n.evidence_json!=`object`||Array.isArray(n.evidence_json))throw Error(`Checker output must include an evidence_json object`);let o={...n.evidence_json},s=Gf(e,`evidence_json`);if(!s)throw Error(`Checker evidence_json source text is missing`);if(o.candidate_ref!==i)throw Error(`Checker evidence_json candidate_ref must match candidate_ref`);return{candidateRef:i,evidenceRefs:a.map(e=>e.trim()),evidence:o,evidenceJson:s}}async function qf(e,t,n){let r=n.trim();if(r.startsWith(`{`)&&r.endsWith(`}`)||!t.result_file)return r;let i=await $f(e),a=D.resolve(i,t.result_file),o=D.relative(i,a);if(o.startsWith(`..`)||D.isAbsolute(o))throw Error(`Checker result_file must stay inside the competition repository`);let s;try{s=await M.lstat(a)}catch{throw Error(`Checker result_file must be an existing regular file inside the competition repository`)}if(s.isSymbolicLink())throw Error(`Checker result_file must not be a symbolic link`);if(!s.isFile())throw Error(`Checker result_file must be an existing regular file inside the competition repository`);let c;try{c=await M.realpath(a)}catch{throw Error(`Checker result_file must resolve to a regular file inside the competition repository`)}let l=D.relative(i,c);if(l.startsWith(`..`)||D.isAbsolute(l))throw Error(`Checker result_file must stay inside the competition repository`);return(await M.readFile(c,`utf8`)).trim()}function Jf(e,t){let n=D.relative(e,t);return n===``||!n.startsWith(`..`)&&!D.isAbsolute(n)}function Yf(e){return If.some(t=>Jf(t,e))}async function Xf(e,t,n){let r=e.includes(`/`)?[D.resolve(t,e)]:(process.env.PATH??``).split(D.delimiter).filter(Boolean).map(t=>D.join(t,e));for(let i of r){let r;try{r=await M.realpath(i),await M.access(r,M.constants.X_OK)}catch{continue}if(!Jf(t,r)&&!Yf(r)&&r!==n)throw Error(`Checker executable '${e}' must resolve inside the competition repository or a trusted runtime directory`);return r}throw Error(`Checker executable '${e}' was not found`)}async function Zf(e){let t=[];for(let n of e)try{(await M.stat(n)).isDirectory()&&t.push(n)}catch{}return t}async function Qf(e){let t=await M.realpath(Ce.homedir());if(e===D.parse(e).root||e===t)throw Error(`Solve checker repository must be a dedicated directory, not the filesystem or home root`)}async function $f(e){let t=await M.realpath(e);return await Qf(t),t}async function ep(e){let t=D.join(e,`.git`),n;try{n=await M.lstat(t)}catch{return}if(n.isSymbolicLink())throw Error(`Solve checker repository .git must not be a symbolic link`);if(!n.isDirectory()&&!n.isFile())return;let r;try{let t={...process.env};for(let e of[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_CONFIG_COUNT`,`GIT_CONFIG_PARAMETERS`])delete t[e];let n=await Pf(`/usr/bin/git`,[`-C`,e,`rev-parse`,`--verify`,`HEAD^{commit}`],{encoding:`utf8`,maxBuffer:1e5,env:{...t,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_CONFIG_SYSTEM:`/dev/null`,GIT_CONFIG_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}),i=String(n.stdout).trim();/^[0-9a-f]{40}$/i.test(i)&&(r=i.toLowerCase())}catch{}return{kind:n.isDirectory()?`directory`:`file`,...r?{commit:r}:{}}}async function tp(e,t,n){let r=await $f(e);if(process.platform!==`linux`)throw Error(`Solve checkers require the Linux sandbox runtime (bubblewrap) with network isolation`);try{await M.access(Ff,M.constants.X_OK)}catch{throw Error(`Solve checkers require /usr/bin/bwrap; install bubblewrap or run the checker in a Tangle sandbox`)}let i=await Xf(t,r,await M.realpath(process.execPath)),a=await ep(r),o=(await Zf(If)).flatMap(e=>[`--ro-bind`,e,e]),s=Jf(r,i)?`/work/${D.relative(r,i)}`:Yf(i)?i:`/checker/node`;!Jf(r,i)&&!Yf(i)&&o.push(`--ro-bind`,i,`/checker/node`);let c=a?.kind===`directory`?[`--tmpfs`,`/work/.git`]:a?.kind===`file`?[`--ro-bind`,`/dev/null`,`/work/.git`]:[];return{executable:Ff,args:[`--die-with-parent`,`--new-session`,`--unshare-all`,`--clearenv`,...o,`--proc`,`/proc`,`--dev`,`/dev`,`--tmpfs`,`/tmp`,`--dir`,`/tmp/home`,`--bind`,r,`/work`,...c,`--chdir`,`/work`,`--setenv`,`HOME`,`/tmp/home`,...a?.commit?[`--setenv`,`TANGLE_SOLVE_COMMIT`,a.commit]:[],`--setenv`,`TMPDIR`,`/tmp`,`--setenv`,`PATH`,`/checker:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,`--setenv`,`LANG`,`C.UTF-8`,`--setenv`,`PYTHONDONTWRITEBYTECODE`,`1`,`--setenv`,`XDG_CONFIG_HOME`,`/tmp/home/.config`,`--setenv`,`XDG_CACHE_HOME`,`/tmp/home/.cache`,`--setenv`,`XDG_DATA_HOME`,`/tmp/home/.local/share`,`--setenv`,`GIT_CONFIG_GLOBAL`,`/dev/null`,`--setenv`,`GIT_CONFIG_SYSTEM`,`/dev/null`,`--setenv`,`NPM_CONFIG_USERCONFIG`,`/dev/null`,s,...n]}}async function np(e,t){if(!t.command||t.command.includes(`/../`)||Lf(t.command))throw Error(`The competition checker command is invalid`);if(!Array.isArray(t.args))throw Error(`The competition checker arguments must be an array`);for(let e of t.args)Rf(e,`Checker argument`);let n=t.timeout_ms??15*6e4;if(!Number.isSafeInteger(n)||n<1e3||n>60*6e4)throw Error(`Checker timeout must be between one second and one hour`);let r=await $f(e),i;try{let e=await tp(r,t.command,t.args);i=await Pf(e.executable,e.args,{cwd:r,timeout:n,maxBuffer:4194304,encoding:`utf8`})}catch(e){let t=e,n=t.stderr?.trim()||t.stdout?.trim()||t.message||`checker failed`;throw Error(`Pinned checker failed: ${n}`)}let a=String(i.stdout),o=String(i.stderr);return{...Kf(await qf(r,t,a)),stdout:a,stderr:o}}async function rp(e,t){try{let{root:n,manifest:r}=await yd(e,t.directory),i=await wd(n),a=r.provenance?await Td(n,r,i,{allowMissing:!0}):void 0,o=Fu(),s=L(`Running ${r.title} checker…`);t.json||s.start();let c;try{c=await np(n,r.checker)}finally{s.stop()}let l=kd(c,a,r.provenance,void 0,{allowMissingSource:!0,requirePullRequest:!1}),u=xt(ne(32)),d=Af(c.candidateRef,u),f={version:1,competition:r.slug,candidateRef:c.candidateRef,evidence:l.evidence,evidenceJson:c.evidenceJson,evidenceRefs:l.evidenceRefs,salt:u,candidateId:d,...a?{source:a}:{},deviceAddress:o.account.address,clientSubmissionId:C(),createdAt:new Date().toISOString()};await Ad(D.join(n,`.tangle-solve-run.json`),f),t.json?P({localRun:f}):(F(`Checker output recorded locally for operator evaluation`),R({Competition:r.slug,Candidate:c.candidateRef,"Device address":o.account.address,"Evidence refs":l.evidenceRefs.length}),I("Commit any changes, then run `tangle solve submit` from this directory."),r.provenance&&!a&&I(`Add your GitHub fork as 'origin' before submitting. The task repository is available as '${_d}'.`))}catch(e){V(e)}}const ip=/^0x[0-9a-f]{64}$/i;async function ap(e){let t=await td({deviceAddress:e.deviceAddress,apiUrl:e.apiUrl,profile:e.profile}),n=await e.signer.signMessage({message:t.message});return{walletChallengeId:t.challengeId,walletSignature:n}}async function op(e,t){try{let{root:n,manifest:r}=await yd(e,t.directory);Qu({profile:t.profile});let i=await wd(n),a=await jd(n);if(a.competition!==r.slug)throw Error(`.tangle-solve-run.json does not match this competition`);if(!ip.test(a.salt)||!ip.test(a.candidateId))throw Error("This run predates durable candidate identity. Run `tangle solve run` again");let o=r.provenance?await Td(n,r,i):void 0;if(r.provenance&&a.source&&!Dd(a.source,o))throw Error("The saved run points to a different repository or revision. Keep your fork as 'origin' and run `tangle solve run` again before submitting");let s=Pu();if(!s)throw Error("No Solve device signer found. Run `tangle solve run` first");if(s.account.address.toLowerCase()!==a.deviceAddress.toLowerCase())throw Error("The local Solve device account changed after `tangle solve run`; run the checker again");let c=L(`Checking the committed candidate…`);t.json||c.start();let l;try{l=await np(n,r.checker)}finally{c.stop()}if(l.candidateRef!==a.candidateRef||l.evidenceJson!==a.evidenceJson)throw Error("The committed checker output changed after `tangle solve run`; run the checker again");if(Af(l.candidateRef,a.salt).toLowerCase()!==a.candidateId.toLowerCase())throw Error(`The saved candidate identity does not match the checker output; run the checker again`);let u=Xu(t.prUrl);if(!r.provenance&&u)throw Error(`This competition does not accept GitHub pull request provenance`);if(u){if(!o)throw Error(`A provenance policy is required for a pull request`);await Md({pullRequest:u,taskRepository:o.taskRepository,submissionRepository:o.submissionRepository,submissionRevision:i})}let d=kd(l,o,r.provenance,u,{requirePullRequest:!0}),f={...a,...o?{source:o}:{},chainState:{status:`submitting`,transactions:{...a.chainState?.transactions??{}}}},p=D.join(n,`.tangle-solve-run.json`);await Ad(p,f);let m=L(`Submitting candidate to Tempo…`);t.json||m.start();let h;try{h=await Nf(ud(r),s.account,{artifactRef:l.candidateRef,salt:a.salt,evidenceJson:l.evidenceJson,evidenceRefs:d.evidenceRefs},{resumeTransactions:f.chainState?.transactions,onTransaction:async(e,t)=>{f={...f,chainState:{status:`submitting`,transactions:{...f.chainState?.transactions??{},[e]:t}}},await Ad(p,f)}})}finally{m.stop()}f={...f,chainReceipt:h,chainState:{status:`accepted`,transactions:{...f.chainState?.transactions??{},...Nd(h)}}},await Ad(p,f);let g=await ap({deviceAddress:h.address,signer:s.account,apiUrl:t.apiUrl,profile:t.profile}),_=await ed({path:`/v1/submissions`,method:`POST`,apiUrl:t.apiUrl,profile:t.profile,body:{competition:r.slug,candidateRef:l.candidateRef,candidateId:h.candidateId,evidenceJson:l.evidenceJson,evidenceRefs:d.evidenceRefs,deviceAddress:h.address,reportTxHash:h.report,evaluationTxHash:h.evaluation,transactions:Nd(h),...r.provenance&&o?{source:{...o,...u?{pullRequest:u}:{}}}:{},clientSubmissionId:a.clientSubmissionId,...g,...t.model?{model:t.model}:{},...t.note?{note:t.note}:{}}});t.json?P({..._,transactions:Nd(h),candidateId:h.candidateId}):(F(`Submission accepted on Tempo`),R({Competition:r.slug,Candidate:h.candidateId,"Device address":h.address,"Report transaction":h.report,"Evaluation transaction":h.evaluation,"Submission ID":typeof _.id==`string`?_.id:_.submission?.id}))}catch(e){V(e)}}function sp(){let e=new b(`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(Id),e.command(`run [competition]`).description(`Run the competition checker and record its evidence`).option(`--directory <path>`,`Competition directory (defaults to the current directory)`).action(rp),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(op),e.command(`account`).description(`Show the local Solve signing account`).option(`--create`,`Create the account if it does not exist`).action(Lu);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(e=>Of(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((e,t)=>kf(e,t)),e}function cp(e,t){return`tangle ssh-proxy ${e.replace(/\/+$/,``)}/v1/sandboxes/${t}/runtime/ssh`}function lp(e){return/^[A-Za-z0-9_/:=@%+.,-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function up(e){return`'${e.replace(/'/g,`''`)}'`}function dp(e){return e===`win32`?`NUL`:`/dev/null`}function fp(e,t){return t===`win32`?`$env:TANGLE_SSH_PROXY_AUTH_TOKEN=${up(`<token>`)}; ssh ${e.map(up).join(` `)}`:`TANGLE_SSH_PROXY_AUTH_TOKEN=${lp(`<token>`)} ssh ${e.map(lp).join(` `)}`}function pp(e){return e.connection!==void 0&&!e.connection.ssh}function mp(){Pt(`SSH is not enabled for this sandbox.`),I(`Create a sandbox with --ssh to enable SSH access.`),process.exit(1)}function hp(e,t=[],n=process.platform){let r=dp(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 gp(){return new b(`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}=W(n),a=L(`Getting SSH credentials...`);a.start();let o=await K(i,r,e);if(pp(o)){a.stop(),mp();return}o=await q(o);let s=await o.ssh();if(a.stop(),!s){mp();return}let c={...s,proxyCommand:cp(r.baseUrl,o.id)};if(!r.apiKey)throw Error(`SSH proxy requires API key auth. Set TANGLE_API_KEY or pass --api-key.`);let l=hp(c,[...n.identityFile?[`-i`,n.identityFile,`-o`,`IdentitiesOnly=yes`]:[],...t]);if(n.print){console.log(fp(l,process.platform));return}I(`Connecting via tunnel...`);let u=De(`ssh`,l,{stdio:`inherit`,env:{...process.env,TANGLE_SSH_PROXY_AUTH_TOKEN:r.apiKey}});u.on(`error`,e=>{e.code===`ENOENT`&&(Pt(`SSH client not found. Please install OpenSSH.`),process.exit(1)),V(e)}),u.on(`exit`,e=>{process.exit(e??0)})})}function _p(){let e=new b(`ssh-keys`).description(`Manage SSH keys`);return e.command(`list`).description(`List SSH keys`).action(async e=>{let t=L(`Fetching SSH keys...`);try{t.start();let n=await U(H(e)).sshKeys.list();t.stop(),e.json?P({sshKeys:n}):n.length===0?I(`No SSH keys found.`):Bt([`Name`,`Type`,`Fingerprint`,`Created`],n.map(e=>[e.name,e.keyType,e.fingerprint,e.createdAt.toLocaleString()]))}catch(e){t.stop(),V(e)}}),e.command(`add`).description(`Add SSH key`).argument(`<name>`,`SSH key name`).requiredOption(`--key-file <path>`,`Public key file path`).action(async(e,t)=>{let n=L(`Adding SSH key...`);try{let r=pe(t.keyFile,`utf8`).trim();n.start();let i=await U(H(t)).sshKeys.create(e,r);n.stop(),t.json?P({sshKey:i}):F(`Added SSH key ${i.name} (${i.fingerprint})`)}catch(e){n.stop(),V(e)}}),e.command(`delete`).description(`Delete SSH key`).argument(`<name>`,`SSH key name or ID`).action(async(e,t)=>{let n=L(`Deleting SSH key...`);try{n.start(),await U(H(t)).sshKeys.delete(e),n.stop(),F(`Deleted SSH key ${e}`)}catch(e){n.stop(),V(e)}}),e}function vp(e,t=1){process.stderr.write(`${e}\n`),process.exit(t)}function yp(){return new b(`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||vp(`TANGLE_SSH_PROXY_AUTH_TOKEN not set`);let n=new Tt(new URL(e.replace(/^http/,`ws`)),{headers:{Authorization:`Bearer ${t}`},perMessageDeflate:!1}),r;function i(){r&&=(clearInterval(r),void 0)}n.on(`open`,()=>{r=setInterval(()=>{n.readyState===Tt.OPEN&&n.ping()},15e3),r.unref?.(),process.stdin.on(`data`,e=>{n.readyState===Tt.OPEN&&n.send(e,{binary:!0,compress:!1})}),process.stdin.on(`end`,()=>n.close(1e3))}),n.on(`message`,e=>{let t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e);process.stdout.write(t)}),n.on(`error`,e=>{i(),vp(`WebSocket error: ${e.message}`)}),n.on(`close`,e=>{i(),process.exit(e===1e3?0:1)}),process.stdin.on(`error`,()=>n.close())})}function bp(){let e=new b(`team`).description(`Manage teams`);return $(e,`list`).description(`List teams for the current account`).action(async e=>{let t=H(e),n=U(t),r=e.json?null:L(`Fetching teams...`);r?.start();let i=await n.teams.list();if(r?.stop(),e.json){P({teams:i,activeTeamId:t.activeTeamId??null});return}N(i.map(e=>({active:e.id===t.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}])}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=t.json?null:L(`Creating team...`);i?.start();let a=await r.teams.create({name:e,orgId:t.orgId});if(t.switch&&Es(a,n.profile),i?.stop(),t.json){P({team:a,active:!!t.switch});return}F(`Team created: ${Cs(a)}`),t.switch&&F(`Active team set to ${a.name}`)}),$(e,`switch <team>`).description(`Set the active team for the current profile`).action(async(e,t)=>{let n=H(t),r=await ws(U(n),e);if(Es(r,n.profile),t.json){P({team:r,activeTeamId:r.id});return}F(`Active team set to ${Cs(r)}`)}),e.command(`current`).description(`Show the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(e=>{let t=pr(e.profile);if(e.json){P(t.activeTeamId?t:{activeTeamId:null});return}if(!t.activeTeamId){console.log(`No active team.`);return}R({ID:t.activeTeamId,Name:t.activeTeamName})}),e.command(`clear`).description(`Clear the active team for the current profile`).option(`--profile <profile>`,`Credential profile`).action(e=>{if(Ds(e.profile),e.json){P({activeTeamId:null});return}F(`Active team cleared.`)}),$(e,`members [team]`).description(`List team members`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listMembers(i.id);if(t.json){P({team:i,members:a});return}N(a,[{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}])}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=xp(t.role),o=await r.teams.updateMember(i.id,e,{role:a});if(t.json){P({team:i,member:o});return}F(`Member updated: ${o.customerEmail}`),R({Team:i.name,Role:o.role,Status:o.status})}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=xp(t.role),o=await r.teams.invite(i.id,{email:e,role:a,ttlHours:t.ttlHours?Number.parseInt(t.ttlHours,10):void 0});if(t.json){P({team:i,invitation:o});return}F(`Invitation created for ${o.email}`),R({Team:i.name,Role:o.role,Expires:o.expiresAt,"Invitation ID":o.id}),F(`Re-run with --json to retrieve the invitation token for sharing.`)}),$(e,`leave [team]`).description(`Leave a team as the current user`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile);if(!(!t.force&&!t.json&&!await $r(`Leave team '${i.name}'? (y/N) `,`--force`))){if(await r.teams.leave(i.id),n.activeTeamId===i.id&&Ds(n.profile),t.json){P({success:!0,teamId:i.id});return}F(`Left team: ${i.name}`)}}),$(e,`transfer <new-owner-customer-id> [team]`).description(`Transfer team ownership to another active member`).option(`--force`,`Skip confirmation prompt`).action(async(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,t,r.profile);if(!(!n.force&&!n.json&&!await $r(`Transfer ownership of '${a.name}' to ${e}? This cannot be undone without the new owner's cooperation. (y/N) `,`--force`))){if(await i.teams.transferOwnership(a.id,e),n.json){P({success:!0,teamId:a.id,newOwnerCustomerId:e});return}F(`Ownership transferred for ${a.name}`)}}),e.addCommand(Sp()),e.addCommand(Cp()),$(e,`invitations [team]`).description(`List pending and historical team invitations`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listInvitations(i.id);if(t.json){P({team:i,invitations:a});return}N(a,[{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}])}),$(e,`accept <token>`).description(`Accept a team invitation`).option(`--no-switch`,`Do not set the accepted team as active`).action(async(e,t)=>{let n=H(t),r=U(n),i=await r.teams.acceptInvitation(e),a=t.switch===!1?null:await r.teams.get(i.teamId);if(a&&Es(a,n.profile),t.json){P({member:i,activeTeamId:a?.id??null});return}F(`Invitation accepted for team ${i.teamId}`),a&&F(`Active team set to ${a.name}`)}),$(e,`revoke-invitation <invitation-id>`).description(`Revoke a pending team invitation`).action(async(e,t)=>{if(await U(H(t)).teams.revokeInvitation(e),t.json){P({success:!0,invitationId:e});return}F(`Invitation revoked: ${e}`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(await r.teams.removeMember(i.id,e),t.json){P({success:!0,teamId:i.id,memberId:e});return}F(`Member removed: ${e}`)}),e}function xp(e){if(e===`admin`||e===`member`||e===`viewer`)return e;throw Error(`Role must be one of: admin, member, viewer`)}function Sp(){let e=new b(`secret`).description(`Manage team secrets`);return $(e,`list [team]`).description(`List team secret names`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listSecrets(i.id);if(t.json){P({team:i,secrets:a});return}N(a,[{key:`name`,header:`Name`,width:28},{key:`updatedAt`,header:`Updated`,width:24},{key:`updatedBy`,header:`Updated By`,width:28}])}),$(e,`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(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,n.team,r.profile),o=await Du({value:t,valueStdin:n.valueStdin,prompt:`Enter value for team secret '${e}': `}),s=await i.teams.upsertSecret(a.id,e,o);if(n.json){P({team:a,secret:s});return}F(`Team secret saved: ${s.name}`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(!(!t.force&&!t.json&&!await $r(`Delete team secret '${e}' from '${i.name}'? (y/N) `,`--force`))){if(await r.teams.deleteSecret(i.id,e),t.json){P({success:!0,teamId:i.id,name:e});return}F(`Team secret deleted: ${e}`)}}),$(e,`reveal <name>`).description(`Reveal a team secret value`).option(`-t, --team <team>`,`Team id or name (defaults to active team)`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile),a=await r.teams.revealSecret(i.id,e);if(t.json){P({teamId:i.id,...a});return}console.log(a.value)}),e}function Cp(){let e=new b(`templates`).description(`Manage team golden-path templates`);return $(e,`list [team]`).description(`List a team's golden-path templates`).action(async(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,e,n.profile),a=await r.teams.listTemplates(i.id);if(t.json){P({team:i,templates:a});return}if(a.length===0){console.log(`No templates yet for ${i.name}.`);return}N(a.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}])}),$(e,`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(e,t,n)=>{let r=H(n),i=U(r),a=await Ts(i,n.team,r.profile),o;if(n.config)try{let e=JSON.parse(n.config);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--config must be a JSON object`);o=e}catch(e){throw Error(`--config is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let s=await i.teams.createTemplate(a.id,{name:e,snapshotId:t,description:n.description,environment:n.environment,config:o});if(n.json){P({team:a,template:s});return}F(`Team template created: ${s.name} (${s.id})`)}),$(e,`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(e,t)=>{let n=H(t),r=U(n),i=await Ts(r,t.team,n.profile);if(!(!t.force&&!t.json&&!await $r(`Delete template '${e}' from '${i.name}'? (y/N) `,`--force`))){if(await r.teams.deleteTemplate(i.id,e),t.json){P({success:!0,teamId:i.id,templateId:e});return}F(`Team template deleted: ${e}`)}}),e}function $(e,t){return e.command(t).option(`--profile <profile>`,`Credential profile`)}async function wp(e,t,n){let r=new AbortController,i=()=>r.abort();try{let n=U(H({...e,timeout:void 0}));process.once(`SIGINT`,i),process.once(`SIGTERM`,i);let a=await t(n,{...e.timeout===void 0?{}:{timeoutMs:Number(e.timeout)*1e3},resumeJobId:e.resumeJob,signal:r.signal,onProgress:e=>{process.stderr.write(`Publication ${e.id}: ${e.status}\n`)}}).finally(()=>{process.off(`SIGINT`,i),process.off(`SIGTERM`,i)});e.json?P(a):F(`template`in a?`Published template: ${a.template.slug}`:`Published template version: ${a.version.id}`)}catch(t){if(t instanceof o&&t.status!==401&&t.job&&[`pending`,`scanning`,`ready`].includes(t.job.status)){let e=[`tangle`,`template`,...n,`--resume-job`,t.job.id].map(He).join(` `);Object.assign(t,{fix:{command:e}})}V(t,e.json)}}function Tp(){let e=new b(`template`).description(`Manage published public templates`);return e.command(`list`).option(`-q, --query <query>`,`Search query`).option(`--tag <tag>`,`Filter by tag`).option(`--featured`,`Show featured templates only`).action(async e=>{let t=U(H(e)),n=e.featured?await t.publicTemplates.featured():await t.publicTemplates.list({query:e.query,tag:e.tag});if(e.json){P({templates:n});return}N(n,[{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}])}),e.command(`get <id-or-slug>`).action(async(e,t)=>{let n=await U(H(t)).publicTemplates.get(e);if(t.json){P({template:n});return}P(n)}),e.command(`versions <id-or-slug>`).action(async(e,t)=>{let n=await U(H(t)).publicTemplates.versions(e);if(t.json){P({versions:n});return}N(n.map(e=>({...e})),[{key:`id`,header:`Version ID`,width:38},{key:`versionNumber`,header:`Version`,width:8},{key:`snapshotId`,header:`Snapshot`,width:20},{key:`createdAt`,header:`Created`,width:24}])}),e.command(`publish <name> <snapshot-id> <sandbox-id>`).option(`--timeout <seconds>`,`Maximum wait for publication`).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)=>wp(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])),e.command(`publish-version <id-or-slug> <snapshot-id> <sandbox-id>`).option(`--timeout <seconds>`,`Maximum wait for publication`).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)=>wp(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])),e}function Ep(){let e=new b(`traces`).description(`Read hosted agent traces, spans, and eval-runs from Tangle Intelligence`);return e.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 e=>{try{let t={from:e.from,to:e.to,model:e.model,runId:e.run,status:e.status===void 0?void 0:Lp(e.status),q:e.query,cursor:e.cursor,limit:e.limit===void 0?void 0:Hp(e.limit)},n=Op(e),r=e.json?null:L(`Fetching traces...`);r?.start();let i=await n.listTraces(t);if(r?.stop(),e.json)return P(i);jp(i.items),Fp(i.nextCursor)}catch(t){Ap(t,e)}}),e.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(e,t)=>{try{let n=Op(t);if(t.ndjson){await kp(n,e);return}let r=t.json?null:L(`Fetching trace spans...`);r?.start();let i=await n.getTraceSpans(e,{cursor:t.cursor,limit:t.limit===void 0?void 0:Hp(t.limit)});if(r?.stop(),t.json)return P(i);Mp(i.items),i.truncated&&R({Spans:`${i.items.length} of ${i.total} (truncated)`}),Fp(i.nextCursor)}catch(e){Ap(e,t)}}),e.addCommand(Dp()),e}function Dp(){let e=new b(`runs`).description(`Read eval-runs pivoted off the trace surface`);return e.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 e=>{try{let t={status:e.status===void 0?void 0:zp(e.status),gate:e.gate===void 0?void 0:Vp(e.gate),label:e.label,from:e.from,to:e.to,q:e.query,cursor:e.cursor,limit:e.limit===void 0?void 0:Hp(e.limit)},n=Op(e),r=e.json?null:L(`Fetching runs...`);r?.start();let i=await n.listRuns(t);if(r?.stop(),e.json)return P(i);Np(i.items),Fp(i.nextCursor)}catch(t){Ap(t,e)}}),e.command(`get <runId>`).description(`Show a single eval-run`).action(async(e,t)=>{try{let n=Op(t),r=t.json?null:L(`Fetching run...`);r?.start();let i=await n.getRun(e);if(r?.stop(),t.json)return P(i);Pp(i)}catch(e){Ap(e,t)}}),e}function Op(e){let t=rr(e.apiKey);if(!t)throw Error(`No API key found. Set TANGLE_API_KEY or run: tangle auth login`);return Et({apiKey:t,baseUrl:e.baseUrl??process.env.TANGLE_INTELLIGENCE_BASE_URL})}async function kp(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 Ap(e,t){return V(e,t.json===!0)}function jp(e){N(e.map(e=>({traceId:e.traceId,root:e.rootName??`-`,model:e.model??`-`,spans:e.spanCount,errors:e.errorCount,durationMs:e.durationMs,cost:Ip(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 Mp(e){N(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 Np(e){N(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 Pp(e){R({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 Fp(e){e&&R({"Next page":`--cursor ${e}`})}function Ip(e){return e===null?`-`:`$${e.toFixed(4)}`}function Lp(e){if(e===`ERROR`||e===`OK`)return e;throw Error(`--status must be ERROR or OK`)}const Rp=[`started`,`baseline-complete`,`generation-complete`,`gate-decided`,`finished`,`errored`];function zp(e){let t=Rp.find(t=>t===e);if(t)return t;throw Error(`--status must be one of ${Rp.join(`, `)}`)}const Bp=[`ship`,`hold`,`need_more_work`,`model_ceiling`,`arch_ceiling`];function Vp(e){let t=Bp.find(t=>t===e);if(t)return t;throw Error(`--gate must be one of ${Bp.join(`, `)}`)}function Hp(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`--limit must be a positive integer`);return t}function Up(){return new b(`usage`).description(`Show account usage and billing information`).action(async e=>{let{client:t}=W(e),n=e.json?null:L(`Fetching usage...`);n?.start();let[r,i]=await Promise.all([t.usage(),t.subscription().catch(()=>null)]);n?.stop(),e.json?P({...r,subscription:i}):(console.log(),console.log(`Account Usage`),console.log(`─`.repeat(40)),R({"Active Sandboxes":r.activeSandboxes,"Total Sandboxes":r.totalSandboxes,"Compute Minutes":Wp(r.computeMinutes),"GPU Seconds":r.gpuSeconds,"GPU Spend":Gp(r.gpuCostUsd)}),i&&(console.log(),console.log(`Subscription`),console.log(`─`.repeat(40)),R({Plan:i.plan,Status:i.status,"Credits Available":Gp(i.creditsAvailableUsd),"Credits Used":Gp(i.creditsUsedUsd),"Monthly Balance":Gp(i.monthlyBalanceUsd)})),console.log(),console.log(`Billing Period`),console.log(`─`.repeat(40)),R({Start:r.periodStart.toLocaleDateString(),End:r.periodEnd.toLocaleDateString()}),console.log())})}function Wp(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 Gp(e){return e<0?`-$${(-e).toFixed(2)}`:`$${e.toFixed(2)}`}function Kp(){return new b(`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){Yn(),I(`Cleared the active sandbox.`);return}if(e){Jn(e),I(`Active sandbox set to ${e}. Commands now default to it; override with --box or TANGLE_SANDBOX.`);return}let n=qn();I(n?`Active sandbox: ${n}`:"No active sandbox. Set one with `tangle use <id>`.")})}function qp(e){N(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 Jp(e){e.command(`artifacts`).description(`List a run's artifact metadata (never the bytes)`).argument(`<id>`,`Workflow ID`).argument(`<runId>`,`Run ID`).action(async(e,t,n)=>{let r=await(await X(n)).workflows.listArtifacts(e,t);if(n.json)return P(r);qp(r.artifacts)}),e.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(e,t,n,r)=>{let i=await(await X(r)).workflows.downloadArtifact(e,t,n),a=r.out??n;try{he(a,i.bytes)}catch(e){throw Error(`Could not write artifact to "${a}": ${e instanceof Error?e.message:String(e)}`)}if(r.json)return P({file:a,contentType:i.contentType,bytes:i.bytes.length});I(`Wrote ${a} (${i.bytes.length} bytes, ${i.contentType}).`)})}function Yp(e){N(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 Xp(e){e.command(`decisions`).description(`List a workflow's pending human decisions`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{let n=(await(await X(t)).workflows.listPendingDecisions()).decisions.filter(t=>t.workflowId===e);if(t.json)return P({decisions:n});Yp(n)}),e.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(e,t,n)=>{let r=await X(n),i=await r.workflows.getRunDecision(e,t),a=await r.workflows.resolveRunDecision(e,t,{decisionId:i.id,choice:n.choice});if(n.json)return P(a);if(a.resumed){I(`Resolved decision ${a.decisionId} with "${a.choice}" — run ${a.runId} resumed.`);return}I(`Resolved decision ${a.decisionId} with "${a.choice}", but run ${a.runId} had already finished — nothing to resume.`)})}function Zp(e){try{return pe(e,`utf8`)}catch(t){throw Error(`Could not read workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function Qp(e){N(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 $p(e){let t=e.workflows.filter(e=>e.failed>0).length,n=e.workflows.filter(e=>e.failed===0&&e.waiting>0).length,r=e.workflows.filter(e=>e.failed===0&&e.waiting===0&&e.runsInWindow>0).length;I(`${t} failing · ${n} waiting · ${r} healthy · ${e.workflows.length} total over ${e.window}`),N(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 em(e){if(R({ID:e.id,Name:e.name,Description:e.description??``,Enabled:e.enabled?`yes`:`no`,Actions:e.actions.length}),e.triggers&&e.triggers.length>0&&(I(`Triggers`),tm(e.triggers)),e.validationErrors.length>0){I(`Validation issues`);for(let t of e.validationErrors)console.log(` ${t.path}: ${t.message}`)}}function tm(e){N(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 nm(e){e.command(`list`).description(`List your workflows`).action(async e=>{let t=await(await X(e)).workflows.list();if(e.json)return P(t);Qp(t)}),e.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 e=>{let t=await(await X(e)).workflows.fleetInsights({window:e.window});if(e.json)return P(t);$p(t)}),e.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(e,t)=>{let n=await(await X(t)).workflows.get(e);if(t.yaml){if(n.definitionYaml===null)throw Error(`Workflow ${n.id} has no stored definition YAML to export`);process.stdout.write(n.definitionYaml.endsWith(`
|
|
163
163
|
`)?n.definitionYaml:`${n.definitionYaml}\n`);return}if(t.json)return P(n);em(n)}),e.command(`create`).description(`Create a workflow from a YAML file`).argument(`<file>`,`Path to the workflow YAML`).action(async(e,t)=>{let n=Zp(e),r=await(await X(t)).workflows.create(n);if(t.json)return P(r);I(`Created workflow ${r.id} (${r.name}).`),em(r)}),e.command(`apply`).description(`Create or update a workflow idempotently, matched by the definition's name`).argument(`<file>`,`Path to the workflow YAML`).action(async(e,t)=>{let n=Zp(e),r=await X(t),i=await r.workflows.validate(n,{structural:!0});if(!i.valid){if(process.exitCode=1,t.json)return P(i);I(`Invalid workflow:`);for(let e of i.errors)console.log(` ${e.path}: ${e.message}`);return}let a=(await r.workflows.list()).find(e=>e.name===i.name);if(a){let e=await r.workflows.update(a.id,n);if(t.json)return P({action:`updated`,workflow:e});I(`Updated workflow ${e.id} (${e.name}) — matched by name.`),em(e);return}let o=await r.workflows.create(n);if(t.json)return P({action:`created`,workflow:o});I(`Created workflow ${o.id} (${o.name}).`),em(o)}),e.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(e,t,n)=>{let r=Zp(t),i=await(await X(n)).workflows.update(e,r,{...n.note===void 0?{}:{note:n.note}});if(n.json)return P(i);I(`Updated workflow ${i.id} (${i.name}).`),em(i)}),e.command(`delete`).description(`Delete a workflow and its triggers`).argument(`<id>`,`Workflow ID`).option(`--force`,`Skip confirmation prompt`).action(async(e,t)=>{if(!t.force&&!await $r(`Delete workflow ${e}? `,`--force`)){I(`Delete cancelled.`);return}if(await(await X(t)).workflows.delete(e),t.json)return P({deleted:!0,id:e});I(`Deleted workflow ${e}.`)}),e.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(e,t)=>{let n=Zp(e),r=await(await X(t)).workflows.validate(n,{...t.structural?{structural:!0}:{}});if(t.json)return P(r);if(r.valid)I(`Valid: ${r.name} (${r.actionCount} action(s), ${r.triggerCount} trigger(s)).`);else{I(`Invalid workflow:`);for(let e of r.errors)console.log(` ${e.path}: ${e.message}`);process.exitCode=1}}),e.command(`schema`).description(`Print the JSON Schema for the workflow YAML`).action(async e=>{P(await(await X(e)).workflows.schema())})}async function rm(e,t,n){let r=await(await X(n)).workflows.setEnabled(e,t);if(n.json)return P(r);I(`${t?`Enabled`:`Disabled`} workflow ${r.id}.`),em(r)}function im(e,t){try{return JSON.parse(e)}catch{throw Error(`Invalid ${t}: not valid JSON`)}}function am(e,t){try{he(e,t,`utf8`)}catch(t){throw Error(`Could not write workflow file "${e}": ${t instanceof Error?t.message:String(t)}`)}}function om(e){N(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 sm(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 cm(e){e.command(`enable`).description(`Enable a workflow so its triggers and manual runs fire`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await rm(e,!0,t)}),e.command(`disable`).description(`Disable a workflow (pause its triggers and manual runs)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{await rm(e,!1,t)}),e.command(`templates`).description(`List the curated starter workflow templates`).action(async e=>{let t=await(await X(e)).workflows.listTemplates();if(e.json)return P(t);om(t)}),e.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.`,bc,[]).option(`--file <out>`,`Write the instantiated workflow YAML to this file instead of stdout`).action(async(e,t)=>{let n=xc(t.param,`param`)??{},r=await(await X(t)).workflows.instantiateTemplate(e,n);if(t.json)return P(r);if(!r.created){I(`Template ${e} needs provider connections before it can run:`);for(let e of r.connectionRequirements)console.log(` ${e.connected?`✓`:`✗`} ${sm(e,r.connectionRequirements)}`);process.exitCode=1;return}let{workflow:i}=r;if(i.definitionYaml===null)throw Error(`Workflow ${i.id} was created but the server returned no definition YAML`);if(I(`Created workflow ${i.id} (${i.name}).`),t.file){am(t.file,i.definitionYaml),I(`Wrote ${t.file}.`);return}process.stdout.write(i.definitionYaml.endsWith(`
|
|
164
164
|
`)?i.definitionYaml:`${i.definitionYaml}\n`)})}function lm(e){N(e,[{key:`key`,header:`Key`},{key:`version`,header:`Version`},{key:`updatedAt`,header:`Updated`}])}function um(e){R({Key:e.key,Version:e.version,Updated:e.updatedAt}),I(`Value`),P(e.value)}function dm(e){let t=e.command(`kv`).description(`Read and write a workflow's cross-run KV state`);t.command(`list`).description(`List every KV entry of a workflow`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{let n=await(await X(t)).workflows.listKv(e);if(t.json)return P(n);lm(n.entries)}),t.command(`get`).description(`Show one KV entry (value and version)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(e,t,n)=>{let r=await(await X(n)).workflows.getKv(e,t);if(n.json)return P(r);um(r)}),t.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(e,t,n,r)=>{let i=im(n,`<json>`),a=r.cas===void 0?void 0:no(r.cas,`--cas`),o=await X(r),s=a===void 0?await o.workflows.putKv(e,t,i):await o.workflows.casKv(e,t,a,i);if(r.json)return P(s);um(s)}),t.command(`delete`).description(`Delete a KV entry (idempotent)`).argument(`<id>`,`Workflow ID`).argument(`<key>`,`KV key`).action(async(e,t,n)=>{let r=await(await X(n)).workflows.deleteKv(e,t);if(n.json)return P(r);I(r.deleted?`Deleted KV entry "${t}" of workflow ${e}.`:`No KV entry "${t}" on workflow ${e}.`)})}function fm(e){N(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 pm(e){e.command(`revisions`).description(`List a workflow's definition revision history (newest first)`).argument(`<id>`,`Workflow ID`).action(async(e,t)=>{let n=await(await X(t)).workflows.listRevisions(e);if(t.json)return P(n);fm(n)}),e.command(`revision`).description(`Show one revision's metadata and definition YAML`).argument(`<id>`,`Workflow ID`).argument(`<rev>`,`Revision number`).action(async(e,t,n)=>{let r=no(t,`<rev>`),i=await(await X(n)).workflows.getRevision(e,r);if(n.json)return P(i);R({Revision:i.rev,Created:i.createdAt,"Created by":i.createdBy,Source:i.source,Note:i.note??``}),process.stdout.write(i.yaml.endsWith(`
|
|
165
165
|
`)?i.yaml:`${i.yaml}\n`)}),e.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(e,t,n)=>{let r=no(t,`<rev>`),i=await(await X(n)).workflows.rollback(e,r);if(n.json)return P(i);I(`Rolled back workflow ${i.id} to rev ${r}.`),em(i)})}function mm(){let e=new b(`workflows`).description(`Create and manage Tangle workflows`);return nm(e),Ec(e),cm(e),pm(e),dm(e),Jp(e),Xp(e),e}function hm(e){for(let[t,n]of Object.entries(e.optsWithGlobals()))e.getOptionValue(t)===void 0&&n!==void 0&&e.setOptionValue(t,n)}const gm=e(import.meta.url)(`../package.json`);function _m(){let e=new b;e.name(`tangle`).description(`CLI for Tangle Sandbox operations`).version(gm.version??`0.0.0`).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,t)=>{hm(t);let n=t.opts();Ot(n.json===!0||n.ndjson===!0)}),e.addCommand(Fi()),e.addCommand(wu()),e.addCommand(Kp()),e.addCommand(Eu()),e.addCommand(Ql()),e.addCommand(cu()),e.addCommand(lu()),e.addCommand(rs()),e.addCommand(gp()),e.addCommand(_p()),e.addCommand(yp()),e.addCommand(hi()),e.addCommand(ku()),e.addCommand(Xs()),e.addCommand(Up()),e.addCommand(bp()),e.addCommand(Tp()),e.addCommand(Wi()),e.addCommand(ta()),e.addCommand(gu()),e.addCommand(Zs()),e.addCommand(ec()),e.addCommand(Ml()),e.addCommand(Kc()),e.addCommand(mm()),e.addCommand(Ho()),e.addCommand(Tu()),e.addCommand(sp()),e.addCommand(Ou()),e.addCommand(na()),e.addCommand(mu()),e.addCommand(Nl()),e.addCommand(Fo()),e.addCommand(Io()),e.addCommand(Su()),e.addCommand(uu()),e.addCommand(Ep()),e.addCommand(Sl());function t(e){e.configureHelp({showGlobalOptions:!0}),e.configureOutput({writeErr:()=>{}}),e.exitOverride(t=>{t.exitCode===0&&process.exit(0),V(t,e.optsWithGlobals().json===!0)});for(let n of e.commands)t(n)}return t(e),e}const vm=_m();vm.parseAsync(process.argv).catch(e=>{V(e,vm.opts().json===!0)});export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/sandbox-cli",
|
|
3
|
-
"version": "0.22.
|
|
3
|
+
"version": "0.22.18",
|
|
4
4
|
"description": "CLI for Tangle Sandbox operations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -25,10 +25,10 @@
|
|
|
25
25
|
"@tangle-network/agent-runtime": "^8.0.0",
|
|
26
26
|
"@tangle-network/harness-sessions": "^1.0.2",
|
|
27
27
|
"@tangle-network/hub-sdk": "1.0.21",
|
|
28
|
-
"@tangle-network/sandbox": "^1.0.
|
|
28
|
+
"@tangle-network/sandbox": "^1.0.286",
|
|
29
29
|
"@tangle-network/sdk-cli-runner": "^0.3.10",
|
|
30
30
|
"chalk": "^5.6.2",
|
|
31
|
-
"cli-bridge": "https://github.com/drewstone/cli-bridge/archive/
|
|
31
|
+
"cli-bridge": "https://github.com/drewstone/cli-bridge/archive/5798fd5297b8705f367f95ab966df7d8e2f875d2.tar.gz",
|
|
32
32
|
"commander": "12.1.0",
|
|
33
33
|
"dotenv": "17.2.3",
|
|
34
34
|
"ora": "^9.4.1",
|
|
@@ -78,8 +78,8 @@
|
|
|
78
78
|
"author": "Tangle Network",
|
|
79
79
|
"license": "MIT",
|
|
80
80
|
"tangleRelease": {
|
|
81
|
-
"sourceSha": "
|
|
82
|
-
"mergedAt": "2026-11-
|
|
81
|
+
"sourceSha": "b3fc5be10695f69e0ee92db861b4c392635ee264",
|
|
82
|
+
"mergedAt": "2026-11-07T17:12:01-08:00"
|
|
83
83
|
},
|
|
84
84
|
"scripts": {
|
|
85
85
|
"build": "tsdown",
|