@elizaos/core 1.6.2-alpha.16 → 1.6.2-alpha.18
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.
|
@@ -601,7 +601,7 @@ ${A.map((X)=>`- ${X}`).join(`
|
|
|
601
601
|
|
|
602
602
|
`)}
|
|
603
603
|
|
|
604
|
-
${$}`}let O={prompt:_,maxTokens:q?.maxTokens,temperature:q?.temperature,frequencyPenalty:q?.frequencyPenalty,presencePenalty:q?.presencePenalty,stopSequences:q?.stopSequences};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 K=Array.isArray($)?$:[$];for(let P of K){let _=this.events[P];if(!_)continue;try{let O={runtime:this};if(typeof q==="object"&&q)O={...q,...O};await Promise.all(_.map((j)=>j(O)))}catch(O){this.logger.error(`Error during emitEvent for ${P} (handler execution): ${O}`)}}}async ensureEmbeddingDimension(){if(this.logger.debug(`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`),!this.adapter)throw Error(`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`);try{if(!this.getModel(Jq.TEXT_EMBEDDING))throw Error(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`);this.logger.debug(`[AgentRuntime][${this.character.name}] Getting embedding dimensions`);let q=await this.useModel(Jq.TEXT_EMBEDDING,null);if(!q||!q.length)throw Error(`[AgentRuntime][${this.character.name}] Invalid embedding received`);this.logger.debug(`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${q.length}`),await this.adapter.ensureEmbeddingDimension(q.length),this.logger.debug(`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`)}catch($){throw this.logger.debug(`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension: ${$}`),$}}registerTaskWorker($){if(this.taskWorkers.has($.name))this.logger.warn(`Task definition ${$.name} already registered. Will be overwritten.`);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(!$.name)throw Error("Agent name is required");let K=(await this.adapter.getAgents()).find((O)=>O.name===$.name)?.id;if(K){let O={...$,id:K,updatedAt:Date.now()};await this.adapter.updateAgent(K,O);let j=await this.adapter.getAgent(K);if(!j)throw Error(`Failed to retrieve agent after update: ${K}`);return this.logger.debug(`Updated existing agent ${$.name} on restart`),j}let P={...$,id:t7($.name)};if(!await this.adapter.createAgent(P))throw Error(`Failed to create agent: ${$.name}`);return this.logger.debug(`Created new agent ${$.name}`),P}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 createEntities($){return $.forEach((q)=>{q.agentId=this.agentId}),await this.adapter.createEntities($)}async updateEntity($){await this.adapter.updateEntity($)}async getComponent($,q,K,P){return await this.adapter.getComponent($,q,K,P)}async getComponents($,q,K){return await this.adapter.getComponents($,q,K)}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(Jq.TEXT_EMBEDDING,{text:q})}catch(K){this.logger.error("Failed to generate embedding:",K),$.embedding=await this.useModel(Jq.TEXT_EMBEDDING,null)}return $}async queueEmbeddingGeneration($,q){if(q=q||"normal",!$)return;if($.embedding)return;if(!$.content?.text){this.logger.debug("Skipping embedding generation for memory without text content");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 K of $)try{let P=await this.adapter.getMemories({agentId:this.agentId,tableName:K,count:1e4});q.push(...P)}catch(P){this.logger.debug(`Failed to get memories from table ${K}: ${P}`)}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 K=q.map((O)=>({title:O.id,content:O.content.text}));return new FH(K).search($,q.length).map((O)=>q[O.index])}async createMemory($,q,K){if(K!==void 0)$.unique=K;return await this.adapter.createMemory($,q,K)}async updateMemory($){return await this.adapter.updateMemory($)}async deleteMemory($){await this.adapter.deleteMemory($)}async deleteManyMemories($){await this.adapter.deleteManyMemories($)}async clearAllAgentMemories(){this.logger.info(`Clearing all memories for agent ${this.character.name} (${this.agentId})`);let q=(await this.getAllMemories()).map((K)=>K.id).filter((K)=>K!==void 0);if(q.length===0){this.logger.info("No memories found to delete");return}this.logger.info(`Found ${q.length} memories to delete`),await this.adapter.deleteManyMemories(q),this.logger.info(`Successfully cleared all ${q.length} memories for agent`)}async deleteAllMemories($,q){await this.adapter.deleteAllMemories($,q)}async countMemories($,q,K){return await this.adapter.countMemories($,q,K)}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:K,type:P,channelId:_,serverId:O,worldId:j}){if(!j)throw Error("worldId is required");let z=await this.adapter.createRooms([{id:$,name:q,source:K,type:P,channelId:_,serverId:O,worldId:j}]);if(!z.length)throw Error("Failed to create room");return z[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,K){await this.adapter.setParticipantUserState($,q,K)}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 K=this.eventHandlers.get($),P=K.indexOf(q);if(P!==-1)K.splice(P,1)}emit($,q){if(!this.eventHandlers.has($))return;for(let K of this.eventHandlers.get($))K(q)}async sendControlMessage($){try{let{roomId:q,action:K,target:P}=$,_={type:"control",payload:{action:K,target:P},roomId:q};await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:_,source:"agent"}),this.logger.debug(`Sent control message: ${K} to room ${q}`)}catch(q){this.logger.error(`Error sending control message: ${q}`)}}registerSendHandler($,q){if(this.sendHandlers.has($))this.logger.warn(`Send handler for source '${$}' already registered. Overwriting.`);this.sendHandlers.set($,q),this.logger.info(`Registered send handler for source: ${$}`)}async sendMessageToTarget($,q){let K=this.sendHandlers.get($.source);if(!K){let P=`No send handler registered for source: ${$.source}`;throw this.logger.error(P),Error(P)}try{await K(this,$,q)}catch(P){throw this.logger.error(`Error executing send handler for source ${$.source}:`,P),P}}async getMemoriesByWorldId($){return await this.adapter.getMemoriesByWorldId($)}async runMigrations($){if(this.adapter&&"runMigrations"in this.adapter)await this.adapter.runMigrations($);else this.logger.warn("Database adapter does not support migrations.")}async isReady(){if(!this.adapter)throw Error("Database adapter not registered");return await this.adapter.isReady()}}SK();function QH($){return Boolean($?.settings?.secrets&&Object.keys($.settings.secrets).length>0)}async function pn($){let q=await import("node:fs"),K=await Promise.resolve().then(() => Iq(zH(),1)),{findEnvFile:P}=await Promise.resolve().then(() => (SK(),sS));if(QH($))return!1;let _=P();if(!_)return!1;try{let O=q.readFileSync(_),j=K.parse(O);if(!$.settings)$.settings={};return $.settings.secrets=j,!0}catch{return!1}}async function oM($){if(I_()!=="node")return!1;return pn($)}import YO from"crypto-browserify";SK();function mn($){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 t4=null,eH=!1,dn=300000;function b_(){let $=VK("SECRET_SALT","secretsalt")||"secretsalt",q=Date.now();if(t4!==null){if(q-t4.timestamp<dn&&t4.value===$)return t4.value}if($==="secretsalt"&&!eH)z6.warn("SECRET_SALT is not set or using default value"),eH=!0;return t4={value:$,timestamp:q},$}function Z7$(){t4=null,eH=!1}function tM($,q){if($===void 0||$===null)return z6.debug("Attempted to encrypt undefined or null value"),$;if(typeof $==="boolean"||typeof $==="number")return z6.debug("Value is a boolean or number, returning as is"),$;if(typeof $!=="string")return z6.debug(`Value is not a string (type: ${typeof $}), returning as is`),$;let K=$.split(":");if(K.length===2)try{if(BK.fromHex(K[0]).length===16)return z6.debug("Value appears to be already encrypted, skipping re-encryption"),$}catch(z){}let P=YO.createHash("sha256").update(q).digest().slice(0,32),_=BK.randomBytes(16),O=YO.createCipheriv("aes-256-cbc",P,_),j=O.update($,"utf8","hex");return j+=O.final("hex"),`${BK.toHex(_)}:${j}`}function OO($,q){try{if($===void 0||$===null)return $;if(typeof $==="boolean"||typeof $==="number")return $;if(typeof $!=="string")return z6.debug(`Value is not a string (type: ${typeof $}), returning as is`),$;let K=$.split(":");if(K.length!==2)return $;let P=BK.fromHex(K[0]),_=K[1];if(P.length!==16){if(P.length)z6.debug(`Invalid IV length (${P.length}) - expected 16 bytes`);return $}let O=YO.createHash("sha256").update(q).digest().slice(0,32),j=YO.createDecipheriv("aes-256-cbc",O,P),z=j.update(_,"hex","utf8");return z+=j.final("utf8"),z}catch(K){return z6.error(`Error decrypting value: ${K}`),$}}function rn($,q){let K={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)K.value=tM($.value,q);return K}function ln($,q){let K={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)K.value=OO($.value,q);return K}function on($,q){let K={};for(let[P,_]of Object.entries($))K[P]=rn(_,q);return K}function BM($,q){let K={};for(let[P,_]of Object.entries($))K[P]=ln(_,q);return K}async function f7$($,q,K){let P=g_($,q),_=await $.getWorld(P);if(!_)return z6.error(`No world found for server ${q}`),!1;if(!_.metadata)_.metadata={};let O=b_(),j=on(K,O);return _.metadata.settings=j,await $.updateWorld(_),!0}async function X7$($,q){let K=g_($,q),P=await $.getWorld(K);if(!P||!P.metadata?.settings)return null;let _=P.metadata.settings,O=b_();return BM(_,O)}async function k7$($,q,K){if(q.metadata?.settings){z6.info(`Onboarding state already exists for server ${q.serverId}`);let _=q.metadata.settings,O=b_();return BM(_,O)}let P={};if(K.settings)for(let[_,O]of Object.entries(K.settings))P[_]=mn(O);if(!q.metadata)q.metadata={};return q.metadata.settings=P,await $.updateWorld(q),z6.info(`Initialized settings config for server ${q.serverId}`),P}function A7$($){let q=JSON.parse(JSON.stringify($)),K=b_();if(q.settings?.secrets)q.settings.secrets=nM(q.settings.secrets,K);if(q.secrets)q.secrets=nM(q.secrets,K);return q}function G7$($,q){let K=JSON.parse(JSON.stringify($)),P=b_();if(K.settings?.secrets)K.settings.secrets=iM(K.settings.secrets,P);if(K.secrets)K.secrets=iM(K.secrets,P);return K}function nM($,q){let K={};for(let[P,_]of Object.entries($))if(typeof _==="string"&&_)K[P]=tM(_,q);else K[P]=_;return K}function iM($,q){let K={};for(let[P,_]of Object.entries($))if(typeof _==="string"&&_)K[P]=OO(_,q);else K[P]=_;return K}class UM{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,K=this.startFn,P=this.stopFn;return class extends HO{static serviceType=$;capabilityDescription=q;static async start(_){if(!K)throw Error(`Start function not defined for service ${$}`);return K(_)}async stop(){if(P)await P()}}}}function nn($){return new UM($)}function M7$($){return nn($.serviceType).withDescription($.description).withStart($.start).withStop($.stop||(()=>Promise.resolve())).build()}SK();var FM=new Set;function tn(){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 Bn($){try{if(!tn())return z6.debug(`Auto-install disabled or not allowed in this environment. Skipping install for ${$}.`),!1;if(FM.has($))return z6.debug(`Auto-install already attempted for ${$}. Skipping.`),!1;if(FM.add($),typeof Bun>"u"||typeof Bun.spawn!=="function")return z6.warn(`Bun runtime not available. Cannot auto-install ${$}. Please run: bun add ${$}`),!1;try{if(await Bun.spawn(["bun","--version"],{stdout:"pipe",stderr:"pipe"}).exited!==0)return z6.warn(`Bun not available on PATH. Cannot auto-install ${$}. Please run: bun add ${$}`),!1}catch{return z6.warn(`Bun not available on PATH. Cannot auto-install ${$}. Please run: bun add ${$}`),!1}z6.info(`Attempting to auto-install missing plugin: ${$}`);let K=await Bun.spawn(["bun","add",$],{cwd:process.cwd(),env:process.env,stdout:"inherit",stderr:"inherit"}).exited;if(K===0)return z6.info(`Successfully installed ${$}. Retrying import...`),!0;return z6.error(`bun add ${$} failed with exit code ${K}. Please install manually.`),!1}catch(q){let K=q instanceof Error?q.message:String(q);return z6.error(`Unexpected error during auto-install of ${$}: ${K}`),!1}}function aM($){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 Un($){let q=[];if(!$)return q.push("Plugin is null or undefined"),{isValid:!1,errors:q};let K=$;if(!K.name)q.push("Plugin must have a name");if(K.actions){if(!Array.isArray(K.actions))q.push("Plugin actions must be an array");else if(K.actions.filter((_)=>typeof _!=="object"||!_).length>0)q.push("Plugin actions must be an array of action objects")}if(K.services){if(!Array.isArray(K.services))q.push("Plugin services must be an array");else if(K.services.filter((_)=>typeof _!=="function"&&(typeof _!=="object"||!_)).length>0)q.push("Plugin services must be an array of service classes or objects")}if(K.providers&&!Array.isArray(K.providers))q.push("Plugin providers must be an array");if(K.evaluators&&!Array.isArray(K.evaluators))q.push("Plugin evaluators must be an array");return{isValid:q.length===0,errors:q}}async function Fn($){try{let q;try{q=await import($)}catch(O){if(z6.warn(`Failed to load plugin ${$}: ${O}`),!await Bn($))return null;try{q=await import($)}catch(z){return z6.error(`Auto-install attempted for ${$} but import still failed: ${z}`),null}}if(!q)return z6.error(`Failed to load module for plugin ${$}.`),null;let K=`${$.replace(/^@elizaos\/plugin-/,"").replace(/^@elizaos\//,"").replace(/-./g,(O)=>O[1].toUpperCase())}Plugin`,P=q,_=[P[K],P.default,...Object.values(P)];for(let O of _){if(aM(O))return O;if(typeof O==="function"&&O.length===0)try{let j=O();if(aM(j))return j}catch(j){z6.debug(`Factory export threw for ${$}: ${j}`)}}return z6.warn(`Could not find a valid plugin export in ${$}.`),null}catch(q){return z6.error(`Error loading plugin ${$}: ${q}`),null}}function QM($,q=!1){let K=[],P=new Set,_=new Set;function O(z){if(!$.has(z)){z6.warn(`Plugin dependency "${z}" not found and will be skipped.`);return}if(P.has(z))return;if(_.has(z)){z6.error(`Circular dependency detected involving plugin: ${z}`);return}_.add(z);let J=$.get(z);if(J){let w=[...J.dependencies||[]];if(q)w.push(...J.testDependencies||[]);for(let A of w)O(A)}_.delete(z),P.add(z),K.push(z)}for(let z of $.keys())if(!P.has(z))O(z);let j=K.map((z)=>$.get(z)).filter((z)=>Boolean(z));return z6.info({plugins:j.map((z)=>z.name)},"Final plugins being loaded:"),j}async function an($){if(typeof $==="string")return Fn($);let q=Un($);if(!q.isValid)return z6.error(`Invalid plugin provided: ${q.errors.join(", ")}`),null;return $}async function Qn($,q=!1){let K=new Map,P=[...$];while(P.length>0){let _=P.shift(),O=await an(_);if(!O)continue;if(!K.has(O.name)){K.set(O.name,O);for(let j of O.dependencies??[])if(!K.has(j))P.push(j);if(q){for(let j of O.testDependencies??[])if(!K.has(j))P.push(j)}}}return QM(K,q)}async function eM($,q=!1){if(I_()==="node")return Qn($,q);let P=$.filter((O)=>typeof O!=="string");if($.some((O)=>typeof O==="string"))z6.warn("Browser environment: String plugin references are not supported. Only Plugin objects will be used. Skipped plugins: "+$.filter((O)=>typeof O==="string").join(", "));let _=new Map;for(let O of P)_.set(O.name,O);return QM(_,q)}class en extends EventTarget{runtimes=new Map;editableMode=!1;async addAgents($,q){let K=$.map(async(_)=>{let O=_.character;if(!QH(O))await oM(O);let j=_.plugins?await eM(_.plugins,q?.isTestMode||!1):[],z=new aH({character:O,plugins:j,settings:_.settings||{}});this.runtimes.set(z.agentId,z);let{settings:J,...w}=O,{secrets:A,...X}=J||{};return this.dispatchEvent(new CustomEvent("agent:added",{detail:{agentId:z.agentId,character:{...w,settings:X}}})),z.agentId}),P=await Promise.all(K);return this.dispatchEvent(new CustomEvent("agents:added",{detail:{agentIds:P,count:P.length}})),P}registerAgent($){if(this.runtimes.has($.agentId))throw Error(`Agent ${$.agentId} already registered`);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 K=this.runtimes.get($);if(!K)throw Error(`Agent ${$} not found`);Object.assign(K.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.dispatchEvent(new CustomEvent("agents:deleted",{detail:{agentIds:$,count:$.length}}))}async startAgents($){let q=$||Array.from(this.runtimes.keys());await Promise.all(q.map(async(K)=>{let P=this.runtimes.get(K);if(!P)throw Error(`Agent ${K} not found`);await P.initialize(),this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:K}}))})),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(K)=>{let P=this.runtimes.get(K);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((K)=>K.toLowerCase()));return this.getAgents().filter((K)=>q.has(K.character.name.toLowerCase()))}getAgentById($){return this.getAgent($)}getAgentByName($){let q=$.toLowerCase();return this.getAgents().find((K)=>K.character.name.toLowerCase()===q)}getAgentByCharacterName($){return this.getAgentByName($)}getAgentByCharacterId($){return this.getAgents().find((q)=>q.character.id===$)}async sendMessage($,q,K){let P=this.runtimes.get($);if(!P)throw Error(`Agent ${$} not found`);let _=typeof q==="string"?{id:a8(),entityId:K?.userId||"system",agentId:$,roomId:K?.roomId||$,content:{text:q},createdAt:Date.now(),metadata:K?.metadata}:q,O=[];return await P.processActions(_,O),this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:$,message:_,responses:O}})),O}async sendMessages($){let q=await Promise.all($.map(async({agentId:K,message:P,options:_})=>{try{let O=await this.sendMessage(K,P,_);return{agentId:K,responses:O}}catch(O){return{agentId:K,responses:[],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,K=$||Array.from(this.runtimes.keys());for(let P of K){let _=this.runtimes.get(P);if(_){let O=!!(_.getSetting("OPENAI_API_KEY")||_.getSetting("ANTHROPIC_API_KEY"));q.set(P,O)}}return q}async healthCheck($){let q=new Map,K=$||Array.from(this.runtimes.keys());for(let P of K){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;let K=q;if(K.stateCache&&K.stateCache.size>0){let P=Array.from(K.stateCache.values());return P[P.length-1]}return}}}enableEditableMode(){this.editableMode=!0,this.dispatchEvent(new CustomEvent("mode:editable",{detail:{editable:!0}}))}}var sn=`# Task: Resolve Entity Name
|
|
604
|
+
${$}`}let O={prompt:_,maxTokens:q?.maxTokens,temperature:q?.temperature,frequencyPenalty:q?.frequencyPenalty,presencePenalty:q?.presencePenalty,stopSequences:q?.stopSequences};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 K=Array.isArray($)?$:[$];for(let P of K){let _=this.events[P];if(!_)continue;try{let O={runtime:this};if(typeof q==="object"&&q)O={...q,...O};await Promise.all(_.map((j)=>j(O)))}catch(O){this.logger.error(`Error during emitEvent for ${P} (handler execution): ${O}`)}}}async ensureEmbeddingDimension(){if(this.logger.debug(`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`),!this.adapter)throw Error(`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`);try{if(!this.getModel(Jq.TEXT_EMBEDDING))throw Error(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`);this.logger.debug(`[AgentRuntime][${this.character.name}] Getting embedding dimensions`);let q=await this.useModel(Jq.TEXT_EMBEDDING,null);if(!q||!q.length)throw Error(`[AgentRuntime][${this.character.name}] Invalid embedding received`);this.logger.debug(`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${q.length}`),await this.adapter.ensureEmbeddingDimension(q.length),this.logger.debug(`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`)}catch($){throw this.logger.debug(`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension: ${$}`),$}}registerTaskWorker($){if(this.taskWorkers.has($.name))this.logger.warn(`Task definition ${$.name} already registered. Will be overwritten.`);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(!$.name)throw Error("Agent name is required");let K=(await this.adapter.getAgents()).find((O)=>O.name===$.name)?.id;if(K){let O={...$,id:K,updatedAt:Date.now()};await this.adapter.updateAgent(K,O);let j=await this.adapter.getAgent(K);if(!j)throw Error(`Failed to retrieve agent after update: ${K}`);return this.logger.debug(`Updated existing agent ${$.name} on restart`),j}let P={...$,id:t7($.name)};if(!await this.adapter.createAgent(P))throw Error(`Failed to create agent: ${$.name}`);return this.logger.debug(`Created new agent ${$.name}`),P}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 createEntities($){return $.forEach((q)=>{q.agentId=this.agentId}),await this.adapter.createEntities($)}async updateEntity($){await this.adapter.updateEntity($)}async getComponent($,q,K,P){return await this.adapter.getComponent($,q,K,P)}async getComponents($,q,K){return await this.adapter.getComponents($,q,K)}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(Jq.TEXT_EMBEDDING,{text:q})}catch(K){this.logger.error("Failed to generate embedding:",K),$.embedding=await this.useModel(Jq.TEXT_EMBEDDING,null)}return $}async queueEmbeddingGeneration($,q){if(q=q||"normal",!$)return;if($.embedding)return;if(!$.content?.text){this.logger.debug("Skipping embedding generation for memory without text content");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 K of $)try{let P=await this.adapter.getMemories({agentId:this.agentId,tableName:K,count:1e4});q.push(...P)}catch(P){this.logger.debug(`Failed to get memories from table ${K}: ${P}`)}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 K=q.map((O)=>({title:O.id,content:O.content.text}));return new FH(K).search($,q.length).map((O)=>q[O.index])}async createMemory($,q,K){if(K!==void 0)$.unique=K;return await this.adapter.createMemory($,q,K)}async updateMemory($){return await this.adapter.updateMemory($)}async deleteMemory($){await this.adapter.deleteMemory($)}async deleteManyMemories($){await this.adapter.deleteManyMemories($)}async clearAllAgentMemories(){this.logger.info(`Clearing all memories for agent ${this.character.name} (${this.agentId})`);let q=(await this.getAllMemories()).map((K)=>K.id).filter((K)=>K!==void 0);if(q.length===0){this.logger.info("No memories found to delete");return}this.logger.info(`Found ${q.length} memories to delete`),await this.adapter.deleteManyMemories(q),this.logger.info(`Successfully cleared all ${q.length} memories for agent`)}async deleteAllMemories($,q){await this.adapter.deleteAllMemories($,q)}async countMemories($,q,K){return await this.adapter.countMemories($,q,K)}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:K,type:P,channelId:_,serverId:O,worldId:j}){if(!j)throw Error("worldId is required");let z=await this.adapter.createRooms([{id:$,name:q,source:K,type:P,channelId:_,serverId:O,worldId:j}]);if(!z.length)throw Error("Failed to create room");return z[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,K){await this.adapter.setParticipantUserState($,q,K)}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 K=this.eventHandlers.get($),P=K.indexOf(q);if(P!==-1)K.splice(P,1)}emit($,q){if(!this.eventHandlers.has($))return;for(let K of this.eventHandlers.get($))K(q)}async sendControlMessage($){try{let{roomId:q,action:K,target:P}=$,_={type:"control",payload:{action:K,target:P},roomId:q};await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:_,source:"agent"}),this.logger.debug(`Sent control message: ${K} to room ${q}`)}catch(q){this.logger.error(`Error sending control message: ${q}`)}}registerSendHandler($,q){if(this.sendHandlers.has($))this.logger.warn(`Send handler for source '${$}' already registered. Overwriting.`);this.sendHandlers.set($,q),this.logger.info(`Registered send handler for source: ${$}`)}async sendMessageToTarget($,q){let K=this.sendHandlers.get($.source);if(!K){let P=`No send handler registered for source: ${$.source}`;throw this.logger.error(P),Error(P)}try{await K(this,$,q)}catch(P){throw this.logger.error(`Error executing send handler for source ${$.source}:`,P),P}}async getMemoriesByWorldId($){return await this.adapter.getMemoriesByWorldId($)}async runMigrations($){if(this.adapter&&"runMigrations"in this.adapter)await this.adapter.runMigrations($);else this.logger.warn("Database adapter does not support migrations.")}async isReady(){if(!this.adapter)throw Error("Database adapter not registered");return await this.adapter.isReady()}}SK();function QH($){return Boolean($?.settings?.secrets&&Object.keys($.settings.secrets).length>0)}async function pn($){let q=await import("node:fs"),K=await Promise.resolve().then(() => Iq(zH(),1)),{findEnvFile:P}=await Promise.resolve().then(() => (SK(),sS));if(QH($))return!1;let _=P();if(!_)return!1;try{let O=q.readFileSync(_),j=K.parse(O);if(!$.settings)$.settings={};return $.settings.secrets=j,!0}catch{return!1}}async function oM($){if(I_()!=="node")return!1;return pn($)}import YO from"crypto-browserify";SK();function mn($){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 t4=null,eH=!1,dn=300000;function b_(){let $=VK("SECRET_SALT","secretsalt")||"secretsalt",q=Date.now();if(t4!==null){if(q-t4.timestamp<dn&&t4.value===$)return t4.value}if($==="secretsalt"&&!eH)z6.warn("SECRET_SALT is not set or using default value"),eH=!0;return t4={value:$,timestamp:q},$}function Z7$(){t4=null,eH=!1}function tM($,q){if($===void 0||$===null)return z6.debug("Attempted to encrypt undefined or null value"),$;if(typeof $==="boolean"||typeof $==="number")return z6.debug("Value is a boolean or number, returning as is"),$;if(typeof $!=="string")return z6.debug(`Value is not a string (type: ${typeof $}), returning as is`),$;let K=$.split(":");if(K.length===2)try{if(BK.fromHex(K[0]).length===16)return z6.debug("Value appears to be already encrypted, skipping re-encryption"),$}catch(z){}let P=YO.createHash("sha256").update(q).digest().slice(0,32),_=BK.randomBytes(16),O=YO.createCipheriv("aes-256-cbc",P,_),j=O.update($,"utf8","hex");return j+=O.final("hex"),`${BK.toHex(_)}:${j}`}function OO($,q){try{if($===void 0||$===null)return $;if(typeof $==="boolean"||typeof $==="number")return $;if(typeof $!=="string")return z6.debug(`Value is not a string (type: ${typeof $}), returning as is`),$;let K=$.split(":");if(K.length!==2)return $;let P=BK.fromHex(K[0]),_=K[1];if(P.length!==16){if(P.length)z6.debug(`Invalid IV length (${P.length}) - expected 16 bytes`);return $}let O=YO.createHash("sha256").update(q).digest().slice(0,32),j=YO.createDecipheriv("aes-256-cbc",O,P),z=j.update(_,"hex","utf8");return z+=j.final("utf8"),z}catch(K){return z6.error(`Error decrypting value: ${K}`),$}}function rn($,q){let K={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)K.value=tM($.value,q);return K}function ln($,q){let K={...$};if($.secret===!0&&typeof $.value==="string"&&$.value)K.value=OO($.value,q);return K}function on($,q){let K={};for(let[P,_]of Object.entries($))K[P]=rn(_,q);return K}function BM($,q){let K={};for(let[P,_]of Object.entries($))K[P]=ln(_,q);return K}async function f7$($,q,K){let P=g_($,q),_=await $.getWorld(P);if(!_)return z6.error(`No world found for server ${q}`),!1;if(!_.metadata)_.metadata={};let O=b_(),j=on(K,O);return _.metadata.settings=j,await $.updateWorld(_),!0}async function X7$($,q){let K=g_($,q),P=await $.getWorld(K);if(!P||!P.metadata?.settings)return null;let _=P.metadata.settings,O=b_();return BM(_,O)}async function k7$($,q,K){if(q.metadata?.settings){z6.info(`Onboarding state already exists for server ${q.serverId}`);let _=q.metadata.settings,O=b_();return BM(_,O)}let P={};if(K.settings)for(let[_,O]of Object.entries(K.settings))P[_]=mn(O);if(!q.metadata)q.metadata={};return q.metadata.settings=P,await $.updateWorld(q),z6.info(`Initialized settings config for server ${q.serverId}`),P}function A7$($){let q=JSON.parse(JSON.stringify($)),K=b_();if(q.settings?.secrets)q.settings.secrets=nM(q.settings.secrets,K);if(q.secrets)q.secrets=nM(q.secrets,K);return q}function G7$($,q){let K=JSON.parse(JSON.stringify($)),P=b_();if(K.settings?.secrets)K.settings.secrets=iM(K.settings.secrets,P);if(K.secrets)K.secrets=iM(K.secrets,P);return K}function nM($,q){let K={};for(let[P,_]of Object.entries($))if(typeof _==="string"&&_)K[P]=tM(_,q);else K[P]=_;return K}function iM($,q){let K={};for(let[P,_]of Object.entries($))if(typeof _==="string"&&_)K[P]=OO(_,q);else K[P]=_;return K}class UM{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,K=this.startFn,P=this.stopFn;return class extends HO{static serviceType=$;capabilityDescription=q;static async start(_){if(!K)throw Error(`Start function not defined for service ${$}`);return K(_)}async stop(){if(P)await P()}}}}function nn($){return new UM($)}function M7$($){return nn($.serviceType).withDescription($.description).withStart($.start).withStop($.stop||(()=>Promise.resolve())).build()}SK();var FM=new Set;function tn(){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 Bn($){try{if(!tn())return z6.debug(`Auto-install disabled or not allowed in this environment. Skipping install for ${$}.`),!1;if(FM.has($))return z6.debug(`Auto-install already attempted for ${$}. Skipping.`),!1;if(FM.add($),typeof Bun>"u"||typeof Bun.spawn!=="function")return z6.warn(`Bun runtime not available. Cannot auto-install ${$}. Please run: bun add ${$}`),!1;try{if(await Bun.spawn(["bun","--version"],{stdout:"pipe",stderr:"pipe"}).exited!==0)return z6.warn(`Bun not available on PATH. Cannot auto-install ${$}. Please run: bun add ${$}`),!1}catch{return z6.warn(`Bun not available on PATH. Cannot auto-install ${$}. Please run: bun add ${$}`),!1}z6.info(`Attempting to auto-install missing plugin: ${$}`);let K=await Bun.spawn(["bun","add",$],{cwd:process.cwd(),env:process.env,stdout:"inherit",stderr:"inherit"}).exited;if(K===0)return z6.info(`Successfully installed ${$}. Retrying import...`),!0;return z6.error(`bun add ${$} failed with exit code ${K}. Please install manually.`),!1}catch(q){let K=q instanceof Error?q.message:String(q);return z6.error(`Unexpected error during auto-install of ${$}: ${K}`),!1}}function aM($){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 Un($){let q=[];if(!$)return q.push("Plugin is null or undefined"),{isValid:!1,errors:q};let K=$;if(!K.name)q.push("Plugin must have a name");if(K.actions){if(!Array.isArray(K.actions))q.push("Plugin actions must be an array");else if(K.actions.filter((_)=>typeof _!=="object"||!_).length>0)q.push("Plugin actions must be an array of action objects")}if(K.services){if(!Array.isArray(K.services))q.push("Plugin services must be an array");else if(K.services.filter((_)=>typeof _!=="function"&&(typeof _!=="object"||!_)).length>0)q.push("Plugin services must be an array of service classes or objects")}if(K.providers&&!Array.isArray(K.providers))q.push("Plugin providers must be an array");if(K.evaluators&&!Array.isArray(K.evaluators))q.push("Plugin evaluators must be an array");return{isValid:q.length===0,errors:q}}async function Fn($){try{let q;try{q=await import($)}catch(O){if(z6.warn(`Failed to load plugin ${$}: ${O}`),!await Bn($))return null;try{q=await import($)}catch(z){return z6.error(`Auto-install attempted for ${$} but import still failed: ${z}`),null}}if(!q)return z6.error(`Failed to load module for plugin ${$}.`),null;let K=`${$.replace(/^@elizaos\/plugin-/,"").replace(/^@elizaos\//,"").replace(/-./g,(O)=>O[1].toUpperCase())}Plugin`,P=q,_=[P[K],P.default,...Object.values(P)];for(let O of _){if(aM(O))return O;if(typeof O==="function"&&O.length===0)try{let j=O();if(aM(j))return j}catch(j){z6.debug(`Factory export threw for ${$}: ${j}`)}}return z6.warn(`Could not find a valid plugin export in ${$}.`),null}catch(q){return z6.error(`Error loading plugin ${$}: ${q}`),null}}function QM($,q=!1){let K=[],P=new Set,_=new Set;function O(z){if(!$.has(z)){z6.warn(`Plugin dependency "${z}" not found and will be skipped.`);return}if(P.has(z))return;if(_.has(z)){z6.error(`Circular dependency detected involving plugin: ${z}`);return}_.add(z);let J=$.get(z);if(J){let w=[...J.dependencies||[]];if(q)w.push(...J.testDependencies||[]);for(let A of w)O(A)}_.delete(z),P.add(z),K.push(z)}for(let z of $.keys())if(!P.has(z))O(z);let j=K.map((z)=>$.get(z)).filter((z)=>Boolean(z));return z6.info({plugins:j.map((z)=>z.name)},"Final plugins being loaded:"),j}async function an($){if(typeof $==="string")return Fn($);let q=Un($);if(!q.isValid)return z6.error(`Invalid plugin provided: ${q.errors.join(", ")}`),null;return $}async function Qn($,q=!1){let K=new Map,P=[...$];while(P.length>0){let _=P.shift(),O=await an(_);if(!O)continue;if(!K.has(O.name)){K.set(O.name,O);for(let j of O.dependencies??[])if(!K.has(j))P.push(j);if(q){for(let j of O.testDependencies??[])if(!K.has(j))P.push(j)}}}return QM(K,q)}async function eM($,q=!1){if(I_()==="node")return Qn($,q);let P=$.filter((O)=>typeof O!=="string");if($.some((O)=>typeof O==="string"))z6.warn("Browser environment: String plugin references are not supported. Only Plugin objects will be used. Skipped plugins: "+$.filter((O)=>typeof O==="string").join(", "));let _=new Map;for(let O of P)_.set(O.name,O);return QM(_,q)}class en extends EventTarget{runtimes=new Map;initFunctions=new Map;editableMode=!1;async addAgents($,q){let K=$.map(async(_)=>{let O=_.character;if(!QH(O))await oM(O);let j=_.plugins?await eM(_.plugins,q?.isTestMode||!1):[],z=new aH({character:O,plugins:j,settings:_.settings||{}});if(this.runtimes.set(z.agentId,z),typeof _.init==="function")this.initFunctions.set(z.agentId,_.init);let{settings:J,...w}=O,{secrets:A,...X}=J||{};return this.dispatchEvent(new CustomEvent("agent:added",{detail:{agentId:z.agentId,character:{...w,settings:X}}})),z.agentId}),P=await Promise.all(K);return this.dispatchEvent(new CustomEvent("agents:added",{detail:{agentIds:P,count:P.length}})),P}registerAgent($){if(this.runtimes.has($.agentId))throw Error(`Agent ${$.agentId} already registered`);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 K=this.runtimes.get($);if(!K)throw Error(`Agent ${$} not found`);Object.assign(K.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(K)=>{let P=this.runtimes.get(K);if(!P)throw Error(`Agent ${K} not found`);await P.initialize(),this.dispatchEvent(new CustomEvent("agent:started",{detail:{agentId:K}}))}));for(let K of q){let P=this.initFunctions.get(K);if(P){let _=this.runtimes.get(K);if(_)await P(_),this.initFunctions.delete(K)}}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(K)=>{let P=this.runtimes.get(K);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((K)=>K.toLowerCase()));return this.getAgents().filter((K)=>q.has(K.character.name.toLowerCase()))}getAgentById($){return this.getAgent($)}getAgentByName($){let q=$.toLowerCase();return this.getAgents().find((K)=>K.character.name.toLowerCase()===q)}getAgentByCharacterName($){return this.getAgentByName($)}getAgentByCharacterId($){return this.getAgents().find((q)=>q.character.id===$)}async sendMessage($,q,K){let P=this.runtimes.get($);if(!P)throw Error(`Agent ${$} not found`);let _=typeof q==="string"?{id:a8(),entityId:K?.userId||"system",agentId:$,roomId:K?.roomId||$,content:{text:q},createdAt:Date.now(),metadata:K?.metadata}:q,O=[];return await P.processActions(_,O),this.dispatchEvent(new CustomEvent("message:sent",{detail:{agentId:$,message:_,responses:O}})),O}async sendMessages($){let q=await Promise.all($.map(async({agentId:K,message:P,options:_})=>{try{let O=await this.sendMessage(K,P,_);return{agentId:K,responses:O}}catch(O){return{agentId:K,responses:[],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,K=$||Array.from(this.runtimes.keys());for(let P of K){let _=this.runtimes.get(P);if(_){let O=!!(_.getSetting("OPENAI_API_KEY")||_.getSetting("ANTHROPIC_API_KEY"));q.set(P,O)}}return q}async healthCheck($){let q=new Map,K=$||Array.from(this.runtimes.keys());for(let P of K){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;let K=q;if(K.stateCache&&K.stateCache.size>0){let P=Array.from(K.stateCache.values());return P[P.length-1]}return}}}enableEditableMode(){this.editableMode=!0,this.dispatchEvent(new CustomEvent("mode:editable",{detail:{editable:!0}}))}}var sn=`# Task: Resolve Entity Name
|
|
605
605
|
Message Sender: {{senderName}} (ID: {{senderId}})
|
|
606
606
|
Agent: {{agentName}} (ID: {{agentId}})
|
|
607
607
|
|
|
@@ -642,5 +642,5 @@ Data: ${JSON.stringify(K.metadata)}
|
|
|
642
642
|
`}`}).join(`
|
|
643
643
|
`)}var l7$=!0,o7$=!1,n7$={check:async()=>({status:"not-applicable",environment:"browser"}),isHealthy:()=>!0};export{$n as validateUuid,mM as validateCharacter,pM as uuidSchema,f7$ as updateWorldSettings,BM as unsaltWorldSettings,ln as unsaltSettingValue,Q4$ as truncateToCompleteSentence,s4$ as trimTokens,fn as toString,dM as toHex,zn as templateTypeSchema,Wn as styleSchema,t7 as stringToUuid,e4$ as splitChunks,Vn as slice,RP$ as shouldRespondTemplate,Hn as settingsSchema,Go as setEnv,n7$ as serverHealth,Jn as secretsSchema,on as saltWorldSettings,rn as saltSettingValue,oH as safeReplacer,c4$ as recentLogs,Nn as randomBytes,qP$ as prewarmUuidCache,DP$ as postCreationTemplate,yM as parseKeyValueXml,a4$ as parseJSONObjectFromText,$P$ as parseBooleanFromText,vP$ as parseAndValidateCharacter,DM as normalizeJsonString,uP$ as multiStepSummaryTemplate,bP$ as multiStepDecisionTemplate,IP$ as messageHandlerTemplate,On as messageExampleSchema,Pn as mediaSchema,z6 as logger,Co as loadEnvConfig,vn as knowledgeItemSchema,zP$ as isValidCharacter,o7$ as isNode,VP$ as isMessageMetadata,GP$ as isFragmentMetadata,CP$ as isFragmentMemory,AP$ as isDocumentMetadata,NP$ as isDocumentMemory,SP$ as isDescriptionMetadata,MP$ as isCustomMetadata,Xn as isBuffer,l7$ as isBrowser,k7$ as initializeOnboarding,Mo as initBrowserEnvironment,gP$ as imageDescriptionTemplate,Vo as hasEnv,X7$ as getWorldSettings,pP$ as getUserServerRole,vi as getTypedService,b_ as getSalt,JH as getNumberEnv,EP$ as getMemoryText,_P$ as getLocalServerUrl,D_ as getEnvironment,VK as getEnv,m7$ as getEntityDetails,KP$ as getContentTypeFromMimeType,So as getBooleanEnv,Zn as fromString,wn as fromHex,An as fromBytes,uM as formatTimestamp,U4$ as formatPosts,F4$ as formatMessages,d7$ as formatEntities,ZP$ as formatActions,wP$ as formatActionNames,mP$ as findWorldsForOwner,eS as findEnvFile,p7$ as findEntityByName,Sn as equals,A7$ as encryptedCharacter,tM as encryptStringValue,nM as encryptObjectValues,x4$ as elizaLogger,Yn as directoryItemSchema,I_ as detectEnvironment,M7$ as defineService,G7$ as decryptedCharacter,OO as decryptStringValue,OO as decryptSecret,iM as decryptObjectValues,y4$ as customLevels,No as currentRuntime,g_ as createUniqueUuid,mn as createSettingFromConfig,zi as createServiceError,nn as createService,kP$ as createMessageMemory,i7 as createLogger,jn as contentSchema,Gn as concat,t4$ as composePromptFromState,gM as composePrompt,TP$ as composeActionExamples,Z7$ as clearSaltCache,Tn as characterSchema,Mn as byteLength,LP$ as booleanFooter,Ki as asUUID,kn as alloc,B4$ as addHeader,g4$ as __loggerTestHooks,Ji as VECTOR_DIMS,Y0 as TeeType,O0 as TEEMode,Yi as ServiceType,UM as ServiceBuilder,HO as Service,cn as Semaphore,v0 as SOCKET_MESSAGE_TYPE,_0 as Role,j0 as PlatformPrefix,Jq as ModelType,K0 as MemoryType,U4 as MODEL_SETTINGS,KJ as EventType,HH as Environment,en as ElizaOS,En as DatabaseAdapter,B7 as ContentType,U7 as ChannelType,BK as BufferUtils,FH as BM25,P0 as AgentStatus,aH as AgentRuntime};
|
|
644
644
|
|
|
645
|
-
//# debugId=
|
|
645
|
+
//# debugId=95EBC37A1E66A7BC64756E2164756E21
|
|
646
646
|
//# sourceMappingURL=index.browser.js.map
|