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

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 (3) hide show
  1. package/README.md +6 -8
  2. package/hyperscale.js +30 -36
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @hyperscale0/cli
2
2
 
3
- The Hyperscale founder command line. It logs a founder in, discovers public
4
- Blueprints, composes Products, manages sandbox API keys, and runs one Product's
5
- frozen public actions.
3
+ Hyperscale CLI: the founder command line. It logs a founder in, discovers
4
+ public Blueprints, composes Products, manages sandbox API keys, and runs one
5
+ Product's frozen public actions.
6
6
 
7
7
  ## Install
8
8
 
@@ -14,8 +14,8 @@ bunx @hyperscale0/cli --help
14
14
 
15
15
  ## Quickstart
16
16
 
17
- Mint a founder PAT in the portal at https://hyperscale0.ai/desk. Open Security,
18
- then Personal access tokens. Unapproved founders can request access at
17
+ Mint a founder PAT in Hyperscale Portal at https://hyperscale0.ai/desk. Open
18
+ Security, then Personal access tokens. Unapproved founders can request access at
19
19
  https://hyperscale0.ai/request-access.
20
20
 
21
21
  ```bash
@@ -30,8 +30,6 @@ bunx @hyperscale0/cli key create --name "Founder laptop"
30
30
  bunx @hyperscale0/cli compose check product.hsx
31
31
  bunx @hyperscale0/cli compose plan product.hsx
32
32
  bunx @hyperscale0/cli compose apply product.hsx --yes
33
- bunx @hyperscale0/cli team list
34
- bunx @hyperscale0/cli team invite --email developer@example.com --role developer
35
33
  bunx @hyperscale0/cli activity list
36
34
  bunx @hyperscale0/cli ops list payment
37
35
 
@@ -64,7 +62,7 @@ it prints the PAT desk and request-access URL. With `--token` or
64
62
  browser.
65
63
 
66
64
  Founder PAT commands are `auth`, `whoami`, `product create/list/show/select`,
67
- `compose plan/apply`, `key`, `team`, and `activity`. They use
65
+ `compose plan/apply`, `key`, and `activity`. They use
68
66
  `--token`, `HYPERSCALE_TOKEN`, or a stored login in that order. Product API
69
67
  key commands are `product actions/run`, `ops list`, and `call`. They use
70
68
  `HYPERSCALE_API_KEY` and need no founder login profile. `compose check`
package/hyperscale.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Se}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",O="https://hyperscale0.ai/request-access",C=`Mint a founder PAT in the portal at ${oe}. Open Security, then Personal access tokens.`,et=`Not logged in. Run "hyperscale auth login" to open portal sign-in. In a headless environment, ${C} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${O}.`,tt=`Run "hyperscale auth login". For headless use, ${C} Unapproved founders can request access at ${O}.`,re=3e4,nt=2e3,ot=120*1e3,rt=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,at=`hyperscale <command> [options]
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]
3
3
 
4
4
  Commands:
5
5
  start Create a Product and run its first published journey step
@@ -21,8 +21,6 @@ Commands:
21
21
  key create Create a sandbox Product API key
22
22
  key list List keys for the selected Product
23
23
  key revoke <id> Revoke a Product API key
24
- team list List company members and pending invitations
25
- team invite Invite a company member
26
24
  activity list List company activity
27
25
  whoami Show the user and company this founder PAT resolves to
28
26
  ops list [filter] List the product's callable operations
@@ -35,8 +33,6 @@ Options:
35
33
  --api-key <key> Product API key (default: $HYPERSCALE_API_KEY)
36
34
  --base-url <url> API origin (default: $HYPERSCALE_BASE_URL, else ${ce})
37
35
  --environment <name> sandbox or live (default: $HYPERSCALE_ENVIRONMENT, else ${ue})
38
- --email <email> Email for team invite
39
- --role <role> Seeded role name or custom role id for team invite
40
36
  --blueprint <slug> Blueprint for non-interactive start or product create
41
37
  --name <name> Product or key name
42
38
  --product <id> Product id for key commands and Product-key actions
@@ -51,7 +47,7 @@ Options:
51
47
  --help Print this help
52
48
 
