@elizaos/core 2.0.0-alpha.8 → 2.0.0-alpha.9

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.
@@ -724,7 +724,7 @@ ${Z.map((w)=>`- ${w}`).join(`
724
724
 
725
725
  `)}
726
726
 
727
- ${$}`}let O={prompt:K,maxTokens:q?.maxTokens,minTokens:q?.minTokens,temperature:q?.temperature,topP:q?.topP,topK:q?.topK,minP:q?.minP,seed:q?.seed,repetitionPenalty:q?.repetitionPenalty,frequencyPenalty:q?.frequencyPenalty,presencePenalty:q?.presencePenalty,stopSequences:q?.stopSequences,user:q?.user!==void 0?q.user:this.character?.name,responseFormat:q?.responseFormat};return{text:await this.useModel(P,O)}}registerEvent($,q){if(!this.events[$])this.events[$]=[];this.events[$].push(q)}getEvent($){return this.events[$]}async emitEvent($,q){let _=Array.isArray($)?$:[$];for(let P of _){let K=this.events[P];if(!K)continue;let O={runtime:this,source:"runtime"};if(typeof q==="object"&&q&&q!==null){let Y=q;O={...Y,runtime:this,source:Y.source||"runtime"}}await Promise.all(K.map((Y)=>Y(O)))}}async ensureEmbeddingDimension(){if(!this.adapter)throw Error("Database adapter not initialized before ensureEmbeddingDimension");if(!this.getModel(A6.TEXT_EMBEDDING))throw Error("No TEXT_EMBEDDING model registered");let $=this.getSetting("EMBEDDING_DIMENSION"),q=Number($),_=q>0,P=_?q:(await this.useModel(A6.TEXT_EMBEDDING,{text:""}))?.length;if(!P)throw Error("Invalid embedding dimension");await this.adapter.ensureEmbeddingDimension(P),this.logger.debug({src:"agent",agentId:this.agentId,dimension:P},_?"Embedding dimension set from config":"Embedding dimension set via API call")}registerTaskWorker($){if(this.taskWorkers.has($.name))this.logger.warn({src:"agent",agentId:this.agentId,task:$.name},"Task worker already registered, overwriting");this.taskWorkers.set($.name,$)}getTaskWorker($){return this.taskWorkers.get($)}get db(){return this.adapter.db}async init(){await this.adapter.init()}async close(){if(this.adapter)await this.adapter.close()}async getAgent($){return await this.adapter.getAgent($)}async getAgents(){return await this.adapter.getAgents()}async createAgent($){return await this.adapter.createAgent($)}async updateAgent($,q){return await this.adapter.updateAgent($,q)}async deleteAgent($){return await this.adapter.deleteAgent($)}async ensureAgentExists($){if(!$.id)throw Error("Agent id is required");let q=await this.adapter.getAgent($.id);if(q){let K={...q.settings,...$.settings},O=typeof q.settings?.secrets==="object"||typeof $.settings?.secrets==="object"?{...typeof q.settings?.secrets==="object"?q.settings.secrets:{},...typeof $.settings?.secrets==="object"?$.settings.secrets:{}}:void 0;if(O)K.secrets=O;let Y={...q,...$,settings:K,id:$.id,updatedAt:Date.now()};await this.adapter.updateAgent($.id,Y);let v=await this.adapter.getAgent($.id);if(!v)throw Error(`Failed to retrieve agent after update: ${$.id}`);return this.logger.debug({src:"agent",agentId:$.id},"Agent updated on restart"),v}let _={...$,id:$.id};if(!await this.adapter.createAgent(_))throw Error(`Failed to create agent: ${$.id}`);return this.logger.debug({src:"agent",agentId:$.id},"Agent created"),_}async getEntityById($){let q=await this.adapter.getEntitiesByIds([$]);if(!q?.length)return null;return q[0]}async getEntitiesByIds($){return await this.adapter.getEntitiesByIds($)}async getEntitiesForRoom($,q){return await this.adapter.getEntitiesForRoom($,q)}async createEntity($){if(!$.agentId)$.agentId=this.agentId;return await this.createEntities([$])}async ensureEntity($){if(!$.id)return null;if(!await this.createEntity($))return null;return $}async createEntities($){return $.forEach((q)=>{q.agentId=this.agentId}),await this.adapter.createEntities($)}async updateEntity($){await this.adapter.updateEntity($)}async getComponent($,q,_,P){return await this.adapter.getComponent($,q,_,P)}async getComponents($,q,_){return await this.adapter.getComponents($,q,_)}async createComponent($){return await this.adapter.createComponent($)}async updateComponent($){await this.adapter.updateComponent($)}async deleteComponent($){await this.adapter.deleteComponent($)}async addEmbeddingToMemory($){if($.embedding)return $;let q=$.content.text;if(!q)throw Error("Cannot generate embedding: Memory content is empty");try{$.embedding=await this.useModel(A6.TEXT_EMBEDDING,{text:q})}catch(_){this.logger.error({src:"agent",agentId:this.agentId,error:_ instanceof Error?_.message:String(_)},"Embedding generation failed"),$.embedding=await this.useModel(A6.TEXT_EMBEDDING,{text:""})}return $}async queueEmbeddingGeneration($,q){if(q=q||"normal",!$)return;if($.embedding)return;if(!$.content?.text)return;await this.emitEvent("EMBEDDING_GENERATION_REQUESTED",{runtime:this,memory:$,priority:q,source:"runtime",retryCount:0,maxRetries:3,runId:this.getCurrentRunId()})}async getMemories($){return await this.adapter.getMemories($)}async getAllMemories(){let $=["memories","messages","facts","documents"],q=[];for(let _ of $)try{let P=await this.adapter.getMemories({agentId:this.agentId,tableName:_,count:1e4});q.push(...P)}catch(P){this.logger.debug({src:"agent",agentId:this.agentId,tableName:_,error:P instanceof Error?P.message:String(P)},"Failed to get memories")}return q}async getMemoryById($){return await this.adapter.getMemoryById($)}async getMemoriesByIds($,q){return await this.adapter.getMemoriesByIds($,q)}async getMemoriesByRoomIds($){return await this.adapter.getMemoriesByRoomIds($)}async getCachedEmbeddings($){return await this.adapter.getCachedEmbeddings($)}async log($){await this.adapter.log($)}async searchMemories($){let q=await this.adapter.searchMemories($);if($.query)return await this.rerankMemories($.query,q);return q}async rerankMemories($,q){let _=q.map((O)=>({title:O.id,content:O.content.text}));return new CZ(_).search($,q.length).map((O)=>q[O.index])}async createMemory($,q,_){if(_!==void 0)$.unique=_;return await this.adapter.createMemory($,q,_)}async updateMemory($){return await this.adapter.updateMemory($)}async deleteMemory($){await this.adapter.deleteMemory($)}async deleteManyMemories($){await this.adapter.deleteManyMemories($)}async clearAllAgentMemories(){this.logger.info({src:"agent",agentId:this.agentId},"Clearing all memories");let q=(await this.getAllMemories()).map((_)=>_.id).filter((_)=>_!==void 0);if(q.length===0){this.logger.debug({src:"agent",agentId:this.agentId},"No memories to delete");return}await this.adapter.deleteManyMemories(q),this.logger.info({src:"agent",agentId:this.agentId,count:q.length},"Memories cleared")}async deleteAllMemories($,q){await this.adapter.deleteAllMemories($,q)}async countMemories($,q,_){return await this.adapter.countMemories($,q,_)}async getLogs($){return await this.adapter.getLogs($)}async deleteLog($){await this.adapter.deleteLog($)}async createWorld($){return await this.adapter.createWorld($)}async getWorld($){return await this.adapter.getWorld($)}async removeWorld($){await this.adapter.removeWorld($)}async getAllWorlds(){return await this.adapter.getAllWorlds()}async updateWorld($){await this.adapter.updateWorld($)}async getRoom($){let q=await this.adapter.getRoomsByIds([$]);if(!q?.length)return null;return q[0]}async getRoomsByIds($){return await this.adapter.getRoomsByIds($)}async createRoom({id:$,name:q,source:_,type:P,channelId:K,messageServerId:O,worldId:Y}){if(!Y)throw Error("worldId is required");let v=await this.adapter.createRooms([{id:$,name:q,source:_,type:P,channelId:K,messageServerId:O,worldId:Y}]);if(!v.length)throw Error("Failed to create room");return v[0]}async createRooms($){return await this.adapter.createRooms($)}async deleteRoom($){await this.adapter.deleteRoom($)}async deleteRoomsByWorldId($){await this.adapter.deleteRoomsByWorldId($)}async updateRoom($){await this.adapter.updateRoom($)}async getRoomsForParticipant($){return await this.adapter.getRoomsForParticipant($)}async getRoomsForParticipants($){return await this.adapter.getRoomsForParticipants($)}async getRooms($){return await this.adapter.getRoomsByWorld($)}async getRoomsByWorld($){return await this.adapter.getRoomsByWorld($)}async getParticipantUserState($,q){return await this.adapter.getParticipantUserState($,q)}async setParticipantUserState($,q,_){await this.adapter.setParticipantUserState($,q,_)}async createRelationship($){return await this.adapter.createRelationship($)}async updateRelationship($){await this.adapter.updateRelationship($)}async getRelationship($){return await this.adapter.getRelationship($)}async getRelationships($){return await this.adapter.getRelationships($)}async getCache($){return await this.adapter.getCache($)}async setCache($,q){return await this.adapter.setCache($,q)}async deleteCache($){return await this.adapter.deleteCache($)}async createTask($){return await this.adapter.createTask($)}async getTasks($){return await this.adapter.getTasks($)}async getTask($){return await this.adapter.getTask($)}async getTasksByName($){return await this.adapter.getTasksByName($)}async updateTask($,q){await this.adapter.updateTask($,q)}async deleteTask($){await this.adapter.deleteTask($)}on($,q){if(!this.eventHandlers.has($))this.eventHandlers.set($,[]);this.eventHandlers.get($)?.push(q)}off($,q){if(!this.eventHandlers.has($))return;let _=this.eventHandlers.get($),P=_.indexOf(q);if(P!==-1)_.splice(P,1)}emit($,q){if(!this.eventHandlers.has($))return;for(let _ of this.eventHandlers.get($))_(q)}async sendControlMessage($){let{roomId:q,action:_,target:P}=$,K={type:"control",payload:{action:_,target:P},roomId:q};try{await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:K,source:"agent"}),this.logger.debug({src:"agent",agentId:this.agentId,action:_,channelId:q},"Control message sent")}catch(O){this.logger.error({src:"agent",agentId:this.agentId,error:O instanceof Error?O.message:String(O)},"Control message failed")}}registerSendHandler($,q){if(this.sendHandlers.has($))this.logger.warn({src:"agent",agentId:this.agentId,handlerSource:$},"Send handler already registered, overwriting");this.sendHandlers.set($,q),this.logger.debug({src:"agent",agentId:this.agentId,handlerSource:$},"Send handler registered")}async sendMessageToTarget($,q){let _=this.sendHandlers.get($.source);if(!_){let P=`No send handler registered for source: ${$.source}`;throw this.logger.error({src:"agent",agentId:this.agentId,handlerSource:$.source},"Send handler not found"),Error(P)}try{await _(this,$,q)}catch(P){throw this.logger.error({src:"agent",agentId:this.agentId,handlerSource:$.source,error:P instanceof Error?P.message:String(P)},"Send handler failed"),P}}async getMemoriesByWorldId($){return await this.adapter.getMemoriesByWorldId($)}async runMigrations($){if(this.adapter?.runMigrations)await this.adapter.runMigrations($);else this.logger.warn({src:"agent",agentId:this.agentId},"Database adapter does not support migrations")}async isReady(){if(!this.adapter)throw Error("Database adapter not registered");return await this.adapter.isReady()}hasElizaOS(){return this.elizaOS!==void 0}}var mR=null;async function dR($,q){if(MP()!=="node"||q?.skipEnvMerge)return!1;let _={};if(mR!==null)for(let K of mR){let O=process.env[K];if(O!==void 0)_[K]=O}else for(let[K,O]of Object.entries(process.env))if(O!==void 0)_[K]=O;$.settings??={};let P=$.settings.secrets&&typeof $.settings.secrets==="object"?{...$.settings.secrets}:{};return $.settings.secrets={..._,...P},!0}function Ja(){return typeof process<"u"&&(process.versions?.node!==void 0||process.versions?.bun!==void 0)}function RZ(){if(Ja())return Uq(),H6(Bq);return K4("crypto-browserify")}function IZ($){let _=RZ().createHash($);return{update(P){return _.update(P),this},digest(){return new Uint8Array(_.digest())}}}function lR($,q,_){if($!=="aes-256-cbc")throw Error(`Unsupported algorithm: ${$}. Only 'aes-256-cbc' is currently supported.`);let K=RZ().createCipheriv($,q,_);return{update(O,Y,v){let W=K.update(Buffer.from(O,Y),void 0,v);return typeof W==="string"?W:W.toString(v)},final(O){let Y=K.final(O);return typeof Y==="string"?Y:Y.toString(O)}}}function rR($,q,_){if($!=="aes-256-cbc")throw Error(`Unsupported algorithm: ${$}. Only 'aes-256-cbc' is currently supported.`);let K=RZ().createDecipheriv($,q,_);return{update(O,Y,v){let W=K.update(Buffer.from(O,Y),void 0,v);return typeof W==="string"?W:W.toString(v)},final(O){let Y=K.final(O);return typeof Y==="string"?Y:Y.toString(O)}}}function Wa($){return{name:$.name,description:$.description,usageDescription:$.usageDescription||"",value:null,required:$.required,validation:$.validation||void 0,public:$.public||!1,secret:$.secret||!1,dependsOn:$.dependsOn||[],onSetAction:$.onSetAction||void 0,visibleIf:$.visibleIf||void 0}}var xP=null,hZ=!1,Ha=300000;function m_(){let $=y_("SECRET_SALT","secretsalt")||"secretsalt",q=Date.now();if(xP!==null){if(q-xP.timestamp<Ha&&xP.value===$)return xP.value}if($==="secretsalt"&&!hZ)M6.warn({src:"core:settings"},"SECRET_SALT is not set or using default value"),hZ=!0;return xP={value:$,timestamp:q},$}function uv$(){xP=null,hZ=!1}function nR($,q){if($===void 0||$===null)return $;if(typeof $==="boolean"||typeof $==="number")return $;if(typeof $!=="string")return $;let _=$.split(":");if(_.length===2)try{if(XK.fromHex(_[0]).length===16)return $}catch{}let P=IZ("sha256").update(q).digest().slice(0,32),K=XK.randomBytes(16),O=lR("aes-256-cbc",P,K),Y=O.update($,"utf8","hex");return Y+=O.final("hex"),`${XK.toHex(K)}:${Y}`}function tY($,q){try{let _=$.split(":");if(_.length!==2)return $;let P=XK.fromHex(_[0]),K=_[1];if(P.length!==16)return $;let O=IZ("sha256").update(q).digest().slice(0,32),Y=rR("aes-256-cbc",O,P),v=Y.update(K,"hex","utf8");return v+=Y.final("utf8"),v}catch(_){return M6.error({src:"core:settings",error:_},"Decryption failed"),$}}function Ta($,q){let _={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)_.value=nR($.value,q);return _}function wa($,q){let _={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)_.value=tY($.value,q);return _}function Za($,q){let _={};for(let[P,K]of Object.entries($))_[P]=Ta(K,q);return _}function iR($,q){let _={};for(let[P,K]of Object.entries($))_[P]=wa(K,q);return _}async function xv$($,q,_){let P=H_($,q),K=await $.getWorld(P);if(!K)return M6.error({src:"core:settings",serverId:q},"World not found"),!1;if(!K.metadata)K.metadata={};let O=m_(),Y=Za(_,O);return K.metadata.settings=Y,await $.updateWorld(K),!0}async function pv$($,q){let _=H_($,q),P=await $.getWorld(_);if(!P||!P.metadata?.settings)return null;let K=P.metadata.settings,O=m_();return iR(K,O)}async function cv$($,q,_){if(q.metadata?.settings){M6.debug({src:"core:settings",serverId:q.messageServerId},"Onboarding state already exists");let K=q.metadata.settings,O=m_();return iR(K,O)}let P={};if(_.settings)for(let[K,O]of Object.entries(_.settings))P[K]=Wa(O);if(!q.metadata)q.metadata={};return q.metadata.settings=P,await $.updateWorld(q),M6.info({src:"core:settings",serverId:q.messageServerId},"Settings config initialized"),P}function mv$($){let q=JSON.parse(JSON.stringify($)),_=m_();if(q.settings?.secrets)q.settings.secrets=a7(q.settings.secrets,_);if(q.secrets)q.secrets=a7(q.secrets,_);return q}function dv$($,q){let _=JSON.parse(JSON.stringify($)),P=m_();if(_.settings?.secrets)_.settings.secrets=oR(_.settings.secrets,P);if(_.secrets)_.secrets=oR(_.secrets,P);return _}function a7($,q){let _={};for(let[P,K]of Object.entries($))if(typeof K==="string"&&K)_[P]=nR(K,q);else _[P]=K;return _}function oR($,q){let _={};for(let[P,K]of Object.entries($))if(typeof K==="string"&&K)_[P]=tY(K,q);else _[P]=K;return _}class BR{serviceType;startFn;stopFn;description;constructor($){this.serviceType=$,this.description=""}withDescription($){return this.description=$,this}withStart($){return this.startFn=$,this}withStop($){return this.stopFn=$,this}build(){let $=this.serviceType,q=this.description,_=this.startFn,P=this.stopFn;class K extends sY{static serviceType=$;capabilityDescription=q;static async start(O){if(!_)throw Error(`Start function not defined for service ${$}`);return _(O)}async stop(){if(P)await P()}}return K}}function Xa($){return new BR($)}function ov$($){return Xa($.serviceType).withDescription($.description).withStart($.start).withStop($.stop||(()=>Promise.resolve())).build()}var UR=new Set;function fa(){if(process.env.ELIZA_NO_AUTO_INSTALL==="true")return!1;if(process.env.ELIZA_NO_PLUGIN_AUTO_INSTALL==="true")return!1;if(process.env.CI==="true")return!1;if(process.env.ELIZA_TEST_MODE==="true")return!1;return!0}async function Aa($){try{if(!fa())return M6.debug({src:"core:plugin",pluginName:$},"Auto-install disabled, skipping"),!1;if(UR.has($))return M6.debug({src:"core:plugin",pluginName:$},"Auto-install already attempted, skipping"),!1;if(UR.add($),typeof Bun>"u"||typeof Bun.spawn!=="function")return M6.warn({src:"core:plugin",pluginName:$},"Bun runtime not available, cannot auto-install"),!1;try{if(await Bun.spawn(["bun","--version"],{stdout:"pipe",stderr:"pipe"}).exited!==0)return M6.warn({src:"core:plugin",pluginName:$},"Bun not available on PATH, cannot auto-install"),!1}catch{return M6.warn({src:"core:plugin",pluginName:$},"Bun not available on PATH, cannot auto-install"),!1}M6.info({src:"core:plugin",pluginName:$},"Auto-installing missing plugin");let _=await Bun.spawn(["bun","add",$],{cwd:process.cwd(),env:process.env,stdout:"inherit",stderr:"inherit"}).exited;if(_===0)return M6.info({src:"core:plugin",pluginName:$},"Plugin installed, retrying import"),!0;return M6.error({src:"core:plugin",pluginName:$,exitCode:_},"Plugin installation failed"),!1}catch(q){let _=q instanceof Error?q.message:String(q);return M6.error({src:"core:plugin",pluginName:$,error:_},"Unexpected error during auto-install"),!1}}function tR($){if(!$||typeof $!=="object")return!1;let q=$;if(!q.name)return!1;return!!(q.init||q.services||q.providers||q.actions||q.evaluators||q.description)}function ka($){let q=[];if(!$)return q.push("Plugin is null or undefined"),{isValid:!1,errors:q};let _=$;if(!_.name)q.push("Plugin must have a name");if(_.actions){if(!Array.isArray(_.actions))q.push("Plugin actions must be an array");else if(_.actions.filter((K)=>typeof K!=="object"||!K).length>0)q.push("Plugin actions must be an array of action objects")}if(_.services){if(!Array.isArray(_.services))q.push("Plugin services must be an array");else if(_.services.filter((K)=>typeof K!=="function"&&(typeof K!=="object"||!K)).length>0)q.push("Plugin services must be an array of service classes or objects")}if(_.providers&&!Array.isArray(_.providers))q.push("Plugin providers must be an array");if(_.evaluators&&!Array.isArray(_.evaluators))q.push("Plugin evaluators must be an array");return{isValid:q.length===0,errors:q}}async function Ga($){let q;try{q=await import($)}catch(O){if(M6.warn({src:"core:plugin",pluginName:$,error:O},"Failed to load plugin"),!await Aa($))return null;try{q=await import($)}catch(v){return M6.error({src:"core:plugin",pluginName:$,error:v},"Import failed after auto-install"),null}}if(!q)return M6.error({src:"core:plugin",pluginName:$},"Failed to load plugin module"),null;let _=`${$.replace(/^@elizaos\/plugin-/,"").replace(/^@elizaos\//,"").replace(/-./g,(O)=>O[1].toUpperCase())}Plugin`,P=q,K=[P[_],P.default,...Object.values(P)];for(let O of K){if(tR(O))return O;if(typeof O==="function"&&O.length===0){let Y=O();if(tR(Y))return Y}}return M6.warn({src:"core:plugin",pluginName:$},"No valid plugin export found"),null}function e7($){let q=$.match(/^@[^/]+\/plugin-(.+)$/);if(q)return q[1];return $}function QR($,q=!1){let _=[],P=new Set,K=new Set,O=new Map;for(let[W,T]of $.entries()){if(O.set(W,T),T.name!==W)O.set(T.name,T);if(!T.name.startsWith("@"))O.set(`@elizaos/plugin-${T.name}`,T);let Z=e7(W);if(Z!==W)O.set(Z,T)}function Y(W){let T=O.get(W);if(!T){let k=e7(W),M=O.get(k);if(!M){M6.warn({src:"core:plugin",pluginName:W},"Plugin dependency not found, skipping");return}return Y(M.name)}let Z=T.name;if(P.has(Z))return;if(K.has(Z)){M6.error({src:"core:plugin",pluginName:Z},"Circular dependency detected");return}K.add(Z);let w=[...T.dependencies||[]];if(q)w.push(...T.testDependencies||[]);for(let k of w)Y(k);K.delete(Z),P.add(Z),_.push(Z)}for(let W of $.values())if(!P.has(W.name))Y(W.name);let v=_.map((W)=>{for(let T of $.values())if(T.name===W)return T;return null}).filter((W)=>Boolean(W));return M6.debug({src:"core:plugin",plugins:v.map((W)=>W.name)},"Plugins resolved"),v}async function Va($){if(typeof $==="string")return Ga($);let q=ka($);if(!q.isValid)return M6.error({src:"core:plugin",errors:q.errors},"Invalid plugin provided"),null;return $}function FR($,q,_,P){let K=e7($);if(!(q.has($)||q.has(K)||Array.from(_.keys()).some((Y)=>e7(Y)===K)||Array.from(_.values()).some((Y)=>e7(Y.name)===K||Y.name===$||Y.name===K)))q.add($),q.add(K),P.push($)}async function Sa($,q=!1){let _=new Map,P=[...$],K=new Set;while(P.length>0){let O=P.shift(),Y=await Va(O);if(!Y)continue;let v=Y.name;if(!_.has(v)){_.set(v,Y);for(let W of Y.dependencies??[])FR(W,K,_,P);if(q)for(let W of Y.testDependencies??[])FR(W,K,_,P)}}return QR(_,q)}async function aR($,q=!1){if(MP()==="node")return Sa($,q);let P=$.filter((O)=>typeof O!=="string");if($.some((O)=>typeof O==="string")){let O=$.filter((Y)=>typeof Y==="string");M6.warn({src:"core:plugin",skippedPlugins:O},"Browser environment: String plugin references not supported")}let K=new Map;for(let O of P)K.set(O.name,O);return QR(K,q)}class Ma extends EventTarget{runtimes=new Map;initFunctions=new Map;editableMode=!1;async addAgents($,q){let _=[],P=$.map(async(O)=>{let Y=JSON.parse(JSON.stringify(O.character));await dR(Y,{skipEnvMerge:q?.isTestMode});let v=m_();if(Y.settings?.secrets&&typeof Y.settings.secrets==="object")Y.settings.secrets=a7(Y.settings.secrets,v);if(Y.secrets&&typeof Y.secrets==="object")Y.secrets=a7(Y.secrets,v);let W=O.plugins?await aR(O.plugins,q?.isTestMode||!1):[];if(O.databaseAdapter)W=W.filter((N)=>N.name!=="@elizaos/plugin-sql");let T=new EZ({character:Y,plugins:W,settings:O.settings||{}});if(O.databaseAdapter)T.registerDatabaseAdapter(O.databaseAdapter);if(T.elizaOS=this,!q?.ephemeral)this.runtimes.set(T.agentId,T);if(typeof O.init==="function")this.initFunctions.set(T.agentId,O.init);let{settings:Z,...w}=Y,{secrets:k,...M}=Z||{};return this.dispatchEvent(new CustomEvent("agent:added",{detail:{agentId:T.agentId,character:{...w,settings:M},ephemeral:q?.ephemeral}})),_.push(T),T.agentId}),K=await Promise.all(P);if(q?.autoStart)await Promise.all(_.map(async(O)=>{await O.initialize({skipMigrations:q?.skipMigrations});let Y=this.initFunctions.get(O.agentId);if(Y)await Y(O),this.initFunctions.delete(O.agentId);this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:O.agentId}}))}));if(this.dispatchEvent(new CustomEvent("agents:added",{detail:{agentIds:K,count:K.length,ephemeral:q?.ephemeral}})),q?.returnRuntimes)return _;return K}registerAgent($){if(this.runtimes.has($.agentId))throw Error(`Agent ${$.agentId} already registered`);$.elizaOS=this,this.runtimes.set($.agentId,$),this.dispatchEvent(new CustomEvent("agent:registered",{detail:{agentId:$.agentId,runtime:$}}))}async updateAgent($,q){if(!this.editableMode)throw Error("Editable mode not enabled");let _=this.runtimes.get($);if(!_)throw Error(`Agent ${$} not found`);Object.assign(_.character,q),this.dispatchEvent(new CustomEvent("agent:updated",{detail:{agentId:$,updates:q}}))}async deleteAgents($){await this.stopAgents($);for(let q of $)this.runtimes.delete(q),this.initFunctions.delete(q);this.dispatchEvent(new CustomEvent("agents:deleted",{detail:{agentIds:$,count:$.length}}))}async startAgents($){let q=$||Array.from(this.runtimes.keys());await Promise.all(q.map(async(_)=>{let P=this.runtimes.get(_);if(!P)throw Error(`Agent ${_} not found`);await P.initialize(),this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:_}}))}));for(let _ of q){let P=this.initFunctions.get(_);if(P){let K=this.runtimes.get(_);if(K)await P(K),this.initFunctions.delete(_)}}this.dispatchEvent(new CustomEvent("agents:started",{detail:{agentIds:q,count:q.length}}))}async stopAgents($){let q=$||Array.from(this.runtimes.keys());await Promise.all(q.map(async(_)=>{let P=this.runtimes.get(_);if(P)await P.stop()})),this.dispatchEvent(new CustomEvent("agents:stopped",{detail:{agentIds:q,count:q.length}}))}getAgent($){return this.runtimes.get($)}getAgents(){return Array.from(this.runtimes.values())}getAgentsByIds($){return $.map((q)=>this.runtimes.get(q)).filter((q)=>q!==void 0)}getAgentsByNames($){let q=new Set($.map((_)=>_.toLowerCase()));return this.getAgents().filter((_)=>q.has(_.character.name.toLowerCase()))}getAgentById($){return this.getAgent($)}getAgentByName($){let q=$.toLowerCase();return this.getAgents().find((_)=>_.character.name.toLowerCase()===q)}getAgentByCharacterName($){return this.getAgentByName($)}getAgentByCharacterId($){return this.getAgents().find((q)=>q.character.id===$)}async handleMessage($,q,_){let P,K;if(typeof $==="string"){if(K=$,P=this.runtimes.get(K),!P)throw Error(`Agent ${K} not found in registry`)}else P=$,K=P.agentId;if(!P.messageService)throw Error("messageService is not initialized on runtime");let O=q.id||Y8(),Y={...q,id:O,agentId:q.agentId||P.agentId,createdAt:q.createdAt||Date.now(),entityId:q.entityId,roomId:q.roomId,content:q.content};await P.ensureConnection({entityId:Y.entityId,roomId:Y.roomId,worldId:q.worldId||Y.roomId,source:Y.content.source||"unknown",channelId:Y.roomId});let v={maxRetries:_?.maxRetries,timeoutDuration:_?.timeoutDuration,useMultiStep:_?.useMultiStep,maxMultiStepIterations:_?.maxMultiStepIterations,onStreamChunk:_?.onStreamChunk},W=async(Z)=>{if(P.withEntityContext)return await P.withEntityContext(Y.entityId,Z);else return await Z()};if(!!_?.onResponse){let Z=async(w)=>{try{if(_.onResponse)await _.onResponse(w)}catch(k){if(_.onError)await _.onError(k instanceof Error?k:Error(String(k)))}return[]};return W(()=>P.messageService.handleMessage(P,Y,Z,v)).then(()=>{if(_.onComplete)_.onComplete()}).catch((w)=>{if(_.onError)_.onError(w)}),this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:K,messageId:O,mode:"async"}})),{messageId:O,userMessage:Y}}else{let Z=await W(()=>P.messageService.handleMessage(P,Y,void 0,v));if(_?.onComplete)await _.onComplete();return this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:K,messageId:O,mode:"sync",processing:Z}})),{messageId:O,userMessage:Y,processing:Z}}}async handleMessages($){let q=await Promise.all($.map(async({agentId:_,message:P,options:K})=>{try{let O=await this.handleMessage(_,P,K);return{agentId:_,result:O}}catch(O){return{agentId:_,result:{messageId:P.id||"",userMessage:P},error:O instanceof Error?O:Error(String(O))}}}));return this.dispatchEvent(new CustomEvent("messages:sent",{detail:{results:q,count:$.length}})),q}async validateApiKeys($){let q=new Map,_=$||Array.from(this.runtimes.keys());for(let P of _){let K=this.runtimes.get(P);if(K){let O=!!(K.getSetting("OPENAI_API_KEY")||K.getSetting("ANTHROPIC_API_KEY"));q.set(P,O)}}return q}async healthCheck($){let q=new Map,_=$||Array.from(this.runtimes.keys());for(let P of _){let O={alive:!!this.runtimes.get(P),responsive:!0};if(typeof process<"u")O.memoryUsage=process.memoryUsage().heapUsed,O.uptime=process.uptime();q.set(P,O)}return q}getRuntimeAccessor(){return{getAgent:($)=>this.getAgent($),getAgents:()=>this.getAgents(),getState:($)=>{let q=this.getAgent($);if(!q)return;if(q.stateCache&&q.stateCache.size>0){let _=Array.from(q.stateCache.values());return _[_.length-1]}return}}}enableEditableMode(){this.editableMode=!0,this.dispatchEvent(new CustomEvent("mode:editable",{detail:{editable:!0}}))}}var Na=`# Task: Resolve Entity Name
727
+ ${$}`}let O={prompt:K,maxTokens:q?.maxTokens,minTokens:q?.minTokens,temperature:q?.temperature,topP:q?.topP,topK:q?.topK,minP:q?.minP,seed:q?.seed,repetitionPenalty:q?.repetitionPenalty,frequencyPenalty:q?.frequencyPenalty,presencePenalty:q?.presencePenalty,stopSequences:q?.stopSequences,user:q?.user!==void 0?q.user:this.character?.name,responseFormat:q?.responseFormat};return{text:await this.useModel(P,O)}}registerEvent($,q){if(!this.events[$])this.events[$]=[];this.events[$].push(q)}getEvent($){return this.events[$]}async emitEvent($,q){let _=Array.isArray($)?$:[$];for(let P of _){let K=this.events[P];if(!K)continue;let O={runtime:this,source:"runtime"};if(typeof q==="object"&&q&&q!==null){let Y=q;O={...Y,runtime:this,source:Y.source||"runtime"}}await Promise.all(K.map((Y)=>Y(O)))}}async ensureEmbeddingDimension(){if(!this.adapter)throw Error("Database adapter not initialized before ensureEmbeddingDimension");if(!this.getModel(A6.TEXT_EMBEDDING))throw Error("No TEXT_EMBEDDING model registered");let $=this.getSetting("EMBEDDING_DIMENSION"),q=Number($),_=q>0,P=_?q:(await this.useModel(A6.TEXT_EMBEDDING,null))?.length;if(!P)throw Error("Invalid embedding dimension");await this.adapter.ensureEmbeddingDimension(P),this.logger.debug({src:"agent",agentId:this.agentId,dimension:P},_?"Embedding dimension set from config":"Embedding dimension set via API call")}registerTaskWorker($){if(this.taskWorkers.has($.name))this.logger.warn({src:"agent",agentId:this.agentId,task:$.name},"Task worker already registered, overwriting");this.taskWorkers.set($.name,$)}getTaskWorker($){return this.taskWorkers.get($)}get db(){return this.adapter.db}async init(){await this.adapter.init()}async close(){if(this.adapter)await this.adapter.close()}async getAgent($){return await this.adapter.getAgent($)}async getAgents(){return await this.adapter.getAgents()}async createAgent($){return await this.adapter.createAgent($)}async updateAgent($,q){return await this.adapter.updateAgent($,q)}async deleteAgent($){return await this.adapter.deleteAgent($)}async ensureAgentExists($){if(!$.id)throw Error("Agent id is required");let q=await this.adapter.getAgent($.id);if(q){let K={...q.settings,...$.settings},O=typeof q.settings?.secrets==="object"||typeof $.settings?.secrets==="object"?{...typeof q.settings?.secrets==="object"?q.settings.secrets:{},...typeof $.settings?.secrets==="object"?$.settings.secrets:{}}:void 0;if(O)K.secrets=O;let Y={...q,...$,settings:K,id:$.id,updatedAt:Date.now()};await this.adapter.updateAgent($.id,Y);let v=await this.adapter.getAgent($.id);if(!v)throw Error(`Failed to retrieve agent after update: ${$.id}`);return this.logger.debug({src:"agent",agentId:$.id},"Agent updated on restart"),v}let _={...$,id:$.id};if(!await this.adapter.createAgent(_))throw Error(`Failed to create agent: ${$.id}`);return this.logger.debug({src:"agent",agentId:$.id},"Agent created"),_}async getEntityById($){let q=await this.adapter.getEntitiesByIds([$]);if(!q?.length)return null;return q[0]}async getEntitiesByIds($){return await this.adapter.getEntitiesByIds($)}async getEntitiesForRoom($,q){return await this.adapter.getEntitiesForRoom($,q)}async createEntity($){if(!$.agentId)$.agentId=this.agentId;return await this.createEntities([$])}async ensureEntity($){if(!$.id)return null;if(!await this.createEntity($))return null;return $}async createEntities($){return $.forEach((q)=>{q.agentId=this.agentId}),await this.adapter.createEntities($)}async updateEntity($){await this.adapter.updateEntity($)}async getComponent($,q,_,P){return await this.adapter.getComponent($,q,_,P)}async getComponents($,q,_){return await this.adapter.getComponents($,q,_)}async createComponent($){return await this.adapter.createComponent($)}async updateComponent($){await this.adapter.updateComponent($)}async deleteComponent($){await this.adapter.deleteComponent($)}async addEmbeddingToMemory($){if($.embedding)return $;let q=$.content.text;if(!q)throw Error("Cannot generate embedding: Memory content is empty");try{$.embedding=await this.useModel(A6.TEXT_EMBEDDING,{text:q})}catch(_){this.logger.error({src:"agent",agentId:this.agentId,error:_ instanceof Error?_.message:String(_)},"Embedding generation failed"),$.embedding=await this.useModel(A6.TEXT_EMBEDDING,{text:""})}return $}async queueEmbeddingGeneration($,q){if(q=q||"normal",!$)return;if($.embedding)return;if(!$.content?.text)return;await this.emitEvent("EMBEDDING_GENERATION_REQUESTED",{runtime:this,memory:$,priority:q,source:"runtime",retryCount:0,maxRetries:3,runId:this.getCurrentRunId()})}async getMemories($){return await this.adapter.getMemories($)}async getAllMemories(){let $=["memories","messages","facts","documents"],q=[];for(let _ of $)try{let P=await this.adapter.getMemories({agentId:this.agentId,tableName:_,count:1e4});q.push(...P)}catch(P){this.logger.debug({src:"agent",agentId:this.agentId,tableName:_,error:P instanceof Error?P.message:String(P)},"Failed to get memories")}return q}async getMemoryById($){return await this.adapter.getMemoryById($)}async getMemoriesByIds($,q){return await this.adapter.getMemoriesByIds($,q)}async getMemoriesByRoomIds($){return await this.adapter.getMemoriesByRoomIds($)}async getCachedEmbeddings($){return await this.adapter.getCachedEmbeddings($)}async log($){await this.adapter.log($)}async searchMemories($){let q=await this.adapter.searchMemories($);if($.query)return await this.rerankMemories($.query,q);return q}async rerankMemories($,q){let _=q.map((O)=>({title:O.id,content:O.content.text}));return new CZ(_).search($,q.length).map((O)=>q[O.index])}async createMemory($,q,_){if(_!==void 0)$.unique=_;return await this.adapter.createMemory($,q,_)}async updateMemory($){return await this.adapter.updateMemory($)}async deleteMemory($){await this.adapter.deleteMemory($)}async deleteManyMemories($){await this.adapter.deleteManyMemories($)}async clearAllAgentMemories(){this.logger.info({src:"agent",agentId:this.agentId},"Clearing all memories");let q=(await this.getAllMemories()).map((_)=>_.id).filter((_)=>_!==void 0);if(q.length===0){this.logger.debug({src:"agent",agentId:this.agentId},"No memories to delete");return}await this.adapter.deleteManyMemories(q),this.logger.info({src:"agent",agentId:this.agentId,count:q.length},"Memories cleared")}async deleteAllMemories($,q){await this.adapter.deleteAllMemories($,q)}async countMemories($,q,_){return await this.adapter.countMemories($,q,_)}async getLogs($){return await this.adapter.getLogs($)}async deleteLog($){await this.adapter.deleteLog($)}async createWorld($){return await this.adapter.createWorld($)}async getWorld($){return await this.adapter.getWorld($)}async removeWorld($){await this.adapter.removeWorld($)}async getAllWorlds(){return await this.adapter.getAllWorlds()}async updateWorld($){await this.adapter.updateWorld($)}async getRoom($){let q=await this.adapter.getRoomsByIds([$]);if(!q?.length)return null;return q[0]}async getRoomsByIds($){return await this.adapter.getRoomsByIds($)}async createRoom({id:$,name:q,source:_,type:P,channelId:K,messageServerId:O,worldId:Y}){if(!Y)throw Error("worldId is required");let v=await this.adapter.createRooms([{id:$,name:q,source:_,type:P,channelId:K,messageServerId:O,worldId:Y}]);if(!v.length)throw Error("Failed to create room");return v[0]}async createRooms($){return await this.adapter.createRooms($)}async deleteRoom($){await this.adapter.deleteRoom($)}async deleteRoomsByWorldId($){await this.adapter.deleteRoomsByWorldId($)}async updateRoom($){await this.adapter.updateRoom($)}async getRoomsForParticipant($){return await this.adapter.getRoomsForParticipant($)}async getRoomsForParticipants($){return await this.adapter.getRoomsForParticipants($)}async getRooms($){return await this.adapter.getRoomsByWorld($)}async getRoomsByWorld($){return await this.adapter.getRoomsByWorld($)}async getParticipantUserState($,q){return await this.adapter.getParticipantUserState($,q)}async setParticipantUserState($,q,_){await this.adapter.setParticipantUserState($,q,_)}async createRelationship($){return await this.adapter.createRelationship($)}async updateRelationship($){await this.adapter.updateRelationship($)}async getRelationship($){return await this.adapter.getRelationship($)}async getRelationships($){return await this.adapter.getRelationships($)}async getCache($){return await this.adapter.getCache($)}async setCache($,q){return await this.adapter.setCache($,q)}async deleteCache($){return await this.adapter.deleteCache($)}async createTask($){return await this.adapter.createTask($)}async getTasks($){return await this.adapter.getTasks($)}async getTask($){return await this.adapter.getTask($)}async getTasksByName($){return await this.adapter.getTasksByName($)}async updateTask($,q){await this.adapter.updateTask($,q)}async deleteTask($){await this.adapter.deleteTask($)}on($,q){if(!this.eventHandlers.has($))this.eventHandlers.set($,[]);this.eventHandlers.get($)?.push(q)}off($,q){if(!this.eventHandlers.has($))return;let _=this.eventHandlers.get($),P=_.indexOf(q);if(P!==-1)_.splice(P,1)}emit($,q){if(!this.eventHandlers.has($))return;for(let _ of this.eventHandlers.get($))_(q)}async sendControlMessage($){let{roomId:q,action:_,target:P}=$,K={type:"control",payload:{action:_,target:P},roomId:q};try{await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:K,source:"agent"}),this.logger.debug({src:"agent",agentId:this.agentId,action:_,channelId:q},"Control message sent")}catch(O){this.logger.error({src:"agent",agentId:this.agentId,error:O instanceof Error?O.message:String(O)},"Control message failed")}}registerSendHandler($,q){if(this.sendHandlers.has($))this.logger.warn({src:"agent",agentId:this.agentId,handlerSource:$},"Send handler already registered, overwriting");this.sendHandlers.set($,q),this.logger.debug({src:"agent",agentId:this.agentId,handlerSource:$},"Send handler registered")}async sendMessageToTarget($,q){let _=this.sendHandlers.get($.source);if(!_){let P=`No send handler registered for source: ${$.source}`;throw this.logger.error({src:"agent",agentId:this.agentId,handlerSource:$.source},"Send handler not found"),Error(P)}try{await _(this,$,q)}catch(P){throw this.logger.error({src:"agent",agentId:this.agentId,handlerSource:$.source,error:P instanceof Error?P.message:String(P)},"Send handler failed"),P}}async getMemoriesByWorldId($){return await this.adapter.getMemoriesByWorldId($)}async runMigrations($){if(this.adapter?.runMigrations)await this.adapter.runMigrations($);else this.logger.warn({src:"agent",agentId:this.agentId},"Database adapter does not support migrations")}async isReady(){if(!this.adapter)throw Error("Database adapter not registered");return await this.adapter.isReady()}hasElizaOS(){return this.elizaOS!==void 0}}var mR=null;async function dR($,q){if(MP()!=="node"||q?.skipEnvMerge)return!1;let _={};if(mR!==null)for(let K of mR){let O=process.env[K];if(O!==void 0)_[K]=O}else for(let[K,O]of Object.entries(process.env))if(O!==void 0)_[K]=O;$.settings??={};let P=$.settings.secrets&&typeof $.settings.secrets==="object"?{...$.settings.secrets}:{};return $.settings.secrets={..._,...P},!0}function Ja(){return typeof process<"u"&&(process.versions?.node!==void 0||process.versions?.bun!==void 0)}function RZ(){if(Ja())return Uq(),H6(Bq);return K4("crypto-browserify")}function IZ($){let _=RZ().createHash($);return{update(P){return _.update(P),this},digest(){return new Uint8Array(_.digest())}}}function lR($,q,_){if($!=="aes-256-cbc")throw Error(`Unsupported algorithm: ${$}. Only 'aes-256-cbc' is currently supported.`);let K=RZ().createCipheriv($,q,_);return{update(O,Y,v){let W=K.update(Buffer.from(O,Y),void 0,v);return typeof W==="string"?W:W.toString(v)},final(O){let Y=K.final(O);return typeof Y==="string"?Y:Y.toString(O)}}}function rR($,q,_){if($!=="aes-256-cbc")throw Error(`Unsupported algorithm: ${$}. Only 'aes-256-cbc' is currently supported.`);let K=RZ().createDecipheriv($,q,_);return{update(O,Y,v){let W=K.update(Buffer.from(O,Y),void 0,v);return typeof W==="string"?W:W.toString(v)},final(O){let Y=K.final(O);return typeof Y==="string"?Y:Y.toString(O)}}}function Wa($){return{name:$.name,description:$.description,usageDescription:$.usageDescription||"",value:null,required:$.required,validation:$.validation||void 0,public:$.public||!1,secret:$.secret||!1,dependsOn:$.dependsOn||[],onSetAction:$.onSetAction||void 0,visibleIf:$.visibleIf||void 0}}var xP=null,hZ=!1,Ha=300000;function m_(){let $=y_("SECRET_SALT","secretsalt")||"secretsalt",q=Date.now();if(xP!==null){if(q-xP.timestamp<Ha&&xP.value===$)return xP.value}if($==="secretsalt"&&!hZ)M6.warn({src:"core:settings"},"SECRET_SALT is not set or using default value"),hZ=!0;return xP={value:$,timestamp:q},$}function uv$(){xP=null,hZ=!1}function nR($,q){if($===void 0||$===null)return $;if(typeof $==="boolean"||typeof $==="number")return $;if(typeof $!=="string")return $;let _=$.split(":");if(_.length===2)try{if(XK.fromHex(_[0]).length===16)return $}catch{}let P=IZ("sha256").update(q).digest().slice(0,32),K=XK.randomBytes(16),O=lR("aes-256-cbc",P,K),Y=O.update($,"utf8","hex");return Y+=O.final("hex"),`${XK.toHex(K)}:${Y}`}function tY($,q){try{let _=$.split(":");if(_.length!==2)return $;let P=XK.fromHex(_[0]),K=_[1];if(P.length!==16)return $;let O=IZ("sha256").update(q).digest().slice(0,32),Y=rR("aes-256-cbc",O,P),v=Y.update(K,"hex","utf8");return v+=Y.final("utf8"),v}catch(_){return M6.error({src:"core:settings",error:_},"Decryption failed"),$}}function Ta($,q){let _={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)_.value=nR($.value,q);return _}function wa($,q){let _={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)_.value=tY($.value,q);return _}function Za($,q){let _={};for(let[P,K]of Object.entries($))_[P]=Ta(K,q);return _}function iR($,q){let _={};for(let[P,K]of Object.entries($))_[P]=wa(K,q);return _}async function xv$($,q,_){let P=H_($,q),K=await $.getWorld(P);if(!K)return M6.error({src:"core:settings",serverId:q},"World not found"),!1;if(!K.metadata)K.metadata={};let O=m_(),Y=Za(_,O);return K.metadata.settings=Y,await $.updateWorld(K),!0}async function pv$($,q){let _=H_($,q),P=await $.getWorld(_);if(!P||!P.metadata?.settings)return null;let K=P.metadata.settings,O=m_();return iR(K,O)}async function cv$($,q,_){if(q.metadata?.settings){M6.debug({src:"core:settings",serverId:q.messageServerId},"Onboarding state already exists");let K=q.metadata.settings,O=m_();return iR(K,O)}let P={};if(_.settings)for(let[K,O]of Object.entries(_.settings))P[K]=Wa(O);if(!q.metadata)q.metadata={};return q.metadata.settings=P,await $.updateWorld(q),M6.info({src:"core:settings",serverId:q.messageServerId},"Settings config initialized"),P}function mv$($){let q=JSON.parse(JSON.stringify($)),_=m_();if(q.settings?.secrets)q.settings.secrets=a7(q.settings.secrets,_);if(q.secrets)q.secrets=a7(q.secrets,_);return q}function dv$($,q){let _=JSON.parse(JSON.stringify($)),P=m_();if(_.settings?.secrets)_.settings.secrets=oR(_.settings.secrets,P);if(_.secrets)_.secrets=oR(_.secrets,P);return _}function a7($,q){let _={};for(let[P,K]of Object.entries($))if(typeof K==="string"&&K)_[P]=nR(K,q);else _[P]=K;return _}function oR($,q){let _={};for(let[P,K]of Object.entries($))if(typeof K==="string"&&K)_[P]=tY(K,q);else _[P]=K;return _}class BR{serviceType;startFn;stopFn;description;constructor($){this.serviceType=$,this.description=""}withDescription($){return this.description=$,this}withStart($){return this.startFn=$,this}withStop($){return this.stopFn=$,this}build(){let $=this.serviceType,q=this.description,_=this.startFn,P=this.stopFn;class K extends sY{static serviceType=$;capabilityDescription=q;static async start(O){if(!_)throw Error(`Start function not defined for service ${$}`);return _(O)}async stop(){if(P)await P()}}return K}}function Xa($){return new BR($)}function ov$($){return Xa($.serviceType).withDescription($.description).withStart($.start).withStop($.stop||(()=>Promise.resolve())).build()}var UR=new Set;function fa(){if(process.env.ELIZA_NO_AUTO_INSTALL==="true")return!1;if(process.env.ELIZA_NO_PLUGIN_AUTO_INSTALL==="true")return!1;if(process.env.CI==="true")return!1;if(process.env.ELIZA_TEST_MODE==="true")return!1;return!0}async function Aa($){try{if(!fa())return M6.debug({src:"core:plugin",pluginName:$},"Auto-install disabled, skipping"),!1;if(UR.has($))return M6.debug({src:"core:plugin",pluginName:$},"Auto-install already attempted, skipping"),!1;if(UR.add($),typeof Bun>"u"||typeof Bun.spawn!=="function")return M6.warn({src:"core:plugin",pluginName:$},"Bun runtime not available, cannot auto-install"),!1;try{if(await Bun.spawn(["bun","--version"],{stdout:"pipe",stderr:"pipe"}).exited!==0)return M6.warn({src:"core:plugin",pluginName:$},"Bun not available on PATH, cannot auto-install"),!1}catch{return M6.warn({src:"core:plugin",pluginName:$},"Bun not available on PATH, cannot auto-install"),!1}M6.info({src:"core:plugin",pluginName:$},"Auto-installing missing plugin");let _=await Bun.spawn(["bun","add",$],{cwd:process.cwd(),env:process.env,stdout:"inherit",stderr:"inherit"}).exited;if(_===0)return M6.info({src:"core:plugin",pluginName:$},"Plugin installed, retrying import"),!0;return M6.error({src:"core:plugin",pluginName:$,exitCode:_},"Plugin installation failed"),!1}catch(q){let _=q instanceof Error?q.message:String(q);return M6.error({src:"core:plugin",pluginName:$,error:_},"Unexpected error during auto-install"),!1}}function tR($){if(!$||typeof $!=="object")return!1;let q=$;if(!q.name)return!1;return!!(q.init||q.services||q.providers||q.actions||q.evaluators||q.description)}function ka($){let q=[];if(!$)return q.push("Plugin is null or undefined"),{isValid:!1,errors:q};let _=$;if(!_.name)q.push("Plugin must have a name");if(_.actions){if(!Array.isArray(_.actions))q.push("Plugin actions must be an array");else if(_.actions.filter((K)=>typeof K!=="object"||!K).length>0)q.push("Plugin actions must be an array of action objects")}if(_.services){if(!Array.isArray(_.services))q.push("Plugin services must be an array");else if(_.services.filter((K)=>typeof K!=="function"&&(typeof K!=="object"||!K)).length>0)q.push("Plugin services must be an array of service classes or objects")}if(_.providers&&!Array.isArray(_.providers))q.push("Plugin providers must be an array");if(_.evaluators&&!Array.isArray(_.evaluators))q.push("Plugin evaluators must be an array");return{isValid:q.length===0,errors:q}}async function Ga($){let q;try{q=await import($)}catch(O){if(M6.warn({src:"core:plugin",pluginName:$,error:O},"Failed to load plugin"),!await Aa($))return null;try{q=await import($)}catch(v){return M6.error({src:"core:plugin",pluginName:$,error:v},"Import failed after auto-install"),null}}if(!q)return M6.error({src:"core:plugin",pluginName:$},"Failed to load plugin module"),null;let _=`${$.replace(/^@elizaos\/plugin-/,"").replace(/^@elizaos\//,"").replace(/-./g,(O)=>O[1].toUpperCase())}Plugin`,P=q,K=[P[_],P.default,...Object.values(P)];for(let O of K){if(tR(O))return O;if(typeof O==="function"&&O.length===0){let Y=O();if(tR(Y))return Y}}return M6.warn({src:"core:plugin",pluginName:$},"No valid plugin export found"),null}function e7($){let q=$.match(/^@[^/]+\/plugin-(.+)$/);if(q)return q[1];return $}function QR($,q=!1){let _=[],P=new Set,K=new Set,O=new Map;for(let[W,T]of $.entries()){if(O.set(W,T),T.name!==W)O.set(T.name,T);if(!T.name.startsWith("@"))O.set(`@elizaos/plugin-${T.name}`,T);let Z=e7(W);if(Z!==W)O.set(Z,T)}function Y(W){let T=O.get(W);if(!T){let k=e7(W),M=O.get(k);if(!M){M6.warn({src:"core:plugin",pluginName:W},"Plugin dependency not found, skipping");return}return Y(M.name)}let Z=T.name;if(P.has(Z))return;if(K.has(Z)){M6.error({src:"core:plugin",pluginName:Z},"Circular dependency detected");return}K.add(Z);let w=[...T.dependencies||[]];if(q)w.push(...T.testDependencies||[]);for(let k of w)Y(k);K.delete(Z),P.add(Z),_.push(Z)}for(let W of $.values())if(!P.has(W.name))Y(W.name);let v=_.map((W)=>{for(let T of $.values())if(T.name===W)return T;return null}).filter((W)=>Boolean(W));return M6.debug({src:"core:plugin",plugins:v.map((W)=>W.name)},"Plugins resolved"),v}async function Va($){if(typeof $==="string")return Ga($);let q=ka($);if(!q.isValid)return M6.error({src:"core:plugin",errors:q.errors},"Invalid plugin provided"),null;return $}function FR($,q,_,P){let K=e7($);if(!(q.has($)||q.has(K)||Array.from(_.keys()).some((Y)=>e7(Y)===K)||Array.from(_.values()).some((Y)=>e7(Y.name)===K||Y.name===$||Y.name===K)))q.add($),q.add(K),P.push($)}async function Sa($,q=!1){let _=new Map,P=[...$],K=new Set;while(P.length>0){let O=P.shift(),Y=await Va(O);if(!Y)continue;let v=Y.name;if(!_.has(v)){_.set(v,Y);for(let W of Y.dependencies??[])FR(W,K,_,P);if(q)for(let W of Y.testDependencies??[])FR(W,K,_,P)}}return QR(_,q)}async function aR($,q=!1){if(MP()==="node")return Sa($,q);let P=$.filter((O)=>typeof O!=="string");if($.some((O)=>typeof O==="string")){let O=$.filter((Y)=>typeof Y==="string");M6.warn({src:"core:plugin",skippedPlugins:O},"Browser environment: String plugin references not supported")}let K=new Map;for(let O of P)K.set(O.name,O);return QR(K,q)}class Ma extends EventTarget{runtimes=new Map;initFunctions=new Map;editableMode=!1;async addAgents($,q){let _=[],P=$.map(async(O)=>{let Y=JSON.parse(JSON.stringify(O.character));await dR(Y,{skipEnvMerge:q?.isTestMode});let v=m_();if(Y.settings?.secrets&&typeof Y.settings.secrets==="object")Y.settings.secrets=a7(Y.settings.secrets,v);if(Y.secrets&&typeof Y.secrets==="object")Y.secrets=a7(Y.secrets,v);let W=O.plugins?await aR(O.plugins,q?.isTestMode||!1):[];if(O.databaseAdapter)W=W.filter((N)=>N.name!=="@elizaos/plugin-sql");let T=new EZ({character:Y,plugins:W,settings:O.settings||{}});if(O.databaseAdapter)T.registerDatabaseAdapter(O.databaseAdapter);if(T.elizaOS=this,!q?.ephemeral)this.runtimes.set(T.agentId,T);if(typeof O.init==="function")this.initFunctions.set(T.agentId,O.init);let{settings:Z,...w}=Y,{secrets:k,...M}=Z||{};return this.dispatchEvent(new CustomEvent("agent:added",{detail:{agentId:T.agentId,character:{...w,settings:M},ephemeral:q?.ephemeral}})),_.push(T),T.agentId}),K=await Promise.all(P);if(q?.autoStart)await Promise.all(_.map(async(O)=>{await O.initialize({skipMigrations:q?.skipMigrations});let Y=this.initFunctions.get(O.agentId);if(Y)await Y(O),this.initFunctions.delete(O.agentId);this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:O.agentId}}))}));if(this.dispatchEvent(new CustomEvent("agents:added",{detail:{agentIds:K,count:K.length,ephemeral:q?.ephemeral}})),q?.returnRuntimes)return _;return K}registerAgent($){if(this.runtimes.has($.agentId))throw Error(`Agent ${$.agentId} already registered`);$.elizaOS=this,this.runtimes.set($.agentId,$),this.dispatchEvent(new CustomEvent("agent:registered",{detail:{agentId:$.agentId,runtime:$}}))}async updateAgent($,q){if(!this.editableMode)throw Error("Editable mode not enabled");let _=this.runtimes.get($);if(!_)throw Error(`Agent ${$} not found`);Object.assign(_.character,q),this.dispatchEvent(new CustomEvent("agent:updated",{detail:{agentId:$,updates:q}}))}async deleteAgents($){await this.stopAgents($);for(let q of $)this.runtimes.delete(q),this.initFunctions.delete(q);this.dispatchEvent(new CustomEvent("agents:deleted",{detail:{agentIds:$,count:$.length}}))}async startAgents($){let q=$||Array.from(this.runtimes.keys());await Promise.all(q.map(async(_)=>{let P=this.runtimes.get(_);if(!P)throw Error(`Agent ${_} not found`);await P.initialize(),this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:_}}))}));for(let _ of q){let P=this.initFunctions.get(_);if(P){let K=this.runtimes.get(_);if(K)await P(K),this.initFunctions.delete(_)}}this.dispatchEvent(new CustomEvent("agents:started",{detail:{agentIds:q,count:q.length}}))}async stopAgents($){let q=$||Array.from(this.runtimes.keys());await Promise.all(q.map(async(_)=>{let P=this.runtimes.get(_);if(P)await P.stop()})),this.dispatchEvent(new CustomEvent("agents:stopped",{detail:{agentIds:q,count:q.length}}))}getAgent($){return this.runtimes.get($)}getAgents(){return Array.from(this.runtimes.values())}getAgentsByIds($){return $.map((q)=>this.runtimes.get(q)).filter((q)=>q!==void 0)}getAgentsByNames($){let q=new Set($.map((_)=>_.toLowerCase()));return this.getAgents().filter((_)=>q.has(_.character.name.toLowerCase()))}getAgentById($){return this.getAgent($)}getAgentByName($){let q=$.toLowerCase();return this.getAgents().find((_)=>_.character.name.toLowerCase()===q)}getAgentByCharacterName($){return this.getAgentByName($)}getAgentByCharacterId($){return this.getAgents().find((q)=>q.character.id===$)}async handleMessage($,q,_){let P,K;if(typeof $==="string"){if(K=$,P=this.runtimes.get(K),!P)throw Error(`Agent ${K} not found in registry`)}else P=$,K=P.agentId;if(!P.messageService)throw Error("messageService is not initialized on runtime");let O=q.id||Y8(),Y={...q,id:O,agentId:q.agentId||P.agentId,createdAt:q.createdAt||Date.now(),entityId:q.entityId,roomId:q.roomId,content:q.content};await P.ensureConnection({entityId:Y.entityId,roomId:Y.roomId,worldId:q.worldId||Y.roomId,source:Y.content.source||"unknown",channelId:Y.roomId});let v={maxRetries:_?.maxRetries,timeoutDuration:_?.timeoutDuration,useMultiStep:_?.useMultiStep,maxMultiStepIterations:_?.maxMultiStepIterations,onStreamChunk:_?.onStreamChunk},W=async(Z)=>{if(P.withEntityContext)return await P.withEntityContext(Y.entityId,Z);else return await Z()};if(!!_?.onResponse){let Z=async(w)=>{try{if(_.onResponse)await _.onResponse(w)}catch(k){if(_.onError)await _.onError(k instanceof Error?k:Error(String(k)))}return[]};return W(()=>P.messageService.handleMessage(P,Y,Z,v)).then(()=>{if(_.onComplete)_.onComplete()}).catch((w)=>{if(_.onError)_.onError(w)}),this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:K,messageId:O,mode:"async"}})),{messageId:O,userMessage:Y}}else{let Z=await W(()=>P.messageService.handleMessage(P,Y,void 0,v));if(_?.onComplete)await _.onComplete();return this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:K,messageId:O,mode:"sync",processing:Z}})),{messageId:O,userMessage:Y,processing:Z}}}async handleMessages($){let q=await Promise.all($.map(async({agentId:_,message:P,options:K})=>{try{let O=await this.handleMessage(_,P,K);return{agentId:_,result:O}}catch(O){return{agentId:_,result:{messageId:P.id||"",userMessage:P},error:O instanceof Error?O:Error(String(O))}}}));return this.dispatchEvent(new CustomEvent("messages:sent",{detail:{results:q,count:$.length}})),q}async validateApiKeys($){let q=new Map,_=$||Array.from(this.runtimes.keys());for(let P of _){let K=this.runtimes.get(P);if(K){let O=!!(K.getSetting("OPENAI_API_KEY")||K.getSetting("ANTHROPIC_API_KEY"));q.set(P,O)}}return q}async healthCheck($){let q=new Map,_=$||Array.from(this.runtimes.keys());for(let P of _){let O={alive:!!this.runtimes.get(P),responsive:!0};if(typeof process<"u")O.memoryUsage=process.memoryUsage().heapUsed,O.uptime=process.uptime();q.set(P,O)}return q}getRuntimeAccessor(){return{getAgent:($)=>this.getAgent($),getAgents:()=>this.getAgents(),getState:($)=>{let q=this.getAgent($);if(!q)return;if(q.stateCache&&q.stateCache.size>0){let _=Array.from(q.stateCache.values());return _[_.length-1]}return}}}enableEditableMode(){this.editableMode=!0,this.dispatchEvent(new CustomEvent("mode:editable",{detail:{editable:!0}}))}}var Na=`# Task: Resolve Entity Name
728
728
  Message Sender: {{senderName}} (ID: {{senderId}})
729
729
  Agent: {{agentName}} (ID: {{agentId}})
730
730
 
@@ -765,5 +765,5 @@ Data: ${JSON.stringify(_.metadata)}
765
765
  `}`}).join(`
766
766
  `)}yZ(xZ());var zJ$=!0,WJ$=!1,HJ$={check:async()=>({status:"not-applicable",environment:"browser"}),isHealthy:()=>!0};export{MQ as validateUuid,RR as validateCharacter,ER as uuidSchema,xv$ as updateWorldSettings,iR as unsaltWorldSettings,wa as unsaltSettingValue,SR as truncateToCompleteSentence,Wj$ as trimTokens,mQ as toString,IR as toHex,gQ as templateTypeSchema,bQ as styleSchema,BY as stringToUuid,zj$ as splitChunks,oQ as slice,DR as shouldRespondTemplate,yQ as settingsSchema,yZ as setStreamingContextManager,yY$ as setEnv,HJ$ as serverHealth,uQ as secretsSchema,Za as saltWorldSettings,Ta as saltSettingValue,Hj$ as safeReplacer,fK as runWithStreamingContext,bY$ as resetEnvironmentCache,t3$ as removeLogListener,a3$ as recentLogs,BQ as randomBytes,Tj$ as prewarmUuidCache,dj$ as postCreationTemplate,W_ as parseKeyValueXml,Jj$ as parseJSONObjectFromText,t7 as parseBooleanFromText,kj$ as parseAndValidateCharacter,fR as normalizeJsonString,yR as multiStepSummaryTemplate,bR as multiStepDecisionTemplate,LR as messageHandlerTemplate,hQ as messageExampleSchema,RQ as mediaSchema,M6 as logger,mY$ as loadEnvFilesWithPrecedence,ZF as loadEnvFile,LQ as knowledgeItemSchema,Gj$ as isValidCharacter,ca as isStreamableModelType,WJ$ as isNode,bj$ as isMessageMetadata,gj$ as isFragmentMetadata,pj$ as isFragmentMemory,Lj$ as isDocumentMetadata,xj$ as isDocumentMemory,yj$ as isDescriptionMetadata,uj$ as isCustomMetadata,HZ as isBuffer,zJ$ as isBrowser,cv$ as initializeOnboarding,pY$ as initBrowserEnvironment,gR as imageDescriptionTemplate,uY$ as hasEnv,pv$ as getWorldSettings,ij$ as getUserServerRole,ua as getTypedService,Ra as getStreamingContextManager,P4 as getStreamingContext,m_ as getSalt,VE as getNumberEnv,cj$ as getMemoryText,CR as getLocalServerUrl,NP as getEnvironment,y_ as getEnv,YJ$ as getEntityDetails,wj$ as getContentTypeFromMimeType,xY$ as getBooleanEnv,cQ as fromString,pQ as fromHex,lQ as fromBytes,VR as formatTimestamp,jj$ as formatPosts,vj$ as formatMessages,OJ$ as formatEntities,Ej$ as formatActions,Cj$ as formatActionNames,Bj$ as findWorldsForOwner,wF as findEnvFile,PJ$ as findEntityByName,XF as findAllEnvFiles,nQ as equals,mv$ as encryptedCharacter,nR as encryptStringValue,a7 as encryptObjectValues,Q3$ as elizaLogger,DQ as directoryItemSchema,MP as detectEnvironment,ov$ as defineService,dv$ as decryptedCharacter,tY as decryptStringValue,tY as decryptSecret,oR as decryptObjectValues,F3$ as customLevels,cY$ as currentRuntime,H_ as createUniqueUuid,Wa as createSettingFromConfig,xa as createServiceError,Xa as createService,Dj$ as createMessageMemory,B7 as createLogger,IQ as contentSchema,rQ as concat,U7 as composePromptFromState,kR as composePrompt,Nj$ as composeActionExamples,uv$ as clearSaltCache,xQ as characterSchema,iQ as byteLength,lj$ as booleanFooter,eY as asUUID,dQ as alloc,U3$ as addLogListener,Oj$ as addHeader,n3$ as __loggerTestHooks,da as VECTOR_DIMS,OI as TeeType,YI as TEEMode,ya as ServiceType,BR as ServiceBuilder,sY as Service,va as Semaphore,jI as SOCKET_MESSAGE_TYPE,qI as Role,PI as PlatformPrefix,A6 as ModelType,_I as MemoryType,dP as MODEL_SETTINGS,na as MESSAGE_STREAM_EVENT,$O as EventType,gw as Environment,Ma as ElizaOS,MZ as DefaultMessageService,tQ as DatabaseAdapter,cP as ContentType,mP as ChannelType,XK as BufferUtils,CZ as BM25,KI as AgentStatus,EZ as AgentRuntime};
767
767
 
768
- //# debugId=DE6F794793A6A0FB64756E2164756E21
768
+ //# debugId=4E3699EC7D8437BF64756E2164756E21
769
769
  //# sourceMappingURL=index.browser.js.map