phala 0.0.1-alpha → 0.0.1-alpha-6

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 bun
2
- import{a as we,b as r}from"./chunk-A4IAJHG6.js";import{Command as so}from"commander";import Se from"chalk";var ke=Se.hex("#cdfa50"),Ee=ke(`
2
+ import{a as $e,b as r}from"./chunk-DGIS5AEA.js";import{Command as So}from"commander";import De from"chalk";var Ie=De.hex("#cdfa50"),Fe=Ie(`
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{a as we,b as r}from"./chunk-A4IAJHG6.js";import{Command as so}from"comman
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=ke(`
24
+ `),_o=Ie(`
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,7 +43,7 @@ import{a as we,b as r}from"./chunk-A4IAJHG6.js";import{Command as so}from"comman
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
- `),co=Se.cyan("PHALA TEE CLOUD CLI");import{Command as dr}from"commander";import{Command as cr}from"commander";import $ from"fs";import me from"path";import I from"os";import W from"crypto";var N=me.join(I.homedir(),".phala-cloud"),O=me.join(N,"api-key"),ae=me.join(N,"docker-credentials.json");function be(){if(!$.existsSync(N))try{$.mkdirSync(N,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${N}:`,t),t}}function _e(){let t=[I.hostname(),I.platform(),I.arch(),I.cpus()[0]?.model||"",I.userInfo().username],e=W.createHash("sha256");return e.update(t.join("|")),e.digest()}function xe(t){try{let e=_e(),o=W.randomBytes(16),n=W.createCipheriv("aes-256-cbc",e.slice(0,32),o),i=n.update(t,"utf8","hex");return i+=n.final("hex"),o.toString("hex")+":"+i}catch(e){throw r.error("Encryption failed:",e),new Error("Failed to encrypt data")}}function $e(t){try{let e=_e(),o=t.split(":");if(o.length!==2)throw new Error("Invalid encrypted format");let n=Buffer.from(o[0],"hex"),i=o[1],a=W.createDecipheriv("aes-256-cbc",e.slice(0,32),n),m=a.update(i,"hex","utf8");return m+=a.final("utf8"),m}catch(e){throw r.error("Decryption failed:",e),new Error("Failed to decrypt data")}}async function Pe(t){be();try{let e=xe(t);$.writeFileSync(O,e,{mode:384})}catch(e){throw r.error("Failed to save API key:",e),e}}async function X(){try{if($.existsSync(O)){let t=$.readFileSync(O,"utf8").trim();return $e(t)}return null}catch(t){return r.error("Failed to read API key:",t),null}}async function U(){try{$.existsSync(O)?($.unlinkSync(O),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 De(t){be();try{t.password=xe(t.password),$.writeFileSync(ae,JSON.stringify(t,null,2),{mode:384}),r.success("Docker credentials saved successfully.")}catch(e){throw r.error("Failed to save Docker credentials:",e),e}}async function x(){try{if($.existsSync(ae)){let t=$.readFileSync(ae,"utf8"),e=JSON.parse(t);return e.password&&(e.password=$e(e.password)),e}return null}catch(t){return r.error("Failed to read Docker credentials:",t),null}}import pr from"prompts";import Wt from"axios";var ce=process.env.CLOUD_API_URL||"https://cloud-api.phala.network",T=process.env.CLOUD_URL||"https://cloud.phala.network",Ie="0.0.1",pe="https://hub.docker.com/v2",Te="phalanetwork/tappd-simulator:latest",L=1,z=2048,j=20,C={USER_INFO:"/api/v1/auth/me",TEEPODS:"/api/v1/teepods?enabled=true",TEEPOD_IMAGES:t=>`/api/v1/teepods/${t}/images`,CVMS:t=>`/api/v1/cvms?user_id=${t}`,CVM_BY_APP_ID:t=>`/api/v1/cvms/app_${t}`,CVM_START:t=>`/api/v1/cvms/app_${t}/start`,CVM_STOP:t=>`/api/v1/cvms/app_${t}/stop`,CVM_RESTART:t=>`/api/v1/cvms/app_${t}/restart`,CVM_LOGS:t=>`/api/v1/cvms/app_${t}/logs`,CVM_FROM_CONFIGURATION:"/api/v1/cvms/from_cvm_configuration",CVM_PUBKEY:"/api/v1/cvms/pubkey/from_cvm_configuration",CVM_UPGRADE:t=>`/api/v1/cvms/app_${t}/compose`,CVM_ATTESTATION:t=>`/api/v1/cvms/app_${t}/attestation`,CVM_RESIZE:t=>`/api/v1/cvms/app_${t}/resources`},Fe=`version: '3.8'
46
+ `),xo=De.cyan("PHALA TEE CLOUD CLI");import{Command as br}from"commander";import{Command as wr}from"commander";import x from"fs";import fe from"path";import R from"os";import oe from"crypto";var z=fe.join(R.homedir(),".phala-cloud"),j=fe.join(z,"api-key"),de=fe.join(z,"docker-credentials.json");function Te(){if(!x.existsSync(z))try{x.mkdirSync(z,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${z}:`,t),t}}function Ae(){let t=[R.hostname(),R.platform(),R.arch(),R.cpus()[0]?.model||"",R.userInfo().username],e=oe.createHash("sha256");return e.update(t.join("|")),e.digest()}function nr(t){try{let e=Ae(),o=oe.randomBytes(16),n=oe.createCipheriv("aes-256-cbc",e.slice(0,32),o),s=n.update(t,"utf8","hex");return s+=n.final("hex"),o.toString("hex")+":"+s}catch(e){throw r.error("Encryption failed:",e),new Error("Failed to encrypt data")}}function ir(t){try{let e=Ae(),o=t.split(":");if(o.length!==2)throw new Error("Invalid encrypted format");let n=Buffer.from(o[0],"hex"),s=o[1],a=oe.createDecipheriv("aes-256-cbc",e.slice(0,32),n),m=a.update(s,"hex","utf8");return m+=a.final("utf8"),m}catch(e){throw r.error("Decryption failed:",e),new Error("Failed to decrypt data")}}async function Re(t){Te();try{let e=nr(t);x.writeFileSync(j,e,{mode:384})}catch(e){throw r.error("Failed to save API key:",e),e}}async function ne(){try{if(x.existsSync(j)){let t=x.readFileSync(j,"utf8").trim();return ir(t)}return null}catch(t){return r.error("Failed to read API key:",t),null}}async function B(){try{x.existsSync(j)?(x.unlinkSync(j),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 Me(t){Te();try{x.writeFileSync(de,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 P(){try{if(x.existsSync(de)){let t=x.readFileSync(de,"utf8");return JSON.parse(t)}return null}catch(t){return r.error("Failed to read Docker credentials:",t),null}}import Sr from"prompts";import sr from"axios";var ge=process.env.CLOUD_API_URL||"https://cloud-api.phala.network",M=process.env.CLOUD_URL||"https://cloud.phala.network",Ve="0.0.1",Ne="https://hub.docker.com/v2",Oe="phalanetwork/tappd-simulator:latest",G=2,K=4096,q=40,Le="3",Ue="dstack-0.3.5",y={USER_INFO:"/api/v1/auth/me",TEEPODS:"/api/v1/teepods/available",TEEPOD_IMAGES:t=>`/api/v1/teepods/${t}/images`,CVMS:t=>`/api/v1/cvms?user_id=${t}`,CVM_BY_APP_ID:t=>`/api/v1/cvms/app_${t}`,CVM_START:t=>`/api/v1/cvms/app_${t}/start`,CVM_STOP:t=>`/api/v1/cvms/app_${t}/stop`,CVM_RESTART:t=>`/api/v1/cvms/app_${t}/restart`,CVM_LOGS:t=>`/api/v1/cvms/app_${t}/logs`,CVM_FROM_CONFIGURATION:"/api/v1/cvms/from_cvm_configuration",CVM_PUBKEY:"/api/v1/cvms/pubkey/from_cvm_configuration",CVM_UPGRADE:t=>`/api/v1/cvms/app_${t}/compose`,CVM_ATTESTATION:t=>`/api/v1/cvms/app_${t}/attestation`,CVM_RESIZE:t=>`/api/v1/cvms/app_${t}/resources`},ze=`version: '3.8'
47
47
  services:
48
48
  postgres:
49
49
  image: postgres:15
@@ -88,7 +88,7 @@ networks:
88
88
  driver: bridge
89
89
 
90
90
  volumes:
91
- postgres-data:`,Ae=`version: '3.8'
91
+ postgres-data:`,je=`version: '3.8'
92
92
  services:
93
93
  app:
94
94
  image: {{imageName}}:{{tag}}
@@ -99,16 +99,20 @@ services:
99
99
  {{#each envVars}} - {{{this}}}
100
100
  {{/each}}
101
101
  restart: always
102
- `;function le(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}var ue=class{client;apiKey=null;constructor(e){r.debug(`Creating API client with base URL: ${e}`),this.client=Wt.create({baseURL:e,headers:{"Content-Type":"application/json","User-Agent":`tee-cloud-cli/${Ie}`}}),this.client.interceptors.request.use(async o=>{if(!this.apiKey){if(this.apiKey=await X(),!this.apiKey)throw new Error('API key not found. Please set an API key first with "phala auth login"');r.debug(`API key loaded: ${this.apiKey.substring(0,5)}...`)}return o.headers["X-API-Key"]=this.apiKey,r.debug(`Making request to: ${o.baseURL}${o.url}`),o}),this.client.interceptors.response.use(o=>(r.debug(`Received successful response from: ${o.config.url}`),o),o=>{if(o.response){let{status:n,data:i}=o.response;r.debug(`Received error response: ${n} - ${le(i)}`),n===401?r.error("Authentication failed. Please check your API key."):n===403?r.error("You do not have permission to perform this action."):n===404?r.error("Resource not found."):r.error(`API Error (${n}): ${i.message||le(i)}`)}else o.request?(r.error("No response received from the server. Please check your internet connection."),r.debug(`Request details: ${le(o.request).substring(0,200)}...`)):r.error(`Error: ${o.message}`);return Promise.reject(o)})}async get(e,o){try{return r.debug(`GET request to: ${e}`),(await this.client.get(e,o)).data}catch(n){throw r.debug(`GET request failed: ${n instanceof Error?n.message:String(n)}`),n}}async post(e,o,n){try{return r.debug(`POST request to: ${e}`),(await this.client.post(e,o,n)).data}catch(i){throw r.debug(`POST request failed: ${i instanceof Error?i.message:String(i)}`),i}}async put(e,o,n){try{return r.debug(`PUT request to: ${e}`),(await this.client.put(e,o,n)).data}catch(i){throw r.debug(`PUT request failed: ${i instanceof Error?i.message:String(i)}`),i}}async delete(e,o){try{return r.debug(`DELETE request to: ${e}`),(await this.client.delete(e,o)).data}catch(n){throw r.debug(`DELETE request failed: ${n instanceof Error?n.message:String(n)}`),n}}async patch(e,o,n){try{return r.debug(`PATCH request to: ${e}`),(await this.client.patch(e,o,n)).data}catch(i){throw r.debug(`PATCH request failed: ${i instanceof Error?i.message:String(i)}`),i}}};r.debug(`Initializing API client with URL: ${ce}`);var w=new ue(ce);import{z as s}from"zod";import{INVALID as Xt,ParseStatus as Qt,ZodIssueCode as F,ZodParsedType as Me,ZodType as er,addIssueToContext as A,z as Ve}from"zod";var tr="ZodDecimal",rr=/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,G=class extends er{_parse(e){if(e.data!==null&&typeof e.data=="object"&&"toNumber"in e.data&&(e.data=e.data.toNumber()),this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Me.number){let a=this._getOrReturnCtx(e);return A(a,{code:F.invalid_type,expected:Me.number,received:a.parsedType}),Xt}let n,i=new Qt;for(let a of this._def.checks)if(a.kind==="precision"){let m=e.data.toString().match(rr);Math.max((m[1]?m[1].length:0)-(m[2]?parseInt(m[2],10):0),0)>a.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:F.custom,message:a.message,params:{precision:a.value}}),i.dirty())}else a.kind==="wholeNumber"?e.data.toString().split(".")[0].length>a.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:F.custom,message:a.message,params:{wholeNumber:a.value}}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:F.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:F.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="finite"&&(Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:F.not_finite,message:a.message}),i.dirty()));return{status:i.value,value:e.data}}setLimit(e,o,n,i){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:o,inclusive:n,message:i}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}lte(e,o){return this.setLimit("max",e,!0,o)}lt(e,o){return this.setLimit("max",e,!1,o)}max=this.lte;gt(e,o){return this.setLimit("min",e,!1,o)}gte(e,o){return this.setLimit("min",e,!0,o)}min=this.gte;precision(e,o){return this._addCheck({kind:"precision",value:e,message:o})}wholeNumber(e,o){return this._addCheck({kind:"wholeNumber",value:e,message:o})}get minValue(){let e=null;for(let o of this._def.checks)o.kind==="min"&&(e===null||o.value>e)&&(e=o.value);return e}get maxValue(){let e=null;for(let o of this._def.checks)o.kind==="max"&&(e===null||o.value<e)&&(e=o.value);return e}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e})}finite(e){return this._addCheck({kind:"finite",message:e})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e})}get isFinite(){let e=null,o=null;for(let n of this._def.checks){if(n.kind==="finite")return!0;n.kind==="min"?(o===null||n.value>o)&&(o=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(o)&&Number.isFinite(e)}},B=G;we(B,"create",e=>new G({checks:[],typeName:tr,coerce:e?.coerce??!1}));var Re=Ve.object({template:Ve.string().min(1,"Template cannot be empty")});var or=s.object({password:s.string(),registry:s.string().nullable(),username:s.string()}),nr=s.object({docker_compose_file:s.string(),docker_config:or.optional(),features:s.array(s.string()),kms_enabled:s.boolean(),manifest_version:s.number(),name:s.string(),public_logs:s.boolean(),public_sysinfo:s.boolean(),runner:s.string().optional(),salt:s.string().nullable().optional(),tproxy_enabled:s.boolean(),version:s.string().optional()}),sr=s.object({name:s.string(),image:s.string(),compose_file:nr,vcpu:s.number(),memory:s.number(),disk_size:s.number(),ports:s.array(s.any())}),ir=s.object({id:s.string(),name:s.string(),status:s.string(),uptime:s.string(),app_url:s.string(),app_id:s.string(),instance_id:s.string(),configuration:sr,exited_at:s.string(),boot_progress:s.string(),boot_error:s.string(),shutdown_progress:s.string(),image_version:s.string()}),ar=s.object({id:s.number(),username:s.string()}),mr=s.object({id:s.number(),name:s.string()}),de=s.object({hosted:ir,name:s.string(),managed_user:ar,node:mr,listed:s.boolean(),status:s.string(),in_progress:s.boolean(),dapp_dashboard_url:s.string().nullable(),syslog_endpoint:s.string(),allow_upgrade:s.boolean()}),Ne=s.object({id:s.number(),name:s.string(),status:s.string(),teepod_id:s.number(),teepod:s.object({id:s.number(),name:s.string()}),user_id:s.number(),app_id:s.string(),vm_uuid:s.string().nullable(),instance_id:s.string().nullable(),app_url:s.string().nullable(),base_image:s.string(),vcpu:s.number(),memory:s.number(),disk_size:s.number(),manifest_version:s.number(),version:s.string(),runner:s.string(),docker_compose_file:s.string(),features:s.array(s.string()).nullable(),created_at:s.string(),encrypted_env_pubkey:s.string()}),Oe=s.object({app_env_encrypt_pubkey:s.string(),app_id_salt:s.string()}),Ue=s.object({id:s.number(),teepod_id:s.number(),teepod:s.object({id:s.number(),name:s.string()}),name:s.string(),status:s.string(),in_progress:s.boolean(),app_id:s.string(),vm_uuid:s.string(),instance_id:s.string(),vcpu:s.number(),memory:s.number(),disk_size:s.number(),base_image:s.string(),encrypted_env_pubkey:s.string(),listed:s.boolean(),project_id:s.string(),project_type:s.string().nullable()}),Le=s.object({username:s.string(),email:s.string(),credits:B.create({coerce:!0}),role:s.string(),avatar:s.string(),flag_reset_password:s.boolean(),team_name:s.string(),team_tier:s.string(),trial_ended_at:s.string().nullable()}),Ro=s.array(de),ze=s.object({detail:s.string()}),No=s.object({key:s.string(),value:s.string()}),je=s.object({id:s.number(),name:s.string(),status:s.string()}),Be=s.object({name:s.string(),description:s.string().optional()});function Ge(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}async function q(){try{r.debug(`Fetching user info from ${C.USER_INFO}`);let t=await w.get(C.USER_INFO);r.debug(`Received response: ${Ge(t)}`);try{return Le.parse(t)}catch(e){throw r.error(`Failed to parse user info response: ${e}`),r.debug(`Response structure: ${Ge(t)}`),e}}catch(t){throw r.error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`),new Error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`)}}var qe=new cr().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async t=>{try{if(!t)t=(await pr({type:"password",name:"apiKey",message:"Enter your API key:",validate:async o=>{if(o.length===0)return"API key cannot be empty";try{if(await Pe(o),!(await q()).username)return await U(),"Invalid API key"}catch{return"Invalid API key"}return!0}})).apiKey;else if(!(await q()).username)return await U(),"Invalid API key";r.success("API key validated and saved successfully"),r.info(`
103
- You can check your authentication status with "phala auth status"`)}catch(e){r.error(`Failed to set API key: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as lr}from"commander";var Ke=new lr().name("logout").description("Remove the stored API key").action(async()=>{try{await U(),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{Command as ur}from"commander";var He=new ur().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async t=>{try{t.debug&&(process.env.DEBUG="true");let e=await X();if(!e){r.warn('Not authenticated. Please set an API key with "phala auth login"');return}r.debug(`Using API key: ${e.substring(0,5)}...`);let o=r.startSpinner("Checking authentication status");try{let n=await q();if(o.stop(!0),t.json){console.log(JSON.stringify(n,null,2));return}r.success(`Authenticated as ${n.username}`),r.break();let i={Username:n.username,Email:n.email,Role:n.role,Team:`${n.team_name} (${n.team_tier})`,Credits:`$${n.credits}`};n.trial_ended_at&&(i["Trial Ended At"]=n.trial_ended_at),console.table(i)}catch(n){o.stop(!1),r.error("Authentication failed. Your API key may be invalid or expired."),r.info('Please set a new API key with "phala auth login"'),t.debug&&r.debug(`Error details: ${n instanceof Error?n.message:String(n)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Ze=new dr().name("auth").description("Authenticate with Phala Cloud").addCommand(qe).addCommand(Ke).addCommand(He);import{Command as hr}from"commander";import{Command as fr}from"commander";import{z as Je}from"zod";async function M(){try{let t=await w.get(C.TEEPODS);return Je.array(je).parse(t)}catch(t){throw new Error(`Failed to get TEEPods: ${t instanceof Error?t.message:String(t)}`)}}async function Q(t){try{let e=await w.get(C.TEEPOD_IMAGES(t));return Je.array(Be).parse(e)}catch(e){throw new Error(`Failed to get TEEPod images: ${e instanceof Error?e.message:String(e)}`)}}var Ye=new fr().name("list").description("List available TEEPods").action(async()=>{try{let t=r.startSpinner("Fetching TEEPods"),e=await M();if(t.stop(!0),e.length===0){r.info("No TEEPods found");return}r.info("Available TEEPods:"),r.table(e,["id","name","status"])}catch(t){r.error(`Failed to list TEEPods: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as gr}from"commander";import yr from"inquirer";var We=new gr().name("images").description("List available images for a TEEPod").option("-t, --teepod-id <teepodId>","TEEPod ID").action(async t=>{try{let e=r.startSpinner(`Fetching images for TEEPod ${t.teepodId}`);if(!t.teepodId){let n=r.startSpinner("Fetching available TEEPods"),i=await M();n.stop(!0),i.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:a}=await yr.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:i.map(m=>({name:`${m.name} (${m.status})`,value:m.id}))}]);t.teepodId=a}let o=await Q(t.teepodId);if(e.stop(!0),o.length===0){r.info(`No images found for TEEPod ${t.teepodId}`);return}r.info(`Available images for TEEPod ${t.teepodId}:`),r.table(o,["name","description"])}catch(e){r.error(`Failed to list images: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Xe=new hr().name("teepods").description("TEEPod management commands").addCommand(Ye).addCommand(We);import{Command as Fr}from"commander";import{Command as _r}from"commander";import{execa as tt}from"execa";import D from"fs";import fe from"path";import rt from"axios";import vr from"handlebars";import{exec as wr,spawn as Sr}from"child_process";import{promisify as kr}from"util";import Er from"os";import Cr from"inquirer";import Qe from"fs";import et from"path";function E(t,e=process.cwd()){let o=et.resolve(e,t);if(!Qe.existsSync(o))throw new Error(`File not found at ${o}`);return!0}async function V(t,e,o="file",n=process.cwd()){return(await Cr.prompt([{type:"input",name:o,message:t,default:e,validate:a=>{let m=et.resolve(n,a);return Qe.existsSync(m)?!0:`File not found at ${m}`}}]))[o]}var ee=kr(wr),ot=".phala-cloud/logs",br=".phala-cloud/compose",nt=10,h=class{username;image;registry;constructor(e,o,n){this.image=e,this.username=o||"",this.registry=n||""}ensureLogsDir(){let e=fe.resolve(ot);D.existsSync(e)||D.mkdirSync(e,{recursive:!0})}getLogFilePath(e){let o=new Date().toISOString().replace(/[:.]/g,"-");return fe.resolve(ot,`${this.image}-${e}-${o}.log`)}getSystemArchitecture(){let e=Er.arch();switch(e){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return e}}spawnProcess(e,o,n){return new Promise((i,a)=>{let m=Sr(e,o),c=this.getLogFilePath(n);this.ensureLogsDir();let p=D.createWriteStream(c,{flags:"a"}),f=[],d=(u,y=!1)=>{let l=u.toString().split(`
104
- `);p.write(u),l.forEach(g=>{g.trim()&&(f.push(g),f.length>nt&&f.shift(),console.clear(),console.log(`Latest ${nt} lines (full log at ${c}):`),console.log("-".repeat(50)),f.forEach(k=>{y?console.error(k):console.log(k)}))})};m.stdout.on("data",u=>d(u)),m.stderr.on("data",u=>d(u,!0)),m.on("close",u=>{p.end(),u===0?(console.log(`
105
- Operation completed. Full log available at: ${c}`),i()):a(new Error(`Process exited with code ${u}. Check log file: ${c}`))}),m.on("error",u=>{p.end(),a(u)})})}setCredentials(e,o){this.username=e,o&&(this.registry=o)}async buildImage(e,o){try{let n=this.getSystemArchitecture(),i=`${this.username}/${this.image}:${o}`,a=r.startSpinner(`Building Docker image ${this.username}/${this.image}:${o}`);E(e);let m=["build","-t",i,"-f",e];return n==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),m.push("--platform","linux/amd64")),m.push("."),await this.spawnProcess("docker",m,"build"),a.stop(!0,`Docker image ${i} built successfully`),!0}catch(n){return r.error(`Failed to build Docker image: ${n instanceof Error?n.message:String(n)}`),!1}}async pushImage(e){try{let o=r.startSpinner(`Pushing Docker image ${this.username}/${this.image}:${e} to Docker Hub`);if(!await x())throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let i=`${this.username}/${this.image}:${e}`;return console.log(`Pushing image ${i} to Docker Hub...`),await this.spawnProcess("docker",["push",i],"push"),o.stop(!0,`Docker image ${i} pushed successfully`),!0}catch(o){return r.error(`Failed to push Docker image: ${o instanceof Error?o.message:String(o)}`),!1}}async listTags(){try{let e=r.startSpinner(`Listing tags for ${this.username}/${this.image}`),o=await rt.get(`${pe}/repositories/${this.username}/${this.image}/tags`);if(!o.data||!o.data.results)throw e.stop(!1),new Error("Failed to get tags from Docker Hub");let n=o.data.results.map(i=>i.name);return e.stop(!0,`Found ${n.length} tags`),n}catch(e){return r.error(`Failed to list tags: ${e instanceof Error?e.message:String(e)}`),[]}}async deleteTag(e){try{let o=r.startSpinner(`Deleting tag ${this.username}/${this.image}:${e}`),n=await x();if(!n)throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let i=await rt.delete(`${pe}/repositories/${this.username}/${this.image}/tags/${e}`,{auth:{username:n.username,password:n.password}});return o.stop(!0,"Tag deleted successfully"),!0}catch(o){return r.error(`Failed to delete tag: ${o instanceof Error?o.message:String(o)}`),!1}}async login(e,o,n){try{let i=r.startSpinner(`Logging in to Docker Hub as ${e}`);return await tt("docker",["login",...n?[n]:[],"-u",e,"--password-stdin"],{input:o}),i.stop(!0,"Logged in to Docker Hub successfully"),!0}catch(i){return r.error(`Failed to login to Docker Hub: ${i instanceof Error?i.message:String(i)}`),!1}}async buildComposeFile(e,o,n){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let i=n=="eliza"?Fe:Ae,a=Re.parse({template:i}),m=br;D.existsSync(m)||(r.info(`Creating directory: ${m}`),D.mkdirSync(m,{recursive:!0}));let c=[];o&&(c=D.readFileSync(o,"utf-8").split(`
106
- `).filter(l=>l&&!l.startsWith("#")).map(l=>{let g=l.indexOf("#");return g>0&&(l=l.substring(0,g).trim()),l.trim()}).filter(l=>l.includes("=")).map(l=>{let[g,k]=l.split("=",2),v=g.trim();return(k?k.trim():"")===""?null:`${v}=${v}`}).filter(Boolean));let p=`${this.username}/${this.image}`,d=vr.compile(a.template,{noEscape:!0})({imageName:p,tag:e,envVars:c.map(y=>y.replace(/=.*/,"=${"+y.split("=")[0]+"}"))}),u=fe.join(m,`${this.image}-${e}-tee-compose.yaml`);return D.writeFileSync(u,d),r.success(`Backup of docker compose file created at: ${u}`),u}async runComposeLocally(e,o){try{let n=r.startSpinner(`Running Docker Compose file at ${e}
107
- - If you run with the simulator, set DSTACK_SIMULATOR_ENDPOINT to http://host.docker.internal:8090`);E(e);let i=["-f",e,"up","-d"];return o&&(E(o),i.splice(2,0,"--env-file",o)),await tt("docker-compose",i),n.stop(!0,"Docker Compose file running successfully"),!0}catch(n){return r.error(`Failed to run Docker Compose file: ${n instanceof Error?n.message:String(n)}`),!1}}async runSimulator(e){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await ee(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:o}=await ee(`docker run -d --name tee-simulator --rm -p 8090:8090 ${e}`),n=o.trim();return r.success(`TEE simulator running successfully. Container ID: ${n}`),r.info(`
102
+ `;function ye(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}var he=class{client;apiKey=null;constructor(e){r.debug(`Creating API client with base URL: ${e}`),this.client=sr.create({baseURL:e,headers:{"Content-Type":"application/json","User-Agent":`tee-cloud-cli/${Ve}`}}),this.client.interceptors.request.use(async o=>{if(!this.apiKey){if(this.apiKey=await ne(),!this.apiKey)throw new Error('API key not found. Please set an API key first with "phala auth login"');r.debug(`API key loaded: ${this.apiKey.substring(0,5)}...`)}return o.headers["X-API-Key"]=this.apiKey,r.debug(`Making request to: ${o.baseURL}${o.url}`),o}),this.client.interceptors.response.use(o=>(r.debug(`Received successful response from: ${o.config.url}`),o),o=>{if(o.response){let{status:n,data:s}=o.response;r.debug(`Received error response: ${n} - ${ye(s)}`),n===401?r.error("Authentication failed. Please check your API key."):n===403?r.error("You do not have permission to perform this action."):n===404?r.error("Resource not found."):r.error(`API Error (${n}): ${s.message||ye(s)}`)}else o.request?(r.error("No response received from the server. Please check your internet connection."),r.debug(`Request details: ${ye(o.request).substring(0,200)}...`)):r.error(`Error: ${o.message}`);return Promise.reject(o)})}async get(e,o){try{return r.debug(`GET request to: ${e}`),(await this.client.get(e,o)).data}catch(n){throw r.debug(`GET request failed: ${n instanceof Error?n.message:String(n)}`),n}}async post(e,o,n){try{return r.debug(`POST request to: ${e}`),(await this.client.post(e,o,n)).data}catch(s){throw r.debug(`POST request failed: ${s instanceof Error?s.message:String(s)}`),s}}async put(e,o,n){try{return r.debug(`PUT request to: ${e}`),(await this.client.put(e,o,n)).data}catch(s){throw r.debug(`PUT request failed: ${s instanceof Error?s.message:String(s)}`),s}}async delete(e,o){try{return r.debug(`DELETE request to: ${e}`),(await this.client.delete(e,o)).data}catch(n){throw r.debug(`DELETE request failed: ${n instanceof Error?n.message:String(n)}`),n}}async patch(e,o,n){try{return r.debug(`PATCH request to: ${e}`),(await this.client.patch(e,o,n)).data}catch(s){throw r.debug(`PATCH request failed: ${s instanceof Error?s.message:String(s)}`),s}}};r.debug(`Initializing API client with URL: ${ge}`);var v=new he(ge);import{z as i}from"zod";import{INVALID as ar,ParseStatus as mr,ZodIssueCode as V,ZodParsedType as Be,ZodType as cr,addIssueToContext as N,z as Ge}from"zod";var lr="ZodDecimal",pr=/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,Z=class extends cr{_parse(e){if(e.data!==null&&typeof e.data=="object"&&"toNumber"in e.data&&(e.data=e.data.toNumber()),this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Be.number){let a=this._getOrReturnCtx(e);return N(a,{code:V.invalid_type,expected:Be.number,received:a.parsedType}),ar}let n,s=new mr;for(let a of this._def.checks)if(a.kind==="precision"){let m=e.data.toString().match(pr);Math.max((m[1]?m[1].length:0)-(m[2]?parseInt(m[2],10):0),0)>a.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:V.custom,message:a.message,params:{precision:a.value}}),s.dirty())}else a.kind==="wholeNumber"?e.data.toString().split(".")[0].length>a.value&&(n=this._getOrReturnCtx(e,n),N(n,{code:V.custom,message:a.message,params:{wholeNumber:a.value}}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:V.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:V.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="finite"&&(Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:V.not_finite,message:a.message}),s.dirty()));return{status:s.value,value:e.data}}setLimit(e,o,n,s){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:o,inclusive:n,message:s}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}lte(e,o){return this.setLimit("max",e,!0,o)}lt(e,o){return this.setLimit("max",e,!1,o)}max=this.lte;gt(e,o){return this.setLimit("min",e,!1,o)}gte(e,o){return this.setLimit("min",e,!0,o)}min=this.gte;precision(e,o){return this._addCheck({kind:"precision",value:e,message:o})}wholeNumber(e,o){return this._addCheck({kind:"wholeNumber",value:e,message:o})}get minValue(){let e=null;for(let o of this._def.checks)o.kind==="min"&&(e===null||o.value>e)&&(e=o.value);return e}get maxValue(){let e=null;for(let o of this._def.checks)o.kind==="max"&&(e===null||o.value<e)&&(e=o.value);return e}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e})}finite(e){return this._addCheck({kind:"finite",message:e})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e})}get isFinite(){let e=null,o=null;for(let n of this._def.checks){if(n.kind==="finite")return!0;n.kind==="min"?(o===null||n.value>o)&&(o=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(o)&&Number.isFinite(e)}},H=Z;$e(H,"create",e=>new Z({checks:[],typeName:lr,coerce:e?.coerce??!1}));var Ke=Ge.object({template:Ge.string().min(1,"Template cannot be empty")});var ur=i.object({password:i.string(),registry:i.string().nullable(),username:i.string()}),dr=i.object({docker_compose_file:i.string(),docker_config:ur.optional(),features:i.array(i.string()),kms_enabled:i.boolean(),manifest_version:i.number(),name:i.string(),public_logs:i.boolean(),public_sysinfo:i.boolean(),runner:i.string().optional(),salt:i.string().nullable().optional(),tproxy_enabled:i.boolean(),version:i.string().optional()}),fr=i.object({name:i.string(),image:i.string(),compose_file:dr,vcpu:i.number(),memory:i.number(),disk_size:i.number(),ports:i.array(i.any())}),gr=i.object({id:i.string(),name:i.string(),status:i.string(),uptime:i.string(),app_url:i.string(),app_id:i.string(),instance_id:i.string(),configuration:fr,exited_at:i.string(),boot_progress:i.string(),boot_error:i.string(),shutdown_progress:i.string(),image_version:i.string()}),yr=i.object({id:i.number(),username:i.string()}),hr=i.object({id:i.number(),name:i.string()}),ve=i.object({hosted:gr,name:i.string(),managed_user:yr,node:hr,listed:i.boolean(),status:i.string(),in_progress:i.boolean(),dapp_dashboard_url:i.string().nullable(),syslog_endpoint:i.string(),allow_upgrade:i.boolean()}),qe=i.object({id:i.number(),name:i.string(),status:i.string(),teepod_id:i.number(),teepod:i.object({id:i.number(),name:i.string()}),user_id:i.number(),app_id:i.string(),vm_uuid:i.string().nullable(),instance_id:i.string().nullable(),app_url:i.string().nullable(),base_image:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),manifest_version:i.number(),version:i.string(),runner:i.string(),docker_compose_file:i.string(),features:i.array(i.string()).nullable(),created_at:i.string(),encrypted_env_pubkey:i.string()}),He=i.object({app_env_encrypt_pubkey:i.string(),app_id_salt:i.string()}),Ze=i.object({id:i.number(),teepod_id:i.number(),teepod:i.object({id:i.number(),name:i.string()}),name:i.string(),status:i.string(),in_progress:i.boolean(),app_id:i.string(),vm_uuid:i.string(),instance_id:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),base_image:i.string(),encrypted_env_pubkey:i.string(),listed:i.boolean(),project_id:i.string(),project_type:i.string().nullable()}),Je=i.object({username:i.string(),email:i.string(),credits:H.create({coerce:!0}),role:i.string(),avatar:i.string(),flag_reset_password:i.boolean(),team_name:i.string(),team_tier:i.string(),trial_ended_at:i.string().nullable()}),Xo=i.array(ve),Ye=i.object({detail:i.string()}),Qo=i.object({key:i.string(),value:i.string()}),Ce=i.object({name:i.string(),description:i.string().optional(),version:i.array(i.number()).optional(),is_dev:i.boolean().optional(),rootfs_hash:i.string().optional(),shared_ro:i.boolean().optional(),cmdline:i.string().optional(),kernel:i.string().optional(),initrd:i.string().optional(),hda:i.string().nullable().optional(),rootfs:i.string().optional(),bios:i.string().optional()}),vr=i.object({teepod_id:i.number(),name:i.string(),listed:i.boolean(),resource_score:i.number(),remaining_vcpu:i.number(),remaining_memory:i.number(),remaining_cvm_slots:i.number(),images:i.array(Ce).optional()}),Cr=i.object({max_instances:i.number().nullable(),max_vcpu:i.number().nullable(),max_memory:i.number().nullable(),max_disk:i.number().nullable()}),We=i.object({tier:i.string(),capacity:Cr,nodes:i.array(vr)});function Xe(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}async function J(){try{r.debug(`Fetching user info from ${y.USER_INFO}`);let t=await v.get(y.USER_INFO);r.debug(`Received response: ${Xe(t)}`);try{return Je.parse(t)}catch(e){throw r.error(`Failed to parse user info response: ${e}`),r.debug(`Response structure: ${Xe(t)}`),e}}catch(t){throw r.error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`),new Error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`)}}var Qe=new wr().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 Sr({type:"password",name:"apiKey",message:"Enter your API key:",validate:async n=>{if(n.length===0)return"API key cannot be empty";try{if(await Re(n),e=await J(),!e.username)return await B(),"Invalid API key"}catch{return"Invalid API key"}return!0}})).apiKey;else if(e=await J(),!e.username)return await B(),"Invalid API key";r.success(`Welcome ${e.username}! API key validated and saved successfully
103
+ `),r.info(`
104
+ Open in Web UI at https://phala.cloud/dashboard`)}catch(e){r.error(`Failed to set API key: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as kr}from"commander";var et=new kr().name("logout").description("Remove the stored API key").action(async()=>{try{await B(),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{Command as Er}from"commander";var tt=new Er().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async t=>{try{t.debug&&(process.env.DEBUG="true");let e=await ne();if(!e){r.warn('Not authenticated. Please set an API key with "phala auth login"');return}r.debug(`Using API key: ${e.substring(0,5)}...`);let o=r.startSpinner("Checking authentication status");try{let n=await J();if(o.stop(!0),t.json){console.log(JSON.stringify(n,null,2));return}r.success(`Authenticated as ${n.username}`),r.break();let s={Username:n.username,Email:n.email,Role:n.role,Team:`${n.team_name} (${n.team_tier})`,Credits:`$${n.credits}`};n.trial_ended_at&&(s["Trial Ended At"]=n.trial_ended_at),console.table(s)}catch(n){o.stop(!1),r.error("Authentication failed. Your API key may be invalid or expired."),r.info('Please set a new API key with "phala auth login"'),t.debug&&r.debug(`Error details: ${n instanceof Error?n.message:String(n)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var rt=new br().name("auth").description("Authenticate with Phala Cloud").addCommand(Qe).addCommand(et).addCommand(tt);import{Command as Dr}from"commander";import{Command as xr}from"commander";import{z as _r}from"zod";async function I(){try{let t=await v.get(y.TEEPODS);return We.parse(t).nodes}catch(t){throw new Error(`Failed to get TEEPods: ${t instanceof Error?t.message:String(t)}`)}}async function ie(t){try{let o=(await I()).find(s=>s.teepod_id===Number(t));if(o&&o.images&&o.images.length>0)return o.images;let n=await v.get(y.TEEPOD_IMAGES(t));return _r.array(Ce).parse(n)}catch(e){throw new Error(`Failed to get TEEPod images: ${e instanceof Error?e.message:String(e)}`)}}var ot=new xr().name("list").alias("ls").description("List available TEEPods").action(async()=>{try{let t=r.startSpinner("Fetching TEEPods"),e=await I();if(t.stop(!0),e.length===0){r.info("No TEEPods found");return}r.info("Available TEEPods:"),r.table(e,["teepod_id","name"])}catch(t){r.error(`Failed to list TEEPods: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Pr}from"commander";import $r from"inquirer";var nt=new Pr().name("images").description("List available images for a TEEPod").option("-t, --teepod-id <teepodId>","TEEPod ID").action(async t=>{try{let e=r.startSpinner(`Fetching images for TEEPod ${t.teepodId}`);if(!t.teepodId){let n=r.startSpinner("Fetching available TEEPods"),s=await I();n.stop(!0),s.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:a}=await $r.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:s.map(m=>({name:`${m.name}`,value:m.teepod_id}))}]);t.teepodId=a}let o=await ie(t.teepodId);if(e.stop(!0),o.length===0){r.info(`No images found for TEEPod ${t.teepodId}`);return}r.info(`Available images for TEEPod ${t.teepodId}:`),r.table(o,["name","description"])}catch(e){r.error(`Failed to list images: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var it=new Dr().name("teepods").description("TEEPod management commands").addCommand(ot).addCommand(nt);import{Command as qr}from"commander";import{Command as Ur}from"commander";import{execa as lt}from"execa";import A from"fs";import be from"path";import Ar from"axios";import Rr from"handlebars";import{exec as Mr,spawn as Vr}from"child_process";import{promisify as Nr}from"util";import Or from"os";import Ir from"inquirer";import we from"fs";import Se from"path";function E(t,e=process.cwd()){let o=Se.resolve(e,t);if(!we.existsSync(o))throw new Error(`File not found at ${o}`);return!0}async function F(t,e,o="file",n=process.cwd()){return(await Ir.prompt([{type:"input",name:o,message:t,default:e,validate:a=>{let m=Se.resolve(n,a);return we.existsSync(m)?!0:`File not found at ${m}`}}]))[o]}function se(t,e){for(let o of t){let n=Se.join(process.cwd(),o);if(we.existsSync(n))return e?r.info(e.replace("{path}",n)):r.info(`File detected: ${n}`),o}}import*as S from"fs";import*as $ from"path";import*as O from"os";import{execSync as L,spawn as Fr}from"child_process";import*as ke from"net";var w={version:"0.1.4",baseUrl:"https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4",installDir:$.join(O.homedir(),".phala-cloud","tappd-simulator"),defaultLogPath:$.join(O.homedir(),".phala-cloud","logs","tappd-simulator.log"),platforms:{darwin:{filename:"tappd-simulator-0.1.4-aarch64-apple-darwin.tgz",extractedFolder:"tappd-simulator-0.1.4-aarch64-apple-darwin",socketArg:"unix:/tmp/tappd.sock"},linux:{filename:"tappd-simulator-0.1.4-x86_64-linux-musl.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-linux-musl",socketArg:"unix:/tmp/tappd.sock"},win32:{filename:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc",socketArg:"127.0.0.1:8090"}}};function st(){try{if(!S.existsSync(w.installDir))return!1;let t=O.platform();if(!w.platforms[t])throw new Error(`Unsupported platform: ${t}`);let e=$.join(w.installDir,w.platforms[t].extractedFolder);if(!S.existsSync(e))return!1;let n=$.join(e,t==="win32"?"tappd-simulator.exe":"tappd-simulator");return S.existsSync(n)}catch(t){return r.error("Error checking if simulator is installed:",t),!1}}function Y(){let t=O.platform();if(!w.platforms[t])throw new Error(`Unsupported platform: ${t}. Only darwin, linux, and win32 are supported.`);return t}async function at(t){let e=o=>{r.info(o),t&&t(o)};try{let o=Y(),n=w.platforms[o];S.existsSync(w.installDir)||(r.info(`Creating installation directory at ${w.installDir}`),S.mkdirSync(w.installDir,{recursive:!0})),process.chdir(w.installDir);let s=`${w.baseUrl}/${n.filename}`;r.info(`Downloading simulator from ${s}`),L(`wget ${s}`,{stdio:"inherit"}),r.info(`Extracting ${n.filename}`),L(`tar -xvf ${n.filename}`,{stdio:"inherit"}),r.success("Simulator installation completed successfully")}catch(o){throw r.error("Error installing simulator:",o),new Error(`Failed to install simulator: ${o}`)}}async function mt(t={}){try{let e=Y(),o=w.platforms[e],n=$.join(w.installDir,o.extractedFolder);process.chdir(n);let s=e==="win32"?"tappd-simulator.exe":"./tappd-simulator",a={background:t.background??!0,logToFile:t.logToFile??!0,logFilePath:t.logFilePath??w.defaultLogPath};if(a.logToFile){let p=$.dirname(a.logFilePath);S.existsSync(p)||S.mkdirSync(p,{recursive:!0}),r.info(`Simulator logs will be written to: ${a.logFilePath}`)}r.info(`Starting simulator with: ${s} -l ${o.socketArg}`);let m="inherit",c=null;a.logToFile&&(c=S.createWriteStream(a.logFilePath,{flags:"a"}),m=["ignore",c,c]);let l=Fr(s,["-l",o.socketArg],{stdio:m,shell:e==="win32",detached:a.background});if(c){let p=new Date().toISOString();c.write(`
105
+ [${p}] Simulator started
106
+ `)}return a.background&&(l.unref(),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 ae(){try{let t=Y(),e=w.platforms[t];if(t==="darwin"||t==="linux"){let o="/tmp/tappd.sock";return S.existsSync(o)?new Promise(n=>{let s=ke.createConnection({path:o}).on("connect",()=>{s.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{s.end(),n(!1)},1e3)}):!1}else if(t==="win32"){let o="127.0.0.1";return new Promise(s=>{let a=ke.createConnection({host:o,port:8090}).on("connect",()=>{a.end(),s(!0)}).on("error",()=>{s(!1)});setTimeout(()=>{a.end(),s(!1)},1e3)})}return!1}catch(t){return r.error("Error checking if simulator is running:",t),!1}}async function ct(){try{let t=Y();if(!await ae())return r.info("Simulator is not running"),!0;r.info("Stopping simulator..."),t==="win32"?L(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :8080') do taskkill /F /PID %a`,{stdio:"inherit"}):L("pkill -f tappd-simulator",{stdio:"inherit"});let e=!await ae();return e?r.success("Simulator stopped successfully"):r.error("Failed to stop simulator"),await T(),e}catch(t){return r.error("Error stopping simulator:",t),!1}}function Tr(){return Y()==="win32"?"http://127.0.0.1:8090":"unix:///tmp/tappd.sock"}async function Ee(t){try{let e=Tr(),o=t||e;return await L(`export DSTACK_SIMULATOR_ENDPOINT=${o}`),r.success(`Setting DSTACK_SIMULATOR_ENDPOINT=${o} for current process`),t}catch(e){throw r.error("Error setting simulator endpoint environment variable:",e),new Error(`Failed to set simulator endpoint: ${e}`)}}async function T(){return await L("unset DSTACK_SIMULATOR_ENDPOINT"),r.success("Deleted DSTACK_SIMULATOR_ENDPOINT from current process"),!0}var W=Nr(Mr),pt=".phala-cloud/logs",Lr=".phala-cloud/compose",ut=10,h=class{username;image;registry;constructor(e,o,n){this.image=e,this.username=o||"",this.registry=n||""}ensureLogsDir(){let e=be.resolve(pt);A.existsSync(e)||A.mkdirSync(e,{recursive:!0})}getLogFilePath(e){let o=new Date().toISOString().replace(/[:.]/g,"-");return be.resolve(pt,`${this.image}-${e}-${o}.log`)}getSystemArchitecture(){let e=Or.arch();switch(e){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return e}}spawnProcess(e,o,n){return new Promise((s,a)=>{let m=Vr(e,o),c=this.getLogFilePath(n);this.ensureLogsDir();let l=A.createWriteStream(c,{flags:"a"}),p=[],g=(u,d=!1)=>{let f=u.toString().split(`
107
+ `);l.write(u),f.forEach(_=>{_.trim()&&(p.push(_),p.length>ut&&p.shift(),console.clear(),console.log(`Latest ${ut} lines (full log at ${c}):`),console.log("-".repeat(50)),p.forEach(k=>{d?console.error(k):console.log(k)}))})};m.stdout.on("data",u=>g(u)),m.stderr.on("data",u=>g(u,!0)),m.on("close",u=>{l.end(),u===0?(console.log(`
108
+ Operation completed. Full log available at: ${c}`),s()):a(new Error(`Process exited with code ${u}. Check log file: ${c}`))}),m.on("error",u=>{l.end(),a(u)})})}setCredentials(e,o){this.username=e,o&&(this.registry=o)}async buildImage(e,o){try{let n=this.getSystemArchitecture(),s=`${this.username}/${this.image}:${o}`,a=r.startSpinner(`Building Docker image ${this.username}/${this.image}:${o}`);E(e);let m=["build","-t",s,"-f",e];return n==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),m.push("--platform","linux/amd64")),m.push("."),await this.spawnProcess("docker",m,"build"),a.stop(!0,`Docker image ${s} built successfully`),!0}catch(n){return r.error(`Failed to build Docker image: ${n instanceof Error?n.message:String(n)}`),!1}}async pushImage(e){try{let o=r.startSpinner(`Pushing Docker image ${this.username}/${this.image}:${e} to Docker Hub`);if(!await P())throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let s=`${this.username}/${this.image}:${e}`;return console.log(`Pushing image ${s} to Docker Hub...`),await this.spawnProcess("docker",["push",s],"push"),o.stop(!0,`Docker image ${s} pushed successfully`),!0}catch(o){return r.error(`Failed to push Docker image: ${o instanceof Error?o.message:String(o)}`),!1}}async listTags(){try{let e=r.startSpinner(`Listing tags for ${this.username}/${this.image}`),o=await Ar.get(`${Ne}/repositories/${this.username}/${this.image}/tags`);if(!o.data||!o.data.results)throw e.stop(!1),new Error("Failed to get tags from Docker Hub");let n=o.data.results.map(s=>s.name);return e.stop(!0,`Found ${n.length} tags`),n}catch(e){return r.error(`Failed to list tags: ${e instanceof Error?e.message:String(e)}`),[]}}async login(e,o,n){try{let s=r.startSpinner(`Logging in to Docker Hub as ${e}`);return await this.checkLogin()?(s.stop(!0,`Logged in as ${e}`),this.setCredentials(e,n),!0):(await lt("docker",["login",...n?[n]:[],"-u",e,"--password-stdin"],{input:o}),s.stop(!0,"Logged in to Docker Hub successfully"),!0)}catch(s){return r.error(`Failed to login to Docker Hub: ${s instanceof Error?s.message:String(s)}`),!1}}async checkLogin(){try{let{stdout:e}=await lt("docker",["login"]);return e.includes("Login Succeeded")}catch{return!1}}async buildComposeFile(e,o,n){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let s=n=="eliza"?ze:je,a=Ke.parse({template:s}),m=Lr;A.existsSync(m)||(r.info(`Creating directory: ${m}`),A.mkdirSync(m,{recursive:!0}));let c=[];o&&(c=A.readFileSync(o,"utf-8").split(`
109
+ `).filter(f=>f&&!f.startsWith("#")).map(f=>{let _=f.indexOf("#");return _>0&&(f=f.substring(0,_).trim()),f.trim()}).filter(f=>f.includes("=")).map(f=>{let[_,k]=f.split("=",2),D=_.trim();return(k?k.trim():"")===""?null:`${D}=${D}`}).filter(Boolean));let l=`${this.username}/${this.image}`,g=Rr.compile(a.template,{noEscape:!0})({imageName:l,tag:e,envVars:c.map(d=>d.replace(/=.*/,"=${"+d.split("=")[0]+"}"))}),u=be.join(m,`${this.image}-${e}-tee-compose.yaml`);return A.writeFileSync(u,g),r.success(`Backup of docker compose file created at: ${u}`),u}async runComposeLocally(e,o){try{let n=r.startSpinner(`Running Docker Compose file at ${e}
110
+ - If you run with the simulator, set DSTACK_SIMULATOR_ENDPOINT to http://host.docker.internal:8090`);E(e);let s=["-f",e,"up","-d"];return o&&(E(o),s.splice(2,0,"--env-file",o)),await W(`docker compose ${s.join(" ")}`),n.stop(!0,"Docker Compose file running successfully"),!0}catch(n){return r.error(`Failed to run Docker Compose file: ${n instanceof Error?n.message:String(n)}`),!1}}async runSimulator(e,o){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await W(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:n}=await W(`docker run -d --name tee-simulator --rm -p ${o}:${o} ${e}`),s=n.trim();return r.success(`TEE simulator running successfully. Container ID: ${s}`),r.info(`
108
111
 
109
- Useful commands:`),r.info(`- View logs: docker logs -f ${n}`),r.info(`- Stop simulator: docker stop ${n}`),!0}catch(o){return r.error(`Failed to run TEE simulator: ${o instanceof Error?o.message:String(o)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await ee("docker stop tee-simulator"),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 ee('docker images --format "{{.Repository}}:{{.Tag}}"');return e.split(`
110
- `).filter(n=>n&&!n.includes("<none>")).map(n=>{let[i,a]=n.split(":"),m=i.split("/");return{name:m.length>1?m[1]:i,tag:a}})}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import st from"prompts";var it=new _r().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,n=t.registry;if(!e){let m=await st({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:c=>c.length>0?!0:"Username cannot be empty"});m.username||(r.error("Username is required"),process.exit(1)),e=m.username}if(!o){let m=await st({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:c=>c.length>0?!0:"Password cannot be empty"});m.password||(r.error("Password is required"),process.exit(1)),o=m.password}await new h("",e,n).login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await De({username:e,password:o,registry:n||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 xr}from"commander";import at from"path";import mt from"inquirer";import $r from"fs";var ct=new xr().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 x();if(e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let m=await mt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);t.image=m.image}if(!t.tag){let m=await mt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);t.tag=m.tag}let o=at.resolve(process.cwd(),t.file);$r.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await V("Enter the path to your Dockerfile:","Dockerfile","file"));let n=at.resolve(process.cwd(),t.file);await new h(t.image,e.username,e.registry).buildImage(n,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 Pr}from"commander";import pt from"inquirer";var lt=new Pr().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").action(async t=>{try{let e=await x();e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image,n=t.tag;if(!o||!n){let m=await h.listLocalImages();if(m.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let c=Array.from(new Set(m.map(f=>f.name))),{selectedImage:p}=await pt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:c}]);o=p}if(!n){let c=m.filter(f=>f.name===o).map(f=>f.tag);c.length===0&&(r.error(`No tags found for image ${o}`),process.exit(1));let{selectedTag:p}=await pt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${o}:`,choices:c}]);n=p}}await new h(o,e.username,e.registry).pushImage(n)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${o}:${n} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Dr}from"commander";var ut=new Dr().name("tags").description("List tags for a Docker image").requiredOption("-i, --image <image>","Image name").option("-j, --json","Output in JSON format").action(async t=>{try{let e=await x();e||(r.error('Docker credentials not found. Please login first with "teecloud docker login"'),process.exit(1));let n=await new h(t.image,e.username,e.registry).listTags();if(n.length===0){r.info(`No tags found for image ${e.username}/${t.image}`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}r.info(`Tags for image ${e.username}/${t.image}:`),n.forEach(i=>{r.info(`- ${i}`)})}catch(e){r.error(`Failed to list tags: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Ir}from"commander";import te from"inquirer";import dt from"fs";import ft from"path";var gt=new Ir().name("run").description("Run a Docker Compose setup").option("-c, --compose <compose>","Path to docker-compose.yml file").option("-e, --env-file <env-file>","Path to environment variables file").option("--skip-env","Skip environment variables file prompt",!0).action(async t=>{try{let e=t.compose,o=t.env;if(e)try{E(e)}catch{r.error(`File not found: ${e}`),process.exit(1)}else{let a=ft.join(process.cwd(),"docker-compose.yml");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);c&&(e=a)}if(!e){let{composePath:c}=await te.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:p=>E(p)?!0:"File not found"}]);e=c}}if(!o&&!t.skipEnv){let a=ft.join(process.cwd(),".env");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);c&&(o=a)}if(!o){let{envPath:c}=await te.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:p=>{try{return E(p),!0}catch{return`File not found: ${p}`}}}]);o=c}}let n=new h("");if(o){try{E(o)}catch{r.error(`File not found: ${o}`),process.exit(1)}r.info(`Running Docker Compose with compose file: ${e} and env file: ${o}`)}else r.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,o)||(r.error("Failed to run Docker Compose"),process.exit(1)),r.success("Docker Compose is running")}catch(e){r.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Tr}from"commander";import b from"inquirer";import K from"fs";import re from"path";var yt=new Tr().name("generate").description("Generate a Docker Compose file").option("-i, --image <image>","Docker image name to use in the compose file").option("-t, --tag <tag>","Docker image tag to use in the compose file").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").option("--manual","Skip automatic image detection and enter image/tag manually").action(async t=>{try{let e=await x();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `tcc docker login`"),process.exit(1));let o=t.image||"",n=t.tag||"";if((!o||!n)&&!t.manual)try{r.info("Detecting local Docker images...");let p=await h.listLocalImages();if(p.length===0)r.warn("No local Docker images found. You will need to enter image details manually.");else{let f=new Map;if(p.forEach(d=>{f.has(d.name)||f.set(d.name,[]),f.get(d.name)?.push(d.tag)}),o&&!n){let d=f.get(o)||[];if(d.length>0){let{imageTag:u}=await b.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${o}:`,choices:[...d,new b.Separator,"[ Enter manually ]"]}]);u!=="[ Enter manually ]"&&(n=u)}else r.warn(`No tags found for image ${o}. You will need to enter the tag manually.`)}else if(!o){let d=Array.from(f.keys()),{imageName:u}=await b.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...d,new b.Separator,"[ Enter manually ]"]}]);if(u!=="[ Enter manually ]"){o=u;let y=f.get(u)||[],{imageTag:l}=await b.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...y,new b.Separator,"[ Enter manually ]"]}]);l!=="[ Enter manually ]"&&(n=l)}}}}catch(p){r.warn(`Failed to detect local images: ${p instanceof Error?p.message:String(p)}`),r.info("Continuing with manual input...")}if(!o){let{inputImage:p}=await b.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:f=>f.trim()?!0:"Image name cannot be empty"}]);o=p}if(!n){let{inputTag:p}=await b.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${o}:`,validate:f=>f.trim()?!0:"Tag cannot be empty"}]);n=p}let i=t.envFile;if(i)try{E(i)}catch{r.error(`File not found: ${i}`),process.exit(1)}else{let p=re.join(process.cwd(),".env");if(K.existsSync(p)){let{useDefault:d}=await b.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);d&&(i=p)}if(!i){let{envPath:d}=await b.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return E(u),!0}catch{return`File not found: ${u}`}}}]);i=d}}let a=t.output;if(!a&&(a=re.join(process.cwd(),"docker-compose.yml"),K.existsSync(a))){let{confirmOverwrite:p}=await b.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!p){let{customPath:f}=await b.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:re.join(process.cwd(),`${o}-${n}-compose.yml`)}]);a=f}}let m=new h(o,e.username,e.registry);i?r.info(`Generating Docker Compose file for ${o}:${n} using env file: ${i}`):r.info(`Generating Docker Compose file for ${o}:${n} without env file`);let c=await m.buildComposeFile(n,i,t.template);if(c!==a){let p=re.dirname(a);K.existsSync(p)||(r.info(`Creating directory: ${p}`),K.mkdirSync(p,{recursive:!0})),K.copyFileSync(c,a)}r.success(`Docker Compose file generated successfully: ${a}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var ht=new Fr().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(it).addCommand(ct).addCommand(lt).addCommand(ut).addCommand(gt).addCommand(yt);import{Command as Vr}from"commander";import{Command as Ar}from"commander";var Ct=new Ar().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",Te).action(async t=>{try{await new h("").runSimulator(t.image)||(r.error("Failed to start TEE simulator"),process.exit(1))}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Mr}from"commander";var vt=new Mr().name("stop").description("Stop the TEE simulator").action(async()=>{try{await new h("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1))}catch(t){r.error(`Failed to stop TEE simulator: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var wt=new Vr().name("simulator").description("TEE simulator commands").addCommand(Ct).addCommand(vt);import{Command as jr}from"commander";import{Command as Ur}from"commander";import H from"fs";import St from"path";import Rr from"os";var oe=St.join(Rr.homedir(),".phala-cloud"),ye=St.join(oe,"config.json"),ge={apiUrl:"https://cloud-api.phala.network",cloudUrl:"https://cloud.phala.network",defaultTeepodId:3,defaultImage:"dstack-dev-0.3.5",defaultVcpu:1,defaultMemory:2048,defaultDiskSize:20};function Nr(){if(!H.existsSync(oe))try{H.mkdirSync(oe,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${oe}:`,t),t}}function ne(){try{if(H.existsSync(ye)){let t=H.readFileSync(ye,"utf8");return{...ge,...JSON.parse(t)}}return ge}catch(t){return r.error("Failed to load configuration:",t),ge}}function Or(t){Nr();try{H.writeFileSync(ye,JSON.stringify({...ne(),...t},null,2),{mode:384}),r.success("Configuration saved successfully.")}catch(e){throw r.error("Failed to save configuration:",e),e}}function kt(t){return ne()[t]}function Et(t,e){let o=ne();o[t]=e,Or(o)}function bt(){return ne()}var _t=new Ur().name("get").description("Get a configuration value").argument("<key>","Configuration key").action(t=>{try{let e=kt(t);e===void 0&&(r.error(`Configuration key '${t}' not found`),process.exit(1)),r.info(`${t}: ${JSON.stringify(e)}`)}catch(e){r.error(`Failed to get configuration value: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Lr}from"commander";var xt=new Lr().name("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action((t,e)=>{try{let o=e;if(e.startsWith("{")||e.startsWith("[")||e==="true"||e==="false"||!isNaN(Number(e)))try{o=JSON.parse(e)}catch{}Et(t,o),r.success(`Configuration value for '${t}' set successfully`)}catch(o){r.error(`Failed to set configuration value: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as zr}from"commander";var $t=new zr().name("list").description("List all configuration values").option("-j, --json","Output in JSON format").action(t=>{try{let e=bt();if(t.json){console.log(JSON.stringify(e,null,2));return}r.info("Configuration values:");for(let[o,n]of Object.entries(e))r.info(`${o}: ${JSON.stringify(n)}`)}catch(e){r.error(`Failed to list configuration values: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Pt=new jr().name("config").description("Manage your local configuration").addCommand(_t).addCommand(xt).addCommand($t);import{Command as no}from"commander";import{Command as Br}from"commander";import{z as Dt}from"zod";async function he(){try{let t=await w.get(C.CVMS(0));return Dt.array(de).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function R(t){try{let e=await w.get(C.CVM_BY_APP_ID(t));return Ue.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function It(t){try{let e=await w.post(C.CVM_PUBKEY,t);return Oe.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Tt(t){try{let e=await w.post(C.CVM_FROM_CONFIGURATION,t);return Ne.parse(e)}catch(e){throw e instanceof Dt.ZodError?(console.error("Schema validation error:",JSON.stringify(e.errors,null,2)),console.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ft(t){try{return await w.post(C.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function At(t){try{return await w.post(C.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Mt(t){try{return await w.post(C.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Vt(t,e){try{let o=await w.put(C.CVM_UPGRADE(t),e);return ze.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Rt(t){try{return await w.delete(C.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function S(){let{logger:t}=await import("./logger-LBGFMBSV.js"),e=(await import("inquirer")).default,o=t.startSpinner("Fetching available CVMs"),n=await he();if(o.stop(!0),!n||n.length===0){t.info("No CVMs found for your account");return}let i=n.map(m=>{let c=m.hosted?.app_id||m.hosted?.id,p=m.name||m.hosted&&m.hosted.name,f=m.status||m.hosted&&m.hosted.status;return{name:`${p||"Unnamed"} (${c}) - Status: ${f||"Unknown"}`,value:c}}),{selectedCvm:a}=await e.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:i}]);return a}async function Nt(t){try{return await w.get(C.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function Ot(t,e,o,n,i){try{let a={};if(e!==void 0&&(a.vcpu=e),o!==void 0&&(a.memory=o),n!==void 0&&(a.disk_size=n),i!==void 0&&(a.allow_restart=i),Object.keys(a).length===0)throw new Error("At least one resource parameter must be provided");return await w.patch(C.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}var Ut=new Br().name("list").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await he();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}o.forEach(n=>{r.keyValueTable({"App ID":n.hosted.app_id,Name:n.name,Status:n.status,"Node Info URL":n.hosted.app_url,"App URL":`${T}/dashboard/cvms/app_${n.hosted.app_id}`})}),r.success(`Found ${o.length} CVMs:`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Gr}from"commander";var Lt=new Gr().name("get").description("Get details of a CVM").option("-i, --id <app-id>","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async t=>{try{let e=t.id;if(!e&&(e=await S(),!e))return;let o=r.startSpinner(`Fetching CVM with App ID ${e}`),n=await R(e);if(o.stop(!0),n||(r.error(`CVM with App ID ${e} not found`),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}r.keyValueTable({Name:n.name,Status:n.status,vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"TEEPod ID":n.teepod_id,"App URL":`${T}/dashboard/cvms/app_${n.app_id}`})}catch(e){r.error(`Failed to get CVM details: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as qr}from"commander";var zt=new qr().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{if(!t&&(t=await S(),!t))return;let e=r.startSpinner(`Starting CVM with App ID ${t}`);await Ft(t),e.stop(!0),r.success(`CVM with App ID ${t} started successfully`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Kr}from"commander";var jt=new Kr().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{if(!t&&(t=await S(),!t))return;let e=r.startSpinner(`Stopping CVM with App ID ${t}`);await At(t),e.stop(!0),r.success(`CVM with App ID ${t} stopped successfully`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Hr}from"commander";var Bt=new Hr().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{if(!t&&(t=await S(),!t))return;let e=r.startSpinner(`Restarting CVM with App ID ${t}`);await Mt(t),e.stop(!0),r.success(`CVM with App ID ${t} restarted successfully`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Zr}from"commander";import se from"chalk";var Gt=new Zr().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{if(!t){r.info("No CVM specified, fetching available CVMs...");let n=await S();if(!n)return;t=n}r.info(`Fetching attestation information for CVM ${t}...`);let o=r.startSpinner("Fetching attestation information");try{let n=await Nt(t);if(o.stop(!0),!n||Object.keys(n).length===0){r.info("No attestation information found");return}if(e?.json){console.log(JSON.stringify(n,null,2));return}r.success("Attestation Summary:");let i={Status:n.is_online?se.green("Online"):se.red("Offline"),"Public Access":n.is_public?se.green("Enabled"):se.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};r.keyValueTable(i,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,m)=>{r.success(`Certificate #${m+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let c={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};r.keyValueTable(c,{borderStyle:"single"})}),n.tcb_info&&(r.success("Trusted Computing Base (TCB) Information:"),r.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw o.stop(!0),n}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Yr}from"commander";import{encryptEnvVars as Wr}from"@phala/dstack-sdk/encrypt-env-vars";import J from"fs";import ie from"path";import P from"inquirer";import Jr from"fs";var Z=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[i,a]=n.split("=");i&&a&&(o[i]=a)}}if(e){let n=Jr.readFileSync(e,"utf8");for(let i of n.split(`
111
- `))if(!(!i.trim()||i.trim().startsWith("#"))&&i.includes("=")){let[a,...m]=i.split("="),c=m.join("="),p=c.search(/\s+#/);p!==-1&&(c=c.substring(0,p).trim()),a&&c&&(o[a.trim()]=c.trim())}}return Object.entries(o).map(([n,i])=>({key:n,value:i}))};var qt=new Yr().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",String(L)).option("--memory <memory>","Memory in MB",String(z)).option("--disk-size <diskSize>","Disk size in GB",String(j)).option("--teepod-id <teepodId>","TEEPod ID to use").option("--image <image>","Version of dstack image to use").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:l}=await P.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:g=>g.trim()?!0:"CVM name is required"}]);t.name=l}let e=ie.join(process.cwd(),"examples"),o=[];if(J.existsSync(e)){let l=J.readdirSync(e,{withFileTypes:!0}).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>g.name);o.push(...l)}let n="";try{if(!t.compose)if(o.length>0){let g=[...o.map((v,_)=>({name:v,value:{type:"example",name:v}})),new P.Separator,{name:"Enter a file path",value:{type:"custom"}}],{selection:k}=await P.prompt([{type:"list",name:"selection",message:"Choose a Docker Compose example or enter a custom path:",choices:g}]);if(k.type==="example"){let v=ie.join(e,k.name),_=["docker-compose.yml","docker-compose.yaml"],Ce=!1;for(let Yt of _){let ve=ie.join(v,Yt);if(J.existsSync(ve)){t.compose=ve,Ce=!0,r.info(`Using example: ${k.name} (${t.compose})`);break}}Ce||(r.error(`Could not find docker-compose.yml or docker-compose.yaml in ${v}`),process.exit(1))}else{let{customPath:v}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:_=>_.trim()?!0:"Docker Compose file path is required"}]);t.compose=v}}else{let{customPath:g}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:k=>k.trim()?!0:"Docker Compose file path is required"}]);t.compose=g}let l=ie.resolve(t.compose);J.existsSync(l)||(r.error(`Docker Compose file not found: ${l}`),process.exit(1)),n=J.readFileSync(l,"utf8")}catch(l){r.error(`Failed to read Docker Compose file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let i=[];if(t.envFile)try{i=Z([],t.envFile)}catch(l){r.error(`Failed to read environment file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}else if(!t.skipEnv){let l=await V("Enter the path to your environment file:",".env","file");i=Z([],l)}let a=[];if(t.vcpu===String(L)&&a.push({type:"input",name:"vcpu",message:`Enter number of vCPUs (default: ${L}):`,default:String(L),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.memory===String(z)&&a.push({type:"input",name:"memory",message:`Enter memory in MB (default: ${z}):`,default:String(z),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.diskSize===String(j)&&a.push({type:"input",name:"diskSize",message:`Enter disk size in GB (default: ${j}):`,default:String(j),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),a.length>0){let l=await P.prompt(a);l.vcpu&&(t.vcpu=l.vcpu),l.memory&&(t.memory=l.memory),l.diskSize&&(t.diskSize=l.diskSize)}if(!t.teepodId){let l=r.startSpinner("Fetching available TEEPods"),g=await M();l.stop(!0),g.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:k}=await P.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:g.map(_=>({name:`${_.name} (${_.status})`,value:_.id}))}]),v=g.find(_=>_.id===k);v||(r.error("Failed to find selected TEEPod"),process.exit(1)),r.info(`Selected TEEPod: ${v.name}`),t.teepodId=v.id}if(!t.image){let g=(await Q(t.teepodId)).map(v=>({name:`${v.name}`,value:v.name})),{selectedImage:k}=await P.prompt([{type:"list",name:"selectedImage",message:"Select an image:",choices:g}]);t.image=k.value}let m={teepod_id:t.teepodId||3,name:t.name,image:t.image||"dstack-dev-0.3.5",vcpu:parseInt(t.vcpu),memory:parseInt(t.memory),disk_size:parseInt(t.diskSize),compose_manifest:{docker_compose_file:n,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},c=r.startSpinner("Getting public key from CVM"),p=await It(m);c.stop(!0),p||(r.error("Failed to get public key from CVM"),process.exit(1));let f=r.startSpinner("Encrypting environment variables"),d=await Wr(i,p.app_env_encrypt_pubkey);f.stop(!0),t.debug&&(r.debug("Public key:",p.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",d),r.debug("Environment variables:",JSON.stringify(i)));let u=r.startSpinner("Creating CVM"),y=await Tt({...m,encrypted_env:d,app_env_encrypt_pubkey:p.app_env_encrypt_pubkey,app_id_salt:p.app_id_salt});u.stop(!0),y||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.info(`CVM ID: ${y.id}`),r.info(`Name: ${y.name}`),r.info(`Status: ${y.status}`),r.info(`App ID: ${y.app_id}`),y.app_url?r.info(`App URL: ${y.app_url}`):r.info(`App URL: ${T}/dashboard/cvms/app_${y.app_id}`),r.info(""),r.info("Your CVM is being created. You can check its status with:"),r.info(`phala cvms status ${y.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Xr}from"commander";import Qr from"inquirer";var Kt=new Xr().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{if(!t&&(t=await S(),!t))return;if(!e.force){let{confirm:i}=await Qr.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID ${t}? This action cannot be undone.`,default:!1}]);if(!i){r.info("Deletion cancelled");return}}let o=r.startSpinner(`Deleting CVM ${t}`),n=await Rt(t);o.stop(!0),n||(r.error(`Failed to delete CVM ${t}`),process.exit(1)),r.success(`CVM ${t} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as eo}from"commander";import to from"fs";import{encryptEnvVars as ro}from"@phala/dstack-sdk/encrypt-env-vars";var Ht=new eo().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{if(!t){r.info("No CVM specified, fetching available CVMs...");let d=await S();if(!d)return;t=d}let o=r.startSpinner(`Fetching current configuration for CVM ${t}`),n=await R(t);o.stop(!0),n||(r.error(`CVM with App ID ${t} not found`),process.exit(1));let i={};e.compose||(e.compose=await V("Enter the path to your Docker Compose file:","docker-compose.yml","file"));let a="";if(e.compose)try{a=to.readFileSync(e.compose,"utf8")}catch(d){r.error(`Failed to read Docker Compose file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let m="";if(e.envFile){let d=[];if(e.envFile)try{d=Z([],e.envFile),m=await ro(d,n.encrypted_env_pubkey)}catch(u){r.error(`Failed to read environment file: ${u instanceof Error?u.message:String(u)}`),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_${e.appId}`},encrypted_env:m,allow_restart:!0},p=r.startSpinner(`Upgrading CVM ${t}`),f=await Vt(t,c);p.stop(!0),f||(r.error("Failed to upgrade CVM"),process.exit(1)),r.success(`CVM ${t} upgraded successfully`),f.detail&&r.info(`Details: ${f.detail}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as oo}from"commander";import Y from"inquirer";var Zt=new oo().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{if(!t&&(t=await S(),!t)){r.info("No CVMs found or selection cancelled");return}let o=await R(t),n=e.vcpu,i=e.memory,a=e.diskSize,m=e.allowRestart;n||(n=(await Y.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.vcpu,filter:u=>parseInt(u)}])).vcpu),i||(i=(await Y.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.memory,filter:u=>parseInt(u)}])).memory),a||(a=(await Y.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.disk_size,filter:u=>parseInt(u)}])).diskSize),m||(m=(await Y.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let c=`Are you sure you want to resize CVM ${t} with the following changes:
112
- `;if(r.keyValueTable({vCPUs:o.vcpu!==n?`${o.vcpu} -> ${n}`:o.vcpu,Memory:o.memory!==i?`${o.memory} MB -> ${i} MB`:o.memory,"Disk Size":o.disk_size!==a?`${o.disk_size} GB -> ${a} GB`:o.disk_size,"Allow Restart":m?"Yes":"No"}),!e.yes){let{confirm:d}=await Y.prompt([{type:"confirm",name:"confirm",message:c,default:!1}]);if(!d){r.info("Resize operation cancelled");return}}let p=r.startSpinner(`Resizing CVM with App ID ${t}`);await Ot(t,n,i,a,m?1:0),p.stop(!0),r.success(`CVM with App ID ${t} resized successfully`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var Jt=new no().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(Ut).addCommand(Lt).addCommand(qt).addCommand(Ht).addCommand(zt).addCommand(jt).addCommand(Bt).addCommand(Gt).addCommand(Kt).addCommand(Zt);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function io(){new so().name("phala").description(`${Ee}
113
- Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("0.0.1").addCommand(Ze).addCommand(Xe).addCommand(ht).addCommand(wt).addCommand(Pt).addCommand(Jt).parse(process.argv)}io().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
112
+ Useful commands:`),r.info(`- View logs: docker logs -f ${s}`),r.info(`- Stop simulator: docker stop ${s}
113
+ `),Ee(`http://localhost:${o}`),!0}catch(n){return r.error(`Failed to run TEE simulator: ${n instanceof Error?n.message:String(n)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await W("docker stop tee-simulator"),await T(),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 W('docker images --format "{{.Repository}}:{{.Tag}}"'),n=(await P())?.username;return e.split(`
114
+ `).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${n}/`)).map(a=>{let[m,c]=a.split(":"),l=m.split("/");return{name:l.length>1?l[1]:m,tag:c}})}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import dt from"prompts";var ft=new Ur().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,n=t.registry;if(!e){r.info("First we need your Docker Hub username to check if you are already logged in.");let c=await dt({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 s=new h("",e,n);if(await s.login(e)){r.success(`${e} is logged in to Docker Hub`);return}if(!o){let c=await dt({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 s.login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await Me({username:e,registry:n||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 zr}from"commander";import gt from"path";import yt from"inquirer";import jr from"fs";var ht=new zr().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 P();if(e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let m=await yt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);t.image=m.image}if(!t.tag){let m=await yt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);t.tag=m.tag}let o=gt.resolve(process.cwd(),t.file);jr.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await F("Enter the path to your Dockerfile:","Dockerfile","file"));let n=gt.resolve(process.cwd(),t.file);await new h(t.image,e.username,e.registry).buildImage(n,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 Br}from"commander";import vt from"inquirer";var Ct=new Br().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").action(async t=>{try{let e=await P();e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image,n=t.tag;if(!o||!n){let m=await h.listLocalImages();if(m.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let c=Array.from(new Set(m.map(p=>p.name))),{selectedImage:l}=await vt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:c}]);o=l}if(!n){let c=m.filter(p=>p.name===o).map(p=>p.tag);c.length===0&&(r.error(`No tags found for image ${o}`),process.exit(1));let{selectedTag:l}=await vt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${o}:`,choices:c}]);n=l}}await new h(o,e.username,e.registry).pushImage(n)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${o}:${n} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Gr}from"commander";import me from"inquirer";import wt from"fs";import St from"path";var kt=new Gr().name("run").description("Run a Docker Compose setup").option("-c, --compose <compose>","Path to docker-compose.yml file").option("-e, --env-file <env-file>","Path to environment variables file").option("--skip-env","Skip environment variables file prompt",!0).action(async t=>{try{let e=t.compose,o=t.env;if(e)try{E(e)}catch{r.error(`File not found: ${e}`),process.exit(1)}else{let a=St.join(process.cwd(),"docker-compose.yml");if(wt.existsSync(a)){let{useDefault:c}=await me.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);c&&(e=a)}if(!e){let{composePath:c}=await me.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:l=>E(l)?!0:"File not found"}]);e=c}}if(!o&&!t.skipEnv){let a=St.join(process.cwd(),".env");if(wt.existsSync(a)){let{useDefault:c}=await me.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);c&&(o=a)}if(!o){let{envPath:c}=await me.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:l=>{try{return E(l),!0}catch{return`File not found: ${l}`}}}]);o=c}}let n=new h("");if(o){try{E(o)}catch{r.error(`File not found: ${o}`),process.exit(1)}r.info(`Running Docker Compose with compose file: ${e} and env file: ${o}`)}else r.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,o)||(r.error("Failed to run Docker Compose"),process.exit(1)),r.success("Docker Compose is running")}catch(e){r.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Kr}from"commander";import b from"inquirer";import X from"fs";import ce from"path";var Et=new Kr().name("generate").description("Generate a Docker Compose file").option("-i, --image <image>","Docker image name to use in the compose file").option("-t, --tag <tag>","Docker image tag to use in the compose file").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").option("--manual","Skip automatic image detection and enter image/tag manually").action(async t=>{try{let e=await P();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let o=t.image||"",n=t.tag||"";if((!o||!n)&&!t.manual)try{r.info("Detecting local Docker images...");let l=await h.listLocalImages();if(l.length===0)r.warn("No local Docker images found. You will need to enter image details manually.");else{let p=new Map;if(l.forEach(g=>{p.has(g.name)||p.set(g.name,[]),p.get(g.name)?.push(g.tag)}),o&&!n){let g=p.get(o)||[];if(g.length>0){let{imageTag:u}=await b.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${o}:`,choices:[...g,new b.Separator,"[ Enter manually ]"]}]);u!=="[ Enter manually ]"&&(n=u)}else r.warn(`No tags found for image ${o}. You will need to enter the tag manually.`)}else if(!o){let g=Array.from(p.keys()),{imageName:u}=await b.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...g,new b.Separator,"[ Enter manually ]"]}]);if(u!=="[ Enter manually ]"){o=u;let d=p.get(u)||[],{imageTag:f}=await b.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...d,new b.Separator,"[ Enter manually ]"]}]);f!=="[ Enter manually ]"&&(n=f)}}}}catch(l){r.warn(`Failed to detect local images: ${l instanceof Error?l.message:String(l)}`),r.info("Continuing with manual input...")}if(!o){let{inputImage:l}=await b.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:p=>p.trim()?!0:"Image name cannot be empty"}]);o=l}if(!n){let{inputTag:l}=await b.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${o}:`,validate:p=>p.trim()?!0:"Tag cannot be empty"}]);n=l}let s=t.envFile;if(s)try{E(s)}catch{r.error(`File not found: ${s}`),process.exit(1)}else{let l=ce.join(process.cwd(),".env");if(X.existsSync(l)){let{useDefault:g}=await b.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);g&&(s=l)}if(!s){let{envPath:g}=await b.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return E(u),!0}catch{return`File not found: ${u}`}}}]);s=g}}let a=t.output;if(!a&&(a=ce.join(process.cwd(),"docker-compose.yml"),X.existsSync(a))){let{confirmOverwrite:l}=await b.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!l){let{customPath:p}=await b.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:ce.join(process.cwd(),"docker-generated-compose.yml")}]);a=p}}let m=new h(o,e.username,e.registry);s?r.info(`Generating Docker Compose file for ${o}:${n} using env file: ${s}`):r.info(`Generating Docker Compose file for ${o}:${n} without env file`);let c=await m.buildComposeFile(n,s,t.template);if(c!==a){let l=ce.dirname(a);X.existsSync(l)||(r.info(`Creating directory: ${l}`),X.mkdirSync(l,{recursive:!0})),X.copyFileSync(c,a)}r.success(`Docker Compose file generated successfully: ${a}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var bt=new qr().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(ft).addCommand(ht).addCommand(kt).addCommand(Ct).addCommand(Et);import{Command as Jr}from"commander";import{Command as Hr}from"commander";var _t=new Hr().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",Oe).option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{if(t.type==="docker")await new h("").runSimulator(t.image,t.port)||(r.error("Failed to start TEE simulator"),process.exit(1));else if(t.type==="native")if(st()||await at(),await ae()){r.success("TEE simulator is already running");return}else{let o=mt();r.success("TEE simulator started successfully")}else r.error("Invalid simulator type"),process.exit(1)}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Zr}from"commander";var xt=new Zr().name("stop").description("Stop the TEE simulator").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{t.type==="docker"?await new h("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1)):t.type==="native"?await ct()||(r.error("Failed to stop TEE simulator"),process.exit(1)):(r.error("Invalid simulator type"),process.exit(1))}catch(e){r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Pt=new Jr().name("simulator").description("TEE simulator commands").addCommand(_t).addCommand(xt);import{Command as ro}from"commander";import{Command as Qr}from"commander";import Q from"fs";import $t from"path";import Yr from"os";var le=$t.join(Yr.homedir(),".phala-cloud"),xe=$t.join(le,"config.json"),_e={apiUrl:"https://cloud-api.phala.network",cloudUrl:"https://cloud.phala.network",defaultTeepodId:3,defaultImage:"dstack-dev-0.3.5",defaultVcpu:1,defaultMemory:2048,defaultDiskSize:20};function Wr(){if(!Q.existsSync(le))try{Q.mkdirSync(le,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${le}:`,t),t}}function pe(){try{if(Q.existsSync(xe)){let t=Q.readFileSync(xe,"utf8");return{..._e,...JSON.parse(t)}}return _e}catch(t){return r.error("Failed to load configuration:",t),_e}}function Xr(t){Wr();try{Q.writeFileSync(xe,JSON.stringify({...pe(),...t},null,2),{mode:384}),r.success("Configuration saved successfully.")}catch(e){throw r.error("Failed to save configuration:",e),e}}function Dt(t){return pe()[t]}function It(t,e){let o=pe();o[t]=e,Xr(o)}function Ft(){return pe()}var Tt=new Qr().name("get").description("Get a configuration value").argument("<key>","Configuration key").action(t=>{try{let e=Dt(t);e===void 0&&(r.error(`Configuration key '${t}' not found`),process.exit(1)),r.info(`${t}: ${JSON.stringify(e)}`)}catch(e){r.error(`Failed to get configuration value: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as eo}from"commander";var At=new eo().name("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action((t,e)=>{try{let o=e;if(e.startsWith("{")||e.startsWith("[")||e==="true"||e==="false"||!isNaN(Number(e)))try{o=JSON.parse(e)}catch{}It(t,o),r.success(`Configuration value for '${t}' set successfully`)}catch(o){r.error(`Failed to set configuration value: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as to}from"commander";var Rt=new to().name("list").alias("ls").description("List all configuration values").option("-j, --json","Output in JSON format").action(t=>{try{let e=Ft();if(t.json){console.log(JSON.stringify(e,null,2));return}r.info("Configuration values:");for(let[o,n]of Object.entries(e))r.info(`${o}: ${JSON.stringify(n)}`)}catch(e){r.error(`Failed to list configuration values: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Mt=new ro().name("config").description("Manage your local configuration").addCommand(Tt).addCommand(At).addCommand(Rt);import{Command as wo}from"commander";import{Command as oo}from"commander";import{z as Vt}from"zod";async function Pe(){try{let t=await v.get(y.CVMS(0));return Vt.array(ve).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function U(t){try{let e=await v.get(y.CVM_BY_APP_ID(t));return Ze.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function Nt(t){try{let e=await v.post(y.CVM_PUBKEY,t);return He.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ot(t){try{let e=await v.post(y.CVM_FROM_CONFIGURATION,t);return qe.parse(e)}catch(e){throw e instanceof Vt.ZodError?(console.error("Schema validation error:",JSON.stringify(e.errors,null,2)),console.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Lt(t){try{return await v.post(y.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ut(t){try{return await v.post(y.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function zt(t){try{return await v.post(y.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function jt(t,e){try{let o=await v.put(y.CVM_UPGRADE(t),e);return Ye.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Bt(t){try{return await v.delete(y.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function C(){let{logger:t}=await import("./logger-672CA57G.js"),e=(await import("inquirer")).default,o=t.startSpinner("Fetching available CVMs"),n=await Pe();if(o.stop(!0),!n||n.length===0){t.info("No CVMs found for your account");return}let s=n.map(m=>{let c=m.hosted?.app_id||m.hosted?.id,l=m.name||m.hosted&&m.hosted.name,p=m.status||m.hosted&&m.hosted.status;return{name:`${l||"Unnamed"} (${c}) - Status: ${p||"Unknown"}`,value:c}}),{selectedCvm:a}=await e.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:s}]);return a}async function Gt(t){try{return await v.get(y.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function Kt(t,e,o,n,s){try{let a={};if(e!==void 0&&(a.vcpu=e),o!==void 0&&(a.memory=o),n!==void 0&&(a.disk_size=n),s!==void 0&&(a.allow_restart=s),Object.keys(a).length===0)throw new Error("At least one resource parameter must be provided");return await v.patch(y.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}var qt=new oo().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 Pe();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}o.forEach(n=>{r.keyValueTable({"App ID":`app_${n.hosted.app_id}`,Name:n.name,Status:n.status,"Node Info URL":n.hosted.app_url,"App URL":`${M}/dashboard/cvms/app_${n.hosted.app_id}`})}),r.success(`Found ${o.length} CVMs:`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as no}from"commander";var Ht=new no().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{if(!t&&(t=await C(),!t)){r.info("No CVMs found or selection cancelled");return}let o=r.startSpinner(`Fetching CVM with App ID ${t}`),n=await U(t);if(o.stop(!0),n||(r.error(`CVM with App ID ${t} not found`),process.exit(1)),e.json){console.log(JSON.stringify(n,null,2));return}r.keyValueTable({Name:n.name,Status:n.status,vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"TEEPod ID":n.teepod_id,"App URL":`${M}/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 io}from"commander";var Zt=new io().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{if(!t&&(t=await C(),!t))return;let e=r.startSpinner(`Starting CVM with App ID ${t}`);await Lt(t),e.stop(!0),r.success(`CVM with App ID ${t} started successfully`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as so}from"commander";var Jt=new so().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{if(!t&&(t=await C(),!t))return;let e=r.startSpinner(`Stopping CVM with App ID ${t}`);await Ut(t),e.stop(!0),r.success(`CVM with App ID ${t} stopped successfully`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as ao}from"commander";var Yt=new ao().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{if(!t&&(t=await C(),!t))return;let e=r.startSpinner(`Restarting CVM with App ID ${t}`);await zt(t),e.stop(!0),r.success(`CVM with App ID ${t} restarted successfully`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as mo}from"commander";import ue from"chalk";var Wt=new mo().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{if(!t){r.info("No CVM specified, fetching available CVMs...");let n=await C();if(!n)return;t=n}r.info(`Fetching attestation information for CVM ${t}...`);let o=r.startSpinner("Fetching attestation information");try{let n=await Gt(t);if(o.stop(!0),!n||Object.keys(n).length===0){r.info("No attestation information found");return}if(e?.json){console.log(JSON.stringify(n,null,2));return}r.success("Attestation Summary:");let s={Status:n.is_online?ue.green("Online"):ue.red("Offline"),"Public Access":n.is_public?ue.green("Enabled"):ue.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};r.keyValueTable(s,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,m)=>{r.success(`Certificate #${m+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let c={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};r.keyValueTable(c,{borderStyle:"single"})}),n.tcb_info&&(r.success("Trusted Computing Base (TCB) Information:"),r.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw o.stop(!0),n}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as lo}from"commander";import{encryptEnvVars as po}from"@phala/dstack-sdk/encrypt-env-vars";import Xt from"fs";import uo from"path";import te from"inquirer";import co from"fs";var ee=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[s,a]=n.split("=");s&&a&&(o[s]=a)}}if(e){let n=co.readFileSync(e,"utf8");for(let s of n.split(`
115
+ `))if(!(!s.trim()||s.trim().startsWith("#"))&&s.includes("=")){let[a,...m]=s.split("="),c=m.join("="),l=c.search(/\s+#/);l!==-1&&(c=c.substring(0,l).trim()),a&&c&&(o[a.trim()]=c.trim())}}return Object.entries(o).map(([n,s])=>({key:n,value:s}))};var Qt=new lo().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",String(G)).option("--memory <memory>","Memory in MB",String(K)).option("--disk-size <diskSize>","Disk size in GB",String(q)).option("--teepod-id <teepodId>","TEEPod ID to use",Le).option("--image <image>","Version of dstack image to use",Ue).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:d}=await te.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:f=>f.trim()?!0:"CVM name is required"}]);t.name=d}if(!t.compose){let f=se(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await F("Enter the path to your Docker Compose file:",f,"file")}let e=uo.resolve(t.compose);Xt.existsSync(e)||(r.error(`Docker Compose file not found: ${e}`),process.exit(1));let o=Xt.readFileSync(e,"utf8");await T();let n=[];if(t.envFile)try{n=ee([],t.envFile)}catch(d){r.error(`Failed to read environment file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}else if(!t.skipEnv)if(await te.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!1}]))r.info("Skipping environment variable prompt");else{let f=await F("Enter the path to your environment file:",".env","file");n=ee([],f)}let s=[];if(t.vcpu===String(G)&&s.push({type:"input",name:"vcpu",message:`Enter number of vCPUs (default: ${G}):`,default:String(G),validate:d=>{let f=parseInt(d);return isNaN(f)||f<=0?"Please enter a valid positive number":!0}}),t.memory===String(K)&&s.push({type:"input",name:"memory",message:`Enter memory in MB (default: ${K}):`,default:String(K),validate:d=>{let f=parseInt(d);return isNaN(f)||f<=0?"Please enter a valid positive number":!0}}),t.diskSize===String(q)&&s.push({type:"input",name:"diskSize",message:`Enter disk size in GB (default: ${q}):`,default:String(q),validate:d=>{let f=parseInt(d);return isNaN(f)||f<=0?"Please enter a valid positive number":!0}}),s.length>0){let d=await te.prompt(s);d.vcpu&&(t.vcpu=d.vcpu),d.memory&&(t.memory=d.memory),d.diskSize&&(t.diskSize=d.diskSize)}if(!t.teepodId){let d=r.startSpinner("Fetching available TEEPods"),f=await I();d.stop(!0),f.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:_}=await te.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:f.map(D=>({name:`${D.name}`,value:D.teepod_id}))}]),k=f.find(D=>D.teepod_id===_);k||(r.error("Failed to find selected TEEPod"),process.exit(1)),r.info(`Selected TEEPod: ${k.name}`),t.teepodId=k.teepod_id}if(!t.image){let f=(await ie(t.teepodId)).map(k=>({name:`${k.name}`,value:k.name})),{selectedImage:_}=await te.prompt([{type:"list",name:"selectedImage",message:"Select an image:",choices:f}]);t.image=_.value}let a={teepod_id:t.teepodId||3,name:t.name,image:t.image||"dstack-dev-0.3.5",vcpu:parseInt(t.vcpu),memory:parseInt(t.memory),disk_size:parseInt(t.diskSize),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},m=r.startSpinner("Getting public key from CVM"),c=await Nt(a);m.stop(!0),c||(r.error("Failed to get public key from CVM"),process.exit(1));let l=r.startSpinner("Encrypting environment variables"),p=await po(n,c.app_env_encrypt_pubkey);l.stop(!0),t.debug&&(r.debug("Public key:",c.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",p),r.debug("Environment variables:",JSON.stringify(n)));let g=r.startSpinner("Creating CVM"),u=await Ot({...a,encrypted_env:p,app_env_encrypt_pubkey:c.app_env_encrypt_pubkey,app_id_salt:c.app_id_salt});g.stop(!0),u||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.info(`CVM ID: ${u.id}`),r.info(`Name: ${u.name}`),r.info(`Status: ${u.status}`),r.info(`App ID: ${u.app_id}`),u.app_url?r.info(`App URL: ${u.app_url}`):r.info(`App URL: ${M}/dashboard/cvms/app_${u.app_id}`),r.info(""),r.info("Your CVM is being created. You can check its status with:"),r.info(`phala cvms get ${u.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as fo}from"commander";import go from"inquirer";var er=new fo().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{if(!t&&(t=await C(),!t))return;if(!e.force){let{confirm:s}=await go.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID ${t}? This action cannot be undone.`,default:!1}]);if(!s){r.info("Deletion cancelled");return}}let o=r.startSpinner(`Deleting CVM ${t}`),n=await Bt(t);o.stop(!0),n||(r.error(`Failed to delete CVM ${t}`),process.exit(1)),r.success(`CVM ${t} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as yo}from"commander";import ho from"fs";import{encryptEnvVars as vo}from"@phala/dstack-sdk/encrypt-env-vars";var tr=new yo().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{if(!t){r.info("No CVM specified, fetching available CVMs...");let p=await C();if(!p)return;t=p}let o=r.startSpinner(`Fetching current configuration for CVM ${t}`),n=await U(t);if(o.stop(!0),n||(r.error(`CVM with App ID ${t} not found`),process.exit(1)),!e.compose){let g=se(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");e.compose=await F("Enter the path to your Docker Compose file:",g,"file")}let s="";if(e.compose)try{s=ho.readFileSync(e.compose,"utf8")}catch(p){r.error(`Failed to read Docker Compose file: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}await T();let a="";if(e.envFile){let p=[];if(e.envFile)try{p=ee([],e.envFile),a=await vo(p,n.encrypted_env_pubkey)}catch(g){r.error(`Failed to read environment file: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}}let m={compose_manifest:{docker_compose_file:s,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${e.appId}`},encrypted_env:a,allow_restart:!0},c=r.startSpinner(`Upgrading CVM ${t}`),l=await jt(t,m);c.stop(!0),l||(r.error("Failed to upgrade CVM"),process.exit(1)),r.success(`CVM ${t} upgraded successfully`),l.detail&&r.info(`Details: ${l.detail}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as Co}from"commander";import re from"inquirer";var rr=new Co().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{if(!t&&(t=await C(),!t)){r.info("No CVMs found or selection cancelled");return}let o=await U(t),n=e.vcpu,s=e.memory,a=e.diskSize,m=e.allowRestart;n||(n=(await re.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:u=>{let d=parseInt(u);return isNaN(d)||d<0?"Please enter a valid non-negative number":!0},default:o.vcpu,filter:u=>parseInt(u)}])).vcpu),s||(s=(await re.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:u=>{let d=parseInt(u);return isNaN(d)||d<0?"Please enter a valid non-negative number":!0},default:o.memory,filter:u=>parseInt(u)}])).memory),a||(a=(await re.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:u=>{let d=parseInt(u);return isNaN(d)||d<0?"Please enter a valid non-negative number":!0},default:o.disk_size,filter:u=>parseInt(u)}])).diskSize),m||(m=(await re.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let c=`Are you sure you want to resize CVM ${t} with the following changes:
116
+ `;if(r.keyValueTable({vCPUs:o.vcpu!==n?`${o.vcpu} -> ${n}`:o.vcpu,Memory:o.memory!==s?`${o.memory} MB -> ${s} MB`:o.memory,"Disk Size":o.disk_size!==a?`${o.disk_size} GB -> ${a} GB`:o.disk_size,"Allow Restart":m?"Yes":"No"}),!e.yes){let{confirm:g}=await re.prompt([{type:"confirm",name:"confirm",message:c,default:!1}]);if(!g){r.info("Resize operation cancelled");return}}let l=r.startSpinner(`Resizing CVM with App ID ${t}`);await Kt(t,n,s,a,m?1:0),l.stop(!0),r.success(`CVM with App ID ${t} resized successfully`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var or=new wo().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(qt).addCommand(Ht).addCommand(Qt).addCommand(tr).addCommand(Zt).addCommand(Jt).addCommand(Yt).addCommand(Wt).addCommand(er).addCommand(rr);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function ko(){new So().name("phala").description(`${Fe}
117
+ Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("0.0.1").addCommand(rt).addCommand(it).addCommand(bt).addCommand(Pt).addCommand(Mt).addCommand(or).parse(process.argv)}ko().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
114
118
  //# sourceMappingURL=index.js.map