phala 1.0.22 → 1.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{G as ge,H as Re,I as te,J as L,K as Le,M as Oe,N as Ke,O as Be,P as ze,Q as je,R as Ge,T as oe,U as He,V as qe,W as Ye,X as We,Y as O,a as r,b as y,c as T,d as V,e as N,f as fe,g as Ve,h as Ne,i as Ue}from"./chunk-YV2WYCLU.js";import{Command as Ao}from"commander";import Je from"chalk";var Ze=Je.hex("#cdfa50"),Xe=Ze(`
2
+ import{$ as Ke,L as ue,M as xe,N as Q,O as L,P as Fe,R as Me,S as Te,T as Ve,U as Ue,V as Ne,W as Re,Y as ee,Z as Le,_ as Oe,a as e,aa as ze,b as le,ba as O,c as R,d as B,e as pe,f as P,g as y,h as M,i as T,j as V,k as de,l as Ie,m as Pe,n as Ae}from"./chunk-YGMCMGJL.js";import{Command as Co}from"commander";import Be from"chalk";var Ge=Be.hex("#cdfa50"),je=Ge(`
3
3
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
4
4
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
5
5
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
@@ -21,7 +21,7 @@ import{G as ge,H as Re,I as te,J as L,K as Le,M as Oe,N as Ke,O as Be,P as ze,Q
21
21
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
22
22
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
23
23
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
24
- `),Mo=Ze(`
24
+ `),_o=Ge(`
25
25
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
26
26
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
27
27
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
@@ -43,30 +43,30 @@ import{G as ge,H as Re,I as te,J as L,K as Le,M as Oe,N as Ke,O as Be,P as ze,Q
43
43
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
44
44
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
45
45
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
46
- `),To=Je.cyan("PHALA TEE CLOUD CLI");import{Command as pt}from"commander";import{Command as nt}from"commander";import $ from"node:fs";import ye from"node:path";import K from"node:os";import ie from"node:crypto";var j=ye.join(K.homedir(),".phala-cloud"),G=ye.join(j,"api-key"),he=ye.join(j,"docker-credentials.json");function Qe(){if(!$.existsSync(j))try{$.mkdirSync(j,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${j}:`,t),t}}function er(){let t=[K.hostname(),K.platform(),K.arch(),K.cpus()[0]?.model||"",K.userInfo().username],e=ie.createHash("sha256");return e.update(t.join("|")),e.digest()}function ot(t){try{let e=er(),o=ie.randomBytes(16),i=ie.createCipheriv("aes-256-cbc",e.slice(0,32),o),n=i.update(t,"utf8","hex");return n+=i.final("hex"),o.toString("hex")+":"+n}catch(e){throw r.error("Encryption failed:",e),new Error("Failed to encrypt data")}}function it(t){try{let e=er(),o=t.split(":");if(o.length!==2)throw new Error("Invalid encrypted format");let i=Buffer.from(o[0],"hex"),n=o[1],a=ie.createDecipheriv("aes-256-cbc",e.slice(0,32),i),s=a.update(n,"hex","utf8");return s+=a.final("utf8"),s}catch(e){throw r.error("Decryption failed:",e),new Error("Failed to decrypt data")}}async function ve(t){Qe();try{let e=ot(t);$.writeFileSync(G,e,{mode:384})}catch(e){throw r.error("Failed to save API key:",e),e}}function ne(){try{if($.existsSync(G)){let t=$.readFileSync(G,"utf8").trim();return it(t)}return null}catch(t){return r.error("Failed to read API key:",t),null}}async function H(){try{$.existsSync(G)?($.unlinkSync(G),r.success("API key removed successfully.")):r.warn("No API key found to remove.")}catch(t){throw r.error("Failed to remove API key:",t),t}}async function Ce(t){Qe();try{$.writeFileSync(he,JSON.stringify(t,null,2),{mode:384}),r.success("Docker information saved successfully.")}catch(e){throw r.error("Failed to save Docker information:",e),e}}async function A(){try{if($.existsSync(he)){let t=$.readFileSync(he,"utf8");return JSON.parse(t)}return null}catch(t){return r.error("Failed to read Docker credentials:",t),null}}import st from"prompts";var rr=new nt().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async t=>{try{let e;if(!t)t=(await st({type:"password",name:"apiKey",message:"Enter your API key:",validate:async i=>{if(i.length===0)return"API key cannot be empty";try{if(await ve(i),e=await ge(),!e.username)return await H(),"Invalid API key"}catch{return"Invalid API key"}return!0}})).apiKey;else if(await ve(t),e=await ge(),!e.username)return await H(),"Invalid API key";r.success(`Welcome ${e.username}! API key validated and saved successfully`),r.break(),r.info(`Open in Web UI at ${y}/dashboard/`)}catch(e){r.error(`Failed to set API key: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as at}from"commander";var tr=new at().name("logout").description("Remove the stored API key").action(async()=>{try{await H(),r.success("API key removed successfully")}catch(t){r.error(`Failed to remove API key: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{createClient as ct}from"@phala/cloud";import{Command as mt}from"commander";import{safeGetCurrentUser as lt}from"@phala/cloud";var or=new mt().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async t=>{try{let e=t.debug||process.env.DEBUG?.toLowerCase()==="true",o=ne();if(!o){console.log('Not authenticated. Please set an API key with "phala auth login"');return}e&&r.debug(`Using API key: ${o.substring(0,5)}...`);try{let i=ct(),n=await lt(i);if(!n.success){r.error("Failed to get user information"),n.error&&r.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(t.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),e&&r.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var ir=new pt().name("auth").description("Authenticate with Phala Cloud").addCommand(rr).addCommand(tr).addCommand(or);import{Command as It}from"commander";import{Command as _t}from"commander";import{execa as ht}from"execa";import F from"node:fs";import W from"node:path";import yt from"handlebars";import{exec as vt,spawn as Ct}from"node:child_process";import{promisify as wt}from"node:util";import mr from"node:os";import dt from"inquirer";import we from"node:fs";import ke from"node:path";function U(t,e=process.cwd()){let o=ke.resolve(e,t);if(!we.existsSync(o))throw new Error(`File not found at ${o}`);return!0}async function D(t,e,o="file",i=process.cwd()){return(await dt.prompt([{type:"input",name:o,message:t,default:e,validate:a=>{let s=ke.resolve(i,a);return we.existsSync(s)?!0:`File not found at ${s}`}}]))[o]}function B(t,e){for(let o of t){let i=ke.join(process.cwd(),o);if(we.existsSync(i))return e?r.info(e.replace("{path}",i)):r.info(`File detected: ${i}`),o}}import*as h from"node:fs";import*as S from"node:path";import*as I from"node:os";import{execSync as x,spawn as ut}from"node:child_process";import*as _e from"node:net";var C={version:"0.5.3",baseUrl:"https://github.com/Dstack-TEE/dstack/releases/download/v0.5.3",installDir:S.join(I.homedir(),".phala-cloud","simulator"),defaultLogPath:S.join(I.homedir(),".phala-cloud","logs","dstack-simulator.log"),platforms:{darwin:{filename:"dstack-simulator-0.5.3-aarch64-apple-darwin.tgz",extractedFolder:"0.5.3",socketPath:S.join(I.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},linux:{filename:"dstack-simulator-0.5.3-x86_64-linux-musl.tgz",extractedFolder:"0.5.3",socketPath:S.join(I.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},win32:{filename:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc.tgz",extractedFolder:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc",socketPath:"127.0.0.1:8090"}}};function nr(){try{if(!h.existsSync(C.installDir))return!1;let t=I.platform();if(!C.platforms[t])throw new Error(`Unsupported platform: ${t}`);let e=S.join(C.installDir,C.platforms[t].extractedFolder);if(!h.existsSync(e))return!1;let i=S.join(e,t==="win32"?"dstack-simulator.exe":"dstack-simulator");return h.existsSync(i)}catch(t){return r.error("Error checking if simulator is installed:",t),!1}}function q(){let t=I.platform();if(!C.platforms[t])throw new Error(`Unsupported platform: ${t}. Only darwin, linux, and win32 are supported.`);return t}async function sr(t){let e=o=>{r.info(o),t&&t(o)};try{let o=q(),i=C.platforms[o];if(o==="win32"){try{x("tar --version",{stdio:"ignore"})}catch{throw new Error("Windows 10 build 17063 or later is required (includes tar command). Please update your Windows version.")}throw new Error("Windows platform is currently not supported. Support will be added in a future release.")}h.existsSync(C.installDir)||(r.info(`Creating installation directory at ${C.installDir}`),h.mkdirSync(C.installDir,{recursive:!0})),process.chdir(C.installDir);let n=`${C.baseUrl}/${i.filename}`;r.info(`Downloading simulator from ${n}`),x(`wget ${n}`,{stdio:"inherit"});let a=S.join(C.installDir,i.extractedFolder);h.existsSync(a)||h.mkdirSync(a,{recursive:!0}),r.info(`Extracting ${i.filename} to ${a}`);let s=`tar -xvf "${i.filename}" -C "${a}" --strip-components=1`;r.debug(`Running: ${s}`);try{x(s,{stdio:"inherit"}),h.unlinkSync(i.filename)}catch(c){throw r.error(`Failed to extract ${i.filename}:`,c),new Error("Failed to extract simulator archive. Make sure you have sufficient permissions and disk space.")}r.success("Simulator installation completed successfully")}catch(o){throw r.error("Error installing simulator:",o),new Error(`Failed to install simulator: ${o}`)}}var Se=()=>S.join(I.tmpdir(),"dstack-simulator.pid");function ft(t){return Buffer.byteLength(t,"utf8")>104}function se(){try{let t=Se();if(h.existsSync(t)){let e=parseInt(h.readFileSync(t,"utf-8").trim(),10);try{return process.kill(e,0),e}catch{h.unlinkSync(t)}}return null}catch(t){return r.warn("Error checking simulator PID:",t),null}}function gt(t,e){try{let o=Se();e&&r.info(`Saving simulator PID ${t} to: ${o}`),h.writeFileSync(o,t.toString(),"utf-8")}catch(o){r.warn("Failed to save simulator PID:",o)}}async function ar(t={}){try{let e=q(),o=C.platforms[e],i=S.join(C.installDir,o.extractedFolder),n=se();if(n)throw new Error(`Simulator is already running with PID: ${n}`);if(e!=="win32"&&ft(o.socketPath))throw new Error(`Socket path is too long (${o.socketPath.length} chars, max 104): ${o.socketPath}`);if(e!=="win32"&&h.existsSync(o.socketPath)){r.warn(`Removing existing socket file: ${o.socketPath}`);try{h.unlinkSync(o.socketPath)}catch(m){r.warn(`Failed to remove existing socket file: ${m}`)}}process.chdir(i);let a=e==="win32"?"dstack-simulator.exe":"./dstack-simulator";t.verbose&&e!=="win32"&&r.info(`Using socket path: ${o.socketPath}`);let s={background:t.background??!0,logToFile:t.logToFile??!0,logFilePath:t.logFilePath??C.defaultLogPath};if(s.logToFile){let m=S.dirname(s.logFilePath);h.existsSync(m)||h.mkdirSync(m,{recursive:!0}),t.verbose&&r.info(`Simulator logs will be written to: ${s.logFilePath}`)}t.verbose&&r.info(`Starting simulator with: ${a}`);let c=s.logToFile?["ignore",h.openSync(s.logFilePath,"a"),h.openSync(s.logFilePath,"a")]:"inherit",l=ut(a,[],{stdio:c,shell:e==="win32",detached:s.background});if(s.logToFile&&Array.isArray(c)&&(typeof c[1]=="number"&&h.closeSync(c[1]),typeof c[2]=="number"&&h.closeSync(c[2])),s.logToFile){let d=`
46
+ `),So=Be.cyan("PHALA TEE CLOUD CLI");import{Command as et}from"commander";import{Command as Yr}from"commander";import Wr from"prompts";var He=new Yr().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async o=>{try{let r;if(!o)o=(await Wr({type:"password",name:"apiKey",message:"Enter your API key:",validate:async i=>{if(i.length===0)return"API key cannot be empty";try{if(await le(i),r=await ue(),!r.username)throw await B(),new Error("Invalid API key")}catch{throw new Error("Invalid API key")}return!0}})).apiKey;else if(await le(o),r=await ue(o),!r.username)throw await B(),new Error("Invalid API key");e.success(`Welcome ${r.username}! API key validated and saved successfully`),e.break(),e.info(`Open in Web UI at ${y}/dashboard/`)}catch(r){e.error(`Failed to set API key: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Jr}from"commander";var qe=new Jr().name("logout").description("Remove the stored API key").action(async()=>{try{await B(),e.success("API key removed successfully")}catch(o){e.error(`Failed to remove API key: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{createClient as Zr}from"@phala/cloud";import{Command as Xr}from"commander";import{safeGetCurrentUser as Qr}from"@phala/cloud";var Ye=new Xr().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async o=>{try{let r=o.debug||process.env.DEBUG?.toLowerCase()==="true",t=R();if(!t){console.log('Not authenticated. Please set an API key with "phala auth login"');return}r&&e.debug(`Using API key: ${t.substring(0,5)}...`);try{let i=Zr({apiKey:t}),n=await Qr(i);if(!n.success){e.error("Failed to get user information"),n.error&&e.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(o.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),r&&e.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(r){e.error(`Failed to check authentication status: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});var We=new et().name("auth").description("Authenticate with Phala Cloud").addCommand(He).addCommand(qe).addCommand(Ye);import{Command as yt}from"commander";import{Command as pt}from"commander";import{execa as nt}from"execa";import x from"node:fs";import H from"node:path";import st from"handlebars";import{exec as at,spawn as ct}from"node:child_process";import{promisify as mt}from"node:util";import er from"node:os";import rt from"inquirer";import fe from"node:fs";import ge from"node:path";function U(o,r=process.cwd()){let t=ge.resolve(r,o);if(!fe.existsSync(t))throw new Error(`File not found at ${t}`);return!0}async function $(o,r,t="file",i=process.cwd()){return(await rt.prompt([{type:"input",name:t,message:o,default:r,validate:a=>{let s=ge.resolve(i,a);return fe.existsSync(s)?!0:`File not found at ${s}`}}]))[t]}function K(o,r){for(let t of o){let i=ge.join(process.cwd(),t);if(fe.existsSync(i))return r?e.info(r.replace("{path}",i)):e.info(`File detected: ${i}`),t}}import*as h from"node:fs";import*as S from"node:path";import*as D from"node:os";import{execSync as A,spawn as tt}from"node:child_process";import*as he from"node:net";var C={version:"0.5.3",baseUrl:"https://github.com/Dstack-TEE/dstack/releases/download/v0.5.3",installDir:S.join(D.homedir(),".phala-cloud","simulator"),defaultLogPath:S.join(D.homedir(),".phala-cloud","logs","dstack-simulator.log"),platforms:{darwin:{filename:"dstack-simulator-0.5.3-aarch64-apple-darwin.tgz",extractedFolder:"0.5.3",socketPath:S.join(D.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},linux:{filename:"dstack-simulator-0.5.3-x86_64-linux-musl.tgz",extractedFolder:"0.5.3",socketPath:S.join(D.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},win32:{filename:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc.tgz",extractedFolder:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc",socketPath:"127.0.0.1:8090"}}};function Je(){try{if(!h.existsSync(C.installDir))return!1;let o=D.platform();if(!C.platforms[o])throw new Error(`Unsupported platform: ${o}`);let r=S.join(C.installDir,C.platforms[o].extractedFolder);if(!h.existsSync(r))return!1;let i=S.join(r,o==="win32"?"dstack-simulator.exe":"dstack-simulator");return h.existsSync(i)}catch(o){return e.error("Error checking if simulator is installed:",o),!1}}function G(){let o=D.platform();if(!C.platforms[o])throw new Error(`Unsupported platform: ${o}. Only darwin, linux, and win32 are supported.`);return o}async function Ze(o){let r=t=>{e.info(t),o&&o(t)};try{let t=G(),i=C.platforms[t];if(t==="win32"){try{A("tar --version",{stdio:"ignore"})}catch{throw new Error("Windows 10 build 17063 or later is required (includes tar command). Please update your Windows version.")}throw new Error("Windows platform is currently not supported. Support will be added in a future release.")}h.existsSync(C.installDir)||(e.info(`Creating installation directory at ${C.installDir}`),h.mkdirSync(C.installDir,{recursive:!0})),process.chdir(C.installDir);let n=`${C.baseUrl}/${i.filename}`;e.info(`Downloading simulator from ${n}`),A(`wget ${n}`,{stdio:"inherit"});let a=S.join(C.installDir,i.extractedFolder);h.existsSync(a)||h.mkdirSync(a,{recursive:!0}),e.info(`Extracting ${i.filename} to ${a}`);let s=`tar -xvf "${i.filename}" -C "${a}" --strip-components=1`;e.debug(`Running: ${s}`);try{A(s,{stdio:"inherit"}),h.unlinkSync(i.filename)}catch(c){throw e.error(`Failed to extract ${i.filename}:`,c),new Error("Failed to extract simulator archive. Make sure you have sufficient permissions and disk space.")}e.success("Simulator installation completed successfully")}catch(t){throw e.error("Error installing simulator:",t),new Error(`Failed to install simulator: ${t}`)}}var ye=()=>S.join(D.tmpdir(),"dstack-simulator.pid");function ot(o){return Buffer.byteLength(o,"utf8")>104}function re(){try{let o=ye();if(h.existsSync(o)){let r=parseInt(h.readFileSync(o,"utf-8").trim(),10);try{return process.kill(r,0),r}catch{h.unlinkSync(o)}}return null}catch(o){return e.warn("Error checking simulator PID:",o),null}}function it(o,r){try{let t=ye();r&&e.info(`Saving simulator PID ${o} to: ${t}`),h.writeFileSync(t,o.toString(),"utf-8")}catch(t){e.warn("Failed to save simulator PID:",t)}}async function Xe(o={}){try{let r=G(),t=C.platforms[r],i=S.join(C.installDir,t.extractedFolder),n=re();if(n)throw new Error(`Simulator is already running with PID: ${n}`);if(r!=="win32"&&ot(t.socketPath))throw new Error(`Socket path is too long (${t.socketPath.length} chars, max 104): ${t.socketPath}`);if(r!=="win32"&&h.existsSync(t.socketPath)){e.warn(`Removing existing socket file: ${t.socketPath}`);try{h.unlinkSync(t.socketPath)}catch(m){e.warn(`Failed to remove existing socket file: ${m}`)}}process.chdir(i);let a=r==="win32"?"dstack-simulator.exe":"./dstack-simulator";o.verbose&&r!=="win32"&&e.info(`Using socket path: ${t.socketPath}`);let s={background:o.background??!0,logToFile:o.logToFile??!0,logFilePath:o.logFilePath??C.defaultLogPath};if(s.logToFile){let m=S.dirname(s.logFilePath);h.existsSync(m)||h.mkdirSync(m,{recursive:!0}),o.verbose&&e.info(`Simulator logs will be written to: ${s.logFilePath}`)}o.verbose&&e.info(`Starting simulator with: ${a}`);let c=s.logToFile?["ignore",h.openSync(s.logFilePath,"a"),h.openSync(s.logFilePath,"a")]:"inherit",l=tt(a,[],{stdio:c,shell:r==="win32",detached:s.background});if(s.logToFile&&Array.isArray(c)&&(typeof c[1]=="number"&&h.closeSync(c[1]),typeof c[2]=="number"&&h.closeSync(c[2])),s.logToFile){let d=`
47
47
  === Simulator started at ${new Date().toISOString()} ===
48
48
  Command: ${a}
49
49
 
50
- `;h.appendFileSync(s.logFilePath,d)}return l.pid&&gt(l.pid,t.verbose),s.background&&(l.unref(),t.verbose&&r.success("Simulator is running in the background")),await Ee(),l}catch(e){throw r.error("Error running simulator:",e),new Error(`Failed to run simulator: ${e}`)}}async function Y(){try{let t=q(),e=C.platforms[t];if(t==="darwin"||t==="linux"){let o=e.socketPath;return h.existsSync(o)?new Promise(i=>{let n=_e.createConnection({path:o}).on("connect",()=>{n.end(),i(!0)}).on("error",()=>{i(!1)});setTimeout(()=>{n.end(),i(!1)},1e3)}):!1}if(t==="win32"){let o="127.0.0.1";return new Promise(n=>{let a=_e.createConnection({host:o,port:8090}).on("connect",()=>{a.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{a.end(),n(!1)},1e3)})}return!1}catch(t){return r.error("Error checking if simulator is running:",t),!1}}async function cr(){try{let t=se();if(!await Y()&&!t)return r.info("Simulator is not running"),!0;let o=q(),i=!1;if(o==="win32")try{t?(r.info(`Stopping simulator process (PID: ${t})...`),process.kill(t,"SIGTERM")):x("taskkill /F /IM dstack-simulator.exe",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return r.error("Failed to stop simulator:",a),!1;i=!0}else try{t?(r.info(`Stopping simulator process (PID: ${t})...`),process.kill(t,"SIGTERM")):x("pkill -f dstack-simulator",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return r.error("Failed to stop simulator:",a),!1;i=!0}let n=Se();if(h.existsSync(n))try{h.unlinkSync(n)}catch(a){r.warn("Failed to remove PID file:",a)}return await R(),i&&r.success("Simulator stopped successfully"),i}catch(t){return r.error("Error stopping simulator:",t),!1}}function ae(){let t=q(),e=C.platforms[t];return t==="win32"?"http://127.0.0.1:8090":`${e.socketPath||"/tmp/dstack.sock"}`}async function Ee(t){try{let e=ae(),o=t||e;await x(`export DSTACK_SIMULATOR_ENDPOINT=${o}`);let i=o.replace(/dstack\.sock$/,"tappd.sock");return await x(`export TAPPD_SIMULATOR_ENDPOINT=${i}`),r.success("Setting environment for current process..."),r.success(` DSTACK_SIMULATOR_ENDPOINT=${o}`),r.success(` TAPPD_SIMULATOR_ENDPOINT=${i}`),o}catch(e){throw r.error("Error setting simulator endpoint environment variable:",e),new Error(`Failed to set simulator endpoint: ${e}`)}}async function R(){try{return await x("unset DSTACK_SIMULATOR_ENDPOINT"),await x("unset TAPPD_SIMULATOR_ENDPOINT"),r.debug("Deleted simulator endpoint environment variables from current process"),!0}catch(t){return r.warn("Error while unsetting simulator endpoint environment variables:",t),!1}}var J=wt(vt),lr=".phala-cloud/logs",kt=".phala-cloud/compose",pr=10,E=class{username;image;registry;constructor(e,o,i){this.image=e,this.username=o||"",this.registry=i||""}ensureLogsDir(){let e=W.resolve(lr);F.existsSync(e)||F.mkdirSync(e,{recursive:!0})}getLogFilePath(e,o){let i=new Date().toISOString().replace(/[:.]/g,"-");return W.resolve(lr,`${o||this.image}-${e}-${i}.log`)}getSystemArchitecture(){let e=mr.arch();switch(e){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return e}}spawnProcess(e,o,i,n){return new Promise((a,s)=>{let c=Ct(e,o);this.ensureLogsDir();let l=this.getLogFilePath(i,n),m=F.createWriteStream(l,{flags:"a"}),d=[],g=(p,u=!1)=>{let v=p.toString().split(`
51
- `);m.write(p);for(let f of v)if(f.trim()){d.push(f),d.length>pr&&d.shift(),console.clear(),console.log(`Latest ${pr} lines (full log at ${l}):`),console.log("-".repeat(50));for(let P of d)u?console.error(P):console.log(P)}};c.stdout.on("data",p=>g(p)),c.stderr.on("data",p=>g(p,!0)),c.on("close",p=>{m.end(),p===0?(console.log(`
52
- Operation completed. Full log available at: ${l}`),a()):s(new Error(`Process exited with code ${p}. Check log file: ${l}`))}),c.on("error",p=>{m.end(),s(p)})})}setCredentials(e,o){this.username=e,o&&(this.registry=o)}async buildImage(e,o){try{let i=this.getSystemArchitecture(),n=`${this.username}/${this.image}:${o}`,a=r.startSpinner(`Building Docker image ${this.username}/${this.image}:${o}`);U(e);let s=["build","-t",n,"-f",e];return i==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),s.push("--platform","linux/amd64")),s.push("."),await this.spawnProcess("docker",s,"build",this.image),a.stop(!0,`Docker image ${n} built successfully`),!0}catch(i){return r.error(`Failed to build Docker image: ${i instanceof Error?i.message:String(i)}`),!1}}async pushImage(e){try{let o=r.startSpinner(`Pushing Docker image ${e} to Docker Hub`);if(!await A())throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let n=e;return console.log(`Pushing image ${n} to Docker Hub...`),await this.spawnProcess("docker",["push",n],"push",e.replace(/.*\/+([\w-]+):.*$/g,"$1")),o.stop(!0,`Docker image ${n} pushed successfully`),!0}catch(o){return r.error(`Failed to push Docker image: ${o instanceof Error?o.message:String(o)}`),!1}}async login(e,o,i){try{let n=r.startSpinner(`Logging in to Docker Hub as ${e}`);if(await this.checkLogin())return n.stop(!0,"Already logged in to Docker Hub"),this.setCredentials(e,i),!0;if(!o)throw n.stop(!1),new Error("Password is required for Docker login");try{await ht("docker",["login",...i?[i]:[],"-u",e,"--password-stdin"],{input:o,timeout:1e4})}catch(s){throw s.timedOut?(n.stop(!1),new Error("Docker login timed out. Please check your credentials and try again.")):s}return n.stop(!0,"Logged in to Docker Hub successfully"),this.setCredentials(e,i),!0}catch(n){return r.error(`Failed to login to Docker Hub: ${n instanceof Error?n.message:String(n)}`),!1}}async checkLogin(){try{let e=mr.homedir(),o=W.join(e,".docker","config.json");if(!F.existsSync(o))return!1;let i=JSON.parse(F.readFileSync(o,"utf-8"));return!!(i?.auths&&Object.keys(i.auths).length>0)}catch(e){return r.debug(`Docker login check failed: ${e instanceof Error?e.message:String(e)}`),!1}}async buildComposeFile(e,o,i){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let n=i==="eliza"?Ve:Ne,a=Ue.parse({template:n}),s=W.resolve(kt);F.existsSync(s)||(r.info(`Creating directory: ${s}`),F.mkdirSync(s,{recursive:!0}));let c=[];o&&(c=F.readFileSync(o,"utf-8").split(`
53
- `).filter(u=>u&&!u.startsWith("#")).map(u=>{let v=u.indexOf("#");return v>0&&(u=u.substring(0,v).trim()),u.trim()}).filter(u=>u.includes("=")).map(u=>{let[v,f]=u.split("=",2),P=v.trim();return(f?f.trim():"")===""?null:`${P}=${P}`}).filter(Boolean));let l=e,d=yt.compile(a.template,{noEscape:!0})({imageName:l,envVars:c.map(p=>p.replace(/=.*/,`=\${${p.split("=")[0]}}`))}),g=W.join(s,`${e.replace(/.*\/+([\w-]+):.*$/g,"$1")}-tee-compose.yaml`);return F.writeFileSync(g,d),r.success(`Backup of docker compose file created at: ${g}`),g}async runComposeLocally(e,o){try{let i=r.startSpinner(`Running Docker Compose file at ${e}`);U(e);let n=["-f",e,"up","-d"];return o&&(U(o),n.splice(2,0,"--env-file",o)),await J(`docker compose ${n.join(" ")}`),i.stop(!0,"Docker Compose file running successfully"),!0}catch(i){return r.error(`Failed to run Docker Compose file: ${i instanceof Error?i.message:String(i)}`),!1}}async runSimulator(e,o){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await J(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:i}=await J(`docker run -d --name tee-simulator --rm -p ${o}:${o} ${e}`),n=i.trim();return r.success(`TEE simulator running successfully. Container ID: ${n}`),r.break(),r.break(),r.info("Useful commands:"),r.info(`- View logs: docker logs -f ${n}`),r.info(`- Stop simulator: docker stop ${n}`),Ee(`http://localhost:${o}`),!0}catch(i){return r.error(`Failed to run TEE simulator: ${i instanceof Error?i.message:String(i)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await J("docker stop tee-simulator"),await R(),e.stop(!0,"TEE simulator stopped successfully"),!0}catch(e){return r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),!1}}static async listLocalImages(){try{let{stdout:e}=await J('docker images --format "{{.Repository}}:{{.Tag}}"'),i=(await A())?.username;return e.split(`
54
- `).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${i}/`)).map(a=>({imageName:a}))}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import dr from"prompts";var ur=new _t().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async t=>{try{let e=t.username,o=t.password,i=t.registry;if(!e){r.info("First we need your Docker Hub username to check if you are already logged in.");let c=await dr({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:l=>l.length>0?!0:"Username cannot be empty"});c.username||(r.error("Username is required"),process.exit(1)),e=c.username}let n=new E("",e,i);if(await n.login(e)){r.success(`${e} is logged in to Docker Hub`),await Ce({username:e,registry:i||null});return}if(!o){let c=await dr({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:l=>l.length>0?!0:"Password cannot be empty"});c.password||(r.error("Password is required"),process.exit(1)),o=c.password}await n.login(e,o,i)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await Ce({username:e,registry:i||null}),r.success("Logged in to Docker Hub successfully")}catch(e){r.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as St}from"commander";import fr from"node:path";import gr from"inquirer";import Et from"node:fs";var hr=new St().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async t=>{try{let e=await A();if(e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let s=await gr.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);t.image=s.image}if(!t.tag){let s=await gr.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);t.tag=s.tag}let o=fr.resolve(process.cwd(),t.file);Et.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await D("Enter the path to your Dockerfile:","Dockerfile","file"));let i=fr.resolve(process.cwd(),t.file);await new E(t.image,e.username,e.registry).buildImage(i,t.tag)||(r.error("Failed to build Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){r.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as bt}from"commander";import $t from"inquirer";var yr=new bt().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Full image name (e.g. username/image:tag)").action(async t=>{try{let e=await A();e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image;if(!o){let a=await E.listLocalImages();if(a.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let s=Array.from(new Set(a.map(l=>l.imageName))),{selectedImage:c}=await $t.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:s}]);o=c}}await new E("",e.username,e.registry).pushImage(o)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${o} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Dt}from"commander";import Z from"inquirer";import X from"node:fs";import ce from"node:path";var vr=new Dt().name("generate").description("Generate a Docker Compose file").option("-i, --image <imageName>","Docker image name to use in the compose file (e.g. phala/phala-cloud)").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").action(async t=>{try{let e=await A();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let o=t.image;if(!o){let c=await E.listLocalImages();if(c.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let l=Array.from(new Set(c.map(d=>d.imageName))),{selectedImage:m}=await Z.prompt([{type:"list",name:"selectedImage",message:"Select an image to use in the compose file:",choices:l}]);o=m}}let i=t.envFile;if(i)try{U(i)}catch{r.error(`File not found: ${i}`),process.exit(1)}else{let c=ce.join(process.cwd(),".env");if(X.existsSync(c)){let{useDefault:m}=await Z.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);m&&(i=c)}if(!i){let{envPath:m}=await Z.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:d=>{try{return U(d),!0}catch{return`File not found: ${d}`}}}]);i=m}}let n=t.output;if(!n&&(n=ce.join(process.cwd(),"docker-compose.yml"),X.existsSync(n))){let{confirmOverwrite:c}=await Z.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${n} already exists. Overwrite?`,default:!1}]);if(!c){let{customPath:l}=await Z.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:ce.join(process.cwd(),"docker-generated-compose.yml")}]);n=l}}let a=new E("",e.username,e.registry);i?r.info(`Generating Docker Compose file for ${o} using env file: ${i}`):r.info(`Generating Docker Compose file for ${o} without env file`);let s=await a.buildComposeFile(o,i,t.template);if(s!==n){let c=ce.dirname(n);X.existsSync(c)||(r.info(`Creating directory: ${c}`),X.mkdirSync(c,{recursive:!0})),X.copyFileSync(s,n)}r.success(`Docker Compose file generated successfully: ${n}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Cr=new It().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(ur).addCommand(hr).addCommand(yr).addCommand(vr);import{Command as xt}from"commander";import{Command as Pt}from"commander";var wr=new Pt().name("start").description("Start the TEE simulator").option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-v, --verbose","Enable verbose output",!1).action(async t=>{try{if(nr()||await sr(),await Y()){r.success("TEE simulator is already running");return}let o=await ar({verbose:t.verbose});r.success("TEE simulator started successfully")}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as At}from"commander";var kr=new At().name("stop").description("Stop the TEE simulator").action(async()=>{try{await cr()||(r.error("Failed to stop TEE simulator"),process.exit(1)),r.success("TEE simulator stopped successfully")}catch(t){r.error(`Failed to stop TEE simulator: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var be=new xt().name("simulator").description("TEE simulator commands").addCommand(wr).addCommand(kr);be.action(async()=>{try{let t=await Y(),e=se();if(t&&e){let o=ae(),i=ae(),n=i.replace(/dstack\.sock$/,"tappd.sock");console.log(`\u2713 TEE simulator is running (PID: ${e})`),console.log(`
50
+ `;h.appendFileSync(s.logFilePath,d)}return l.pid&&it(l.pid,o.verbose),s.background&&(l.unref(),o.verbose&&e.success("Simulator is running in the background")),await ve(),l}catch(r){throw e.error("Error running simulator:",r),new Error(`Failed to run simulator: ${r}`)}}async function j(){try{let o=G(),r=C.platforms[o];if(o==="darwin"||o==="linux"){let t=r.socketPath;return h.existsSync(t)?new Promise(i=>{let n=he.createConnection({path:t}).on("connect",()=>{n.end(),i(!0)}).on("error",()=>{i(!1)});setTimeout(()=>{n.end(),i(!1)},1e3)}):!1}if(o==="win32"){let t="127.0.0.1";return new Promise(n=>{let a=he.createConnection({host:t,port:8090}).on("connect",()=>{a.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{a.end(),n(!1)},1e3)})}return!1}catch(o){return e.error("Error checking if simulator is running:",o),!1}}async function Qe(){try{let o=re();if(!await j()&&!o)return e.info("Simulator is not running"),!0;let t=G(),i=!1;if(t==="win32")try{o?(e.info(`Stopping simulator process (PID: ${o})...`),process.kill(o,"SIGTERM")):A("taskkill /F /IM dstack-simulator.exe",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return e.error("Failed to stop simulator:",a),!1;i=!0}else try{o?(e.info(`Stopping simulator process (PID: ${o})...`),process.kill(o,"SIGTERM")):A("pkill -f dstack-simulator",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return e.error("Failed to stop simulator:",a),!1;i=!0}let n=ye();if(h.existsSync(n))try{h.unlinkSync(n)}catch(a){e.warn("Failed to remove PID file:",a)}return await N(),i&&e.success("Simulator stopped successfully"),i}catch(o){return e.error("Error stopping simulator:",o),!1}}function te(){let o=G(),r=C.platforms[o];return o==="win32"?"http://127.0.0.1:8090":`${r.socketPath||"/tmp/dstack.sock"}`}async function ve(o){try{let r=te(),t=o||r;await A(`export DSTACK_SIMULATOR_ENDPOINT=${t}`);let i=t.replace(/dstack\.sock$/,"tappd.sock");return await A(`export TAPPD_SIMULATOR_ENDPOINT=${i}`),e.success("Setting environment for current process..."),e.success(` DSTACK_SIMULATOR_ENDPOINT=${t}`),e.success(` TAPPD_SIMULATOR_ENDPOINT=${i}`),t}catch(r){throw e.error("Error setting simulator endpoint environment variable:",r),new Error(`Failed to set simulator endpoint: ${r}`)}}async function N(){try{return await A("unset DSTACK_SIMULATOR_ENDPOINT"),await A("unset TAPPD_SIMULATOR_ENDPOINT"),e.debug("Deleted simulator endpoint environment variables from current process"),!0}catch(o){return e.warn("Error while unsetting simulator endpoint environment variables:",o),!1}}var q=mt(at),rr=".phala-cloud/logs",lt=".phala-cloud/compose",tr=10,b=class{username;image;registry;constructor(r,t,i){this.image=r,this.username=t||"",this.registry=i||""}ensureLogsDir(){let r=H.resolve(rr);x.existsSync(r)||x.mkdirSync(r,{recursive:!0})}getLogFilePath(r,t){let i=new Date().toISOString().replace(/[:.]/g,"-");return H.resolve(rr,`${t||this.image}-${r}-${i}.log`)}getSystemArchitecture(){let r=er.arch();switch(r){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return r}}spawnProcess(r,t,i,n){return new Promise((a,s)=>{let c=ct(r,t);this.ensureLogsDir();let l=this.getLogFilePath(i,n),m=x.createWriteStream(l,{flags:"a"}),d=[],g=(p,u=!1)=>{let v=p.toString().split(`
51
+ `);m.write(p);for(let f of v)if(f.trim()){d.push(f),d.length>tr&&d.shift(),console.clear(),console.log(`Latest ${tr} lines (full log at ${l}):`),console.log("-".repeat(50));for(let I of d)u?console.error(I):console.log(I)}};c.stdout.on("data",p=>g(p)),c.stderr.on("data",p=>g(p,!0)),c.on("close",p=>{m.end(),p===0?(console.log(`
52
+ Operation completed. Full log available at: ${l}`),a()):s(new Error(`Process exited with code ${p}. Check log file: ${l}`))}),c.on("error",p=>{m.end(),s(p)})})}setCredentials(r,t){this.username=r,t&&(this.registry=t)}async buildImage(r,t){try{let i=this.getSystemArchitecture(),n=`${this.username}/${this.image}:${t}`,a=e.startSpinner(`Building Docker image ${this.username}/${this.image}:${t}`);U(r);let s=["build","-t",n,"-f",r];return i==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),s.push("--platform","linux/amd64")),s.push("."),await this.spawnProcess("docker",s,"build",this.image),a.stop(!0,`Docker image ${n} built successfully`),!0}catch(i){return e.error(`Failed to build Docker image: ${i instanceof Error?i.message:String(i)}`),!1}}async pushImage(r){try{let t=e.startSpinner(`Pushing Docker image ${r} to Docker Hub`);if(!await P())throw t.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let n=r;return console.log(`Pushing image ${n} to Docker Hub...`),await this.spawnProcess("docker",["push",n],"push",r.replace(/.*\/+([\w-]+):.*$/g,"$1")),t.stop(!0,`Docker image ${n} pushed successfully`),!0}catch(t){return e.error(`Failed to push Docker image: ${t instanceof Error?t.message:String(t)}`),!1}}async login(r,t,i){try{let n=e.startSpinner(`Logging in to Docker Hub as ${r}`);if(await this.checkLogin())return n.stop(!0,"Already logged in to Docker Hub"),this.setCredentials(r,i),!0;if(!t)throw n.stop(!1),new Error("Password is required for Docker login");try{await nt("docker",["login",...i?[i]:[],"-u",r,"--password-stdin"],{input:t,timeout:1e4})}catch(s){throw s.timedOut?(n.stop(!1),new Error("Docker login timed out. Please check your credentials and try again.")):s}return n.stop(!0,"Logged in to Docker Hub successfully"),this.setCredentials(r,i),!0}catch(n){return e.error(`Failed to login to Docker Hub: ${n instanceof Error?n.message:String(n)}`),!1}}async checkLogin(){try{let r=er.homedir(),t=H.join(r,".docker","config.json");if(!x.existsSync(t))return!1;let i=JSON.parse(x.readFileSync(t,"utf-8"));return!!(i?.auths&&Object.keys(i.auths).length>0)}catch(r){return e.debug(`Docker login check failed: ${r instanceof Error?r.message:String(r)}`),!1}}async buildComposeFile(r,t,i){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let n=i==="eliza"?Ie:Pe,a=Ae.parse({template:n}),s=H.resolve(lt);x.existsSync(s)||(e.info(`Creating directory: ${s}`),x.mkdirSync(s,{recursive:!0}));let c=[];t&&(c=x.readFileSync(t,"utf-8").split(`
53
+ `).filter(u=>u&&!u.startsWith("#")).map(u=>{let v=u.indexOf("#");return v>0&&(u=u.substring(0,v).trim()),u.trim()}).filter(u=>u.includes("=")).map(u=>{let[v,f]=u.split("=",2),I=v.trim();return(f?f.trim():"")===""?null:`${I}=${I}`}).filter(Boolean));let l=r,d=st.compile(a.template,{noEscape:!0})({imageName:l,envVars:c.map(p=>p.replace(/=.*/,`=\${${p.split("=")[0]}}`))}),g=H.join(s,`${r.replace(/.*\/+([\w-]+):.*$/g,"$1")}-tee-compose.yaml`);return x.writeFileSync(g,d),e.success(`Backup of docker compose file created at: ${g}`),g}async runComposeLocally(r,t){try{let i=e.startSpinner(`Running Docker Compose file at ${r}`);U(r);let n=["-f",r,"up","-d"];return t&&(U(t),n.splice(2,0,"--env-file",t)),await q(`docker compose ${n.join(" ")}`),i.stop(!0,"Docker Compose file running successfully"),!0}catch(i){return e.error(`Failed to run Docker Compose file: ${i instanceof Error?i.message:String(i)}`),!1}}async runSimulator(r,t){try{e.info(`Running TEE simulator with image ${r}`),e.info("Pulling latest simulator image..."),await q(`docker pull ${r}`),e.info("Starting simulator in background...");let{stdout:i}=await q(`docker run -d --name tee-simulator --rm -p ${t}:${t} ${r}`),n=i.trim();return e.success(`TEE simulator running successfully. Container ID: ${n}`),e.break(),e.break(),e.info("Useful commands:"),e.info(`- View logs: docker logs -f ${n}`),e.info(`- Stop simulator: docker stop ${n}`),ve(`http://localhost:${t}`),!0}catch(i){return e.error(`Failed to run TEE simulator: ${i instanceof Error?i.message:String(i)}`),!1}}async stopSimulator(){try{let r=e.startSpinner("Stopping TEE simulator...");return await q("docker stop tee-simulator"),await N(),r.stop(!0,"TEE simulator stopped successfully"),!0}catch(r){return e.error(`Failed to stop TEE simulator: ${r instanceof Error?r.message:String(r)}`),!1}}static async listLocalImages(){try{let{stdout:r}=await q('docker images --format "{{.Repository}}:{{.Tag}}"'),i=(await P())?.username;return r.split(`
54
+ `).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${i}/`)).map(a=>({imageName:a}))}catch(r){return e.error(`Failed to list local Docker images: ${r instanceof Error?r.message:String(r)}`),[]}}};import or from"prompts";var ir=new pt().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async o=>{try{let r=o.username,t=o.password,i=o.registry;if(!r){e.info("First we need your Docker Hub username to check if you are already logged in.");let c=await or({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:l=>l.length>0?!0:"Username cannot be empty"});c.username||(e.error("Username is required"),process.exit(1)),r=c.username}let n=new b("",r,i);if(await n.login(r)){e.success(`${r} is logged in to Docker Hub`),await pe({username:r,registry:i||null});return}if(!t){let c=await or({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:l=>l.length>0?!0:"Password cannot be empty"});c.password||(e.error("Password is required"),process.exit(1)),t=c.password}await n.login(r,t,i)||(e.error("Failed to login to Docker Hub"),process.exit(1)),await pe({username:r,registry:i||null}),e.success("Logged in to Docker Hub successfully")}catch(r){e.error(`Failed to login to Docker Hub: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as dt}from"commander";import nr from"node:path";import sr from"inquirer";import ut from"node:fs";var ar=new dt().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async o=>{try{let r=await P();if(r||(e.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!o.image){let s=await sr.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);o.image=s.image}if(!o.tag){let s=await sr.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);o.tag=s.tag}let t=nr.resolve(process.cwd(),o.file);ut.existsSync(t)||(e.info(`Default Dockerfile not found at ${t}`),o.file=await $("Enter the path to your Dockerfile:","Dockerfile","file"));let i=nr.resolve(process.cwd(),o.file);await new b(o.image,r.username,r.registry).buildImage(i,o.tag)||(e.error("Failed to build Docker image"),process.exit(1)),e.success(`Docker image ${r.username}/${o.image}:${o.tag} built successfully`)}catch(r){e.error(`Failed to build Docker image: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as ft}from"commander";import gt from"inquirer";var cr=new ft().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Full image name (e.g. username/image:tag)").action(async o=>{try{let r=await P();r||(e.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let t=o.image;if(!t){let a=await b.listLocalImages();if(a.length===0&&(e.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!t){let s=Array.from(new Set(a.map(l=>l.imageName))),{selectedImage:c}=await gt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:s}]);t=c}}await new b("",r.username,r.registry).pushImage(t)||(e.error("Failed to push Docker image"),process.exit(1)),e.success(`Docker image ${t} pushed successfully`)}catch(r){e.error(`Failed to push Docker image: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as ht}from"commander";import Y from"inquirer";import W from"node:fs";import oe from"node:path";var mr=new ht().name("generate").description("Generate a Docker Compose file").option("-i, --image <imageName>","Docker image name to use in the compose file (e.g. phala/phala-cloud)").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").action(async o=>{try{let r=await P();(!r||!r.username)&&(e.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let t=o.image;if(!t){let c=await b.listLocalImages();if(c.length===0&&(e.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!t){let l=Array.from(new Set(c.map(d=>d.imageName))),{selectedImage:m}=await Y.prompt([{type:"list",name:"selectedImage",message:"Select an image to use in the compose file:",choices:l}]);t=m}}let i=o.envFile;if(i)try{U(i)}catch{e.error(`File not found: ${i}`),process.exit(1)}else{let c=oe.join(process.cwd(),".env");if(W.existsSync(c)){let{useDefault:m}=await Y.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);m&&(i=c)}if(!i){let{envPath:m}=await Y.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:d=>{try{return U(d),!0}catch{return`File not found: ${d}`}}}]);i=m}}let n=o.output;if(!n&&(n=oe.join(process.cwd(),"docker-compose.yml"),W.existsSync(n))){let{confirmOverwrite:c}=await Y.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${n} already exists. Overwrite?`,default:!1}]);if(!c){let{customPath:l}=await Y.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:oe.join(process.cwd(),"docker-generated-compose.yml")}]);n=l}}let a=new b("",r.username,r.registry);i?e.info(`Generating Docker Compose file for ${t} using env file: ${i}`):e.info(`Generating Docker Compose file for ${t} without env file`);let s=await a.buildComposeFile(t,i,o.template);if(s!==n){let c=oe.dirname(n);W.existsSync(c)||(e.info(`Creating directory: ${c}`),W.mkdirSync(c,{recursive:!0})),W.copyFileSync(s,n)}e.success(`Docker Compose file generated successfully: ${n}`)}catch(r){e.error(`Failed to generate Docker Compose file: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});var lr=new yt().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(ir).addCommand(ar).addCommand(cr).addCommand(mr);import{Command as wt}from"commander";import{Command as vt}from"commander";var pr=new vt().name("start").description("Start the TEE simulator").option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-v, --verbose","Enable verbose output",!1).action(async o=>{try{if(Je()||await Ze(),await j()){e.success("TEE simulator is already running");return}let t=await Xe({verbose:o.verbose});e.success("TEE simulator started successfully")}catch(r){e.error(`Failed to start TEE simulator: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Ct}from"commander";var dr=new Ct().name("stop").description("Stop the TEE simulator").action(async()=>{try{await Qe()||(e.error("Failed to stop TEE simulator"),process.exit(1)),e.success("TEE simulator stopped successfully")}catch(o){e.error(`Failed to stop TEE simulator: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var Ce=new wt().name("simulator").description("TEE simulator commands").addCommand(pr).addCommand(dr);Ce.action(async()=>{try{let o=await j(),r=re();if(o&&r){let t=te(),i=te(),n=i.replace(/dstack\.sock$/,"tappd.sock");console.log(`\u2713 TEE simulator is running (PID: ${r})`),console.log(`
55
55
  Set these environment variables to use the simulator:`),console.log(` export DSTACK_SIMULATOR_ENDPOINT=${i}`),console.log(` export TAPPD_SIMULATOR_ENDPOINT=${n}`)}else console.log("TEE simulator is not running"),console.log(`
56
- To start the simulator, run:`),console.log(" phala simulator start")}catch(t){console.error("Error checking simulator status:",t)}});import{Command as Zt}from"commander";import{Command as Ft}from"commander";import $e from"chalk";var _r=new Ft().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await Re();if(e.stop(!0),!o||o.length===0){r.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(o,null,2));return}for(let i of o)r.keyValueTable({Name:i.name,"App ID":`app_${i.hosted.app_id}`,"CVM ID":i.hosted.id.replace(/-/g,""),Region:i.node.region_identifier,Status:i.status==="running"?$e.green(i.status):i.status==="stopped"?$e.red(i.status):$e.yellow(i.status),"Node Info URL":i.hosted.app_url,"App URL":`${y}/dashboard/cvms/${i.hosted.id.replace(/-/g,"")}`}),r.break();r.success(`Found ${o.length} CVMs`),r.break(),r.info(`Go to ${y}/dashboard/ to view your CVMs`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Mt}from"commander";import De from"chalk";async function k(t){if(!t){let e=await oe();return e||void 0}return await te(t)}var Sr=new Mt().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o=await k(t),i=r.startSpinner(`Fetching CVM with App ID app_${o}`),n=await L(o);if(i.stop(!0),r.break(),n||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),e.json){console.log(JSON.stringify(n,null,2));return}r.keyValueTable({Name:n.name,"App ID":`app_${n.app_id}`,Status:n.status==="running"?De.green(n.status):n.status==="stopped"?De.red(n.status):De.yellow(n.status),vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"App URL":`${y}/dashboard/cvms/app_${n.app_id}`})}catch(o){r.error(`Failed to get CVM details: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as Tt}from"commander";var Er=new Tt().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await k(t),o=r.startSpinner(`Starting CVM with App ID app_${e}`),i=await Ke(e);o.stop(!0),r.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};r.keyValueTable(n,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being started. You can check the dashboard for more details:
57
- ${y}/dashboard/cvms/app_${i.app_id}`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Vt}from"commander";var br=new Vt().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await k(t),o=r.startSpinner(`Stopping CVM with App ID app_${e}`),i=await Be(e);o.stop(!0),r.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};r.keyValueTable(n,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being stopped. You can check the dashboard for more details:
58
- ${y}/dashboard/cvms/app_${i.app_id}`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Nt}from"commander";var $r=new Nt().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await k(t),o=r.startSpinner(`Restarting CVM with App ID app_${e}`),i=await ze(e);o.stop(!0),r.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`,"App URL":i.app_url?i.app_url:`${y}/dashboard/cvms/app_${i.app_id}`};r.keyValueTable(n,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being restarted. You can check the dashboard for more details:
59
- ${y}/dashboard/cvms/app_${i.app_id}`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Ut}from"commander";import me from"chalk";var Dr=new Ut().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o;if(t)o=await te(t);else{r.info("No CVM specified, fetching available CVMs...");let n=await oe();if(!n)return;o=n}let i=r.startSpinner(`Fetching attestation information for CVM app_${o}...`);try{let n=await He(o);if(i.stop(!0),!n||Object.keys(n).length===0){r.info("No attestation information found");return}if(e?.json){r.info(JSON.stringify(n,null,2));return}r.success("Attestation Summary:");let a={Status:n.is_online?me.green("Online"):me.red("Offline"),"Public Access":n.is_public?me.green("Enabled"):me.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};if(r.keyValueTable(a,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((s,c)=>{r.break(),r.success(`Certificate #${c+1} (${s.position_in_chain===0?"End Entity":"CA"}):`);let l={Subject:`${s.subject.common_name||"Unknown"}${s.subject.organization?` (${s.subject.organization})`:""}`,Issuer:`${s.issuer.common_name||"Unknown"}${s.issuer.organization?` (${s.issuer.organization})`:""}`,"Serial Number":s.serial_number,Validity:`${new Date(s.not_before).toLocaleString()} to ${new Date(s.not_after).toLocaleString()}`,Fingerprint:s.fingerprint,"Signature Algorithm":s.signature_algorithm,"Is CA":s.is_ca?"Yes":"No","Position in Chain":s.position_in_chain};r.keyValueTable(l,{borderStyle:"rounded"})}),n.tcb_info){r.break(),r.success("Trusted Computing Base (TCB) Information:");let s={Mrtd:n.tcb_info.mrtd,"Rootfs Hash":n.tcb_info.rootfs_hash,Rtmr0:n.tcb_info.rtmr0,Rtmr1:n.tcb_info.rtmr1,Rtmr2:n.tcb_info.rtmr2,Rtmr3:n.tcb_info.rtmr3,"Event Log Entries":`${n.tcb_info.event_log.length} entries`};if(r.keyValueTable(s,{borderStyle:"rounded"}),n.tcb_info.event_log&&n.tcb_info.event_log.length>0){r.break(),r.success("Event Log (Showing entries to reproduce RTMR3):");let c=5,l=n.tcb_info.event_log.filter(m=>m.event!==null&&m.event!=="").map(m=>({Event:m.event,IMR:m.imr.toString(),"Event Type":m.event_type.toString(),Payload:m.event_payload}));r.table(l,[{key:"Event",header:"Event",minWidth:8},{key:"IMR",header:"IMR",minWidth:3},{key:"Event Type",header:"Type",minWidth:8},{key:"Payload",header:"Payload",minWidth:25}]),n.tcb_info.event_log.length>c&&r.info("To see all full attestation data, use --json"),r.break(),r.success("To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/")}}}catch(n){throw i.stop(!1),n}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Rt}from"commander";import{encryptEnvVars as Lt}from"@phala/dstack-sdk/encrypt-env-vars";import Pr from"node:fs";import Ot from"node:path";import Ar from"inquirer";import*as Ir from"node:fs";var Q=(t,e)=>{let o={};if(t){for(let i of t)if(i.includes("=")){let[n,...a]=i.split("="),s=a.join("=");n&&(o[n]=s)}}if(e){let i=Ir.readFileSync(e,"utf8");for(let n of i.split(`
56
+ To start the simulator, run:`),console.log(" phala simulator start")}catch(o){console.error("Error checking simulator status:",o)}});import{Command as Ot}from"commander";import{Command as kt}from"commander";import we from"chalk";var ur=new kt().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async o=>{try{let r=e.startSpinner("Fetching CVMs"),t=await xe();if(r.stop(!0),!t||t.length===0){e.info("No CVMs found");return}if(o.json){console.log(JSON.stringify(t,null,2));return}for(let i of t)e.keyValueTable({Name:i.name,"App ID":`app_${i.hosted.app_id}`,"CVM ID":i.hosted.id.replace(/-/g,""),Region:i.node.region_identifier,Status:i.status==="running"?we.green(i.status):i.status==="stopped"?we.red(i.status):we.yellow(i.status),"Node Info URL":i.hosted.app_url,"App URL":`${y}/dashboard/cvms/${i.hosted.id.replace(/-/g,"")}`}),e.break();e.success(`Found ${t.length} CVMs`),e.break(),e.info(`Go to ${y}/dashboard/ to view your CVMs`)}catch(r){e.error(`Failed to list CVMs: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as _t}from"commander";import ke from"chalk";async function k(o){if(!o){let r=await ee();return r||void 0}return await Q(o)}var fr=new _t().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(o,r)=>{try{let t=await k(o),i=e.startSpinner(`Fetching CVM with App ID app_${t}`),n=await L(t);if(i.stop(!0),e.break(),n||(e.error(`CVM with App ID app_${t} not found`),process.exit(1)),r.json){console.log(JSON.stringify(n,null,2));return}e.keyValueTable({Name:n.name,"App ID":`app_${n.app_id}`,Status:n.status==="running"?ke.green(n.status):n.status==="stopped"?ke.red(n.status):ke.yellow(n.status),vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"App URL":`${y}/dashboard/cvms/app_${n.app_id}`})}catch(t){e.error(`Failed to get CVM details: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as St}from"commander";var gr=new St().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let r=await k(o),t=e.startSpinner(`Starting CVM with App ID app_${r}`),i=await Te(r);t.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being started. You can check the dashboard for more details:
57
+ ${y}/dashboard/cvms/app_${i.app_id}`)}catch(r){e.error(`Failed to start CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as bt}from"commander";var hr=new bt().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let r=await k(o),t=e.startSpinner(`Stopping CVM with App ID app_${r}`),i=await Ve(r);t.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being stopped. You can check the dashboard for more details:
58
+ ${y}/dashboard/cvms/app_${i.app_id}`)}catch(r){e.error(`Failed to stop CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Et}from"commander";var yr=new Et().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let r=await k(o),t=e.startSpinner(`Restarting CVM with App ID app_${r}`),i=await Ue(r);t.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`,"App URL":i.app_url?i.app_url:`${y}/dashboard/cvms/app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being restarted. You can check the dashboard for more details:
59
+ ${y}/dashboard/cvms/app_${i.app_id}`)}catch(r){e.error(`Failed to restart CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as $t}from"commander";import ie from"chalk";var vr=new $t().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(o,r)=>{try{let t;if(o)t=await Q(o);else{e.info("No CVM specified, fetching available CVMs...");let n=await ee();if(!n)return;t=n}let i=e.startSpinner(`Fetching attestation information for CVM app_${t}...`);try{let n=await Le(t);if(i.stop(!0),!n||Object.keys(n).length===0){e.info("No attestation information found");return}if(r?.json){e.info(JSON.stringify(n,null,2));return}e.success("Attestation Summary:");let a={Status:n.is_online?ie.green("Online"):ie.red("Offline"),"Public Access":n.is_public?ie.green("Enabled"):ie.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};if(e.keyValueTable(a,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((s,c)=>{e.break(),e.success(`Certificate #${c+1} (${s.position_in_chain===0?"End Entity":"CA"}):`);let l={Subject:`${s.subject.common_name||"Unknown"}${s.subject.organization?` (${s.subject.organization})`:""}`,Issuer:`${s.issuer.common_name||"Unknown"}${s.issuer.organization?` (${s.issuer.organization})`:""}`,"Serial Number":s.serial_number,Validity:`${new Date(s.not_before).toLocaleString()} to ${new Date(s.not_after).toLocaleString()}`,Fingerprint:s.fingerprint,"Signature Algorithm":s.signature_algorithm,"Is CA":s.is_ca?"Yes":"No","Position in Chain":s.position_in_chain};e.keyValueTable(l,{borderStyle:"rounded"})}),n.tcb_info){e.break(),e.success("Trusted Computing Base (TCB) Information:");let s={Mrtd:n.tcb_info.mrtd,"Rootfs Hash":n.tcb_info.rootfs_hash,Rtmr0:n.tcb_info.rtmr0,Rtmr1:n.tcb_info.rtmr1,Rtmr2:n.tcb_info.rtmr2,Rtmr3:n.tcb_info.rtmr3,"Event Log Entries":`${n.tcb_info.event_log.length} entries`};if(e.keyValueTable(s,{borderStyle:"rounded"}),n.tcb_info.event_log&&n.tcb_info.event_log.length>0){e.break(),e.success("Event Log (Showing entries to reproduce RTMR3):");let c=5,l=n.tcb_info.event_log.filter(m=>m.event!==null&&m.event!=="").map(m=>({Event:m.event,IMR:m.imr.toString(),"Event Type":m.event_type.toString(),Payload:m.event_payload}));e.table(l,[{key:"Event",header:"Event",minWidth:8},{key:"IMR",header:"IMR",minWidth:3},{key:"Event Type",header:"Type",minWidth:8},{key:"Payload",header:"Payload",minWidth:25}]),n.tcb_info.event_log.length>c&&e.info("To see all full attestation data, use --json"),e.break(),e.success("To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/")}}}catch(n){throw i.stop(!1),n}}catch(t){e.error(`Failed to get attestation information: ${t instanceof Error?t.message:String(t)}`)}});import{Command as Dt}from"commander";import{encryptEnvVars as It}from"@phala/dstack-sdk/encrypt-env-vars";import wr from"node:fs";import Pt from"node:path";import kr from"inquirer";import*as Cr from"node:fs";var J=(o,r)=>{let t={};if(o){for(let i of o)if(i.includes("=")){let[n,...a]=i.split("="),s=a.join("=");n&&(t[n]=s)}}if(r){let i=Cr.readFileSync(r,"utf8");for(let n of i.split(`
60
60
  `)){if(!n.trim()||n.trim().startsWith("#"))continue;let a=-1,s=!1,c="";for(let f=0;f<n.length;f++)if((n[f]==='"'||n[f]==="'"||n[f]==="`")&&(f===0||n[f-1]!=="\\"))s&&n[f]===c?(s=!1,c=""):s||(s=!0,c=n[f]);else if(n[f]==="="&&!s){a=f;break}else if(n[f]==="#"&&!s)break;if(a===-1){n.trim().startsWith("#");continue}let l=n.substring(0,a).trim(),m=n.substring(a+1),d=!1,g="",p=-1;for(let f=0;f<m.length;f++)if((m[f]==='"'||m[f]==="'"||m[f]==="`")&&(f===0||m[f-1]!=="\\"))d&&m[f]===g?(d=!1,g=""):d||(d=!0,g=m[f]);else if(m[f]==="#"&&!d&&f>0&&m[f-1]===" "){p=f-1;break}else if(m[f]==="#"&&!d&&f===0){p=f;break}p!==-1&&(m=m.substring(0,p)),m===void 0&&(m="");let u=m.charAt(0),v=m.charAt(m.length-1);u==='"'&&v==='"'||u==="'"&&v==="'"||u==="`"&&v==="`"?(m=m.substring(1,m.length-1),u==='"'&&(m=m.replace(/\\\\n/g,`
61
- `))):m=m.trim(),l&&(o[l]=m)}}return Object.entries(o).map(([i,n])=>({key:i,value:n}))};var xr=new Rt().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>",`Number of vCPUs, default is ${T}`).option("--memory <memory>",`Memory in MB, default is ${V}`).option("--disk-size <diskSize>",`Disk size in GB, default is ${N}`).option("--teepod-id <teepodId>","TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.").option("--image <image>","Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.").option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async t=>{try{if(!t.name){let{name:w}=await Ar.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:b=>b.trim()?b.trim().length>20?"CVM name must be less than 20 characters":b.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(b)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);t.name=w}if(!t.compose){let b=B(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await D("Enter the path to your Docker Compose file:",b,"file")}let e=Ot.resolve(t.compose);Pr.existsSync(e)||(r.error(`Docker Compose file not found: ${e}`),process.exit(1));let o=Pr.readFileSync(e,"utf8");await R(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?r.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?r.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):r.info("\u{1F510} Using public DockerHub registry...");let i=[];if(t.envFile)try{i=Q([],t.envFile)}catch(w){r.error(`Failed to read environment file: ${w instanceof Error?w.message:String(w)}`),process.exit(1)}else if(!t.skipEnv){let{shouldSkip:w}=await Ar.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!0}]);if(w)r.info("Skipping environment variable prompt");else{let b=await D("Enter the path to your environment file:",".env","file");i=Q([],b)}}let n=Number(t.vcpu)||T,a=Number(t.memory)||V,s=Number(t.diskSize)||N;(Number.isNaN(n)||n<=0)&&(r.error(`Invalid number of vCPUs: ${n}`),process.exit(1)),(Number.isNaN(a)||a<=0)&&(r.error(`Invalid memory: ${a}`),process.exit(1)),(Number.isNaN(s)||s<=0)&&(r.error(`Invalid disk size: ${s}`),process.exit(1));let c=r.startSpinner("Fetching available TEEPods"),l=await O();c.stop(!0),l.nodes.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let m;t.teepodId?(m=l.nodes.find(w=>w.teepod_id===Number(t.teepodId)),m||(r.error("Failed to find selected TEEPod"),process.exit(1))):(m=l.nodes[0],m||(r.error("Failed to find default TEEPod"),process.exit(1)));let d;t.image?(d=m.images?.find(w=>w.name===t.image),d||(r.error(`Failed to find selected image: ${t.image}`),process.exit(1))):(d=m.images?.find(w=>w.name===fe),d||(r.error(`Failed to find default image ${fe}`),process.exit(1)));let g={teepod_id:m.teepod_id,name:t.name,image:d.name,vcpu:n,memory:a,disk_size:s,compose_manifest:{docker_compose_file:o,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:t.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},p=r.startSpinner("Getting public key from CVM"),u=await Le(g);p.stop(!0),u||(r.error("Failed to get public key from CVM"),process.exit(1));let v=r.startSpinner("Encrypting environment variables"),f=await Lt(i,u.app_env_encrypt_pubkey);v.stop(!0),t.debug&&(r.debug("Public key:",u.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",f),r.debug("Environment variables:",JSON.stringify(i)));let P=r.startSpinner("Creating CVM"),_=await Oe({...g,encrypted_env:f,app_env_encrypt_pubkey:u.app_env_encrypt_pubkey,app_id_salt:u.app_id_salt});P.stop(!0),_||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.break();let le={"CVM ID":_.id,Name:_.name,Status:_.status,"App ID":`app_${_.app_id}`,"App URL":_.app_url?_.app_url:`${y}/dashboard/cvms/app_${_.app_id}`};r.keyValueTable(le,{borderStyle:"rounded"}),r.info(""),r.success(`Your CVM is being created. You can check its status with:
62
- phala cvms get app_${_.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Kt}from"commander";import Bt from"inquirer";var Fr=new Kt().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(t,e)=>{try{let o=await k(t);if(!e.force){let{confirm:a}=await Bt.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID app_${o}? This action cannot be undone.`,default:!1}]);if(!a){r.info("Deletion cancelled");return}}let i=r.startSpinner(`Deleting CVM app_${o}`),n=await Ge(o);i.stop(!0),n||(r.error(`Failed to delete CVM app_${o}`),process.exit(1)),r.success(`CVM app_${o} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as zt}from"commander";import jt from"node:fs";import{encryptEnvVars as Gt}from"@phala/dstack-sdk/encrypt-env-vars";var Mr=new zt().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(t,e)=>{try{let o=await k(t),i=r.startSpinner(`Fetching current configuration for CVM app_${o}`),n=await L(o);if(i.stop(!0),n||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),!e.compose){let g=B(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");e.compose=await D("Enter the path to your Docker Compose file:",g,"file")}let a="";if(e.compose)try{a=jt.readFileSync(e.compose,"utf8")}catch(d){r.error(`Failed to read Docker Compose file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}await R(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?r.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?r.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):r.info("\u{1F510} Using public DockerHub registry...");let s="";if(e.envFile){let d=[];if(e.envFile)try{d=Q([],e.envFile),s=await Gt(d,n.encrypted_env_pubkey)}catch(g){r.error(`Failed to read environment file: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}}let c={compose_manifest:{docker_compose_file:a,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${o}`},encrypted_env:s,allow_restart:!0},l=r.startSpinner(`Upgrading CVM app_${o}`),m=await je(o,c);m||(l.stop(!1),r.error("Failed to upgrade CVM"),process.exit(1)),l.stop(!0),m.detail&&r.info(`Details: ${m.detail}`),r.break(),r.success(`Your CVM is being upgraded. You can check the dashboard for more details:
63
- ${y}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as Ht}from"commander";import ee from"inquirer";import M from"chalk";var Tr=new Ht().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(t,e)=>{try{let o=await k(t),i=await L(o),n=e.vcpu,a=e.memory,s=e.diskSize,c=e.allowRestart;n||(n=(await ee.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.vcpu,filter:p=>parseInt(p)}])).vcpu),a||(a=(await ee.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.memory,filter:p=>parseInt(p)}])).memory),s||(s=(await ee.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.disk_size,filter:p=>parseInt(p)}])).diskSize),c||(c=(await ee.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let l=`Are you sure you want to resize CVM app_${o} with the following changes:
64
- `;if(r.keyValueTable({vCPUs:i.vcpu!==n?`${M.red(i.vcpu)} -> ${M.green(n)}`:i.vcpu,Memory:i.memory!==a?`${M.red(i.memory)} MB -> ${M.green(a)} MB`:i.memory,"Disk Size":i.disk_size!==s?`${M.red(i.disk_size)} GB -> ${M.green(s)} GB`:i.disk_size,"Allow Restart":c?M.green("Yes"):M.red("No")}),!e.yes){let{confirm:g}=await ee.prompt([{type:"confirm",name:"confirm",message:l,default:!1}]);if(!g){r.info("Resize operation cancelled");return}}let m=r.startSpinner(`Resizing CVM with App ID app_${o}`);await We(o,n,a,s,c?1:0),m.stop(!0),r.break(),r.success(`Your CVM is being resized. You can check the dashboard for more details:
65
- ${y}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as qt}from"commander";var Vr=new qt().name("list-nodes").description("List all available worker nodes.").action(async()=>{try{let{nodes:t,kms_list:e}=await O();if(t.length===0){r.info("No available nodes found.");return}r.info("Available Nodes:"),t.forEach(o=>{r.info("----------------------------------------"),r.info(` ID: ${o.teepod_id}`),r.info(` Name: ${o.name}`),r.info(` Region: ${o.region_identifier}`),r.info(` FMSPC: ${o.fmspc||"N/A"}`),r.info(` Device ID: ${o.device_id||"N/A"}`),r.info(` Support Onchain KMS: ${o.support_onchain_kms}`),r.info(" Images:"),o.images&&o.images.length>0?o.images.forEach(i=>{r.info(` - ${i.name}`),r.info(` Hash: ${i.os_image_hash||"N/A"}`)}):r.info(" N/A")}),e&&e.length>0&&(r.info(`
66
- Available KMS Instances:`),e.forEach(o=>{r.info("----------------------------------------"),r.info(` ID: ${o.id}`),r.info(` URL: ${o.url}`),r.info(` Version: ${o.version}`),r.info(` Chain ID: ${o.chain_id}`),r.info(` Contract Address: ${o.kms_contract_address}`),r.info(` Gateway App ID: ${o.gateway_app_id}`)}))}catch(t){r.error(`Failed to list available nodes: ${t instanceof Error?t.message:String(t)}`)}});import{Command as Yt}from"commander";import{encryptEnvVars as Wt}from"@phala/dstack-sdk/encrypt-env-vars";import Nr from"node:fs";import Jt from"node:path";var Ur=new Yt().name("replicate").description("Create a replica of an existing CVM").argument("<cvm-id>","UUID of the CVM to replicate").option("--teepod-id <teepodId>","TEEPod ID to use for the replica").option("-e, --env-file <envFile>","Path to environment file").action(async(t,e)=>{try{let o;if(t=t.replace(/-/g,""),e.envFile){let s=Jt.resolve(process.cwd(),e.envFile);if(!Nr.existsSync(s))throw new Error(`Environment file not found: ${s}`);let l=Nr.readFileSync(s,"utf-8").split(`
67
- `).filter(g=>g.trim()!==""&&!g.trim().startsWith("#")).map(g=>{let[p,...u]=g.split("=");return{key:p.trim(),value:u.join("=").trim()}}),m=await qe(t);r.info("Encrypting environment variables..."),o=await Wt(l,m.env_pubkey)}let i={};e.teepodId&&(i.teepod_id=parseInt(e.teepodId,10)),o&&(i.encrypted_env=o);let n=await Ye(t,i);r.success(`Successfully created replica of CVM UUID: ${t} with App ID: ${n.app_id}`);let a={"CVM UUID":n.vm_uuid.replace(/-/g,""),"App ID":n.app_id,Name:n.name,Status:n.status,TEEPod:`${n.teepod.name} (ID: ${n.teepod_id})`,vCPUs:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"App URL":n.app_url||`${process.env.CLOUD_URL||"https://cloud.phala.network"}/dashboard/cvms/${n.vm_uuid.replace(/-/g,"")}`};r.keyValueTable(a,{borderStyle:"rounded"}),r.success(`Your CVM replica is being created. You can check its status with:
68
- phala cvms get ${n.app_id}`)}catch(o){r.error("Failed to create CVM replica:",o instanceof Error?o.message:o),process.exit(1)}});var Rr=new Zt().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(Dr).addCommand(xr).addCommand(Fr).addCommand(Sr).addCommand(_r).addCommand(Er).addCommand(br).addCommand(Tr).addCommand($r).addCommand(Mr).addCommand(Vr).addCommand(Ur);import{Command as Lr}from"commander";async function Ie(){try{let{nodes:t,kms_list:e}=await O();if(t.length===0){r.info("No available nodes found.");return}r.info("Available Nodes:"),t.forEach(o=>{r.info("----------------------------------------"),r.info(` ID: ${o.teepod_id}`),r.info(` Name: ${o.name}`),r.info(` Region: ${o.region_identifier}`),r.info(` FMSPC: ${o.fmspc||"N/A"}`),r.info(` Device ID: ${o.device_id||"N/A"}`),r.info(` Support Onchain KMS: ${o.support_onchain_kms}`),r.info(" Images:"),o.images&&o.images.length>0?o.images.forEach(i=>{r.info(` - ${i.name}`),r.info(` Hash: ${i.os_image_hash||"N/A"}`)}):r.info(" N/A")}),e&&e.length>0&&(r.info(`
69
- Available KMS Instances:`),e.forEach(o=>{r.info("----------------------------------------"),r.info(` Slug: ${o.slug}`),r.info(` URL: ${o.url}`),r.info(` Version: ${o.version}`),o.chain_id&&(r.info(` Chain ID: ${o.chain_id}`),r.info(` Contract Address: ${o.kms_contract_address}`),r.info(` Gateway App ID: ${o.gateway_app_id}`))}))}catch(t){throw r.error(`Failed to list available nodes: ${t instanceof Error?t.message:String(t)}`),t}}var Or=new Lr().name("nodes").description("List and manage TEE nodes").action(Ie).addCommand(new Lr("list").description("List all available worker nodes").alias("ls").action(Ie));import{createClient as Xt}from"@phala/cloud";import{Command as Qt}from"commander";import{safeGetCurrentUser as eo}from"@phala/cloud";async function ro(t={}){try{let e=t.debug||process.env.DEBUG?.toLowerCase()==="true",o=ne();if(!o){r.warn('Not authenticated. Please set an API key with "phala auth login"');return}e&&r.debug(`Using API key: ${o.substring(0,5)}...`);try{let i=Xt(),n=await eo(i);if(!n.success){r.error("Failed to get user information"),n.error&&r.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(t.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),e&&r.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}var Kr=new Qt().name("status").description("Check Phala Cloud status and authentication").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(ro);import{Command as no,Option as so}from"commander";import Me from"dedent";import xe from"fs-extra";import z from"inquirer";import ao from"path";import{createClient as Ae,encryptEnvVars as Fe,parseEnvVars as co,safeAddComposeHash as mo,safeCommitCvmComposeFileUpdate as lo,safeCommitCvmProvision as Zr,safeDeployAppAuth as po,safeGetAppEnvEncryptPubKey as uo,safeGetAvailableNodes as fo,safeGetCvmComposeFile as go,safeGetCvmInfo as ho,safeGetKmsList as yo,safeProvisionCvm as vo,safeProvisionCvmComposeFileUpdate as Co}from"@phala/cloud";function Br(t,e="B"){if(!t||typeof t!="string")throw new Error("Invalid input: must be a non-empty string");let o=t.trim().match(/^(\d+(?:\.\d+)?)\s*([KkMmGgTt][Bb]?)?$/);if(!o)throw new Error(`Invalid format: ${t}. Expected format: <number>[unit] (e.g., 2G, 500MB, 1T)`);let i=parseFloat(o[1]),n=(o[2]||e).toUpperCase().replace("B",""),a={K:1024,M:1024*1024,G:1024*1024*1024,T:1024*1024*1024*1024,"":1};if(!(n in a))throw new Error(`Unsupported unit: ${n}. Supported units: B, K/KB, M/MB, G/GB, T/TB`);return Math.round(i*a[n])}function zr(t){let e=Br(t,"MB"),o=Math.round(e/(1024*1024));if(o%1024!==0)throw new Error(`Memory must be a multiple of 1GB (1024MB). Got: ${o}MB`);return o}function jr(t){let e=Br(t,"GB"),o=Math.round(e/(1024*1024*1024));if(o%1!==0)throw new Error(`Disk size must be a multiple of 1GB. Got: ${o}GB`);let i=250;if(o>i)throw new Error(`Maximum disk size is ${i}GB. Got: ${o}GB`);return o}import re from"fs-extra";import Gr from"node:path";import to from"node:os";import{join as Hr}from"path";var oo=Gr.join(to.homedir(),".phala-cloud"),ec=Gr.join(oo,"config.json");function Pe(){return Hr(process.cwd(),".phala","config")}function qr(){let t=Pe(),e=Hr(process.cwd(),".phala");re.ensureDirSync(e),re.pathExistsSync(t)||re.writeJsonSync(t,{},{spaces:2})}function Yr(){return qr(),re.readJsonSync(Pe())}function io(t){qr(),re.writeJsonSync(Pe(),t,{spaces:2})}function Wr(t){let e=Yr();e.cvmUuid=t,io(e)}function Jr(){return process.env.PHALA_CLOUD_CVM_UUID?process.env.PHALA_CLOUD_CVM_UUID:Yr().cvmUuid}async function wo({apiKey:t,interactive:e}){if(!t&&!process.env.PHALA_CLOUD_API_KEY)if(e){let{apiKey:o}=await z.prompt([{type:"password",name:"apiKey",message:"Enter your API key:",validate:i=>i.trim()?!0:"API key is required"}]);return Ae({apiKey:o})}else throw new Error("API key is required. Please provide it via --api-key or PHALA_CLOUD_API_KEY environment variable");else if(t)return Ae({apiKey:t});return Ae()}async function ko({dockerComposePath:t,interactive:e}){if(!t)if(e){let i=B(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t=await D("Enter the path to your Docker Compose file:",i,"file")}else throw new Error(Me(`
61
+ `))):m=m.trim(),l&&(t[l]=m)}}return Object.entries(t).map(([i,n])=>({key:i,value:n}))};var _r=new Dt().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>",`Number of vCPUs, default is ${M}`).option("--memory <memory>",`Memory in MB, default is ${T}`).option("--disk-size <diskSize>",`Disk size in GB, default is ${V}`).option("--teepod-id <teepodId>","TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.").option("--image <image>","Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.").option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async o=>{try{if(!o.name){let{name:w}=await kr.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:E=>E.trim()?E.trim().length>20?"CVM name must be less than 20 characters":E.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(E)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);o.name=w}if(!o.compose){let E=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");o.compose=await $("Enter the path to your Docker Compose file:",E,"file")}let r=Pt.resolve(o.compose);wr.existsSync(r)||(e.error(`Docker Compose file not found: ${r}`),process.exit(1));let t=wr.readFileSync(r,"utf8");await N(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?e.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?e.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):e.info("\u{1F510} Using public DockerHub registry...");let i=[];if(o.envFile)try{i=J([],o.envFile)}catch(w){e.error(`Failed to read environment file: ${w instanceof Error?w.message:String(w)}`),process.exit(1)}else if(!o.skipEnv){let{shouldSkip:w}=await kr.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!0}]);if(w)e.info("Skipping environment variable prompt");else{let E=await $("Enter the path to your environment file:",".env","file");i=J([],E)}}let n=Number(o.vcpu)||M,a=Number(o.memory)||T,s=Number(o.diskSize)||V;(Number.isNaN(n)||n<=0)&&(e.error(`Invalid number of vCPUs: ${n}`),process.exit(1)),(Number.isNaN(a)||a<=0)&&(e.error(`Invalid memory: ${a}`),process.exit(1)),(Number.isNaN(s)||s<=0)&&(e.error(`Invalid disk size: ${s}`),process.exit(1));let c=e.startSpinner("Fetching available TEEPods"),l=await O();c.stop(!0),l.nodes.length===0&&(e.error("No TEEPods available. Please try again later."),process.exit(1));let m;o.teepodId?(m=l.nodes.find(w=>w.teepod_id===Number(o.teepodId)),m||(e.error("Failed to find selected TEEPod"),process.exit(1))):(m=l.nodes[0],m||(e.error("Failed to find default TEEPod"),process.exit(1)));let d;o.image?(d=m.images?.find(w=>w.name===o.image),d||(e.error(`Failed to find selected image: ${o.image}`),process.exit(1))):(d=m.images?.find(w=>w.name===de),d||(e.error(`Failed to find default image ${de}`),process.exit(1)));let g={teepod_id:m.teepod_id,name:o.name,image:d.name,vcpu:n,memory:a,disk_size:s,compose_manifest:{docker_compose_file:t,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:o.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},p=e.startSpinner("Getting public key from CVM"),u=await Fe(g);p.stop(!0),u||(e.error("Failed to get public key from CVM"),process.exit(1));let v=e.startSpinner("Encrypting environment variables"),f=await It(i,u.app_env_encrypt_pubkey);v.stop(!0),o.debug&&(e.debug("Public key:",u.app_env_encrypt_pubkey),e.debug("Encrypted environment variables:",f),e.debug("Environment variables:",JSON.stringify(i)));let I=e.startSpinner("Creating CVM"),_=await Me({...g,encrypted_env:f,app_env_encrypt_pubkey:u.app_env_encrypt_pubkey,app_id_salt:u.app_id_salt});I.stop(!0),_||(e.error("Failed to create CVM"),process.exit(1)),e.success("CVM created successfully"),e.break();let se={"CVM ID":_.id,Name:_.name,Status:_.status,"App ID":`app_${_.app_id}`,"App URL":_.app_url?_.app_url:`${y}/dashboard/cvms/app_${_.app_id}`};e.keyValueTable(se,{borderStyle:"rounded"}),e.info(""),e.success(`Your CVM is being created. You can check its status with:
62
+ phala cvms get app_${_.app_id}`)}catch(r){e.error(`Failed to create CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as At}from"commander";import xt from"inquirer";var Sr=new At().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(o,r)=>{try{let t=await k(o);if(!r.force){let{confirm:a}=await xt.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID app_${t}? This action cannot be undone.`,default:!1}]);if(!a){e.info("Deletion cancelled");return}}let i=e.startSpinner(`Deleting CVM app_${t}`),n=await Re(t);i.stop(!0),n||(e.error(`Failed to delete CVM app_${t}`),process.exit(1)),e.success(`CVM app_${t} deleted successfully`)}catch(t){e.error(`Failed to delete CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Ft}from"commander";import Mt from"node:fs";import{encryptEnvVars as Tt}from"@phala/dstack-sdk/encrypt-env-vars";var br=new Ft().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(o,r)=>{try{let t=await k(o),i=e.startSpinner(`Fetching current configuration for CVM app_${t}`),n=await L(t);if(i.stop(!0),n||(e.error(`CVM with App ID app_${t} not found`),process.exit(1)),!r.compose){let g=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");r.compose=await $("Enter the path to your Docker Compose file:",g,"file")}let a="";if(r.compose)try{a=Mt.readFileSync(r.compose,"utf8")}catch(d){e.error(`Failed to read Docker Compose file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}await N(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?e.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?e.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):e.info("\u{1F510} Using public DockerHub registry...");let s="";if(r.envFile){let d=[];if(r.envFile)try{d=J([],r.envFile),s=await Tt(d,n.encrypted_env_pubkey)}catch(g){e.error(`Failed to read environment file: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}}let c={compose_manifest:{docker_compose_file:a,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${t}`},encrypted_env:s,allow_restart:!0},l=e.startSpinner(`Upgrading CVM app_${t}`),m=await Ne(t,c);m||(l.stop(!1),e.error("Failed to upgrade CVM"),process.exit(1)),l.stop(!0),m.detail&&e.info(`Details: ${m.detail}`),e.break(),e.success(`Your CVM is being upgraded. You can check the dashboard for more details:
63
+ ${y}/dashboard/cvms/app_${t}`)}catch(t){e.error(`Failed to upgrade CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Vt}from"commander";import Z from"inquirer";import F from"chalk";var Er=new Vt().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(o,r)=>{try{let t=await k(o),i=await L(t),n=r.vcpu,a=r.memory,s=r.diskSize,c=r.allowRestart;n||(n=(await Z.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.vcpu,filter:p=>parseInt(p)}])).vcpu),a||(a=(await Z.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.memory,filter:p=>parseInt(p)}])).memory),s||(s=(await Z.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:p=>{let u=parseInt(p);return isNaN(u)||u<0?"Please enter a valid non-negative number":!0},default:i.disk_size,filter:p=>parseInt(p)}])).diskSize),c||(c=(await Z.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let l=`Are you sure you want to resize CVM app_${t} with the following changes:
64
+ `;if(e.keyValueTable({vCPUs:i.vcpu!==n?`${F.red(i.vcpu)} -> ${F.green(n)}`:i.vcpu,Memory:i.memory!==a?`${F.red(i.memory)} MB -> ${F.green(a)} MB`:i.memory,"Disk Size":i.disk_size!==s?`${F.red(i.disk_size)} GB -> ${F.green(s)} GB`:i.disk_size,"Allow Restart":c?F.green("Yes"):F.red("No")}),!r.yes){let{confirm:g}=await Z.prompt([{type:"confirm",name:"confirm",message:l,default:!1}]);if(!g){e.info("Resize operation cancelled");return}}let m=e.startSpinner(`Resizing CVM with App ID app_${t}`);await ze(t,n,a,s,c?1:0),m.stop(!0),e.break(),e.success(`Your CVM is being resized. You can check the dashboard for more details:
65
+ ${y}/dashboard/cvms/app_${t}`)}catch(t){e.error(`Failed to resize CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Ut}from"commander";var $r=new Ut().name("list-nodes").description("List all available worker nodes.").action(async()=>{try{let{nodes:o,kms_list:r}=await O();if(o.length===0){e.info("No available nodes found.");return}e.info("Available Nodes:"),o.forEach(t=>{e.info("----------------------------------------"),e.info(` ID: ${t.teepod_id}`),e.info(` Name: ${t.name}`),e.info(` Region: ${t.region_identifier}`),e.info(` FMSPC: ${t.fmspc||"N/A"}`),e.info(` Device ID: ${t.device_id||"N/A"}`),e.info(` Support Onchain KMS: ${t.support_onchain_kms}`),e.info(" Images:"),t.images&&t.images.length>0?t.images.forEach(i=>{e.info(` - ${i.name}`),e.info(` Hash: ${i.os_image_hash||"N/A"}`)}):e.info(" N/A")}),r&&r.length>0&&(e.info(`
66
+ Available KMS Instances:`),r.forEach(t=>{e.info("----------------------------------------"),e.info(` ID: ${t.id}`),e.info(` URL: ${t.url}`),e.info(` Version: ${t.version}`),e.info(` Chain ID: ${t.chain_id}`),e.info(` Contract Address: ${t.kms_contract_address}`),e.info(` Gateway App ID: ${t.gateway_app_id}`)}))}catch(o){e.error(`Failed to list available nodes: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Nt}from"commander";import{encryptEnvVars as Rt}from"@phala/dstack-sdk/encrypt-env-vars";import Dr from"node:fs";import Lt from"node:path";var Ir=new Nt().name("replicate").description("Create a replica of an existing CVM").argument("<cvm-id>","UUID of the CVM to replicate").option("--teepod-id <teepodId>","TEEPod ID to use for the replica").option("-e, --env-file <envFile>","Path to environment file").action(async(o,r)=>{try{let t;if(o=o.replace(/-/g,""),r.envFile){let s=Lt.resolve(process.cwd(),r.envFile);if(!Dr.existsSync(s))throw new Error(`Environment file not found: ${s}`);let l=Dr.readFileSync(s,"utf-8").split(`
67
+ `).filter(g=>g.trim()!==""&&!g.trim().startsWith("#")).map(g=>{let[p,...u]=g.split("=");return{key:p.trim(),value:u.join("=").trim()}}),m=await Oe(o);e.info("Encrypting environment variables..."),t=await Rt(l,m.env_pubkey)}let i={};r.teepodId&&(i.teepod_id=parseInt(r.teepodId,10)),t&&(i.encrypted_env=t);let n=await Ke(o,i);e.success(`Successfully created replica of CVM UUID: ${o} with App ID: ${n.app_id}`);let a={"CVM UUID":n.vm_uuid.replace(/-/g,""),"App ID":n.app_id,Name:n.name,Status:n.status,TEEPod:`${n.teepod.name} (ID: ${n.teepod_id})`,vCPUs:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"App URL":n.app_url||`${process.env.CLOUD_URL||"https://cloud.phala.network"}/dashboard/cvms/${n.vm_uuid.replace(/-/g,"")}`};e.keyValueTable(a,{borderStyle:"rounded"}),e.success(`Your CVM replica is being created. You can check its status with:
68
+ phala cvms get ${n.app_id}`)}catch(t){e.error("Failed to create CVM replica:",t instanceof Error?t.message:t),process.exit(1)}});var Pr=new Ot().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(vr).addCommand(_r).addCommand(Sr).addCommand(fr).addCommand(ur).addCommand(gr).addCommand(hr).addCommand(Er).addCommand(yr).addCommand(br).addCommand($r).addCommand(Ir);import{Command as Ar}from"commander";async function _e(){try{let{nodes:o,kms_list:r}=await O();if(o.length===0){e.info("No available nodes found.");return}e.info("Available Nodes:"),o.forEach(t=>{e.info("----------------------------------------"),e.info(` ID: ${t.teepod_id}`),e.info(` Name: ${t.name}`),e.info(` Region: ${t.region_identifier}`),e.info(` FMSPC: ${t.fmspc||"N/A"}`),e.info(` Device ID: ${t.device_id||"N/A"}`),e.info(` Support Onchain KMS: ${t.support_onchain_kms}`),e.info(" Images:"),t.images&&t.images.length>0?t.images.forEach(i=>{e.info(` - ${i.name}`),e.info(` Hash: ${i.os_image_hash||"N/A"}`)}):e.info(" N/A")}),r&&r.length>0&&(e.info(`
69
+ Available KMS Instances:`),r.forEach(t=>{e.info("----------------------------------------"),e.info(` Slug: ${t.slug}`),e.info(` URL: ${t.url}`),e.info(` Version: ${t.version}`),t.chain_id&&(e.info(` Chain ID: ${t.chain_id}`),e.info(` Contract Address: ${t.kms_contract_address}`),e.info(` Gateway App ID: ${t.gateway_app_id}`))}))}catch(o){throw e.error(`Failed to list available nodes: ${o instanceof Error?o.message:String(o)}`),o}}var xr=new Ar().name("nodes").description("List and manage TEE nodes").action(_e).addCommand(new Ar("list").description("List all available worker nodes").alias("ls").action(_e));import{createClient as Kt}from"@phala/cloud";import{Command as zt}from"commander";import{safeGetCurrentUser as Bt}from"@phala/cloud";async function Gt(o={}){try{let r=o.debug||process.env.DEBUG?.toLowerCase()==="true",t=o.apiKey||R();if(!t){e.warn('Not authenticated. Please set an API key with "phala auth login"');return}r&&e.debug(`Using API key: ${t.substring(0,5)}...`);try{let i=Kt({apiKey:t}),n=await Bt(i);if(!n.success){e.error("Failed to get user information"),n.error&&e.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(o.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),r&&e.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(r){e.error(`Failed to check authentication status: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}var Fr=new zt().name("status").description("Check Phala Cloud status and authentication").option("--api-key <apiKey>","API key for authentication").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(Gt);import{Command as Yt,Option as Wt}from"commander";import $e from"dedent";import be from"fs-extra";import z from"inquirer";import Jt from"path";import{createClient as ne,encryptEnvVars as Ee,parseEnvVars as Zt,safeAddComposeHash as Xt,safeCommitCvmComposeFileUpdate as Qt,safeCommitCvmProvision as zr,safeDeployAppAuth as eo,safeGetAppEnvEncryptPubKey as ro,safeGetAvailableNodes as to,safeGetCvmComposeFile as oo,safeGetCvmInfo as io,safeGetKmsList as no,safeProvisionCvm as so,safeProvisionCvmComposeFileUpdate as ao}from"@phala/cloud";function Mr(o,r="B"){if(!o||typeof o!="string")throw new Error("Invalid input: must be a non-empty string");let t=o.trim().match(/^(\d+(?:\.\d+)?)\s*([KkMmGgTt][Bb]?)?$/);if(!t)throw new Error(`Invalid format: ${o}. Expected format: <number>[unit] (e.g., 2G, 500MB, 1T)`);let i=parseFloat(t[1]),n=(t[2]||r).toUpperCase().replace("B",""),a={K:1024,M:1024*1024,G:1024*1024*1024,T:1024*1024*1024*1024,"":1};if(!(n in a))throw new Error(`Unsupported unit: ${n}. Supported units: B, K/KB, M/MB, G/GB, T/TB`);return Math.round(i*a[n])}function Tr(o){let r=Mr(o,"MB"),t=Math.round(r/(1024*1024));if(t%1024!==0)throw new Error(`Memory must be a multiple of 1GB (1024MB). Got: ${t}MB`);return t}function Vr(o){let r=Mr(o,"GB"),t=Math.round(r/(1024*1024*1024));if(t%1!==0)throw new Error(`Disk size must be a multiple of 1GB. Got: ${t}GB`);let i=250;if(t>i)throw new Error(`Maximum disk size is ${i}GB. Got: ${t}GB`);return t}import X from"fs-extra";import Ur from"node:path";import jt from"node:os";import{join as Nr}from"path";var Ht=Ur.join(jt.homedir(),".phala-cloud"),Na=Ur.join(Ht,"config.json");function Se(){return Nr(process.cwd(),".phala","config")}function Rr(){let o=Se(),r=Nr(process.cwd(),".phala");X.ensureDirSync(r),X.pathExistsSync(o)||X.writeJsonSync(o,{},{spaces:2})}function Lr(){return Rr(),X.readJsonSync(Se())}function qt(o){Rr(),X.writeJsonSync(Se(),o,{spaces:2})}function Or(o){let r=Lr();r.cvmUuid=o,qt(r)}function Kr(){return process.env.PHALA_CLOUD_CVM_UUID?process.env.PHALA_CLOUD_CVM_UUID:Lr().cvmUuid}async function co({apiKey:o,interactive:r}){if(!o&&!process.env.PHALA_CLOUD_API_KEY)if(r){let{apiKey:t}=await z.prompt([{type:"password",name:"apiKey",message:"Enter your API key:",validate:i=>i.trim()?!0:"API key is required"}]);return ne({apiKey:t})}else{let t=R();if(!t)throw new Error("API key is required. Please provide it via --api-key or PHALA_CLOUD_API_KEY environment variable");return ne({apiKey:t})}else if(o)return ne({apiKey:o});return ne()}async function mo({dockerComposePath:o,interactive:r}){if(!o)if(r){let i=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");o=await $("Enter the path to your Docker Compose file:",i,"file")}else throw new Error($e(`
70
70
  Docker Compose file is required.
71
71
 
72
72
  Usage examples:
@@ -81,13 +81,13 @@ Available KMS Instances:`),e.forEach(o=>{r.info("-------------------------------
81
81
  --private-key <key> Private key for deployment
82
82
 
83
83
  Run with --interactive for guided setup
84
- `));if(!xe.existsSync(t))throw new Error(`Docker compose file not found: ${t}`);return xe.readFileSync(t,"utf8")}function _o({uuid:t}={}){return t||Jr()}var So=async(t,e)=>{if(!t.privateKey&&process.env.PRIVATE_KEY&&(t.privateKey=process.env.PRIVATE_KEY),t.kmsId&&e&&!t.privateKey)if(t.interactive){let{privateKey:o}=await z.prompt([{type:"password",name:"privateKey",message:"Enter your private key:",validate:i=>i.trim()?!0:"Private key is required"}]);t.privateKey=o}else throw new Error("When using on-chain KMS, either --private-key (or PRIVATE_KEY env) must be provided")},Eo=async t=>{if(!t.name){let e=ao.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g,"-");e.length<3&&(e=e+"-cvm");let o=e.slice(0,20);if(!t.interactive)t.name=o;else{let{name:i}=await z.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",default:o,validate:n=>n.trim()?n.trim().length>20?"CVM name must be less than 20 characters":n.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(n)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);t.name=i}}},bo=async t=>{let e=[],o=t.envFile;if(t.interactive&&(!t.envFile||o===!0)&&(o=await D("Enter the path to your environment file:",".env","file")),o&&o!==!0)try{let i=xe.readFileSync(o,{encoding:"utf8"});e=co(i)}catch(i){throw new Error(`Error reading environment file ${o}:`,i)}return e},$o=async t=>{let e=T;if(t.vcpu)try{e=Number(t.vcpu)}catch{throw new Error(`Invalid vCPU format '${t.vcpu}'. Using default: ${T}`)}let o=V;if(t.memory)try{o=zr(t.memory)}catch{throw new Error(`Invalid memory format '${t.memory}'. Using default: ${V}MB`)}let i=N;if(t.diskSize)try{i=jr(t.diskSize)}catch{throw new Error(`Invalid disk size format '${t.diskSize}'. Using default: ${N}GB`)}return{vcpu:e,memoryMB:o,diskSizeGB:i}},Do=async(t,e)=>{let o=await fo(e);if(!o.success)throw"isRequestError"in o.error?new Error(`HTTP ${o.error.status}: ${o.error.message}`):new Error(`Validation error: ${o.error.issues}`);let i=o.data,n=null,a=null;if(t.nodeId){if(n=i.nodes.find(c=>c.teepod_id===Number(t.nodeId)),!n)throw new Error(`Node ${t.nodeId} not found, available nodes: ${i.nodes.map(c=>c.teepod_id).join(", ")}`)}else if(t.interactive){let{node:c}=await z.prompt([{type:"list",name:"node",message:"Select a Node to use:",choices:i.nodes.map(l=>({name:`${l.name} (Region: ${l.region_identifier})`,value:l}))}]);n=c,t.nodeId=c.teepod_id}else n=i.nodes[0],t.nodeId=i.nodes[0].teepod_id;if(!n)throw new Error(`No available nodes found, available nodes: ${i.nodes.map(c=>c.teepod_id).join(", ")}`);if(n.support_onchain_kms){let c=await yo(e);if(!c.success)throw"isRequestError"in c.error?new Error(`HTTP ${c.error.status}: ${c.error.message}`):new Error(`Validation error: ${c.error.issues}`);let l=c.data;if(t.kmsId)a=l.items.find(m=>m.slug===t.kmsId||m.id===t.kmsId);else if(t.interactive){let{kmsChoice:m}=await z.prompt([{type:"list",name:"kmsChoice",message:"Select a KMS to use:",choices:l.items.map(d=>({name:d.chain_id?`${d.slug} (Chain ID: ${d.chain_id})`:`${d.slug} (No chain required)`,value:d}))}]);a=m,t.kmsId=m.slug}else throw new Error(`Node ${n.name} requires a KMS ID for Contract Owned CVM, available kms: ${l.items.map(m=>m.slug).join(", ")}`);if(a)await So(t,a.chain_id);else throw new Error(`KMS ${t.kmsId} not found, available kms: ${l.items.map(m=>m.slug).join(", ")}`)}let s=n.images[0];if(t.image){if(s=n.images.find(c=>c.name===t.image),!s)throw new Error(`Image ${t.image} not found in the node ${n.name}, available images: ${n.images.map(c=>c.name).join(", ")}.`)}else if(t.interactive){let{imageChoice:c}=await z.prompt([{type:"list",name:"imageChoice",message:"Select an image to use:",choices:n.images.map(l=>({name:`${l.name}`,value:l}))}]);s=c}if(!s)throw new Error(`No available OS images found in the node ${n.name}, available images: ${n.images.map(c=>c.name).join(", ")}.`);return{target:n,kms:a,image:s}},Io=async(t,e,o,i)=>{await Eo(t);let{vcpu:n,memoryMB:a,diskSizeGB:s}=await $o(t),{target:c,kms:l,image:m}=await Do(t,i),d={name:t.name,compose_file:{docker_compose_file:e},vcpu:n,memory:a,disk_size:s,node_id:c.teepod_id,image:m.name,kms_id:l?.slug},g=await vo(i,d);if(!g.success)throw new Error("Failed to provision CVM:",g.error);let p=g.data,u;if(p.app_env_encrypt_pubkey&&p.app_id||!l?.chain_id){let f=await Fe(o,p.app_env_encrypt_pubkey);u=await Zr(i,{app_id:p.app_id,encrypted_env:f,compose_hash:p.compose_hash,kms_id:l?.slug})}else{let f=l.slug,P=l.kms_contract_address,_=l.chain,le=t.privateKey,w=p.compose_hash,b=c.device_id,Qr=t.rpcUrl,pe=await po({chain:_,rpcUrl:Qr,kmsContractAddress:P,privateKey:le,deviceId:b,composeHash:w});if(!pe.success){let tt=pe?.error?.message;throw new Error(`Deployment contract failed: ${tt}`)}let de=pe.data,Te=de.appId,ue=await uo(i,{app_id:Te,kms:f});if(!ue.success)throw new Error(`Failed to get app env encrypt pubkey: ${ue.error.message}`);let et=ue.data,rt=await Fe(o,et.public_key);u=await Zr(i,{app_id:Te,encrypted_env:rt,compose_hash:p.compose_hash,kms_id:f,contract_address:de.appAuthAddress,deployer_address:de.deployer})}if(!u.success)throw"isRequestError"in u.error?new Error(`HTTP ${u.error.status}: ${u.error.message}`):new Error(`Validation error: ${u.error.issues}`);let v=u.data;if(Wr(v.vm_uuid),t?.json!==!1)console.log(JSON.stringify({success:!0,vm_uuid:v.vm_uuid,name:v.name,app_id:v.app_id,dashboard_url:`${y}/dashboard/cvms/${v.vm_uuid}`},null,2));else{let f=Me`
84
+ `));if(!be.existsSync(o))throw new Error(`Docker compose file not found: ${o}`);return be.readFileSync(o,"utf8")}function lo({uuid:o}={}){return o||Kr()}var po=async(o,r)=>{if(!o.privateKey&&process.env.PRIVATE_KEY&&(o.privateKey=process.env.PRIVATE_KEY),o.kmsId&&r&&!o.privateKey)if(o.interactive){let{privateKey:t}=await z.prompt([{type:"password",name:"privateKey",message:"Enter your private key:",validate:i=>i.trim()?!0:"Private key is required"}]);o.privateKey=t}else throw new Error("When using on-chain KMS, either --private-key (or PRIVATE_KEY env) must be provided")},uo=async o=>{if(!o.name){let r=Jt.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g,"-");r.length<3&&(r=r+"-cvm");let t=r.slice(0,20);if(!o.interactive)o.name=t;else{let{name:i}=await z.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",default:t,validate:n=>n.trim()?n.trim().length>20?"CVM name must be less than 20 characters":n.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(n)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);o.name=i}}},fo=async o=>{let r=[],t=o.envFile;if(o.interactive&&(!o.envFile||t===!0)&&(t=await $("Enter the path to your environment file:",".env","file")),t&&t!==!0)try{let i=be.readFileSync(t,{encoding:"utf8"});r=Zt(i)}catch(i){throw new Error(`Error reading environment file ${t}:`,i)}return r},go=async o=>{let r=M;if(o.vcpu)try{r=Number(o.vcpu)}catch{throw new Error(`Invalid vCPU format '${o.vcpu}'. Using default: ${M}`)}let t=T;if(o.memory)try{t=Tr(o.memory)}catch{throw new Error(`Invalid memory format '${o.memory}'. Using default: ${T}MB`)}let i=V;if(o.diskSize)try{i=Vr(o.diskSize)}catch{throw new Error(`Invalid disk size format '${o.diskSize}'. Using default: ${V}GB`)}return{vcpu:r,memoryMB:t,diskSizeGB:i}},ho=async(o,r)=>{let t=await to(r);if(!t.success)throw"isRequestError"in t.error?new Error(`HTTP ${t.error.status}: ${t.error.message}`):new Error(`Validation error: ${t.error.issues}`);let i=t.data,n=null,a=null;if(o.nodeId){if(n=i.nodes.find(c=>c.teepod_id===Number(o.nodeId)),!n)throw new Error(`Node ${o.nodeId} not found, available nodes: ${i.nodes.map(c=>c.teepod_id).join(", ")}`)}else if(o.interactive){let{node:c}=await z.prompt([{type:"list",name:"node",message:"Select a Node to use:",choices:i.nodes.map(l=>({name:`${l.name} (Region: ${l.region_identifier})`,value:l}))}]);n=c,o.nodeId=c.teepod_id}else n=i.nodes[0],o.nodeId=i.nodes[0].teepod_id;if(!n)throw new Error(`No available nodes found, available nodes: ${i.nodes.map(c=>c.teepod_id).join(", ")}`);if(n.support_onchain_kms){let c=await no(r);if(!c.success)throw"isRequestError"in c.error?new Error(`HTTP ${c.error.status}: ${c.error.message}`):new Error(`Validation error: ${c.error.issues}`);let l=c.data;if(o.kmsId)a=l.items.find(m=>m.slug===o.kmsId||m.id===o.kmsId);else if(o.interactive){let{kmsChoice:m}=await z.prompt([{type:"list",name:"kmsChoice",message:"Select a KMS to use:",choices:l.items.map(d=>({name:d.chain_id?`${d.slug} (Chain ID: ${d.chain_id})`:`${d.slug} (No chain required)`,value:d}))}]);a=m,o.kmsId=m.slug}else throw new Error(`Node ${n.name} requires a KMS ID for Contract Owned CVM, available kms: ${l.items.map(m=>m.slug).join(", ")}`);if(a)await po(o,a.chain_id);else throw new Error(`KMS ${o.kmsId} not found, available kms: ${l.items.map(m=>m.slug).join(", ")}`)}let s=n.images[0];if(o.image){if(s=n.images.find(c=>c.name===o.image),!s)throw new Error(`Image ${o.image} not found in the node ${n.name}, available images: ${n.images.map(c=>c.name).join(", ")}.`)}else if(o.interactive){let{imageChoice:c}=await z.prompt([{type:"list",name:"imageChoice",message:"Select an image to use:",choices:n.images.map(l=>({name:`${l.name}`,value:l}))}]);s=c}if(!s)throw new Error(`No available OS images found in the node ${n.name}, available images: ${n.images.map(c=>c.name).join(", ")}.`);return{target:n,kms:a,image:s}},yo=async(o,r,t,i)=>{await uo(o);let{vcpu:n,memoryMB:a,diskSizeGB:s}=await go(o),{target:c,kms:l,image:m}=await ho(o,i),d={name:o.name,compose_file:{docker_compose_file:r},vcpu:n,memory:a,disk_size:s,node_id:c.teepod_id,image:m.name,kms_id:l?.slug},g=await so(i,d);if(!g.success)throw new Error("Failed to provision CVM:",g.error);let p=g.data,u;if(p.app_env_encrypt_pubkey&&p.app_id||!l?.chain_id){let f=await Ee(t,p.app_env_encrypt_pubkey);u=await zr(i,{app_id:p.app_id,encrypted_env:f,compose_hash:p.compose_hash,kms_id:l?.slug})}else{let f=l.slug,I=l.kms_contract_address,_=l.chain,se=o.privateKey,w=p.compose_hash,E=c.device_id,Gr=o.rpcUrl,ae=await eo({chain:_,rpcUrl:Gr,kmsContractAddress:I,privateKey:se,deviceId:E,composeHash:w});if(!ae.success){let qr=ae?.error?.message;throw new Error(`Deployment contract failed: ${qr}`)}let ce=ae.data,De=ce.appId,me=await ro(i,{app_id:De,kms:f});if(!me.success)throw new Error(`Failed to get app env encrypt pubkey: ${me.error.message}`);let jr=me.data,Hr=await Ee(t,jr.public_key);u=await zr(i,{app_id:De,encrypted_env:Hr,compose_hash:p.compose_hash,kms_id:f,contract_address:ce.appAuthAddress,deployer_address:ce.deployer})}if(!u.success)throw"isRequestError"in u.error?new Error(`HTTP ${u.error.status}: ${u.error.message}`):new Error(`Validation error: ${u.error.issues}`);let v=u.data;if(Or(v.vm_uuid),o?.json!==!1)console.log(JSON.stringify({success:!0,vm_uuid:v.vm_uuid,name:v.name,app_id:v.app_id,dashboard_url:`${y}/dashboard/cvms/${v.vm_uuid}`},null,2));else{let f=$e`
85
85
  CVM created successfully!
86
86
 
87
87
  CVM ID: ${v.vm_uuid}
88
88
  Name: ${v.name}
89
89
  App ID: ${v.app_id}
90
90
  Dashboard URL: ${y}/dashboard/cvms/${v.vm_uuid}
91
- `;console.log(f)}},Po=async(t,e,o,i)=>{let[n,a]=await Promise.all([ho(i,{uuid:t.uuid}),go(i,{uuid:t.uuid})]);if(!n.success)throw new Error(`Failed to get cvm info: ${n.error.message}`);if(!a.success)throw new Error(`Failed to get cvm compose file: ${a.error.message}`);let s=n.data,c=a.data;c.docker_compose_file=e,c.allowed_envs=o.map(p=>p.key),console.log(`Preparing update for CVM ${t.uuid}...`);let l=await Co(i,{uuid:t.uuid,app_compose:c});if(!l.success)throw new Error(`Failed to provision cvm compose file: ${l.error.message}`);let m=l.data,d;if(s.kms_info?.chain_id){if(!t.privateKey)throw new Error("Private key is required for contract DstackApp");let p=await mo({chain:s.kms_info?.chain,rpcUrl:t.rpcUrl,appId:s.app_id,composeHash:m.compose_hash,privateKey:t.privateKey});if(!p.success){let u=p?.error?.message;throw new Error(`Failed to add compose hash: ${u}`)}}else o.length>0&&(d=await Fe(o,s.encrypted_env_pubkey));let g=await lo(i,{id:t.uuid,compose_hash:m.compose_hash,encrypted_env:d,env_keys:o.map(p=>p.key)});if(!g.success)throw new Error(`Failed to commit CVM compose file update: ${g.error.message}`);t?.json!==!1?console.log(JSON.stringify({success:!0,vm_uuid:t.uuid,name:s.name,app_id:s.app_id,dashboard_url:`${y}/dashboard/cvms/${t.uuid}`},null,2)):console.log("CVM compose file updated successfully!")},Xr=new no().command("deploy [compose]").description("Create a new CVM with on-chain KMS in one step.").option("--json","Output in JSON format",!1).option("--no-json","Disable JSON output format").option("--debug","Enable debug logging",!1).option("--api-key <apiKey>","API key for authentication").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file (default: docker-compose.yml in current directory)").option("--vcpu <vcpu>",`Number of vCPUs, default is ${T}`).option("--memory <memory>",`Memory with optional unit (e.g., 2G, 1024MB), default is ${V}MB`).option("--disk-size <diskSize>",`Disk size with optional unit (e.g., 50G, 100GB), default is ${N}GB`).option("--image <image>","Version of dstack image to use").option("--node-id <nodeId>","Node ID to use").option("-e, --env-file <envFile>","Prompt for environment variables and save to file (optional)").option("-i, --interactive","Enable interactive mode for required parameters",!1).option("--kms-id <kmsId>","KMS ID to use.").option("--uuid <uuid>","UUID of the CVM to upgrade").addOption(new so("--custom-app-id <customAppId>","Custom App ID to use.").hideHelp()).option("--pre-launch-script <preLaunchScript>","Path to pre-launch script").option("--private-key <privateKey>","Private key for signing transactions.").option("--rpc-url <rpcUrl>","RPC URL for the blockchain.").action(async(t,e)=>{try{let o=t||e.compose,i=await wo({apiKey:e.apiKey,interactive:e.interactive}),n=await ko({dockerComposePath:o,interactive:e.interactive}),a=_o({uuid:e.uuid}),s=await bo(e);!!a?await Po({...e,uuid:a},n,s,i):await Io({...e,uuid:a},n,s,i)}catch(o){e.json!==!1?console.error(JSON.stringify({success:!1,error:o.message,stack:e.debug&&o instanceof Error?o.stack:void 0},null,2)):console.error(Me`${o.message}`),process.exit(1)}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function xo(){new Ao().name("phala").alias("pha").description(`${Xe}
92
- Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.15").addCommand(Kr).addCommand(ir).addCommand(Rr).addCommand(Cr).addCommand(be).addCommand(Or).addCommand(Xr).parse(process.argv)}xo().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
91
+ `;console.log(f)}},vo=async(o,r,t,i)=>{let[n,a]=await Promise.all([io(i,{uuid:o.uuid}),oo(i,{uuid:o.uuid})]);if(!n.success)throw new Error(`Failed to get cvm info: ${n.error.message}`);if(!a.success)throw new Error(`Failed to get cvm compose file: ${a.error.message}`);let s=n.data,c=a.data;c.docker_compose_file=r,c.allowed_envs=t.map(p=>p.key),console.log(`Preparing update for CVM ${o.uuid}...`);let l=await ao(i,{uuid:o.uuid,app_compose:c});if(!l.success)throw new Error(`Failed to provision cvm compose file: ${l.error.message}`);let m=l.data,d;if(s.kms_info?.chain_id){if(!o.privateKey)throw new Error("Private key is required for contract DstackApp");let p=await Xt({chain:s.kms_info?.chain,rpcUrl:o.rpcUrl,appId:s.app_id,composeHash:m.compose_hash,privateKey:o.privateKey});if(!p.success){let u=p?.error?.message;throw new Error(`Failed to add compose hash: ${u}`)}}else t.length>0&&(d=await Ee(t,s.encrypted_env_pubkey));let g=await Qt(i,{id:o.uuid,compose_hash:m.compose_hash,encrypted_env:d,env_keys:t.map(p=>p.key)});if(!g.success)throw new Error(`Failed to commit CVM compose file update: ${g.error.message}`);o?.json!==!1?console.log(JSON.stringify({success:!0,vm_uuid:o.uuid,name:s.name,app_id:s.app_id,dashboard_url:`${y}/dashboard/cvms/${o.uuid}`},null,2)):console.log("CVM compose file updated successfully!")},Br=new Yt().command("deploy [compose]").description("Create a new CVM with on-chain KMS in one step.").option("--json","Output in JSON format",!1).option("--no-json","Disable JSON output format").option("--debug","Enable debug logging",!1).option("--api-key <apiKey>","API key for authentication").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file (default: docker-compose.yml in current directory)").option("--vcpu <vcpu>",`Number of vCPUs, default is ${M}`).option("--memory <memory>",`Memory with optional unit (e.g., 2G, 1024MB), default is ${T}MB`).option("--disk-size <diskSize>",`Disk size with optional unit (e.g., 50G, 100GB), default is ${V}GB`).option("--image <image>","Version of dstack image to use").option("--node-id <nodeId>","Node ID to use").option("-e, --env-file <envFile>","Prompt for environment variables and save to file (optional)").option("-i, --interactive","Enable interactive mode for required parameters",!1).option("--kms-id <kmsId>","KMS ID to use.").option("--uuid <uuid>","UUID of the CVM to upgrade").addOption(new Wt("--custom-app-id <customAppId>","Custom App ID to use.").hideHelp()).option("--pre-launch-script <preLaunchScript>","Path to pre-launch script").option("--private-key <privateKey>","Private key for signing transactions.").option("--rpc-url <rpcUrl>","RPC URL for the blockchain.").action(async(o,r)=>{try{let t=o||r.compose,i=await co({apiKey:r.apiKey,interactive:r.interactive}),n=await mo({dockerComposePath:t,interactive:r.interactive}),a=lo({uuid:r.uuid}),s=await fo(r);!!a?await vo({...r,uuid:a},n,s,i):await yo({...r,uuid:a},n,s,i)}catch(t){r.json!==!1?console.error(JSON.stringify({success:!1,error:t.message,stack:r.debug&&t instanceof Error?t.stack:void 0},null,2)):console.error($e`${t.message}`),process.exit(1)}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function wo(){new Co().name("phala").alias("pha").description(`${je}
92
+ Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.15").addCommand(Fr).addCommand(We).addCommand(Pr).addCommand(lr).addCommand(Ce).addCommand(xr).addCommand(Br).parse(process.argv)}wo().catch(o=>{e.error("An error occurred:",o),process.exit(1)});
93
93
  //# sourceMappingURL=index.js.map