53
49
  Founder PAT commands: auth, whoami, product create/list/show, compose check/plan/apply,
54
- key, team, and activity. Product API key commands: product actions/run, ops list,
50
+ key, and activity. Product API key commands: product actions/run, ops list,
55
51
  and call. The server compiles every compose command against the selected tenant
56
52
  catalog revision. The two credential types are not interchangeable. Browser
57
53
  login returns through a single-use localhost callback.
@@ -65,8 +61,8 @@ key. The explicit flag wins over its environment variable. Founder logins use
65
61
  macOS Keychain when available. Set HYPERSCALE_CREDENTIAL_STORE=file to keep the
66
62
  founder PAT in the owner-only CLI profile instead and skip Keychain access.
67
63
 
68
- ${C}
69
- Request access at ${O}.
64
+ ${O}
65
+ Request access at ${C}.
70
66
 
71
67
  Examples:
72
68
  hyperscale start
@@ -83,45 +79,43 @@ Examples:
83
79
  hyperscale compose check product.hsx
84
80
  hyperscale compose plan product.hsx --json
85
81
  hyperscale compose apply product.hsx --yes
86
- hyperscale team list
87
- hyperscale team invite --email developer@example.com --role developer
88
82
  hyperscale activity list
89
83
  hyperscale ops list account
90
84
  hyperscale call account.list --input '{"limit":5}'
91
85
  hyperscale call account.list --input-file input.json
92
86
  printf '{"limit":5}' | hyperscale call account.list
93
87
  hyperscale call account.retrieve --input '{"accountId":"acct_sandbox_..."}'
