@elizaos/plugin-elizacloud 2.0.0-alpha.5 → 2.0.0-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.
|
@@ -17,6 +17,6 @@ we accept pull requests
|
|
|
17
17
|
https://github.com/browserify/crypto-browserify`)},Q.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}}),p0=d$(RG(),1),TG=p0.prng,zG=p0.pseudoRandomBytes,MG=p0.rng,qG=p0.randomBytes,PG=p0.Hash,kG=p0.createHash,_G=p0.Hmac,vG=p0.createHmac,jG=p0.getHashes,BG=p0.pbkdf2,xG=p0.pbkdf2Sync,NG=p0.Cipher,gG=p0.createCipher,fG=p0.Cipheriv,wG=p0.createCipheriv,yG=p0.Decipher,cG=p0.createDecipher,pG=p0.Decipheriv,hG=p0.createDecipheriv,uG=p0.getCiphers,bG=p0.listCiphers,lG=p0.DiffieHellmanGroup,dG=p0.createDiffieHellmanGroup,oG=p0.getDiffieHellman,nG=p0.createDiffieHellman,mG=p0.DiffieHellman,sG=p0.createSign,tG=p0.Sign,rG=p0.createVerify,aG=p0.Verify,eG=p0.createECDH,iG=p0.publicEncrypt,UV=p0.privateEncrypt,OV=p0.publicDecrypt,ZV=p0.privateDecrypt,XV=p0.randomFill,QV=p0.randomFillSync,YV=p0.createCredentials,AV=p0.constants,VV=["p192","p224","p256","p384","p521","curve25519","ed25519","secp256k1","secp224r1","prime256v1","prime192v1","ed25519","secp384r1","secp521r1"];IV=crypto,CV=crypto});import{logger as BU,ModelType as a0}from"@elizaos/core";var LX={name:"CHECK_CLOUD_CREDITS",description:"Check ElizaCloud credit balance, container costs, and estimated remaining runtime.",similes:["check credits","check balance","how much credit","cloud billing"],tags:["cloud","billing"],parameters:[{name:"detailed",description:"Include transaction history",required:!1,schema:{type:"boolean"}}],async validate(Q){return!!Q.getService("CLOUD_AUTH")?.isAuthenticated()},async handler(Q,$,V,W,C){let F=Q.getService("CLOUD_AUTH"),A=Q.getService("CLOUD_CONTAINER"),z=F.getClient(),M=W?.detailed===!0||$.metadata?.detailed===!0,{data:{balance:S}}=await z.get("/credits/balance"),R=A?.getTrackedContainers().filter((_)=>_.status==="running").length??0,L=R*0.67,H=L>0?S/L:null,q=[`ElizaCloud credits: $${S.toFixed(2)}`,R>0?`Active containers: ${R} ($${L.toFixed(2)}/day) — ~${H?.toFixed(1)} days remaining`:"No active containers."];if(M){let{data:_}=await z.get("/credits/summary");q.push(`Total spent: $${_.totalSpent.toFixed(2)} | Total added: $${_.totalAdded.toFixed(2)}`);for(let k of _.recentTransactions.slice(0,10)){let B=k.amount>=0?"+":"";q.push(` ${B}$${k.amount.toFixed(2)} — ${k.description} (${new Date(k.created_at).toLocaleDateString()})`)}}let P=q.join(`
|
|
18
18
|
`);if(C)await C({text:P,actions:["CHECK_CLOUD_CREDITS"]});return{success:!0,text:P,data:{balance:S,runningContainers:R,dailyCost:L,estimatedDaysRemaining:H}}}};function vY(Q,$){if($?.containerId)return String($.containerId);let V=Q.metadata?.actionParams;return V?.containerId?String(V.containerId):null}var WX={name:"FREEZE_CLOUD_AGENT",description:"Freeze a cloud agent: snapshot state, disconnect bridge, stop container.",similes:["freeze agent","hibernate agent","pause agent","stop cloud agent"],tags:["cloud","container","backup"],parameters:[{name:"containerId",description:"ID of the container to freeze",required:!0,schema:{type:"string"}}],async validate(Q){return!!Q.getService("CLOUD_AUTH")?.isAuthenticated()},async handler(Q,$,V,W,C){let F=Q.getService("CLOUD_CONTAINER"),A=Q.getService("CLOUD_BRIDGE"),z=Q.getService("CLOUD_BACKUP"),M=vY($,W);if(!M)return{success:!1,error:"Missing containerId"};let S=await F.getContainer(M);if(S.status!=="running")return{success:!1,error:`Container not running (status: ${S.status})`};let R=async(H)=>{if(C)await C({text:H,actions:["FREEZE_CLOUD_AGENT"]})};await R(`Freezing "${S.name}"... Creating snapshot.`);let L=null;if(z)L=(await z.createSnapshot(M,"manual",{trigger:"user-freeze",containerName:S.name})).id,z.cancelAutoBackup(M);if(A)await A.disconnect(M);return await F.deleteContainer(M),await R(`"${S.name}" frozen.${L?` Snapshot: ${L}`:""}`),{success:!0,text:`Agent "${S.name}" frozen`,data:{containerId:M,containerName:S.name,snapshotId:L}}}};import{logger as BY}from"@elizaos/core";var qU={enabled:!1,baseUrl:"https://www.elizacloud.ai/api/v1",inferenceMode:"cloud",autoProvision:!1,bridge:{reconnectIntervalMs:3000,maxReconnectAttempts:20,heartbeatIntervalMs:30000},backup:{autoBackupIntervalMs:3600000,maxSnapshots:10},container:{defaultImage:"elizaos/agent:latest",defaultArchitecture:"arm64",defaultCpu:1792,defaultMemory:1792,defaultPort:3000}};class DO extends Error{statusCode;errorBody;constructor(Q,$){super($.error);this.name="CloudApiError",this.statusCode=Q,this.errorBody=$}}class IZ extends DO{requiredCredits;constructor(Q){super(402,Q);this.name="InsufficientCreditsError",this.requiredCredits=Q.requiredCredits??0}}var jY=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GROQ_API_KEY","ELIZAOS_CLOUD_API_KEY","SMALL_MODEL","LARGE_MODEL","ELIZAOS_CLOUD_SMALL_MODEL","ELIZAOS_CLOUD_LARGE_MODEL"];function gO(Q){let $={};for(let V of jY){let W=Q.getSetting(V);if(W)$[V]=String(W)}return $}function xY(Q,$){if($&&Object.keys($).length>0)return $;let V=Q.metadata;if(V?.actionParams)return V.actionParams;let W=Q.content?.text??"",C=W.match(/name[:\s]+["']?([^"',]+)["']?/i)?.[1]?.trim(),F=W.match(/project[:\s]+["']?([^"',\s]+)["']?/i)?.[1]?.trim();return{name:C,project_name:F}}var HX={name:"PROVISION_CLOUD_AGENT",description:"Deploy an ElizaOS agent to ElizaCloud. Provisions a container, waits for deployment, connects the bridge, and starts auto-backup.",similes:["deploy agent to cloud","launch cloud agent","start remote agent","provision container"],tags:["cloud","container","deployment"],parameters:[{name:"name",description:"Human-readable name for the cloud agent",required:!0,schema:{type:"string"}},{name:"project_name",description:"Unique project identifier (lowercase, no spaces)",required:!0,schema:{type:"string"}},{name:"description",description:"Optional description",required:!1,schema:{type:"string"}},{name:"environment_vars",description:"Additional environment variables",required:!1,schema:{type:"object"}},{name:"auto_backup",description:"Enable periodic auto-backup (default: true)",required:!1,schema:{type:"boolean"}}],async validate(Q){return!!Q.getService("CLOUD_AUTH")?.isAuthenticated()},async handler(Q,$,V,W,C){let F=Q.getService("CLOUD_AUTH"),A=Q.getService("CLOUD_CONTAINER"),z=Q.getService("CLOUD_BRIDGE"),M=Q.getService("CLOUD_BACKUP");if(!F?.isAuthenticated()||!A)return{success:!1,error:"ElizaCloud not authenticated or container service unavailable"};let S=xY($,W);if(!S.name||!S.project_name)return{success:!1,error:"Missing required parameters: name and project_name"};let R=async(B)=>{if(C)await C({text:B,actions:["PROVISION_CLOUD_AGENT"]})};await R(`Provisioning cloud agent "${S.name}"... This typically takes 8-12 minutes.`);let L=qU.container,H={name:S.name,project_name:S.project_name,description:S.description,port:L.defaultPort,cpu:L.defaultCpu,memory:L.defaultMemory,architecture:L.defaultArchitecture,ecr_image_uri:L.defaultImage,environment_vars:{...gO(Q),...S.environment_vars},health_check_path:"/health"},q=await A.createContainer(H),P=q.data.id;await R(`Container created (id: ${P}). Credits: -$${q.creditsDeducted.toFixed(2)} ($${q.creditsRemaining.toFixed(2)} remaining).`);let _=await A.waitForDeployment(P);if(await R(`Container running at ${_.load_balancer_url}`),z)await z.connect(P),BY.info(`[PROVISION] Bridge connected to ${P}`);let k=S.auto_backup!==!1;if(k&&M)M.scheduleAutoBackup(P);return await R(`Agent "${S.name}" deployed.${k?" Auto-backup enabled.":""}`),{success:!0,text:`Cloud agent "${S.name}" deployed`,data:{containerId:P,containerUrl:_.load_balancer_url,status:_.status,creditsDeducted:q.creditsDeducted,creditsRemaining:q.creditsRemaining,bridgeConnected:z?.getConnectionState(P)==="connected",autoBackupEnabled:k}}}};function NY(Q,$){if($&&Object.keys($).length>0)return $;return Q.metadata?.actionParams??{}}async function gY(Q,$,V){let C=(await $.listContainers()).filter((A)=>A.project_name===V).map((A)=>A.id),F=[];for(let A of C)F.push(...await Q.listSnapshots(A));return F.sort((A,z)=>new Date(z.created_at).getTime()-new Date(A.created_at).getTime()),F[0]??null}var DX={name:"RESUME_CLOUD_AGENT",description:"Resume a frozen cloud agent from snapshot. Re-provisions, restores state, reconnects bridge.",similes:["resume agent","unfreeze agent","restart cloud agent","restore agent"],tags:["cloud","container","restore"],parameters:[{name:"name",description:"Name for the restored agent",required:!0,schema:{type:"string"}},{name:"project_name",description:"Project identifier (must match original)",required:!0,schema:{type:"string"}},{name:"snapshotId",description:"Specific snapshot ID (defaults to latest)",required:!1,schema:{type:"string"}},{name:"environment_vars",description:"Additional environment variables",required:!1,schema:{type:"object"}}],async validate(Q){return!!Q.getService("CLOUD_AUTH")?.isAuthenticated()},async handler(Q,$,V,W,C){let F=Q.getService("CLOUD_CONTAINER"),A=Q.getService("CLOUD_BRIDGE"),z=Q.getService("CLOUD_BACKUP"),M=NY($,W);if(!M.name||!M.project_name)return{success:!1,error:"Missing required parameters: name and project_name"};let S=async(k)=>{if(C)await C({text:k,actions:["RESUME_CLOUD_AGENT"]})};await S(`Resuming cloud agent "${M.name}"...`);let R=qU.container,L={name:M.name,project_name:M.project_name,port:R.defaultPort,cpu:R.defaultCpu,memory:R.defaultMemory,architecture:R.defaultArchitecture,ecr_image_uri:R.defaultImage,environment_vars:{...gO(Q),...M.environment_vars},health_check_path:"/health"},H=await F.createContainer(L),q=H.data.id;await S(`Container re-provisioned (${q}). Waiting for infrastructure...`);let P=await F.waitForDeployment(q),_=null;if(z){let k=M.snapshotId;if(k)await z.restoreSnapshot(q,k),_=k;else{let B=await gY(z,F,M.project_name);if(B)await z.restoreSnapshot(q,B.id),_=B.id}z.scheduleAutoBackup(q)}if(A)await A.connect(q);return await S(`Agent "${M.name}" resumed at ${P.load_balancer_url}.`+(_?` Restored snapshot ${_}.`:" No snapshot to restore.")),{success:!0,text:`Cloud agent "${M.name}" resumed`,data:{containerId:q,containerUrl:P.load_balancer_url,restoredSnapshotId:_,creditsDeducted:H.creditsDeducted,creditsRemaining:H.creditsRemaining}}}};var SX={name:"elizacloud_status",description:"ElizaCloud container and connection status",dynamic:!0,position:90,async get(Q,$,V){if(!Q.getService("CLOUD_AUTH")?.isAuthenticated())return{text:"ElizaCloud: Not authenticated",values:{cloudAuthenticated:!1}};let C=Q.getService("CLOUD_CONTAINER"),F=Q.getService("CLOUD_BRIDGE"),A=C?.getTrackedContainers()??[],z=F?.getConnectedContainerIds()??[],M=A.filter((H)=>H.status==="running").length,S=A.filter((H)=>H.status==="pending"||H.status==="building"||H.status==="deploying").length,R=A.map((H)=>({id:H.id,name:H.name,status:H.status,url:H.load_balancer_url,billing:H.billing_status,bridged:z.includes(H.id)}));return{text:[`ElizaCloud: ${A.length} container(s), ${M} running, ${z.length} bridged`,...R.map((H)=>` - ${H.name} [${H.status}]${H.url?` @ ${H.url}`:""}${H.bridged?" (bridged)":""}`)].join(`
|
|
19
19
|
`),values:{cloudAuthenticated:!0,totalContainers:A.length,runningContainers:M,deployingContainers:S},data:{containers:R}}}};var FX={name:"elizacloud_health",description:"ElizaCloud container health",dynamic:!0,position:92,private:!0,async get(Q,$,V){if(!Q.getService("CLOUD_AUTH")?.isAuthenticated())return{text:""};let F=Q.getService("CLOUD_CONTAINER")?.getTrackedContainers().filter((S)=>S.status==="running")??[];if(F.length===0)return{text:"No running containers.",values:{healthyContainers:0}};let A=F.map((S)=>({id:S.id,name:S.name,healthy:S.status==="running"&&S.billing_status==="active"&&!S.error_message,status:S.status,billing:S.billing_status})),z=A.filter((S)=>S.healthy).length;return{text:[`Health: ${z}/${A.length} healthy`,...A.map((S)=>` - ${S.name}: ${S.healthy?"OK":"UNHEALTHY"} (status=${S.status}, billing=${S.billing})`)].join(`
|
|
20
|
-
`),values:{healthyContainers:z,unhealthyContainers:A.length-z},data:{reports:A}}}};import{logger as RX}from"@elizaos/core";var CZ="https://www.elizacloud.ai/dashboard/billing",TX=new WeakMap,fY=60000,zX={name:"elizacloud_credits",description:"ElizaCloud credit balance",dynamic:!0,position:91,async get(Q,$,V){let W=Q.getService("CLOUD_AUTH");if(!W?.isAuthenticated())return{text:""};let C=TX.get(Q);if(C&&Date.now()-C.at<fY)return KZ(C.value);let F;try{let{data:A}=await W.getClient().get("/credits/balance");F=A.balance}catch(A){if(RX.warn(`[CloudCredits] Failed to fetch balance: ${A instanceof Error?A.message:A}`),C)return KZ(C.value);return{text:""}}if(TX.set(Q,{value:F,at:Date.now()}),F<1)RX.warn(`[CloudCredits] Low balance: $${F.toFixed(2)}`);return KZ(F)}};function KZ(Q){let $=Q<2,V=Q<0.5,W=`ElizaCloud credits: $${Q.toFixed(2)}`;if(V)W+=` (CRITICAL — top up at ${CZ})`;else if($)W+=` (LOW — top up at ${CZ})`;return{text:W,values:{cloudCredits:Q,cloudCreditsLow:$,cloudCreditsCritical:V,cloudTopUpUrl:CZ}}}var MX=new WeakMap,PX={name:"elizacloud_models",description:"Available AI models from ElizaCloud grouped by provider",dynamic:!0,position:92,async get(Q,$,V){let W=Q.getService("CLOUD_MODEL_REGISTRY");if(!W)return{text:""};let C=MX.get(Q);if(C&&Date.now()-C.at<300000)return qX(C.value);let F=await W.getModelsByProvider();if(Object.keys(F).length===0)return{text:""};return MX.set(Q,{value:F,at:Date.now()}),qX(F)}};function qX(Q){let $=Object.keys(Q).sort(),V=Object.values(Q).reduce((W,C)=>W+C.length,0);return{text:`ElizaCloud: ${V} models (${$.join(", ")})`,values:{cloudModelProviders:$.join(","),cloudModelCount:V}}}import{logger as hU}from"@elizaos/core";import{logger as fO}from"@elizaos/core";function wY(Q){if(typeof process>"u")return;let $=process.env[Q];return $===void 0?void 0:String($)}function u0(Q,$,V){let W=Q.getSetting($);if(W!==void 0&&W!==null)return String(W);return wY($)??V}function tU(){return typeof globalThis<"u"&&typeof globalThis.document<"u"}function kX(Q){return tU()&&!!u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL")}function gU(Q,$=!1){if(tU())return{};let V=$?yY(Q):rU(Q);return V?{Authorization:`Bearer ${V}`}:{}}function PU(Q){let $=u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL");return tU()&&$?$:u0(Q,"ELIZAOS_CLOUD_BASE_URL","https://www.elizacloud.ai/api/v1")}function _X(Q){let $=tU()?u0(Q,"ELIZAOS_CLOUD_BROWSER_EMBEDDING_URL")||u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL"):u0(Q,"ELIZAOS_CLOUD_EMBEDDING_URL");if($)return fO.debug(`[ELIZAOS_CLOUD] Using specific embedding base URL: ${$}`),$;return fO.debug("[ELIZAOS_CLOUD] Falling back to general base URL for embeddings."),PU(Q)}function rU(Q){return u0(Q,"ELIZAOS_CLOUD_API_KEY")}function yY(Q){let $=u0(Q,"ELIZAOS_CLOUD_EMBEDDING_API_KEY");if($)return fO.debug("[ELIZAOS_CLOUD] Using specific embedding API key (present)"),$;return fO.debug("[ELIZAOS_CLOUD] Falling back to general API key for embeddings."),rU(Q)}function wO(Q){return u0(Q,"ELIZAOS_CLOUD_SMALL_MODEL")??u0(Q,"SMALL_MODEL","openai/gpt-5-mini")}function SO(Q){return u0(Q,"ELIZAOS_CLOUD_LARGE_MODEL")??u0(Q,"LARGE_MODEL","anthropic/claude-sonnet-4.5")}function vX(Q){return u0(Q,"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL","gpt-5-mini")}function jX(Q){return u0(Q,"ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL","google/gemini-2.5-flash-image")??"google/gemini-2.5-flash-image"}function BX(Q){return u0(Q,"ELIZAOS_CLOUD_REASONING_SMALL_MODEL")??u0(Q,"REASONING_SMALL_MODEL","deepseek/deepseek-r1")}function xX(Q){return u0(Q,"ELIZAOS_CLOUD_REASONING_LARGE_MODEL")??u0(Q,"REASONING_LARGE_MODEL","anthropic/claude-opus-4.5")}function NX(Q){return u0(Q,"ELIZAOS_CLOUD_RESEARCH_MODEL")??u0(Q,"RESEARCH_MODEL","o3-deep-research")}function gX(Q){let $=u0(Q,"ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY","false");return String($).toLowerCase()==="true"}function fX(Q,$){(async()=>{try{if(!rU($)&&!tU()){hU.warn("ELIZAOS_CLOUD_API_KEY is not set in environment - ElizaOS Cloud functionality will be limited"),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys");return}try{let V=PU($),W=await fetch(`${V}/models`,{headers:{...gU($)}});if(!W.ok)hU.warn(`ElizaOS Cloud API key validation failed: ${W.statusText}`),hU.warn("ElizaOS Cloud functionality will be limited until a valid API key is provided"),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys");else hU.log("ElizaOS Cloud API key validated successfully")}catch(V){let W=V instanceof Error?V.message:String(V);hU.warn(`Error validating ElizaOS Cloud API key: ${W}`),hU.warn("ElizaOS Cloud functionality will be limited until a valid API key is provided")}}catch(V){let W=V?.errors?.map((C)=>C.message).join(", ")||(V instanceof Error?V.message:String(V));hU.warn(`ElizaOS Cloud plugin configuration issue: ${W} - You need to configure the ELIZAOS_CLOUD_API_KEY in your environment variables`),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys")}})()}import{logger as TU,ModelType as pY,VECTOR_DIMS as wX}from"@elizaos/core";import{EventType as cY}from"@elizaos/core";function yU(Q,$,V,W){let C=Number(W.inputTokens||0),F=Number(W.outputTokens||0),A=Number(W.totalTokens!=null?W.totalTokens:C+F);Q.emitEvent(cY.MODEL_USED,{runtime:Q,source:"elizacloud",type:$,tokens:{prompt:C,completion:F,total:A}})}var yO=100;function hY(Q){return{remainingRequests:parseInt(Q.headers.get("x-ratelimit-remaining-requests")||"",10)||void 0,remainingTokens:parseInt(Q.headers.get("x-ratelimit-remaining-tokens")||"",10)||void 0,limitRequests:parseInt(Q.headers.get("x-ratelimit-limit-requests")||"",10)||void 0,limitTokens:parseInt(Q.headers.get("x-ratelimit-limit-tokens")||"",10)||void 0,resetRequests:Q.headers.get("x-ratelimit-reset-requests")||void 0,resetTokens:Q.headers.get("x-ratelimit-reset-tokens")||void 0,retryAfter:parseInt(Q.headers.get("retry-after")||"",10)||void 0}}function yX(Q){let $=u0(Q,"ELIZAOS_CLOUD_EMBEDDING_MODEL","text-embedding-3-small"),V=Number.parseInt(u0(Q,"ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS","1536")||"1536",10);if(!Object.values(wX).includes(V)){let W=`Invalid embedding dimension: ${V}. Must be one of: ${Object.values(wX).join(", ")}`;throw TU.error(W),Error(W)}return{embeddingModelName:$,embeddingDimension:V}}function aU(Q,$){let V=Array(Q).fill(0);return V[0]=$,V}async function LZ(Q,$){let{embeddingDimension:V}=yX(Q);if($===null)return TU.debug("Creating test embedding for initialization"),aU(V,0.1);let W;if(typeof $==="string")W=$;else if(typeof $==="object"&&$.text)W=$.text;else return TU.warn("Invalid input format for embedding"),aU(V,0.2);if(!W.trim())return TU.warn("Empty text for embedding"),aU(V,0.3);return(await cX(Q,[W]))[0]}async function cX(Q,$){let{embeddingModelName:V,embeddingDimension:W}=yX(Q),C=_X(Q);if(!$||$.length===0)return TU.warn("[BatchEmbeddings] Empty texts array"),[];let F=[],A=Array($.length);for(let z=0;z<$.length;z++){let M=$[z]?.trim();if(M)F.push({text:M,originalIndex:z});else A[z]=aU(W,0.3)}if(F.length===0)return TU.warn("[BatchEmbeddings] All texts were empty"),A;for(let z=0;z<F.length;z+=yO){let M=Math.min(z+yO,F.length),S=F.slice(z,M),R=S.map((L)=>L.text);TU.info(`[BatchEmbeddings] Processing batch ${Math.floor(z/yO)+1}/${Math.ceil(F.length/yO)}: ${S.length} texts`);try{let L=await fetch(`${C}/embeddings`,{method:"POST",headers:{...gU(Q,!0),"Content-Type":"application/json"},body:JSON.stringify({model:V,input:R})}),H=hY(L);if(H.remainingRequests!==void 0&&H.remainingRequests<50)TU.warn(`[BatchEmbeddings] Rate limit: ${H.remainingRequests}/${H.limitRequests} requests remaining`);if(L.status===429){let P=H.retryAfter||30;TU.warn(`[BatchEmbeddings] Rate limited, waiting ${P}s...`),await new Promise((B)=>setTimeout(B,P*1000));let _=await fetch(`${C}/embeddings`,{method:"POST",headers:{...gU(Q,!0),"Content-Type":"application/json"},body:JSON.stringify({model:V,input:R})});if(!_.ok){TU.error(`[BatchEmbeddings] Retry failed: ${_.status}`);for(let B of S)A[B.originalIndex]=aU(W,0.4);continue}let k=await _.json();if(k?.data){for(let B of k.data){let j=S[B.index].originalIndex;A[j]=B.embedding}TU.info(`[BatchEmbeddings] Retry successful for ${S.length} embeddings`)}continue}if(!L.ok){TU.error(`[BatchEmbeddings] API error: ${L.status} - ${L.statusText}`);for(let P of S)A[P.originalIndex]=aU(W,0.4);continue}let q=await L.json();if(!q?.data||!Array.isArray(q.data)){TU.error("[BatchEmbeddings] API returned invalid structure");for(let P of S)A[P.originalIndex]=aU(W,0.5);continue}for(let P of q.data){let _=S[P.index].originalIndex;A[_]=P.embedding}if(q.usage){let P={inputTokens:q.usage.prompt_tokens,outputTokens:0,totalTokens:q.usage.total_tokens};yU(Q,pY.TEXT_EMBEDDING,`batch:${S.length}`,P)}TU.debug(`[BatchEmbeddings] Got ${S.length} embeddings (${W}d), remaining: ${H.remainingRequests??"unknown"}`)}catch(L){let H=L instanceof Error?L.message:String(L);TU.error(`[BatchEmbeddings] Error: ${H}`);for(let q of S)A[q.originalIndex]=aU(W,0.6)}}return A}import{logger as kO,ModelType as dA}from"@elizaos/core";import{logger as vQ}from"@elizaos/core";import{JSONParseError as lA}from"ai";function BZ(){return async({text:Q,error:$})=>{try{if($ instanceof lA){let V=Q.replace(/```json\n|\n```|```/g,"");return JSON.parse(V),V}return null}catch(V){let W=V instanceof Error?V.message:String(V);return vQ.warn(`Failed to repair JSON text: ${W}`),null}}}async function jQ(Q){try{let{Readable:$}=await Promise.resolve().then(() => PY(dO(),1)),V=Q.getReader();return new $({async read(){try{let{done:W,value:C}=await V.read();if(W)this.push(null);else this.push(C)}catch(W){this.destroy(W)}},destroy(W,C){V.cancel().finally(()=>C(W))}})}catch($){let V=$ instanceof Error?$.message:String($);throw vQ.error(`Failed to load node:stream module: ${V}`),Error("Cannot convert stream: node:stream module unavailable. This feature requires a Node.js environment.")}}function BQ(Q){let V=Q.match(/title[:\s]+(.+?)(?:\n|$)/i)?.[1]?.trim()||"Image Analysis",W=Q.replace(/title[:\s]+(.+?)(?:\n|$)/i,"").trim();return{title:V,description:W}}async function xZ(Q,$){let V=$.count||1,W=$.size||"1024x1024",C=$.prompt,F=jX(Q);kO.log(`[ELIZAOS_CLOUD] Using IMAGE model: ${F}`);let A=PU(Q),M={"1024x1024":"1:1","1792x1024":"16:9","1024x1792":"9:16"}[W]||"1:1";try{let S=`${A}/generate-image`,R={prompt:C,numImages:V,aspectRatio:M,model:F},L=await fetch(S,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json"},body:JSON.stringify(R)});if(!L.ok){let _=await L.text();throw Error(`Failed to generate image: ${L.status} ${_}`)}return(await L.json()).images.map((_)=>({url:_.url||_.image}))}catch(S){let R=S instanceof Error?S.message:String(S);throw kO.error(`[ELIZAOS_CLOUD] Image generation error: ${R}`),S}}async function NZ(Q,$){let V,W,C=vX(Q);kO.log(`[ELIZAOS_CLOUD] Using IMAGE_DESCRIPTION model: ${C}`);let F=Number.parseInt(u0(Q,"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS","8192")||"8192",10);if(typeof $==="string")V=$,W="Please analyze this image and provide a title and detailed description.";else V=$.imageUrl,W=$.prompt||"Please analyze this image and provide a title and detailed description.";let A=[{role:"user",content:[{type:"text",text:W},{type:"image_url",image_url:{url:V}}]}],z=PU(Q);try{let M={model:C,messages:A,max_tokens:F},S=null;for(let H=0;H<3;H++){if(S=await fetch(`${z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",...gU(Q)},body:JSON.stringify(M)}),S.status===429&&H<2){let q=(H+1)*2000;kO.warn(`[ELIZAOS_CLOUD] Image analysis rate-limited (429), retrying in ${q/1000}s...`),await new Promise((P)=>setTimeout(P,q));continue}break}if(!S||!S.ok){let H=S?.status??0;if(H===402)throw Error("Eliza Cloud credits exhausted — top up at https://www.elizacloud.ai/dashboard/billing");throw Error(`ElizaOS Cloud API error: ${H}`)}let R=await S.json(),L=R.choices?.[0]?.message?.content;if(R.usage)yU(Q,dA.IMAGE_DESCRIPTION,typeof $==="string"?$:$.prompt||"",{inputTokens:R.usage.prompt_tokens,outputTokens:R.usage.completion_tokens,totalTokens:R.usage.total_tokens});if(!L)return{title:"Failed to analyze image",description:"No response from API"};return BQ(L)}catch(M){let S=M instanceof Error?M.message:String(M);return kO.error(`Error analyzing image: ${S}`),{title:"Failed to analyze image",description:`Error: ${S}`}}}import{logger as IO,ModelType as xQ}from"@elizaos/core";import{generateObject as nA,JSONParseError as mA}from"ai";import{createOpenAI as oA}from"@ai-sdk/openai";function oO(Q){let $=PU(Q),V=rU(Q)??(kX(Q)?"eliza-proxy":void 0);return oA({apiKey:V??"",baseURL:$})}var sA=["o1","o3","o4","deepseek-r1","deepseek-reasoner","claude-opus-4.5","claude-opus-4","gpt-5-mini","gpt-5"];function tA(Q){let $=Q.toLowerCase();return sA.some((V)=>$.includes(V))}async function NQ(Q,$,V,W){let C=oO(Q),F=W(Q);IO.log(`[ELIZAOS_CLOUD] Using ${V} model: ${F}`);let A=tA(F);try{let z=C.chat(F),{object:M,usage:S}=await nA({model:z,output:"no-schema",prompt:$.prompt,...A?{}:{temperature:$.temperature??0},experimental_repairText:BZ()});if(S)yU(Q,V,$.prompt,S);return M}catch(z){if(z instanceof mA){IO.error(`[generateObject] Failed to parse JSON: ${z.message}`);let S=await BZ()({text:z.text,error:z});if(S)try{let R=JSON.parse(S);return IO.info("[generateObject] Successfully repaired JSON."),R}catch(R){let L=R instanceof Error?R.message:String(R);throw IO.error(`[generateObject] Failed to parse repaired JSON: ${L}`),R}else throw IO.error("[generateObject] JSON repair failed."),z}else{let M=z instanceof Error?z.message:String(z);throw IO.error(`[generateObject] Error: ${M}`),z}}}async function gZ(Q,$){return NQ(Q,$,xQ.OBJECT_SMALL,wO)}async function fZ(Q,$){return NQ(Q,$,xQ.OBJECT_LARGE,SO)}import{logger as rA,ModelType as aA}from"@elizaos/core";function eA(Q){return Q.filter(($)=>$.url!==void 0).map(($)=>({url:$.url,title:$.title??"",startIndex:$.start_index??0,endIndex:$.end_index??0}))}function iA(Q){let $=[];for(let V of Q)switch(V.type){case"web_search_call":$.push({id:V.id??"",type:"web_search_call",status:V.status??"completed",action:{type:V.action?.type??"search",query:V.action?.query,url:V.action?.url}});break;case"file_search_call":$.push({id:V.id??"",type:"file_search_call",status:V.status??"completed",query:V.query??"",results:V.results?.map((W)=>({fileId:W.file_id,fileName:W.file_name,score:W.score}))});break;case"code_interpreter_call":$.push({id:V.id??"",type:"code_interpreter_call",status:V.status??"completed",code:V.code??"",output:V.output});break;case"mcp_tool_call":$.push({id:V.id??"",type:"mcp_tool_call",status:V.status??"completed",serverLabel:V.server_label??"",toolName:V.tool_name??"",arguments:V.arguments??{},result:V.result});break;case"message":{let W=V.content??[];$.push({type:"message",content:W.filter((C)=>C.type==="output_text").map((C)=>({type:"output_text",text:C.text??"",annotations:eA(C.annotations??[])}))});break}}return $}async function wZ(Q,$){let V=$.model??NX(Q);rA.log(`[ELIZAOS_CLOUD] Using RESEARCH model: ${V}`);let W=PU(Q),C=$.tools??[{type:"web_search_preview"}],F={model:V,input:$.input,tools:C};if($.instructions)F.instructions=$.instructions;if($.background!==void 0)F.background=$.background;if($.maxToolCalls!==void 0)F.max_tool_calls=$.maxToolCalls;if($.reasoningSummary)F.reasoning={summary:$.reasoningSummary};let A=await fetch(`${W}/responses`,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json"},body:JSON.stringify(F)});if(!A.ok){let L=await A.text();throw Error(`Research API error: ${A.status} ${L}`)}let z=await A.json();if(z.usage)yU(Q,aA.RESEARCH,$.input,{inputTokens:z.usage.input_tokens,outputTokens:z.usage.output_tokens,totalTokens:z.usage.total_tokens});let M=iA(z.output),S="",R=[];for(let L of M)if(L.type==="message"){for(let H of L.content)if(H.type==="output_text")S+=H.text,R.push(...H.annotations)}return{id:z.id,text:S,annotations:R,outputItems:M,status:z.status}}import{logger as _E}from"@elizaos/core";async function yZ(Q,$){let V=u0(Q,"ELIZAOS_CLOUD_TTS_MODEL","gpt-5-mini-tts"),W=u0(Q,"ELIZAOS_CLOUD_TTS_VOICE","nova"),C=u0(Q,"ELIZAOS_CLOUD_TTS_INSTRUCTIONS",""),F=PU(Q),A=$.model||V,z=$.voice||W,M=$.instructions??C,S=$.format||"mp3";try{let R=await fetch(`${F}/audio/speech`,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json",...S==="mp3"?{Accept:"audio/mpeg"}:{}},body:JSON.stringify({model:A,voice:z,input:$.text,format:S,...M&&{instructions:M}})});if(!R.ok){let L=await R.text();throw Error(`ElizaOS Cloud TTS error ${R.status}: ${L}`)}if(!R.body)throw Error("ElizaOS Cloud TTS response body is null");if(!tU())return await jQ(R.body);return R.body}catch(R){let L=R instanceof Error?R.message:String(R);throw Error(`Failed to fetch speech from ElizaOS Cloud TTS: ${L}`)}}import{logger as nO,ModelType as lU}from"@elizaos/core";import{generateText as U$,streamText as O$}from"ai";var Z$=["o1","o3","o4","deepseek-r1","deepseek-reasoner","claude-opus-4.5","claude-opus-4","gpt-5-mini","gpt-5"];function X$(Q){let $=Q.toLowerCase();return Z$.some((V)=>$.includes(V))}function Q$(Q,$){switch($){case lU.TEXT_SMALL:return wO(Q);case lU.TEXT_LARGE:return SO(Q);case lU.TEXT_REASONING_SMALL:return BX(Q);case lU.TEXT_REASONING_LARGE:return xX(Q);default:return SO(Q)}}function Y$(Q,$,V){let{prompt:W,stopSequences:C=[]}=V,F=V.maxTokens??8192,A=oO(Q),z=Q$(Q,$),M=gX(Q),S=A.chat(z),R=X$(z)||$===lU.TEXT_REASONING_SMALL||$===lU.TEXT_REASONING_LARGE;return{generateParams:{model:S,prompt:W,system:Q.character.system??void 0,...R?{}:{stopSequences:C},maxOutputTokens:F,experimental_telemetry:{isEnabled:M}},modelName:z,modelType:$,prompt:W}}function A$(Q,$,V,W){nO.debug(`[ELIZAOS_CLOUD] Streaming text with ${$} model`);let C=O$(V);return{textStream:C.textStream,text:Promise.resolve(C.text),usage:Promise.resolve(C.usage).then((F)=>{if(F){yU(Q,$,W,F);let A=F.inputTokens??0,z=F.outputTokens??0;return{promptTokens:A,completionTokens:z,totalTokens:A+z}}return}),finishReason:Promise.resolve(C.finishReason)}}async function mO(Q,$,V){let{generateParams:W,modelName:C,prompt:F}=Y$(Q,$,V);if(nO.debug(`[ELIZAOS_CLOUD] Generating text with ${$} model: ${C}`),V.stream)return A$(Q,$,W,F);nO.log(`[ELIZAOS_CLOUD] Using ${$} model: ${C}`),nO.log(F);let A=await U$(W);if(A.usage)yU(Q,$,F,A.usage);return A.text}async function cZ(Q,$){return mO(Q,lU.TEXT_SMALL,$)}async function pZ(Q,$){return mO(Q,lU.TEXT_LARGE,$)}async function hZ(Q,$){return mO(Q,lU.TEXT_REASONING_SMALL,$)}async function uZ(Q,$){return mO(Q,lU.TEXT_REASONING_LARGE,$)}import{logger as ZO,Service as KV}from"@elizaos/core";import{logger as $$}from"@elizaos/core";class bZ{baseUrl;apiKey;constructor(Q,$){this.baseUrl=Q.replace(/\/+$/,""),this.apiKey=$}setApiKey(Q){this.apiKey=Q}setBaseUrl(Q){this.baseUrl=Q.replace(/\/+$/,"")}getBaseUrl(){return this.baseUrl}getApiKey(){return this.apiKey}buildWsUrl(Q){return`${this.baseUrl.replace(/^http/,"ws")}${Q}`}async get(Q){return this.request("GET",Q)}async post(Q,$){return this.request("POST",Q,$)}async delete(Q){return this.request("DELETE",Q)}async postUnauthenticated(Q,$){return this.request("POST",Q,$,!0)}async request(Q,$,V,W=!1){let C=`${this.baseUrl}${$}`;$$.debug(`[CloudAPI] ${Q} ${C}`);let F={"Content-Type":"application/json",Accept:"application/json"};if(!W&&this.apiKey)F.Authorization=`Bearer ${this.apiKey}`;let A=await fetch(C,{method:Q,headers:F,...V?{body:JSON.stringify(V)}:{}});return this.handleResponse(A)}async handleResponse(Q){if(!(Q.headers.get("content-type")??"").includes("application/json")){if(!Q.ok)throw new DO(Q.status,{success:!1,error:`HTTP ${Q.status}: ${Q.statusText}`});return{success:!0}}let V=await Q.json();if(!Q.ok){let W=V;throw Q.status===402?new IZ(W):new DO(Q.status,W)}return V}}async function LV(){let Q=await Promise.resolve().then(() => (dZ(),lZ)),$=await Promise.resolve().then(() => (jU(),vU)),V=Q.cpus(),W=[Q.hostname(),Q.platform(),Q.arch(),V[0]?.model??"?",V.length,Q.totalmem()].join(":");return $.createHash("sha256").update(W).digest("hex")}function WV(){if(typeof process>"u")return"web";return{darwin:"macos",win32:"windows",linux:"linux"}[process.platform]??"linux"}class QZ extends KV{static serviceType="CLOUD_AUTH";capabilityDescription="ElizaCloud device authentication and session management";client;credentials=null;constructor(Q){super(Q);this.client=new bZ(qU.baseUrl)}static async start(Q){let $=new QZ(Q);return await $.initialize(),$}async stop(){this.credentials=null}async initialize(){let Q=String(this.runtime.getSetting("ELIZAOS_CLOUD_BASE_URL")??qU.baseUrl);this.client.setBaseUrl(Q);let $=this.runtime.getSetting("ELIZAOS_CLOUD_API_KEY");if($){let W=String($);this.client.setApiKey(W),this.credentials={apiKey:W,userId:String(this.runtime.getSetting("ELIZAOS_CLOUD_USER_ID")??""),organizationId:String(this.runtime.getSetting("ELIZAOS_CLOUD_ORG_ID")??""),authenticatedAt:Date.now()},ZO.info("[CloudAuth] Authenticated with saved API key"),this.validateApiKey(W).then((C)=>{if(!C)ZO.warn("[CloudAuth] Saved API key could not be validated (cloud may be unreachable or key revoked) — model calls will use the key anyway")}).catch(()=>{});return}let V=this.runtime.getSetting("ELIZAOS_CLOUD_ENABLED");if(V==="true"||V==="1")try{await this.authenticateWithDevice()}catch(W){let C=W instanceof Error?W.message:String(W);ZO.warn(`[CloudAuth] Device auth failed (cloud may be unreachable): ${C}`),ZO.info("[CloudAuth] Service will start unauthenticated — cloud features disabled until connectivity is restored")}else ZO.info("[CloudAuth] Cloud not enabled (set ELIZAOS_CLOUD_ENABLED=true)")}async validateApiKey(Q){try{return(await fetch(`${this.client.getBaseUrl()}/models`,{headers:{Authorization:`Bearer ${Q}`},signal:AbortSignal.timeout(1e4)})).ok}catch($){let V=$ instanceof Error?$.message:String($);return ZO.warn(`[CloudAuth] Could not reach cloud API to validate key: ${V}`),!1}}async authenticateWithDevice(){let Q=await LV(),$=WV(),V=process.env.ELIZAOS_CLOUD_APP_VERSION??"2.0.0-alpha",W=await Promise.resolve().then(() => (dZ(),lZ));ZO.info(`[CloudAuth] Authenticating device (platform=${$})`);let C=await this.client.postUnauthenticated("/device-auth",{deviceId:Q,platform:$,appVersion:V,deviceName:W.hostname()});this.credentials={apiKey:C.data.apiKey,userId:C.data.userId,organizationId:C.data.organizationId,authenticatedAt:Date.now()},this.client.setApiKey(C.data.apiKey);let F=C.data.isNew?"New account created":"Authenticated";return ZO.info(`[CloudAuth] ${F} (credits: $${C.data.credits.toFixed(2)})`),this.credentials}isAuthenticated(){return this.credentials!==null}getCredentials(){return this.credentials}getApiKey(){return this.credentials?.apiKey??this.client.getApiKey()}getClient(){return this.client}getUserId(){return this.credentials?.userId}getOrganizationId(){return this.credentials?.organizationId}}import{logger as NU,Service as HV}from"@elizaos/core";class YZ extends HV{static serviceType="CLOUD_BACKUP";capabilityDescription="ElizaCloud agent state backup and restore";authService;autoBackups=new Map;maxSnapshots=qU.backup.maxSnapshots;backupIntervalMs=qU.backup.autoBackupIntervalMs;static async start(Q){let $=new YZ(Q);return await $.initialize(),$}async stop(){for(let[,Q]of this.autoBackups)clearInterval(Q.timer);this.autoBackups.clear(),NU.info("[CloudBackup] Service stopped")}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){NU.warn("[CloudBackup] CloudAuthService not available");return}this.authService=Q,NU.info("[CloudBackup] Service initialized")}async createSnapshot(Q,$="manual",V){let C=await this.authService.getClient().post(`/agent-state/${Q}/snapshot`,{snapshotType:$,metadata:V});NU.info(`[CloudBackup] Created ${$} snapshot for container ${Q} (id=${C.data.id}, size=${DV(C.data.sizeBytes)})`);let F=this.autoBackups.get(Q);if(F)F.lastBackupAt=Date.now();return C.data}async listSnapshots(Q){return(await this.authService.getClient().get(`/agent-state/${Q}/snapshots`)).data}async restoreSnapshot(Q,$){await this.authService.getClient().post(`/agent-state/${Q}/restore`,{snapshotId:$}),NU.info(`[CloudBackup] Restored snapshot ${$} for container ${Q}`)}async getLatestSnapshot(Q){let $=await this.listSnapshots(Q);if($.length===0)return null;return $.sort((V,W)=>new Date(W.created_at).getTime()-new Date(V.created_at).getTime()),$[0]}scheduleAutoBackup(Q,$){if(this.autoBackups.has(Q)){NU.debug(`[CloudBackup] Auto-backup already scheduled for ${Q}`);return}let V=$??this.backupIntervalMs,W=setInterval(()=>{NU.debug(`[CloudBackup] Running auto-backup for container ${Q}`),this.createSnapshot(Q,"auto",{trigger:"scheduled",scheduledIntervalMs:V}).then(()=>this.pruneSnapshots(Q)).catch((C)=>{NU.error(`[CloudBackup] Auto-backup failed for ${Q}: ${C.message}`)})},V);this.autoBackups.set(Q,{containerId:Q,timer:W,lastBackupAt:null}),NU.info(`[CloudBackup] Scheduled auto-backup for ${Q} every ${Math.round(V/60000)} minutes`)}cancelAutoBackup(Q){let $=this.autoBackups.get(Q);if(!$)return;clearInterval($.timer),this.autoBackups.delete(Q),NU.info(`[CloudBackup] Cancelled auto-backup for ${Q}`)}async createPreEvictionSnapshot(Q){return NU.info(`[CloudBackup] Creating pre-eviction snapshot for ${Q}`),this.createSnapshot(Q,"pre-eviction",{trigger:"billing-eviction",createdAt:new Date().toISOString()})}async pruneSnapshots(Q){let W=(await this.listSnapshots(Q)).filter((F)=>F.snapshotType==="auto").sort((F,A)=>new Date(A.created_at).getTime()-new Date(F.created_at).getTime()).slice(this.maxSnapshots);if(W.length===0)return;let C=this.authService.getClient();for(let F of W)await C.delete(`/agent-state/${Q}/snapshots/${F.id}`),NU.debug(`[CloudBackup] Pruned old auto snapshot ${F.id} for ${Q}`);NU.info(`[CloudBackup] Pruned ${W.length} old auto snapshot(s) for ${Q}`)}isAutoBackupScheduled(Q){return this.autoBackups.has(Q)}getLastBackupTime(Q){return this.autoBackups.get(Q)?.lastBackupAt??null}}function DV(Q){if(Q<1024)return`${Q} B`;if(Q<1048576)return`${(Q/1024).toFixed(1)} KB`;if(Q<1073741824)return`${(Q/1048576).toFixed(1)} MB`;return`${(Q/1073741824).toFixed(1)} GB`}import{logger as cU,Service as SV}from"@elizaos/core";import{WebSocket as VX}from"undici";class AZ extends SV{static serviceType="CLOUD_BRIDGE";capabilityDescription="WebSocket bridge to cloud-hosted ElizaOS agents";authService;bridgeConfig=qU.bridge;connections=new Map;static async start(Q){let $=new AZ(Q);return await $.initialize(),$}async stop(){for(let[Q]of this.connections)await this.disconnect(Q);cU.info("[CloudBridge] Service stopped")}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){cU.warn("[CloudBridge] CloudAuthService not available");return}this.authService=Q,cU.info("[CloudBridge] Service initialized")}async connect(Q){if(this.connections.has(Q)){let $=this.connections.get(Q);if($.state==="connected"||$.state==="connecting"){cU.debug(`[CloudBridge] Already connected/connecting to ${Q}`);return}}await this.establishConnection(Q,0)}async disconnect(Q){let $=this.connections.get(Q);if(!$)return;if($.heartbeatTimer)clearInterval($.heartbeatTimer);if($.reconnectTimer)clearTimeout($.reconnectTimer);for(let[,V]of $.pendingRequests)clearTimeout(V.timeout),V.reject(Error("Bridge disconnected"));if($.pendingRequests.clear(),$.ws.readyState===VX.OPEN||$.ws.readyState===VX.CONNECTING)$.ws.close(1000,"Client disconnect");this.connections.delete(Q),cU.info(`[CloudBridge] Disconnected from ${Q}`)}async establishConnection(Q,$){let V=this.authService.getClient(),W=this.authService.getApiKey(),C=V.buildWsUrl(`/agent-bridge/${Q}`),F=W?`${C}?token=${encodeURIComponent(W)}`:C,A={ws:new VX(F),state:"connecting",connectedAt:null,lastHeartbeat:null,reconnectAttempts:$,heartbeatTimer:null,reconnectTimer:null,handlers:this.connections.get(Q)?.handlers??new Set,pendingRequests:new Map,nextRequestId:1};this.connections.set(Q,A),A.ws.addEventListener("open",()=>{A.state="connected",A.connectedAt=Date.now(),A.reconnectAttempts=0,cU.info(`[CloudBridge] Connected to agent ${Q}`),A.heartbeatTimer=setInterval(()=>{this.sendHeartbeat(Q)},this.bridgeConfig.heartbeatIntervalMs)}),A.ws.addEventListener("message",(z)=>{let M=z.data,S=typeof M==="string"?M:M instanceof Buffer?M.toString("utf-8"):String(M),R=JSON.parse(S);if(R.method==="heartbeat.ack"){A.lastHeartbeat=Date.now();return}if(R.id!==void 0&&!R.method){let L=A.pendingRequests.get(R.id);if(L){if(clearTimeout(L.timeout),A.pendingRequests.delete(R.id),R.error)L.reject(Error(R.error.message));else L.resolve(R.result);return}}for(let L of A.handlers)L(R)}),A.ws.addEventListener("close",(z)=>{if(A.state="disconnected",A.heartbeatTimer)clearInterval(A.heartbeatTimer);if(z.code===1000){cU.info(`[CloudBridge] Clean disconnect from ${Q}`);return}cU.warn(`[CloudBridge] Connection lost to ${Q} (code=${z.code}, reason=${z.reason})`),this.scheduleReconnect(Q,A.reconnectAttempts+1)}),A.ws.addEventListener("error",()=>{cU.error(`[CloudBridge] WebSocket error for ${Q}`)})}scheduleReconnect(Q,$){if($>this.bridgeConfig.maxReconnectAttempts){cU.error(`[CloudBridge] Max reconnect attempts (${this.bridgeConfig.maxReconnectAttempts}) reached for ${Q}`),this.connections.delete(Q);return}let V=this.bridgeConfig.reconnectIntervalMs,W=Math.min(V*2**Math.min($,5),120000),C=Math.floor(Math.random()*1000);cU.info(`[CloudBridge] Reconnecting to ${Q} in ${Math.round((W+C)/1000)}s (attempt ${$})`);let F=this.connections.get(Q);if(F)F.state="reconnecting",F.reconnectTimer=setTimeout(()=>{this.establishConnection(Q,$)},W+C)}sendHeartbeat(Q){let $=this.connections.get(Q);if(!$||$.state!=="connected")return;let V={jsonrpc:"2.0",method:"heartbeat",params:{timestamp:Date.now()}};$.ws.send(JSON.stringify(V))}async sendRequest(Q,$,V,W=60000){let C=this.connections.get(Q);if(!C||C.state!=="connected")throw Error(`Not connected to container ${Q}`);let F=C.nextRequestId++,A={jsonrpc:"2.0",id:F,method:$,params:V};return new Promise((z,M)=>{let S=setTimeout(()=>{C.pendingRequests.delete(F),M(Error(`Request ${$} timed out after ${W}ms`))},W);C.pendingRequests.set(F,{resolve:z,reject:M,timeout:S}),C.ws.send(JSON.stringify(A))})}sendNotification(Q,$,V){let W=this.connections.get(Q);if(!W||W.state!=="connected")throw Error(`Not connected to container ${Q}`);let C={jsonrpc:"2.0",method:$,params:V};W.ws.send(JSON.stringify(C))}async sendChatMessage(Q,$,V,W){return await this.sendRequest(Q,"message.send",{text:$,roomId:V,metadata:W})}async getAgentStatus(Q){return await this.sendRequest(Q,"status.get",{})}async updateAgentConfig(Q,$){await this.sendRequest(Q,"config.update",$)}onMessage(Q,$){let V=this.connections.get(Q);if(!V)V={ws:null,state:"disconnected",connectedAt:null,lastHeartbeat:null,reconnectAttempts:0,heartbeatTimer:null,reconnectTimer:null,handlers:new Set,pendingRequests:new Map,nextRequestId:1},this.connections.set(Q,V);return V.handlers.add($),()=>{V.handlers.delete($)}}getConnectionState(Q){return this.connections.get(Q)?.state??"disconnected"}getConnectionInfo(Q){let $=this.connections.get(Q);if(!$)return null;return{containerId:Q,state:$.state,connectedAt:$.connectedAt,lastHeartbeat:$.lastHeartbeat,reconnectAttempts:$.reconnectAttempts}}getConnectedContainerIds(){let Q=[];for(let[$,V]of this.connections)if(V.state==="connected")Q.push($);return Q}}import{logger as pU,Service as FV}from"@elizaos/core";class $Z extends FV{static serviceType="CLOUD_CONTAINER";capabilityDescription="ElizaCloud container provisioning and lifecycle management";authService;containerDefaults=qU.container;tracked=new Map;static async start(Q){let $=new $Z(Q);return await $.initialize(),$}async stop(){for(let[,Q]of this.tracked){if(Q.pollingTimer)clearTimeout(Q.pollingTimer);if(Q.healthTimer)clearInterval(Q.healthTimer)}this.tracked.clear()}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){pU.warn("[CloudContainer] CloudAuthService not available, container operations will fail");return}if(this.authService=Q,this.authService.isAuthenticated()){let $=await this.listContainers();for(let V of $){if(this.tracked.set(V.id,{container:V,pollingTimer:null,healthTimer:null}),V.status==="pending"||V.status==="building"||V.status==="deploying")this.startPolling(V.id);if(V.status==="running")this.startHealthMonitoring(V.id)}pU.info(`[CloudContainer] Loaded ${$.length} existing container(s)`)}}getClient(){return this.authService.getClient()}async createContainer(Q){let $=this.getClient(),V=this.containerDefaults,W={name:Q.name,project_name:Q.project_name,description:Q.description,port:Q.port??V.defaultPort,desired_count:Q.desired_count??1,cpu:Q.cpu??V.defaultCpu,memory:Q.memory??V.defaultMemory,environment_vars:Q.environment_vars??{},health_check_path:Q.health_check_path??"/health",ecr_image_uri:Q.ecr_image_uri,ecr_repository_uri:Q.ecr_repository_uri,image_tag:Q.image_tag,architecture:Q.architecture??V.defaultArchitecture},C=await $.post("/containers",W);return this.tracked.set(C.data.id,{container:C.data,pollingTimer:null,healthTimer:null}),this.startPolling(C.data.id),pU.info(`[CloudContainer] Created container "${Q.name}" (id=${C.data.id}, stack=${C.stackName})`),C}async listContainers(){return(await this.getClient().get("/containers")).data}async getContainer(Q){let V=await this.getClient().get(`/containers/${Q}`),W=this.tracked.get(Q);if(W)W.container=V.data;return V.data}async deleteContainer(Q){await this.getClient().delete(`/containers/${Q}`);let V=this.tracked.get(Q);if(V){if(V.pollingTimer)clearTimeout(V.pollingTimer);if(V.healthTimer)clearInterval(V.healthTimer);this.tracked.delete(Q)}pU.info(`[CloudContainer] Deleted container ${Q}`)}startPolling(Q){let $=this.tracked.get(Q);if(!$)return;let V=0,W=120,C=5000,F=30000,A=async()=>{if(V++,V>W){pU.error(`[CloudContainer] Polling timed out for container ${Q} after ${W} attempts`);return}let z=await this.getContainer(Q),M=z.status;if(pU.debug(`[CloudContainer] Poll #${V} for ${Q}: status=${M}`),M==="running"){pU.info(`[CloudContainer] Container ${Q} is now running at ${z.load_balancer_url}`),this.startHealthMonitoring(Q);return}if(M==="failed"||M==="stopped"||M==="suspended"){if(pU.warn(`[CloudContainer] Container ${Q} reached terminal state: ${M}`),z.error_message)pU.error(`[CloudContainer] Error: ${z.error_message}`);return}let S=Math.min(C*2**Math.min(V-1,3),F);$.pollingTimer=setTimeout(A,S)};$.pollingTimer=setTimeout(A,C)}async waitForDeployment(Q,$=900000){let V=Date.now()+$,W=5000,C=30000;while(Date.now()<V){let F=await this.getContainer(Q);if(F.status==="running")return F;if(F.status==="failed")throw Error(`Container deployment failed: ${F.error_message??"unknown error"}`);if(F.status==="stopped"||F.status==="suspended")throw Error(`Container reached terminal state: ${F.status}`);await new Promise((A)=>setTimeout(A,W)),W=Math.min(W*1.5,C)}throw Error(`Container deployment timed out after ${Math.round($/1000)}s`)}startHealthMonitoring(Q){let $=this.tracked.get(Q);if(!$||$.healthTimer)return;let V=60000;$.healthTimer=setInterval(()=>{this.getContainerHealth(Q).then((W)=>{if(!W.data.healthy)pU.warn(`[CloudContainer] Container ${Q} unhealthy: ${W.data.status}`)}).catch((W)=>{pU.error(`[CloudContainer] Health check failed for ${Q}: ${W.message}`)})},V)}async getContainerHealth(Q){return this.getClient().get(`/containers/${Q}/health`)}getTrackedContainers(){return Array.from(this.tracked.values()).map((Q)=>Q.container)}getTrackedContainer(Q){return this.tracked.get(Q)?.container}isContainerRunning(Q){return this.tracked.get(Q)?.container.status==="running"}getContainerUrl(Q){return this.tracked.get(Q)?.container.load_balancer_url??null}}import{logger as EX,Service as RV}from"@elizaos/core";var TY=1800000,TV=[["gpt-","openai"],["o1","openai"],["o3","openai"],["o4","openai"],["dall-e","openai"],["whisper","openai"],["tts","openai"],["claude-","anthropic"],["gemini-","google"],["llama","meta"],["deepseek","deepseek"],["grok","xai"],["kimi","moonshot"]];function zV(Q){if(Q.includes("/"))return Q.split("/")[0];let $=Q.toLowerCase();for(let[V,W]of TV)if($.startsWith(V))return W;return"unknown"}function MV(Q){if(Q.includes("/"))return Q.split("/").slice(1).join("/");return Q}class JZ extends RV{static serviceType="CLOUD_MODEL_REGISTRY";capabilityDescription="Discovers and caches available AI models from ElizaCloud";models=[];byProvider={};lastFetchedAt=0;fetchPromise=null;constructor(Q){super(Q)}static async start(Q){let $=new JZ(Q);return await $.initialize(),$}async stop(){this.models=[],this.byProvider={},this.lastFetchedAt=0}async initialize(){if(!this.runtime.getService("CLOUD_AUTH")?.isAuthenticated()){EX.info("[CloudModelRegistry] Auth not available, will fetch models on first access");return}await this.fetchModels(),this.validateConfiguredModels()}async fetchModels(){if(this.fetchPromise){await this.fetchPromise;return}this.fetchPromise=this.doFetchModels(),await this.fetchPromise,this.fetchPromise=null}async doFetchModels(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q?.isAuthenticated())return;let W=(await Q.getClient().get("/models")).data??[];this.models=W.map((C)=>({id:C.id,provider:zV(C.id),name:MV(C.id),createdAt:C.created})),this.byProvider={};for(let C of this.models){if(!this.byProvider[C.provider])this.byProvider[C.provider]=[];this.byProvider[C.provider].push(C)}this.lastFetchedAt=Date.now(),EX.info(`[CloudModelRegistry] Loaded ${this.models.length} models from ${Object.keys(this.byProvider).length} providers`)}validateConfiguredModels(){if(this.models.length===0)return;let Q=new Set(this.models.map((W)=>W.id)),$=new Set(this.models.map((W)=>W.name)),V=[{key:"ELIZAOS_CLOUD_SMALL_MODEL",label:"small model"},{key:"ELIZAOS_CLOUD_LARGE_MODEL",label:"large model"},{key:"ELIZAOS_CLOUD_REASONING_SMALL_MODEL",label:"reasoning small model"},{key:"ELIZAOS_CLOUD_REASONING_LARGE_MODEL",label:"reasoning large model"},{key:"ELIZAOS_CLOUD_RESEARCH_MODEL",label:"research model"},{key:"ELIZAOS_CLOUD_EMBEDDING_MODEL",label:"embedding model"},{key:"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL",label:"image description model"},{key:"ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL",label:"image generation model"},{key:"ELIZAOS_CLOUD_TTS_MODEL",label:"TTS model"},{key:"ELIZAOS_CLOUD_TRANSCRIPTION_MODEL",label:"transcription model"}];for(let{key:W,label:C}of V){let F=this.runtime.getSetting(W);if(F&&typeof F==="string"){if(!(Q.has(F)||$.has(F)))EX.warn(`[CloudModelRegistry] Configured ${C} "${F}" not found in available models. It may still work if the gateway supports it, but check your configuration.`)}}}async getAvailableModels(){if(Date.now()-this.lastFetchedAt>TY)await this.fetchModels();return this.models}async getModelsByProvider(){if(Date.now()-this.lastFetchedAt>TY)await this.fetchModels();return this.byProvider}}function qV(){if(typeof process>"u")return{};return process.env}var m0=qV(),PV={name:"elizaOSCloud",description:"ElizaOS Cloud plugin — Multi-model AI generation, container provisioning, agent bridge, and billing management",config:{ELIZAOS_CLOUD_API_KEY:m0.ELIZAOS_CLOUD_API_KEY??null,ELIZAOS_CLOUD_BASE_URL:m0.ELIZAOS_CLOUD_BASE_URL??null,ELIZAOS_CLOUD_ENABLED:m0.ELIZAOS_CLOUD_ENABLED??null,ELIZAOS_CLOUD_SMALL_MODEL:m0.ELIZAOS_CLOUD_SMALL_MODEL??null,ELIZAOS_CLOUD_LARGE_MODEL:m0.ELIZAOS_CLOUD_LARGE_MODEL??null,SMALL_MODEL:m0.SMALL_MODEL??null,LARGE_MODEL:m0.LARGE_MODEL??null,ELIZAOS_CLOUD_REASONING_SMALL_MODEL:m0.ELIZAOS_CLOUD_REASONING_SMALL_MODEL??null,ELIZAOS_CLOUD_REASONING_LARGE_MODEL:m0.ELIZAOS_CLOUD_REASONING_LARGE_MODEL??null,REASONING_SMALL_MODEL:m0.REASONING_SMALL_MODEL??null,REASONING_LARGE_MODEL:m0.REASONING_LARGE_MODEL??null,ELIZAOS_CLOUD_RESEARCH_MODEL:m0.ELIZAOS_CLOUD_RESEARCH_MODEL??null,RESEARCH_MODEL:m0.RESEARCH_MODEL??null,ELIZAOS_CLOUD_EMBEDDING_MODEL:m0.ELIZAOS_CLOUD_EMBEDDING_MODEL??null,ELIZAOS_CLOUD_EMBEDDING_API_KEY:m0.ELIZAOS_CLOUD_EMBEDDING_API_KEY??null,ELIZAOS_CLOUD_EMBEDDING_URL:m0.ELIZAOS_CLOUD_EMBEDDING_URL??null,ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS:m0.ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS??null,ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL:m0.ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL??null,ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS:m0.ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS??null,ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL:m0.ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL??null,ELIZAOS_CLOUD_TTS_MODEL:m0.ELIZAOS_CLOUD_TTS_MODEL??null,ELIZAOS_CLOUD_TRANSCRIPTION_MODEL:m0.ELIZAOS_CLOUD_TRANSCRIPTION_MODEL??null,ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY:m0.ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY??null},async init(Q,$){fX(Q,$)},services:[QZ,JZ,$Z,AZ,YZ],actions:[HX,WX,DX,LX],providers:[SX,zX,FX,PX],models:{[a0.TEXT_EMBEDDING]:LZ,[a0.TEXT_SMALL]:cZ,[a0.TEXT_LARGE]:pZ,[a0.TEXT_REASONING_SMALL]:hZ,[a0.TEXT_REASONING_LARGE]:uZ,[a0.RESEARCH]:wZ,[a0.IMAGE]:xZ,[a0.IMAGE_DESCRIPTION]:NZ,[a0.OBJECT_SMALL]:gZ,[a0.OBJECT_LARGE]:fZ},tests:[{name:"ELIZAOS_CLOUD_plugin_tests",tests:[{name:"ELIZAOS_CLOUD_test_url_and_api_key_validation",fn:async(Q)=>{let $=PU(Q),V=await fetch(`${$}/models`,{headers:{Authorization:`Bearer ${rU(Q)}`}}),W=await V.json();if(BU.log({data:W?.data?.length??"N/A"},"Models Available"),!V.ok)throw Error(`Failed to validate OpenAI API key: ${V.statusText}`)}},{name:"ELIZAOS_CLOUD_test_text_embedding",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_EMBEDDING,{text:"Hello, world!"});BU.log({embedding:$},"embedding")}},{name:"ELIZAOS_CLOUD_test_text_large",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_LARGE,{prompt:"What is the nature of reality in 10 words?"});if($.length===0)throw Error("Failed to generate text");BU.log({text:$},"generated with test_text_large")}},{name:"ELIZAOS_CLOUD_test_text_small",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_SMALL,{prompt:"What is the nature of reality in 10 words?"});if($.length===0)throw Error("Failed to generate text");BU.log({text:$},"generated with test_text_small")}},{name:"ELIZAOS_CLOUD_test_image_generation",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_image_generation");let $=await Q.useModel(a0.IMAGE,{prompt:"A beautiful sunset over a calm ocean",count:1,size:"1024x1024"});BU.log({image:$},"generated with test_image_generation")}},{name:"image-description",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_image_description");let $=await Q.useModel(a0.IMAGE_DESCRIPTION,"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg/537px-Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg");if($&&typeof $==="object"&&"title"in $&&"description"in $)BU.log({result:$},"Image description");else BU.error(`Invalid image description result format: ${JSON.stringify($)}`)}},{name:"ELIZAOS_CLOUD_test_transcription",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_transcription");let V=await(await fetch("https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg")).arrayBuffer(),W=await Q.useModel(a0.TRANSCRIPTION,Buffer.from(new Uint8Array(V)));BU.log({transcription:W},"generated with test_transcription")}},{name:"ELIZAOS_CLOUD_test_text_tokenizer_encode",fn:async(Q)=>{let V=await Q.useModel(a0.TEXT_TOKENIZER_ENCODE,{prompt:"Hello tokenizer encode!",modelType:a0.TEXT_SMALL});if(!Array.isArray(V)||V.length===0)throw Error("Failed to tokenize text: expected non-empty array of tokens");BU.log({tokens:V},"Tokenized output")}},{name:"ELIZAOS_CLOUD_test_text_tokenizer_decode",fn:async(Q)=>{let V=await Q.useModel(a0.TEXT_TOKENIZER_ENCODE,{prompt:"Hello tokenizer decode!",modelType:a0.TEXT_SMALL}),W=await Q.useModel(a0.TEXT_TOKENIZER_DECODE,{tokens:V,modelType:a0.TEXT_SMALL});if(W!=="Hello tokenizer decode!")throw Error(`Decoded text does not match original. Expected "Hello tokenizer decode!", got "${W}"`);BU.log({decodedText:W},"Decoded text")}},{name:"ELIZAOS_CLOUD_test_text_to_speech",fn:async(Q)=>{if(!await yZ(Q,{text:"Hello, this is a test for text-to-speech."}))throw Error("Failed to generate speech");BU.log("Generated speech successfully")}}]}]},kV=PV;export{PV as elizaOSCloudPlugin,kV as default};
|
|
20
|
+
`),values:{healthyContainers:z,unhealthyContainers:A.length-z},data:{reports:A}}}};import{logger as RX}from"@elizaos/core";var CZ="https://www.elizacloud.ai/dashboard/billing",TX=new WeakMap,fY=60000,zX={name:"elizacloud_credits",description:"ElizaCloud credit balance",dynamic:!0,position:91,async get(Q,$,V){let W=Q.getService("CLOUD_AUTH");if(!W?.isAuthenticated())return{text:""};let C=TX.get(Q);if(C&&Date.now()-C.at<fY)return KZ(C.value);let F;try{let{data:A}=await W.getClient().get("/credits/balance");F=A.balance}catch(A){if(RX.warn(`[CloudCredits] Failed to fetch balance: ${A instanceof Error?A.message:A}`),C)return KZ(C.value);return{text:""}}if(TX.set(Q,{value:F,at:Date.now()}),F<1)RX.warn(`[CloudCredits] Low balance: $${F.toFixed(2)}`);return KZ(F)}};function KZ(Q){let $=Q<2,V=Q<0.5,W=`ElizaCloud credits: $${Q.toFixed(2)}`;if(V)W+=` (CRITICAL — top up at ${CZ})`;else if($)W+=` (LOW — top up at ${CZ})`;return{text:W,values:{cloudCredits:Q,cloudCreditsLow:$,cloudCreditsCritical:V,cloudTopUpUrl:CZ}}}var MX=new WeakMap,PX={name:"elizacloud_models",description:"Available AI models from ElizaCloud grouped by provider",dynamic:!0,position:92,async get(Q,$,V){let W=Q.getService("CLOUD_MODEL_REGISTRY");if(!W)return{text:""};let C=MX.get(Q);if(C&&Date.now()-C.at<300000)return qX(C.value);let F=await W.getModelsByProvider();if(Object.keys(F).length===0)return{text:""};return MX.set(Q,{value:F,at:Date.now()}),qX(F)}};function qX(Q){let $=Object.keys(Q).sort(),V=Object.values(Q).reduce((W,C)=>W+C.length,0);return{text:`ElizaCloud: ${V} models (${$.join(", ")})`,values:{cloudModelProviders:$.join(","),cloudModelCount:V}}}import{logger as hU}from"@elizaos/core";import{logger as fO}from"@elizaos/core";function wY(Q){if(typeof process>"u")return;let $=process.env[Q];return $===void 0?void 0:String($)}function u0(Q,$,V){let W=Q.getSetting($);if(W!==void 0&&W!==null)return String(W);return wY($)??V}function tU(){return typeof globalThis<"u"&&typeof globalThis.document<"u"}function kX(Q){return tU()&&!!u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL")}function gU(Q,$=!1){if(tU())return{};let V=$?yY(Q):rU(Q);return V?{Authorization:`Bearer ${V}`}:{}}function PU(Q){let $=u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL");return tU()&&$?$:u0(Q,"ELIZAOS_CLOUD_BASE_URL","https://www.elizacloud.ai/api/v1")}function _X(Q){let $=tU()?u0(Q,"ELIZAOS_CLOUD_BROWSER_EMBEDDING_URL")||u0(Q,"ELIZAOS_CLOUD_BROWSER_BASE_URL"):u0(Q,"ELIZAOS_CLOUD_EMBEDDING_URL");if($)return fO.debug(`[ELIZAOS_CLOUD] Using specific embedding base URL: ${$}`),$;return fO.debug("[ELIZAOS_CLOUD] Falling back to general base URL for embeddings."),PU(Q)}function rU(Q){return u0(Q,"ELIZAOS_CLOUD_API_KEY")}function yY(Q){let $=u0(Q,"ELIZAOS_CLOUD_EMBEDDING_API_KEY");if($)return fO.debug("[ELIZAOS_CLOUD] Using specific embedding API key (present)"),$;return fO.debug("[ELIZAOS_CLOUD] Falling back to general API key for embeddings."),rU(Q)}function wO(Q){return u0(Q,"ELIZAOS_CLOUD_SMALL_MODEL")??u0(Q,"SMALL_MODEL","openai/gpt-5-mini")}function SO(Q){return u0(Q,"ELIZAOS_CLOUD_LARGE_MODEL")??u0(Q,"LARGE_MODEL","anthropic/claude-sonnet-4.5")}function vX(Q){return u0(Q,"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL","gpt-5-mini")}function jX(Q){return u0(Q,"ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL","google/gemini-2.5-flash-image")??"google/gemini-2.5-flash-image"}function BX(Q){return u0(Q,"ELIZAOS_CLOUD_REASONING_SMALL_MODEL")??u0(Q,"REASONING_SMALL_MODEL","deepseek/deepseek-r1")}function xX(Q){return u0(Q,"ELIZAOS_CLOUD_REASONING_LARGE_MODEL")??u0(Q,"REASONING_LARGE_MODEL","anthropic/claude-opus-4.5")}function NX(Q){return u0(Q,"ELIZAOS_CLOUD_RESEARCH_MODEL")??u0(Q,"RESEARCH_MODEL","o3-deep-research")}function gX(Q){let $=u0(Q,"ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY","false");return String($).toLowerCase()==="true"}function fX(Q,$){(async()=>{try{if(!rU($)&&!tU()){hU.warn("ELIZAOS_CLOUD_API_KEY is not set in environment - ElizaOS Cloud functionality will be limited"),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys");return}try{let V=PU($),W=await fetch(`${V}/models`,{headers:{...gU($)}});if(!W.ok)hU.warn(`ElizaOS Cloud API key validation failed: ${W.statusText}`),hU.warn("ElizaOS Cloud functionality will be limited until a valid API key is provided"),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys");else hU.log("ElizaOS Cloud API key validated successfully")}catch(V){let W=V instanceof Error?V.message:String(V);hU.warn(`Error validating ElizaOS Cloud API key: ${W}`),hU.warn("ElizaOS Cloud functionality will be limited until a valid API key is provided")}}catch(V){let W=V?.errors?.map((C)=>C.message).join(", ")||(V instanceof Error?V.message:String(V));hU.warn(`ElizaOS Cloud plugin configuration issue: ${W} - You need to configure the ELIZAOS_CLOUD_API_KEY in your environment variables`),hU.info("Get your API key from https://www.elizacloud.ai/dashboard/api-keys")}})()}import{logger as TU,ModelType as pY,VECTOR_DIMS as wX}from"@elizaos/core";import{EventType as cY}from"@elizaos/core";function yU(Q,$,V,W){let C=Number(W.inputTokens||0),F=Number(W.outputTokens||0),A=Number(W.totalTokens!=null?W.totalTokens:C+F);Q.emitEvent(cY.MODEL_USED,{runtime:Q,source:"elizacloud",type:$,tokens:{prompt:C,completion:F,total:A}})}var yO=100;function hY(Q){return{remainingRequests:parseInt(Q.headers.get("x-ratelimit-remaining-requests")||"",10)||void 0,remainingTokens:parseInt(Q.headers.get("x-ratelimit-remaining-tokens")||"",10)||void 0,limitRequests:parseInt(Q.headers.get("x-ratelimit-limit-requests")||"",10)||void 0,limitTokens:parseInt(Q.headers.get("x-ratelimit-limit-tokens")||"",10)||void 0,resetRequests:Q.headers.get("x-ratelimit-reset-requests")||void 0,resetTokens:Q.headers.get("x-ratelimit-reset-tokens")||void 0,retryAfter:parseInt(Q.headers.get("retry-after")||"",10)||void 0}}function yX(Q){let $=u0(Q,"ELIZAOS_CLOUD_EMBEDDING_MODEL","text-embedding-3-small"),V=Number.parseInt(u0(Q,"ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS","1536")||"1536",10);if(!Object.values(wX).includes(V)){let W=`Invalid embedding dimension: ${V}. Must be one of: ${Object.values(wX).join(", ")}`;throw TU.error(W),Error(W)}return{embeddingModelName:$,embeddingDimension:V}}function aU(Q,$){let V=Array(Q).fill(0);return V[0]=$,V}async function LZ(Q,$){let{embeddingDimension:V}=yX(Q);if($===null)return TU.debug("Creating test embedding for initialization"),aU(V,0.1);let W;if(typeof $==="string")W=$;else if(typeof $==="object"&&$.text)W=$.text;else return TU.warn("Invalid input format for embedding"),aU(V,0.2);if(!W.trim())return TU.warn("Empty text for embedding"),aU(V,0.3);return(await cX(Q,[W]))[0]}async function cX(Q,$){let{embeddingModelName:V,embeddingDimension:W}=yX(Q),C=_X(Q);if(!$||$.length===0)return TU.warn("[BatchEmbeddings] Empty texts array"),[];let F=[],A=Array($.length);for(let z=0;z<$.length;z++){let M=$[z]?.trim();if(M)F.push({text:M,originalIndex:z});else A[z]=aU(W,0.3)}if(F.length===0)return TU.warn("[BatchEmbeddings] All texts were empty"),A;for(let z=0;z<F.length;z+=yO){let M=Math.min(z+yO,F.length),S=F.slice(z,M),R=S.map((L)=>L.text);TU.info(`[BatchEmbeddings] Processing batch ${Math.floor(z/yO)+1}/${Math.ceil(F.length/yO)}: ${S.length} texts`);try{let L=await fetch(`${C}/embeddings`,{method:"POST",headers:{...gU(Q,!0),"Content-Type":"application/json"},body:JSON.stringify({model:V,input:R})}),H=hY(L);if(H.remainingRequests!==void 0&&H.remainingRequests<50)TU.warn(`[BatchEmbeddings] Rate limit: ${H.remainingRequests}/${H.limitRequests} requests remaining`);if(L.status===429){let P=H.retryAfter||30;TU.warn(`[BatchEmbeddings] Rate limited, waiting ${P}s...`),await new Promise((B)=>setTimeout(B,P*1000));let _=await fetch(`${C}/embeddings`,{method:"POST",headers:{...gU(Q,!0),"Content-Type":"application/json"},body:JSON.stringify({model:V,input:R})});if(!_.ok){TU.error(`[BatchEmbeddings] Retry failed: ${_.status}`);for(let B of S)A[B.originalIndex]=aU(W,0.4);continue}let k=await _.json();if(k?.data){for(let B of k.data){let j=S[B.index].originalIndex;A[j]=B.embedding}TU.info(`[BatchEmbeddings] Retry successful for ${S.length} embeddings`)}continue}if(!L.ok){TU.error(`[BatchEmbeddings] API error: ${L.status} - ${L.statusText}`);for(let P of S)A[P.originalIndex]=aU(W,0.4);continue}let q=await L.json();if(!q?.data||!Array.isArray(q.data)){TU.error("[BatchEmbeddings] API returned invalid structure");for(let P of S)A[P.originalIndex]=aU(W,0.5);continue}for(let P of q.data){let _=S[P.index].originalIndex;A[_]=P.embedding}if(q.usage){let P={inputTokens:q.usage.prompt_tokens,outputTokens:0,totalTokens:q.usage.total_tokens};yU(Q,pY.TEXT_EMBEDDING,`batch:${S.length}`,P)}TU.debug(`[BatchEmbeddings] Got ${S.length} embeddings (${W}d), remaining: ${H.remainingRequests??"unknown"}`)}catch(L){let H=L instanceof Error?L.message:String(L);TU.error(`[BatchEmbeddings] Error: ${H}`);for(let q of S)A[q.originalIndex]=aU(W,0.6)}}return A}import{logger as kO,ModelType as dA}from"@elizaos/core";import{logger as vQ}from"@elizaos/core";import{JSONParseError as lA}from"ai";function BZ(){return async({text:Q,error:$})=>{try{if($ instanceof lA){let V=Q.replace(/```json\n|\n```|```/g,"");return JSON.parse(V),V}return null}catch(V){let W=V instanceof Error?V.message:String(V);return vQ.warn(`Failed to repair JSON text: ${W}`),null}}}async function jQ(Q){try{let{Readable:$}=await Promise.resolve().then(() => PY(dO(),1)),V=Q.getReader();return new $({async read(){try{let{done:W,value:C}=await V.read();if(W)this.push(null);else this.push(C)}catch(W){this.destroy(W)}},destroy(W,C){V.cancel().finally(()=>C(W))}})}catch($){let V=$ instanceof Error?$.message:String($);throw vQ.error(`Failed to load node:stream module: ${V}`),Error("Cannot convert stream: node:stream module unavailable. This feature requires a Node.js environment.")}}function BQ(Q){let V=Q.match(/title[:\s]+(.+?)(?:\n|$)/i)?.[1]?.trim()||"Image Analysis",W=Q.replace(/title[:\s]+(.+?)(?:\n|$)/i,"").trim();return{title:V,description:W}}async function xZ(Q,$){let V=$.count||1,W=$.size||"1024x1024",C=$.prompt,F=jX(Q);kO.log(`[ELIZAOS_CLOUD] Using IMAGE model: ${F}`);let A=PU(Q),M={"1024x1024":"1:1","1792x1024":"16:9","1024x1792":"9:16"}[W]||"1:1";try{let S=`${A}/generate-image`,R={prompt:C,numImages:V,aspectRatio:M,model:F},L=await fetch(S,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json"},body:JSON.stringify(R)});if(!L.ok){let _=await L.text();throw Error(`Failed to generate image: ${L.status} ${_}`)}return(await L.json()).images.map((_)=>({url:_.url||_.image}))}catch(S){let R=S instanceof Error?S.message:String(S);throw kO.error(`[ELIZAOS_CLOUD] Image generation error: ${R}`),S}}async function NZ(Q,$){let V,W,C=vX(Q);kO.log(`[ELIZAOS_CLOUD] Using IMAGE_DESCRIPTION model: ${C}`);let F=Number.parseInt(u0(Q,"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS","8192")||"8192",10);if(typeof $==="string")V=$,W="Please analyze this image and provide a title and detailed description.";else V=$.imageUrl,W=$.prompt||"Please analyze this image and provide a title and detailed description.";let A=[{role:"user",content:[{type:"text",text:W},{type:"image_url",image_url:{url:V}}]}],z=PU(Q);try{let M={model:C,messages:A,max_tokens:F},S=null;for(let H=0;H<3;H++){if(S=await fetch(`${z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",...gU(Q)},body:JSON.stringify(M)}),S.status===429&&H<2){let q=(H+1)*2000;kO.warn(`[ELIZAOS_CLOUD] Image analysis rate-limited (429), retrying in ${q/1000}s...`),await new Promise((P)=>setTimeout(P,q));continue}break}if(!S||!S.ok){let H=S?.status??0;if(H===402)throw Error("Eliza Cloud credits exhausted — top up at https://www.elizacloud.ai/dashboard/billing");throw Error(`ElizaOS Cloud API error: ${H}`)}let R=await S.json(),L=R.choices?.[0]?.message?.content;if(R.usage)yU(Q,dA.IMAGE_DESCRIPTION,typeof $==="string"?$:$.prompt||"",{inputTokens:R.usage.prompt_tokens,outputTokens:R.usage.completion_tokens,totalTokens:R.usage.total_tokens});if(!L)return{title:"Failed to analyze image",description:"No response from API"};return BQ(L)}catch(M){let S=M instanceof Error?M.message:String(M);return kO.error(`Error analyzing image: ${S}`),{title:"Failed to analyze image",description:`Error: ${S}`}}}import{logger as IO,ModelType as xQ}from"@elizaos/core";import{generateObject as nA,JSONParseError as mA}from"ai";import{createOpenAI as oA}from"@ai-sdk/openai";function oO(Q){let $=PU(Q),V=rU(Q)??(kX(Q)?"eliza-proxy":void 0);return oA({apiKey:V??"",baseURL:$})}var sA=["o1","o3","o4","deepseek-r1","deepseek-reasoner","claude-opus-4.5","claude-opus-4","gpt-5-mini","gpt-5"];function tA(Q){let $=Q.toLowerCase();return sA.some((V)=>$.includes(V))}async function NQ(Q,$,V,W){let C=oO(Q),F=W(Q);IO.log(`[ELIZAOS_CLOUD] Using ${V} model: ${F}`);let A=tA(F);try{let z=C.chat(F),{object:M,usage:S}=await nA({model:z,output:"no-schema",prompt:$.prompt,...A?{}:{temperature:$.temperature??0},experimental_repairText:BZ()});if(S)yU(Q,V,$.prompt,S);return M}catch(z){if(z instanceof mA){IO.error(`[generateObject] Failed to parse JSON: ${z.message}`);let S=await BZ()({text:z.text,error:z});if(S)try{let R=JSON.parse(S);return IO.info("[generateObject] Successfully repaired JSON."),R}catch(R){let L=R instanceof Error?R.message:String(R);throw IO.error(`[generateObject] Failed to parse repaired JSON: ${L}`),R}else throw IO.error("[generateObject] JSON repair failed."),z}else{let M=z instanceof Error?z.message:String(z);throw IO.error(`[generateObject] Error: ${M}`),z}}}async function gZ(Q,$){return NQ(Q,$,xQ.OBJECT_SMALL,wO)}async function fZ(Q,$){return NQ(Q,$,xQ.OBJECT_LARGE,SO)}import{logger as rA,ModelType as aA}from"@elizaos/core";function eA(Q){return Q.filter(($)=>$.url!==void 0).map(($)=>({url:$.url,title:$.title??"",startIndex:$.start_index??0,endIndex:$.end_index??0}))}function iA(Q){let $=[];for(let V of Q)switch(V.type){case"web_search_call":$.push({id:V.id??"",type:"web_search_call",status:V.status??"completed",action:{type:V.action?.type??"search",query:V.action?.query,url:V.action?.url}});break;case"file_search_call":$.push({id:V.id??"",type:"file_search_call",status:V.status??"completed",query:V.query??"",results:V.results?.map((W)=>({fileId:W.file_id,fileName:W.file_name,score:W.score}))});break;case"code_interpreter_call":$.push({id:V.id??"",type:"code_interpreter_call",status:V.status??"completed",code:V.code??"",output:V.output});break;case"mcp_tool_call":$.push({id:V.id??"",type:"mcp_tool_call",status:V.status??"completed",serverLabel:V.server_label??"",toolName:V.tool_name??"",arguments:V.arguments??{},result:V.result});break;case"message":{let W=V.content??[];$.push({type:"message",content:W.filter((C)=>C.type==="output_text").map((C)=>({type:"output_text",text:C.text??"",annotations:eA(C.annotations??[])}))});break}}return $}async function wZ(Q,$){let V=$.model??NX(Q);rA.log(`[ELIZAOS_CLOUD] Using RESEARCH model: ${V}`);let W=PU(Q),C=$.tools??[{type:"web_search_preview"}],F={model:V,input:$.input,tools:C};if($.instructions)F.instructions=$.instructions;if($.background!==void 0)F.background=$.background;if($.maxToolCalls!==void 0)F.max_tool_calls=$.maxToolCalls;if($.reasoningSummary)F.reasoning={summary:$.reasoningSummary};let A=await fetch(`${W}/responses`,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json"},body:JSON.stringify(F)});if(!A.ok){let L=await A.text();throw Error(`Research API error: ${A.status} ${L}`)}let z=await A.json();if(z.usage)yU(Q,aA.RESEARCH,$.input,{inputTokens:z.usage.input_tokens,outputTokens:z.usage.output_tokens,totalTokens:z.usage.total_tokens});let M=iA(z.output),S="",R=[];for(let L of M)if(L.type==="message"){for(let H of L.content)if(H.type==="output_text")S+=H.text,R.push(...H.annotations)}return{id:z.id,text:S,annotations:R,outputItems:M,status:z.status}}import{logger as _E}from"@elizaos/core";async function yZ(Q,$){let V=u0(Q,"ELIZAOS_CLOUD_TTS_MODEL","gpt-5-mini-tts"),W=u0(Q,"ELIZAOS_CLOUD_TTS_VOICE","nova"),C=u0(Q,"ELIZAOS_CLOUD_TTS_INSTRUCTIONS",""),F=PU(Q),A=$.model||V,z=$.voice||W,M=$.instructions??C,S=$.format||"mp3";try{let R=await fetch(`${F}/audio/speech`,{method:"POST",headers:{...gU(Q),"Content-Type":"application/json",...S==="mp3"?{Accept:"audio/mpeg"}:{}},body:JSON.stringify({model:A,voice:z,input:$.text,format:S,...M&&{instructions:M}})});if(!R.ok){let L=await R.text();throw Error(`ElizaOS Cloud TTS error ${R.status}: ${L}`)}if(!R.body)throw Error("ElizaOS Cloud TTS response body is null");if(!tU())return await jQ(R.body);return R.body}catch(R){let L=R instanceof Error?R.message:String(R);throw Error(`Failed to fetch speech from ElizaOS Cloud TTS: ${L}`)}}import{logger as nO,ModelType as lU}from"@elizaos/core";import{generateText as U$,streamText as O$}from"ai";var Z$=["o1","o3","o4","deepseek-r1","deepseek-reasoner","claude-opus-4.5","claude-opus-4","gpt-5-mini","gpt-5"];function X$(Q){let $=Q.toLowerCase();return Z$.some((V)=>$.includes(V))}function Q$(Q,$){switch($){case lU.TEXT_SMALL:return wO(Q);case lU.TEXT_LARGE:return SO(Q);case lU.TEXT_REASONING_SMALL:return BX(Q);case lU.TEXT_REASONING_LARGE:return xX(Q);default:return SO(Q)}}function Y$(Q,$,V){let{prompt:W,stopSequences:C=[]}=V,F=V.maxTokens??8192,A=oO(Q),z=Q$(Q,$),M=gX(Q),S=A.chat(z),R=X$(z)||$===lU.TEXT_REASONING_SMALL||$===lU.TEXT_REASONING_LARGE;return{generateParams:{model:S,prompt:W,system:Q.character.system??void 0,...R?{}:{stopSequences:C},maxOutputTokens:F,experimental_telemetry:{isEnabled:M}},modelName:z,modelType:$,prompt:W}}function A$(Q,$,V,W){nO.debug(`[ELIZAOS_CLOUD] Streaming text with ${$} model`);let C=O$(V);return{textStream:C.textStream,text:Promise.resolve(C.text),usage:Promise.resolve(C.usage).then((F)=>{if(F){yU(Q,$,W,F);let A=F.inputTokens??0,z=F.outputTokens??0;return{promptTokens:A,completionTokens:z,totalTokens:A+z}}return}),finishReason:Promise.resolve(C.finishReason)}}async function mO(Q,$,V){let{generateParams:W,modelName:C,prompt:F}=Y$(Q,$,V);if(nO.debug(`[ELIZAOS_CLOUD] Generating text with ${$} model: ${C}`),V.stream)return A$(Q,$,W,F);nO.log(`[ELIZAOS_CLOUD] Using ${$} model: ${C}`),nO.log(F);let A=await U$(W);if(A.usage)yU(Q,$,F,A.usage);return A.text}async function cZ(Q,$){return mO(Q,lU.TEXT_SMALL,$)}async function pZ(Q,$){return mO(Q,lU.TEXT_LARGE,$)}async function hZ(Q,$){return mO(Q,lU.TEXT_REASONING_SMALL,$)}async function uZ(Q,$){return mO(Q,lU.TEXT_REASONING_LARGE,$)}import{logger as ZO,Service as KV}from"@elizaos/core";import{logger as $$}from"@elizaos/core";class bZ{baseUrl;apiKey;constructor(Q,$){this.baseUrl=Q.replace(/\/+$/,""),this.apiKey=$}setApiKey(Q){this.apiKey=Q}setBaseUrl(Q){this.baseUrl=Q.replace(/\/+$/,"")}getBaseUrl(){return this.baseUrl}getApiKey(){return this.apiKey}buildWsUrl(Q){return`${this.baseUrl.replace(/^http/,"ws")}${Q}`}async get(Q){return this.request("GET",Q)}async post(Q,$){return this.request("POST",Q,$)}async delete(Q){return this.request("DELETE",Q)}async postUnauthenticated(Q,$){return this.request("POST",Q,$,!0)}async request(Q,$,V,W=!1){let C=`${this.baseUrl}${$}`;$$.debug(`[CloudAPI] ${Q} ${C}`);let F={"Content-Type":"application/json",Accept:"application/json"};if(!W&&this.apiKey)F.Authorization=`Bearer ${this.apiKey}`;let A=await fetch(C,{method:Q,headers:F,...V?{body:JSON.stringify(V)}:{}});return this.handleResponse(A)}async handleResponse(Q){if(!(Q.headers.get("content-type")??"").includes("application/json")){if(!Q.ok)throw new DO(Q.status,{success:!1,error:`HTTP ${Q.status}: ${Q.statusText}`});return{success:!0}}let V=await Q.json();if(!Q.ok){let W=V;throw Q.status===402?new IZ(W):new DO(Q.status,W)}return V}}async function LV(){let Q=await Promise.resolve().then(() => (dZ(),lZ)),$=await Promise.resolve().then(() => (jU(),vU)),V=Q.cpus(),W=[Q.hostname(),Q.platform(),Q.arch(),V[0]?.model??"?",V.length,Q.totalmem()].join(":");return $.createHash("sha256").update(W).digest("hex")}function WV(){if(typeof process>"u")return"web";return{darwin:"macos",win32:"windows",linux:"linux"}[process.platform]??"linux"}class QZ extends KV{static serviceType="CLOUD_AUTH";capabilityDescription="ElizaCloud device authentication and session management";client;credentials=null;constructor(Q){super(Q);this.client=new bZ(qU.baseUrl)}static async start(Q){let $=new QZ(Q);return await $.initialize(),$}async stop(){this.credentials=null}async initialize(){let Q=String(this.runtime.getSetting("ELIZAOS_CLOUD_BASE_URL")??qU.baseUrl);this.client.setBaseUrl(Q);let $=this.runtime.getSetting("ELIZAOS_CLOUD_API_KEY");if($){let W=String($);this.client.setApiKey(W),this.credentials={apiKey:W,userId:String(this.runtime.getSetting("ELIZAOS_CLOUD_USER_ID")??""),organizationId:String(this.runtime.getSetting("ELIZAOS_CLOUD_ORG_ID")??""),authenticatedAt:Date.now()},ZO.info("[CloudAuth] Authenticated with saved API key"),this.validateApiKey(W).then((C)=>{if(!C)ZO.warn("[CloudAuth] Saved API key could not be validated (cloud may be unreachable or key revoked) — model calls will use the key anyway")}).catch(()=>{});return}let V=this.runtime.getSetting("ELIZAOS_CLOUD_ENABLED");if(V==="true"||V==="1")try{await this.authenticateWithDevice()}catch(W){let C=W instanceof Error?W.message:String(W);ZO.warn(`[CloudAuth] Device auth failed (cloud may be unreachable): ${C}`),ZO.info("[CloudAuth] Service will start unauthenticated — cloud features disabled until connectivity is restored")}else ZO.info("[CloudAuth] Cloud not enabled (set ELIZAOS_CLOUD_ENABLED=true)")}async validateApiKey(Q){try{return(await fetch(`${this.client.getBaseUrl()}/models`,{headers:{Authorization:`Bearer ${Q}`},signal:AbortSignal.timeout(1e4)})).ok}catch($){let V=$ instanceof Error?$.message:String($);return ZO.warn(`[CloudAuth] Could not reach cloud API to validate key: ${V}`),!1}}async authenticateWithDevice(){let Q=await LV(),$=WV(),V=process.env.ELIZAOS_CLOUD_APP_VERSION??"2.0.0-alpha",W=await Promise.resolve().then(() => (dZ(),lZ));ZO.info(`[CloudAuth] Authenticating device (platform=${$})`);let C=await this.client.postUnauthenticated("/device-auth",{deviceId:Q,platform:$,appVersion:V,deviceName:W.hostname()});this.credentials={apiKey:C.data.apiKey,userId:C.data.userId,organizationId:C.data.organizationId,authenticatedAt:Date.now()},this.client.setApiKey(C.data.apiKey);let F=C.data.isNew?"New account created":"Authenticated";return ZO.info(`[CloudAuth] ${F} (credits: $${C.data.credits.toFixed(2)})`),this.credentials}isAuthenticated(){return this.credentials!==null}getCredentials(){return this.credentials}getApiKey(){return this.credentials?.apiKey??this.client.getApiKey()}getClient(){return this.client}getUserId(){return this.credentials?.userId}getOrganizationId(){return this.credentials?.organizationId}}import{logger as NU,Service as HV}from"@elizaos/core";class YZ extends HV{static serviceType="CLOUD_BACKUP";capabilityDescription="ElizaCloud agent state backup and restore";authService;autoBackups=new Map;maxSnapshots=qU.backup.maxSnapshots;backupIntervalMs=qU.backup.autoBackupIntervalMs;static async start(Q){let $=new YZ(Q);return await $.initialize(),$}async stop(){for(let[,Q]of this.autoBackups)clearInterval(Q.timer);this.autoBackups.clear(),NU.info("[CloudBackup] Service stopped")}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){NU.debug("[CloudBackup] CloudAuthService not available");return}this.authService=Q,NU.info("[CloudBackup] Service initialized")}async createSnapshot(Q,$="manual",V){let C=await this.authService.getClient().post(`/agent-state/${Q}/snapshot`,{snapshotType:$,metadata:V});NU.info(`[CloudBackup] Created ${$} snapshot for container ${Q} (id=${C.data.id}, size=${DV(C.data.sizeBytes)})`);let F=this.autoBackups.get(Q);if(F)F.lastBackupAt=Date.now();return C.data}async listSnapshots(Q){return(await this.authService.getClient().get(`/agent-state/${Q}/snapshots`)).data}async restoreSnapshot(Q,$){await this.authService.getClient().post(`/agent-state/${Q}/restore`,{snapshotId:$}),NU.info(`[CloudBackup] Restored snapshot ${$} for container ${Q}`)}async getLatestSnapshot(Q){let $=await this.listSnapshots(Q);if($.length===0)return null;return $.sort((V,W)=>new Date(W.created_at).getTime()-new Date(V.created_at).getTime()),$[0]}scheduleAutoBackup(Q,$){if(this.autoBackups.has(Q)){NU.debug(`[CloudBackup] Auto-backup already scheduled for ${Q}`);return}let V=$??this.backupIntervalMs,W=setInterval(()=>{NU.debug(`[CloudBackup] Running auto-backup for container ${Q}`),this.createSnapshot(Q,"auto",{trigger:"scheduled",scheduledIntervalMs:V}).then(()=>this.pruneSnapshots(Q)).catch((C)=>{NU.error(`[CloudBackup] Auto-backup failed for ${Q}: ${C.message}`)})},V);this.autoBackups.set(Q,{containerId:Q,timer:W,lastBackupAt:null}),NU.info(`[CloudBackup] Scheduled auto-backup for ${Q} every ${Math.round(V/60000)} minutes`)}cancelAutoBackup(Q){let $=this.autoBackups.get(Q);if(!$)return;clearInterval($.timer),this.autoBackups.delete(Q),NU.info(`[CloudBackup] Cancelled auto-backup for ${Q}`)}async createPreEvictionSnapshot(Q){return NU.info(`[CloudBackup] Creating pre-eviction snapshot for ${Q}`),this.createSnapshot(Q,"pre-eviction",{trigger:"billing-eviction",createdAt:new Date().toISOString()})}async pruneSnapshots(Q){let W=(await this.listSnapshots(Q)).filter((F)=>F.snapshotType==="auto").sort((F,A)=>new Date(A.created_at).getTime()-new Date(F.created_at).getTime()).slice(this.maxSnapshots);if(W.length===0)return;let C=this.authService.getClient();for(let F of W)await C.delete(`/agent-state/${Q}/snapshots/${F.id}`),NU.debug(`[CloudBackup] Pruned old auto snapshot ${F.id} for ${Q}`);NU.info(`[CloudBackup] Pruned ${W.length} old auto snapshot(s) for ${Q}`)}isAutoBackupScheduled(Q){return this.autoBackups.has(Q)}getLastBackupTime(Q){return this.autoBackups.get(Q)?.lastBackupAt??null}}function DV(Q){if(Q<1024)return`${Q} B`;if(Q<1048576)return`${(Q/1024).toFixed(1)} KB`;if(Q<1073741824)return`${(Q/1048576).toFixed(1)} MB`;return`${(Q/1073741824).toFixed(1)} GB`}import{logger as cU,Service as SV}from"@elizaos/core";import{WebSocket as VX}from"undici";class AZ extends SV{static serviceType="CLOUD_BRIDGE";capabilityDescription="WebSocket bridge to cloud-hosted ElizaOS agents";authService;bridgeConfig=qU.bridge;connections=new Map;static async start(Q){let $=new AZ(Q);return await $.initialize(),$}async stop(){for(let[Q]of this.connections)await this.disconnect(Q);cU.info("[CloudBridge] Service stopped")}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){cU.debug("[CloudBridge] CloudAuthService not available");return}this.authService=Q,cU.info("[CloudBridge] Service initialized")}async connect(Q){if(this.connections.has(Q)){let $=this.connections.get(Q);if($.state==="connected"||$.state==="connecting"){cU.debug(`[CloudBridge] Already connected/connecting to ${Q}`);return}}await this.establishConnection(Q,0)}async disconnect(Q){let $=this.connections.get(Q);if(!$)return;if($.heartbeatTimer)clearInterval($.heartbeatTimer);if($.reconnectTimer)clearTimeout($.reconnectTimer);for(let[,V]of $.pendingRequests)clearTimeout(V.timeout),V.reject(Error("Bridge disconnected"));if($.pendingRequests.clear(),$.ws.readyState===VX.OPEN||$.ws.readyState===VX.CONNECTING)$.ws.close(1000,"Client disconnect");this.connections.delete(Q),cU.info(`[CloudBridge] Disconnected from ${Q}`)}async establishConnection(Q,$){let V=this.authService.getClient(),W=this.authService.getApiKey(),C=V.buildWsUrl(`/agent-bridge/${Q}`),F=W?`${C}?token=${encodeURIComponent(W)}`:C,A={ws:new VX(F),state:"connecting",connectedAt:null,lastHeartbeat:null,reconnectAttempts:$,heartbeatTimer:null,reconnectTimer:null,handlers:this.connections.get(Q)?.handlers??new Set,pendingRequests:new Map,nextRequestId:1};this.connections.set(Q,A),A.ws.addEventListener("open",()=>{A.state="connected",A.connectedAt=Date.now(),A.reconnectAttempts=0,cU.info(`[CloudBridge] Connected to agent ${Q}`),A.heartbeatTimer=setInterval(()=>{this.sendHeartbeat(Q)},this.bridgeConfig.heartbeatIntervalMs)}),A.ws.addEventListener("message",(z)=>{let M=z.data,S=typeof M==="string"?M:M instanceof Buffer?M.toString("utf-8"):String(M),R=JSON.parse(S);if(R.method==="heartbeat.ack"){A.lastHeartbeat=Date.now();return}if(R.id!==void 0&&!R.method){let L=A.pendingRequests.get(R.id);if(L){if(clearTimeout(L.timeout),A.pendingRequests.delete(R.id),R.error)L.reject(Error(R.error.message));else L.resolve(R.result);return}}for(let L of A.handlers)L(R)}),A.ws.addEventListener("close",(z)=>{if(A.state="disconnected",A.heartbeatTimer)clearInterval(A.heartbeatTimer);if(z.code===1000){cU.info(`[CloudBridge] Clean disconnect from ${Q}`);return}cU.warn(`[CloudBridge] Connection lost to ${Q} (code=${z.code}, reason=${z.reason})`),this.scheduleReconnect(Q,A.reconnectAttempts+1)}),A.ws.addEventListener("error",()=>{cU.error(`[CloudBridge] WebSocket error for ${Q}`)})}scheduleReconnect(Q,$){if($>this.bridgeConfig.maxReconnectAttempts){cU.error(`[CloudBridge] Max reconnect attempts (${this.bridgeConfig.maxReconnectAttempts}) reached for ${Q}`),this.connections.delete(Q);return}let V=this.bridgeConfig.reconnectIntervalMs,W=Math.min(V*2**Math.min($,5),120000),C=Math.floor(Math.random()*1000);cU.info(`[CloudBridge] Reconnecting to ${Q} in ${Math.round((W+C)/1000)}s (attempt ${$})`);let F=this.connections.get(Q);if(F)F.state="reconnecting",F.reconnectTimer=setTimeout(()=>{this.establishConnection(Q,$)},W+C)}sendHeartbeat(Q){let $=this.connections.get(Q);if(!$||$.state!=="connected")return;let V={jsonrpc:"2.0",method:"heartbeat",params:{timestamp:Date.now()}};$.ws.send(JSON.stringify(V))}async sendRequest(Q,$,V,W=60000){let C=this.connections.get(Q);if(!C||C.state!=="connected")throw Error(`Not connected to container ${Q}`);let F=C.nextRequestId++,A={jsonrpc:"2.0",id:F,method:$,params:V};return new Promise((z,M)=>{let S=setTimeout(()=>{C.pendingRequests.delete(F),M(Error(`Request ${$} timed out after ${W}ms`))},W);C.pendingRequests.set(F,{resolve:z,reject:M,timeout:S}),C.ws.send(JSON.stringify(A))})}sendNotification(Q,$,V){let W=this.connections.get(Q);if(!W||W.state!=="connected")throw Error(`Not connected to container ${Q}`);let C={jsonrpc:"2.0",method:$,params:V};W.ws.send(JSON.stringify(C))}async sendChatMessage(Q,$,V,W){return await this.sendRequest(Q,"message.send",{text:$,roomId:V,metadata:W})}async getAgentStatus(Q){return await this.sendRequest(Q,"status.get",{})}async updateAgentConfig(Q,$){await this.sendRequest(Q,"config.update",$)}onMessage(Q,$){let V=this.connections.get(Q);if(!V)V={ws:null,state:"disconnected",connectedAt:null,lastHeartbeat:null,reconnectAttempts:0,heartbeatTimer:null,reconnectTimer:null,handlers:new Set,pendingRequests:new Map,nextRequestId:1},this.connections.set(Q,V);return V.handlers.add($),()=>{V.handlers.delete($)}}getConnectionState(Q){return this.connections.get(Q)?.state??"disconnected"}getConnectionInfo(Q){let $=this.connections.get(Q);if(!$)return null;return{containerId:Q,state:$.state,connectedAt:$.connectedAt,lastHeartbeat:$.lastHeartbeat,reconnectAttempts:$.reconnectAttempts}}getConnectedContainerIds(){let Q=[];for(let[$,V]of this.connections)if(V.state==="connected")Q.push($);return Q}}import{logger as pU,Service as FV}from"@elizaos/core";class $Z extends FV{static serviceType="CLOUD_CONTAINER";capabilityDescription="ElizaCloud container provisioning and lifecycle management";authService;containerDefaults=qU.container;tracked=new Map;static async start(Q){let $=new $Z(Q);return await $.initialize(),$}async stop(){for(let[,Q]of this.tracked){if(Q.pollingTimer)clearTimeout(Q.pollingTimer);if(Q.healthTimer)clearInterval(Q.healthTimer)}this.tracked.clear()}async initialize(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q){pU.debug("[CloudContainer] CloudAuthService not available, container operations will fail");return}if(this.authService=Q,this.authService.isAuthenticated()){let $=await this.listContainers();for(let V of $){if(this.tracked.set(V.id,{container:V,pollingTimer:null,healthTimer:null}),V.status==="pending"||V.status==="building"||V.status==="deploying")this.startPolling(V.id);if(V.status==="running")this.startHealthMonitoring(V.id)}pU.info(`[CloudContainer] Loaded ${$.length} existing container(s)`)}}getClient(){return this.authService.getClient()}async createContainer(Q){let $=this.getClient(),V=this.containerDefaults,W={name:Q.name,project_name:Q.project_name,description:Q.description,port:Q.port??V.defaultPort,desired_count:Q.desired_count??1,cpu:Q.cpu??V.defaultCpu,memory:Q.memory??V.defaultMemory,environment_vars:Q.environment_vars??{},health_check_path:Q.health_check_path??"/health",ecr_image_uri:Q.ecr_image_uri,ecr_repository_uri:Q.ecr_repository_uri,image_tag:Q.image_tag,architecture:Q.architecture??V.defaultArchitecture},C=await $.post("/containers",W);return this.tracked.set(C.data.id,{container:C.data,pollingTimer:null,healthTimer:null}),this.startPolling(C.data.id),pU.info(`[CloudContainer] Created container "${Q.name}" (id=${C.data.id}, stack=${C.stackName})`),C}async listContainers(){return(await this.getClient().get("/containers")).data}async getContainer(Q){let V=await this.getClient().get(`/containers/${Q}`),W=this.tracked.get(Q);if(W)W.container=V.data;return V.data}async deleteContainer(Q){await this.getClient().delete(`/containers/${Q}`);let V=this.tracked.get(Q);if(V){if(V.pollingTimer)clearTimeout(V.pollingTimer);if(V.healthTimer)clearInterval(V.healthTimer);this.tracked.delete(Q)}pU.info(`[CloudContainer] Deleted container ${Q}`)}startPolling(Q){let $=this.tracked.get(Q);if(!$)return;let V=0,W=120,C=5000,F=30000,A=async()=>{if(V++,V>W){pU.error(`[CloudContainer] Polling timed out for container ${Q} after ${W} attempts`);return}let z=await this.getContainer(Q),M=z.status;if(pU.debug(`[CloudContainer] Poll #${V} for ${Q}: status=${M}`),M==="running"){pU.info(`[CloudContainer] Container ${Q} is now running at ${z.load_balancer_url}`),this.startHealthMonitoring(Q);return}if(M==="failed"||M==="stopped"||M==="suspended"){if(pU.warn(`[CloudContainer] Container ${Q} reached terminal state: ${M}`),z.error_message)pU.error(`[CloudContainer] Error: ${z.error_message}`);return}let S=Math.min(C*2**Math.min(V-1,3),F);$.pollingTimer=setTimeout(A,S)};$.pollingTimer=setTimeout(A,C)}async waitForDeployment(Q,$=900000){let V=Date.now()+$,W=5000,C=30000;while(Date.now()<V){let F=await this.getContainer(Q);if(F.status==="running")return F;if(F.status==="failed")throw Error(`Container deployment failed: ${F.error_message??"unknown error"}`);if(F.status==="stopped"||F.status==="suspended")throw Error(`Container reached terminal state: ${F.status}`);await new Promise((A)=>setTimeout(A,W)),W=Math.min(W*1.5,C)}throw Error(`Container deployment timed out after ${Math.round($/1000)}s`)}startHealthMonitoring(Q){let $=this.tracked.get(Q);if(!$||$.healthTimer)return;let V=60000;$.healthTimer=setInterval(()=>{this.getContainerHealth(Q).then((W)=>{if(!W.data.healthy)pU.warn(`[CloudContainer] Container ${Q} unhealthy: ${W.data.status}`)}).catch((W)=>{pU.error(`[CloudContainer] Health check failed for ${Q}: ${W.message}`)})},V)}async getContainerHealth(Q){return this.getClient().get(`/containers/${Q}/health`)}getTrackedContainers(){return Array.from(this.tracked.values()).map((Q)=>Q.container)}getTrackedContainer(Q){return this.tracked.get(Q)?.container}isContainerRunning(Q){return this.tracked.get(Q)?.container.status==="running"}getContainerUrl(Q){return this.tracked.get(Q)?.container.load_balancer_url??null}}import{logger as EX,Service as RV}from"@elizaos/core";var TY=1800000,TV=[["gpt-","openai"],["o1","openai"],["o3","openai"],["o4","openai"],["dall-e","openai"],["whisper","openai"],["tts","openai"],["claude-","anthropic"],["gemini-","google"],["llama","meta"],["deepseek","deepseek"],["grok","xai"],["kimi","moonshot"]];function zV(Q){if(Q.includes("/"))return Q.split("/")[0];let $=Q.toLowerCase();for(let[V,W]of TV)if($.startsWith(V))return W;return"unknown"}function MV(Q){if(Q.includes("/"))return Q.split("/").slice(1).join("/");return Q}class JZ extends RV{static serviceType="CLOUD_MODEL_REGISTRY";capabilityDescription="Discovers and caches available AI models from ElizaCloud";models=[];byProvider={};lastFetchedAt=0;fetchPromise=null;constructor(Q){super(Q)}static async start(Q){let $=new JZ(Q);return await $.initialize(),$}async stop(){this.models=[],this.byProvider={},this.lastFetchedAt=0}async initialize(){if(!this.runtime.getService("CLOUD_AUTH")?.isAuthenticated()){EX.info("[CloudModelRegistry] Auth not available, will fetch models on first access");return}await this.fetchModels(),this.validateConfiguredModels()}async fetchModels(){if(this.fetchPromise){await this.fetchPromise;return}this.fetchPromise=this.doFetchModels(),await this.fetchPromise,this.fetchPromise=null}async doFetchModels(){let Q=this.runtime.getService("CLOUD_AUTH");if(!Q?.isAuthenticated())return;let W=(await Q.getClient().get("/models")).data??[];this.models=W.map((C)=>({id:C.id,provider:zV(C.id),name:MV(C.id),createdAt:C.created})),this.byProvider={};for(let C of this.models){if(!this.byProvider[C.provider])this.byProvider[C.provider]=[];this.byProvider[C.provider].push(C)}this.lastFetchedAt=Date.now(),EX.info(`[CloudModelRegistry] Loaded ${this.models.length} models from ${Object.keys(this.byProvider).length} providers`)}validateConfiguredModels(){if(this.models.length===0)return;let Q=new Set(this.models.map((W)=>W.id)),$=new Set(this.models.map((W)=>W.name)),V=[{key:"ELIZAOS_CLOUD_SMALL_MODEL",label:"small model"},{key:"ELIZAOS_CLOUD_LARGE_MODEL",label:"large model"},{key:"ELIZAOS_CLOUD_REASONING_SMALL_MODEL",label:"reasoning small model"},{key:"ELIZAOS_CLOUD_REASONING_LARGE_MODEL",label:"reasoning large model"},{key:"ELIZAOS_CLOUD_RESEARCH_MODEL",label:"research model"},{key:"ELIZAOS_CLOUD_EMBEDDING_MODEL",label:"embedding model"},{key:"ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL",label:"image description model"},{key:"ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL",label:"image generation model"},{key:"ELIZAOS_CLOUD_TTS_MODEL",label:"TTS model"},{key:"ELIZAOS_CLOUD_TRANSCRIPTION_MODEL",label:"transcription model"}];for(let{key:W,label:C}of V){let F=this.runtime.getSetting(W);if(F&&typeof F==="string"){if(!(Q.has(F)||$.has(F)))EX.warn(`[CloudModelRegistry] Configured ${C} "${F}" not found in available models. It may still work if the gateway supports it, but check your configuration.`)}}}async getAvailableModels(){if(Date.now()-this.lastFetchedAt>TY)await this.fetchModels();return this.models}async getModelsByProvider(){if(Date.now()-this.lastFetchedAt>TY)await this.fetchModels();return this.byProvider}}function qV(){if(typeof process>"u")return{};return process.env}var m0=qV(),PV={name:"elizaOSCloud",description:"ElizaOS Cloud plugin — Multi-model AI generation, container provisioning, agent bridge, and billing management",config:{ELIZAOS_CLOUD_API_KEY:m0.ELIZAOS_CLOUD_API_KEY??null,ELIZAOS_CLOUD_BASE_URL:m0.ELIZAOS_CLOUD_BASE_URL??null,ELIZAOS_CLOUD_ENABLED:m0.ELIZAOS_CLOUD_ENABLED??null,ELIZAOS_CLOUD_SMALL_MODEL:m0.ELIZAOS_CLOUD_SMALL_MODEL??null,ELIZAOS_CLOUD_LARGE_MODEL:m0.ELIZAOS_CLOUD_LARGE_MODEL??null,SMALL_MODEL:m0.SMALL_MODEL??null,LARGE_MODEL:m0.LARGE_MODEL??null,ELIZAOS_CLOUD_REASONING_SMALL_MODEL:m0.ELIZAOS_CLOUD_REASONING_SMALL_MODEL??null,ELIZAOS_CLOUD_REASONING_LARGE_MODEL:m0.ELIZAOS_CLOUD_REASONING_LARGE_MODEL??null,REASONING_SMALL_MODEL:m0.REASONING_SMALL_MODEL??null,REASONING_LARGE_MODEL:m0.REASONING_LARGE_MODEL??null,ELIZAOS_CLOUD_RESEARCH_MODEL:m0.ELIZAOS_CLOUD_RESEARCH_MODEL??null,RESEARCH_MODEL:m0.RESEARCH_MODEL??null,ELIZAOS_CLOUD_EMBEDDING_MODEL:m0.ELIZAOS_CLOUD_EMBEDDING_MODEL??null,ELIZAOS_CLOUD_EMBEDDING_API_KEY:m0.ELIZAOS_CLOUD_EMBEDDING_API_KEY??null,ELIZAOS_CLOUD_EMBEDDING_URL:m0.ELIZAOS_CLOUD_EMBEDDING_URL??null,ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS:m0.ELIZAOS_CLOUD_EMBEDDING_DIMENSIONS??null,ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL:m0.ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MODEL??null,ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS:m0.ELIZAOS_CLOUD_IMAGE_DESCRIPTION_MAX_TOKENS??null,ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL:m0.ELIZAOS_CLOUD_IMAGE_GENERATION_MODEL??null,ELIZAOS_CLOUD_TTS_MODEL:m0.ELIZAOS_CLOUD_TTS_MODEL??null,ELIZAOS_CLOUD_TRANSCRIPTION_MODEL:m0.ELIZAOS_CLOUD_TRANSCRIPTION_MODEL??null,ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY:m0.ELIZAOS_CLOUD_EXPERIMENTAL_TELEMETRY??null},async init(Q,$){fX(Q,$)},services:[QZ,JZ,$Z,AZ,YZ],actions:[HX,WX,DX,LX],providers:[SX,zX,FX,PX],models:{[a0.TEXT_EMBEDDING]:LZ,[a0.TEXT_SMALL]:cZ,[a0.TEXT_LARGE]:pZ,[a0.TEXT_REASONING_SMALL]:hZ,[a0.TEXT_REASONING_LARGE]:uZ,[a0.RESEARCH]:wZ,[a0.IMAGE]:xZ,[a0.IMAGE_DESCRIPTION]:NZ,[a0.OBJECT_SMALL]:gZ,[a0.OBJECT_LARGE]:fZ},tests:[{name:"ELIZAOS_CLOUD_plugin_tests",tests:[{name:"ELIZAOS_CLOUD_test_url_and_api_key_validation",fn:async(Q)=>{let $=PU(Q),V=await fetch(`${$}/models`,{headers:{Authorization:`Bearer ${rU(Q)}`}}),W=await V.json();if(BU.log({data:W?.data?.length??"N/A"},"Models Available"),!V.ok)throw Error(`Failed to validate OpenAI API key: ${V.statusText}`)}},{name:"ELIZAOS_CLOUD_test_text_embedding",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_EMBEDDING,{text:"Hello, world!"});BU.log({embedding:$},"embedding")}},{name:"ELIZAOS_CLOUD_test_text_large",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_LARGE,{prompt:"What is the nature of reality in 10 words?"});if($.length===0)throw Error("Failed to generate text");BU.log({text:$},"generated with test_text_large")}},{name:"ELIZAOS_CLOUD_test_text_small",fn:async(Q)=>{let $=await Q.useModel(a0.TEXT_SMALL,{prompt:"What is the nature of reality in 10 words?"});if($.length===0)throw Error("Failed to generate text");BU.log({text:$},"generated with test_text_small")}},{name:"ELIZAOS_CLOUD_test_image_generation",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_image_generation");let $=await Q.useModel(a0.IMAGE,{prompt:"A beautiful sunset over a calm ocean",count:1,size:"1024x1024"});BU.log({image:$},"generated with test_image_generation")}},{name:"image-description",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_image_description");let $=await Q.useModel(a0.IMAGE_DESCRIPTION,"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg/537px-Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg");if($&&typeof $==="object"&&"title"in $&&"description"in $)BU.log({result:$},"Image description");else BU.error(`Invalid image description result format: ${JSON.stringify($)}`)}},{name:"ELIZAOS_CLOUD_test_transcription",fn:async(Q)=>{BU.log("ELIZAOS_CLOUD_test_transcription");let V=await(await fetch("https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg")).arrayBuffer(),W=await Q.useModel(a0.TRANSCRIPTION,Buffer.from(new Uint8Array(V)));BU.log({transcription:W},"generated with test_transcription")}},{name:"ELIZAOS_CLOUD_test_text_tokenizer_encode",fn:async(Q)=>{let V=await Q.useModel(a0.TEXT_TOKENIZER_ENCODE,{prompt:"Hello tokenizer encode!",modelType:a0.TEXT_SMALL});if(!Array.isArray(V)||V.length===0)throw Error("Failed to tokenize text: expected non-empty array of tokens");BU.log({tokens:V},"Tokenized output")}},{name:"ELIZAOS_CLOUD_test_text_tokenizer_decode",fn:async(Q)=>{let V=await Q.useModel(a0.TEXT_TOKENIZER_ENCODE,{prompt:"Hello tokenizer decode!",modelType:a0.TEXT_SMALL}),W=await Q.useModel(a0.TEXT_TOKENIZER_DECODE,{tokens:V,modelType:a0.TEXT_SMALL});if(W!=="Hello tokenizer decode!")throw Error(`Decoded text does not match original. Expected "Hello tokenizer decode!", got "${W}"`);BU.log({decodedText:W},"Decoded text")}},{name:"ELIZAOS_CLOUD_test_text_to_speech",fn:async(Q)=>{if(!await yZ(Q,{text:"Hello, this is a test for text-to-speech."}))throw Error("Failed to generate speech");BU.log("Generated speech successfully")}}]}]},kV=PV;export{PV as elizaOSCloudPlugin,kV as default};
|
|
21
21
|
|
|
22
|
-
//# debugId=
|
|
22
|
+
//# debugId=1C4EBCC858D786A564756E2164756E21
|