@hyperscale0/cli 1.0.0-beta.12 → 1.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/hyperscale.js +43 -38
  2. package/package.json +2 -2
package/hyperscale.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as be}from"node:child_process";import{createHash as Ke}from"node:crypto";import{createServer as Ye}from"node:http";import{createInterface as Fe}from"node:readline/promises";import{chmod as X,mkdir as qe,readdir as Me,readFile as q,rename as ze,unlink as Ve,writeFile as We}from"node:fs/promises";import{homedir as Ge}from"node:os";import{basename as Xe,dirname as te,join as M}from"node:path";var ce="https://hyperscale0.ai",ue="sandbox",de="hyperscale-cli-session",Qe="/v1/personal-access-tokens/current",ne=process.platform==="darwin"?"/usr/bin/security":null,Ze="config.json",oe="https://hyperscale0.ai/desk/security/tokens",C="https://hyperscale0.ai/request-access",O=`Mint a founder PAT in Hyperscale Portal at ${oe}. Open Security, then Personal access tokens.`,et=`Not logged in. Run "hyperscale auth login" to open Hyperscale Portal sign-in. In a headless environment, ${O} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${C}.`,tt=`Run "hyperscale auth login". For headless use, ${O} Unapproved founders can request access at ${C}.`,re=3e4,nt=2e3,ot=120*1e3,rt=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,st=`hyperscale <command> [options]
2
+ import{spawn as xe}from"node:child_process";import{createHash as Ve}from"node:crypto";import{createServer as We}from"node:http";import{createInterface as Ge}from"node:readline/promises";import{chmod as Z,mkdir as Xe,readdir as Qe,readFile as M,rename as Ze,unlink as et,writeFile as tt}from"node:fs/promises";import{homedir as nt}from"node:os";import{basename as ot,dirname as oe,join as z}from"node:path";var de="https://hyperscale0.ai",le="sandbox",pe="hyperscale-cli-session",rt="/v1/personal-access-tokens/current",re=process.platform==="darwin"?"/usr/bin/security":null,at="config.json",ae="https://hyperscale0.ai/desk/security/tokens",N="https://hyperscale0.ai/request-access",_=`Mint a founder PAT in Hyperscale Portal at ${ae}. Open Security, then Personal access tokens.`,st=`Not logged in. Run "hyperscale auth login" to open Hyperscale Portal sign-in. In a headless environment, ${_} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${N}.`,it=`Run "hyperscale auth login". For headless use, ${_} Unapproved founders can request access at ${N}.`,se=3e4,ct=2e3,ut=120*1e3,dt=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,lt=`hyperscale <command> [options]
3
3
 
4
4
  Commands:
5
5
  start Create a Product and run its first published journey step
@@ -31,8 +31,8 @@ Options:
31
31
  --revoke Revoke the active founder PAT during auth logout
32
32
  --no-browser Skip browser login and print the founder PAT path
33
33
  --api-key <key> Product API key (default: $HYPERSCALE_API_KEY)
34
- --base-url <url> API origin (default: $HYPERSCALE_BASE_URL, else ${ce})
35
- --environment <name> sandbox or live (default: $HYPERSCALE_ENVIRONMENT, else ${ue})
34
+ --base-url <url> API origin (default: $HYPERSCALE_BASE_URL, else ${de})
35
+ --environment <name> sandbox or live (default: $HYPERSCALE_ENVIRONMENT, else ${le})
36
36
  --blueprint <slug> Blueprint for non-interactive start or product create
37
37
  --name <name> Product or key name
38
38
  --product <id> Product id for key commands and Product-key actions
@@ -55,14 +55,16 @@ login returns through a single-use localhost callback.
55
55
  compose check, plan, and apply exit 2 when the compiler or composer refuses the
56
56
  program. Command, credential, request, and server failures exit 1. compose apply
57
57
  requires --confirm, or --yes for an agent.
58
+ Compose check and plan JSON retain operationId and receiptId when the server
59
+ returns them. Plan JSON includes the prerequisite check result and its identifiers.
58
60
 
59
61
  Use HYPERSCALE_TOKEN for a founder PAT. Use HYPERSCALE_API_KEY for a Product API
60
62
  key. The explicit flag wins over its environment variable. Founder logins use
61
63
  macOS Keychain when available. Set HYPERSCALE_CREDENTIAL_STORE=file to keep the
62
64
  founder PAT in the owner-only CLI profile instead and skip Keychain access.
63
65
 
64
- ${O}
65
- Request access at ${C}.
66
+ ${_}
67
+ Request access at ${N}.
66
68
 
67
69
  Examples:
68
70
  hyperscale start
@@ -85,37 +87,40 @@ Examples:
85
87
  hyperscale call account.list --input-file input.json
86
88
  printf '{"limit":5}' | hyperscale call account.list
87
89
  hyperscale call account.retrieve --input '{"accountId":"acct_sandbox_..."}'