94
- `,we={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_..."},"team list":{usage:"team list [--json]",summary:"List company members and pending invitations.",options:["--json Print machine-readable JSON."],example:"hyperscale team list"},"team invite":{usage:"team invite --email <email> --role <role> [--json]",summary:"Invite a company member.",options:["--email <email> Required invitee email.","--role <role> Required seeded role or custom role id.","--json Print the invitation and one-time token as JSON."],example:"hyperscale team invite --email developer@example.com --role developer"},"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 st(e){let n=Object.keys(we).sort((o,a)=>a.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=we[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(`
95
- `)}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)}},T=class extends u{constructor(t,{requestId:n,status:r,code:o,details:a,operationId:i,receiptId:c,traceId:d,structuredError:l}={}){super(t,{code:o,details:a}),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 Ae(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}},ve=new Set(["--api-key","--base-url","--blueprint","--catalog-revision","--environment","--email","--idempotency-key","--input","--input-file","--name","--product","--role","--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(ve.has(o)){let a=e[r+1];if(a===void 0)throw new u(`${o} needs a value`);n[o]=a,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 ge(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Ae();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(/\/+$/,""),a;try{a=new URL(o)}catch{a=null}let i=a?.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(a.hostname);if(a.protocol!=="https:"&&!(a.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 b(e,t){return M(Te(t),`session-${R(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=b(e,t),r=`${Xe(n)}.`,o;try{o=await Me(te(n),{withFileTypes:!0})}catch(a){if(a&&a.code==="ENOENT")return;throw a}for(let a of o){if(!a.isFile()||!a.name.startsWith(r))continue;let i=a.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 j(M(te(n),a.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 j(r),o}}function ut(e){return te(e)}async function j(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:a}=e;if(typeof n!="string"||typeof r!="string"||o!=="sandbox"&&o!=="live"||!(a===null||typeof a=="string"))throw new u(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:r,environment:o,selectedProduct:a}}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)}
96
- `)}function R(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=Se(ne,e,{env:r,stdio:["pipe","pipe","pipe"]}),a=[],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=>a.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(a).toString("utf8"),unavailable:!1})),t===void 0?o.stdin.end():o.stdin.end(`${t}
97
- `)})}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=R(e);if(z(n)==="auto"&&await pe()){let o=JSON.stringify(t),a=["add-generic-password","-a",r,"-s",de,"-U","-X",Buffer.from(o,"utf8").toString("hex")].join(" ");if((await G(["-i"],a)).status===0)return await j(b(e,n)),"keychain"}return await N(b(e,n),`${JSON.stringify({account:r,activeStore:"file",credential:t})}
98
- `),"file"}async function pt(e,t){let n=R(e);try{let r=JSON.parse(await q(b(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 Ne(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 a=await G(["find-generic-password","-a",R(e),"-s",de,"-w"]);a.status===0&&(o=Ee(a.stdout.trim()))}return o||(r.state==="valid"?r.credential:null)}async function Oe(e,t){await le(e,t);let n=R(e);if(z(t)==="file")return await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
99
- `),{keychainDeleted:!0};if(ne===null)return await j(b(e,t)),{keychainDeleted:!0};if(!await pe())return await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
100
- `),{keychainDeleted:!1};let r=await G(["delete-generic-password","-a",n,"-s",de]);return r.status!==0&&r.status!==44?(await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
101
- `),{keychainDeleted:!1}):(await j(b(e,t)),{keychainDeleted:!0})}function Ce(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function $(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 a=_(e,t,r);if(a.baseUrl!==r.baseUrl||a.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 Ne(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=>`
102
- \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 _e(e,t,n={},r){let o=`${e.baseUrl}${t}`,a=K(e.baseUrl);if(K(o)!==a)throw new u(`The requested path ${t} leaves the ${a} 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 g(e,t,n={},r,o=[]){let{response:a,text:i}=await _e(e,t,n,r);if(!a.ok)throw U(a,i,o);try{return JSON.parse(i)}catch{throw new u(`HTTP ${a.status} returned invalid JSON`)}}function P(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}`,a=K(e.baseUrl);if(K(o)!==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(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 je(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(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: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=ae(t),r=o=>typeof o=="string";if(!E(n)||n.schemaVersion!==1||!r(n.title)||!E(n.composition)||!r(n.composition.id)||!Array.isArray(n.operations))return null;for(let o of n.operations)if(!E(o)||!r(o.method)||!r(o.path)||!r(o.name)||!r(o.operationId)||!r(o.idempotency))return null;return n.sdk!==void 0&&(!E(n.sdk)||!r(n.sdk.packageName))?null:n}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ae(e){return typeof e=="string"?B(e):Array.isArray(e)?e.map(ae):E(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[B(t),ae(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,a=typeof o?.code=="string"?o.code:void 0,i=typeof o?.message=="string"?o.message:e.trim(),c=S(i,t),d=a&&typeof o?.message=="string"?`${a}: ${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:a,details:l,humanMessage:d,redactedMessage:c,requestId:p,structuredError:{code:a??"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,a=e.headers.get("hyperscale-operation-id")??null,i=e.headers.get("hyperscale-receipt-id")??null,c=Re(e.headers),d=r.humanMessage;return new T(`HTTP ${e.status}${d?` \xB7 ${d}`:""}${o?`
103
- Request id: ${o}`:""}`,{code:r.code,details:r.details,operationId:a,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 g(e,Qe,{},t,[t]))}catch(n){throw!(n instanceof T)||n.status!==401?n:new u(`That founder PAT was not accepted (HTTP 401). ${C}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:C})}}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=Se(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,a=new Promise((k,y)=>{o={reject:y,resolve:k}}),i=Ye((k,y)=>{let w=new URL(k.url??"/","http://127.0.0.1");if(k.method!=="GET"||w.pathname!=="/callback"){y.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),y.end(`Not found.
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.
104
98
  `);return}if(r){y.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login callback was already received.
105
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.
106
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.
107
- `),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"),ye=w.searchParams.get("tenantId");if(!H||!ye){y.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login callback is missing its grant or tenant.
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.
108
102
  `);return}r=!0,y.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),y.end(`Login received. Return to the terminal.
109
- `),o.resolve({grant:H,tenantId:ye})});await new Promise((k,y)=>{let w=H=>y(H);i.once("error",w),i.listen(0,"127.0.0.1",()=>{i.off("error",w),k()})}),i.once("error",k=>o.reject(k));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}
110
- `);let I=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 a}finally{clearTimeout(I),await Z(i)}}function ke(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:oe,requestAccessUrl:O};if(e["--json"]){f(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: ${oe}`),s(`No access yet: ${O}`)}async function $e(e,t,n,r,o){let a=await V(o),i={email:t.email,...e,selectedProduct:a&&a.email===t.email&&a.baseUrl===e.baseUrl&&a.environment===e.environment?a.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 Oe(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 ${b(i,o)} with mode 0600.
111
- `)}let d=me(i,t);r["--json"]?f(d):s(`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 $e(n,d,r,e,t);return}if(e["--no-browser"]){ke(e);return}let o=await $t(n,t);if(!o){ke(e);return}let a=await g(n,"/v1/personal-access-token-login-grants/exchange",P({tenantId:o.tenantId,grant:o.grant}),void 0,[o.grant]),i=a?.secret;if(typeof i!="string"||!i.startsWith("hyperscale_pat_")||a?.tenantId!==o.tenantId)throw new u("CLI login grant exchange returned an invalid PAT");let c=await A(n,i);await $e(n,c,i,e,t)}async function bt(e,t){let n=await $(e,t),r=n.identity??await A(n,n.token),o=me(n,r);if(e["--json"]){f(o);return}s(`User: ${r.email}`),s(`Tenant: ${r.tenantId}`),s(`Role: ${r.role}`),s(`Token: ${r.name}`),s(`Scopes: ${r.scopes.join(", ")}`),s(`Expires: ${r.expiresAt}`),s(`API: ${n.baseUrl}`),s(`Environment: ${n.environment}`),s(`Product: ${n.selectedProduct??"not selected"}`)}async function Pt(e,t){let n=await V(t);if(!n){e["--json"]?f({status:"signed_out"}):s("Already logged out.");return}let r=await Ne(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,a=r?.tokenName;if(e["--revoke"]&&r){if(!o||!a){let d=await A(n,r.token);o=d.personalAccessTokenId,a=d.name}await g(n,`/v1/personal-access-tokens/${encodeURIComponent(o)}/revoke`,P({tenantId:r.tenantId,personalAccessTokenId:o}),r.token,[r.token])}let i=await Oe(n,t),c=e["--revoke"]===!0;St(e,{cleanup:i,personalAccessTokenId:o,revoked:c,status:"signed_out",tokenName:a})}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?s(`Revoked founder PAT ${r} and forgot local state.`):(s(`Forgot local founder PAT ${r}.`),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.
112
- `)}function v(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new u(`${t} returned an invalid collection`);return e.items}async function x(e,t,n,r,o,a=[]){let i=[],c=new Set,d,l;for(;;){let I=new URLSearchParams(n);d&&I.set("cursor",d);let k=I.size>0?`?${I}`:"",y=await g(e,`${t}${k}`,{},o,a);l===void 0&&(l=y),i.push(...v(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 x(e,"/v1/blueprints",{},"blueprint.list"),r=v(n,"blueprint.list");if(t["--json"]){f(n);return}s("ID Name Summary");for(let o of r)s(`${o.id} ${o.name}${o.summary?` ${o.summary}`:""}`);s("Next:"),s(" hyperscale blueprint show <id>"),s(" hyperscale product create --blueprint <id> --name <name>")}async function vt(e,t,n){if(!n)throw new u("blueprint show needs a Blueprint id");let r=await g(e,`/v1/blueprints/${encodeURIComponent(n)}`),o=Tt(r,e.baseUrl);if(t["--json"]){f(o);return}s(`${o.name} (${o.id})`),s(o.summary),s(o.description),s("Nouns:");for(let a of o.customInstruments??[])s(` ${a.name} (${a.id}): ${a.summary}`);for(let a of o.instruments??[])s(` ${a.title} (${a.id}): ${a.summary}`);s("Verbs:");for(let a of o.verbs??[])s(` ${a.alias} -> ${a.operation}: ${a.summary}`);s("Parties:");for(let a of o.parties??[])s(` ${a.instrumentId}.${a.role} -> ${a.accountField}`);s("Money flows:");for(let a of o.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 o.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}`)}o.priceEstimate&&(s("Price estimate:"),s(` monthlySar: SAR ${Number(o.priceEstimate.monthlySar).toLocaleString("en-US")}`),s(` setupSar: SAR ${Number(o.priceEstimate.setupSar).toLocaleString("en-US")}`),s(` complexityScore: ${o.priceEstimate.complexityScore}`)),s("Dials:");for(let a of o.dials??[])s(` ${a.instrumentId}.${a.key} (${a.kind}): ${a.summary}`);s("Journeys:");for(let a of o.journeys??[])s(` ${a.title} (${a.id}): ${a.summary}`),s(` ${a.steps.join(" -> ")}`);o.hsxStructured&&(s("HSX:"),s(` Source:
113
- ${Ie(o.hsxStructured.source," ")}`),o.hsxStructured.document&&s(` Structured document:
114
- ${Ie(JSON.stringify(o.hsxStructured.document,null,2)," ")}`)),s("Terms:");for(let[a,i]of Object.entries(o.terminology))s(` ${a}: ${i.definition}`),s(` ${i.href}`);s("Next:"),s(` hyperscale product create --blueprint ${o.id} --name <name>`)}function Tt(e,t){let n=xt(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 xt(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 Ie(e,t){return e.split(`
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(`
115
109
  `).map(n=>`${t}${n}`).join(`
116
- `)}function Et(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 Ot(e,t){s(`${e} operation: ${t.operationId}`),s(`${e} receipt: ${t.receiptId}`)}function Ct(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 jt(e){return v(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 Rt(e,t){let n=await x(t,"/v1/blueprints",{},"blueprint.list"),r=jt(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?
117
- `);for(let[m,h]of r.entries()){let I=h.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${m+1}. ${h.name} (${h.id})${I?`: ${I}`:""}
118
- `)}let a=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 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)?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 be(e,t){_t(e);let n={};try{await Lt(e,t,n)}catch(r){throw typeof n.apiKey!="string"?r:Ct(r,n.apiKey)}}async function Lt(e,t,n){let r=await $(e,t),o=await A(r,r.token),a=await Rt(e,r),i=e["--name"]??a.name;e["--json"]||s(`Authenticated: ${o.email}`);let c=await _e(r,"/v1/products/blueprint-compose",P({blueprintId:a.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!==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=Et(c.response);await W(t,{...r,selectedProduct:d.productId}),e["--json"]||(s(`Product: ${d.productId}`),s(`Blueprint: ${d.blueprintId}`),Ot("Compose",p));let m=[`hyperscale compose plan product.hsx --product ${d.productId}`],h="Composition completed. Run SDK journeys against your Product.",I={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(I);return}s(h),s(`Shown once Product API key: ${l}`),s("Next:");for(let k of m)s(` ${k}`);s(" 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 $(e,t),a;try{a=await x(o,"/v1/products",{tenantId:o.tenantId},"product.list",o.token,[o.token])}catch(m){if(!(m instanceof T)||m.status!==403)throw m}let i=r.trim().toLocaleLowerCase("en-US"),c=(a?v(a,"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 g(o,"/v1/products/blueprint-compose",P({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}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 fe(e){return new URLSearchParams({tenantId:e}).toString()}async function Dt(e,t){let n=await $(e,t),r=await x(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),o=v(r,"product.list");if(e["--json"]){f(r);return}if(o.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 o){let i=a.productId??a.id??"unknown",c=a.displayName??a.name??"unnamed";s(`${i} ${c}${a.status?` ${a.status}`:""}`)}}async function Ht(e,t,n){let r=await $(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 a=await g(r,`/v1/products/${encodeURIComponent(o)}?${fe(r.tenantId)}`,{},r.token,[r.token]);if(e["--json"]){f(a);return}Jt(a,o)}function Jt(e,t){let n=e?.displayName??e?.name??"unnamed",r=e?.status??"unknown",o=e?.blueprint,a=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"):[]];s(`Name: ${n}`),s(`Product: ${e?.productId??t}`),s(`Status: ${r}`),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 h=e?.surfaces?.[p];h?.url&&s(`${m}: ${h.url}`)}s("Next:"),s(` 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 $(e,t),o=await g(r,`/v1/products/${encodeURIComponent(n)}?${fe(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 a={productId:n,selected:!0};e["--json"]?f(a):s(`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 he(e,t,n,r){let o=await Yt(n),a=await $(e,t),i=r?D(a,e):void 0,c=Ft(await g(a,"/v1/composer/check",P({tenantId:a.tenantId,document:o.source,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}),a.token,[a.token]));if(!c.ok)throw new J(["composer.check refused the program.",...Kt(c.issues)].join(`
119
- `),{file:n,issues:c.issues});return{check:c,context:a,productId:i,program:o,catalogRevisionId:e["--catalog-revision"]}}async function qt(e,t,n){let r=await he(e,t,n,!1);if(e["--json"]){f({command:"composer.check",file:n,issues:r.check.issues,ok:!0});return}s(`Check passed: ${n}`)}async function Le(e,t){let n=await g(e.context,"/v1/composer/plan",P({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(`
120
- `),{actions:r,file:t,productId:e.productId});return n}async function Mt(e,t,n){let r=await he(e,t,n,!0),o=await Le(r,n);if(e["--json"]){f({command:"composer.plan",file:n,plan:o,productId:r.productId});return}s(o.summary);for(let a of o.actions)s(`${a.kind} ${a.target} ${a.detail}`);s(`Monthly: SAR ${o.pricing.monthlySar}`),s(`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 he(e,t,n,!0);await Le(r,n);let o=await g(r.context,"/v1/products/recompose",P({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}s(`Product: ${o.productId??r.productId}`),s(`Build: ${o.productBuildId}`),o.buildDigest&&s(`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),a=_(e,t,r??{});if(r&&(a.baseUrl!==r.baseUrl||a.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 Ae(o);let c={...a,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:a}=await L(e,r,{},n);if(o.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.`):U(o,a,[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"){s("This Product uses a legacy surface. It has no frozen public actions yet."),s(`Build: ${o.productBuildId}`);return}if(o.publicActions.length===0)s("No public actions");else{s("Operation ID Input Kind");for(let a of o.publicActions){let i=a.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";s(`${a.instrument}.${a.name} ${en(a.inputSchema)} ${i}`)}}if(o.setupOperations.length>0){s("Setup operations (run with hyperscale call)");for(let a of o.setupOperations)s(a.operationName)}if(o.readOperationIds.length>0){s("Reads (run with hyperscale call)");for(let a of o.readOperationIds)s(Zt(a))}s(`Digest: ${o.tenantOperationSetDigest}`),s(`Setup digest: ${o.tenantSetupOperationSetDigest}`),s(`Read digest: ${o.tenantReadOperationSetDigest}`),s(`Build: ${o.productBuildId}`),s(`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),a=e.setupOperations.find(c=>c&&(c.operationId===t||c.operationId===o||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"]){f(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(!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}s(`Operation ID: ${r.instrument}.${r.name}`),s(`Instrument: ${r.instrument}`),s(`Input schema: ${JSON.stringify(r.inputSchema,null,2)}`),s(`Output schema: ${JSON.stringify(r.outputSchema,null,2)}`),s(`Actor policy: ${JSON.stringify(r.actorPolicy,null,2)}`),s(`Port policy: ${JSON.stringify(r.portPolicy,null,2)}`),s(`Idempotency policy: ${JSON.stringify(r.idempotencyPolicy,null,2)}`),s(`Receipt policy: ${JSON.stringify(r.receiptPolicy,null,2)}`),s(`Receipt evidence: ${JSON.stringify(r.receiptEvidence,null,2)}`),s(`Digest: ${e.tenantOperationSetDigest}`),s(`Build: ${e.productBuildId}`),s(`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,a])=>`${o}${n.has(o)?"":"?"}: ${De(a)}`);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 a=await Je(e),i=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:c,text:d}=await L(r,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(a),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}s(`Operation: ${l??"not returned"}`),s(`Receipt: ${p??"not returned"}`),s(`Idempotency key: ${i}`);let m=Be(d);m&&s(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,a)=>o.distance-a.distance||o.candidate.localeCompare(a.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),a;try{a=JSON.parse(t)}catch{return new u(`HTTP ${e.status}${o?` \xB7 ${o}`:""}`)}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=S(`HTTP ${e.status} \xB7 ${c}${a.error.message}`,n),l=rn(a.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.":[a.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(`
121
- `),{code:i,...a.error.details?{details:F(a.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 a=(Array.isArray(r.path)?r.path.join("."):"input")||"input";return typeof r.message=="string"?[`${a}: ${S(r.message,t)}`]:[]});let n=[];return se(e,"",n,t),n}function se(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,a)=>se(o,`${t}[${a}]`,n,r));return}if(e&&typeof e=="object"){for(let[o,a]of Object.entries(e))se(a,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 an(e,t){let n=await $(e,t),r=D(n,e),o=await g(n,"/v1/sandbox-api-keys",P({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:r}),n.token,[n.token]);if(e["--json"]){f(o);return}s(`Key: ${o.apiKeyId??"unknown"}`),s(`Product: ${o.productId??r}`),s(`Status: ${o.status??"unknown"}`),o.secret?(s(`Secret: ${o.secret}`),s("Store it now. Hyperscale will not return it again."),s("Next:"),s(` export HYPERSCALE_API_KEY=${sn(o.secret)}`),s(` hyperscale product actions --product ${r}`)):s("The key already existed, so the one-time secret is unavailable.")}function sn(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function cn(e,t){let n=await $(e,t),r=D(n,e),o=await x(n,"/v1/api-keys",{tenantId:n.tenantId},"api_key.list",n.token,[n.token]),a=v(o,"api_key.list").filter(c=>c.productId===r),i={...o,items:a};if(e["--json"]){f(i);return}for(let c of a)s(`${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 $(e,t),o=D(r,e),a=await g(r,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,P({tenantId:r.tenantId,productId:o}),r.token,[r.token]);e["--json"]?f(a):s(`Key ${a.apiKeyId??n}: ${a.status??"revoked"}`)}async function dn(e,t){let n=await $(e,t),r=n.identity??await A(n,n.token),o=me(n,r);if(e["--json"]){f(o);return}s(`User: ${r.email}`),s(`Tenant: ${r.tenantId}`),s(`Role: ${r.role}`),s(`Token: ${r.name}`),s(`Expires: ${r.expiresAt}`)}async function ln(e,t,n){let r=await je(e),o=n?n.toLowerCase():null,a=o?r.operations.filter(c=>c.name.toLowerCase().includes(o)||c.path.toLowerCase().includes(o)):r.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 pn(e,t){let n=await $(e,t),r=await g(n,`/v1/team/members?${fe(n.tenantId)}`,{},n.token,[n.token]);if(!r||typeof r!="object"||!Array.isArray(r.members)||!Array.isArray(r.invitations))throw new u("team.member.list returned invalid data");if(e["--json"]){f(r);return}for(let o of r.members)s(`${o.email??"unknown"} ${o.role??"unknown"} ${o.status??"unknown"}`);for(let o of r.invitations)s(`${o.email??"unknown"} ${o.role??"unknown"} pending invitation`)}async function mn(e,t){let n=e["--email"],r=e["--role"];if(!n)throw new u("team invite needs --email <email>");if(!r)throw new u("team invite needs --role <role>");let o=await $(e,t),a=await g(o,"/v1/team/members/invite",P({email:n,role:r,tenantId:o.tenantId}),o.token,[o.token]);if(e["--json"]){f(a);return}s(`Invitation: ${a.invitationId??"unknown"}`),s(`Email: ${a.email??n}`),s(`Role: ${a.role??r}`),s(`Expires: ${a.expiresAt??"unknown"}`),a.inviteToken&&(s(`Invite token: ${a.inviteToken}`),s("Share it now. Hyperscale will not return it again."))}async function fn(e,t){let n=await $(e,t),r=await x(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),o=v(r,"activity.list");if(e["--json"]){f(r);return}s("Time Activity Target Status");for(let a of o){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 hn(e,t){let n={...t},r=[],o=e.path.replace(/\{([^}]+)\}/g,(a,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 yn(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 a=1;a<=t.length;a+=1)o[a]=Math.min(o[a-1]+1,n[a]+1,n[a-1]+(e[r-1]===t[a-1]?0:1));n.splice(0,n.length,...o)}return n[t.length]}function wn(e,t){let n=e.find(a=>a.name===t);if(n)return n;let r=e.filter(a=>a.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(a=>a.name).join(", ")}.`);let o=e.map(a=>({candidate:a,distance:Math.min(ie(t,a.name),ie(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: ${o.join(", ")}.`)}async function gn(e,t,n){if(!n)throw new u("call needs an operation name");let r=await je(e),o=wn(r.operations,n),a=await Je(t),{path:i,remaining:c}=hn(o,a),d={method:o.method},l=i;o.method==="GET"?l+=yn(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),I=p.headers.get("hyperscale-operation-id")??null,k=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:I,receiptId:k,traceId:w});return}s(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 s(e){process.stdout.write(`${e}
122
- `)}function f(e){s(JSON.stringify(e,null,2))}function kn(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(!n.startsWith("--"))return n;ve.has(n)&&(t+=1)}}function $n(e,t){let n=kn(t)==="call",r=t.includes("--json");if(n&&r&&e instanceof T){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}
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}
123
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"?`
124
118
  Fix: ${e.fix}`:"",l=o?`
125
119
  Shown once Product API key: ${o}`:"";process.stderr.write(`${c}${d}${l}
126
- `);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."},...o?{shown_once:o}:{}})}
127
- `)}async function In(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function bn(e,t){let{flags:n,positional:r}=it(e);if(n["--version"])return s(await In()),0;if(n["--help"]&&r.length>0)return process.stdout.write(st(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 be(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(at),0;let[o,...a]=r;if(o==="start")return await be(n,t),0;if(o==="auth"){if(a[0]==="login")await It(n,t);else if(a[0]==="status")await bt(n,t);else if(a[0]==="logout")await Pt(n,t);else throw new u('Auth subcommands are "login", "status", and "logout"');return 0}if(o==="blueprint"){let i=_(n,t);if(a[0]==="list")await At(i,n);else if(a[0]==="show")await vt(i,n,a[1]);else throw new u('Blueprint subcommands are "list" and "show"');return 0}if(o==="product"){if(a[0]==="create")await Ut(n,t);else if(a[0]==="list")await Dt(n,t);else if(a[0]==="show")await Ht(n,t,a[1]);else if(a[0]==="select")await Bt(n,t,a[1]);else if(a[0]==="actions")await Wt(n,t,a[1]);else if(a[0]==="run")await tn(n,t,a[1]);else throw new u('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(o==="compose"){if(a[0]==="check")await qt(n,t,a[1]);else if(a[0]==="plan")await Mt(n,t,a[1]);else if(a[0]==="apply")await zt(n,t,a[1]);else throw new u('Compose subcommands are "check", "plan", and "apply"');return 0}if(o==="key"){if(a[0]==="create")await an(n,t);else if(a[0]==="list")await cn(n,t);else if(a[0]==="revoke")await un(n,t,a[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==="team"){if(a[0]==="list")await pn(n,t);else if(a[0]==="invite")await mn(n,t);else throw new u('Team subcommands are "list" and "invite"');return 0}if(o==="activity"){if(a[0]!=="list")throw new u('The only activity subcommand is "list"');return await fn(n,t),0}if(o==="ops"){if(a[0]!=="list")throw new u('The only ops subcommand is "list"');let i=n["--product"]?await Y(n,t):ge(n,t);return await ln(i,n,a[1]),0}if(o==="call"){let i=n["--product"]?await Y(n,t):ge(n,t);return await gn(i,n,a[0]),0}throw new u(`Unknown command: ${o}`)}bn(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{$n(e,process.argv.slice(2)),process.exitCode=e instanceof u&&Number.isInteger(e.exitCode)?e.exitCode:1});
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});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hyperscale0/cli",
3
- "version": "1.0.0-beta.10",
4
- "description": "The Hyperscale founder command line: compose Products, manage keys, and call Product operations.",
3
+ "version": "1.0.0-beta.12",
4
+ "description": "Hyperscale CLI: compose Products, manage keys, and call Product operations.",
5
5
  "license": "LicenseRef-Hyperscale-Proprietary",
6
6
  "author": "Hyperscale LLC",
7
7
  "contributors": [
@@ -20,5 +20,5 @@
20
20
  "publishConfig": {
21
21
  "access": "public"
22
22
  },
23
- "gitHead": "b63bc088b12ddcf09cddc6e6467d749817c14827"
23
+ "gitHead": "8b8e65601bb845e906f480c9950226c9171b6487"
24
24
  }