@hyperscale0/cli 1.0.0-beta.20 → 1.0.0-beta.22

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 +34 -0
  2. package/hyperscale.js +72 -46
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -25,6 +25,7 @@ bunx @hyperscale0/cli whoami
25
25
  bunx @hyperscale0/cli start --blueprint vehicle-escrow-marketplace --json
26
26
  bunx @hyperscale0/cli blueprint list
27
27
  bunx @hyperscale0/cli product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"
28
+ bunx @hyperscale0/cli product create --source product.hsx --name "Custom Escrow"
28
29
  bunx @hyperscale0/cli product select <Product id>
29
30
  bunx @hyperscale0/cli key create --name "Founder laptop"
30
31
  bunx @hyperscale0/cli compose check product.hsx
@@ -46,6 +47,8 @@ bunx @hyperscale0/cli call account.list --input '{"limit":5}'
46
47
  operation id such as `escrow_order.placeBuyerHold` to return its full input
47
48
  schema, output schema, policies, build id, surface version, and operation-set
48
49
  digest.
50
+ `product create` creates and selects a new Product with `--name <name>`
51
+ from either `--blueprint <slug>` or `--source <file.hsx>`.
49
52
  `start` asks which catalog company to build in a terminal. Scripts and agents
50
53
  pass `--blueprint <slug>` to skip the prompt. `product select <Product id>`
51
54
  stores the default Product used by compose, key, and Product commands when
@@ -83,6 +86,37 @@ https://hyperscale0.ai/signin.
83
86
 
84
87
  Run `bunx @hyperscale0/cli --help` for the full option list.
85
88
 
89
+ ## Command shapes and automation
90
+
91
+ When passing `--json`, commands emit structured JSON to stdout on success.
92
+ Commands that create or switch active resources (`product create`, `product select`,
93
+ `product show`, `blueprint show`, `key create`, and `start`) include a
94
+ `nextCommands` string array in their success envelope with recommended follow-up
95
+ commands.
96
+
97
+ Failures under `--json` emit a single JSON object strictly to stderr, leaving
98
+ stdout empty. The stderr failure envelope contains:
99
+ - `status`: the numeric HTTP status when the failure came from the API; absent otherwise
100
+ - `error.code`: stable error code string
101
+ - `error.message`: sanitized diagnostic message (capped at 1024 characters)
102
+ - `error.fix`: actionable corrective step
103
+ - `error.details`: structured error details or contextual payload
104
+ - Correlation fields: `requestId`, `operationId`, `receiptId`, and `traceId` when reported by the upstream API
105
+
106
+ ## Pricing and compose flags
107
+
108
+ `compose apply` takes one confirmation form:
109
+ - `--confirm`: confirm the mutation for a person
110
+ - `--yes`: confirm the mutation without a prompt for an agent; accepts the candidate price current at apply time
111
+ - `--pricing-identity <id>`: candidate pricing identity from `compose plan`; required with `--confirm` only when scheduled pricing exists
112
+ - `--plan-file <path>`: saved JSON plan file from `compose plan --json`; used with `--confirm` to read the pricing identity when scheduled pricing exists
113
+
114
+ ## Exit codes
115
+
116
+ - `0`: Success
117
+ - `1`: General failure (validation error, transport failure, server error, or unknown option)
118
+ - `2`: Compiler or composer refusal (such as contract incompatibility or invalid composition)
119
+
86
120
  ## Reference
87
121
 
88
122
  - [Portal desk](https://hyperscale0.ai/desk)
package/hyperscale.js CHANGED
@@ -1,14 +1,35 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Te}from"node:child_process";import{createHash as We}from"node:crypto";import{createServer as ze}from"node:http";import{createInterface as Ge}from"node:readline/promises";import{chmod as ee,mkdir as Xe,readdir as Qe,readFile as D,rename as Ze,unlink as et,writeFile as tt}from"node:fs/promises";import{homedir as nt}from"node:os";import{basename as ot,dirname as re,join as M}from"node:path";var pe="https://hyperscale0.ai",le="sandbox",me="hyperscale-cli-session",rt="/v1/personal-access-tokens/current",ie=process.platform==="darwin"?"/usr/bin/security":null,it="config.json",ae="https://hyperscale0.ai/desk/security/tokens",_="https://hyperscale0.ai/request-access",j=`Mint a founder PAT in Hyperscale Portal at ${ae}. Open Security, then Personal access tokens.`,at=`Not logged in. Run "hyperscale auth login" to open Hyperscale Portal sign-in. In a headless environment, ${j} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${_}.`,st=`Run "hyperscale auth login". For headless use, ${j} Unapproved founders can request access at ${_}.`,se=3e4,ct=2e3,ut=120*1e3,dt=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,pt=`hyperscale <command> [options]
2
+ import{spawn as Be}from"node:child_process";import{createHash as mt}from"node:crypto";import{createServer as ft}from"node:http";import{createInterface as yt}from"node:readline/promises";import{chmod as ue,mkdir as wt,readdir as gt,readFile as B,rename as It,unlink as $t,writeFile as kt}from"node:fs/promises";import{homedir as Pt}from"node:os";import{basename as bt,dirname as me,join as te}from"node:path";var Pe="https://hyperscale0.ai",be="sandbox",Ae="hyperscale-cli-session",At="/v1/personal-access-tokens/current",fe=process.platform==="darwin"?"/usr/bin/security":null,St="config.json",ye="https://hyperscale0.ai/desk/security/tokens",H="https://hyperscale0.ai/request-access",K=`Mint a founder PAT in Hyperscale Portal at ${ye}. Open Security, then Personal access tokens.`,xt=`Not logged in. Run "hyperscale auth login" to open Hyperscale Portal sign-in. In a headless environment, ${K} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${H}.`,vt=`Run "hyperscale auth login". For headless use, ${K} Unapproved founders can request access at ${H}.`,we=3e4,Et=2e3,Tt=120*1e3,Ct=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,Ne=`hyperscale <command> [options]
3
+
4
+ The founder command line.
5
+
6
+ Concepts:
7
+ Blueprint -> Product:
8
+ A Blueprint is a public catalog template. Composing from a Blueprint
9
+ or raw HSX source creates a tenant Product.
10
+ Founder PAT vs Product API key:
11
+ A founder Personal Access Token (PAT) manages the company and tenant:
12
+ Blueprints, Product creation, composition (plan/apply), and keys.
13
+ A Product API key authenticates against one Product's operational
14
+ surface and executes runtime actions. The two credentials are not
15
+ interchangeable.
16
+ Custom product actions vs operation calls:
17
+ Product actions ("product actions" and "product run") execute the Product's
18
+ frozen, published public contract actions. Platform operations ("ops list"
19
+ and "call") invoke catalog operations from the Product machine document.
20
+ Credential-free blueprint discovery:
21
+ "blueprint list" and "blueprint show" are public discovery commands that
22
+ require no authentication or credentials.
3
23
 
4
24
  Commands:
5
- start Create a Product and run its first published journey step
25
+ start Create a Product and run its first published step
26
+ help [command] Print help for hyperscale or a specific command
6
27
  auth login Sign in through the portal or save a founder PAT
7
28
  auth status Verify and show the active founder PAT
8
29
  auth logout [--revoke] Forget the local founder PAT, optionally revoke it
9
30
  blueprint list List public Blueprints without authentication
10
31
  blueprint show <id> Show one public Blueprint
11
- product create Create a Product from a Blueprint
32
+ product create Create a Product from a Blueprint or HSX source
12
33
  product list List Products in the signed-in company
13
34
  product show [id] Show a Product (default: selected Product)
14
35
  product select <id> Select the default Product for later commands
@@ -23,7 +44,7 @@ Commands:
23
44
  key revoke <id> Revoke a Product API key
24
45
  activity list List company activity
25
46
  whoami Show the user and company this founder PAT resolves to
26
- ops list [filter] List the product's callable operations
47
+ ops list [filter] List the product's callable operations (supports substring filter)
27
48
  call <operation> Call one operation by name or operation id
28
49
 
29
50
  Options:
@@ -31,9 +52,10 @@ Options:
31
52
  --revoke Revoke the active founder PAT during auth logout
32
53
  --no-browser Skip browser login and print the founder PAT path
33
54
  --api-key <key> Product API key (default: $HYPERSCALE_API_KEY)
34
- --base-url <url> API origin (default: $HYPERSCALE_BASE_URL, else ${pe})
35
- --environment <name> sandbox or live (default: $HYPERSCALE_ENVIRONMENT, else ${le})
55
+ --base-url <url> API origin (default: $HYPERSCALE_BASE_URL, else ${Pe})
56
+ --environment <name> sandbox or live (default: $HYPERSCALE_ENVIRONMENT, else ${be})
36
57
  --blueprint <slug> Blueprint for non-interactive start or product create
58
+ --source <file> HSX source file for product create
37
59
  --name <name> Product or key name
38
60
  --product <id> Product id for key commands and Product-key actions
39
61
  --catalog-revision <id> Tenant catalog revision for HSX composition
@@ -42,9 +64,11 @@ Options:
42
64
  --idempotency-key <key> Idempotency key for a mutation or public action (default: generated)
43
65
  --confirm Confirm compose apply for a person
44
66
  --yes Confirm compose apply without a prompt for an agent
67
+ --pricing-identity <id> Candidate pricing identity from compose plan (required with --confirm when scheduled pricing exists)
68
+ --plan-file <path> Saved JSON plan file from compose plan --json (used with --confirm when scheduled pricing exists)
45
69
  --json Print machine-readable JSON
46
- --version Print the CLI version
47
- --help Print this help
70
+ --version, -v Print the CLI version
71
+ --help, -h Print this help (use "hyperscale help <command>" for command help)
48
72
 
49
73
  Founder PAT commands: auth, whoami, product create/list/show, compose check/plan/apply,
50
74
  key, and activity. Product API key commands: product actions/run, ops list,
@@ -53,8 +77,8 @@ catalog revision. The two credential types are not interchangeable. Browser
53
77
  login returns through a single-use localhost callback.
54
78
 
55
79
  compose check, plan, and apply exit 2 when the compiler or composer refuses the
56
- program. Command, credential, request, and server failures exit 1. compose apply
57
- requires --confirm, or --yes for an agent.
80
+ program. Command, credential, request, and server failures exit 1.
81
+ compose apply requires --confirm (with --pricing-identity or --plan-file only when scheduled pricing exists), or --yes for an agent to accept the current candidate price.
58
82
  Compose check and plan JSON retain operationId and receiptId when the server
59
83
  returns them. Plan JSON includes the prerequisite check result and its identifiers.
60
84
 
@@ -63,8 +87,8 @@ key. The explicit flag wins over its environment variable. Founder logins use
63
87
  macOS Keychain when available. Set HYPERSCALE_CREDENTIAL_STORE=file to keep the
64
88
  founder PAT in the owner-only CLI profile instead and skip Keychain access.
65
89
 
66
- ${j}
67
- Request access at ${_}.
90
+ ${K}
91
+ Request access at ${H}.
68
92
 
69
93
  Examples:
70
94
  hyperscale start
@@ -74,6 +98,7 @@ Examples:
74
98
  hyperscale auth login --token hyperscale_pat_...
75
99
  hyperscale blueprint list
76
100
  hyperscale product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"
101
+ hyperscale product create --source company.hsx --name "Company"
77
102
  hyperscale key create --name "Founder laptop"
78
103
  hyperscale product actions
79
104
  hyperscale product actions escrow_order.placeBuyerHold --json
@@ -87,40 +112,41 @@ Examples:
87
112
  hyperscale call account.list --input-file input.json
88
113
  printf '{"limit":5}' | hyperscale call account.list
89
114
  hyperscale call account.retrieve --input '{"accountId":"acct_sandbox_..."}'