88
- `,ye={start:{usage:"start [--blueprint <slug>] [--name <name>] [--json]",summary:"Choose a catalog company, create its Product, and run its first published runnable journey step.",options:["--blueprint <slug> Skip the prompt and choose this catalog Blueprint.","--name <name> Product name. Defaults to the selected Blueprint name.","--json Print one machine document, including the one-time API key under shown_once."],notes:["The command requires an active founder login.","Without --blueprint, start requires an interactive terminal and asks which company to build.","Scripts and agents must pass --blueprint <slug>.","Machine output returns the Product API key only under shown_once.","A Blueprint without a published runnable journey stops after composition and names the next command."],example:"hyperscale start --blueprint vehicle-escrow-marketplace --json"},"auth login":{usage:"auth login [--no-browser] [--token <pat>]",summary:"Sign in through the portal callback or save a founder PAT.",options:["--no-browser Skip the portal callback. Print where to mint a PAT when no token is set.","--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN.","--json Print the saved session summary as one JSON document."],notes:["Without a PAT, the CLI opens portal sign-in and accepts one localhost callback.","Headless environments should pass --no-browser and set HYPERSCALE_TOKEN or --token to a portal-minted founder PAT.","Set HYPERSCALE_CREDENTIAL_STORE=file to use the 0600 profile file instead of macOS Keychain."],example:"hyperscale auth login --no-browser"},"auth status":{usage:"auth status [--json]",summary:"Verify and show the active founder PAT and selected Product.",options:["--json Print machine-readable JSON."],example:"hyperscale auth status --json"},"auth logout":{usage:"auth logout [--revoke] [--json]",summary:"Forget the local founder PAT. Optionally revoke it first.",options:["--revoke Revoke the PAT before deleting local state.","--json Print machine-readable JSON."],example:"hyperscale auth logout --revoke"},"blueprint list":{usage:"blueprint list [--json]",summary:"List public Blueprints without authentication.",options:["--json Print the complete collection as JSON."],example:"hyperscale blueprint list"},"blueprint show":{usage:"blueprint show <id> [--json]",summary:"Show one public Blueprint.",options:["--json Print the complete Blueprint as JSON."],example:"hyperscale blueprint show luxury-goods-consignment-escrow"},"product create":{usage:"product create --blueprint <id> --name <name> [--json]",summary:"Create and select a Product. The command refuses a duplicate name.",options:["--blueprint <id> Required Blueprint id.","--name <name> Required Product name.","--json Print the creation summary as JSON."],example:'hyperscale product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"'},"product list":{usage:"product list [--json]",summary:"List Products in the signed-in company.",options:["--json Print the complete collection as JSON."],example:"hyperscale product list"},"product show":{usage:"product show [id] [--json]",summary:"Show a Product summary, or the complete Product document as JSON.",options:["--json Print the complete Product document."],example:"hyperscale product show prd_sandbox_..."},"product select":{usage:"product select <id> [--json]",summary:"Verify a Product and save it as the default for later commands.",options:["--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN or the stored login.","--base-url <url> API origin. Defaults to the active founder profile.","--environment <name> sandbox or live. Defaults to the active founder profile.","--json Print the selected Product id as JSON."],notes:["The CLI stores the selection in the active founder profile.","Product show, compose plan/apply, and key commands use it when --product is absent.","Product create and start select the Product they create."],example:"hyperscale product select prd_sandbox_..."},"product actions":{usage:"product actions [operation-id] [--product <id>] [--json]",summary:"List frozen public actions or show one action's full schemas.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print machine-readable JSON."],notes:["Setup operation details include the public input schema used by hyperscale call.","When that schema has no required fields, omit --input or pass {}."],example:"hyperscale product actions escrow_order.placeBuyerHold --json"},"product run":{usage:"product run <operation-id> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--json]",summary:"Run one frozen public action with a Product API key.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header. The default is a generated UUID.","--json Print the key, receipt ids, and output as JSON."],notes:["Reuse an Idempotency-Key only with the same operation and input.",'If a bounded validation value appears as "[Truncated]", run "hyperscale product actions <operation-id>" for the full input schema.'],example:`hyperscale product run escrow_order.placeBuyerHold --input '{"escrowOrderId":"eord_sandbox_..."}' --idempotency-key hold-001`},"compose check":{usage:"compose check <file.hsx> [--catalog-revision <id>] [--json]",summary:"Ask the server to compile and check an HSX program.",options:["--catalog-revision <id> Compile against this immutable tenant catalog revision.","--json Print diagnostics and the verdict as JSON."],example:"hyperscale compose check product.hsx"},"compose plan":{usage:"compose plan <file.hsx> [--product <id>] [--catalog-revision <id>] [--json]",summary:"Diff an HSX program against a Product.",options:["--product <id> Product to compare. Defaults to the selected Product.","--catalog-revision <id> Compile against this immutable tenant catalog revision.","--json Print the plan as JSON."],example:"hyperscale compose plan product.hsx --json"},"compose apply":{usage:"compose apply <file.hsx> (--confirm | --yes) [--product <id>] [--catalog-revision <id>] [--json]",summary:"Recompose a Product from checked HSX.",options:["--confirm Confirm the mutation for a person.","--yes Confirm the mutation without a prompt for an agent.","--product <id> Product to recompose. Defaults to the selected Product.","--catalog-revision <id> Compile and persist against this immutable tenant catalog revision.","--json Print the result as JSON."],example:"hyperscale compose apply product.hsx --yes"},"key create":{usage:"key create [--name <name>] [--product <id>] [--json]",summary:"Create a sandbox Product API key.",options:["--name <name> Key name. Defaults to Founder CLI.","--product <id> Product for the key. Defaults to the selected Product.","--json Print the one-time secret and key metadata as JSON."],example:'hyperscale key create --name "Founder laptop"'},"key list":{usage:"key list [--product <id>] [--json]",summary:"List keys for one Product.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--json Print the collection as JSON."],example:"hyperscale key list --json"},"key revoke":{usage:"key revoke <id> [--product <id>] [--json]",summary:"Revoke one Product API key.",options:["--product <id> Product that owns the key. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale key revoke key_sandbox_..."},"activity list":{usage:"activity list [--json]",summary:"List company activity with timestamps and resource targets.",options:["--json Print the complete collection as JSON."],example:"hyperscale activity list"},whoami:{usage:"whoami [--json]",summary:"Show the user and company the founder PAT resolves to.",options:["--json Print machine-readable JSON."],example:"hyperscale whoami --json"},"ops list":{usage:"ops list [filter] [--product <id>] [--json]",summary:"List callable operations from the Product machine document.",options:["--product <id> Product to inspect. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print matching operations as JSON."],example:"hyperscale ops list account"},call:{usage:"call <operation> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--product <id>]",summary:"Call one operation from the Product machine document.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header for a mutation. The default is a generated UUID."],notes:["Reuse an Idempotency-Key only with the same operation and input."],example:`hyperscale call account.create --input '{"currency":"SAR"}'`}};function at(e){let n=Object.keys(ye).sort((o,s)=>s.split(" ").length-o.split(" ").length).find(o=>o.split(" ").every((i,c)=>e[c]===i));if(!n)throw new u(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`);let r=ye[n];return[`Usage: hyperscale ${r.usage}`,"",r.summary,"","Options:",...r.options.map(o=>` ${o}`),...r.notes?["","Notes:",...r.notes.map(o=>` ${o}`)]:[],"","Example:",` ${r.example}`,""].join(`
89
- `)}var u=class extends Error{constructor(t,n={}){super(t),typeof n.code=="string"&&(this.code=n.code),n.details!==void 0&&(this.details=n.details),Number.isInteger(n.exitCode)&&(this.exitCode=n.exitCode),typeof n.fix=="string"&&(this.fix=n.fix)}},x=class extends u{constructor(t,{requestId:n,status:r,code:o,details:s,operationId:i,receiptId:c,traceId:d,structuredError:l}={}){super(t,{code:o,details:s}),this.requestId=n,this.status=r,this.operationId=i??null,this.receiptId=c??null,this.traceId=d??null,this.structuredError=l}};function Q(){return new u(et,{fix:tt})}function Se(e){let t=e??"<id>";return new u(`This command needs a Product API key. Create one with "hyperscale key create --name 'Founder CLI' --product ${t}", then set HYPERSCALE_API_KEY or pass --api-key.`)}var J=class extends u{constructor(t,n){super(t),this.code="check_failed",this.details=n,this.exitCode=2}},Ae=new Set(["--api-key","--base-url","--blueprint","--catalog-revision","--environment","--idempotency-key","--input","--input-file","--name","--product","--token"]);function it(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let o=e[r];if(!o.startsWith("--")){t.push(o);continue}if(Ae.has(o)){let s=e[r+1];if(s===void 0)throw new u(`${o} needs a value`);n[o]=s,r+=1;continue}if(o==="--help"||o==="--version"||o==="--json"||o==="--confirm"||o==="--yes"||o==="--no-browser"||o==="--passkey"||o==="--revoke"){n[o]=!0;continue}throw new u(`Unknown option: ${o}`)}return{flags:n,positional:t}}function we(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Se();let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??ue;if(r!=="sandbox"&&r!=="live")throw new u(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??ce).replace(/\/+$/,"");return{apiKey:n,baseUrl:o,environment:r}}function _(e,t,n={}){let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??ue;if(r!=="sandbox"&&r!=="live")throw new u(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??ce).replace(/\/+$/,""),s;try{s=new URL(o)}catch{s=null}let i=s?.origin??null;if(!i||i!==o)throw new u(`Invalid API origin: ${o}. Use an origin such as https://hyperscale0.ai.`);let c=["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&c))throw new u(`Refusing cleartext API origin ${o}. Use HTTPS unless the API runs on loopback.`);return{baseUrl:o,environment:r}}function Te(e){return e.HYPERSCALE_CONFIG_DIR??M(Ge(),".config","hyperscale")}function xe(e){return M(Te(e),Ze)}function P(e,t){return M(Te(t),`session-${j(e)}.json`)}function z(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new u(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function le(e,t){let n=P(e,t),r=`${Xe(n)}.`,o;try{o=await Me(te(n),{withFileTypes:!0})}catch(s){if(s&&s.code==="ENOENT")return;throw s}for(let s of o){if(!s.isFile()||!s.name.startsWith(r))continue;let i=s.name.slice(r.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(i)&&await R(M(te(n),s.name))}}async function ct(e){try{return JSON.parse(await q(e,"utf8"))}catch(t){if(t&&t.code==="ENOENT")return null;throw t instanceof SyntaxError?new u(`${e} is not valid JSON`):t}}async function N(e,t){let n=ut(e);await qe(n,{mode:448,recursive:!0}),await X(n,448);let r=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await We(r,t,{flag:"wx",mode:384}),await X(r,384);try{await ze(r,e),await X(e,384)}catch(o){throw await R(r),o}}function ut(e){return te(e)}async function R(e){try{await Ve(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new u(`${t} does not contain a CLI profile`);let{baseUrl:n,email:r,environment:o,selectedProduct:s}=e;if(typeof n!="string"||typeof r!="string"||o!=="sandbox"&&o!=="live"||!(s===null||typeof s=="string"))throw new u(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:r,environment:o,selectedProduct:s}}async function V(e){let t=xe(e),n=await ct(t);return n===null?null:dt(n,t)}async function W(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await N(xe(e),`${JSON.stringify(n,null,2)}
90
- `)}function j(e){return Ke("sha256").update(`${e.baseUrl}\0${e.environment}\0${e.email}`).digest("hex")}async function G(e,t){return ne===null?{error:null,status:null,stdout:"",unavailable:!0}:await new Promise(n=>{let r={...process.env};delete r.HYPERSCALE_API_KEY,delete r.HYPERSCALE_TOKEN;let o=be(ne,e,{env:r,stdio:["pipe","pipe","pipe"]}),s=[],i=!1,c=l=>{i||(i=!0,clearTimeout(d),n(l))},d=setTimeout(()=>{o.kill("SIGKILL"),c({error:null,status:null,stdout:"",unavailable:!0})},nt);o.stdout.on("data",l=>s.push(l)),o.stderr.on("data",()=>{}),o.stdin.on("error",()=>{}),o.once("error",l=>c({error:l,status:null,stdout:"",unavailable:!0})),o.once("close",l=>c({error:null,status:l,stdout:Buffer.concat(s).toString("utf8"),unavailable:!1})),t===void 0?o.stdin.end():o.stdin.end(`${t}
91
- `)})}async function pe(){return(await G(["show-keychain-info"])).status===0}function Ee(e){try{let t=typeof e=="string"?JSON.parse(e):e;if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.token=="string"&&typeof t.tenantId=="string"&&(t.personalAccessTokenId===void 0||typeof t.personalAccessTokenId=="string")&&(t.tokenName===void 0||typeof t.tokenName=="string"))return{token:t.token,tenantId:t.tenantId,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.tokenName?{tokenName:t.tokenName}:{}}}catch{}return null}async function lt(e,t,n){await le(e,n);let r=j(e);if(z(n)==="auto"&&await pe()){let o=JSON.stringify(t),s=["add-generic-password","-a",r,"-s",de,"-U","-X",Buffer.from(o,"utf8").toString("hex")].join(" ");if((await G(["-i"],s)).status===0)return await R(P(e,n)),"keychain"}return await N(P(e,n),`${JSON.stringify({account:r,activeStore:"file",credential:t})}
92
- `),"file"}async function pt(e,t){let n=j(e);try{let r=JSON.parse(await q(P(e,t),"utf8"));if(!r||typeof r!="object"||Array.isArray(r)||r.account!==n)return{state:"invalid"};if(r.revoked===!0)return{state:"revoked"};let o=Ee(r.credential);return o?{activeStore:r.activeStore==="file"?"file":null,credential:o,state:"valid"}:{state:"invalid"}}catch(r){return r&&r.code==="ENOENT"?{state:"missing"}:{state:"invalid"}}}async function ve(e,t){await le(e,t);let n=z(t),r=await pt(e,t);if(r.state==="revoked")return null;if(r.state==="valid"&&(r.activeStore==="file"||n==="file"))return r.credential;if(n==="file")return null;let o=null;if(await pe()){let s=await G(["find-generic-password","-a",j(e),"-s",de,"-w"]);s.status===0&&(o=Ee(s.stdout.trim()))}return o||(r.state==="valid"?r.credential:null)}async function Ne(e,t){await le(e,t);let n=j(e);if(z(t)==="file")return await N(P(e,t),`${JSON.stringify({account:n,revoked:!0})}
93
- `),{keychainDeleted:!0};if(ne===null)return await R(P(e,t)),{keychainDeleted:!0};if(!await pe())return await N(P(e,t),`${JSON.stringify({account:n,revoked:!0})}
94
- `),{keychainDeleted:!1};let r=await G(["delete-generic-password","-a",n,"-s",de]);return r.status!==0&&r.status!==44?(await N(P(e,t),`${JSON.stringify({account:n,revoked:!0})}
95
- `),{keychainDeleted:!1}):(await R(P(e,t)),{keychainDeleted:!0})}function Ce(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function I(e,t,n=!1){let r=await V(t),o=Ce(e,t);if(o!==void 0){if(!o)throw Q();let c=_(e,t,r??{}),d=await A(c,o),l=r?.baseUrl===c.baseUrl&&r.environment===c.environment&&r.email===d.email;return{...c,email:d.email,identity:d,personalAccessTokenId:d.personalAccessTokenId,selectedProduct:l?r.selectedProduct:null,tenantId:d.tenantId,token:o,tokenName:d.name}}if(!r){if(n)return null;throw Q()}let s=_(e,t,r);if(s.baseUrl!==r.baseUrl||s.environment!==r.environment)throw new u(`The active founder login belongs to ${r.baseUrl} (${r.environment}). Log in again to change it.`);let i=await ve(r,t);if(!i){if(n)return null;throw Q()}return{...r,...i}}function B(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
96
- \r`.includes(t)?t:"")}function K(e){try{return new URL(e).origin}catch{return null}}function S(e,t){let n=e;for(let r of t)typeof r=="string"&&r.length>0&&(n=n.replaceAll(r,"[redacted]"));return n}async function Oe(e,t,n={},r){let o=`${e.baseUrl}${t}`,s=K(e.baseUrl);if(K(o)!==s)throw new u(`The requested path ${t} leaves the ${s} origin; refusing the request.`);try{let i=await fetch(o,{...n,headers:{accept:"application/json",...r?{authorization:`Bearer ${r}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(re),redirect:"manual"});if(i.status>=300&&i.status<400)throw new u(`${o} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`);return{response:i,text:B(await i.text())}}catch(i){throw i instanceof u?i:new u(`Could not reach ${o}: ${i.message}`)}}async function k(e,t,n={},r,o=[]){let{response:s,text:i}=await Oe(e,t,n,r);if(!s.ok)throw U(s,i,o);try{return JSON.parse(i)}catch{throw new u(`HTTP ${s.status} returned invalid JSON`)}}function b(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function mt(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function L(e,t,n={},r){let o=`${e.baseUrl}${t}`,s=K(e.baseUrl);if(K(o)!==s)throw new u(`The product document puts ${t} on another origin than the ${s} you configured; refusing to send the key there.`);try{let i=await fetch(o,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(re),redirect:"manual"});if(i.status>=300&&i.status<400)throw new u(`${o} redirected, so the key was not sent on. Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://.`);return{response:i,text:B(await i.text())}}catch(i){throw i instanceof u?i:r&&(i?.name==="TimeoutError"||i?.name==="AbortError")?new u(`product run ${r} timed out after ${re/1e3} seconds.`):new u(`Could not reach ${o}: ${i.message}`)}}async function _e(e){let{response:t,text:n}=await L(e,"/v1/product.json");if(!t.ok)throw U(t,n,[e.apiKey]);let r=ft(n);if(!r)throw new Error("The product document is not in the expected format; upgrade the CLI.");let o=r.operations.map(s=>{if(typeof s.summary!="string"||typeof s.description!="string")throw new u(`The product document carries no prose for ${s.operationId}. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);return{description:s.description,idempotency:s.idempotency,method:s.method,name:s.name,operationId:s.operationId,path:s.path,summary:s.summary}});return{compositionId:r.composition.id,operations:o,packageName:r.sdk?r.sdk.packageName.trim():null,title:r.title.trim()}}function ft(e){let t;try{t=JSON.parse(e)}catch{return null}let n=se(t),r=o=>typeof o=="string";if(!v(n)||n.schemaVersion!==1||!r(n.title)||!v(n.composition)||!r(n.composition.id)||!Array.isArray(n.operations))return null;for(let o of n.operations)if(!v(o)||!r(o.method)||!r(o.path)||!r(o.name)||!r(o.operationId)||!r(o.idempotency))return null;return n.sdk!==void 0&&(!v(n.sdk)||!r(n.sdk.packageName))?null:n}function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e){return typeof e=="string"?B(e):Array.isArray(e)?e.map(se):v(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[B(t),se(n)])):e}function Re(e){let t=e.get("x-trace-id");if(t&&t.trim()!=="")return t.trim();let n=e.get("traceparent");if(n){let r=/^00-([0-9a-fA-F]{32})-[0-9a-fA-F]{16}-[0-9a-fA-F]{2}$/.exec(n.trim());if(r)return r[1]}return null}function ht(e){if(!e||e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function yt(e,t=[],n){let r;try{r=JSON.parse(e)}catch{r=null}let o=r&&typeof r=="object"&&r.error&&typeof r.error=="object"?r.error:null,s=typeof o?.code=="string"?o.code:void 0,i=typeof o?.message=="string"?o.message:e.trim(),c=S(i,t),d=s&&typeof o?.message=="string"?`${s}: ${c}`:c,l=o?.details!==void 0?F(o.details,t):void 0,p=r&&typeof r=="object"&&typeof r.requestId=="string"?r.requestId:void 0,m=n?`HTTP ${n}`:"HTTP error";return{code:s,details:l,humanMessage:d,redactedMessage:c,requestId:p,structuredError:{code:s??"http_error",message:c||m,...l!==void 0?{details:l}:{}}}}function U(e,t,n=[]){let r=yt(t,n,e.status),o=e.headers.get("x-request-id")??r.requestId??null,s=e.headers.get("hyperscale-operation-id")??null,i=e.headers.get("hyperscale-receipt-id")??null,c=Re(e.headers),d=r.humanMessage;return new x(`HTTP ${e.status}${d?` \xB7 ${d}`:""}${o?`
97
- Request id: ${o}`:""}`,{code:r.code,details:r.details,operationId:s,receiptId:i,requestId:o,status:e.status,structuredError:r.structuredError,traceId:c})}function me(e,t){return{authenticated:!0,baseUrl:e.baseUrl,email:t.email,environment:e.environment,expiresAt:t.expiresAt,personalAccessTokenId:t.personalAccessTokenId,role:t.role,scopes:t.scopes,selectedProduct:e.selectedProduct,teamId:t.teamId,tenantId:t.tenantId,tokenName:t.name,userId:t.userId}}function wt(e){if(!e||typeof e!="object"||typeof e.userId!="string"||typeof e.email!="string"||typeof e.tenantId!="string"||typeof e.teamId!="string"||typeof e.role!="string"||typeof e.personalAccessTokenId!="string"||typeof e.name!="string"||!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string")||typeof e.expiresAt!="string"||e.status!=="active")throw new u("personal_access_token.current returned invalid data");return e}async function A(e,t){try{return wt(await k(e,Qe,{},t,[t]))}catch(n){throw!(n instanceof x)||n.status!==401?n:new u(`That founder PAT was not accepted (HTTP 401). ${O}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:O})}}function gt(e,t){return e.HYPERSCALE_CLI_BROWSER?{command:e.HYPERSCALE_CLI_BROWSER,args:[t]}:e.HYPERSCALE_NO_BROWSER==="1"||e.CI==="1"||e.CI==="true"||process.platform==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?null:process.platform==="darwin"?{command:"/usr/bin/open",args:[t]}:process.platform==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:{command:"xdg-open",args:[t]}}async function kt(e,t){let n=gt(e,t);return n?new Promise(r=>{let o=be(n.command,n.args,{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}):!1}function Z(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function $t(e,t){let n=globalThis.crypto.randomUUID(),r=!1,o,s=new Promise((g,y)=>{o={reject:y,resolve:g}}),i=Ye((g,y)=>{let w=new URL(g.url??"/","http://127.0.0.1");if(g.method!=="GET"||w.pathname!=="/callback"){y.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),y.end(`Not found.
98
- `);return}if(r){y.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login callback was already received.
99
- `);return}if(w.searchParams.get("state")!==n){y.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login state did not match. Return to the terminal.
100
- `);return}if(w.searchParams.get("error")!==null){r=!0,y.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login declined. Return to the terminal.
101
- `),o.reject(new u("Portal login was declined. Run hyperscale auth login to start again.",{code:"auth_callback_denied"}));return}let H=w.searchParams.get("grant"),he=w.searchParams.get("tenantId");if(!H||!he){y.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login callback is missing its grant or tenant.
102
- `);return}r=!0,y.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login received. Return to the terminal.
103
- `),o.resolve({grant:H,tenantId:he})});await new Promise((g,y)=>{let w=H=>y(H);i.once("error",w),i.listen(0,"127.0.0.1",()=>{i.off("error",w),g()})}),i.once("error",g=>o.reject(g));let c=i.address();if(!c||typeof c=="string")throw await Z(i),new u("Could not bind the localhost login callback");let d=`http://127.0.0.1:${c.port}/callback`,l=new URL("/auth/cli",e.baseUrl);l.searchParams.set("callback",d),l.searchParams.set("state",n);let p=new URL("/signin",e.baseUrl);p.searchParams.set("returnTo",`${l.pathname}${l.search}`);let m=p.toString();if(!await kt(t,m))return await Z(i),null;process.stderr.write(`Opening portal sign-in: ${m}
104
- `);let $=setTimeout(()=>{o.reject(new u("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},ot);try{return await s}finally{clearTimeout($),await Z(i)}}function ge(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:oe,requestAccessUrl:C};if(e["--json"]){f(t);return}a("No browser detected. Mint a founder PAT in the portal, then run:");for(let n of t.next)a(` ${n}`);a(`PAT desk: ${oe}`),a(`No access yet: ${C}`)}async function ke(e,t,n,r,o){let s=await V(o),i={email:t.email,...e,selectedProduct:s&&s.email===t.email&&s.baseUrl===e.baseUrl&&s.environment===e.environment?s.selectedProduct:null},c=await lt(i,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},o);try{await W(o,i)}catch(l){throw await Ne(i,o),l}if(c==="file"){let l=z(o)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${l} The founder PAT is in ${P(i,o)} with mode 0600.
105
- `)}let d=me(i,t);r["--json"]?f(d):a(`Logged in as ${t.email} with PAT ${t.name}.`)}async function It(e,t){let n=_(e,t),r=Ce(e,t);if(r){if(!r.startsWith("hyperscale_pat_"))throw new u("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let d=await A(n,r);await ke(n,d,r,e,t);return}if(e["--no-browser"]){ge(e);return}let o=await $t(n,t);if(!o){ge(e);return}let s=await k(n,"/v1/personal-access-token-login-grants/exchange",b({tenantId:o.tenantId,grant:o.grant}),void 0,[o.grant]),i=s?.secret;if(typeof i!="string"||!i.startsWith("hyperscale_pat_")||s?.tenantId!==o.tenantId)throw new u("CLI login grant exchange returned an invalid PAT");let c=await A(n,i);await ke(n,c,i,e,t)}async function Pt(e,t){let n=await I(e,t),r=n.identity??await A(n,n.token),o=me(n,r);if(e["--json"]){f(o);return}a(`User: ${r.email}`),a(`Tenant: ${r.tenantId}`),a(`Role: ${r.role}`),a(`Token: ${r.name}`),a(`Scopes: ${r.scopes.join(", ")}`),a(`Expires: ${r.expiresAt}`),a(`API: ${n.baseUrl}`),a(`Environment: ${n.environment}`),a(`Product: ${n.selectedProduct??"not selected"}`)}async function bt(e,t){let n=await V(t);if(!n){e["--json"]?f({status:"signed_out"}):a("Already logged out.");return}let r=await ve(n,t);if(e["--revoke"]&&!r)throw new u("The local founder PAT is missing, so the CLI cannot revoke it.");let o=r?.personalAccessTokenId,s=r?.tokenName;if(e["--revoke"]&&r){if(!o||!s){let d=await A(n,r.token);o=d.personalAccessTokenId,s=d.name}await k(n,`/v1/personal-access-tokens/${encodeURIComponent(o)}/revoke`,b({tenantId:r.tenantId,personalAccessTokenId:o}),r.token,[r.token])}let i=await Ne(n,t),c=e["--revoke"]===!0;St(e,{cleanup:i,personalAccessTokenId:o,revoked:c,status:"signed_out",tokenName:s})}function St(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])f({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let r=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?a(`Revoked founder PAT ${r} and forgot local state.`):(a(`Forgot local founder PAT ${r}.`),a("The PAT stays valid until expiry; revoke at /desk/security/tokens."))}t.cleanup.keychainDeleted||process.stderr.write(`Keychain cleanup failed. A 0600 profile tombstone blocks the stale founder PAT.
106
- `)}function T(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new u(`${t} returned an invalid collection`);return e.items}async function E(e,t,n,r,o,s=[]){let i=[],c=new Set,d,l;for(;;){let $=new URLSearchParams(n);d&&$.set("cursor",d);let g=$.size>0?`?${$}`:"",y=await k(e,`${t}${g}`,{},o,s);l===void 0&&(l=y),i.push(...T(y,r));let w=y.nextCursor;if(typeof w!="string"||w.length===0)break;if(c.has(w))throw new u(`${r} repeated cursor ${w}`);c.add(w),d=w}let{items:p,nextCursor:m,...h}=l;return{...h,items:i}}async function At(e,t){let n=await E(e,"/v1/blueprints",{},"blueprint.list"),r=T(n,"blueprint.list");if(t["--json"]){f(n);return}a("ID Name Summary");for(let o of r)a(`${o.id} ${o.name}${o.summary?` ${o.summary}`:""}`);a("Next:"),a(" hyperscale blueprint show <id>"),a(" hyperscale product create --blueprint <id> --name <name>")}async function Tt(e,t,n){if(!n)throw new u("blueprint show needs a Blueprint id");let r=await k(e,`/v1/blueprints/${encodeURIComponent(n)}`),o=xt(r,e.baseUrl);if(t["--json"]){f(o);return}a(`${o.name} (${o.id})`),a(o.summary),a(o.description),a("Nouns:");for(let s of o.customInstruments??[])a(` ${s.name} (${s.id}): ${s.summary}`);for(let s of o.instruments??[])a(` ${s.title} (${s.id}): ${s.summary}`);a("Verbs:");for(let s of o.verbs??[])a(` ${s.alias} -> ${s.operation}: ${s.summary}`);a("Parties:");for(let s of o.parties??[])a(` ${s.instrumentId}.${s.role} -> ${s.accountField}`);a("Money flows:");for(let s of o.moneyFlows??[]){let i=s.sourceAccount??"action input",c=s.destinationAccount??"action input",d=s.amountPath??"action input";a(` ${s.action} [${s.kind}]: ${i} -> ${c}; amount ${d}`)}a("Fee forms:");for(let s of o.feeForms??[]){let i=s.bps?`${s.bps} bps`:s.amountSar?`SAR ${s.amountSar}`:s.includedQuantity?`${s.includedQuantity} included`:s.kind;a(` ${s.id}: ${i} per ${s.unit}. ${s.summary}`)}o.priceEstimate&&(a("Price estimate:"),a(` monthlySar: SAR ${Number(o.priceEstimate.monthlySar).toLocaleString("en-US")}`),a(` setupSar: SAR ${Number(o.priceEstimate.setupSar).toLocaleString("en-US")}`),a(` complexityScore: ${o.priceEstimate.complexityScore}`)),a("Dials:");for(let s of o.dials??[])a(` ${s.instrumentId}.${s.key} (${s.kind}): ${s.summary}`);a("Journeys:");for(let s of o.journeys??[])a(` ${s.title} (${s.id}): ${s.summary}`),a(` ${s.steps.join(" -> ")}`);o.hsxStructured&&(a("HSX:"),a(` Source:
107
- ${$e(o.hsxStructured.source," ")}`),o.hsxStructured.document&&a(` Structured document:
108
- ${$e(JSON.stringify(o.hsxStructured.document,null,2)," ")}`)),a("Terms:");for(let[s,i]of Object.entries(o.terminology))a(` ${s}: ${i.definition}`),a(` ${i.href}`);a("Next:"),a(` hyperscale product create --blueprint ${o.id} --name <name>`)}function xt(e,t){let n=Et(e?.hsx);return{...e,...n?{hsxStructured:n}:{},terminology:{firedBy:{definition:"Who invokes an action: tenant through the Product surface, operator through a console session, or machine when a due condition arrives.",href:`${t}/glossary#action-caller`},publicIntents:{definition:"The retired name for publicActions. publicActions contains the canonical action IDs frozen into a composed Product.",href:`${t}/glossary#public-actions`},trustFile:{definition:"The evidence attached to a business record for later review, such as inspection, authentication, delivery, or proof-of-work records.",href:`${t}/glossary#trust-file`}}}}function Et(e){if(typeof e!="string"||e.length===0)return;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return{document:n,language:"hsx-json",source:e,verdict:"valid"}}catch{}let t=compile(e);return{diagnostics:t.diagnostics,...t.artifacts?{document:t.artifacts.document,frame:t.artifacts.frame}:{},language:"hsx-text",source:e,verdict:t.verdict}}function $e(e,t){return e.split(`
90
+ `,Ie={start:{usage:"start [--blueprint <slug>] [--name <name>] [--json]",summary:"Choose a catalog company, create its Product, and run its first published runnable journey step.",options:["--blueprint <slug> Skip the prompt and choose this catalog Blueprint.","--name <name> Product name. Defaults to the selected Blueprint name.","--json Print one machine document, including the one-time API key under shown_once."],notes:["The command requires an active founder login.","Without --blueprint, start requires an interactive terminal and asks which company to build.","Scripts and agents must pass --blueprint <slug>.","Machine output returns the Product API key only under shown_once.","A Blueprint without a published runnable journey stops after composition and names the next command."],example:"hyperscale start --blueprint vehicle-escrow-marketplace --json"},"auth login":{usage:"auth login [--no-browser] [--token <pat>]",summary:"Sign in through the portal callback or save a founder PAT.",options:["--no-browser Skip the portal callback. Print where to mint a PAT when no token is set.","--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN.","--json Print the saved session summary as one JSON document."],notes:["Without a PAT, the CLI opens portal sign-in and accepts one localhost callback.","Headless environments should pass --no-browser and set HYPERSCALE_TOKEN or --token to a portal-minted founder PAT.","Set HYPERSCALE_CREDENTIAL_STORE=file to use the 0600 profile file instead of macOS Keychain."],example:"hyperscale auth login --no-browser"},"auth status":{usage:"auth status [--json]",summary:"Verify and show the active founder PAT and selected Product.",options:["--json Print machine-readable JSON."],example:"hyperscale auth status --json"},"auth logout":{usage:"auth logout [--revoke] [--json]",summary:"Forget the local founder PAT. Optionally revoke it first.",options:["--revoke Revoke the PAT before deleting local state.","--json Print machine-readable JSON."],example:"hyperscale auth logout --revoke"},"blueprint list":{usage:"blueprint list [--json]",summary:"List public Blueprints without authentication.",options:["--json Print the complete collection as JSON."],example:"hyperscale blueprint list"},"blueprint show":{usage:"blueprint show <id> [--json]",summary:"Show one public Blueprint.",options:["--json Print the complete Blueprint as JSON."],example:"hyperscale blueprint show luxury-goods-consignment-escrow"},"product create":{usage:"product create --blueprint <id> --name <name> [--json]",summary:"Create and select a Product. The command refuses a duplicate name.",options:["--blueprint <id> Required Blueprint id.","--name <name> Required Product name.","--json Print the creation summary as JSON."],example:'hyperscale product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"'},"product list":{usage:"product list [--json]",summary:"List Products in the signed-in company.",options:["--json Print the complete collection as JSON."],example:"hyperscale product list"},"product show":{usage:"product show [id] [--json]",summary:"Show a Product summary, or the complete Product document as JSON.",options:["--json Print the complete Product document."],example:"hyperscale product show prd_sandbox_..."},"product select":{usage:"product select <id> [--json]",summary:"Verify a Product and save it as the default for later commands.",options:["--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN or the stored login.","--base-url <url> API origin. Defaults to the active founder profile.","--environment <name> sandbox or live. Defaults to the active founder profile.","--json Print the selected Product id as JSON."],notes:["The CLI stores the selection in the active founder profile.","Product show, compose plan/apply, and key commands use it when --product is absent.","Product create and start select the Product they create."],example:"hyperscale product select prd_sandbox_..."},"product actions":{usage:"product actions [operation-id] [--product <id>] [--json]",summary:"List frozen public actions or show one action's full schemas.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print machine-readable JSON."],notes:["Setup operation details include the public input schema used by hyperscale call.","When that schema has no required fields, omit --input or pass {}."],example:"hyperscale product actions escrow_order.placeBuyerHold --json"},"product run":{usage:"product run <operation-id> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--json]",summary:"Run one frozen public action with a Product API key.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header. The default is a generated UUID.","--json Print the key, receipt ids, and output as JSON."],notes:["Reuse an Idempotency-Key only with the same operation and input.",'If a bounded validation value appears as "[Truncated]", run "hyperscale product actions <operation-id>" for the full input schema.'],example:`hyperscale product run escrow_order.placeBuyerHold --input '{"escrowOrderId":"eord_sandbox_..."}' --idempotency-key hold-001`},"compose check":{usage:"compose check <file.hsx> [--catalog-revision <id>] [--json]",summary:"Ask the server to compile and check an HSX program.",options:["--catalog-revision <id> Compile against this immutable tenant catalog revision.","--json Print diagnostics and the verdict as JSON."],example:"hyperscale compose check product.hsx"},"compose plan":{usage:"compose plan <file.hsx> [--product <id>] [--catalog-revision <id>] [--json]",summary:"Diff an HSX program against a Product.",options:["--product <id> Product to compare. Defaults to the selected Product.","--catalog-revision <id> Compile against this immutable tenant catalog revision.","--json Print the plan as JSON."],example:"hyperscale compose plan product.hsx --json"},"compose apply":{usage:"compose apply <file.hsx> (--confirm | --yes) [--product <id>] [--catalog-revision <id>] [--json]",summary:"Recompose a Product from checked HSX.",options:["--confirm Confirm the mutation for a person.","--yes Confirm the mutation without a prompt for an agent.","--product <id> Product to recompose. Defaults to the selected Product.","--catalog-revision <id> Compile and persist against this immutable tenant catalog revision.","--json Print the result as JSON."],example:"hyperscale compose apply product.hsx --yes"},"key create":{usage:"key create [--name <name>] [--product <id>] [--json]",summary:"Create a sandbox Product API key.",options:["--name <name> Key name. Defaults to Founder CLI.","--product <id> Product for the key. Defaults to the selected Product.","--json Print the one-time secret and key metadata as JSON."],example:'hyperscale key create --name "Founder laptop"'},"key list":{usage:"key list [--product <id>] [--json]",summary:"List keys for one Product.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--json Print the collection as JSON."],example:"hyperscale key list --json"},"key revoke":{usage:"key revoke <id> [--product <id>] [--json]",summary:"Revoke one Product API key.",options:["--product <id> Product that owns the key. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale key revoke key_sandbox_..."},"activity list":{usage:"activity list [--json]",summary:"List company activity with timestamps and resource targets.",options:["--json Print the complete collection as JSON."],example:"hyperscale activity list"},whoami:{usage:"whoami [--json]",summary:"Show the user and company the founder PAT resolves to.",options:["--json Print machine-readable JSON."],example:"hyperscale whoami --json"},"ops list":{usage:"ops list [filter] [--product <id>] [--json]",summary:"List callable operations from the Product machine document.",options:["--product <id> Product to inspect. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print matching operations as JSON."],example:"hyperscale ops list account"},call:{usage:"call <operation> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--product <id>]",summary:"Call one operation from the Product machine document.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header for a mutation. The default is a generated UUID."],notes:["Reuse an Idempotency-Key only with the same operation and input."],example:`hyperscale call account.create --input '{"currency":"SAR"}'`}};function pt(e){let n=Object.keys(Ie).sort((r,a)=>a.split(" ").length-r.split(" ").length).find(r=>r.split(" ").every((i,c)=>e[c]===i));if(!n)throw new u(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`);let o=Ie[n];return[`Usage: hyperscale ${o.usage}`,"",o.summary,"","Options:",...o.options.map(r=>` ${r}`),...o.notes?["","Notes:",...o.notes.map(r=>` ${r}`)]:[],"","Example:",` ${o.example}`,""].join(`
91
+ `)}var u=class extends Error{constructor(t,n={}){super(t),typeof n.code=="string"&&(this.code=n.code),n.details!==void 0&&(this.details=n.details),Number.isInteger(n.exitCode)&&(this.exitCode=n.exitCode),typeof n.fix=="string"&&(this.fix=n.fix)}},v=class extends u{constructor(t,{requestId:n,status:o,code:r,details:a,operationId:i,receiptId:c,traceId:d,structuredError:l}={}){super(t,{code:r,details:a}),this.requestId=n,this.status=o,this.operationId=i??null,this.receiptId=c??null,this.traceId=d??null,this.structuredError=l}};function ee(){return new u(st,{fix:it})}function Te(e){let t=e??"<id>";return new u(`This command needs a Product API key. Create one with "hyperscale key create --name 'Founder CLI' --product ${t}", then set HYPERSCALE_API_KEY or pass --api-key.`)}var J=class extends u{constructor(t,n){super(t),this.code="check_failed",this.details=n,this.exitCode=2}},Ee=new Set(["--api-key","--base-url","--blueprint","--catalog-revision","--environment","--idempotency-key","--input","--input-file","--name","--product","--token"]);function mt(e){let t=[],n={};for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--")){t.push(r);continue}if(Ee.has(r)){let a=e[o+1];if(a===void 0)throw new u(`${r} needs a value`);n[r]=a,o+=1;continue}if(r==="--help"||r==="--version"||r==="--json"||r==="--confirm"||r==="--yes"||r==="--no-browser"||r==="--passkey"||r==="--revoke"){n[r]=!0;continue}throw new u(`Unknown option: ${r}`)}return{flags:n,positional:t}}function ke(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Te();let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??le;if(o!=="sandbox"&&o!=="live")throw new u(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??de).replace(/\/+$/,"");return{apiKey:n,baseUrl:r,environment:o}}function j(e,t,n={}){let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??le;if(o!=="sandbox"&&o!=="live")throw new u(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??de).replace(/\/+$/,""),a;try{a=new URL(r)}catch{a=null}let i=a?.origin??null;if(!i||i!==r)throw new u(`Invalid API origin: ${r}. Use an origin such as https://hyperscale0.ai.`);let c=["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname);if(a.protocol!=="https:"&&!(a.protocol==="http:"&&c))throw new u(`Refusing cleartext API origin ${r}. Use HTTPS unless the API runs on loopback.`);return{baseUrl:r,environment:o}}function ve(e){return e.HYPERSCALE_CONFIG_DIR??z(nt(),".config","hyperscale")}function Oe(e){return z(ve(e),at)}function S(e,t){return z(ve(t),`session-${U(e)}.json`)}function V(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new u(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function me(e,t){let n=S(e,t),o=`${ot(n)}.`,r;try{r=await Qe(oe(n),{withFileTypes:!0})}catch(a){if(a&&a.code==="ENOENT")return;throw a}for(let a of r){if(!a.isFile()||!a.name.startsWith(o))continue;let i=a.name.slice(o.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(i)&&await L(z(oe(n),a.name))}}async function ft(e){try{return JSON.parse(await M(e,"utf8"))}catch(t){if(t&&t.code==="ENOENT")return null;throw t instanceof SyntaxError?new u(`${e} is not valid JSON`):t}}async function R(e,t){let n=ht(e);await Xe(n,{mode:448,recursive:!0}),await Z(n,448);let o=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await tt(o,t,{flag:"wx",mode:384}),await Z(o,384);try{await Ze(o,e),await Z(e,384)}catch(r){throw await L(o),r}}function ht(e){return oe(e)}async function L(e){try{await et(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function yt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new u(`${t} does not contain a CLI profile`);let{baseUrl:n,email:o,environment:r,selectedProduct:a}=e;if(typeof n!="string"||typeof o!="string"||r!=="sandbox"&&r!=="live"||!(a===null||typeof a=="string"))throw new u(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:o,environment:r,selectedProduct:a}}async function W(e){let t=Oe(e),n=await ft(t);return n===null?null:yt(n,t)}async function G(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await R(Oe(e),`${JSON.stringify(n,null,2)}
92
+ `)}function U(e){return Ve("sha256").update(`${e.baseUrl}\0${e.environment}\0${e.email}`).digest("hex")}async function X(e,t){return re===null?{error:null,status:null,stdout:"",unavailable:!0}:await new Promise(n=>{let o={...process.env};delete o.HYPERSCALE_API_KEY,delete o.HYPERSCALE_TOKEN;let r=xe(re,e,{env:o,stdio:["pipe","pipe","pipe"]}),a=[],i=!1,c=l=>{i||(i=!0,clearTimeout(d),n(l))},d=setTimeout(()=>{r.kill("SIGKILL"),c({error:null,status:null,stdout:"",unavailable:!0})},ct);r.stdout.on("data",l=>a.push(l)),r.stderr.on("data",()=>{}),r.stdin.on("error",()=>{}),r.once("error",l=>c({error:l,status:null,stdout:"",unavailable:!0})),r.once("close",l=>c({error:null,status:l,stdout:Buffer.concat(a).toString("utf8"),unavailable:!1})),t===void 0?r.stdin.end():r.stdin.end(`${t}
93
+ `)})}async function fe(){return(await X(["show-keychain-info"])).status===0}function Ce(e){try{let t=typeof e=="string"?JSON.parse(e):e;if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.token=="string"&&typeof t.tenantId=="string"&&(t.personalAccessTokenId===void 0||typeof t.personalAccessTokenId=="string")&&(t.tokenName===void 0||typeof t.tokenName=="string"))return{token:t.token,tenantId:t.tenantId,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.tokenName?{tokenName:t.tokenName}:{}}}catch{}return null}async function wt(e,t,n){await me(e,n);let o=U(e);if(V(n)==="auto"&&await fe()){let r=JSON.stringify(t),a=["add-generic-password","-a",o,"-s",pe,"-U","-X",Buffer.from(r,"utf8").toString("hex")].join(" ");if((await X(["-i"],a)).status===0)return await L(S(e,n)),"keychain"}return await R(S(e,n),`${JSON.stringify({account:o,activeStore:"file",credential:t})}
94
+ `),"file"}async function gt(e,t){let n=U(e);try{let o=JSON.parse(await M(S(e,t),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||o.account!==n)return{state:"invalid"};if(o.revoked===!0)return{state:"revoked"};let r=Ce(o.credential);return r?{activeStore:o.activeStore==="file"?"file":null,credential:r,state:"valid"}:{state:"invalid"}}catch(o){return o&&o.code==="ENOENT"?{state:"missing"}:{state:"invalid"}}}async function Re(e,t){await me(e,t);let n=V(t),o=await gt(e,t);if(o.state==="revoked")return null;if(o.state==="valid"&&(o.activeStore==="file"||n==="file"))return o.credential;if(n==="file")return null;let r=null;if(await fe()){let a=await X(["find-generic-password","-a",U(e),"-s",pe,"-w"]);a.status===0&&(r=Ce(a.stdout.trim()))}return r||(o.state==="valid"?o.credential:null)}async function Ne(e,t){await me(e,t);let n=U(e);if(V(t)==="file")return await R(S(e,t),`${JSON.stringify({account:n,revoked:!0})}
95
+ `),{keychainDeleted:!0};if(re===null)return await L(S(e,t)),{keychainDeleted:!0};if(!await fe())return await R(S(e,t),`${JSON.stringify({account:n,revoked:!0})}
96
+ `),{keychainDeleted:!1};let o=await X(["delete-generic-password","-a",n,"-s",pe]);return o.status!==0&&o.status!==44?(await R(S(e,t),`${JSON.stringify({account:n,revoked:!0})}
97
+ `),{keychainDeleted:!1}):(await L(S(e,t)),{keychainDeleted:!0})}function _e(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function $(e,t,n=!1){let o=await W(t),r=_e(e,t);if(r!==void 0){if(!r)throw ee();let c=j(e,t,o??{}),d=await T(c,r),l=o?.baseUrl===c.baseUrl&&o.environment===c.environment&&o.email===d.email;return{...c,email:d.email,identity:d,personalAccessTokenId:d.personalAccessTokenId,selectedProduct:l?o.selectedProduct:null,tenantId:d.tenantId,token:r,tokenName:d.name}}if(!o){if(n)return null;throw ee()}let a=j(e,t,o);if(a.baseUrl!==o.baseUrl||a.environment!==o.environment)throw new u(`The active founder login belongs to ${o.baseUrl} (${o.environment}). Log in again to change it.`);let i=await Re(o,t);if(!i){if(n)return null;throw ee()}return{...o,...i}}function B(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
98
+ \r`.includes(t)?t:"")}function Y(e){try{return new URL(e).origin}catch{return null}}function y(e,t){let n=e;for(let o of t)typeof o=="string"&&o.length>0&&(n=n.replaceAll(o,"[redacted]"));return n}function je(e,t=[]){if(!e?.ok||!e?.headers)return;let n=e.headers.get("x-request-id"),o=e.headers.get("hyperscale-operation-id"),r=e.headers.get("hyperscale-receipt-id"),a=n?y(n,t):null,i=o?y(o,t):null,c=r?y(r,t):null;a&&process.stderr.write(`Request id: ${a}
99
+ `),i&&process.stderr.write(`Operation: ${i}
100
+ `),c&&process.stderr.write(`Receipt: ${c}
101
+ `)}async function Q(e,t,n={},o){let r=`${e.baseUrl}${t}`,a=Y(e.baseUrl);if(Y(r)!==a)throw new u(`The requested path ${t} leaves the ${a} origin; refusing the request.`);try{let i=await fetch(r,{...n,headers:{accept:"application/json",...o?{authorization:`Bearer ${o}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(se),redirect:"manual"});if(i.status>=300&&i.status<400)throw new u(`${r} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`);return je(i,[o].filter(Boolean)),{response:i,text:B(await i.text())}}catch(i){throw i instanceof u?i:new u(`Could not reach ${r}: ${i.message}`)}}async function b(e,t,n={},o,r=[]){let{response:a,text:i}=await Q(e,t,n,o);if(!a.ok)throw H(a,i,r);try{return JSON.parse(i)}catch{throw new u(`HTTP ${a.status} returned invalid JSON`)}}function A(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function It(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function D(e,t,n={},o){let r=`${e.baseUrl}${t}`,a=Y(e.baseUrl);if(Y(r)!==a)throw new u(`The product document puts ${t} on another origin than the ${a} you configured; refusing to send the key there.`);try{let i=await fetch(r,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(se),redirect:"manual"});if(i.status>=300&&i.status<400)throw new u(`${r} redirected, so the key was not sent on. Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://.`);return je(i,[e.apiKey].filter(Boolean)),{response:i,text:B(await i.text())}}catch(i){throw i instanceof u?i:o&&(i?.name==="TimeoutError"||i?.name==="AbortError")?new u(`product run ${o} timed out after ${se/1e3} seconds.`):new u(`Could not reach ${r}: ${i.message}`)}}async function Le(e){let{response:t,text:n}=await D(e,"/v1/product.json");if(!t.ok)throw H(t,n,[e.apiKey]);let o=kt(n);if(!o)throw new Error("The product document is not in the expected format; upgrade the CLI.");let r=o.operations.map(a=>{if(typeof a.summary!="string"||typeof a.description!="string")throw new u(`The product document carries no prose for ${a.operationId}. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);return{description:a.description,idempotency:a.idempotency,method:a.method,name:a.name,operationId:a.operationId,path:a.path,summary:a.summary}});return{compositionId:o.composition.id,operations:r,packageName:o.sdk?o.sdk.packageName.trim():null,title:o.title.trim()}}function kt(e){let t;try{t=JSON.parse(e)}catch{return null}let n=ie(t),o=r=>typeof r=="string";if(!C(n)||n.schemaVersion!==1||!o(n.title)||!C(n.composition)||!o(n.composition.id)||!Array.isArray(n.operations))return null;for(let r of n.operations)if(!C(r)||!o(r.method)||!o(r.path)||!o(r.name)||!o(r.operationId)||!o(r.idempotency))return null;return n.sdk!==void 0&&(!C(n.sdk)||!o(n.sdk.packageName))?null:n}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ie(e){return typeof e=="string"?B(e):Array.isArray(e)?e.map(ie):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[B(t),ie(n)])):e}function Ue(e){let t=e.get("x-trace-id");if(t&&t.trim()!=="")return t.trim();let n=e.get("traceparent");if(n){let o=/^00-([0-9a-fA-F]{32})-[0-9a-fA-F]{16}-[0-9a-fA-F]{2}$/.exec(n.trim());if(o)return o[1]}return null}function $t(e){if(!e||e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function Pt(e,t=[],n){let o;try{o=JSON.parse(e)}catch{o=null}let r=o&&typeof o=="object"&&o.error&&typeof o.error=="object"?o.error:null,a=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:e.trim(),c=y(i,t),d=a&&typeof r?.message=="string"?`${a}: ${c}`:c,l=r?.details!==void 0?F(r.details,t):void 0,p=o&&typeof o=="object"&&typeof o.requestId=="string"?o.requestId:void 0,m=n?`HTTP ${n}`:"HTTP error";return{code:a,details:l,humanMessage:d,redactedMessage:c,requestId:p,structuredError:{code:a??"http_error",message:c||m,...l!==void 0?{details:l}:{}}}}function H(e,t,n=[]){let o=Pt(t,n,e.status),r=e.headers.get("x-request-id")??o.requestId??null,a=e.headers.get("hyperscale-operation-id")??null,i=e.headers.get("hyperscale-receipt-id")??null,c=r?y(r,n):null,d=a?y(a,n):null,l=i?y(i,n):null,p=Ue(e.headers),m=o.humanMessage;return new v(`HTTP ${e.status}${m?` \xB7 ${m}`:""}${c?`
102
+ Request id: ${c}`:""}`,{code:o.code,details:o.details,operationId:d,receiptId:l,requestId:c,status:e.status,structuredError:o.structuredError,traceId:p})}function he(e,t){return{authenticated:!0,baseUrl:e.baseUrl,email:t.email,environment:e.environment,expiresAt:t.expiresAt,personalAccessTokenId:t.personalAccessTokenId,role:t.role,scopes:t.scopes,selectedProduct:e.selectedProduct,teamId:t.teamId,tenantId:t.tenantId,tokenName:t.name,userId:t.userId}}function bt(e){if(!e||typeof e!="object"||typeof e.userId!="string"||typeof e.email!="string"||typeof e.tenantId!="string"||typeof e.teamId!="string"||typeof e.role!="string"||typeof e.personalAccessTokenId!="string"||typeof e.name!="string"||!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string")||typeof e.expiresAt!="string"||e.status!=="active")throw new u("personal_access_token.current returned invalid data");return e}async function T(e,t){try{return bt(await b(e,rt,{},t,[t]))}catch(n){throw!(n instanceof v)||n.status!==401?n:new u(`That founder PAT was not accepted (HTTP 401). ${_}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:_})}}function St(e,t){return e.HYPERSCALE_CLI_BROWSER?{command:e.HYPERSCALE_CLI_BROWSER,args:[t]}:e.HYPERSCALE_NO_BROWSER==="1"||e.CI==="1"||e.CI==="true"||process.platform==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?null:process.platform==="darwin"?{command:"/usr/bin/open",args:[t]}:process.platform==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:{command:"xdg-open",args:[t]}}async function At(e,t){let n=St(e,t);return n?new Promise(o=>{let r=xe(n.command,n.args,{detached:!0,stdio:"ignore"});r.once("error",()=>o(!1)),r.once("spawn",()=>{r.unref(),o(!0)})}):!1}function te(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function xt(e,t){let n=globalThis.crypto.randomUUID(),o=!1,r,a=new Promise((g,h)=>{r={reject:h,resolve:g}}),i=We((g,h)=>{let I=new URL(g.url??"/","http://127.0.0.1");if(g.method!=="GET"||I.pathname!=="/callback"){h.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),h.end(`Not found.
103
+ `);return}if(o){h.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login callback was already received.
104
+ `);return}if(I.searchParams.get("state")!==n){h.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login state did not match. Return to the terminal.
105
+ `);return}if(I.searchParams.get("error")!==null){o=!0,h.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login declined. Return to the terminal.
106
+ `),r.reject(new u("Portal login was declined. Run hyperscale auth login to start again.",{code:"auth_callback_denied"}));return}let P=I.searchParams.get("grant"),x=I.searchParams.get("tenantId");if(!P||!x){h.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login callback is missing its grant or tenant.
107
+ `);return}o=!0,h.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login received. Return to the terminal.
108
+ `),r.resolve({grant:P,tenantId:x})});await new Promise((g,h)=>{let I=P=>h(P);i.once("error",I),i.listen(0,"127.0.0.1",()=>{i.off("error",I),g()})}),i.once("error",g=>r.reject(g));let c=i.address();if(!c||typeof c=="string")throw await te(i),new u("Could not bind the localhost login callback");let d=`http://127.0.0.1:${c.port}/callback`,l=new URL("/auth/cli",e.baseUrl);l.searchParams.set("callback",d),l.searchParams.set("state",n);let p=new URL("/signin",e.baseUrl);p.searchParams.set("returnTo",`${l.pathname}${l.search}`);let m=p.toString();if(!await At(t,m))return await te(i),null;process.stderr.write(`Opening portal sign-in: ${m}
109
+ `);let k=setTimeout(()=>{r.reject(new u("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},ut);try{return await a}finally{clearTimeout(k),await te(i)}}function $e(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:ae,requestAccessUrl:N};if(e["--json"]){w(t);return}s("No browser detected. Mint a founder PAT in the portal, then run:");for(let n of t.next)s(` ${n}`);s(`PAT desk: ${ae}`),s(`No access yet: ${N}`)}async function Pe(e,t,n,o,r){let a=await W(r),i={email:t.email,...e,selectedProduct:a&&a.email===t.email&&a.baseUrl===e.baseUrl&&a.environment===e.environment?a.selectedProduct:null},c=await wt(i,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},r);try{await G(r,i)}catch(l){throw await Ne(i,r),l}if(c==="file"){let l=V(r)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${l} The founder PAT is in ${S(i,r)} with mode 0600.
110
+ `)}let d=he(i,t);o["--json"]?w(d):s(`Logged in as ${t.email} with PAT ${t.name}.`)}async function Tt(e,t){let n=j(e,t),o=_e(e,t);if(o){if(!o.startsWith("hyperscale_pat_"))throw new u("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let d=await T(n,o);await Pe(n,d,o,e,t);return}if(e["--no-browser"]){$e(e);return}let r=await xt(n,t);if(!r){$e(e);return}let a=await b(n,"/v1/personal-access-token-login-grants/exchange",A({tenantId:r.tenantId,grant:r.grant}),void 0,[r.grant]),i=a?.secret;if(typeof i!="string"||!i.startsWith("hyperscale_pat_")||a?.tenantId!==r.tenantId)throw new u("CLI login grant exchange returned an invalid PAT");let c=await T(n,i);await Pe(n,c,i,e,t)}async function Et(e,t){let n=await $(e,t),o=n.identity??await T(n,n.token),r=he(n,o);if(e["--json"]){w(r);return}s(`User: ${o.email}`),s(`Tenant: ${o.tenantId}`),s(`Role: ${o.role}`),s(`Token: ${o.name}`),s(`Scopes: ${o.scopes.join(", ")}`),s(`Expires: ${o.expiresAt}`),s(`API: ${n.baseUrl}`),s(`Environment: ${n.environment}`),s(`Product: ${n.selectedProduct??"not selected"}`)}async function vt(e,t){let n=await W(t);if(!n){e["--json"]?w({status:"signed_out"}):s("Already logged out.");return}let o=await Re(n,t);if(e["--revoke"]&&!o)throw new u("The local founder PAT is missing, so the CLI cannot revoke it.");let r=o?.personalAccessTokenId,a=o?.tokenName;if(e["--revoke"]&&o){if(!r||!a){let d=await T(n,o.token);r=d.personalAccessTokenId,a=d.name}await b(n,`/v1/personal-access-tokens/${encodeURIComponent(r)}/revoke`,A({tenantId:o.tenantId,personalAccessTokenId:r}),o.token,[o.token])}let i=await Ne(n,t),c=e["--revoke"]===!0;Ot(e,{cleanup:i,personalAccessTokenId:r,revoked:c,status:"signed_out",tokenName:a})}function Ot(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])w({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let o=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?s(`Revoked founder PAT ${o} and forgot local state.`):(s(`Forgot local founder PAT ${o}.`),s("The PAT stays valid until expiry; revoke at /desk/security/tokens."))}t.cleanup.keychainDeleted||process.stderr.write(`Keychain cleanup failed. A 0600 profile tombstone blocks the stale founder PAT.
111
+ `)}function E(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new u(`${t} returned an invalid collection`);return e.items}async function O(e,t,n,o,r,a=[]){let i=[],c=new Set,d,l;for(;;){let k=new URLSearchParams(n);d&&k.set("cursor",d);let g=k.size>0?`?${k}`:"",h=await b(e,`${t}${g}`,{},r,a);l===void 0&&(l=h),i.push(...E(h,o));let I=h.nextCursor;if(typeof I!="string"||I.length===0)break;if(c.has(I))throw new u(`${o} repeated cursor ${I}`);c.add(I),d=I}let{items:p,nextCursor:m,...f}=l;return{...f,items:i}}async function Ct(e,t){let n=await O(e,"/v1/blueprints",{},"blueprint.list"),o=E(n,"blueprint.list");if(t["--json"]){w(n);return}s("ID Name Summary");for(let r of o)s(`${r.id} ${r.name}${r.summary?` ${r.summary}`:""}`);s("Next:"),s(" hyperscale blueprint show <id>"),s(" hyperscale product create --blueprint <id> --name <name>")}async function Rt(e,t,n){if(!n)throw new u("blueprint show needs a Blueprint id");let o=await b(e,`/v1/blueprints/${encodeURIComponent(n)}`),r=Nt(o,e.baseUrl);if(t["--json"]){w(r);return}s(`${r.name} (${r.id})`),s(r.summary),s(r.description),s("Nouns:");for(let a of r.customInstruments??[])s(` ${a.name} (${a.id}): ${a.summary}`);for(let a of r.instruments??[])s(` ${a.title} (${a.id}): ${a.summary}`);s("Verbs:");for(let a of r.verbs??[])s(` ${a.alias} -> ${a.operation}: ${a.summary}`);s("Parties:");for(let a of r.parties??[])s(` ${a.instrumentId}.${a.role} -> ${a.accountField}`);s("Money flows:");for(let a of r.moneyFlows??[]){let i=a.sourceAccount??"action input",c=a.destinationAccount??"action input",d=a.amountPath??"action input";s(` ${a.action} [${a.kind}]: ${i} -> ${c}; amount ${d}`)}s("Fee forms:");for(let a of r.feeForms??[]){let i=a.bps?`${a.bps} bps`:a.amountSar?`SAR ${a.amountSar}`:a.includedQuantity?`${a.includedQuantity} included`:a.kind;s(` ${a.id}: ${i} per ${a.unit}. ${a.summary}`)}r.priceEstimate&&(s("Price estimate:"),s(` monthlySar: SAR ${Number(r.priceEstimate.monthlySar).toLocaleString("en-US")}`),s(` setupSar: SAR ${Number(r.priceEstimate.setupSar).toLocaleString("en-US")}`),s(` complexityScore: ${r.priceEstimate.complexityScore}`)),s("Dials:");for(let a of r.dials??[])s(` ${a.instrumentId}.${a.key} (${a.kind}): ${a.summary}`);s("Journeys:");for(let a of r.journeys??[])s(` ${a.title} (${a.id}): ${a.summary}`),s(` ${a.steps.join(" -> ")}`);r.hsxStructured&&(s("HSX:"),s(` Source:
112
+ ${be(r.hsxStructured.source," ")}`),r.hsxStructured.document&&s(` Structured document:
113
+ ${be(JSON.stringify(r.hsxStructured.document,null,2)," ")}`)),s("Terms:");for(let[a,i]of Object.entries(r.terminology))s(` ${a}: ${i.definition}`),s(` ${i.href}`);s("Next:"),s(` hyperscale product create --blueprint ${r.id} --name <name>`)}function Nt(e,t){let n=_t(e?.hsx);return{...e,...n?{hsxStructured:n}:{},terminology:{firedBy:{definition:"Who invokes an action: tenant through the Product surface, operator through a console session, or machine when a due condition arrives.",href:`${t}/glossary#action-caller`},publicIntents:{definition:"The retired name for publicActions. publicActions contains the canonical action IDs frozen into a composed Product.",href:`${t}/glossary#public-actions`},trustFile:{definition:"The evidence attached to a business record for later review, such as inspection, authentication, delivery, or proof-of-work records.",href:`${t}/glossary#trust-file`}}}}function _t(e){if(typeof e!="string"||e.length===0)return;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return{document:n,language:"hsx-json",source:e,verdict:"valid"}}catch{}let t=compile(e);return{diagnostics:t.diagnostics,...t.artifacts?{document:t.artifacts.document,frame:t.artifacts.frame}:{},language:"hsx-text",source:e,verdict:t.verdict}}function be(e,t){return e.split(`
109
114
  `).map(n=>`${t}${n}`).join(`
110
- `)}function vt(e){return{operationId:e.headers.get("hyperscale-operation-id")??"not returned",receiptId:e.headers.get("hyperscale-receipt-id")??"not returned"}}function Nt(e,t,n=[]){if(!e.ok)throw U(e,t,n);try{return JSON.parse(t)}catch{throw new u(`HTTP ${e.status} returned invalid JSON`)}}function Ct(e,t){a(`${e} operation: ${t.operationId}`),a(`${e} receipt: ${t.receiptId}`)}function Ot(e,t){let n=e instanceof u?e:new u("hyperscale start failed after the Product was created",{code:"start_failed_after_compose"});return n.shownOnce=t,n}function _t(e){if(!e["--blueprint"]&&!(process.stdin.isTTY&&process.stderr.isTTY))throw new u("hyperscale start needs an interactive terminal to choose a company. Pass --blueprint <slug> in scripts and non-interactive environments.",{code:"start_blueprint_required",fix:'Run "hyperscale blueprint list", then pass --blueprint <slug>.'})}function Rt(e){return T(e,"blueprint.list").map(t=>{if(typeof t?.id!="string"||t.id.length===0||typeof t?.name!="string"||t.name.length===0)throw new u("blueprint.list returned an invalid start choice");return{id:t.id,name:t.name,summary:typeof t.summary=="string"?t.summary:""}})}async function jt(e,t){let n=await E(t,"/v1/blueprints",{},"blueprint.list"),r=Rt(n);if(r.length===0)throw new u("The Blueprint catalog has no companies to build.");let o=e["--blueprint"];if(o){let m=r.find(({id:h})=>h===o);if(m)return m;throw new u(`Unknown Blueprint: ${o}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
111
- `);for(let[m,h]of r.entries()){let $=h.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${m+1}. ${h.name} (${h.id})${$?`: ${$}`:""}
112
- `)}let s=Fe({input:process.stdin,output:process.stderr,terminal:!0}),i=new AbortController,c=()=>i.abort();process.stdin.once("end",c),process.stdin.readableEnded&&i.abort();let d;try{try{d=(await s.question("Choose a number or Blueprint slug: ",{signal:i.signal})).trim()}catch(m){throw m?.name!=="AbortError"&&m?.code!=="ABORT_ERR"?m:new u("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",c),s.close()}let l=Number(d),p=Number.isInteger(l)?r[l-1]:r.find(({id:m})=>m===d);if(p)return p;throw new u(`No Blueprint matches ${JSON.stringify(d)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}async function Ie(e,t){_t(e);let n={};try{await Lt(e,t,n)}catch(r){throw typeof n.apiKey!="string"?r:Ot(r,n.apiKey)}}async function Lt(e,t,n){let r=await I(e,t),o=await A(r,r.token),s=await jt(e,r),i=e["--name"]??s.name;e["--json"]||a(`Authenticated: ${o.email}`);let c=await Oe(r,"/v1/products/blueprint-compose",b({blueprintId:s.id,name:i,tenantId:r.tenantId}),r.token),d=Nt(c.response,c.text,[r.token]);if(typeof d?.productId!="string"||!rt.test(d.productId)||typeof d?.productBuildId!="string"||d?.blueprintId!==s.id)throw new u("product.blueprint.compose returned an invalid start Product");let l=d?.shown_once;if(typeof l!="string"||l.length===0)throw new u("The composed Product did not return its one-time API key. Choose a new Product name and run hyperscale start again.",{code:"start_api_key_unavailable"});n.apiKey=l;let p=vt(c.response);await W(t,{...r,selectedProduct:d.productId}),e["--json"]||(a(`Product: ${d.productId}`),a(`Blueprint: ${d.blueprintId}`),Ct("Compose",p));let m=[`hyperscale compose plan product.hsx --product ${d.productId}`],h="Composition completed. Run SDK journeys against your Product.",$={blueprintId:d.blueprintId,composeOnly:!0,nextCommands:m,notice:h,productBuildId:d.productBuildId,productId:d.productId,receipts:[{stage:"product.blueprint.compose",...p}],...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},shown_once:l};if(e["--json"]){f($);return}a(h),a(`Shown once Product API key: ${l}`),a("Next:");for(let g of m)a(` ${g}`);a(" Run journeys with the Hyperscale SDK using the Product API key above.")}async function Ut(e,t){let n=e["--blueprint"],r=e["--name"];if(!n)throw new u("product create needs --blueprint <id>");if(!r)throw new u("product create needs --name <name>");let o=await I(e,t),s;try{s=await E(o,"/v1/products",{tenantId:o.tenantId},"product.list",o.token,[o.token])}catch(m){if(!(m instanceof x)||m.status!==403)throw m}let i=r.trim().toLocaleLowerCase("en-US"),c=(s?T(s,"product.list"):[]).find(m=>{let h=m?.displayName??m?.name;return typeof h=="string"&&h.trim().toLocaleLowerCase("en-US")===i});if(c){let m=c.productId??c.id??"<id>";throw new u(`A Product named ${JSON.stringify(r.trim())} already exists as ${m}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${m}" or choose another --name.`})}let d=await k(o,"/v1/products/blueprint-compose",b({blueprintId:n,name:r,tenantId:o.tenantId}),o.token,[o.token]);if(typeof d?.productId!="string"||typeof d?.blueprintId!="string"||typeof d?.productBuildId!="string")throw new u("product.blueprint.compose returned an invalid Product");await W(t,{...o,selectedProduct:d.productId});let l=typeof d?.shown_once=="string"&&d.shown_once.length>0?d.shown_once:void 0,p={blueprintId:d.blueprintId,nextSteps:[`hyperscale product show ${d.productId}`,...l?[]:['hyperscale key create --name "Founder CLI"']],productBuildId:d.productBuildId,productId:d.productId,selectedProduct:d.productId,...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},...l?{shown_once:l}:{}};if(e["--json"]){f(p);return}a(`Product: ${p.productId}`),a(`Blueprint: ${p.blueprintId}`),a(`Build: ${p.productBuildId}`),a(`Selected: ${p.selectedProduct}`),p.shown_once&&a(`Shown once Product API key: ${p.shown_once}`),a("Next:");for(let m of p.nextSteps)a(` ${m}`)}function je(e){return new URLSearchParams({tenantId:e}).toString()}async function Dt(e,t){let n=await I(e,t),r=await E(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),o=T(r,"product.list");if(e["--json"]){f(r);return}if(o.length===0){a('No Products yet. Run "hyperscale blueprint list", then "hyperscale product create --blueprint <id> --name <name>".');return}a("ID Name Status");for(let s of o){let i=s.productId??s.id??"unknown",c=s.displayName??s.name??"unnamed";a(`${i} ${c}${s.status?` ${s.status}`:""}`)}}async function Ht(e,t,n){let r=await I(e,t),o=n??r.selectedProduct;if(!o)throw new u("product show needs an id because no Product is selected. Create a Product first.");let s=await k(r,`/v1/products/${encodeURIComponent(o)}?${je(r.tenantId)}`,{},r.token,[r.token]);if(e["--json"]){f(s);return}Jt(s,o)}function Jt(e,t){let n=e?.displayName??e?.name??"unnamed",r=e?.status??"unknown",o=e?.blueprint,s=o?.id?`${o.name??o.id}${o.name?` (${o.id})`:""}`:"custom composition",i=e?.cost?.currency??"SAR",c=e?.plan?.monthlySar??e?.cost?.platformMonthlySar,d=e?.plan?.setupSar??e?.cost?.platformSetupSar,l=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements:[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(p=>`unavailable:${p}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(p=>p?.code??"pricing"):[]];a(`Name: ${n}`),a(`Product: ${e?.productId??t}`),a(`Status: ${r}`),a(`Blueprint: ${s}`),a(`Monthly: ${c==null?"not returned":`${i} ${c}`}`),a(`Setup: ${d==null?"not returned":`${i} ${d}`}`),a(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),a(`Live blockers: ${l.length>0?l.join(", "):"none"}`);for(let[p,m]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let h=e?.surfaces?.[p];h?.url&&a(`${m}: ${h.url}`)}a("Next:"),a(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function Bt(e,t,n){if(!n)throw new u("product select needs a Product id");let r=await I(e,t),o=await k(r,`/v1/products/${encodeURIComponent(n)}?${je(r.tenantId)}`,{},r.token,[r.token]);if(o?.productId!==n)throw new u("product.retrieve returned the wrong Product");await W(t,{...r,selectedProduct:n});let s={productId:n,selected:!0};e["--json"]?f(s):a(`Selected Product: ${o.displayName??n} (${n})`)}function Kt(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}async function Yt(e){if(!e)throw new u("compose needs a .hsx file");if(!e.endsWith(".hsx"))throw new u(`compose reads a .hsx file, got ${e}`);let t;try{t=await q(e,"utf8")}catch(n){throw new u(`Could not read ${e}: ${n.message}`)}return{file:e,source:t}}function Ft(e){if(!e||typeof e!="object"||typeof e.ok!="boolean"||!Array.isArray(e.issues))throw new u("composer.check returned an invalid result");return{issues:e.issues.map(n=>{if(!n||typeof n!="object"||typeof n.code!="string"||typeof n.message!="string"||typeof n.path!="string")throw new u("composer.check returned an invalid issue");return{code:n.code,message:n.message,path:n.path}}),ok:e.ok}}async function fe(e,t,n,r){let o=await Yt(n),s=await I(e,t),i=r?D(s,e):void 0,c=Ft(await k(s,"/v1/composer/check",b({tenantId:s.tenantId,document:o.source,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}),s.token,[s.token]));if(!c.ok)throw new J(["composer.check refused the program.",...Kt(c.issues)].join(`
113
- `),{file:n,issues:c.issues});return{check:c,context:s,productId:i,program:o,catalogRevisionId:e["--catalog-revision"]}}async function qt(e,t,n){let r=await fe(e,t,n,!1);if(e["--json"]){f({command:"composer.check",file:n,issues:r.check.issues,ok:!0});return}a(`Check passed: ${n}`)}async function Le(e,t){let n=await k(e.context,"/v1/composer/plan",b({document:e.program.source,tenantId:e.context.tenantId,productId:e.productId,...e.catalogRevisionId?{catalogRevisionId:e.catalogRevisionId}:{}}),e.context.token,[e.context.token]);if(!n||typeof n!="object"||typeof n.summary!="string"||!Array.isArray(n.actions)||!n.pricing||typeof n.pricing!="object")throw new u("composer.plan returned an invalid result");let r=n.actions.filter(o=>!o||typeof o!="object"||o.kind!=="configure_product");if(r.length>0)throw new J([n.summary,...r.map(o=>o&&typeof o=="object"?`${o.kind??"unknown"} ${o.target??"unknown"} ${o.detail??"Composer refused this action."}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
114
- `),{actions:r,file:t,productId:e.productId});return n}async function Mt(e,t,n){let r=await fe(e,t,n,!0),o=await Le(r,n);if(e["--json"]){f({command:"composer.plan",file:n,plan:o,productId:r.productId});return}a(o.summary);for(let s of o.actions)a(`${s.kind} ${s.target} ${s.detail}`);a(`Monthly: SAR ${o.pricing.monthlySar}`),a(`Activation: SAR ${o.pricing.activationSar}`)}async function zt(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new u("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let r=await fe(e,t,n,!0);await Le(r,n);let o=await k(r.context,"/v1/products/recompose",b({program:{source:r.program.source},...r.catalogRevisionId?{catalogRevisionId:r.catalogRevisionId}:{},tenantId:r.context.tenantId,productId:r.productId},e["--idempotency-key"]),r.context.token,[r.context.token]);if(!o||typeof o.productBuildId!="string")throw new u("product.recompose returned no new build identity");if(e["--json"]){f({command:"product.recompose",file:n,output:o});return}a(`Product: ${o.productId??r.productId}`),a(`Build: ${o.productBuildId}`),o.buildDigest&&a(`Digest: ${o.buildDigest}`)}function D(e,t){let n=t["--product"]??e.selectedProduct;if(!n)throw new u("No Product selected. Pass --product <id> or create a Product first.");return n}async function Y(e,t,n){let r=await V(t),o=D(r??{},e),s=_(e,t,r??{});if(r&&(s.baseUrl!==r.baseUrl||s.environment!==r.environment))throw new u(`The selected Product belongs to ${r.baseUrl} (${r.environment}). Select a Product at the configured API origin first.`);let i=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!i)throw Se(o);let c={...s,apiKey:i,productId:o};return await Vt(c,o,n),c}async function Vt(e,t,n){let r=`/v1/products/${encodeURIComponent(t)}/operation-set`,{response:o,text:s}=await L(e,r,{},n);if(o.ok)return;let i;try{i=JSON.parse(s)?.error?.message}catch{i=void 0}throw typeof i=="string"&&i.includes("does not match API key Product")?new u(`${i} Or set HYPERSCALE_API_KEY to a key for ${t}, or pass that key with --api-key.`):U(o,s,[e.apiKey])}async function Ue(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:r,text:o}=await L(e,n,{},t);if(!r.ok)throw He(r,o,[e.apiKey]);return Xt(o,r.status)}async function Wt(e,t,n){let r=await Y(e,t),o=await Ue(r);if(n){Gt(o,n,e);return}if(e["--json"]){f(o);return}if(o.status==="legacy"){a("This Product uses a legacy surface. It has no frozen public actions yet."),a(`Build: ${o.productBuildId}`);return}if(o.publicActions.length===0)a("No public actions");else{a("Operation ID Input Kind");for(let s of o.publicActions){let i=s.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";a(`${s.instrument}.${s.name} ${en(s.inputSchema)} ${i}`)}}if(o.setupOperations.length>0){a("Setup operations (run with hyperscale call)");for(let s of o.setupOperations)a(s.operationName)}if(o.readOperationIds.length>0){a("Reads (run with hyperscale call)");for(let s of o.readOperationIds)a(Zt(s))}a(`Digest: ${o.tenantOperationSetDigest}`),a(`Setup digest: ${o.tenantSetupOperationSetDigest}`),a(`Read digest: ${o.tenantReadOperationSetDigest}`),a(`Build: ${o.productBuildId}`),a(`Surface version: ${o.tenantSurfaceVersion}`)}function Gt(e,t,n){if(e.status==="legacy")throw new u(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let r=e.publicActions.find(c=>c&&`${c.instrument}.${c.name}`===t),o=Qt(t),s=e.setupOperations.find(c=>c&&(c.operationId===t||c.operationId===o||c.operationName===t));if(s){let{inputSchema:c,operationId:d,operationName:l}=s,p={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:d,operationName:l,command:`hyperscale call ${l}`,inputSchema:c};if(n["--json"]){f(p);return}a(`Operation ID: ${d}`),a(`Operation name: ${l}`),a(`Run: hyperscale call ${l}`),a(`Input schema: ${JSON.stringify(c,null,2)}`),(!Array.isArray(c.required)||c.required.length===0)&&a("Input: omit --input or pass {}."),a(`Setup digest: ${e.tenantSetupOperationSetDigest}`),a(`Build: ${e.productBuildId}`),a(`Surface version: ${e.tenantSurfaceVersion}`);return}if(!r)throw new u(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let i={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:r};if(n["--json"]){f(i);return}a(`Operation ID: ${r.instrument}.${r.name}`),a(`Instrument: ${r.instrument}`),a(`Input schema: ${JSON.stringify(r.inputSchema,null,2)}`),a(`Output schema: ${JSON.stringify(r.outputSchema,null,2)}`),a(`Actor policy: ${JSON.stringify(r.actorPolicy,null,2)}`),a(`Port policy: ${JSON.stringify(r.portPolicy,null,2)}`),a(`Idempotency policy: ${JSON.stringify(r.idempotencyPolicy,null,2)}`),a(`Receipt policy: ${JSON.stringify(r.receiptPolicy,null,2)}`),a(`Receipt evidence: ${JSON.stringify(r.receiptEvidence,null,2)}`),a(`Digest: ${e.tenantOperationSetDigest}`),a(`Build: ${e.productBuildId}`),a(`Surface version: ${e.tenantSurfaceVersion}`)}function Xt(e,t){let n;try{n=JSON.parse(e)}catch{throw new u(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="legacy"&&n.status!=="frozen"||typeof n.productBuildId!="string")throw new u("The Product operation set is not in the expected format. Upgrade the CLI.");if(n.status==="legacy")return n;if(typeof n.tenantSurfaceVersion!="number"||typeof n.tenantOperationSetDigest!="string"||typeof n.tenantReadOperationSetDigest!="string"||typeof n.tenantSetupOperationSetDigest!="string"||!Array.isArray(n.publicActions)||!Array.isArray(n.readOperationIds)||!Array.isArray(n.setupOperationIds)||!Array.isArray(n.setupOperations))throw new u("The Product operation set is not in the expected format. Upgrade the CLI.");return n}function Qt(e){return e.replaceAll(".","_")}function Zt(e){for(let t of["create","list","retrieve"]){let n=`_${t}`;if(e.endsWith(n))return`${e.slice(0,-n.length)}.${t}`}return e}function en(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(o=>typeof o=="string"):[]),r=Object.entries(t).map(([o,s])=>`${o}${n.has(o)?"":"?"}: ${De(s)}`);return r.length===0?"no input":r.join(", ")}function De(e){return!e||typeof e!="object"?"value":Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(t=>String(t)).join(" | "):e.type==="array"?`${De(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function tn(e,t,n){if(!n)throw new u("product run needs a public action");let r=await Y(e,t,n),o=await Ue(r,n);nn(o,n);let s=await Je(e),i=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:c,text:d}=await L(r,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(s),headers:{"content-type":"application/json","idempotency-key":i},method:"POST"},n);if(!c.ok)throw He(c,d,[r.apiKey],{action:n});let l=c.headers.get("hyperscale-operation-id"),p=c.headers.get("hyperscale-receipt-id");if(e["--json"]){f({idempotencyKey:i,operationId:l,receiptId:p,output:on(d)});return}a(`Operation: ${l??"not returned"}`),a(`Receipt: ${p??"not returned"}`),a(`Idempotency key: ${i}`);let m=Be(d);m&&a(m)}function nn(e,t){if(e.status==="legacy")throw new u(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let n=e.publicActions.find(o=>o&&`${o.instrument}.${o.name}`===t);if(n)return n;let r=e.publicActions.map(o=>`${o.instrument}.${o.name}`).map(o=>({candidate:o,distance:ie(t,o)})).sort((o,s)=>o.distance-s.distance||o.candidate.localeCompare(s.candidate)).slice(0,3).map(({candidate:o})=>o);throw new u(`Unknown frozen public action: ${t}. Closest valid names: ${r.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function on(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function He(e,t,n=[],r={}){let o=S(t.trim(),n),s;try{s=JSON.parse(t)}catch{return new u(`HTTP ${e.status}${o?` \xB7 ${o}`:""}`)}if(!s?.error||typeof s.error.message!="string")return new u(`HTTP ${e.status}`);let i=typeof s.error.code=="string"?s.error.code:"user_error",c=i==="user_error"?"":`${i}: `,d=S(`HTTP ${e.status} \xB7 ${c}${s.error.message}`,n),l=rn(s.error.details,n),p;return i==="idempotency_conflict"?p="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":[s.error.message,...l].some(m=>typeof m=="string"&&m.includes("[Truncated]"))&&r.action&&(p=`Run "hyperscale product actions ${r.action}" to read the full input schema and allowed values.`),new u([d,...l].join(`
115
- `),{code:i,...s.error.details?{details:F(s.error.details,n)}:{},...p?{fix:p}:{}})}function F(e,t){return typeof e=="string"?S(e,t):Array.isArray(e)?e.map(n=>F(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[S(n,t),F(r,t)])):e}function rn(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(r=>{if(!r||typeof r!="object")return[];let s=(Array.isArray(r.path)?r.path.join("."):"input")||"input";return typeof r.message=="string"?[`${s}: ${S(r.message,t)}`]:[]});let n=[];return ae(e,"",n,t),n}function ae(e,t,n,r){if(Array.isArray(e)){if(e.every(o=>o===null||typeof o!="object")){n.push(`${Pe(t)}: ${S(e.join(", "),r)}`);return}e.forEach((o,s)=>ae(o,`${t}[${s}]`,n,r));return}if(e&&typeof e=="object"){for(let[o,s]of Object.entries(e))ae(s,t?`${t}.${o}`:o,n,r);return}t&&n.push(`${Pe(t)}: ${S(String(e),r)}`)}function Pe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function sn(e,t){let n=await I(e,t),r=D(n,e),o=await k(n,"/v1/sandbox-api-keys",b({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:r}),n.token,[n.token]);if(e["--json"]){f(o);return}a(`Key: ${o.apiKeyId??"unknown"}`),a(`Product: ${o.productId??r}`),a(`Status: ${o.status??"unknown"}`),o.secret?(a(`Secret: ${o.secret}`),a("Store it now. Hyperscale will not return it again."),a("Next:"),a(` export HYPERSCALE_API_KEY=${an(o.secret)}`),a(` hyperscale product actions --product ${r}`)):a("The key already existed, so the one-time secret is unavailable.")}function an(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function cn(e,t){let n=await I(e,t),r=D(n,e),o=await E(n,"/v1/api-keys",{tenantId:n.tenantId},"api_key.list",n.token,[n.token]),s=T(o,"api_key.list").filter(c=>c.productId===r),i={...o,items:s};if(e["--json"]){f(i);return}for(let c of s)a(`${c.apiKeyId} ${c.name??"unnamed"} ${c.status??"unknown"}`)}async function un(e,t,n){if(!n)throw new u("key revoke needs an API key id");let r=await I(e,t),o=D(r,e),s=await k(r,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,b({tenantId:r.tenantId,productId:o}),r.token,[r.token]);e["--json"]?f(s):a(`Key ${s.apiKeyId??n}: ${s.status??"revoked"}`)}async function dn(e,t){let n=await I(e,t),r=n.identity??await A(n,n.token),o=me(n,r);if(e["--json"]){f(o);return}a(`User: ${r.email}`),a(`Tenant: ${r.tenantId}`),a(`Role: ${r.role}`),a(`Token: ${r.name}`),a(`Expires: ${r.expiresAt}`)}async function ln(e,t,n){let r=await _e(e),o=n?n.toLowerCase():null,s=o?r.operations.filter(c=>c.name.toLowerCase().includes(o)||c.path.toLowerCase().includes(o)):r.operations;if(t["--json"]){a(JSON.stringify(s,null,2));return}if(s.length===0){a(n?`No operation matches ${n}`:"No operations");return}let i=Math.max(...s.map(c=>c.name.length));for(let c of s)a(`${c.name.padEnd(i)} ${c.method.padEnd(6)}${c.path}`)}async function pn(e,t){let n=await I(e,t),r=await E(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),o=T(r,"activity.list");if(e["--json"]){f(r);return}a("Time Activity Target Status");for(let s of o){let i=s.operation??s.auditEvent??"activity",c=s.resourceKind&&s.resourceId?`${s.resourceKind}:${s.resourceId}`:s.resourceKind??s.resourceId??"-";a(`${s.occurredAt??"unknown"} ${i} ${c} ${s.status??"recorded"}`)}}function mn(e,t){let n={...t},r=[],o=e.path.replace(/\{([^}]+)\}/g,(s,i)=>{let c=n[i];return c==null?(r.push(i),""):(delete n[i],encodeURIComponent(String(c)))});if(r.length>0)throw new u(`${e.name} needs ${r.join(", ")} in --input`);return{path:o,remaining:n}}function fn(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!=null&&t.set(r,typeof o=="string"?o:JSON.stringify(o));let n=t.toString();return n?`?${n}`:""}function ie(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let s=1;s<=t.length;s+=1)o[s]=Math.min(o[s-1]+1,n[s]+1,n[s-1]+(e[r-1]===t[s-1]?0:1));n.splice(0,n.length,...o)}return n[t.length]}function hn(e,t){let n=e.find(s=>s.name===t);if(n)return n;let r=e.filter(s=>s.operationId===t);if(r.length===1)return r[0];if(r.length>1)throw new u(`${t} matches more than one operation. Use one of: ${r.map(s=>s.name).join(", ")}.`);let o=e.map(s=>({candidate:s,distance:Math.min(ie(t,s.name),ie(t,s.operationId))})).sort((s,i)=>s.distance-i.distance||s.candidate.name.localeCompare(i.candidate.name)).slice(0,3).flatMap(({candidate:s})=>[s.name,s.operationId]);throw new u(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${o.join(", ")}.`)}async function yn(e,t,n){if(!n)throw new u("call needs an operation name");let r=await _e(e),o=hn(r.operations,n),s=await Je(t),{path:i,remaining:c}=mn(o,s),d={method:o.method},l=i;o.method==="GET"?l+=fn(c):(d.body=JSON.stringify(c),d.headers={"content-type":"application/json",...o.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:p,text:m}=await L(e,l,d);if(p.ok){if(t["--json"]){let h=ht(m),$=p.headers.get("hyperscale-operation-id")??null,g=p.headers.get("hyperscale-receipt-id")??null,y=p.headers.get("x-request-id")??(h&&typeof h=="object"&&typeof h.requestId=="string"?h.requestId:null),w=Re(p.headers);f({status:p.status,data:h,requestId:y,operationId:$,receiptId:g,traceId:w});return}a(Be(m));return}throw U(p,m,[e.apiKey])}async function Je(e){if(e["--input"]!==void 0&&e["--input-file"]!==void 0)throw new u("Use only one of --input and --input-file");if(e["--input"]!==void 0)return ee(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await q(e["--input-file"],"utf8")}catch(n){throw new u(`Could not read ${e["--input-file"]}: ${n.message}`)}return ee(t,"--input-file")}if(!process.stdin.isTTY){let t=await mt();if(t.trim()!=="")return ee(t,"stdin")}return{}}function ee(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(r){throw new u(`${t} is not valid JSON: ${r.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new u(`${t} must be a JSON object`);return n}function Be(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function a(e){process.stdout.write(`${e}
116
- `)}function f(e){a(JSON.stringify(e,null,2))}function wn(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(!n.startsWith("--"))return n;Ae.has(n)&&(t+=1)}}function gn(e,t){let n=wn(t)==="call",r=t.includes("--json");if(n&&r&&e instanceof x){f({status:e.status,error:e.structuredError??{code:e.code??"http_error",message:e.message},requestId:e.requestId??null,operationId:e.operationId??null,receiptId:e.receiptId??null,traceId:e.traceId??null});let c=typeof e.message=="string"?e.message:e.stack??String(e);process.stderr.write(`${c}
117
- `);return}let o=e instanceof u&&typeof e.shownOnce=="string"?e.shownOnce:void 0;if(!r){let c=e instanceof u?e.message:e.stack??String(e),d=e instanceof u&&typeof e.fix=="string"?`
118
- Fix: ${e.fix}`:"",l=o?`
119
- Shown once Product API key: ${o}`:"";process.stderr.write(`${c}${d}${l}
120
- `);return}let s=e instanceof u,i=s&&typeof e.code=="string"?e.code:s?"user_error":"internal_error";process.stderr.write(`${JSON.stringify({error:{code:i,message:s?e.message:"The command failed unexpectedly.",...s&&e.details?{details:e.details}:{},fix:s?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."},...o?{shown_once:o}:{}})}
121
- `)}async function kn(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function $n(e,t){let{flags:n,positional:r}=it(e);if(n["--version"])return a(await kn()),0;if(n["--help"]&&r.length>0)return process.stdout.write(at(r)),0;if(r.length===0&&!n["--help"]){if(n["--json"])throw new u('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await Ie(n,t),0):(a('Build your first Product with "hyperscale start".'),a('Run "hyperscale --help" for every command.'),0)}if(n["--help"])return process.stdout.write(st),0;let[o,...s]=r;if(o==="start")return await Ie(n,t),0;if(o==="auth"){if(s[0]==="login")await It(n,t);else if(s[0]==="status")await Pt(n,t);else if(s[0]==="logout")await bt(n,t);else throw new u('Auth subcommands are "login", "status", and "logout"');return 0}if(o==="blueprint"){let i=_(n,t);if(s[0]==="list")await At(i,n);else if(s[0]==="show")await Tt(i,n,s[1]);else throw new u('Blueprint subcommands are "list" and "show"');return 0}if(o==="product"){if(s[0]==="create")await Ut(n,t);else if(s[0]==="list")await Dt(n,t);else if(s[0]==="show")await Ht(n,t,s[1]);else if(s[0]==="select")await Bt(n,t,s[1]);else if(s[0]==="actions")await Wt(n,t,s[1]);else if(s[0]==="run")await tn(n,t,s[1]);else throw new u('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(o==="compose"){if(s[0]==="check")await qt(n,t,s[1]);else if(s[0]==="plan")await Mt(n,t,s[1]);else if(s[0]==="apply")await zt(n,t,s[1]);else throw new u('Compose subcommands are "check", "plan", and "apply"');return 0}if(o==="key"){if(s[0]==="create")await sn(n,t);else if(s[0]==="list")await cn(n,t);else if(s[0]==="revoke")await un(n,t,s[1]);else throw new u('Key subcommands are "create", "list", and "revoke"');return 0}if(o==="whoami")return await dn(n,t),0;if(o==="activity"){if(s[0]!=="list")throw new u('The only activity subcommand is "list"');return await pn(n,t),0}if(o==="ops"){if(s[0]!=="list")throw new u('The only ops subcommand is "list"');let i=n["--product"]?await Y(n,t):we(n,t);return await ln(i,n,s[1]),0}if(o==="call"){let i=n["--product"]?await Y(n,t):we(n,t);return await yn(i,n,s[0]),0}throw new u(`Unknown command: ${o}`)}$n(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{gn(e,process.argv.slice(2)),process.exitCode=e instanceof u&&Number.isInteger(e.exitCode)?e.exitCode:1});
115
+ `)}function ye(e,t=[]){let n=e.headers.get("hyperscale-operation-id"),o=e.headers.get("hyperscale-receipt-id"),r=n?y(n,t):void 0,a=o?y(o,t):void 0;return{...r?{operationId:r}:{},...a?{receiptId:a}:{}}}function we(e,t,n=[]){if(!e.ok)throw H(e,t,n);try{return JSON.parse(t)}catch{throw new u(`HTTP ${e.status} returned invalid JSON`)}}function jt(e,t){t.operationId&&s(`${e} operation: ${t.operationId}`),t.receiptId&&s(`${e} receipt: ${t.receiptId}`)}function Lt(e,t){let n=e instanceof u?e:new u("hyperscale start failed after the Product was created",{code:"start_failed_after_compose"});return n.shownOnce=t,n}function Ut(e){if(!e["--blueprint"]&&!(process.stdin.isTTY&&process.stderr.isTTY))throw new u("hyperscale start needs an interactive terminal to choose a company. Pass --blueprint <slug> in scripts and non-interactive environments.",{code:"start_blueprint_required",fix:'Run "hyperscale blueprint list", then pass --blueprint <slug>.'})}function Dt(e){return E(e,"blueprint.list").map(t=>{if(typeof t?.id!="string"||t.id.length===0||typeof t?.name!="string"||t.name.length===0)throw new u("blueprint.list returned an invalid start choice");return{id:t.id,name:t.name,summary:typeof t.summary=="string"?t.summary:""}})}async function Ht(e,t){let n=await O(t,"/v1/blueprints",{},"blueprint.list"),o=Dt(n);if(o.length===0)throw new u("The Blueprint catalog has no companies to build.");let r=e["--blueprint"];if(r){let m=o.find(({id:f})=>f===r);if(m)return m;throw new u(`Unknown Blueprint: ${r}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
116
+ `);for(let[m,f]of o.entries()){let k=f.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${m+1}. ${f.name} (${f.id})${k?`: ${k}`:""}
117
+ `)}let a=Ge({input:process.stdin,output:process.stderr,terminal:!0}),i=new AbortController,c=()=>i.abort();process.stdin.once("end",c),process.stdin.readableEnded&&i.abort();let d;try{try{d=(await a.question("Choose a number or Blueprint slug: ",{signal:i.signal})).trim()}catch(m){throw m?.name!=="AbortError"&&m?.code!=="ABORT_ERR"?m:new u("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",c),a.close()}let l=Number(d),p=Number.isInteger(l)?o[l-1]:o.find(({id:m})=>m===d);if(p)return p;throw new u(`No Blueprint matches ${JSON.stringify(d)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}async function Se(e,t){Ut(e);let n={};try{await Kt(e,t,n)}catch(o){throw typeof n.apiKey!="string"?o:Lt(o,n.apiKey)}}async function Kt(e,t,n){let o=await $(e,t),r=await T(o,o.token),a=await Ht(e,o),i=e["--name"]??a.name;e["--json"]||s(`Authenticated: ${r.email}`);let c=await Q(o,"/v1/products/blueprint-compose",A({blueprintId:a.id,name:i,tenantId:o.tenantId}),o.token),d=we(c.response,c.text,[o.token]);if(typeof d?.productId!="string"||!dt.test(d.productId)||typeof d?.productBuildId!="string"||d?.blueprintId!==a.id)throw new u("product.blueprint.compose returned an invalid start Product");let l=d?.shown_once;if(typeof l!="string"||l.length===0)throw new u("The composed Product did not return its one-time API key. Choose a new Product name and run hyperscale start again.",{code:"start_api_key_unavailable"});n.apiKey=l;let p=ye(c.response);await G(t,{...o,selectedProduct:d.productId}),e["--json"]||(s(`Product: ${d.productId}`),s(`Blueprint: ${d.blueprintId}`),jt("Compose",p));let m=[`hyperscale compose plan product.hsx --product ${d.productId}`],f="Composition completed. Run SDK journeys against your Product.",k={blueprintId:d.blueprintId,composeOnly:!0,nextCommands:m,notice:f,productBuildId:d.productBuildId,productId:d.productId,receipts:[{stage:"product.blueprint.compose",...p}],...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},shown_once:l};if(e["--json"]){w(k);return}s(f),s(`Shown once Product API key: ${l}`),s("Next:");for(let g of m)s(` ${g}`);s(" Run journeys with the Hyperscale SDK using the Product API key above.")}async function Jt(e,t){let n=e["--blueprint"],o=e["--name"];if(!n)throw new u("product create needs --blueprint <id>");if(!o)throw new u("product create needs --name <name>");let r=await $(e,t),a;try{a=await O(r,"/v1/products",{tenantId:r.tenantId},"product.list",r.token,[r.token])}catch(m){if(!(m instanceof v)||m.status!==403)throw m}let i=o.trim().toLocaleLowerCase("en-US"),c=(a?E(a,"product.list"):[]).find(m=>{let f=m?.displayName??m?.name;return typeof f=="string"&&f.trim().toLocaleLowerCase("en-US")===i});if(c){let m=c.productId??c.id??"<id>";throw new u(`A Product named ${JSON.stringify(o.trim())} already exists as ${m}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${m}" or choose another --name.`})}let d=await b(r,"/v1/products/blueprint-compose",A({blueprintId:n,name:o,tenantId:r.tenantId}),r.token,[r.token]);if(typeof d?.productId!="string"||typeof d?.blueprintId!="string"||typeof d?.productBuildId!="string")throw new u("product.blueprint.compose returned an invalid Product");await G(t,{...r,selectedProduct:d.productId});let l=typeof d?.shown_once=="string"&&d.shown_once.length>0?d.shown_once:void 0,p={blueprintId:d.blueprintId,nextSteps:[`hyperscale product show ${d.productId}`,...l?[]:['hyperscale key create --name "Founder CLI"']],productBuildId:d.productBuildId,productId:d.productId,selectedProduct:d.productId,...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},...l?{shown_once:l}:{}};if(e["--json"]){w(p);return}s(`Product: ${p.productId}`),s(`Blueprint: ${p.blueprintId}`),s(`Build: ${p.productBuildId}`),s(`Selected: ${p.selectedProduct}`),p.shown_once&&s(`Shown once Product API key: ${p.shown_once}`),s("Next:");for(let m of p.nextSteps)s(` ${m}`)}function De(e){return new URLSearchParams({tenantId:e}).toString()}async function Bt(e,t){let n=await $(e,t),o=await O(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),r=E(o,"product.list");if(e["--json"]){w(o);return}if(r.length===0){s('No Products yet. Run "hyperscale blueprint list", then "hyperscale product create --blueprint <id> --name <name>".');return}s("ID Name Status");for(let a of r){let i=a.productId??a.id??"unknown",c=a.displayName??a.name??"unnamed";s(`${i} ${c}${a.status?` ${a.status}`:""}`)}}async function Yt(e,t,n){let o=await $(e,t),r=n??o.selectedProduct;if(!r)throw new u("product show needs an id because no Product is selected. Create a Product first.");let a=await b(o,`/v1/products/${encodeURIComponent(r)}?${De(o.tenantId)}`,{},o.token,[o.token]);if(e["--json"]){w(a);return}qt(a,r)}function qt(e,t){let n=e?.displayName??e?.name??"unnamed",o=e?.status??"unknown",r=e?.blueprint,a=r?.id?`${r.name??r.id}${r.name?` (${r.id})`:""}`:"custom composition",i=e?.cost?.currency??"SAR",c=e?.plan?.monthlySar??e?.cost?.platformMonthlySar,d=e?.plan?.setupSar??e?.cost?.platformSetupSar,l=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements:[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(p=>`unavailable:${p}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(p=>p?.code??"pricing"):[]];s(`Name: ${n}`),s(`Product: ${e?.productId??t}`),s(`Status: ${o}`),s(`Blueprint: ${a}`),s(`Monthly: ${c==null?"not returned":`${i} ${c}`}`),s(`Setup: ${d==null?"not returned":`${i} ${d}`}`),s(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),s(`Live blockers: ${l.length>0?l.join(", "):"none"}`);for(let[p,m]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let f=e?.surfaces?.[p];f?.url&&s(`${m}: ${f.url}`)}s("Next:"),s(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function Ft(e,t,n){if(!n)throw new u("product select needs a Product id");let o=await $(e,t),r=await b(o,`/v1/products/${encodeURIComponent(n)}?${De(o.tenantId)}`,{},o.token,[o.token]);if(r?.productId!==n)throw new u("product.retrieve returned the wrong Product");await G(t,{...o,selectedProduct:n});let a={productId:n,selected:!0};e["--json"]?w(a):s(`Selected Product: ${r.displayName??n} (${n})`)}function Mt(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}async function zt(e){if(!e)throw new u("compose needs a .hsx file");if(!e.endsWith(".hsx"))throw new u(`compose reads a .hsx file, got ${e}`);let t;try{t=await M(e,"utf8")}catch(n){throw new u(`Could not read ${e}: ${n.message}`)}return{file:e,source:t}}function Vt(e){if(!e||typeof e!="object"||typeof e.ok!="boolean"||!Array.isArray(e.issues))throw new u("composer.check returned an invalid result");return{issues:e.issues.map(n=>{if(!n||typeof n!="object"||typeof n.code!="string"||typeof n.message!="string"||typeof n.path!="string")throw new u("composer.check returned an invalid issue");return{code:n.code,message:n.message,path:n.path}}),ok:e.ok}}async function ge(e,t,n,o="none"){let r=await zt(n),a=await $(e,t),i=o==="required"?K(a,e):o==="optional"?Ke(a,e):void 0,c=await Q(a,"/v1/composer/check",A({tenantId:a.tenantId,document:r.source,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}),a.token),d=ye(c.response,[a.token]),l=Vt(we(c.response,c.text,[a.token]));if(!l.ok)throw new J(["composer.check refused the program.",...Mt(l.issues)].join(`
118
+ `),{file:n,issues:l.issues,...d});return{check:l,receipt:d,context:a,productId:i,program:r,catalogRevisionId:e["--catalog-revision"]}}async function Wt(e,t,n){let o=await ge(e,t,n,"none");if(e["--json"]){w({command:"composer.check",file:n,issues:o.check.issues,ok:!0,...o.receipt});return}s(`Check passed: ${n}`)}async function He(e,t){let n=await Q(e.context,"/v1/composer/plan",A({document:e.program.source,tenantId:e.context.tenantId,...e.productId?{productId:e.productId}:{},...e.catalogRevisionId?{catalogRevisionId:e.catalogRevisionId}:{}}),e.context.token),o=we(n.response,n.text,[e.context.token]),r=ye(n.response,[e.context.token]);if(!o||typeof o!="object"||typeof o.summary!="string"||!Array.isArray(o.actions)||!o.pricing||typeof o.pricing!="object")throw new u("composer.plan returned an invalid result");let a=o.actions.filter(i=>!i||typeof i!="object"||i.kind!=="configure_product");if(a.length>0)throw new J([o.summary,...a.map(i=>i&&typeof i=="object"?`${i.kind??"unknown"} ${i.target??"unknown"} ${i.detail??"Composer refused this action."}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
119
+ `),{actions:a,file:t,...r,...e.productId?{productId:e.productId}:{}});return{...o,...r}}async function Gt(e,t,n){let o=await ge(e,t,n,"optional"),r=await He(o,n);if(e["--json"]){w({command:"composer.plan",file:n,check:{...o.check,...o.receipt},plan:r,...o.productId?{productId:o.productId}:{}});return}s(r.summary);for(let a of r.actions)s(`${a.kind} ${a.target} ${a.detail}`);s(`Monthly: SAR ${r.pricing.monthlySar}`),s(`Activation: SAR ${r.pricing.activationSar}`)}async function Xt(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new u("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let o=await ge(e,t,n,"required");await He(o,n);let r=await b(o.context,"/v1/products/recompose",A({program:{source:o.program.source},...o.catalogRevisionId?{catalogRevisionId:o.catalogRevisionId}:{},tenantId:o.context.tenantId,productId:o.productId},e["--idempotency-key"]),o.context.token,[o.context.token]);if(!r||typeof r.productBuildId!="string")throw new u("product.recompose returned no new build identity");if(e["--json"]){w({command:"product.recompose",file:n,output:r});return}s(`Product: ${r.productId??o.productId}`),s(`Build: ${r.productBuildId}`),r.buildDigest&&s(`Digest: ${r.buildDigest}`)}function Ke(e,t){let n=t["--product"]??e.selectedProduct;return typeof n=="string"&&n.length>0?n:void 0}function K(e,t){let n=Ke(e,t);if(!n)throw new u("No Product selected. Pass --product <id> or create a Product first.");return n}async function q(e,t,n){let o=await W(t),r=K(o??{},e),a=j(e,t,o??{});if(o&&(a.baseUrl!==o.baseUrl||a.environment!==o.environment))throw new u(`The selected Product belongs to ${o.baseUrl} (${o.environment}). Select a Product at the configured API origin first.`);let i=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!i)throw Te(r);let c={...a,apiKey:i,productId:r};return await Qt(c,r,n),c}async function Qt(e,t,n){let o=`/v1/products/${encodeURIComponent(t)}/operation-set`,{response:r,text:a}=await D(e,o,{},n);if(r.ok)return;let i;try{i=JSON.parse(a)?.error?.message}catch{i=void 0}throw typeof i=="string"&&i.includes("does not match API key Product")?new u(`${i} Or set HYPERSCALE_API_KEY to a key for ${t}, or pass that key with --api-key.`):H(r,a,[e.apiKey])}async function Je(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:o,text:r}=await D(e,n,{},t);if(!o.ok)throw Ye(o,r,[e.apiKey]);return tn(r,o.status)}async function Zt(e,t,n){let o=await q(e,t),r=await Je(o);if(n){en(r,n,e);return}if(e["--json"]){w(r);return}if(r.status==="legacy"){s("This Product uses a legacy surface. It has no frozen public actions yet."),s(`Build: ${r.productBuildId}`);return}if(r.publicActions.length===0)s("No public actions");else{s("Operation ID Input Kind");for(let a of r.publicActions){let i=a.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";s(`${a.instrument}.${a.name} ${rn(a.inputSchema)} ${i}`)}}if(r.setupOperations.length>0){s("Setup operations (run with hyperscale call)");for(let a of r.setupOperations)s(a.operationName)}if(r.readOperationIds.length>0){s("Reads (run with hyperscale call)");for(let a of r.readOperationIds)s(on(a))}s(`Digest: ${r.tenantOperationSetDigest}`),s(`Setup digest: ${r.tenantSetupOperationSetDigest}`),s(`Read digest: ${r.tenantReadOperationSetDigest}`),s(`Build: ${r.productBuildId}`),s(`Surface version: ${r.tenantSurfaceVersion}`)}function en(e,t,n){if(e.status==="legacy")throw new u(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let o=e.publicActions.find(c=>c&&`${c.instrument}.${c.name}`===t),r=nn(t),a=e.setupOperations.find(c=>c&&(c.operationId===t||c.operationId===r||c.operationName===t));if(a){let{inputSchema:c,operationId:d,operationName:l}=a,p={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:d,operationName:l,command:`hyperscale call ${l}`,inputSchema:c};if(n["--json"]){w(p);return}s(`Operation ID: ${d}`),s(`Operation name: ${l}`),s(`Run: hyperscale call ${l}`),s(`Input schema: ${JSON.stringify(c,null,2)}`),(!Array.isArray(c.required)||c.required.length===0)&&s("Input: omit --input or pass {}."),s(`Setup digest: ${e.tenantSetupOperationSetDigest}`),s(`Build: ${e.productBuildId}`),s(`Surface version: ${e.tenantSurfaceVersion}`);return}if(!o)throw new u(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let i={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:o};if(n["--json"]){w(i);return}s(`Operation ID: ${o.instrument}.${o.name}`),s(`Instrument: ${o.instrument}`),s(`Input schema: ${JSON.stringify(o.inputSchema,null,2)}`),s(`Output schema: ${JSON.stringify(o.outputSchema,null,2)}`),s(`Actor policy: ${JSON.stringify(o.actorPolicy,null,2)}`),s(`Port policy: ${JSON.stringify(o.portPolicy,null,2)}`),s(`Idempotency policy: ${JSON.stringify(o.idempotencyPolicy,null,2)}`),s(`Receipt policy: ${JSON.stringify(o.receiptPolicy,null,2)}`),s(`Receipt evidence: ${JSON.stringify(o.receiptEvidence,null,2)}`),s(`Digest: ${e.tenantOperationSetDigest}`),s(`Build: ${e.productBuildId}`),s(`Surface version: ${e.tenantSurfaceVersion}`)}function tn(e,t){let n;try{n=JSON.parse(e)}catch{throw new u(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="legacy"&&n.status!=="frozen"||typeof n.productBuildId!="string")throw new u("The Product operation set is not in the expected format. Upgrade the CLI.");if(n.status==="legacy")return n;if(typeof n.tenantSurfaceVersion!="number"||typeof n.tenantOperationSetDigest!="string"||typeof n.tenantReadOperationSetDigest!="string"||typeof n.tenantSetupOperationSetDigest!="string"||!Array.isArray(n.publicActions)||!Array.isArray(n.readOperationIds)||!Array.isArray(n.setupOperationIds)||!Array.isArray(n.setupOperations))throw new u("The Product operation set is not in the expected format. Upgrade the CLI.");return n}function nn(e){return e.replaceAll(".","_")}function on(e){for(let t of["create","list","retrieve"]){let n=`_${t}`;if(e.endsWith(n))return`${e.slice(0,-n.length)}.${t}`}return e}function rn(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(r=>typeof r=="string"):[]),o=Object.entries(t).map(([r,a])=>`${r}${n.has(r)?"":"?"}: ${Be(a)}`);return o.length===0?"no input":o.join(", ")}function Be(e){return!e||typeof e!="object"?"value":Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(t=>String(t)).join(" | "):e.type==="array"?`${Be(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function an(e,t,n){if(!n)throw new u("product run needs a public action");let o=await q(e,t,n),r=await Je(o,n);sn(r,n);let a=await qe(e),i=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:c,text:d}=await D(o,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(a),headers:{"content-type":"application/json","idempotency-key":i},method:"POST"},n);if(!c.ok)throw Ye(c,d,[o.apiKey],{action:n});let l=c.headers.get("hyperscale-operation-id"),p=c.headers.get("hyperscale-receipt-id"),m=c.headers.get("x-request-id"),f=l?y(l,[o.apiKey]):null,k=p?y(p,[o.apiKey]):null,g=m?y(m,[o.apiKey]):null;if(e["--json"]){w({idempotencyKey:i,...g?{requestId:g}:{},operationId:f,receiptId:k,output:cn(d)});return}f&&s(`Operation: ${f}`),k&&s(`Receipt: ${k}`),s(`Idempotency key: ${i}`);let h=Fe(d);h&&s(h)}function sn(e,t){if(e.status==="legacy")throw new u(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let n=e.publicActions.find(r=>r&&`${r.instrument}.${r.name}`===t);if(n)return n;let o=e.publicActions.map(r=>`${r.instrument}.${r.name}`).map(r=>({candidate:r,distance:ue(t,r)})).sort((r,a)=>r.distance-a.distance||r.candidate.localeCompare(a.candidate)).slice(0,3).map(({candidate:r})=>r);throw new u(`Unknown frozen public action: ${t}. Closest valid names: ${o.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function cn(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function Ye(e,t,n=[],o={}){let r=y(t.trim(),n),a;try{a=JSON.parse(t)}catch{return new u(`HTTP ${e.status}${r?` \xB7 ${r}`:""}`)}if(!a?.error||typeof a.error.message!="string")return new u(`HTTP ${e.status}`);let i=typeof a.error.code=="string"?a.error.code:"user_error",c=i==="user_error"?"":`${i}: `,d=y(`HTTP ${e.status} \xB7 ${c}${a.error.message}`,n),l=un(a.error.details,n),p;i==="idempotency_conflict"?p="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":[a.error.message,...l].some(x=>typeof x=="string"&&x.includes("[Truncated]"))&&o.action&&(p=`Run "hyperscale product actions ${o.action}" to read the full input schema and allowed values.`);let m=e.headers.get("x-request-id")??(a&&typeof a=="object"&&typeof a.requestId=="string"?a.requestId:void 0),f=e.headers.get("hyperscale-operation-id")??void 0,k=e.headers.get("hyperscale-receipt-id")??void 0,g=m?y(m,n):void 0,h=f?y(f,n):void 0,I=k?y(k,n):void 0,P=new u([d,...l].join(`
120
+ `),{code:i,...a.error.details?{details:F(a.error.details,n)}:{},...p?{fix:p}:{}});return g&&(P.requestId=g),h&&(P.operationId=h),I&&(P.receiptId=I),P}function F(e,t){return typeof e=="string"?y(e,t):Array.isArray(e)?e.map(n=>F(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[y(n,t),F(o,t)])):e}function un(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(o=>{if(!o||typeof o!="object")return[];let a=(Array.isArray(o.path)?o.path.join("."):"input")||"input";return typeof o.message=="string"?[`${a}: ${y(o.message,t)}`]:[]});let n=[];return ce(e,"",n,t),n}function ce(e,t,n,o){if(Array.isArray(e)){if(e.every(r=>r===null||typeof r!="object")){n.push(`${Ae(t)}: ${y(e.join(", "),o)}`);return}e.forEach((r,a)=>ce(r,`${t}[${a}]`,n,o));return}if(e&&typeof e=="object"){for(let[r,a]of Object.entries(e))ce(a,t?`${t}.${r}`:r,n,o);return}t&&n.push(`${Ae(t)}: ${y(String(e),o)}`)}function Ae(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function dn(e,t){let n=await $(e,t),o=K(n,e),r=await b(n,"/v1/sandbox-api-keys",A({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:o}),n.token,[n.token]);if(e["--json"]){w(r);return}s(`Key: ${r.apiKeyId??"unknown"}`),s(`Product: ${r.productId??o}`),s(`Status: ${r.status??"unknown"}`),r.secret?(s(`Secret: ${r.secret}`),s("Store it now. Hyperscale will not return it again."),s("Next:"),s(` export HYPERSCALE_API_KEY=${ln(r.secret)}`),s(` hyperscale product actions --product ${o}`)):s("The key already existed, so the one-time secret is unavailable.")}function ln(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function pn(e,t){let n=await $(e,t),o=K(n,e),r=await O(n,"/v1/api-keys",{tenantId:n.tenantId},"api_key.list",n.token,[n.token]),a=E(r,"api_key.list").filter(c=>c.productId===o),i={...r,items:a};if(e["--json"]){w(i);return}for(let c of a)s(`${c.apiKeyId} ${c.name??"unnamed"} ${c.status??"unknown"}`)}async function mn(e,t,n){if(!n)throw new u("key revoke needs an API key id");let o=await $(e,t),r=K(o,e),a=await b(o,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,A({tenantId:o.tenantId,productId:r}),o.token,[o.token]);e["--json"]?w(a):s(`Key ${a.apiKeyId??n}: ${a.status??"revoked"}`)}async function fn(e,t){let n=await $(e,t),o=n.identity??await T(n,n.token),r=he(n,o);if(e["--json"]){w(r);return}s(`User: ${o.email}`),s(`Tenant: ${o.tenantId}`),s(`Role: ${o.role}`),s(`Token: ${o.name}`),s(`Expires: ${o.expiresAt}`)}async function hn(e,t,n){let o=await Le(e),r=n?n.toLowerCase():null,a=r?o.operations.filter(c=>c.name.toLowerCase().includes(r)||c.path.toLowerCase().includes(r)):o.operations;if(t["--json"]){s(JSON.stringify(a,null,2));return}if(a.length===0){s(n?`No operation matches ${n}`:"No operations");return}let i=Math.max(...a.map(c=>c.name.length));for(let c of a)s(`${c.name.padEnd(i)} ${c.method.padEnd(6)}${c.path}`)}async function yn(e,t){let n=await $(e,t),o=await O(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),r=E(o,"activity.list");if(e["--json"]){w(o);return}s("Time Activity Target Status");for(let a of r){let i=a.operation??a.auditEvent??"activity",c=a.resourceKind&&a.resourceId?`${a.resourceKind}:${a.resourceId}`:a.resourceKind??a.resourceId??"-";s(`${a.occurredAt??"unknown"} ${i} ${c} ${a.status??"recorded"}`)}}function wn(e,t){let n={...t},o=[],r=e.path.replace(/\{([^}]+)\}/g,(a,i)=>{let c=n[i];return c==null?(o.push(i),""):(delete n[i],encodeURIComponent(String(c)))});if(o.length>0)throw new u(`${e.name} needs ${o.join(", ")} in --input`);return{path:r,remaining:n}}function gn(e){let t=new URLSearchParams;for(let[o,r]of Object.entries(e))r!=null&&t.set(o,typeof r=="string"?r:JSON.stringify(r));let n=t.toString();return n?`?${n}`:""}function ue(e,t){let n=Array.from({length:t.length+1},(o,r)=>r);for(let o=1;o<=e.length;o+=1){let r=[o];for(let a=1;a<=t.length;a+=1)r[a]=Math.min(r[a-1]+1,n[a]+1,n[a-1]+(e[o-1]===t[a-1]?0:1));n.splice(0,n.length,...r)}return n[t.length]}function In(e,t){let n=e.find(a=>a.name===t);if(n)return n;let o=e.filter(a=>a.operationId===t);if(o.length===1)return o[0];if(o.length>1)throw new u(`${t} matches more than one operation. Use one of: ${o.map(a=>a.name).join(", ")}.`);let r=e.map(a=>({candidate:a,distance:Math.min(ue(t,a.name),ue(t,a.operationId))})).sort((a,i)=>a.distance-i.distance||a.candidate.name.localeCompare(i.candidate.name)).slice(0,3).flatMap(({candidate:a})=>[a.name,a.operationId]);throw new u(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${r.join(", ")}.`)}async function kn(e,t,n){if(!n)throw new u("call needs an operation name");let o=await Le(e),r=In(o.operations,n),a=await qe(t),{path:i,remaining:c}=wn(r,a),d={method:r.method},l=i;r.method==="GET"?l+=gn(c):(d.body=JSON.stringify(c),d.headers={"content-type":"application/json",...r.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:p,text:m}=await D(e,l,d);if(p.ok){if(t["--json"]){let f=$t(m),k=p.headers.get("x-request-id")??(f&&typeof f=="object"&&typeof f.requestId=="string"?f.requestId:null),g=p.headers.get("hyperscale-operation-id")??null,h=p.headers.get("hyperscale-receipt-id")??null,I=Ue(p.headers),P=k?y(k,[e.apiKey]):null,x=g?y(g,[e.apiKey]):null,Me=h?y(h,[e.apiKey]):null,ze=I?y(I,[e.apiKey]):null;w({status:p.status,data:f,requestId:P,operationId:x,receiptId:Me,traceId:ze});return}s(Fe(m));return}throw H(p,m,[e.apiKey])}async function qe(e){if(e["--input"]!==void 0&&e["--input-file"]!==void 0)throw new u("Use only one of --input and --input-file");if(e["--input"]!==void 0)return ne(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await M(e["--input-file"],"utf8")}catch(n){throw new u(`Could not read ${e["--input-file"]}: ${n.message}`)}return ne(t,"--input-file")}if(!process.stdin.isTTY){let t=await It();if(t.trim()!=="")return ne(t,"stdin")}return{}}function ne(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(o){throw new u(`${t} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new u(`${t} must be a JSON object`);return n}function Fe(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function s(e){process.stdout.write(`${e}
121
+ `)}function w(e){s(JSON.stringify(e,null,2))}function $n(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(!n.startsWith("--"))return n;Ee.has(n)&&(t+=1)}}function Pn(e,t){let n=$n(t)==="call",o=t.includes("--json");if(n&&o&&e instanceof v){w({status:e.status,error:e.structuredError??{code:e.code??"http_error",message:e.message},requestId:e.requestId??null,operationId:e.operationId??null,receiptId:e.receiptId??null,traceId:e.traceId??null});let c=typeof e.message=="string"?e.message:e.stack??String(e);process.stderr.write(`${c}
122
+ `);return}let r=e instanceof u&&typeof e.shownOnce=="string"?e.shownOnce:void 0;if(!o){let c=e instanceof u?e.message:e.stack??String(e),d=e instanceof u&&typeof e.fix=="string"?`
123
+ Fix: ${e.fix}`:"",l=r?`
124
+ Shown once Product API key: ${r}`:"";process.stderr.write(`${c}${d}${l}
125
+ `);return}let a=e instanceof u,i=a&&typeof e.code=="string"?e.code:a?"user_error":"internal_error";process.stderr.write(`${JSON.stringify({error:{code:i,message:a?e.message:"The command failed unexpectedly.",...a&&e.details?{details:e.details}:{},fix:a?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."},...r?{shown_once:r}:{}})}
126
+ `)}async function bn(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function Sn(e,t){let{flags:n,positional:o}=mt(e);if(n["--version"])return s(await bn()),0;if(n["--help"]&&o.length>0)return process.stdout.write(pt(o)),0;if(o.length===0&&!n["--help"]){if(n["--json"])throw new u('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await Se(n,t),0):(s('Build your first Product with "hyperscale start".'),s('Run "hyperscale --help" for every command.'),0)}if(n["--help"])return process.stdout.write(lt),0;let[r,...a]=o;if(r==="start")return await Se(n,t),0;if(r==="auth"){if(a[0]==="login")await Tt(n,t);else if(a[0]==="status")await Et(n,t);else if(a[0]==="logout")await vt(n,t);else throw new u('Auth subcommands are "login", "status", and "logout"');return 0}if(r==="blueprint"){let i=j(n,t);if(a[0]==="list")await Ct(i,n);else if(a[0]==="show")await Rt(i,n,a[1]);else throw new u('Blueprint subcommands are "list" and "show"');return 0}if(r==="product"){if(a[0]==="create")await Jt(n,t);else if(a[0]==="list")await Bt(n,t);else if(a[0]==="show")await Yt(n,t,a[1]);else if(a[0]==="select")await Ft(n,t,a[1]);else if(a[0]==="actions")await Zt(n,t,a[1]);else if(a[0]==="run")await an(n,t,a[1]);else throw new u('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(r==="compose"){if(a[0]==="check")await Wt(n,t,a[1]);else if(a[0]==="plan")await Gt(n,t,a[1]);else if(a[0]==="apply")await Xt(n,t,a[1]);else throw new u('Compose subcommands are "check", "plan", and "apply"');return 0}if(r==="key"){if(a[0]==="create")await dn(n,t);else if(a[0]==="list")await pn(n,t);else if(a[0]==="revoke")await mn(n,t,a[1]);else throw new u('Key subcommands are "create", "list", and "revoke"');return 0}if(r==="whoami")return await fn(n,t),0;if(r==="activity"){if(a[0]!=="list")throw new u('The only activity subcommand is "list"');return await yn(n,t),0}if(r==="ops"){if(a[0]!=="list")throw new u('The only ops subcommand is "list"');let i=n["--product"]?await q(n,t):ke(n,t);return await hn(i,n,a[1]),0}if(r==="call"){let i=n["--product"]?await q(n,t):ke(n,t);return await kn(i,n,a[0]),0}throw new u(`Unknown command: ${r}`)}Sn(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{Pn(e,process.argv.slice(2)),process.exitCode=e instanceof u&&Number.isInteger(e.exitCode)?e.exitCode:1});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperscale0/cli",
3
- "version": "1.0.0-beta.12",
3
+ "version": "1.0.0-beta.14",
4
4
  "description": "Hyperscale CLI: compose Products, manage keys, and call Product operations.",
5
5
  "license": "LicenseRef-Hyperscale-Proprietary",
6
6
  "author": "Hyperscale LLC",
@@ -20,5 +20,5 @@
20
20
  "publishConfig": {
21
21
  "access": "public"
22
22
  },
23
- "gitHead": "8b8e65601bb845e906f480c9950226c9171b6487"
23
+ "gitHead": "20edb82f11d248c315526a34ad3b2c1fc4354919"
24
24
  }