90
- `,$e={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 (--pricing-identity <id> | --plan-file <path>) | --yes) [--product <id>] [--catalog-revision <id>] [--json]",summary:"Recompose a Product from checked HSX.",options:["--confirm Confirm the mutation for a person, who must also name the candidate price they reviewed.","--yes Confirm the mutation without a prompt for an agent; accepts the candidate price current at apply time.","--pricing-identity <id> Candidate pricing identity from compose plan.","--plan-file <path> Saved JSON plan file from compose plan --json.","--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 --pricing-identity <id>"},"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 lt(e){let n=Object.keys($e).sort((r,i)=>i.split(" ").length-r.split(" ").length).find(r=>r.split(" ").every((s,c)=>e[c]===s));if(!n)throw new u(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`);let o=$e[n];return[`Usage: hyperscale ${o.usage}`,"",o.summary,"","Options:",...o.options.map(r=>` ${r}`),...o.notes?["","Notes:",...o.notes.map(r=>` ${r}`)]:[],"","Example:",` ${o.example}`,""].join(`
91
- `)}var u=class extends Error{constructor(t,n={}){super(t),typeof n.code=="string"&&(this.code=n.code),n.details!==void 0&&(this.details=n.details),Number.isInteger(n.exitCode)&&(this.exitCode=n.exitCode),typeof n.fix=="string"&&(this.fix=n.fix)}},O=class extends u{constructor(t,{requestId:n,status:o,code:r,details:i,operationId:s,receiptId:c,traceId:d,structuredError:p}={}){super(t,{code:r,details:i}),this.requestId=n,this.status=o,this.operationId=s??null,this.receiptId=c??null,this.traceId=d??null,this.structuredError=p}};function te(){return new u(at,{fix:st})}function Ee(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 K=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","--idempotency-key","--input","--input-file","--name","--plan-file","--pricing-identity","--product","--token"]);function mt(e){let t=[],n={};for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--")){t.push(r);continue}if(ve.has(r)){let i=e[o+1];if(i===void 0)throw new u(`${r} needs a value`);n[r]=i,o+=1;continue}if(r==="--help"||r==="--version"||r==="--json"||r==="--confirm"||r==="--yes"||r==="--no-browser"||r==="--passkey"||r==="--revoke"){n[r]=!0;continue}throw new u(`Unknown option: ${r}`)}return{flags:n,positional:t}}function ke(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Ee();let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??le;if(o!=="sandbox"&&o!=="live")throw new u(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??pe).replace(/\/+$/,"");return{apiKey:n,baseUrl:r,environment:o}}function L(e,t,n={}){let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??le;if(o!=="sandbox"&&o!=="live")throw new u(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??pe).replace(/\/+$/,""),i;try{i=new URL(r)}catch{i=null}let s=i?.origin??null;if(!s||s!==r)throw new u(`Invalid API origin: ${r}. Use an origin such as https://hyperscale0.ai.`);let c=["localhost","127.0.0.1","[::1]","::1"].includes(i.hostname);if(i.protocol!=="https:"&&!(i.protocol==="http:"&&c))throw new u(`Refusing cleartext API origin ${r}. Use HTTPS unless the API runs on loopback.`);return{baseUrl:r,environment:o}}function Oe(e){return e.HYPERSCALE_CONFIG_DIR??M(nt(),".config","hyperscale")}function Ce(e){return M(Oe(e),it)}function b(e,t){return M(Oe(t),`session-${H(e)}.json`)}function V(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new u(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function fe(e,t){let n=b(e,t),o=`${ot(n)}.`,r;try{r=await Qe(re(n),{withFileTypes:!0})}catch(i){if(i&&i.code==="ENOENT")return;throw i}for(let i of r){if(!i.isFile()||!i.name.startsWith(o))continue;let s=i.name.slice(o.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(s)&&await U(M(re(n),i.name))}}async function ft(e){try{return JSON.parse(await D(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=ht(e);await Xe(n,{mode:448,recursive:!0}),await ee(n,448);let o=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await tt(o,t,{flag:"wx",mode:384}),await ee(o,384);try{await Ze(o,e),await ee(e,384)}catch(r){throw await U(o),r}}function ht(e){return re(e)}async function U(e){try{await et(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function yt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new u(`${t} does not contain a CLI profile`);let{baseUrl:n,email:o,environment:r,selectedProduct:i}=e;if(typeof n!="string"||typeof o!="string"||r!=="sandbox"&&r!=="live"||!(i===null||typeof i=="string"))throw new u(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:o,environment:r,selectedProduct:i}}async function W(e){let t=Ce(e),n=await ft(t);return n===null?null:yt(n,t)}async function z(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await N(Ce(e),`${JSON.stringify(n,null,2)}
92
- `)}function H(e){return We("sha256").update(`${e.baseUrl}\0${e.environment}\0${e.email}`).digest("hex")}async function G(e,t){return ie===null?{error:null,status:null,stdout:"",unavailable:!0}:await new Promise(n=>{let o={...process.env};delete o.HYPERSCALE_API_KEY,delete o.HYPERSCALE_TOKEN;let r=Te(ie,e,{env:o,stdio:["pipe","pipe","pipe"]}),i=[],s=!1,c=p=>{s||(s=!0,clearTimeout(d),n(p))},d=setTimeout(()=>{r.kill("SIGKILL"),c({error:null,status:null,stdout:"",unavailable:!0})},ct);r.stdout.on("data",p=>i.push(p)),r.stderr.on("data",()=>{}),r.stdin.on("error",()=>{}),r.once("error",p=>c({error:p,status:null,stdout:"",unavailable:!0})),r.once("close",p=>c({error:null,status:p,stdout:Buffer.concat(i).toString("utf8"),unavailable:!1})),t===void 0?r.stdin.end():r.stdin.end(`${t}
93
- `)})}async function he(){return(await G(["show-keychain-info"])).status===0}function Re(e){try{let t=typeof e=="string"?JSON.parse(e):e;if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.token=="string"&&typeof t.tenantId=="string"&&(t.personalAccessTokenId===void 0||typeof t.personalAccessTokenId=="string")&&(t.tokenName===void 0||typeof t.tokenName=="string"))return{token:t.token,tenantId:t.tenantId,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.tokenName?{tokenName:t.tokenName}:{}}}catch{}return null}async function wt(e,t,n){await fe(e,n);let o=H(e);if(V(n)==="auto"&&await he()){let r=JSON.stringify(t),i=["add-generic-password","-a",o,"-s",me,"-U","-X",Buffer.from(r,"utf8").toString("hex")].join(" ");if((await G(["-i"],i)).status===0)return await U(b(e,n)),"keychain"}return await N(b(e,n),`${JSON.stringify({account:o,activeStore:"file",credential:t})}
94
- `),"file"}async function gt(e,t){let n=H(e);try{let o=JSON.parse(await D(b(e,t),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||o.account!==n)return{state:"invalid"};if(o.revoked===!0)return{state:"revoked"};let r=Re(o.credential);return r?{activeStore:o.activeStore==="file"?"file":null,credential:r,state:"valid"}:{state:"invalid"}}catch(o){return o&&o.code==="ENOENT"?{state:"missing"}:{state:"invalid"}}}async function Ne(e,t){await fe(e,t);let n=V(t),o=await gt(e,t);if(o.state==="revoked")return null;if(o.state==="valid"&&(o.activeStore==="file"||n==="file"))return o.credential;if(n==="file")return null;let r=null;if(await he()){let i=await G(["find-generic-password","-a",H(e),"-s",me,"-w"]);i.status===0&&(r=Re(i.stdout.trim()))}return r||(o.state==="valid"?o.credential:null)}async function _e(e,t){await fe(e,t);let n=H(e);if(V(t)==="file")return await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
95
- `),{keychainDeleted:!0};if(ie===null)return await U(b(e,t)),{keychainDeleted:!0};if(!await he())return await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
96
- `),{keychainDeleted:!1};let o=await G(["delete-generic-password","-a",n,"-s",me]);return o.status!==0&&o.status!==44?(await N(b(e,t),`${JSON.stringify({account:n,revoked:!0})}
97
- `),{keychainDeleted:!1}):(await U(b(e,t)),{keychainDeleted:!0})}function je(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function k(e,t,n=!1){let o=await W(t),r=je(e,t);if(r!==void 0){if(!r)throw te();let c=L(e,t,o??{}),d=await E(c,r),p=o?.baseUrl===c.baseUrl&&o.environment===c.environment&&o.email===d.email;return{...c,email:d.email,identity:d,personalAccessTokenId:d.personalAccessTokenId,selectedProduct:p?o.selectedProduct:null,tenantId:d.tenantId,token:r,tokenName:d.name}}if(!o){if(n)return null;throw te()}let i=L(e,t,o);if(i.baseUrl!==o.baseUrl||i.environment!==o.environment)throw new u(`The active founder login belongs to ${o.baseUrl} (${o.environment}). Log in again to change it.`);let s=await Ne(o,t);if(!s){if(n)return null;throw te()}return{...o,...s}}function B(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
98
- \r`.includes(t)?t:"")}function q(e){try{return new URL(e).origin}catch{return null}}function y(e,t){let n=e;for(let o of t)typeof o=="string"&&o.length>0&&(n=n.replaceAll(o,"[redacted]"));return n}function Le(e,t=[]){if(!e?.ok||!e?.headers)return;let n=e.headers.get("x-request-id"),o=e.headers.get("hyperscale-operation-id"),r=e.headers.get("hyperscale-receipt-id"),i=n?y(n,t):null,s=o?y(o,t):null,c=r?y(r,t):null;i&&process.stderr.write(`Request id: ${i}
115
+ `,de={start:{usage:"start [--blueprint <slug>] [--name <name>] [--json]",summary:"Choose a catalog company, create its Product, and run its first published runnable 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 step 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> | --source <file>) --name <name> [--catalog-revision <id>] [--json]",summary:"Create and select a Product. The command refuses a duplicate name.",options:["--blueprint <id> Blueprint id to compose from.","--source <file> HSX source file to compose from.","--name <name> Required Product name.","--catalog-revision <id> Tenant catalog revision for HSX composition.","--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 [--pricing-identity <id> | --plan-file <path>] | --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; accepts the candidate price current at apply time.","--pricing-identity <id> Candidate pricing identity from compose plan. Required with --confirm only when scheduled pricing exists.","--plan-file <path> Saved JSON plan file from compose plan --json. Used with --confirm to extract pricing identity when scheduled pricing exists.","--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."],notes:["Apply --confirm requires a reviewed pricing identity or saved plan only when plan.pricing.scheduled exists; --yes selects the current candidate."],example:"hyperscale compose apply product.hsx --yes --pricing-identity <id>"},"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:["filter Optional case-insensitive substring filter matching operation names and paths.","--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."],notes:["The optional filter argument matches operation names and paths by case-insensitive substring."],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"}'`},help:{usage:"help [command]",summary:"Print help for hyperscale or a specific command.",options:[],notes:['Pass a command name to read its usage, options, and examples (e.g. "hyperscale help product create").'],example:"hyperscale help product create"}};function je(e){let t=Object.keys(de).sort((i,s)=>s.split(" ").length-i.split(" ").length),n=t.find(i=>i.split(" ").every((c,u)=>e[u]===c));if(n){let i=de[n];return[`Usage: hyperscale ${i.usage}`,"",i.summary,"","Options:",...i.options.map(s=>` ${s}`),...i.notes?["","Notes:",...i.notes.map(s=>` ${s}`)]:[],"","Example:",` ${i.example}`,""].join(`
116
+ `)}let o=e.join(" "),r=t.filter(i=>i.startsWith(`${o} `));if(r.length>0)return[`Usage: hyperscale ${o} <subcommand> [options]`,"",`Available ${o} subcommands:`,...r.map(i=>` ${i.slice(o.length+1).padEnd(20)} ${de[i].summary}`),"",`Run "hyperscale help ${o} <subcommand>" for detailed options and examples.`,""].join(`
117
+ `);throw new d(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`,{fix:'Run "hyperscale --help" to list commands.'})}var d=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 d{constructor(t,{requestId:n,status:o,code:r,details:i,operationId:s,receiptId:c,traceId:u,structuredError:p,fix:l}={}){super(t,{code:r,details:i,fix:l}),this.requestId=n,this.status=o,this.operationId=s??null,this.receiptId=c??null,this.traceId=u??null,this.structuredError=p}};function pe(){return new d(xt,{fix:vt})}function qe(e){let t=e??"<id>";return new d(`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.`,{fix:`Run "hyperscale key create --name 'Founder CLI' --product ${t}", then set HYPERSCALE_API_KEY or pass --api-key.`})}var Z=class extends d{constructor(t,n){super(t),this.code="check_failed",this.details=n,this.exitCode=2}},Rt=new Set(["--api-key","--base-url","--blueprint","--catalog-revision","--environment","--idempotency-key","--input","--input-file","--name","--plan-file","--pricing-identity","--product","--source","--token"]);function _t(e){let t=[],n={};for(let o=0;o<e.length;o+=1){let r=e[o];if(r==="-h")r="--help";else if(r==="-v")r="--version";else if(r.startsWith("-")&&!r.startsWith("--"))throw new d(`Unknown option: ${r}`);if(!r.startsWith("--")){t.push(r);continue}if(Rt.has(r)){let i=e[o+1];if(i===void 0)throw new d(`${r} needs a value`);n[r]=i,o+=1;continue}if(r==="--help"||r==="--version"||r==="--json"||r==="--confirm"||r==="--yes"||r==="--no-browser"||r==="--revoke"){n[r]=!0;continue}throw new d(`Unknown option: ${r}`)}return{flags:n,positional:t}}function Le(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw qe();let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??be;if(o!=="sandbox"&&o!=="live")throw new d(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??Pe).replace(/\/+$/,"");return{apiKey:n,baseUrl:r,environment:o}}function D(e,t,n={}){let o=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??be;if(o!=="sandbox"&&o!=="live")throw new d(`Unknown environment: ${o}. Use sandbox or live.`);let r=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??Pe).replace(/\/+$/,"");return ve(r),{baseUrl:r,environment:o}}function Ye(e){return e.HYPERSCALE_CONFIG_DIR??te(Pt(),".config","hyperscale")}function Fe(e){return te(Ye(e),St)}function x(e,t){return te(Ye(t),`session-${q(e)}.json`)}function ne(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new d(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function Se(e,t){let n=x(e,t),o=`${bt(n)}.`,r;try{r=await gt(me(n),{withFileTypes:!0})}catch(i){if(i&&i.code==="ENOENT")return;throw i}for(let i of r){if(!i.isFile()||!i.name.startsWith(o))continue;let s=i.name.slice(o.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(s)&&await J(te(me(n),i.name))}}async function Ot(e){try{return JSON.parse(await B(e,"utf8"))}catch(t){if(t&&t.code==="ENOENT")return null;throw t instanceof SyntaxError?new d(`The CLI profile at ${e} is corrupt: not valid JSON.`,{code:"corrupt_profile",fix:`Back up or remove ${e} before logging in again with "hyperscale auth login" (or "hyperscale auth login --no-browser").`}):t}}async function U(e,t){let n=Nt(e);await wt(n,{mode:448,recursive:!0}),await ue(n,448);let o=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await kt(o,t,{flag:"wx",mode:384}),await ue(o,384);try{await It(o,e),await ue(e,384)}catch(r){throw await J(o),r}}function Nt(e){return me(e)}async function J(e){try{await $t(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function jt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new d(`The CLI profile at ${t} is corrupt: not a profile object.`,{code:"corrupt_profile",fix:`Back up or remove ${t} before logging in again with "hyperscale auth login" (or "hyperscale auth login --no-browser").`});let{baseUrl:n,email:o,environment:r,selectedProduct:i}=e;if(typeof n!="string"||typeof o!="string"||r!=="sandbox"&&r!=="live"||!(i===null||typeof i=="string"))throw new d(`The CLI profile at ${t} is corrupt: invalid profile fields.`,{code:"corrupt_profile",fix:`Back up or remove ${t} before logging in again with "hyperscale auth login" (or "hyperscale auth login --no-browser").`});return{baseUrl:n,email:o,environment:r,selectedProduct:i}}async function oe(e){let t=Fe(e),n=await Ot(t);return n===null?null:jt(n,t)}async function re(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await U(Fe(e),`${JSON.stringify(n,null,2)}
118
+ `)}function q(e){return mt("sha256").update(`${e.baseUrl}\0${e.environment}\0${e.email}`).digest("hex")}async function ie(e,t){return fe===null?{error:null,status:null,stdout:"",unavailable:!0}:await new Promise(n=>{let o={...process.env};delete o.HYPERSCALE_API_KEY,delete o.HYPERSCALE_TOKEN;let r=Be(fe,e,{env:o,stdio:["pipe","pipe","pipe"]}),i=[],s=!1,c=p=>{s||(s=!0,clearTimeout(u),n(p))},u=setTimeout(()=>{r.kill("SIGKILL"),c({error:null,status:null,stdout:"",unavailable:!0})},Et);r.stdout.on("data",p=>i.push(p)),r.stderr.on("data",()=>{}),r.stdin.on("error",()=>{}),r.once("error",p=>c({error:p,status:null,stdout:"",unavailable:!0})),r.once("close",p=>c({error:null,status:p,stdout:Buffer.concat(i).toString("utf8"),unavailable:!1})),t===void 0?r.stdin.end():r.stdin.end(`${t}
119
+ `)})}async function xe(){return(await ie(["show-keychain-info"])).status===0}function Me(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 Se(e,n);let o=q(e);if(ne(n)==="auto"&&await xe()){let r=JSON.stringify(t),i=["add-generic-password","-a",o,"-s",Ae,"-U","-X",Buffer.from(r,"utf8").toString("hex")].join(" ");if((await ie(["-i"],i)).status===0)return await J(x(e,n)),"keychain"}return await U(x(e,n),`${JSON.stringify({account:o,activeStore:"file",credential:t})}
120
+ `),"file"}async function Ut(e,t){let n=q(e);try{let o=JSON.parse(await B(x(e,t),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||o.account!==n)return{state:"invalid"};if(o.revoked===!0)return{state:"revoked"};let r=Me(o.credential);return r?{activeStore:o.activeStore==="file"?"file":null,credential:r,state:"valid"}:{state:"invalid"}}catch(o){return o&&o.code==="ENOENT"?{state:"missing"}:{state:"invalid"}}}async function ze(e,t){await Se(e,t);let n=ne(t),o=await Ut(e,t);if(o.state==="revoked")return null;if(o.state==="valid"&&(o.activeStore==="file"||n==="file"))return o.credential;if(n==="file")return null;let r=null;if(await xe()){let i=await ie(["find-generic-password","-a",q(e),"-s",Ae,"-w"]);i.status===0&&(r=Me(i.stdout.trim()))}return r||(o.state==="valid"?o.credential:null)}async function We(e,t){await Se(e,t);let n=q(e);if(ne(t)==="file")return await U(x(e,t),`${JSON.stringify({account:n,revoked:!0})}
121
+ `),{keychainDeleted:!0};if(fe===null)return await J(x(e,t)),{keychainDeleted:!0};if(!await xe())return await U(x(e,t),`${JSON.stringify({account:n,revoked:!0})}
122
+ `),{keychainDeleted:!1};let o=await ie(["delete-generic-password","-a",n,"-s",Ae]);return o.status!==0&&o.status!==44?(await U(x(e,t),`${JSON.stringify({account:n,revoked:!0})}
123
+ `),{keychainDeleted:!1}):(await J(x(e,t)),{keychainDeleted:!0})}function Ve(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function P(e,t,n=!1){let o=await oe(t),r=Ve(e,t);if(r!==void 0){if(!r)throw pe();let c=D(e,t,o??{}),u=await C(c,r),p=o?.baseUrl===c.baseUrl&&o.environment===c.environment&&o.email===u.email;return{...c,email:u.email,identity:u,personalAccessTokenId:u.personalAccessTokenId,selectedProduct:p?o.selectedProduct:null,tenantId:u.tenantId,token:r,tokenName:u.name}}if(!o){if(n)return null;throw pe()}let i=D(e,t,o);if(i.baseUrl!==o.baseUrl||i.environment!==o.environment)throw new d(`The active founder login belongs to ${o.baseUrl} (${o.environment}). Log in again to change it.`);let s=await ze(o,t);if(!s){if(n)return null;throw pe()}return{...o,...s}}function $(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
124
+ \r`.includes(t)?t:"")}function Ge(e){try{return new URL(e).origin}catch{return null}}function ve(e){let t;try{t=new URL(e)}catch{t=null}if(!t||t.origin!==e)throw new d(`Invalid API origin: ${e}. Use a scheme, host, and optional port with nothing after them, such as https://hyperscale0.ai.`);let n=["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new d(`Refusing cleartext API origin ${e}: no credential was sent. Use https://${t.host} instead, or keep http:// only for a loopback API such as http://127.0.0.1:8787.`);return t.origin}var Ht=/(?<![A-Za-z0-9_-])(?:hyperscale|arc)_[A-Za-z0-9_-]{32,}(?![A-Za-z0-9_-])/g,Kt=/(?<![A-Za-z0-9_-])whsec_[A-Za-z0-9+/=]{32,}(?![A-Za-z0-9+/=])/g;function y(e,t=[]){let n=e;for(let o of t)typeof o=="string"&&o.length>0&&(n=n.replaceAll(o,"[redacted]"));return n.replaceAll(Ht,"[redacted]").replaceAll(Kt,"[redacted]")}function Xe(e,t=[]){if(!e?.ok||!e?.headers)return;let n=e.headers.get("x-request-id"),o=e.headers.get("hyperscale-operation-id"),r=e.headers.get("hyperscale-receipt-id"),i=n?y(n,t):null,s=o?y(o,t):null,c=r?y(r,t):null;i&&process.stderr.write(`Request id: ${i}
99
125
  `),s&&process.stderr.write(`Operation: ${s}
100
126
  `),c&&process.stderr.write(`Receipt: ${c}
101
- `)}async function X(e,t,n={},o){let r=`${e.baseUrl}${t}`,i=q(e.baseUrl);if(q(r)!==i)throw new u(`The requested path ${t} leaves the ${i} origin; refusing the request.`);try{let s=await fetch(r,{...n,headers:{accept:"application/json",...o?{authorization:`Bearer ${o}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(se),redirect:"manual"});if(s.status>=300&&s.status<400)throw new u(`${r} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`);return Le(s,[o].filter(Boolean)),{response:s,text:B(await s.text())}}catch(s){throw s instanceof u?s:new u(`Could not reach ${r}: ${s.message}`)}}async function P(e,t,n={},o,r=[]){let{response:i,text:s}=await X(e,t,n,o);if(!i.ok)throw Z(i,s,r);try{return JSON.parse(s)}catch{throw new u(`HTTP ${i.status} returned invalid JSON`)}}function x(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function It(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function Q(e,t,n={},o){let r=`${e.baseUrl}${t}`,i=q(e.baseUrl);if(q(r)!==i)throw new u(`The product document puts ${t} on another origin than the ${i} you configured; refusing to send the key there.`);try{let s=await fetch(r,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(se),redirect:"manual"});if(s.status>=300&&s.status<400)throw new u(`${r} redirected, so the key was not sent on. Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://.`);return Le(s,[e.apiKey].filter(Boolean)),{response:s,text:B(await s.text())}}catch(s){throw s instanceof u?s:o&&(s?.name==="TimeoutError"||s?.name==="AbortError")?new u(`product run ${o} timed out after ${se/1e3} seconds.`):new u(`Could not reach ${r}: ${s.message}`)}}async function Ue(e){let{response:t,text:n}=await Q(e,"/v1/product.json");if(!t.ok)throw Z(t,n,[e.apiKey]);let o=$t(n);if(!o)throw new u("The product document is not in the expected format; upgrade the CLI.");if(e.productId&&o.productId===void 0)throw new u(`The server's product document names no Product, so "--product ${e.productId}" cannot be checked against the API key. The platform predates Product identity in the descriptor: redeploy it, or drop --product.`);if(e.productId&&o.productId&&e.productId!==o.productId)throw new u(`Selected Product ${e.productId} does not match API key Product ${o.productId}. Run "hyperscale product select ${o.productId}" or pass "--product ${o.productId}". Or set HYPERSCALE_API_KEY to a key for ${e.productId}, or pass that key with --api-key.`);let r=o.operations.map(i=>{if(typeof i.summary!="string"||typeof i.description!="string")throw new u(`The product document carries no prose for ${i.operationId}. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);return{description:i.description,idempotency:i.idempotency,method:i.method,name:i.name,operationId:i.operationId,path:i.path,summary:i.summary}});return{compositionId:o.composition.id,operations:r,packageName:o.sdk?o.sdk.packageName.trim():null,title:o.title.trim()}}function $t(e){let t;try{t=JSON.parse(e)}catch{return null}let n=ce(t),o=r=>typeof r=="string";if(!R(n)||n.schemaVersion!==1||!(n.productId===void 0||o(n.productId))||!o(n.title)||!R(n.composition)||!o(n.composition.id)||!Array.isArray(n.operations))return null;for(let r of n.operations)if(!R(r)||!o(r.method)||!o(r.path)||!o(r.name)||!o(r.operationId)||!o(r.idempotency))return null;return n.sdk!==void 0&&(!R(n.sdk)||!o(n.sdk.packageName))?null:n}function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e){return typeof e=="string"?B(e):Array.isArray(e)?e.map(ce):R(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[B(t),ce(n)])):e}function De(e){let t=e.get("x-trace-id");if(t&&t.trim()!=="")return t.trim();let n=e.get("traceparent");if(n){let o=/^00-([0-9a-fA-F]{32})-[0-9a-fA-F]{16}-[0-9a-fA-F]{2}$/.exec(n.trim());if(o)return o[1]}return null}function kt(e){if(!e||e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function Pt(e,t=[],n){let o;try{o=JSON.parse(e)}catch{o=null}let r=o&&typeof o=="object"&&o.error&&typeof o.error=="object"?o.error:null,i=typeof r?.code=="string"?r.code:void 0,s=typeof r?.message=="string"?r.message:e.trim(),c=y(s,t),d=i&&typeof r?.message=="string"?`${i}: ${c}`:c,p=r?.details!==void 0?F(r.details,t):void 0,m=o&&typeof o=="object"&&typeof o.requestId=="string"?o.requestId:void 0,l=n?`HTTP ${n}`:"HTTP error";return{code:i,details:p,humanMessage:d,redactedMessage:c,requestId:m,structuredError:{code:i??"http_error",message:c||l,...p!==void 0?{details:p}:{}}}}function Z(e,t,n=[]){let o=Pt(t,n,e.status),r=e.headers.get("x-request-id")??o.requestId??null,i=e.headers.get("hyperscale-operation-id")??null,s=e.headers.get("hyperscale-receipt-id")??null,c=r?y(r,n):null,d=i?y(i,n):null,p=s?y(s,n):null,m=De(e.headers),l=o.humanMessage;return new O(`HTTP ${e.status}${l?` \xB7 ${l}`:""}${c?`
102
- Request id: ${c}`:""}`,{code:o.code,details:o.details,operationId:d,receiptId:p,requestId:c,status:e.status,structuredError:o.structuredError,traceId:m})}function ye(e,t){return{authenticated:!0,baseUrl:e.baseUrl,email:t.email,environment:e.environment,expiresAt:t.expiresAt,personalAccessTokenId:t.personalAccessTokenId,role:t.role,scopes:t.scopes,selectedProduct:e.selectedProduct,teamId:t.teamId,tenantId:t.tenantId,tokenName:t.name,userId:t.userId}}function bt(e){if(!e||typeof e!="object"||typeof e.userId!="string"||typeof e.email!="string"||typeof e.tenantId!="string"||typeof e.teamId!="string"||typeof e.role!="string"||typeof e.personalAccessTokenId!="string"||typeof e.name!="string"||!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string")||typeof e.expiresAt!="string"||e.status!=="active")throw new u("personal_access_token.current returned invalid data");return e}async function E(e,t){try{return bt(await P(e,rt,{},t,[t]))}catch(n){throw!(n instanceof O)||n.status!==401?n:new u(`That founder PAT was not accepted (HTTP 401). ${j}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:j})}}function St(e,t){return e.HYPERSCALE_CLI_BROWSER?{command:e.HYPERSCALE_CLI_BROWSER,args:[t]}:e.HYPERSCALE_NO_BROWSER==="1"||e.CI==="1"||e.CI==="true"||process.platform==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?null:process.platform==="darwin"?{command:"/usr/bin/open",args:[t]}:process.platform==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:{command:"xdg-open",args:[t]}}async function At(e,t){let n=St(e,t);return n?new Promise(o=>{let r=Te(n.command,n.args,{detached:!0,stdio:"ignore"});r.once("error",()=>o(!1)),r.once("spawn",()=>{r.unref(),o(!0)})}):!1}function ne(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function xt(e,t){let n=globalThis.crypto.randomUUID(),o=!1,r,i=new Promise((g,h)=>{r={reject:h,resolve:g}}),s=ze((g,h)=>{let I=new URL(g.url??"/","http://127.0.0.1");if(g.method!=="GET"||I.pathname!=="/callback"){h.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),h.end(`Not found.
103
- `);return}if(o){h.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login callback was already received.
104
- `);return}if(I.searchParams.get("state")!==n){h.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login state did not match. Return to the terminal.
105
- `);return}if(I.searchParams.get("error")!==null){o=!0,h.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login declined. Return to the terminal.
106
- `),r.reject(new u("Portal login was declined. Run hyperscale auth login to start again.",{code:"auth_callback_denied"}));return}let S=I.searchParams.get("grant"),A=I.searchParams.get("tenantId");if(!S||!A){h.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login callback is missing its grant or tenant.
107
- `);return}o=!0,h.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),h.end(`Login received. Return to the terminal.
108
- `),r.resolve({grant:S,tenantId:A})});await new Promise((g,h)=>{let I=S=>h(S);s.once("error",I),s.listen(0,"127.0.0.1",()=>{s.off("error",I),g()})}),s.once("error",g=>r.reject(g));let c=s.address();if(!c||typeof c=="string")throw await ne(s),new u("Could not bind the localhost login callback");let d=`http://127.0.0.1:${c.port}/callback`,p=new URL("/auth/cli",e.baseUrl);p.searchParams.set("callback",d),p.searchParams.set("state",n);let m=new URL("/signin",e.baseUrl);m.searchParams.set("returnTo",`${p.pathname}${p.search}`);let l=m.toString();if(!await At(t,l))return await ne(s),null;process.stderr.write(`Opening portal sign-in: ${l}
109
- `);let $=setTimeout(()=>{r.reject(new u("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},ut);try{return await i}finally{clearTimeout($),await ne(s)}}function Pe(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:ae,requestAccessUrl:_};if(e["--json"]){w(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: ${ae}`),a(`No access yet: ${_}`)}async function be(e,t,n,o,r){let i=await W(r),s={email:t.email,...e,selectedProduct:i&&i.email===t.email&&i.baseUrl===e.baseUrl&&i.environment===e.environment?i.selectedProduct:null},c=await wt(s,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},r);try{await z(r,s)}catch(p){throw await _e(s,r),p}if(c==="file"){let p=V(r)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${p} The founder PAT is in ${b(s,r)} with mode 0600.
110
- `)}let d=ye(s,t);o["--json"]?w(d):a(`Logged in as ${t.email} with PAT ${t.name}.`)}async function Tt(e,t){let n=L(e,t),o=je(e,t);if(o){if(!o.startsWith("hyperscale_pat_"))throw new u("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let d=await E(n,o);await be(n,d,o,e,t);return}if(e["--no-browser"]){Pe(e);return}let r=await xt(n,t);if(!r){Pe(e);return}let i=await P(n,"/v1/personal-access-token-login-grants/exchange",x({tenantId:r.tenantId,grant:r.grant}),void 0,[r.grant]),s=i?.secret;if(typeof s!="string"||!s.startsWith("hyperscale_pat_")||i?.tenantId!==r.tenantId)throw new u("CLI login grant exchange returned an invalid PAT");let c=await E(n,s);await be(n,c,s,e,t)}async function Et(e,t){let n=await k(e,t),o=n.identity??await E(n,n.token),r=ye(n,o);if(e["--json"]){w(r);return}a(`User: ${o.email}`),a(`Tenant: ${o.tenantId}`),a(`Role: ${o.role}`),a(`Token: ${o.name}`),a(`Scopes: ${o.scopes.join(", ")}`),a(`Expires: ${o.expiresAt}`),a(`API: ${n.baseUrl}`),a(`Environment: ${n.environment}`),a(`Product: ${n.selectedProduct??"not selected"}`)}async function vt(e,t){let n=await W(t);if(!n){e["--json"]?w({status:"signed_out"}):a("Already logged out.");return}let o=await Ne(n,t);if(e["--revoke"]&&!o)throw new u("The local founder PAT is missing, so the CLI cannot revoke it.");let r=o?.personalAccessTokenId,i=o?.tokenName;if(e["--revoke"]&&o){if(!r||!i){let d=await E(n,o.token);r=d.personalAccessTokenId,i=d.name}await P(n,`/v1/personal-access-tokens/${encodeURIComponent(r)}/revoke`,x({tenantId:o.tenantId,personalAccessTokenId:r}),o.token,[o.token])}let s=await _e(n,t),c=e["--revoke"]===!0;Ot(e,{cleanup:s,personalAccessTokenId:r,revoked:c,status:"signed_out",tokenName:i})}function Ot(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])w({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let o=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?a(`Revoked founder PAT ${o} and forgot local state.`):(a(`Forgot local founder PAT ${o}.`),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.
111
- `)}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 C(e,t,n,o,r,i=[]){let s=[],c=new Set,d,p;for(;;){let $=new URLSearchParams(n);d&&$.set("cursor",d);let g=$.size>0?`?${$}`:"",h=await P(e,`${t}${g}`,{},r,i);p===void 0&&(p=h),s.push(...v(h,o));let I=h.nextCursor;if(typeof I!="string"||I.length===0)break;if(c.has(I))throw new u(`${o} repeated cursor ${I}`);c.add(I),d=I}let{items:m,nextCursor:l,...f}=p;return{...f,items:s}}async function Ct(e,t){let n=await C(e,"/v1/blueprints",{},"blueprint.list"),o=v(n,"blueprint.list");if(t["--json"]){w(n);return}a("ID Name Summary");for(let r of o)a(`${r.id} ${r.name}${r.summary?` ${r.summary}`:""}`);a("Next:"),a(" hyperscale blueprint show <id>"),a(" hyperscale product create --blueprint <id> --name <name>")}async function Rt(e,t,n){if(!n)throw new u("blueprint show needs a Blueprint id");let o=await P(e,`/v1/blueprints/${encodeURIComponent(n)}`),r=_t(o,e.baseUrl);if(t["--json"]){w(r);return}a(`${r.name} (${r.id})`),a(r.summary),a(r.description),a("Nouns:");for(let i of r.customInstruments??[])a(` ${i.name} (${i.id}): ${i.summary}`);for(let i of r.instruments??[])a(` ${i.title} (${i.id}): ${i.summary}`);a("Verbs:");for(let i of r.verbs??[])a(` ${i.alias} -> ${i.operation}: ${i.summary}`);a("Parties:");for(let i of r.parties??[])a(` ${i.instrumentId}.${i.role} -> ${i.accountField}`);a("Money flows:");for(let i of r.moneyFlows??[]){let s=i.sourceAccount??"action input",c=i.destinationAccount??"action input",d=i.amountPath??"action input";a(` ${i.action} [${i.kind}]: ${s} -> ${c}; amount ${d}`)}a("Fee forms:");for(let i of r.feeForms??[]){let s=i.bps?`${i.bps} bps`:i.amountSar?`SAR ${i.amountSar}`:i.includedQuantity?`${i.includedQuantity} included`:i.kind;a(` ${i.id}: ${s} per ${i.unit}. ${i.summary}`)}r.priceEstimate&&(a("Price estimate:"),a(` monthlySar: SAR ${Number(r.priceEstimate.monthlySar).toLocaleString("en-US")}`),a(` setupSar: SAR ${Number(r.priceEstimate.setupSar).toLocaleString("en-US")}`),a(` complexityScore: ${r.priceEstimate.complexityScore}`)),a("Dials:");for(let i of r.dials??[])a(` ${i.instrumentId}.${i.key} (${i.kind}): ${i.summary}`);a("Journeys:");for(let i of r.journeys??[])a(` ${i.title} (${i.id}): ${i.summary}`),(i.steps??[]).forEach((s,c)=>{a(` ${c+1}. ${Nt(s)}`)});r.hsxStructured&&(a("HSX:"),a(` Source:
112
- ${Se(r.hsxStructured.source," ")}`),r.hsxStructured.document&&a(` Structured document:
113
- ${Se(JSON.stringify(r.hsxStructured.document,null,2)," ")}`)),a("Terms:");for(let[i,s]of Object.entries(r.terminology))a(` ${i}: ${s.definition}`),a(` ${s.href}`);a("Next:"),a(` hyperscale product create --blueprint ${r.id} --name <name>`)}function Nt(e){if(typeof e=="string")return e;let t=e.id?`${e.id} -> ${e.operation}`:e.operation,n=Object.entries(e.bind??{}).map(([r,i])=>`${r} <- ${i}`),o=[e.example?`example ${e.example}`:"",n.length>0?`binds ${n.join(", ")}`:""].filter(Boolean);return o.length>0?`${t}: ${o.join("; ")}`:t}function _t(e,t){let n=jt(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 jt(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 Se(e,t){return e.split(`
127
+ `)}async function se(e,t,n={},o){let r=`${e.baseUrl}${t}`,i=ve(e.baseUrl);if(Ge(r)!==i)throw new d(`The requested path ${t} leaves the ${i} origin; refusing the request.`);let s=[o].filter(Boolean);try{let c=await fetch(r,{...n,headers:{accept:"application/json",...o?{authorization:`Bearer ${o}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(we),redirect:"manual"});if(c.status>=300&&c.status<400){let u=$(y(r,s));throw new d(`${u} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`,{code:"unexpected_redirect",fix:"Point --base-url at the origin the API answers on."})}return Xe(c,s),{response:c,text:$(await c.text())}}catch(c){if(c instanceof d)throw c;let u=$(y(r,s)),p=n.headers?.["idempotency-key"]??n.headers?.["Idempotency-Key"],l=p?$(y(p,s)):void 0,m=$(y(c?.message??"network failure",s)),h=l?`Retry the request with the same idempotency key: ${l}.`:`Check that --base-url names the Hyperscale API origin and connectivity to ${u}.`;throw new d(`Could not reach ${u}: ${m}`,{code:"transport_error",details:{...l?{idempotencyKey:l}:{},path:t,url:u},fix:h})}}async function A(e,t,n={},o,r=[]){let{response:i,text:s}=await se(e,t,n,o);if(!i.ok)throw ce(i,s,r);try{return JSON.parse(s)}catch{throw new d(`HTTP ${i.status} returned invalid JSON`)}}function v(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function Dt(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function ae(e,t,n={},o){let r=`${e.baseUrl}${t}`,i=ve(e.baseUrl);if(Ge(r)!==i)throw new d(`The product document puts ${t} on another origin than the ${i} you configured; refusing to send the key there.`);let s=[e.apiKey].filter(Boolean);try{let c=await fetch(r,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(we),redirect:"manual"});if(c.status>=300&&c.status<400){let u=$(y(r,s));throw new d(`${u} 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://.`,{code:"unexpected_redirect",fix:"Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://."})}return Xe(c,s),{response:c,text:$(await c.text())}}catch(c){if(c instanceof d)throw c;if(o&&(c?.name==="TimeoutError"||c?.name==="AbortError"))throw new d(`product run ${o} timed out after ${we/1e3} seconds.`);let u=$(y(r,s)),p=n.headers?.["idempotency-key"]??n.headers?.["Idempotency-Key"],l=p?$(y(p,s)):void 0,m=$(y(c?.message??"network failure",s)),h=l?`Retry the request with the same idempotency key: ${l}.`:`Check that --base-url names the Hyperscale API origin and connectivity to ${u}.`;throw new d(`Could not reach ${u}: ${m}`,{code:"transport_error",details:{...l?{idempotencyKey:l}:{},path:t,url:u},fix:h})}}async function Ze(e){let{response:t,text:n}=await ae(e,"/v1/product.json");if(!t.ok)throw ce(t,n,[e.apiKey]);let o=Jt(n);if(!o)throw new d("The product document is not in the expected format.",{fix:'Run the latest unpinned CLI (e.g. "bunx @hyperscale0/cli@latest <command>"), or report the issue without including credentials.'});if(e.productId&&o.productId===void 0)throw new d(`The server's product document names no Product, so "--product ${e.productId}" cannot be checked against the API key. The platform predates Product identity in the descriptor: redeploy it, or drop --product.`);if(e.productId&&o.productId&&e.productId!==o.productId)throw new d(`Selected Product ${e.productId} does not match API key Product ${o.productId}. Run "hyperscale product select ${o.productId}" or pass "--product ${o.productId}". Or set HYPERSCALE_API_KEY to a key for ${e.productId}, or pass that key with --api-key.`);let r=o.operations.map(i=>{if(typeof i.summary!="string"||typeof i.description!="string")throw new d(`The product document carries no prose for ${i.operationId}. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);return{description:i.description,idempotency:i.idempotency,method:i.method,name:i.name,operationId:i.operationId,path:i.path,summary:i.summary}});return{compositionId:o.composition.id,operations:r,packageName:o.sdk?o.sdk.packageName.trim():null,title:o.title.trim()}}function Jt(e){let t;try{t=JSON.parse(e)}catch{return null}let n=ge(t),o=r=>typeof r=="string";if(!L(n)||n.schemaVersion!==1||!(n.productId===void 0||o(n.productId))||!o(n.title)||!L(n.composition)||!o(n.composition.id)||!Array.isArray(n.operations))return null;for(let r of n.operations)if(!L(r)||!o(r.method)||!o(r.path)||!o(r.name)||!o(r.operationId)||!o(r.idempotency))return null;return n.sdk!==void 0&&(!L(n.sdk)||!o(n.sdk.packageName))?null:n}function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e){return typeof e=="string"?$(e):Array.isArray(e)?e.map(ge):L(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[$(t),ge(n)])):e}function Qe(e){let t=e.get("x-trace-id");if(t&&t.trim()!=="")return t.trim();let n=e.get("traceparent");if(n){let o=/^00-([0-9a-fA-F]{32})-[0-9a-fA-F]{16}-[0-9a-fA-F]{2}$/.exec(n.trim());if(o)return o[1]}return null}function Bt(e){if(!e||e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function et(e,t,n=[]){let o=e?.get?.("x-request-id")??t??null,r=e?.get?.("hyperscale-operation-id")??null,i=e?.get?.("hyperscale-receipt-id")??null,s=e?Qe(e):null;return{requestId:o?$(y(o,n)):null,operationId:r?$(y(r,n)):null,receiptId:i?$(y(i,n)):null,traceId:s?$(y(s,n)):null}}function Q(e,t=[]){if(typeof e=="string")return $(y(e,t));if(Array.isArray(e))return e.map(n=>Q(n,t));if(e&&typeof e=="object"){let n=[];for(let[o,r]of Object.entries(e)){let i=$(y(o,t));n.push([i,Q(r,t)])}return Object.fromEntries(n)}return e}function tt(e,t=[],n){let o;try{o=JSON.parse(e)}catch{o=null}let r=o&&typeof o=="object"&&o.error&&typeof o.error=="object"?o.error:null;if(r){let c=typeof r.code=="string"?r.code:void 0,u=typeof r.fix=="string"?r.fix:void 0,p=u?$(y(u,t)):void 0,l=typeof r.message=="string"?r.message:n?`HTTP ${n}`:"HTTP error",m=$(y(l,t)),h=m.length>1024?m.slice(0,1024):m,I=c&&typeof r.message=="string"?`${c}: ${h}`:h,g=r.details!==void 0?Q(r.details,t):void 0,f=o&&typeof o=="object"&&typeof o.requestId=="string"?$(y(o.requestId,t)):void 0;return{code:c,details:g,fix:p,humanMessage:I,redactedMessage:h,requestId:f,structuredError:{code:c??"http_error",message:h,...g!==void 0?{details:g}:{},...p!==void 0?{fix:p}:{}}}}let i=n?`HTTP ${n}`:"HTTP error",s="Check that --base-url names the Hyperscale API origin, or report the issue without including credentials.";return{code:"http_error",details:void 0,fix:s,humanMessage:i,redactedMessage:i,requestId:void 0,structuredError:{code:"http_error",message:i,fix:s}}}function ce(e,t,n=[]){let o=tt(t,n,e.status),r=et(e.headers,o.requestId,n),i=o.humanMessage;return new T(`HTTP ${e.status}${i?` \xB7 ${i}`:""}${r.requestId?`
128
+ Request id: ${r.requestId}`:""}`,{code:o.code,details:o.details,fix:o.fix,operationId:r.operationId,receiptId:r.receiptId,requestId:r.requestId,status:e.status,structuredError:o.structuredError,traceId:r.traceId})}function Ee(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 qt(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 d("personal_access_token.current returned invalid data");return e}async function C(e,t){try{return qt(await A(e,At,{},t,[t]))}catch(n){throw!(n instanceof T)||n.status!==401?n:new d(`That founder PAT was not accepted (HTTP 401). ${K}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:K})}}function Yt(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 Ft(e,t){let n=Yt(e,t);return n?new Promise(o=>{let r=Be(n.command,n.args,{detached:!0,stdio:"ignore"});r.once("error",()=>o(!1)),r.once("spawn",()=>{r.unref(),o(!0)})}):!1}function le(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function Mt(e,t){let n=globalThis.crypto.randomUUID(),o=!1,r,i=new Promise((g,f)=>{r={reject:f,resolve:g}}),s=ft((g,f)=>{let w=new URL(g.url??"/","http://127.0.0.1");if(g.method!=="GET"||w.pathname!=="/callback"){f.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),f.end(`Not found.
129
+ `);return}if(o){f.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),f.end(`Login callback was already received.
130
+ `);return}if(w.searchParams.get("state")!==n){f.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),f.end(`Login state did not match. Return to the terminal.
131
+ `);return}if(w.searchParams.get("error")!==null){o=!0,f.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),f.end(`Login declined. Return to the terminal.
132
+ `),r.reject(new d("Portal login was declined. Run hyperscale auth login to start again.",{code:"auth_callback_denied"}));return}let b=w.searchParams.get("grant"),E=w.searchParams.get("tenantId");if(!b||!E){f.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),f.end(`Login callback is missing its grant or tenant.
133
+ `);return}o=!0,f.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),f.end(`Login received. Return to the terminal.
134
+ `),r.resolve({grant:b,tenantId:E})});await new Promise((g,f)=>{let w=b=>f(b);s.once("error",w),s.listen(0,"127.0.0.1",()=>{s.off("error",w),g()})}),s.once("error",g=>r.reject(g));let c=s.address();if(!c||typeof c=="string")throw await le(s),new d("Could not bind the localhost login callback");let u=`http://127.0.0.1:${c.port}/callback`,p=new URL("/auth/cli",e.baseUrl);p.searchParams.set("callback",u),p.searchParams.set("state",n);let l=new URL("/signin",e.baseUrl);l.searchParams.set("returnTo",`${p.pathname}${p.search}`);let m=l.toString();if(!await Ft(t,m))return await le(s),null;process.stderr.write(`Opening portal sign-in: ${m}
135
+ `);let I=setTimeout(()=>{r.reject(new d("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},Tt);try{return await i}finally{clearTimeout(I),await le(s)}}function Ue(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:ye,requestAccessUrl:H};if(e["--json"]){k(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: ${ye}`),a(`No access yet: ${H}`)}async function He(e,t,n,o,r){let i=await oe(r),s={email:t.email,...e,selectedProduct:i&&i.email===t.email&&i.baseUrl===e.baseUrl&&i.environment===e.environment?i.selectedProduct:null},c=await Lt(s,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},r);try{await re(r,s)}catch(p){throw await We(s,r),p}if(c==="file"){let p=ne(r)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${p} The founder PAT is in ${x(s,r)} with mode 0600.
136
+ `)}let u=Ee(s,t);o["--json"]?k(u):a(`Logged in as ${t.email} with PAT ${t.name}.`)}async function zt(e,t){let n=D(e,t),o=Ve(e,t);if(o){if(!o.startsWith("hyperscale_pat_"))throw new d("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let u=await C(n,o);await He(n,u,o,e,t);return}if(e["--no-browser"]){Ue(e);return}let r=await Mt(n,t);if(!r){Ue(e);return}let i=await A(n,"/v1/personal-access-token-login-grants/exchange",v({tenantId:r.tenantId,grant:r.grant}),void 0,[r.grant]),s=i?.secret;if(typeof s!="string"||!s.startsWith("hyperscale_pat_")||i?.tenantId!==r.tenantId)throw new d("CLI login grant exchange returned an invalid PAT");let c=await C(n,s);await He(n,c,s,e,t)}async function Wt(e,t){let n=await P(e,t),o=n.identity??await C(n,n.token),r=Ee(n,o);if(e["--json"]){k(r);return}a(`User: ${o.email}`),a(`Tenant: ${o.tenantId}`),a(`Role: ${o.role}`),a(`Token: ${o.name}`),a(`Scopes: ${o.scopes.join(", ")}`),a(`Expires: ${o.expiresAt}`),a(`API: ${n.baseUrl}`),a(`Environment: ${n.environment}`),a(`Product: ${n.selectedProduct??"not selected"}`)}async function Vt(e,t){let n=await oe(t);if(!n){e["--json"]?k({status:"signed_out"}):a("Already logged out.");return}let o=await ze(n,t);if(e["--revoke"]&&!o)throw new d("The local founder PAT is missing, so the CLI cannot revoke it.");let r=o?.personalAccessTokenId,i=o?.tokenName;if(e["--revoke"]&&o){if(!r||!i){let u=await C(n,o.token);r=u.personalAccessTokenId,i=u.name}await A(n,`/v1/personal-access-tokens/${encodeURIComponent(r)}/revoke`,v({tenantId:o.tenantId,personalAccessTokenId:r}),o.token,[o.token])}let s=await We(n,t),c=e["--revoke"]===!0;Gt(e,{cleanup:s,personalAccessTokenId:r,revoked:c,status:"signed_out",tokenName:i})}function Gt(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])k({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let o=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?a(`Revoked founder PAT ${o} and forgot local state.`):(a(`Forgot local founder PAT ${o}.`),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.
137
+ `)}function R(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new d(`${t} returned an invalid collection`);return e.items}async function O(e,t,n,o,r,i=[]){let s=[],c=new Set,u,p;for(;;){let I=new URLSearchParams(n);u&&I.set("cursor",u);let g=I.size>0?`?${I}`:"",f=await A(e,`${t}${g}`,{},r,i);p===void 0&&(p=f),s.push(...R(f,o));let w=f.nextCursor;if(typeof w!="string"||w.length===0)break;if(c.has(w))throw new d(`${o} repeated cursor ${w}`);c.add(w),u=w}let{items:l,nextCursor:m,...h}=p;return{...h,items:s}}async function Xt(e,t){let n=await O(e,"/v1/blueprints",{},"blueprint.list"),o=R(n,"blueprint.list");if(t["--json"]){k(n);return}a("ID Name Summary");for(let r of o)a(`${r.id} ${r.name}${r.summary?` ${r.summary}`:""}`);a("Next:"),a(" hyperscale blueprint show <id>"),a(" hyperscale product create --blueprint <id> --name <name>")}async function Zt(e,t,n){if(!n)throw new d("blueprint show needs a Blueprint id",{fix:'Run "hyperscale blueprint list" to list Blueprints, then pass one ID.'});let o=await A(e,`/v1/blueprints/${encodeURIComponent(n)}`),r={...en(o,e.baseUrl),nextCommands:[`hyperscale product create --blueprint ${n} --name <name>`]};if(t["--json"]){k(r);return}a(`${r.name} (${r.id})`),a(r.summary),a(r.description),a("Nouns:");for(let i of r.customInstruments??[])a(` ${i.name} (${i.id}): ${i.summary}`);for(let i of r.instruments??[])a(` ${i.title} (${i.id}): ${i.summary}`);a("Verbs:");for(let i of r.verbs??[])a(` ${i.alias} -> ${i.operation}: ${i.summary}`);a("Parties:");for(let i of r.parties??[])a(` ${i.instrumentId}.${i.role} -> ${i.accountField}`);a("Money flows:");for(let i of r.moneyFlows??[]){let s=i.sourceAccount??"action input",c=i.destinationAccount??"action input",u=i.amountPath??"action input";a(` ${i.action} [${i.kind}]: ${s} -> ${c}; amount ${u}`)}a("Fee forms:");for(let i of r.feeForms??[]){let s=i.bps?`${i.bps} bps`:i.amount?`SAR ${i.amount}`:i.includedQuantity?`${i.includedQuantity} included`:i.kind;a(` ${i.id}: ${s} per ${i.unit}. ${i.summary}`)}if(r.priceEstimate){let i=r.priceEstimate.currency??"SAR";a("Price estimate:"),r.priceEstimate.monthly!==void 0&&a(` monthly: ${i} ${Number(r.priceEstimate.monthly).toLocaleString("en-US")}`),r.priceEstimate.setup!==void 0&&a(` setup: ${i} ${Number(r.priceEstimate.setup).toLocaleString("en-US")}`),r.priceEstimate.complexityScore!==void 0&&a(` complexityScore: ${r.priceEstimate.complexityScore}`)}a("Dials:");for(let i of r.dials??[])a(` ${i.instrumentId}.${i.key} (${i.kind}): ${i.summary}`);a("Journeys:");for(let i of r.journeys??[])a(` ${i.title} (${i.id}): ${i.summary}`),(i.steps??[]).forEach((s,c)=>{a(` ${c+1}. ${Qt(s)}`)});r.hsxStructured&&(a("HSX:"),a(` Source:
138
+ ${Ke(r.hsxStructured.source," ")}`),r.hsxStructured.document&&a(` Structured document:
139
+ ${Ke(JSON.stringify(r.hsxStructured.document,null,2)," ")}`)),a("Terms:");for(let[i,s]of Object.entries(r.terminology))a(` ${i}: ${s.definition}`),a(` ${s.href}`);a("Next:"),a(` hyperscale product create --blueprint ${r.id} --name <name>`)}function Qt(e){if(typeof e=="string")return e;let t=e.id?`${e.id} -> ${e.operation}`:e.operation,n=Object.entries(e.bind??{}).map(([r,i])=>`${r} <- ${i}`),o=[e.example?`example ${e.example}`:"",n.length>0?`binds ${n.join(", ")}`:""].filter(Boolean);return o.length>0?`${t}: ${o.join("; ")}`:t}function en(e,t){let n=tn(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 tn(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 Ke(e,t){return e.split(`
114
140
  `).map(n=>`${t}${n}`).join(`
115
- `)}function we(e,t=[]){let n=e.headers.get("hyperscale-operation-id"),o=e.headers.get("hyperscale-receipt-id"),r=n?y(n,t):void 0,i=o?y(o,t):void 0;return{...r?{operationId:r}:{},...i?{receiptId:i}:{}}}function ge(e,t,n=[]){if(!e.ok)throw Z(e,t,n);try{return JSON.parse(t)}catch{throw new u(`HTTP ${e.status} returned invalid JSON`)}}function Lt(e,t){t.operationId&&a(`${e} operation: ${t.operationId}`),t.receiptId&&a(`${e} receipt: ${t.receiptId}`)}function Ut(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 Dt(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 Ht(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 Jt(e,t){let n=await C(t,"/v1/blueprints",{},"blueprint.list"),o=Ht(n);if(o.length===0)throw new u("The Blueprint catalog has no companies to build.");let r=e["--blueprint"];if(r){let l=o.find(({id:f})=>f===r);if(l)return l;throw new u(`Unknown Blueprint: ${r}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
116
- `);for(let[l,f]of o.entries()){let $=f.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${l+1}. ${f.name} (${f.id})${$?`: ${$}`:""}
117
- `)}let i=Ge({input:process.stdin,output:process.stderr,terminal:!0}),s=new AbortController,c=()=>s.abort();process.stdin.once("end",c),process.stdin.readableEnded&&s.abort();let d;try{try{d=(await i.question("Choose a number or Blueprint slug: ",{signal:s.signal})).trim()}catch(l){throw l?.name!=="AbortError"&&l?.code!=="ABORT_ERR"?l:new u("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",c),i.close()}let p=Number(d),m=Number.isInteger(p)?o[p-1]:o.find(({id:l})=>l===d);if(m)return m;throw new u(`No Blueprint matches ${JSON.stringify(d)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}async function Ae(e,t){Dt(e);let n={};try{await Kt(e,t,n)}catch(o){throw typeof n.apiKey!="string"?o:Ut(o,n.apiKey)}}async function Kt(e,t,n){let o=await k(e,t),r=await E(o,o.token),i=await Jt(e,o),s=e["--name"]??i.name;e["--json"]||a(`Authenticated: ${r.email}`);let c=await X(o,"/v1/products/blueprint-compose",x({blueprintId:i.id,name:s,tenantId:o.tenantId}),o.token),d=ge(c.response,c.text,[o.token]);if(typeof d?.productId!="string"||!dt.test(d.productId)||typeof d?.productBuildId!="string"||d?.blueprintId!==i.id)throw new u("product.blueprint.compose returned an invalid start Product");let p=d?.shown_once;if(typeof p!="string"||p.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=p;let m=we(c.response);await z(t,{...o,selectedProduct:d.productId}),e["--json"]||(a(`Product: ${d.productId}`),a(`Blueprint: ${d.blueprintId}`),Lt("Compose",m));let l=[`hyperscale compose plan product.hsx --product ${d.productId}`],f="Composition completed. Run SDK journeys against your Product.",$={blueprintId:d.blueprintId,composeOnly:!0,nextCommands:l,notice:f,productBuildId:d.productBuildId,productId:d.productId,receipts:[{stage:"product.blueprint.compose",...m}],...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},shown_once:p};if(e["--json"]){w($);return}a(f),a(`Shown once Product API key: ${p}`),a("Next:");for(let g of l)a(` ${g}`);a(" Run journeys with the Hyperscale SDK using the Product API key above.")}async function Bt(e,t){let n=e["--blueprint"],o=e["--name"];if(!n)throw new u("product create needs --blueprint <id>");if(!o)throw new u("product create needs --name <name>");let r=await k(e,t),i;try{i=await C(r,"/v1/products",{tenantId:r.tenantId},"product.list",r.token,[r.token])}catch(l){if(!(l instanceof O)||l.status!==403)throw l}let s=o.trim().toLocaleLowerCase("en-US"),c=(i?v(i,"product.list"):[]).find(l=>{let f=l?.displayName??l?.name;return typeof f=="string"&&f.trim().toLocaleLowerCase("en-US")===s});if(c){let l=c.productId??c.id??"<id>";throw new u(`A Product named ${JSON.stringify(o.trim())} already exists as ${l}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${l}" or choose another --name.`})}let d=await P(r,"/v1/products/blueprint-compose",x({blueprintId:n,name:o,tenantId:r.tenantId}),r.token,[r.token]);if(typeof d?.productId!="string"||typeof d?.blueprintId!="string"||typeof d?.productBuildId!="string")throw new u("product.blueprint.compose returned an invalid Product");await z(t,{...r,selectedProduct:d.productId});let p=typeof d?.shown_once=="string"&&d.shown_once.length>0?d.shown_once:void 0,m={blueprintId:d.blueprintId,nextSteps:[`hyperscale product show ${d.productId}`,...p?[]:['hyperscale key create --name "Founder CLI"']],productBuildId:d.productBuildId,productId:d.productId,selectedProduct:d.productId,...typeof d.startKeyId=="string"?{startKeyId:d.startKeyId}:{},...p?{shown_once:p}:{}};if(e["--json"]){w(m);return}a(`Product: ${m.productId}`),a(`Blueprint: ${m.blueprintId}`),a(`Build: ${m.productBuildId}`),a(`Selected: ${m.selectedProduct}`),m.shown_once&&a(`Shown once Product API key: ${m.shown_once}`),a("Next:");for(let l of m.nextSteps)a(` ${l}`)}function He(e){return new URLSearchParams({tenantId:e}).toString()}async function qt(e,t){let n=await k(e,t),o=await C(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),r=v(o,"product.list");if(e["--json"]){w(o);return}if(r.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 i of r){let s=i.productId??i.id??"unknown",c=i.displayName??i.name??"unnamed";a(`${s} ${c}${i.status?` ${i.status}`:""}`)}}async function Yt(e,t,n){let o=await k(e,t),r=n??o.selectedProduct;if(!r)throw new u("product show needs an id because no Product is selected. Create a Product first.");let i=await P(o,`/v1/products/${encodeURIComponent(r)}?${He(o.tenantId)}`,{},o.token,[o.token]);if(e["--json"]){w(i);return}Ft(i,r)}function Ft(e,t){let n=e?.displayName??e?.name??"unnamed",o=e?.status??"unknown",r=e?.blueprint,i=r?.id?`${r.name??r.id}${r.name?` (${r.id})`:""}`:"custom composition",s=e?.cost?.currency??"SAR",c=e?.pricing?.current?.monthlySar??e?.cost?.platformMonthlySar,d=e?.pricing?.current?.setupSar??e?.cost?.platformSetupSar,p=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements:[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(m=>`unavailable:${m}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(m=>m?.code??"pricing"):[]];a(`Name: ${n}`),a(`Product: ${e?.productId??t}`),a(`Status: ${o}`),a(`Blueprint: ${i}`),e?.pricing?.scheduled?(a(`Current billing price: ${s} ${e.pricing.current.monthlySar}/mo`),a(`Accepted price from ${e.pricing.scheduled.effectiveAt}: ${s} ${e.pricing.scheduled.monthlySar}/mo`)):a(`Monthly: ${c==null?"not returned":`${s} ${c}`}`),a(`Setup: ${d==null?"not returned":`${s} ${d}`}`),a(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),a(`Live blockers: ${p.length>0?p.join(", "):"none"}`);for(let[m,l]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let f=e?.surfaces?.[m];f?.url&&a(`${l}: ${f.url}`)}a("Next:"),a(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function Mt(e,t,n){if(!n)throw new u("product select needs a Product id");let o=await k(e,t),r=await P(o,`/v1/products/${encodeURIComponent(n)}?${He(o.tenantId)}`,{},o.token,[o.token]);if(r?.productId!==n)throw new u("product.retrieve returned the wrong Product");await z(t,{...o,selectedProduct:n});let i={productId:n,selected:!0};e["--json"]?w(i):a(`Selected Product: ${r.displayName??n} (${n})`)}function Vt(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}async function Wt(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 D(e,"utf8")}catch(n){throw new u(`Could not read ${e}: ${n.message}`)}return{file:e,source:t}}function zt(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 Ie(e,t,n,o="none"){let r=await Wt(n),i=await k(e,t),s=o==="required"?J(i,e):o==="optional"?Ke(i,e):void 0,c=await X(i,"/v1/composer/check",x({tenantId:i.tenantId,document:r.source,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}),i.token),d=we(c.response,[i.token]),p=zt(ge(c.response,c.text,[i.token]));if(!p.ok)throw new K(["composer.check refused the program.",...Vt(p.issues)].join(`
118
- `),{file:n,issues:p.issues,...d});return{check:p,receipt:d,context:i,productId:s,program:r,catalogRevisionId:e["--catalog-revision"]}}async function Gt(e,t,n){let o=await Ie(e,t,n,"none");if(e["--json"]){w({command:"composer.check",file:n,issues:o.check.issues,ok:!0,...o.receipt});return}a(`Check passed: ${n}`)}async function Je(e,t){let n=await X(e.context,"/v1/composer/plan",x({document:e.program.source,tenantId:e.context.tenantId,...e.productId?{productId:e.productId}:{},...e.catalogRevisionId?{catalogRevisionId:e.catalogRevisionId}:{}}),e.context.token),o=ge(n.response,n.text,[e.context.token]),r=we(n.response,[e.context.token]);if(!o||typeof o!="object"||typeof o.summary!="string"||!Array.isArray(o.actions)||!o.pricing||typeof o.pricing!="object")throw new u("composer.plan returned an invalid result");let i=o.actions.filter(s=>!s||typeof s!="object"||s.kind!=="configure_product");if(i.length>0)throw new K([o.summary,...i.map(s=>s&&typeof s=="object"?`${s.kind??"unknown"} ${s.target??"unknown"} ${s.detail??"Composer refused this action."}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
119
- `),{actions:i,file:t,...r,...e.productId?{productId:e.productId}:{}});return{...o,...r}}async function Xt(e,t,n){let o=await Ie(e,t,n,"optional"),r=await Je(o,n);if(e["--json"]){w({command:"composer.plan",file:n,check:{...o.check,...o.receipt},plan:r,...o.productId?{productId:o.productId}:{}});return}a(r.summary);for(let i of r.actions)a(`${i.kind} ${i.target} ${i.detail}`);r.pricing?.scheduled?(a(`Current billing price: SAR ${r.pricing.current.monthlySar}/mo`),a(`Candidate price from ${r.pricing.scheduled.effectiveAt}: SAR ${r.pricing.scheduled.monthlySar}/mo`),a(`Pricing identity: ${r.pricing.scheduled.pricingIdentity}`)):(a(`Monthly: SAR ${r.pricing.monthlySar}`),a(`Activation: SAR ${r.pricing.activationSar}`))}async function Qt(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new u("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let o=e["--pricing-identity"];if(!o&&e["--plan-file"]){let c=e["--plan-file"];try{let d=await D(c,"utf8"),p=JSON.parse(d);o=p.plan?.pricing?.scheduled?.pricingIdentity??p.pricing?.scheduled?.pricingIdentity??p.pricingIdentity}catch(d){throw new u(`Failed to read saved plan file ${c}: ${d.message}`)}}let r=await Ie(e,t,n,"required"),i=await Je(r,n);if(i.pricing?.scheduled&&!o){if(!e["--yes"])throw new u(`compose apply --confirm requires --pricing-identity (or --plan-file). Run "hyperscale compose plan ${n}" to review candidate pricing and copy the pricing identity, or pass --yes to accept the current candidate.`);o=i.pricing.scheduled.pricingIdentity}let s=await P(r.context,"/v1/products/recompose",x({program:{source:r.program.source},...r.catalogRevisionId?{catalogRevisionId:r.catalogRevisionId}:{},...o?{pricingIdentity:o}:{},tenantId:r.context.tenantId,productId:r.productId},e["--idempotency-key"]),r.context.token,[r.context.token]);if(!s||typeof s.productBuildId!="string")throw new u("product.recompose returned no new build identity");if(e["--json"]){w({command:"product.recompose",file:n,output:s});return}a(`Product: ${s.productId??r.productId}`),a(`Build: ${s.productBuildId}`),s.buildDigest&&a(`Digest: ${s.buildDigest}`),s.pricing?.scheduled&&(a(`Current billing price: SAR ${s.pricing.current.monthlySar}/mo`),a(`Accepted price from ${s.pricing.scheduled.effectiveAt}: SAR ${s.pricing.scheduled.monthlySar}/mo`))}function Ke(e,t){let n=t["--product"]??e.selectedProduct;return typeof n=="string"&&n.length>0?n:void 0}function J(e,t){let n=Ke(e,t);if(!n)throw new u("No Product selected. Pass --product <id> or create a Product first.");return n}async function Y(e,t){let n=await W(t),o=J(n??{},e),r=L(e,t,n??{});if(n&&(r.baseUrl!==n.baseUrl||r.environment!==n.environment))throw new u(`The selected Product belongs to ${n.baseUrl} (${n.environment}). Select a Product at the configured API origin first.`);let i=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!i)throw Ee(o);return{...r,apiKey:i,productId:o}}async function Be(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:o,text:r}=await Q(e,n,{},t);if(!o.ok)throw Ye(o,r,[e.apiKey],{productId:e.productId});return tn(r,o.status)}async function Zt(e,t,n){let o=await Y(e,t),r=await Be(o);if(n){en(r,n,e);return}if(e["--json"]){w(r);return}if(r.publicActions.length===0)a("No public actions");else{a("Operation ID Input Kind");for(let i of r.publicActions){let s=i.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";a(`${i.instrument}.${i.name} ${rn(i.inputSchema)} ${s}`)}}if(r.setupOperations.length>0){a("Setup operations (run with hyperscale call)");for(let i of r.setupOperations)a(i.operationName)}if(r.readOperationIds.length>0){a("Reads (run with hyperscale call)");for(let i of r.readOperationIds)a(on(i))}a(`Digest: ${r.tenantOperationSetDigest}`),a(`Setup digest: ${r.tenantSetupOperationSetDigest}`),a(`Read digest: ${r.tenantReadOperationSetDigest}`),a(`Build: ${r.productBuildId}`),a(`Surface version: ${r.tenantSurfaceVersion}`)}function en(e,t,n){let o=e.publicActions.find(c=>c&&`${c.instrument}.${c.name}`===t),r=nn(t),i=e.setupOperations.find(c=>c&&(c.operationId===t||c.operationId===r||c.operationName===t));if(i){let{inputSchema:c,operationId:d,operationName:p}=i,m={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:d,operationName:p,command:`hyperscale call ${p}`,inputSchema:c};if(n["--json"]){w(m);return}a(`Operation ID: ${d}`),a(`Operation name: ${p}`),a(`Run: hyperscale call ${p}`),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(!o)throw new u(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let s={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:o};if(n["--json"]){w(s);return}a(`Operation ID: ${o.instrument}.${o.name}`),a(`Instrument: ${o.instrument}`),a(`Input schema: ${JSON.stringify(o.inputSchema,null,2)}`),a(`Output schema: ${JSON.stringify(o.outputSchema,null,2)}`),a(`Actor policy: ${JSON.stringify(o.actorPolicy,null,2)}`),a(`Port policy: ${JSON.stringify(o.portPolicy,null,2)}`),a(`Idempotency policy: ${JSON.stringify(o.idempotencyPolicy,null,2)}`),a(`Receipt policy: ${JSON.stringify(o.receiptPolicy,null,2)}`),a(`Receipt evidence: ${JSON.stringify(o.receiptEvidence,null,2)}`),a(`Digest: ${e.tenantOperationSetDigest}`),a(`Build: ${e.productBuildId}`),a(`Surface version: ${e.tenantSurfaceVersion}`)}function tn(e,t){let n;try{n=JSON.parse(e)}catch{throw new u(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="frozen"||typeof n.productBuildId!="string"||typeof n.tenantSurfaceVersion!="number"||typeof n.tenantOperationSetDigest!="string"||typeof n.tenantReadOperationSetDigest!="string"||typeof n.tenantSetupOperationSetDigest!="string"||!Array.isArray(n.publicActions)||!Array.isArray(n.readOperationIds)||!Array.isArray(n.setupOperationIds)||!Array.isArray(n.setupOperations))throw new u("The Product operation set is not in the expected format. Upgrade the CLI.");return n}function nn(e){return e.replaceAll(".","_")}function on(e){for(let t of["create","list","retrieve"]){let n=`_${t}`;if(e.endsWith(n))return`${e.slice(0,-n.length)}.${t}`}return e}function rn(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(r=>typeof r=="string"):[]),o=Object.entries(t).map(([r,i])=>`${r}${n.has(r)?"":"?"}: ${qe(i)}`);return o.length===0?"no input":o.join(", ")}function qe(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"?`${qe(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function an(e,t,n){if(!n)throw new u("product run needs a public action");let o=await Y(e,t),r=await Be(o,n);sn(r,n);let i=await Fe(e),s=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:c,text:d}=await Q(o,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(i),headers:{"content-type":"application/json","idempotency-key":s},method:"POST"},n);if(!c.ok)throw Ye(c,d,[o.apiKey],{action:n,productId:o.productId});let p=c.headers.get("hyperscale-operation-id"),m=c.headers.get("hyperscale-receipt-id"),l=c.headers.get("x-request-id"),f=p?y(p,[o.apiKey]):null,$=m?y(m,[o.apiKey]):null,g=l?y(l,[o.apiKey]):null;if(e["--json"]){w({idempotencyKey:s,...g?{requestId:g}:{},operationId:f,receiptId:$,output:cn(d)});return}f&&a(`Operation: ${f}`),$&&a(`Receipt: ${$}`),a(`Idempotency key: ${s}`);let h=Me(d);h&&a(h)}function sn(e,t){let n=e.publicActions.find(r=>r&&`${r.instrument}.${r.name}`===t);if(n)return n;let o=e.publicActions.map(r=>`${r.instrument}.${r.name}`).map(r=>({candidate:r,distance:de(t,r)})).sort((r,i)=>r.distance-i.distance||r.candidate.localeCompare(i.candidate)).slice(0,3).map(({candidate:r})=>r);throw new u(`Unknown frozen public action: ${t}. Closest valid names: ${o.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function cn(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function Ye(e,t,n=[],o={}){let r=y(t.trim(),n),i;try{i=JSON.parse(t)}catch{return new u(`HTTP ${e.status}${r?` \xB7 ${r}`:""}`)}if(!i?.error||typeof i.error.message!="string")return new u(`HTTP ${e.status}`);let s=typeof i.error.code=="string"?i.error.code:"user_error",c=s==="user_error"?"":`${s}: `,d=i.error.message;if(typeof d=="string"&&d.includes("does not match API key Product")){let T=o.productId??d.match(/^Selected Product (\S+) does not match/)?.[1];T&&(d=`${d} Or set HYPERSCALE_API_KEY to a key for ${T}, or pass that key with --api-key.`)}let p=y(`HTTP ${e.status} \xB7 ${c}${d}`,n),m=un(i.error.details,n),l;s==="idempotency_conflict"?l="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":e.status===409&&typeof i.error.message=="string"&&i.error.message.includes("capability-derived")?l='This Product has no frozen public actions. List its operations with "hyperscale ops list" and run them with "hyperscale call".':[i.error.message,...m].some(T=>typeof T=="string"&&T.includes("[Truncated]"))&&o.action&&(l=`Run "hyperscale product actions ${o.action}" to read the full input schema and allowed values.`);let f=e.headers.get("x-request-id")??(i&&typeof i=="object"&&typeof i.requestId=="string"?i.requestId:void 0),$=e.headers.get("hyperscale-operation-id")??void 0,g=e.headers.get("hyperscale-receipt-id")??void 0,h=f?y(f,n):void 0,I=$?y($,n):void 0,S=g?y(g,n):void 0,A=new u([p,...m].join(`
120
- `),{code:s,...i.error.details?{details:F(i.error.details,n)}:{},...l?{fix:l}:{}});return h&&(A.requestId=h),I&&(A.operationId=I),S&&(A.receiptId=S),A}function F(e,t){return typeof e=="string"?y(e,t):Array.isArray(e)?e.map(n=>F(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[y(n,t),F(o,t)])):e}function un(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(o=>{if(!o||typeof o!="object")return[];let i=(Array.isArray(o.path)?o.path.join("."):"input")||"input";return typeof o.message=="string"?[`${i}: ${y(o.message,t)}`]:[]});let n=[];return ue(e,"",n,t),n}function ue(e,t,n,o){if(Array.isArray(e)){if(e.every(r=>r===null||typeof r!="object")){n.push(`${xe(t)}: ${y(e.join(", "),o)}`);return}e.forEach((r,i)=>ue(r,`${t}[${i}]`,n,o));return}if(e&&typeof e=="object"){for(let[r,i]of Object.entries(e))ue(i,t?`${t}.${r}`:r,n,o);return}t&&n.push(`${xe(t)}: ${y(String(e),o)}`)}function xe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function dn(e,t){let n=await k(e,t),o=J(n,e),r=await P(n,"/v1/sandbox-api-keys",x({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:o}),n.token,[n.token]);if(e["--json"]){w(r);return}a(`Key: ${r.apiKeyId??"unknown"}`),a(`Product: ${r.productId??o}`),a(`Status: ${r.status??"unknown"}`),r.secret?(a(`Secret: ${r.secret}`),a("Store it now. Hyperscale will not return it again."),a("Next:"),a(` export HYPERSCALE_API_KEY=${pn(r.secret)}`),a(` hyperscale product actions --product ${o}`)):a("The key already existed, so the one-time secret is unavailable.")}function pn(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function ln(e,t){let n=await k(e,t),o=J(n,e),r=await C(n,"/v1/api-keys",{productId:o,tenantId:n.tenantId},"api_key.list",n.token,[n.token]),i=v(r,"api_key.list");if(e["--json"]){w(r);return}for(let s of i)a(`${s.apiKeyId} ${s.name??"unnamed"} ${s.status??"unknown"}`)}async function mn(e,t,n){if(!n)throw new u("key revoke needs an API key id");let o=await k(e,t),r=J(o,e),i=await P(o,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,x({tenantId:o.tenantId,productId:r}),o.token,[o.token]);e["--json"]?w(i):a(`Key ${i.apiKeyId??n}: ${i.status??"revoked"}`)}async function fn(e,t){let n=await k(e,t),o=n.identity??await E(n,n.token),r=ye(n,o);if(e["--json"]){w(r);return}a(`User: ${o.email}`),a(`Tenant: ${o.tenantId}`),a(`Role: ${o.role}`),a(`Token: ${o.name}`),a(`Expires: ${o.expiresAt}`)}async function hn(e,t,n){let o=await Ue(e),r=n?n.toLowerCase():null,i=r?o.operations.filter(c=>c.name.toLowerCase().includes(r)||c.path.toLowerCase().includes(r)):o.operations;if(t["--json"]){a(JSON.stringify(i,null,2));return}if(i.length===0){a(n?`No operation matches ${n}`:"No operations");return}let s=Math.max(...i.map(c=>c.name.length));for(let c of i)a(`${c.name.padEnd(s)} ${c.method.padEnd(6)}${c.path}`)}async function yn(e,t){let n=await k(e,t),o=await C(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),r=v(o,"activity.list");if(e["--json"]){w(o);return}a("Time Activity Target Status");for(let i of r){let s=i.operation??i.auditEvent??"activity",c=i.resourceKind&&i.resourceId?`${i.resourceKind}:${i.resourceId}`:i.resourceKind??i.resourceId??"-";a(`${i.occurredAt??"unknown"} ${s} ${c} ${i.status??"recorded"}`)}}function wn(e,t){let n={...t},o=[],r=e.path.replace(/\{([^}]+)\}/g,(i,s)=>{let c=n[s];return c==null?(o.push(s),""):(delete n[s],encodeURIComponent(String(c)))});if(o.length>0)throw new u(`${e.name} needs ${o.join(", ")} in --input`);return{path:r,remaining:n}}function gn(e){let t=new URLSearchParams;for(let[o,r]of Object.entries(e))r!=null&&t.set(o,typeof r=="string"?r:JSON.stringify(r));let n=t.toString();return n?`?${n}`:""}function de(e,t){let n=Array.from({length:t.length+1},(o,r)=>r);for(let o=1;o<=e.length;o+=1){let r=[o];for(let i=1;i<=t.length;i+=1)r[i]=Math.min(r[i-1]+1,n[i]+1,n[i-1]+(e[o-1]===t[i-1]?0:1));n.splice(0,n.length,...r)}return n[t.length]}function In(e,t){let n=e.find(i=>i.name===t);if(n)return n;let o=e.filter(i=>i.operationId===t);if(o.length===1)return o[0];if(o.length>1)throw new u(`${t} matches more than one operation. Use one of: ${o.map(i=>i.name).join(", ")}.`);let r=e.map(i=>({candidate:i,distance:Math.min(de(t,i.name),de(t,i.operationId))})).sort((i,s)=>i.distance-s.distance||i.candidate.name.localeCompare(s.candidate.name)).slice(0,3).flatMap(({candidate:i})=>[i.name,i.operationId]);throw new u(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${r.join(", ")}.`)}async function $n(e,t,n){if(!n)throw new u("call needs an operation name");let o=await Ue(e),r=In(o.operations,n),i=await Fe(t),{path:s,remaining:c}=wn(r,i),d={method:r.method},p=s;r.method==="GET"?p+=gn(c):(d.body=JSON.stringify(c),d.headers={"content-type":"application/json",...r.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:m,text:l}=await Q(e,p,d);if(m.ok){if(t["--json"]){let f=kt(l),$=m.headers.get("x-request-id")??(f&&typeof f=="object"&&typeof f.requestId=="string"?f.requestId:null),g=m.headers.get("hyperscale-operation-id")??null,h=m.headers.get("hyperscale-receipt-id")??null,I=De(m.headers),S=$?y($,[e.apiKey]):null,A=g?y(g,[e.apiKey]):null,T=h?y(h,[e.apiKey]):null,Ve=I?y(I,[e.apiKey]):null;w({status:m.status,data:f,requestId:S,operationId:A,receiptId:T,traceId:Ve});return}a(Me(l));return}throw Z(m,l,[e.apiKey])}async function Fe(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 oe(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await D(e["--input-file"],"utf8")}catch(n){throw new u(`Could not read ${e["--input-file"]}: ${n.message}`)}return oe(t,"--input-file")}if(!process.stdin.isTTY){let t=await It();if(t.trim()!=="")return oe(t,"stdin")}return{}}function oe(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(o){throw new u(`${t} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new u(`${t} must be a JSON object`);return n}function Me(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function a(e){process.stdout.write(`${e}
121
- `)}function w(e){a(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 Pn(e,t){let n=kn(t)==="call",o=t.includes("--json");if(n&&o&&e instanceof O){w({status:e.status,error:e.structuredError??{code:e.code??"http_error",message:e.message},requestId:e.requestId??null,operationId:e.operationId??null,receiptId:e.receiptId??null,traceId:e.traceId??null});let c=typeof e.message=="string"?e.message:e.stack??String(e);process.stderr.write(`${c}
122
- `);return}let r=e instanceof u&&typeof e.shownOnce=="string"?e.shownOnce:void 0;if(!o){let c=e instanceof u?e.message:e.stack??String(e),d=e instanceof u&&typeof e.fix=="string"?`
123
- Fix: ${e.fix}`:"",p=r?`
124
- Shown once Product API key: ${r}`:"";process.stderr.write(`${c}${d}${p}
125
- `);return}let i=e instanceof u,s=i&&typeof e.code=="string"?e.code:i?"user_error":"internal_error";process.stderr.write(`${JSON.stringify({error:{code:s,message:i?e.message:"The command failed unexpectedly.",...i&&e.details?{details:e.details}:{},fix:i?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."},...r?{shown_once:r}:{}})}
126
- `)}async function bn(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function Sn(e,t){let{flags:n,positional:o}=mt(e);if(n["--version"])return a(await bn()),0;if(n["--help"]&&o.length>0)return process.stdout.write(lt(o)),0;if(o.length===0&&!n["--help"]){if(n["--json"])throw new u('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await Ae(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(pt),0;let[r,...i]=o;if(r==="start")return await Ae(n,t),0;if(r==="auth"){if(i[0]==="login")await Tt(n,t);else if(i[0]==="status")await Et(n,t);else if(i[0]==="logout")await vt(n,t);else throw new u('Auth subcommands are "login", "status", and "logout"');return 0}if(r==="blueprint"){let s=L(n,t);if(i[0]==="list")await Ct(s,n);else if(i[0]==="show")await Rt(s,n,i[1]);else throw new u('Blueprint subcommands are "list" and "show"');return 0}if(r==="product"){if(i[0]==="create")await Bt(n,t);else if(i[0]==="list")await qt(n,t);else if(i[0]==="show")await Yt(n,t,i[1]);else if(i[0]==="select")await Mt(n,t,i[1]);else if(i[0]==="actions")await Zt(n,t,i[1]);else if(i[0]==="run")await an(n,t,i[1]);else throw new u('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(r==="compose"){if(i[0]==="check")await Gt(n,t,i[1]);else if(i[0]==="plan")await Xt(n,t,i[1]);else if(i[0]==="apply")await Qt(n,t,i[1]);else throw new u('Compose subcommands are "check", "plan", and "apply"');return 0}if(r==="key"){if(i[0]==="create")await dn(n,t);else if(i[0]==="list")await ln(n,t);else if(i[0]==="revoke")await mn(n,t,i[1]);else throw new u('Key subcommands are "create", "list", and "revoke"');return 0}if(r==="whoami")return await fn(n,t),0;if(r==="activity"){if(i[0]!=="list")throw new u('The only activity subcommand is "list"');return await yn(n,t),0}if(r==="ops"){if(i[0]!=="list")throw new u('The only ops subcommand is "list"');let s=n["--product"]?await Y(n,t):ke(n,t);return await hn(s,n,i[1]),0}if(r==="call"){let s=n["--product"]?await Y(n,t):ke(n,t);return await $n(s,n,i[0]),0}throw new u(`Unknown command: ${r}`)}Sn(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{Pn(e,process.argv.slice(2)),process.exitCode=e instanceof u&&Number.isInteger(e.exitCode)?e.exitCode:1});
141
+ `)}function Te(e,t=[]){let n=e.headers.get("hyperscale-operation-id"),o=e.headers.get("hyperscale-receipt-id"),r=n?y(n,t):void 0,i=o?y(o,t):void 0;return{...r?{operationId:r}:{},...i?{receiptId:i}:{}}}function Ce(e,t,n=[]){if(!e.ok)throw ce(e,t,n);try{return JSON.parse(t)}catch{throw new d(`HTTP ${e.status} returned invalid JSON`)}}function nn(e,t){t.operationId&&a(`${e} operation: ${t.operationId}`),t.receiptId&&a(`${e} receipt: ${t.receiptId}`)}function on(e,t,n){let o=e?.message??String(e),r=[...n?[`hyperscale product show ${n}`]:[],"hyperscale product list"],i="Warning: The returned Product API key was the only copy. Save it or mint a replacement with key create.",s=[`hyperscale start failed after Product ${n??""} was created: ${o}.`,i,"Inspect the created Product with:",...r.map(u=>` ${u}`)].join(`
142
+ `),c=new d(s,{code:"start_failed_after_compose",details:{cause:o,...n?{productId:n}:{},recovery:r,warning:i},fix:n?`Inspect the created Product with "hyperscale product show ${n}".`:'Inspect created Products with "hyperscale product list".'});return c.shownOnce=t,c}function rn(e){if(!e["--blueprint"]&&!(process.stdin.isTTY&&process.stderr.isTTY))throw new d("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 sn(e){return R(e,"blueprint.list").map(t=>{if(typeof t?.id!="string"||t.id.length===0||typeof t?.name!="string"||t.name.length===0)throw new d("blueprint.list returned an invalid start choice");return{id:t.id,name:t.name,summary:typeof t.summary=="string"?t.summary:""}})}async function an(e,t){let n=await O(t,"/v1/blueprints",{},"blueprint.list"),o=sn(n);if(o.length===0)throw new d("The Blueprint catalog has no companies to build.");let r=e["--blueprint"];if(r){let m=o.find(({id:h})=>h===r);if(m)return m;throw new d(`Unknown Blueprint: ${r}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
143
+ `);for(let[m,h]of o.entries()){let I=h.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${m+1}. ${h.name} (${h.id})${I?`: ${I}`:""}
144
+ `)}let i=yt({input:process.stdin,output:process.stderr,terminal:!0}),s=new AbortController,c=()=>s.abort();process.stdin.once("end",c),process.stdin.readableEnded&&s.abort();let u;try{try{u=(await i.question("Choose a number or Blueprint slug: ",{signal:s.signal})).trim()}catch(m){throw m?.name!=="AbortError"&&m?.code!=="ABORT_ERR"?m:new d("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",c),i.close()}let p=Number(u),l=Number.isInteger(p)?o[p-1]:o.find(({id:m})=>m===u);if(l)return l;throw new d(`No Blueprint matches ${JSON.stringify(u)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}async function De(e,t){rn(e);let n={};try{await cn(e,t,n)}catch(o){throw typeof n.apiKey!="string"?o:on(o,n.apiKey,n.productId)}}async function cn(e,t,n){let o=await P(e,t),r=await C(o,o.token),i=await an(e,o),s=e["--name"]??i.name;e["--json"]||a(`Authenticated: ${r.email}`);let c=await se(o,"/v1/products/blueprint-compose",v({blueprintId:i.id,name:s,tenantId:o.tenantId}),o.token),u=Ce(c.response,c.text,[o.token]);if(typeof u?.productId!="string"||!Ct.test(u.productId)||typeof u?.productBuildId!="string"||u?.blueprintId!==i.id)throw new d("product.blueprint.compose returned an invalid start Product");let p=u?.shown_once;if(typeof p!="string"||p.length===0)throw new d("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=p,n.productId=u.productId;let l=Te(c.response);await re(t,{...o,selectedProduct:u.productId}),e["--json"]||(a(`Product: ${u.productId}`),a(`Blueprint: ${u.blueprintId}`),nn("Compose",l));let m=[`hyperscale compose plan product.hsx --product ${u.productId}`],h="Composition completed. Run SDK journeys against your Product.",I={blueprintId:u.blueprintId,composeOnly:!0,nextCommands:m,notice:h,productBuildId:u.productBuildId,productId:u.productId,receipts:[{stage:"product.blueprint.compose",...l}],...typeof u.startKeyId=="string"?{startKeyId:u.startKeyId}:{},shown_once:p};if(e["--json"]){k(I);return}a(h),a(`Shown once Product API key: ${p}`),a("Next:");for(let g of m)a(` ${g}`);a(" Run journeys with the Hyperscale SDK using the Product API key above.")}async function un(e,t){let n=e["--blueprint"],o=e["--source"],r=e["--name"];if(n&&o)throw new d("product create accepts either --blueprint <id> or --source <file>, not both");if(!n&&!o)throw new d("product create needs either --blueprint <id> or --source <file>");if(!r)throw new d("product create needs --name <name>");let i=o?await rt(o,"product create"):void 0,s=await P(e,t),c;try{c=await O(s,"/v1/products",{tenantId:s.tenantId},"product.list",s.token,[s.token])}catch(w){if(!(w instanceof T)||w.status!==403)throw w}let u=r.trim().toLocaleLowerCase("en-US"),p=(c?R(c,"product.list"):[]).find(w=>{let b=w?.displayName??w?.name;return typeof b=="string"&&b.trim().toLocaleLowerCase("en-US")===u});if(p){let w=p.productId??p.id??"<id>";throw new d(`A Product named ${JSON.stringify(r.trim())} already exists as ${w}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${w}" or choose another --name.`})}let l=o?"/v1/products/instruments-compose":"/v1/products/blueprint-compose",m=o?{name:r,program:{source:i.source},tenantId:s.tenantId,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}:{blueprintId:n,name:r,tenantId:s.tenantId},h=await A(s,l,v(m),s.token,[s.token]);if(typeof h?.productId!="string"||typeof h?.productBuildId!="string"||!o&&typeof h?.blueprintId!="string")throw new d(`${o?"product.instruments.compose":"product.blueprint.compose"} returned an invalid Product`);await re(t,{...s,selectedProduct:h.productId});let I=typeof h?.shown_once=="string"&&h.shown_once.length>0?h.shown_once:void 0,g=[`hyperscale product show ${h.productId}`,...I?[]:[`hyperscale key create --name "Founder CLI" --product ${h.productId}`]],f={...h.blueprintId?{blueprintId:h.blueprintId}:{},nextCommands:g,nextSteps:g,productBuildId:h.productBuildId,productId:h.productId,selectedProduct:h.productId,...typeof h.startKeyId=="string"?{startKeyId:h.startKeyId}:{},...I?{shown_once:I}:{}};if(e["--json"]){k(f);return}a(`Product: ${f.productId}`),f.blueprintId&&a(`Blueprint: ${f.blueprintId}`),a(`Build: ${f.productBuildId}`),a(`Selected: ${f.selectedProduct}`),f.shown_once&&a(`Shown once Product API key: ${f.shown_once}`),a("Next:");for(let w of f.nextSteps)a(` ${w}`)}function nt(e){return new URLSearchParams({tenantId:e}).toString()}async function dn(e,t){let n=await P(e,t),o=await O(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),r=R(o,"product.list");if(e["--json"]){k(o);return}if(r.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 i of r){let s=i.productId??i.id??"unknown",c=i.displayName??i.name??"unnamed";a(`${s} ${c}${i.status?` ${i.status}`:""}`)}}async function pn(e,t,n){let o=await P(e,t),r=n??o.selectedProduct;if(!r)throw new d("product show needs an id because no Product is selected. Create a Product first.",{fix:'Run "hyperscale product list" to see existing Products, or "hyperscale product create" to create one.'});let i=await A(o,`/v1/products/${encodeURIComponent(r)}?${nt(o.tenantId)}`,{},o.token,[o.token]);if(e["--json"]){k({...i,nextCommands:[`hyperscale product actions --product ${r}`,`hyperscale key list --product ${r}`]});return}ln(i,r)}function ln(e,t){let n=e?.displayName??e?.name??"unnamed",o=e?.status??"unknown",r=e?.blueprint,i=r?.id?`${r.name??r.id}${r.name?` (${r.id})`:""}`:"custom composition",s=e?.pricing?.currency??e?.cost?.currency??"SAR",c=e?.pricing?.current?.monthly??e?.cost?.platformMonthly,u=e?.pricing?.current?.setup??e?.cost?.platformSetup,p=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements.map(l=>typeof l=="string"?l:l?.owner?`${l.key} (${l.owner})`:l?.key):[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(l=>`unavailable:${l}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(l=>l?.code??"pricing"):[]];if(a(`Name: ${n}`),a(`Product: ${e?.productId??t}`),a(`Status: ${o}`),a(`Blueprint: ${i}`),e?.pricing?.scheduled){let l=e.pricing.current?.monthly,m=e.pricing.scheduled?.monthly;a(`Current billing price: ${s} ${l}/mo`),a(`Accepted price from ${e.pricing.scheduled.effectiveAt}: ${s} ${m}/mo`)}else a(`Monthly: ${c==null?"not returned":`${s} ${c}`}`);a(`Setup: ${u==null?"not returned":`${s} ${u}`}`),a(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),a(`Live blockers: ${p.length>0?p.join(", "):"none"}`);for(let[l,m]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let h=e?.surfaces?.[l];h?.url&&a(`${m}: ${h.url}`)}a("Next:"),a(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function hn(e,t,n){if(!n)throw new d("product select needs a Product id",{fix:'Run "hyperscale product list" to list Products, then pass one ID.'});let o=await P(e,t),r=await A(o,`/v1/products/${encodeURIComponent(n)}?${nt(o.tenantId)}`,{},o.token,[o.token]);if(r?.productId!==n)throw new d("product.retrieve returned the wrong Product");await re(t,{...o,selectedProduct:n});let s={nextCommands:[`hyperscale product show ${n}`,`hyperscale key list --product ${n}`],productId:n,selected:!0};e["--json"]?k(s):a(`Selected Product: ${r.displayName??n} (${n})`)}function mn(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}function fn(e){return JSON.stringify(Ie(e))}function Ie(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ie);let t={};for(let n of Object.keys(e).sort())t[n]=Ie(e[n]);return t}function ot(e,t=""){if(e==null)return t;if(typeof e=="string")return e;if(typeof e=="object")try{return fn(e)}catch{return t}return String(e)}async function rt(e,t="compose"){if(!e)throw new d(`${t} needs a .hsx file`,{fix:`Run "hyperscale ${t} <file.hsx>" with an existing .hsx file.`});if(!e.endsWith(".hsx"))throw new d(`${t} reads a .hsx file, got ${e}`,{fix:`Point ${t} at a file ending in .hsx.`});let n;try{n=await B(e,"utf8")}catch(o){throw new d(`Could not read ${e}: ${o.message}`)}return{file:e,source:n}}function yn(e){if(!e||typeof e!="object"||typeof e.ok!="boolean"||!Array.isArray(e.issues))throw new d("composer.check returned an invalid result",{fix:'Run the latest unpinned CLI (e.g. "bunx @hyperscale0/cli@latest <command>"), or report the issue without including credentials.'});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 d("composer.check returned an invalid issue",{fix:'Run the latest unpinned CLI (e.g. "bunx @hyperscale0/cli@latest <command>"), or report the issue without including credentials.'});return{code:n.code,message:n.message,path:n.path}}),ok:e.ok}}async function Re(e,t,n,o="none",r="compose"){let i=await rt(n,r),s=await P(e,t),c=o==="required"?Y(s,e):o==="optional"?st(s,e):void 0,u=await se(s,"/v1/composer/check",v({tenantId:s.tenantId,document:i.source,...e["--catalog-revision"]?{catalogRevisionId:e["--catalog-revision"]}:{}}),s.token),p=Te(u.response,[s.token]),l=yn(Ce(u.response,u.text,[s.token]));if(!l.ok)throw new Z(["composer.check refused the program.",...mn(l.issues)].join(`
145
+ `),{file:n,issues:l.issues,...p});return{check:l,receipt:p,context:s,productId:c,program:i,catalogRevisionId:e["--catalog-revision"]}}async function wn(e,t,n){let o=await Re(e,t,n,"none","compose check");if(e["--json"]){k({command:"composer.check",file:n,issues:o.check.issues,ok:!0,...o.receipt});return}a(`Check passed: ${n}`)}async function it(e,t){let n=await se(e.context,"/v1/composer/plan",v({document:e.program.source,tenantId:e.context.tenantId,...e.productId?{productId:e.productId}:{},...e.catalogRevisionId?{catalogRevisionId:e.catalogRevisionId}:{}}),e.context.token),o=Ce(n.response,n.text,[e.context.token]),r=Te(n.response,[e.context.token]);if(!o||typeof o!="object"||typeof o.summary!="string"||!Array.isArray(o.actions)||!o.pricing||typeof o.pricing!="object")throw new d("composer.plan returned an invalid result");let i=o.actions.filter(s=>!s||typeof s!="object"||s.kind!=="configure_product");if(i.length>0)throw new Z([o.summary,...i.map(s=>s&&typeof s=="object"?`${s.kind??"unknown"} ${s.target??"unknown"} ${ot(s.detail,"Composer refused this action.")}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
146
+ `),{actions:i,file:t,...r,...e.productId?{productId:e.productId}:{}});return{...o,...r}}async function gn(e,t,n){let o=await Re(e,t,n,"optional","compose plan"),r=await it(o,n);if(e["--json"]){k({command:"composer.plan",file:n,check:{...o.check,...o.receipt},plan:r,...o.productId?{productId:o.productId}:{}});return}a(r.summary);for(let s of r.actions)a(`${s.kind} ${s.target} ${ot(s.detail)}`);let i=r.pricing?.currency??"SAR";if(r.pricing?.scheduled){let s=r.pricing.current?.monthly,c=r.pricing.scheduled?.monthly;a(`Current billing price: ${i} ${s}/mo`),a(`Candidate price from ${r.pricing.scheduled.effectiveAt}: ${i} ${c}/mo`),a(`Pricing identity: ${r.pricing.scheduled.pricingIdentity}`)}else if(r.pricing){let s=r.pricing.monthly,c=r.pricing.activation;s!==void 0&&a(`Monthly: ${i} ${s}`),c!==void 0&&a(`Activation: ${i} ${c}`)}}async function In(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new d("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let o=e["--pricing-identity"];if(!o&&e["--plan-file"]){let u=e["--plan-file"];try{let p=await B(u,"utf8"),l=JSON.parse(p);o=l.plan?.pricing?.scheduled?.pricingIdentity??l.pricing?.scheduled?.pricingIdentity??l.pricingIdentity}catch(p){throw new d(`Failed to read saved plan file ${u}: ${p.message}`)}}let r=await Re(e,t,n,"required","compose apply"),i=await it(r,n);if(i.pricing?.scheduled&&!o){if(!e["--yes"])throw new d(`compose apply --confirm requires --pricing-identity (or --plan-file). Run "hyperscale compose plan ${n}" to review candidate pricing and copy the pricing identity, or pass --yes to accept the current candidate.`);o=i.pricing.scheduled.pricingIdentity}let s=e["--idempotency-key"]??globalThis.crypto.randomUUID(),c;try{c=await A(r.context,"/v1/products/recompose",v({program:{source:r.program.source},...r.catalogRevisionId?{catalogRevisionId:r.catalogRevisionId}:{},...o?{pricingIdentity:o}:{},tenantId:r.context.tenantId,productId:r.productId},s),r.context.token,[r.context.token])}catch(u){throw u instanceof T&&u.code==="product_instrument_not_drained"&&(u.fix=`Drain live instrument instances, or create a new Product directly from source: hyperscale product create --source ${n} --name <name>`),u}if(!c||typeof c.productBuildId!="string")throw new d("product.recompose returned no new build identity");if(e["--json"]){k({command:"product.recompose",file:n,output:c});return}if(a(`Product: ${c.productId??r.productId}`),a(`Build: ${c.productBuildId}`),c.buildDigest&&a(`Digest: ${c.buildDigest}`),c.pricing?.scheduled){let u=c.pricing.currency??"SAR",p=c.pricing.current?.monthly,l=c.pricing.scheduled?.monthly;a(`Current billing price: ${u} ${p}/mo`),a(`Accepted price from ${c.pricing.scheduled.effectiveAt}: ${u} ${l}/mo`)}}function st(e,t){let n=t["--product"]??e.selectedProduct;return typeof n=="string"&&n.length>0?n:void 0}function Y(e,t){let n=st(e,t);if(!n)throw new d("No Product selected. Pass --product <id> or create a Product first.",{fix:'Run "hyperscale product list" to see existing Products, or "hyperscale product create" to create one.'});return n}async function ee(e,t){let n=await oe(t),o=Y(n??{},e),r=D(e,t,n??{});if(n&&(r.baseUrl!==n.baseUrl||r.environment!==n.environment))throw new d(`The selected Product belongs to ${n.baseUrl} (${n.environment}). Select a Product at the configured API origin first.`);let i=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!i)throw qe(o);return{...r,apiKey:i,productId:o}}async function at(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:o,text:r}=await ae(e,n,{},t);if(!o.ok)throw ut(o,r,[e.apiKey],{productId:e.productId});return Pn(r,o.status)}async function $n(e,t,n){let o=await ee(e,t),r=await at(o);if(n){kn(r,n,e);return}if(e["--json"]){k(r);return}if(r.publicActions.length===0)a("No public actions");else{a("Operation ID Input Kind");for(let i of r.publicActions){let s=i.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";a(`${i.instrument}.${i.name} ${Sn(i.inputSchema)} ${s}`)}}if(r.setupOperations.length>0){a("Setup operations (run with hyperscale call)");for(let i of r.setupOperations)a(i.operationName)}if(r.readOperationIds.length>0){a("Reads (run with hyperscale call)");for(let i of r.readOperationIds)a(An(i))}a(`Digest: ${r.tenantOperationSetDigest}`),a(`Setup digest: ${r.tenantSetupOperationSetDigest}`),a(`Read digest: ${r.tenantReadOperationSetDigest}`),a(`Build: ${r.productBuildId}`),a(`Surface version: ${r.tenantSurfaceVersion}`)}function kn(e,t,n){let o=e.publicActions.find(c=>c&&`${c.instrument}.${c.name}`===t),r=bn(t),i=e.setupOperations.find(c=>c&&(c.operationId===t||c.operationId===r||c.operationName===t));if(i){let{inputSchema:c,operationId:u,operationName:p}=i,l={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:u,operationName:p,command:`hyperscale call ${p}`,inputSchema:c};if(n["--json"]){k(l);return}a(`Operation ID: ${u}`),a(`Operation name: ${p}`),a(`Run: hyperscale call ${p}`),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(!o)throw new d(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let s={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:o};if(n["--json"]){k(s);return}a(`Operation ID: ${o.instrument}.${o.name}`),a(`Instrument: ${o.instrument}`),a(`Input schema: ${JSON.stringify(o.inputSchema,null,2)}`),a(`Output schema: ${JSON.stringify(o.outputSchema,null,2)}`),a(`Actor policy: ${JSON.stringify(o.actorPolicy,null,2)}`),a(`Port policy: ${JSON.stringify(o.portPolicy,null,2)}`),a(`Idempotency policy: ${JSON.stringify(o.idempotencyPolicy,null,2)}`),a(`Receipt policy: ${JSON.stringify(o.receiptPolicy,null,2)}`),a(`Receipt evidence: ${JSON.stringify(o.receiptEvidence,null,2)}`),a(`Digest: ${e.tenantOperationSetDigest}`),a(`Build: ${e.productBuildId}`),a(`Surface version: ${e.tenantSurfaceVersion}`)}function Pn(e,t){let n;try{n=JSON.parse(e)}catch{throw new d(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="frozen"||typeof n.productBuildId!="string"||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 d("The Product operation set is not in the expected format.",{fix:'Run the latest unpinned CLI (e.g. "bunx @hyperscale0/cli@latest <command>"), or report the issue without including credentials.'});return n}function bn(e){return e.replaceAll(".","_")}function An(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 Sn(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(r=>typeof r=="string"):[]),o=Object.entries(t).map(([r,i])=>`${r}${n.has(r)?"":"?"}: ${ct(i)}`);return o.length===0?"no input":o.join(", ")}function ct(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"?`${ct(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function xn(e,t,n){if(!n)throw new d("product run needs a public action");let o=await ee(e,t),r=await at(o,n);vn(r,n);let i=await dt(e),s=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:c,text:u}=await ae(o,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(i),headers:{"content-type":"application/json","idempotency-key":s},method:"POST"},n);if(!c.ok)throw ut(c,u,[o.apiKey],{action:n,productId:o.productId});let p=c.headers.get("hyperscale-operation-id"),l=c.headers.get("hyperscale-receipt-id"),m=c.headers.get("x-request-id"),h=p?y(p,[o.apiKey]):null,I=l?y(l,[o.apiKey]):null,g=m?y(m,[o.apiKey]):null;if(e["--json"]){k({idempotencyKey:s,...g?{requestId:g}:{},operationId:h,receiptId:I,output:En(u)});return}h&&a(`Operation: ${h}`),I&&a(`Receipt: ${I}`),a(`Idempotency key: ${s}`);let f=pt(u);f&&a(f)}function vn(e,t){let n=e.publicActions.find(r=>r&&`${r.instrument}.${r.name}`===t);if(n)return n;let o=e.publicActions.map(r=>`${r.instrument}.${r.name}`).map(r=>({candidate:r,distance:ke(t,r)})).sort((r,i)=>r.distance-i.distance||r.candidate.localeCompare(i.candidate)).slice(0,3).map(({candidate:r})=>r);throw new d(`Unknown frozen public action: ${t}. Closest valid names: ${o.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function En(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function ut(e,t,n=[],o={}){let r=tt(t,n,e.status),i=et(e.headers,r.requestId,n),s=r.code??"user_error",c=r.redactedMessage;if(typeof c=="string"&&c.includes("does not match API key Product")){let h=o.productId??c.match(/^Selected Product (\S+) does not match/)?.[1];h&&(c=`${c} Or set HYPERSCALE_API_KEY to a key for ${h}, or pass that key with --api-key.`)}let u=s==="user_error"?"":`${s}: `,p=`HTTP ${e.status} \xB7 ${u}${c}`,l=Tn(r.details,n),m=r.fix;return s==="idempotency_conflict"?m="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":e.status===409&&typeof c=="string"&&c.includes("capability-derived")?m='This Product has no frozen public actions. List its operations with "hyperscale ops list" and run them with "hyperscale call".':[c,...l].some(h=>typeof h=="string"&&h.includes("[Truncated]"))&&o.action&&(m=`Run "hyperscale product actions ${o.action}" to read the full input schema and allowed values.`),new T([p,...l].join(`
147
+ `),{code:s,details:r.details,fix:m,operationId:i.operationId,receiptId:i.receiptId,requestId:i.requestId,status:e.status,traceId:i.traceId})}function Tn(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(o=>{if(!o||typeof o!="object")return[];let i=(Array.isArray(o.path)?o.path.join("."):"input")||"input";return typeof o.message=="string"?[`${i}: ${y(o.message,t)}`]:[]});let n=[];return $e(e,"",n,t),n}function $e(e,t,n,o){if(Array.isArray(e)){if(e.every(r=>r===null||typeof r!="object")){n.push(`${Je(t)}: ${y(e.join(", "),o)}`);return}e.forEach((r,i)=>$e(r,`${t}[${i}]`,n,o));return}if(e&&typeof e=="object"){for(let[r,i]of Object.entries(e))$e(i,t?`${t}.${r}`:r,n,o);return}t&&n.push(`${Je(t)}: ${y(String(e),o)}`)}function Je(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function Cn(e,t){let n=await P(e,t),o=Y(n,e),r=await A(n,"/v1/sandbox-api-keys",v({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:o}),n.token,[n.token]),i=["export HYPERSCALE_API_KEY=<paste the shown_once value>",`hyperscale product actions --product ${o}`];if(e["--json"]){let{secret:s,...c}=r;k({...c,...typeof s=="string"?{shown_once:s}:{},nextCommands:i});return}a(`Key: ${r.apiKeyId??"unknown"}`),a(`Product: ${r.productId??o}`),a(`Status: ${r.status??"unknown"}`),r.secret?(a(`Secret: ${r.secret}`),a("Store it now. Hyperscale will not return it again."),a("Next:"),a(" export HYPERSCALE_API_KEY=<paste the secret above>"),a(` hyperscale product actions --product ${o}`)):a("The key already existed, so the one-time secret is unavailable.")}async function Rn(e,t){let n=await P(e,t),o=Y(n,e),r=await O(n,"/v1/api-keys",{productId:o,tenantId:n.tenantId},"api_key.list",n.token,[n.token]),i=R(r,"api_key.list");if(e["--json"]){k(r);return}for(let s of i)a(`${s.apiKeyId} ${s.name??"unnamed"} ${s.status??"unknown"}`)}async function _n(e,t,n){if(!n)throw new d("key revoke needs an API key id",{fix:'Run "hyperscale key list" to list keys, then pass one ID.'});let o=await P(e,t),r=Y(o,e),i=await A(o,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,v({tenantId:o.tenantId,productId:r}),o.token,[o.token]);e["--json"]?k(i):a(`Key ${i.apiKeyId??n}: ${i.status??"revoked"}`)}async function On(e,t){let n=await P(e,t),o=n.identity??await C(n,n.token),r=Ee(n,o);if(e["--json"]){k(r);return}a(`User: ${o.email}`),a(`Tenant: ${o.tenantId}`),a(`Role: ${o.role}`),a(`Token: ${o.name}`),a(`Expires: ${o.expiresAt}`)}async function Nn(e,t,n){let o=await Ze(e),r=n?n.toLowerCase():null,i=r?o.operations.filter(c=>c.name.toLowerCase().includes(r)||c.path.toLowerCase().includes(r)):o.operations;if(t["--json"]){a(JSON.stringify(i,null,2));return}if(i.length===0){a(n?`No operation matches ${n}`:"No operations");return}let s=Math.max(...i.map(c=>c.name.length));for(let c of i)a(`${c.name.padEnd(s)} ${c.method.padEnd(6)}${c.path}`)}async function jn(e,t){let n=await P(e,t),o=await O(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),r=R(o,"activity.list");if(e["--json"]){k(o);return}a("Time Activity Target Status");for(let i of r){let s=i.operation??i.auditEvent??"activity",c=i.resourceKind&&i.resourceId?`${i.resourceKind}:${i.resourceId}`:i.resourceKind??i.resourceId??"-";a(`${i.occurredAt??"unknown"} ${s} ${c} ${i.status??"recorded"}`)}}function Ln(e,t){let n={...t},o=[],r=e.path.replace(/\{([^}]+)\}/g,(i,s)=>{let c=n[s];return c==null?(o.push(s),""):(delete n[s],encodeURIComponent(String(c)))});if(o.length>0)throw new d(`${e.name} needs ${o.join(", ")} in --input`);return{path:r,remaining:n}}function Un(e){let t=new URLSearchParams;for(let[o,r]of Object.entries(e))r!=null&&t.set(o,typeof r=="string"?r:JSON.stringify(r));let n=t.toString();return n?`?${n}`:""}function ke(e,t){let n=Array.from({length:t.length+1},(o,r)=>r);for(let o=1;o<=e.length;o+=1){let r=[o];for(let i=1;i<=t.length;i+=1)r[i]=Math.min(r[i-1]+1,n[i]+1,n[i-1]+(e[o-1]===t[i-1]?0:1));n.splice(0,n.length,...r)}return n[t.length]}function Hn(e,t){let n=e.find(i=>i.name===t);if(n)return n;let o=e.filter(i=>i.operationId===t);if(o.length===1)return o[0];if(o.length>1)throw new d(`${t} matches more than one operation. Use one of: ${o.map(i=>i.name).join(", ")}.`);let r=e.map(i=>({candidate:i,distance:Math.min(ke(t,i.name),ke(t,i.operationId))})).sort((i,s)=>i.distance-s.distance||i.candidate.name.localeCompare(s.candidate.name)).slice(0,3).flatMap(({candidate:i})=>[i.name,i.operationId]);throw new d(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${r.join(", ")}.`)}async function Kn(e,t,n){if(!n)throw new d("call needs an operation name",{fix:'Run "hyperscale ops list" to list operations.'});let o=await Ze(e),r=Hn(o.operations,n),i=await dt(t),{path:s,remaining:c}=Ln(r,i),u={method:r.method},p=s;r.method==="GET"?p+=Un(c):(u.body=JSON.stringify(c),u.headers={"content-type":"application/json",...r.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:l,text:m}=await ae(e,p,u);if(l.ok){if(t["--json"]){let h=Bt(m),I=l.headers.get("x-request-id")??(h&&typeof h=="object"&&typeof h.requestId=="string"?h.requestId:null),g=l.headers.get("hyperscale-operation-id")??null,f=l.headers.get("hyperscale-receipt-id")??null,w=Qe(l.headers),b=I?y(I,[e.apiKey]):null,E=g?y(g,[e.apiKey]):null,F=f?y(f,[e.apiKey]):null,_=w?y(w,[e.apiKey]):null;k({status:l.status,data:h,requestId:b,operationId:E,receiptId:F,traceId:_});return}a(pt(m));return}throw ce(l,m,[e.apiKey])}async function dt(e){if(e["--input"]!==void 0&&e["--input-file"]!==void 0)throw new d("Use only one of --input and --input-file");if(e["--input"]!==void 0)return he(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await B(e["--input-file"],"utf8")}catch(n){throw new d(`Could not read ${e["--input-file"]}: ${n.message}`)}return he(t,"--input-file")}if(!process.stdin.isTTY){let t=await Dt();if(t.trim()!=="")return he(t,"stdin")}return{}}function he(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(o){throw new d(`${t} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new d(`${t} must be a JSON object`);return n}function pt(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function a(e){process.stdout.write(`${e}
148
+ `)}function k(e){a(JSON.stringify(e,null,2))}function Dn(e,t){let n=t.includes("--json"),o=[process.env.HYPERSCALE_API_KEY,process.env.HYPERSCALE_TOKEN].filter(Boolean),r=e instanceof d,i=r?e.message:"The command failed unexpectedly.",s=$(y(String(i),o)),c=s.length>1024?s.slice(0,1024):s,u=r?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials.",p=$(y(String(u),o)),l=r&&typeof e.shownOnce=="string"?$(y(e.shownOnce,o)):void 0;if(!n){let S=r?c:e?.stack??s,lt=r&&typeof e.fix=="string"?`
149
+ Fix: ${p}`:"",ht=l?`
150
+ Shown once Product API key: ${l}`:"";process.stderr.write(`${S}${lt}${ht}
151
+ `);return}let m=(typeof e?.structuredError?.code=="string"?e.structuredError.code:void 0)??(r&&typeof e.code=="string"?e.code:r?"user_error":"internal_error"),h=(typeof e?.structuredError?.message=="string"?e.structuredError.message:void 0)??(r?e.message:"The command failed unexpectedly."),I=$(y(String(h),o)),g=I.length>1024?I.slice(0,1024):I,f=(typeof e?.structuredError?.fix=="string"?e.structuredError.fix:void 0)??(r?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."),w=$(y(String(f),o)),b=w.length>1024?w.slice(0,1024):w,E=e?.structuredError?.details!==void 0?e.structuredError.details:r&&e.details!==void 0?e.details:void 0,F=E!==void 0?Q(E,o):void 0,_=r&&typeof e.status=="number"?e.status:void 0,M=S=>typeof S!="string"||S.trim().length===0?null:$(y(S.trim(),o)),z=r&&(e.requestId!==void 0||e.operationId!==void 0||e.receiptId!==void 0||e.traceId!==void 0),W=z?M(e.requestId):void 0,V=z?M(e.operationId):void 0,G=z?M(e.receiptId):void 0,X=z?M(e.traceId):void 0,_e=S=>({..._!==void 0?{status:_}:{},error:{code:m,message:g,...S!==void 0?{details:S}:{},fix:b},...W!==void 0?{requestId:W}:{},...V!==void 0?{operationId:V}:{},...G!==void 0?{receiptId:G}:{},...X!==void 0?{traceId:X}:{},...l?{shown_once:l}:{}}),Oe=S=>Buffer.byteLength(S,"utf8")>8192,N=_e(F),j=JSON.stringify(N);Oe(j)&&F!==void 0&&(N=_e("[Truncated]"),j=JSON.stringify(N)),Oe(j)&&(N={..._!==void 0?{status:_}:{},error:{code:m,message:g,fix:"[Truncated]"},...W!==void 0?{requestId:W}:{},...V!==void 0?{operationId:V}:{},...G!==void 0?{receiptId:G}:{},...X!==void 0?{traceId:X}:{}},j=JSON.stringify(N)),process.stderr.write(`${j}
152
+ `)}async function Jn(){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:o}=_t(e);if(n["--version"])return a(await Jn()),0;if(n["--help"]&&o.length>0)return process.stdout.write(je(o)),0;if(o[0]==="help"){let s=o.slice(1);return s.length===0?process.stdout.write(Ne):process.stdout.write(je(s)),0}if(o.length===0&&!n["--help"]){if(n["--json"])throw new d('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await De(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(Ne),0;let[r,...i]=o;if(r==="start")return await De(n,t),0;if(r==="auth"){if(i[0]==="login")await zt(n,t);else if(i[0]==="status")await Wt(n,t);else if(i[0]==="logout")await Vt(n,t);else throw new d('Auth subcommands are "login", "status", and "logout"',{fix:'Run "hyperscale help auth" to see valid subcommands.'});return 0}if(r==="blueprint"){let s=D(n,t);if(i[0]==="list")await Xt(s,n);else if(i[0]==="show")await Zt(s,n,i[1]);else throw new d('Blueprint subcommands are "list" and "show"',{fix:'Run "hyperscale help blueprint" to see valid subcommands.'});return 0}if(r==="product"){if(i[0]==="create")await un(n,t);else if(i[0]==="list")await dn(n,t);else if(i[0]==="show")await pn(n,t,i[1]);else if(i[0]==="select")await hn(n,t,i[1]);else if(i[0]==="actions")await $n(n,t,i[1]);else if(i[0]==="run")await xn(n,t,i[1]);else throw new d('Product subcommands are "create", "list", "show", "select", "actions", and "run"',{fix:'Run "hyperscale help product" to see valid subcommands.'});return 0}if(r==="compose"){if(i[0]==="check")await wn(n,t,i[1]);else if(i[0]==="plan")await gn(n,t,i[1]);else if(i[0]==="apply")await In(n,t,i[1]);else throw new d('Compose subcommands are "check", "plan", and "apply"',{fix:'Run "hyperscale help compose" to see valid subcommands.'});return 0}if(r==="key"){if(i[0]==="create")await Cn(n,t);else if(i[0]==="list")await Rn(n,t);else if(i[0]==="revoke")await _n(n,t,i[1]);else throw new d('Key subcommands are "create", "list", and "revoke"',{fix:'Run "hyperscale help key" to see valid subcommands.'});return 0}if(r==="whoami")return await On(n,t),0;if(r==="activity"){if(i[0]!=="list")throw new d('The only activity subcommand is "list"',{fix:'Run "hyperscale help activity" to see usage.'});return await jn(n,t),0}if(r==="ops"){if(i[0]!=="list")throw new d('The only ops subcommand is "list"',{fix:'Run "hyperscale help ops" to see usage.'});let s=n["--product"]?await ee(n,t):Le(n,t);return await Nn(s,n,i[1]),0}if(r==="call"){let s=n["--product"]?await ee(n,t):Le(n,t);return await Kn(s,n,i[0]),0}throw new d(`Unknown command: ${r}`,{fix:'Run "hyperscale --help" to list commands.'})}Bn(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{Dn(e,process.argv.slice(2)),process.exitCode=e instanceof d&&Number.isInteger(e.exitCode)?e.exitCode:1});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperscale0/cli",
3
- "version": "1.0.0-beta.20",
3
+ "version": "1.0.0-beta.22",
4
4
  "description": "Hyperscale CLI: compose Products, manage keys, and call Product operations.",
5
5
  "license": "LicenseRef-Hyperscale-Proprietary",
6
6
  "author": "Hyperscale LLC",
@@ -20,5 +20,5 @@
20
20
  "publishConfig": {
21
21
  "access": "public"
22
22
  },
23
- "gitHead": "0c57f89561fa9e95f81b4e9236951f6b24653e40"
23
+ "gitHead": "d9200bc6856f30811e8aa2888c44fdd045424120"
24
24
  }