@elizaos/core 1.0.0-alpha.2 → 1.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/actions.ts","../src/database.ts","../src/prompts.ts","../src/logger.ts","../src/entities.ts","../src/environment.ts","../../../node_modules/zod/lib/index.mjs","../src/import.ts","../src/memory.ts","../src/roles.ts","../src/runtime.ts","../src/bootstrap.ts","../src/actions/choice.ts","../src/actions/followRoom.ts","../src/actions/ignore.ts","../src/actions/muteRoom.ts","../src/actions/none.ts","../src/actions/reply.ts","../src/actions/roles.ts","../src/actions/sendMessage.ts","../src/actions/settings.ts","../src/actions/unfollowRoom.ts","../src/actions/unmuteRoom.ts","../src/actions/updateEntity.ts","../src/evaluators/goal.ts","../src/evaluators/reflection.ts","../src/providers/providers.ts","../src/providers/actionExamples.ts","../src/providers/anxiety.ts","../src/providers/attachments.ts","../src/providers/capabilities.ts","../src/providers/character.ts","../src/providers/choice.ts","../src/providers/entities.ts","../src/providers/evaluators.ts","../src/providers/facts.ts","../src/providers/knowledge.ts","../src/providers/recentMessages.ts","../src/providers/relationships.ts","../src/providers/roles.ts","../src/settings.ts","../src/providers/settings.ts","../src/providers/time.ts","../src/services/task.ts","../src/services/scenario.ts","../src/uuid.ts"],"sourcesContent":["/**\n * Represents a UUID string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n */\nexport type UUID = `${string}-${string}-${string}-${string}-${string}`;\n\n/**\n * Represents the content of a message or communication\n */\nexport interface Content {\n\tthought?: string;\n\n\t/** The agent's plan for the next message */\n\tplan?: string;\n\n\t/** The main text content */\n\ttext?: string;\n\n\t/** Optional action associated with the message */\n\tactions?: string[];\n\n\t/** Optional providers associated with the message */\n\tproviders?: string[];\n\n\t/** Optional source/origin of the content */\n\tsource?: string;\n\n\t/** URL of the original message/post (e.g. tweet URL, Discord message link) */\n\turl?: string;\n\n\t/** UUID of parent message if this is a reply/thread */\n\tinReplyTo?: UUID;\n\n\t/** Array of media attachments */\n\tattachments?: Media[];\n\n\t/** Additional dynamic properties */\n\t[key: string]: unknown;\n}\n\n/**\n * Example content with associated user for demonstration purposes\n */\nexport interface ActionExample {\n\t/** User associated with the example */\n\tname: string;\n\n\t/** Content of the example */\n\tcontent: Content;\n}\n\n/**\n * Example conversation content with user ID\n */\nexport interface ConversationExample {\n\t/** UUID of user in conversation */\n\tentityId: UUID;\n\n\t/** Content of the conversation */\n\tcontent: Content;\n}\n\n/**\n * Represents a single objective within a goal\n */\nexport interface Objective {\n\t/** Optional unique identifier */\n\tid?: string;\n\n\t/** Description of what needs to be achieved */\n\tdescription: string;\n\n\t/** Whether objective is completed */\n\tcompleted: boolean;\n}\n\n/**\n * Status enum for goals\n */\nexport enum GoalStatus {\n\tDONE = \"DONE\",\n\tFAILED = \"FAILED\",\n\tIN_PROGRESS = \"IN_PROGRESS\",\n}\n\n/**\n * Represents a high-level goal composed of objectives\n */\nexport interface Goal {\n\t/** Optional unique identifier */\n\tid?: UUID;\n\n\t/** Room ID where goal exists */\n\troomId: UUID;\n\n\t/** User ID of goal owner */\n\tentityId: UUID;\n\n\t/** Name/title of the goal */\n\tname: string;\n\n\t/** Current status */\n\tstatus: GoalStatus;\n\n\t/** Component objectives */\n\tobjectives: Objective[];\n}\n\nexport type ModelType = (typeof ModelTypes)[keyof typeof ModelTypes] | string;\n\n/**\n * Model size/type classification\n */\nexport const ModelTypes = {\n\tSMALL: \"text_small\", // kept for backwards compatibility\n\tMEDIUM: \"text_large\", // kept for backwards compatibility\n\tLARGE: \"text_large\", // kept for backwards compatibility\n\tTEXT_SMALL: \"text_small\",\n\tTEXT_LARGE: \"text_large\",\n\tTEXT_EMBEDDING: \"text_embedding\",\n\tTEXT_TOKENIZER_ENCODE: \"TEXT_TOKENIZER_ENCODE\",\n\tTEXT_TOKENIZER_DECODE: \"TEXT_TOKENIZER_DECODE\",\n\tTEXT_REASONING_SMALL: \"reasoning_small\",\n\tTEXT_REASONING_LARGE: \"reasoning_large\",\n\tIMAGE: \"image\",\n\tIMAGE_DESCRIPTION: \"image_description\",\n\tTRANSCRIPTION: \"transcription\",\n\tTEXT_TO_SPEECH: \"text_to_speech\",\n\tAUDIO: \"audio\",\n\tVIDEO: \"video\",\n} as const;\n\nexport type ServiceType = (typeof ServiceTypes)[keyof typeof ServiceTypes];\n\nexport const ServiceTypes = {\n\tTRANSCRIPTION: \"transcription\",\n\tVIDEO: \"video\",\n\tBROWSER: \"browser\",\n\tPDF: \"pdf\",\n\tREMOTE_FILES: \"aws_s3\",\n\tWEB_SEARCH: \"web_search\",\n\tEMAIL: \"email\",\n\tTEE: \"tee\",\n\tTASK: \"task\",\n} as const;\n\n/**\n * Represents the current state/context of a conversation\n */\nexport interface State {\n\t/** Additional dynamic properties */\n\t[key: string]: any;\n\tvalues: {\n\t\t[key: string]: any;\n\t};\n\tdata: {\n\t\t[key: string]: any;\n\t};\n\ttext: string;\n}\n\nexport type MemoryTypeAlias = string;\n\nexport enum MemoryType {\n\tDOCUMENT = \"document\",\n\tFRAGMENT = \"fragment\",\n\tMESSAGE = \"message\",\n\tDESCRIPTION = \"description\",\n\tCUSTOM = \"custom\",\n}\n\nexport interface BaseMetadata {\n\ttype: MemoryTypeAlias;\n\tsource?: string;\n\tsourceId?: UUID;\n\tscope?: string;\n\ttimestamp?: number;\n\ttags?: string[];\n}\n\nexport interface DocumentMetadata extends BaseMetadata {\n\ttype: MemoryType.DOCUMENT;\n}\n\nexport interface FragmentMetadata extends BaseMetadata {\n\ttype: MemoryType.FRAGMENT;\n\tdocumentId: UUID;\n\tposition: number;\n}\n\nexport interface MessageMetadata extends BaseMetadata {\n\ttype: MemoryType.MESSAGE;\n}\n\nexport interface DescriptionMetadata extends BaseMetadata {\n\ttype: MemoryType.DESCRIPTION;\n}\n\nexport interface CustomMetadata extends BaseMetadata {\n\ttype: MemoryTypeAlias;\n\t[key: string]: unknown;\n}\n\nexport type MemoryMetadata =\n\t| DocumentMetadata\n\t| FragmentMetadata\n\t| MessageMetadata\n\t| DescriptionMetadata\n\t| CustomMetadata\n\t| any;\n\n/**\n * Represents a stored memory/message\n */\nexport interface Memory {\n\t/** Optional unique identifier */\n\tid?: UUID;\n\n\t/** Associated user ID */\n\tentityId: UUID;\n\n\t/** Associated agent ID */\n\tagentId?: UUID;\n\n\t/** Optional creation timestamp */\n\tcreatedAt?: number;\n\n\t/** Memory content */\n\tcontent: Content;\n\n\t/** Optional embedding vector */\n\tembedding?: number[];\n\n\t/** Associated room ID */\n\troomId: UUID;\n\n\t/** Whether memory is unique */\n\tunique?: boolean;\n\n\t/** Embedding similarity score */\n\tsimilarity?: number;\n\n\t/** Metadata for the knowledge */\n\tmetadata?: MemoryMetadata;\n}\n\n/**\n * Example message for demonstration\n */\nexport interface MessageExample {\n\t/** Associated user */\n\tname: string;\n\n\t/** Message content */\n\tcontent: Content;\n}\n\n/**\n * Handler function type for processing messages\n */\nexport type Handler = (\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate?: State,\n\toptions?: { [key: string]: unknown },\n\tcallback?: HandlerCallback,\n\tresponses?: Memory[],\n) => Promise<unknown>;\n\n/**\n * Callback function type for handlers\n */\nexport type HandlerCallback = (\n\tresponse: Content,\n\tfiles?: any,\n) => Promise<Memory[]>;\n\n/**\n * Validator function type for actions/evaluators\n */\nexport type Validator = (\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate?: State,\n) => Promise<boolean>;\n\n/**\n * Represents an action the agent can perform\n */\nexport interface Action {\n\t/** Similar action descriptions */\n\tsimiles?: string[];\n\n\t/** Detailed description */\n\tdescription: string;\n\n\t/** Example usages */\n\texamples?: ActionExample[][];\n\n\t/** Handler function */\n\thandler: Handler;\n\n\t/** Action name */\n\tname: string;\n\n\t/** Validation function */\n\tvalidate: Validator;\n}\n\n/**\n * Example for evaluating agent behavior\n */\nexport interface EvaluationExample {\n\t/** Evaluation context */\n\tprompt: string;\n\n\t/** Example messages */\n\tmessages: Array<ActionExample>;\n\n\t/** Expected outcome */\n\toutcome: string;\n}\n\n/**\n * Evaluator for assessing agent responses\n */\nexport interface Evaluator {\n\t/** Whether to always run */\n\talwaysRun?: boolean;\n\n\t/** Detailed description */\n\tdescription: string;\n\n\t/** Similar evaluator descriptions */\n\tsimiles?: string[];\n\n\t/** Example evaluations */\n\texamples: EvaluationExample[];\n\n\t/** Handler function */\n\thandler: Handler;\n\n\t/** Evaluator name */\n\tname: string;\n\n\t/** Validation function */\n\tvalidate: Validator;\n}\n\nexport interface ProviderResult {\n\tvalues?: {\n\t\t[key: string]: any;\n\t};\n\tdata?: {\n\t\t[key: string]: any;\n\t};\n\ttext?: string;\n}\n\n/**\n * Provider for external data/services\n */\nexport interface Provider {\n\t/** Provider name */\n\tname: string;\n\n\t/** Description of the provider */\n\tdescription?: string;\n\n\t/** Whether the provider is dynamic */\n\tdynamic?: boolean;\n\n\t/** Position of the provider in the provider list, positive or negative */\n\tposition?: number;\n\n\t/**\n\t * Whether the provider is private\n\t *\n\t * Private providers are not displayed in the regular provider list, they have to be called explicitly\n\t */\n\tprivate?: boolean;\n\n\t/** Data retrieval function */\n\tget: (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t) => Promise<ProviderResult>;\n}\n\n/**\n * Represents a relationship between users\n */\nexport interface Relationship {\n\t/** Unique identifier */\n\tid: UUID;\n\n\t/** First user ID */\n\tsourceEntityId: UUID;\n\n\t/** Second user ID */\n\ttargetEntityId: UUID;\n\n\t/** Agent ID */\n\tagentId: UUID;\n\n\t/** Tags for filtering/categorizing relationships */\n\ttags: string[];\n\n\t/** Additional metadata about the relationship */\n\tmetadata: {\n\t\t[key: string]: any;\n\t};\n\n\t/** Optional creation timestamp */\n\tcreatedAt?: string;\n}\n\nexport interface Component {\n\tid: UUID;\n\tentityId: UUID;\n\tagentId: UUID;\n\troomId: UUID;\n\tworldId: UUID;\n\tsourceEntityId: UUID;\n\ttype: string;\n\tdata: {\n\t\t[key: string]: any;\n\t};\n}\n\n/**\n * Represents a user account\n */\nexport interface Entity {\n\t/** Unique identifier, optional on creation */\n\tid?: UUID;\n\n\t/** Names of the entity */\n\tnames: string[];\n\n\t/** Optional additional metadata */\n\tmetadata?: { [key: string]: any };\n\n\t/** Agent ID this account is related to, for agents should be themselves */\n\tagentId: UUID;\n\n\t/** Optional array of components */\n\tcomponents?: Component[];\n}\n\nexport type World = {\n\tid: UUID;\n\tname?: string;\n\tagentId: UUID;\n\tserverId: string;\n\tmetadata?: {\n\t\townership?: {\n\t\t\townerId: string;\n\t\t};\n\t\troles?: {\n\t\t\t[entityId: UUID]: Role;\n\t\t};\n\t\t[key: string]: unknown;\n\t};\n};\n\nexport type Room = {\n\tid: UUID;\n\tname?: string;\n\tagentId?: UUID;\n\tsource: string;\n\ttype: ChannelType;\n\tchannelId?: string;\n\tserverId?: string;\n\tworldId?: UUID;\n\tmetadata?: Record<string, unknown>;\n};\n\n/**\n * Room participant with account details\n */\nexport interface Participant {\n\t/** Unique identifier */\n\tid: UUID;\n\n\t/** Associated account */\n\tentity: Entity;\n}\n\n/**\n * Represents a media attachment\n */\nexport type Media = {\n\t/** Unique identifier */\n\tid: string;\n\n\t/** Media URL */\n\turl: string;\n\n\t/** Media title */\n\ttitle: string;\n\n\t/** Media source */\n\tsource: string;\n\n\t/** Media description */\n\tdescription: string;\n\n\t/** Text content */\n\ttext: string;\n\n\t/** Content type */\n\tcontentType?: string;\n};\n\nexport enum ChannelType {\n\tSELF = \"SELF\",\n\tDM = \"DM\",\n\tGROUP = \"GROUP\",\n\tVOICE_DM = \"VOICE_DM\",\n\tVOICE_GROUP = \"VOICE_GROUP\",\n\tFEED = \"FEED\",\n\tTHREAD = \"THREAD\",\n\tWORLD = \"WORLD\",\n\tAPI = \"API\",\n\tFORUM = \"FORUM\",\n}\n\n/**\n * Client instance\n */\nexport abstract class Service {\n\t/** Runtime instance */\n\tprotected runtime!: IAgentRuntime;\n\n\tconstructor(runtime?: IAgentRuntime) {\n\t\tif (runtime) {\n\t\t\tthis.runtime = runtime;\n\t\t}\n\t}\n\n\tabstract stop(): Promise<void>;\n\n\t/** Service type */\n\tstatic serviceType: string;\n\n\t/** Service name */\n\tabstract capabilityDescription: string;\n\n\t/** Service configuration */\n\tconfig?: { [key: string]: any };\n\n\t/** Start service connection */\n\tstatic async start(_runtime: IAgentRuntime): Promise<Service> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\n\t/** Stop service connection */\n\tstatic async stop(_runtime: IAgentRuntime): Promise<unknown> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n}\n\nexport type Route = {\n\ttype: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n\tpath: string;\n\t// TODO: give me strong types\n\thandler: (req: any, res: any, runtime: IAgentRuntime) => Promise<void>;\n};\n\n/**\n * Plugin for extending agent functionality\n */\nexport interface Plugin {\n\tname: string;\n\tdescription: string;\n\n\t// Initialize plugin with runtime services\n\tinit?: (\n\t\tconfig: Record<string, string>,\n\t\truntime: IAgentRuntime,\n\t) => Promise<void>;\n\n\t// Configuration\n\tconfig?: { [key: string]: any };\n\n\t// Core plugin components\n\tmemoryManagers?: IMemoryManager[];\n\n\tservices?: (typeof Service)[];\n\n\t// Entity component definitions\n\tcomponentTypes?: {\n\t\tname: string;\n\t\tschema: Record<string, unknown>;\n\t\tvalidator?: (data: any) => boolean;\n\t}[];\n\n\t// Optional plugin features\n\tactions?: Action[];\n\tproviders?: Provider[];\n\tevaluators?: Evaluator[];\n\tadapters?: IDatabaseAdapter[];\n\tmodels?: {\n\t\t[key: string]: (...args: any[]) => Promise<any>;\n\t};\n\tevents?: {\n\t\t[key: string]: ((params: any) => Promise<any>)[];\n\t};\n\troutes?: Route[];\n\ttests?: TestSuite[];\n}\n\nexport interface ProjectAgent {\n\tcharacter: Character;\n\tinit?: (runtime: IAgentRuntime) => Promise<void>;\n\tplugins?: Plugin[];\n}\n\nexport interface Project {\n\tagents: ProjectAgent[];\n}\n\nexport interface ModelConfiguration {\n\ttemperature?: number;\n\tmaxOutputTokens?: number;\n\tfrequency_penalty?: number;\n\tpresence_penalty?: number;\n\tmaxInputTokens?: number;\n}\n\nexport type TemplateType = string | ((options: { state: State }) => string);\n\n/**\n * Configuration for an agent character\n */\nexport interface Character {\n\t/** Optional unique identifier */\n\tid?: UUID;\n\n\t/** Character name */\n\tname: string;\n\n\t/** Optional username */\n\tusername?: string;\n\n\t/** Optional system prompt */\n\tsystem?: string;\n\n\t/** Optional prompt templates */\n\ttemplates?: {\n\t\t[key: string]: TemplateType;\n\t};\n\n\t/** Character biography */\n\tbio: string | string[];\n\n\t/** Example messages */\n\tmessageExamples?: MessageExample[][];\n\n\t/** Example posts */\n\tpostExamples?: string[];\n\n\t/** Known topics */\n\ttopics?: string[];\n\n\t/** Character traits */\n\tadjectives?: string[];\n\n\t/** Optional knowledge base */\n\tknowledge?: (string | { path: string; shared?: boolean })[];\n\n\t/** Available plugins */\n\tplugins?: string[];\n\n\t/** Optional configuration */\n\tsettings?: {\n\t\t[key: string]: any | string | boolean | number;\n\t};\n\n\t/** Optional secrets */\n\tsecrets?: {\n\t\t[key: string]: string | boolean | number;\n\t};\n\n\t/** Writing style guides */\n\tstyle?: {\n\t\tall?: string[];\n\t\tchat?: string[];\n\t\tpost?: string[];\n\t};\n}\n\nexport interface Agent extends Character {\n\tenabled: boolean;\n\tcreatedAt: number;\n\tupdatedAt: number;\n}\n\n/**\n * Interface for database operations\n */\nexport interface IDatabaseAdapter {\n\t/** Database instance */\n\tdb: any;\n\n\t/** Close database connection */\n\tclose(): Promise<void>;\n\n\tgetAgent(agentId: UUID): Promise<Agent | null>;\n\n\t/** Get all agents */\n\tgetAgents(): Promise<Agent[]>;\n\n\tcreateAgent(agent: Partial<Agent>): Promise<boolean>;\n\n\tupdateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean>;\n\n\tdeleteAgent(agentId: UUID): Promise<boolean>;\n\n\tensureAgentExists(agent: Partial<Agent>): Promise<void>;\n\n\tensureEmbeddingDimension(dimension: number): Promise<void>;\n\n\t/** Get entity by ID */\n\tgetEntityById(entityId: UUID): Promise<Entity | null>;\n\n\t/** Get entities for room */\n\tgetEntitiesForRoom(\n\t\troomId: UUID,\n\t\tincludeComponents?: boolean,\n\t): Promise<Entity[]>;\n\n\t/** Create new entity */\n\tcreateEntity(entity: Entity): Promise<boolean>;\n\n\t/** Update entity */\n\tupdateEntity(entity: Entity): Promise<void>;\n\n\t/** Get component by ID */\n\tgetComponent(\n\t\tentityId: UUID,\n\t\ttype: string,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component | null>;\n\n\t/** Get all components for an entity */\n\tgetComponents(\n\t\tentityId: UUID,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component[]>;\n\n\t/** Create component */\n\tcreateComponent(component: Component): Promise<boolean>;\n\n\t/** Update component */\n\tupdateComponent(component: Component): Promise<void>;\n\n\t/** Delete component */\n\tdeleteComponent(componentId: UUID): Promise<void>;\n\n\t/** Get memories matching criteria */\n\tgetMemories(params: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t\tstart?: number;\n\t\tend?: number;\n\t}): Promise<Memory[]>;\n\n\tgetMemoryById(id: UUID): Promise<Memory | null>;\n\n\tgetMemoriesByIds(ids: UUID[], tableName?: string): Promise<Memory[]>;\n\n\tgetMemoriesByRoomIds(params: {\n\t\ttableName: string;\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tgetCachedEmbeddings(params: {\n\t\tquery_table_name: string;\n\t\tquery_threshold: number;\n\t\tquery_input: string;\n\t\tquery_field_name: string;\n\t\tquery_field_sub_name: string;\n\t\tquery_match_count: number;\n\t}): Promise<{ embedding: number[]; levenshtein_score: number }[]>;\n\n\tlog(params: {\n\t\tbody: { [key: string]: unknown };\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\ttype: string;\n\t}): Promise<void>;\n\n\tupdateGoalStatus(params: { goalId: UUID; status: GoalStatus }): Promise<void>;\n\n\tsearchMemories(params: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId?: UUID;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t}): Promise<Memory[]>;\n\n\tcreateMemory(\n\t\tmemory: Memory,\n\t\ttableName: string,\n\t\tunique?: boolean,\n\t): Promise<UUID>;\n\n\tremoveMemory(memoryId: UUID, tableName: string): Promise<void>;\n\n\tremoveAllMemories(roomId: UUID, tableName: string): Promise<void>;\n\n\tcountMemories(\n\t\troomId: UUID,\n\t\tunique?: boolean,\n\t\ttableName?: string,\n\t): Promise<number>;\n\n\tgetGoals(params: {\n\t\troomId: UUID;\n\t\tentityId?: UUID | null;\n\t\tonlyInProgress?: boolean;\n\t\tcount?: number;\n\t}): Promise<Goal[]>;\n\n\tupdateGoal(goal: Goal): Promise<void>;\n\n\tcreateGoal(goal: Goal): Promise<void>;\n\n\tremoveGoal(goalId: UUID): Promise<void>;\n\n\tremoveAllGoals(roomId: UUID): Promise<void>;\n\n\tcreateWorld(world: World): Promise<UUID>;\n\n\tgetWorld(id: UUID): Promise<World | null>;\n\n\tgetAllWorlds(): Promise<World[]>;\n\n\tupdateWorld(world: World): Promise<void>;\n\n\tgetRoom(roomId: UUID): Promise<Room | null>;\n\n\tcreateRoom({\n\t\tid,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room): Promise<UUID>;\n\n\tdeleteRoom(roomId: UUID): Promise<void>;\n\n\tupdateRoom(room: Room): Promise<void>;\n\n\tgetRoomsForParticipant(entityId: UUID): Promise<UUID[]>;\n\n\tgetRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;\n\n\tgetRooms(worldId: UUID): Promise<Room[]>;\n\n\taddParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\tremoveParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\tgetParticipantsForEntity(entityId: UUID): Promise<Participant[]>;\n\n\tgetParticipantsForRoom(roomId: UUID): Promise<UUID[]>;\n\n\tgetParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t): Promise<\"FOLLOWED\" | \"MUTED\" | null>;\n\n\tsetParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t\tstate: \"FOLLOWED\" | \"MUTED\" | null,\n\t): Promise<void>;\n\n\t/**\n\t * Creates a new relationship between two entities.\n\t * @param params Object containing the relationship details\n\t * @returns Promise resolving to boolean indicating success\n\t */\n\tcreateRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: { [key: string]: any };\n\t}): Promise<boolean>;\n\n\t/**\n\t * Updates an existing relationship between two entities.\n\t * @param relationship The relationship object with updated data\n\t * @returns Promise resolving to void\n\t */\n\tupdateRelationship(relationship: Relationship): Promise<void>;\n\n\t/**\n\t * Retrieves a relationship between two entities if it exists.\n\t * @param params Object containing the entity IDs and agent ID\n\t * @returns Promise resolving to the Relationship object or null if not found\n\t */\n\tgetRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t}): Promise<Relationship | null>;\n\n\t/**\n\t * Retrieves all relationships for a specific entity.\n\t * @param params Object containing the user ID, agent ID and optional tags to filter by\n\t * @returns Promise resolving to an array of Relationship objects\n\t */\n\tgetRelationships(params: {\n\t\tentityId: UUID;\n\t\ttags?: string[];\n\t}): Promise<Relationship[]>;\n\n\tensureEmbeddingDimension(dimension: number): void;\n\n\tgetCache<T>(key: string): Promise<T | undefined>;\n\tsetCache<T>(key: string, value: T): Promise<boolean>;\n\tdeleteCache(key: string): Promise<boolean>;\n\n\t// Only task instance methods - definitions are in-memory\n\tcreateTask(task: Task): Promise<UUID>;\n\tgetTasks(params: { roomId?: UUID; tags?: string[] }): Promise<Task[]>;\n\tgetTask(id: UUID): Promise<Task | null>;\n\tgetTasksByName(name: string): Promise<Task[]>;\n\tupdateTask(id: UUID, task: Partial<Task>): Promise<void>;\n\tdeleteTask(id: UUID): Promise<void>;\n}\n\nexport interface IMemoryManager {\n\truntime: IAgentRuntime;\n\ttableName: string;\n\tconstructor: Function;\n\n\taddEmbeddingToMemory(memory: Memory): Promise<Memory>;\n\n\tgetMemories(opts: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\tstart?: number;\n\t\tend?: number;\n\t}): Promise<Memory[]>;\n\n\tsearchMemories(params: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId?: UUID;\n\t\tunique?: boolean;\n\t\tmetadata?: MemoryMetadata;\n\t}): Promise<Memory[]>;\n\n\tgetCachedEmbeddings(\n\t\tcontent: string,\n\t): Promise<{ embedding: number[]; levenshtein_score: number }[]>;\n\n\tgetMemoryById(id: UUID): Promise<Memory | null>;\n\tgetMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tcreateMemory(memory: Memory, unique?: boolean): Promise<UUID>;\n\n\tremoveMemory(memoryId: UUID): Promise<void>;\n\n\tremoveAllMemories(roomId: UUID): Promise<void>;\n\n\tcountMemories(roomId: UUID, unique?: boolean): Promise<number>;\n}\n\nexport type CacheOptions = {\n\texpires?: number;\n};\n\nexport interface IAgentRuntime {\n\t// Properties\n\tagentId: UUID;\n\tdatabaseAdapter: IDatabaseAdapter;\n\tcharacter: Character;\n\tproviders: Provider[];\n\tactions: Action[];\n\tevaluators: Evaluator[];\n\tplugins: Plugin[];\n\tservices: Map<ServiceType, Service>;\n\tevents: Map<string, ((params: any) => void)[]>;\n\tfetch?: typeof fetch | null;\n\troutes: Route[];\n\tregisterPlugin(plugin: Plugin): Promise<void>;\n\n\tinitialize(): Promise<void>;\n\n\tgetKnowledge(message: Memory): Promise<KnowledgeItem[]>;\n\taddKnowledge(\n\t\titem: KnowledgeItem,\n\t\toptions: {\n\t\t\ttargetTokens: number;\n\t\t\toverlap: number;\n\t\t\tmodelContextSize: number;\n\t\t},\n\t): Promise<void>;\n\n\tgetMemoryManager(tableName: string): IMemoryManager | null;\n\n\tgetService<T extends Service>(service: ServiceType | string): T | null;\n\n\tgetAllServices(): Map<ServiceType, Service>;\n\n\tregisterService(service: typeof Service): void;\n\n\tregisterDatabaseAdapter(adapter: IDatabaseAdapter): void;\n\n\tgetDatabaseAdapters(): IDatabaseAdapter[];\n\n\tgetDatabaseAdapter(): IDatabaseAdapter | null;\n\n\tsetSetting(\n\t\tkey: string,\n\t\tvalue: string | boolean | null | any,\n\t\tsecret: boolean,\n\t): void;\n\n\tgetSetting(key: string): string | boolean | null | any;\n\n\t// Methods\n\tgetConversationLength(): number;\n\n\tprocessActions(\n\t\tmessage: Memory,\n\t\tresponses: Memory[],\n\t\tstate?: State,\n\t\tcallback?: HandlerCallback,\n\t): Promise<void>;\n\n\tevaluate(\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\tdidRespond?: boolean,\n\t\tcallback?: HandlerCallback,\n\t\tresponses?: Memory[],\n\t): Promise<Evaluator[] | null>;\n\n\tregisterProvider(provider: Provider): void;\n\n\tregisterAction(action: Action): void;\n\n\tregisterEvaluator(evaluator: Evaluator): void;\n\n\tensureConnection({\n\t\tentityId,\n\t\troomId,\n\t\tuserName,\n\t\tname,\n\t\tsource,\n\t\tchannelId,\n\t\tserverId,\n\t\ttype,\n\t\tworldId,\n\t}: {\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\tuserName?: string;\n\t\tname?: string;\n\t\tsource?: string;\n\t\tchannelId?: string;\n\t\tserverId?: string;\n\t\ttype: ChannelType;\n\t\tworldId?: UUID;\n\t}): Promise<void>;\n\n\tensureParticipantInRoom(entityId: UUID, roomId: UUID): Promise<void>;\n\n\tensureWorldExists(world: World): Promise<void>;\n\n\tensureRoomExists(room: Room): Promise<void>;\n\n\tcomposeState(\n\t\tmessage: Memory,\n\t\tfilterList?: string[],\n\t\tincludeList?: string[],\n\t): Promise<State>;\n\n\tuseModel<T = any>(modelType: ModelType | string, params: T): Promise<any>;\n\tregisterModel(\n\t\tmodelType: ModelType | string,\n\t\thandler: (params: any) => Promise<any>,\n\t): void;\n\tgetModel(\n\t\tmodelType: ModelType | string,\n\t): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined;\n\n\tregisterEvent(event: string, handler: (params: any) => void): void;\n\tgetEvent(event: string): ((params: any) => void)[] | undefined;\n\temitEvent(event: string | string[], params: any): void;\n\n\t// In-memory task definition methods\n\tregisterTaskWorker(taskHandler: TaskWorker): void;\n\tgetTaskWorker(name: string): TaskWorker | undefined;\n\n\tstop(): Promise<void>;\n\n\tensureEmbeddingDimension(): Promise<void>;\n}\n\nexport type KnowledgeItem = {\n\tid: UUID;\n\tcontent: Content;\n};\n\nexport enum KnowledgeScope {\n\tSHARED = \"shared\",\n\tPRIVATE = \"private\",\n}\n\nexport enum CacheKeyPrefix {\n\tKNOWLEDGE = \"knowledge\",\n}\n\nexport interface DirectoryItem {\n\tdirectory: string;\n\tshared?: boolean;\n}\n\nexport interface ChunkRow {\n\tid: string;\n\t// Add other properties if needed\n}\n\nexport type GenerateTextParams = {\n\truntime: IAgentRuntime;\n\tprompt: string;\n\tmodelType: ModelType;\n\tmaxTokens?: number;\n\ttemperature?: number;\n\tfrequencyPenalty?: number;\n\tpresencePenalty?: number;\n\tstopSequences?: string[];\n};\n\nexport interface TokenizeTextParams {\n\tprompt: string;\n\tmodelType: ModelType;\n}\n\nexport interface DetokenizeTextParams {\n\ttokens: number[];\n\tmodelType: ModelType;\n}\n\nexport interface IVideoService extends Service {\n\tisVideoUrl(url: string): boolean;\n\tfetchVideoInfo(url: string): Promise<Media>;\n\tdownloadVideo(videoInfo: Media): Promise<string>;\n\tprocessVideo(url: string, runtime: IAgentRuntime): Promise<Media>;\n}\n\nexport interface IBrowserService extends Service {\n\tgetPageContent(\n\t\turl: string,\n\t\truntime: IAgentRuntime,\n\t): Promise<{ title: string; description: string; bodyContent: string }>;\n}\n\nexport interface IPdfService extends Service {\n\tconvertPdfToText(pdfBuffer: Buffer): Promise<string>;\n}\n\nexport interface IFileService extends Service {\n\tuploadFile(\n\t\timagePath: string,\n\t\tsubDirectory: string,\n\t\tuseSignedUrl: boolean,\n\t\texpiresIn: number,\n\t): Promise<{\n\t\tsuccess: boolean;\n\t\turl?: string;\n\t\terror?: string;\n\t}>;\n\tgenerateSignedUrl(fileName: string, expiresIn: number): Promise<string>;\n}\n\nexport interface ITeeLogService extends Service {\n\tlog(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean>;\n\n\tgenerateAttestation<T>(\n\t\treportData: string,\n\t\thashAlgorithm?: T | any,\n\t): Promise<string>;\n\tgetAllAgents(): Promise<TeeAgent[]>;\n\tgetAgent(agentId: string): Promise<TeeAgent | null>;\n\tgetLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n}\n\nexport interface TestCase {\n\tname: string;\n\tfn: (runtime: IAgentRuntime) => Promise<void> | void;\n}\n\nexport interface TestSuite {\n\tname: string;\n\ttests: TestCase[];\n}\n\n// Represents a log entry in the TeeLog table, containing details about agent activities.\nexport interface TeeLog {\n\tid: string;\n\tagentId: string;\n\troomId: string;\n\tentityId: string;\n\ttype: string;\n\tcontent: string;\n\ttimestamp: number;\n\tsignature: string;\n}\n\nexport interface TeeLogQuery {\n\tagentId?: string;\n\troomId?: string;\n\tentityId?: string;\n\ttype?: string;\n\tcontainsContent?: string;\n\tstartTimestamp?: number;\n\tendTimestamp?: number;\n}\n\n// Represents an agent in the TeeAgent table, containing details about the agent.\nexport interface TeeAgent {\n\tid: string; // Primary key\n\t// Allow duplicate agentId.\n\t// This is to support the case where the same agentId is registered multiple times.\n\t// Each time the agent restarts, we will generate a new keypair and attestation.\n\tagentId: string;\n\tagentName: string;\n\tcreatedAt: number;\n\tpublicKey: string;\n\tattestation: string;\n}\n\nexport interface TeePageQuery<Result = any> {\n\tpage: number;\n\tpageSize: number;\n\ttotal?: number;\n\tdata?: Result;\n}\n\nexport abstract class TeeLogDAO<DB = any> {\n\tdb: DB;\n\n\tabstract initialize(): Promise<void>;\n\n\tabstract addLog(log: TeeLog): Promise<boolean>;\n\n\tabstract getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n\n\tabstract addAgent(agent: TeeAgent): Promise<boolean>;\n\n\tabstract getAgent(agentId: string): Promise<TeeAgent>;\n\n\tabstract getAllAgents(): Promise<TeeAgent[]>;\n}\n\nexport enum TEEMode {\n\tOFF = \"OFF\",\n\tLOCAL = \"LOCAL\", // For local development with simulator\n\tDOCKER = \"DOCKER\", // For docker development with simulator\n\tPRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n\tquote: string;\n\ttimestamp: number;\n}\n\nexport interface DeriveKeyAttestationData {\n\tagentId: string;\n\tpublicKey: string;\n\tsubject?: string;\n}\n\nexport interface RemoteAttestationMessage {\n\tagentId: string;\n\ttimestamp: number;\n\tmessage: {\n\t\tentityId: string;\n\t\troomId: string;\n\t\tcontent: string;\n\t};\n}\n\nexport interface SgxAttestation {\n\tquote: string;\n\ttimestamp: number;\n}\n\nexport enum TeeType {\n\tSGX_GRAMINE = \"sgx_gramine\",\n\tTDX_DSTACK = \"tdx_dstack\",\n}\n\nexport interface TeeVendorConfig {\n\t// Add vendor-specific configuration options here\n\t[key: string]: unknown;\n}\n\nexport interface TeePluginConfig {\n\tvendor?: string;\n\tvendorConfig?: TeeVendorConfig;\n}\n\nexport interface TaskWorker {\n\tname: string;\n\texecute: (\n\t\truntime: IAgentRuntime,\n\t\toptions: { [key: string]: unknown },\n\t) => Promise<void>;\n\tvalidate?: (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t) => Promise<boolean>;\n}\n\nexport interface Task {\n\tid?: UUID;\n\tname: string;\n\tupdatedAt?: number;\n\tmetadata?: {\n\t\tupdateInterval?: number;\n\t\toptions?: {\n\t\t\tname: string;\n\t\t\tdescription: string;\n\t\t}[];\n\t\t[key: string]: unknown;\n\t};\n\tdescription: string;\n\troomId?: UUID;\n\tworldId?: UUID;\n\ttags: string[];\n}\n\nexport enum Role {\n\tOWNER = \"OWNER\",\n\tADMIN = \"ADMIN\",\n\tNONE = \"NONE\",\n}\n\nexport interface Setting {\n\tname: string;\n\tdescription: string; // Used in chat context when discussing the setting\n\tusageDescription: string; // Used during settings to guide users\n\tvalue: string | boolean | null;\n\trequired: boolean;\n\tpublic?: boolean; // If true, shown in public channels\n\tsecret?: boolean; // If true, value is masked and only shown during settings\n\tvalidation?: (value: any) => boolean;\n\tdependsOn?: string[];\n\tonSetAction?: (value: any) => string;\n\tvisibleIf?: (settings: { [key: string]: Setting }) => boolean;\n}\n\nexport interface WorldSettings {\n\t[key: string]: Setting;\n}\n\nexport interface OnboardingConfig {\n\tsettings: {\n\t\t[key: string]: Omit<Setting, \"value\">;\n\t};\n}\n","import { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport type { Action, ActionExample } from \"./types.ts\";\n\n/**\n * Composes a set of example conversations based on provided actions and a specified count.\n * It randomly selects examples from the provided actions and formats them with generated names.\n * @param actionsData - An array of `Action` objects from which to draw examples.\n * @param count - The number of examples to generate.\n * @returns A string containing formatted examples of conversations.\n */\nexport const composeActionExamples = (actionsData: Action[], count: number) => {\n\tconst data: ActionExample[][][] = actionsData.map((action: Action) => [\n\t\t...action.examples,\n\t]);\n\n\tconst actionExamples: ActionExample[][] = [];\n\tlet length = data.length;\n\tfor (let i = 0; i < count && length; i++) {\n\t\tconst actionId = i % length;\n\t\tconst examples = data[actionId];\n\t\tif (examples.length) {\n\t\t\tconst rand = ~~(Math.random() * examples.length);\n\t\t\tactionExamples[i] = examples.splice(rand, 1)[0];\n\t\t} else {\n\t\t\ti--;\n\t\t}\n\n\t\tif (examples.length === 0) {\n\t\t\tdata.splice(actionId, 1);\n\t\t\tlength--;\n\t\t}\n\t}\n\n\tconst formattedExamples = actionExamples.map((example) => {\n\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t\t);\n\n\t\treturn `\\n${example\n\t\t\t.map((message) => {\n\t\t\t\tlet messageString = `${message.name}: ${message.content.text}${message.content.actions ? ` (actions: ${message.content.actions.join(\", \")})` : \"\"}`;\n\t\t\t\tfor (let i = 0; i < exampleNames.length; i++) {\n\t\t\t\t\tmessageString = messageString.replaceAll(\n\t\t\t\t\t\t`{{name${i + 1}}}`,\n\t\t\t\t\t\texampleNames[i],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn messageString;\n\t\t\t})\n\t\t\t.join(\"\\n\")}`;\n\t});\n\n\treturn formattedExamples.join(\"\\n\");\n};\n\n/**\n * Formats the names of the provided actions into a comma-separated string.\n * @param actions - An array of `Action` objects from which to extract names.\n * @returns A comma-separated string of action names.\n */\nexport function formatActionNames(actions: Action[]) {\n\treturn actions\n\t\t.sort(() => 0.5 - Math.random())\n\t\t.map((action: Action) => `${action.name}`)\n\t\t.join(\", \");\n}\n\n/**\n * Formats the provided actions into a detailed string listing each action's name and description, separated by commas and newlines.\n * @param actions - An array of `Action` objects to format.\n * @returns A detailed string of actions, including names and descriptions.\n */\nexport function formatActions(actions: Action[]) {\n\treturn actions\n\t\t.sort(() => 0.5 - Math.random())\n\t\t.map((action: Action) => `${action.name}: ${action.description}`)\n\t\t.join(\",\\n\");\n}\n","import type {\n\tAgent,\n\tCharacter,\n\tComponent,\n\tEntity,\n\tGoal,\n\tGoalStatus,\n\tIDatabaseAdapter,\n\tMemory,\n\tParticipant,\n\tRelationship,\n\tRoom,\n\tTask,\n\tUUID,\n\tWorld,\n} from \"./types.ts\";\n\n/**\n * An abstract class representing a database adapter for managing various entities\n * like entities, memories, entities, goals, and rooms.\n */\nexport abstract class DatabaseAdapter<DB = unknown>\n\timplements IDatabaseAdapter\n{\n\t/**\n\t * The database instance.\n\t */\n\tdb: DB;\n\n\t/**\n\t * Optional close method for the database adapter.\n\t * @returns A Promise that resolves when closing is complete.\n\t */\n\tabstract close(): Promise<void>;\n\n\t/**\n\t * Retrieves an account by its ID.\n\t * @param entityId The UUID of the user account to retrieve.\n\t * @returns A Promise that resolves to the Entity object or null if not found.\n\t */\n\tabstract getEntityById(entityId: UUID): Promise<Entity | null>;\n\n\tabstract getEntitiesForRoom(\n\t\troomId: UUID,\n\t\tincludeComponents?: boolean,\n\t): Promise<Entity[]>;\n\n\t/**\n\t * Creates a new entity in the database.\n\t * @param entity The entity object to create.\n\t * @returns A Promise that resolves when the account creation is complete.\n\t */\n\tabstract createEntity(entity: Entity): Promise<boolean>;\n\n\t/**\n\t * Updates an existing entity in the database.\n\t * @param entity The entity object with updated properties.\n\t * @returns A Promise that resolves when the account update is complete.\n\t */\n\tabstract updateEntity(entity: Entity): Promise<void>;\n\n\t/**\n\t * Retrieves a single component by entity ID and type.\n\t * @param entityId The UUID of the entity the component belongs to\n\t * @param type The type identifier for the component\n\t * @param worldId Optional UUID of the world the component belongs to\n\t * @param sourceEntityId Optional UUID of the source entity\n\t * @returns Promise resolving to the Component if found, null otherwise\n\t */\n\tabstract getComponent(\n\t\tentityId: UUID,\n\t\ttype: string,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component | null>;\n\n\t/**\n\t * Retrieves all components for an entity.\n\t * @param entityId The UUID of the entity to get components for\n\t * @param worldId Optional UUID of the world to filter components by\n\t * @param sourceEntityId Optional UUID of the source entity to filter by\n\t * @returns Promise resolving to array of Component objects\n\t */\n\tabstract getComponents(\n\t\tentityId: UUID,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component[]>;\n\n\t/**\n\t * Creates a new component in the database.\n\t * @param component The component object to create\n\t * @returns Promise resolving to true if creation was successful\n\t */\n\tabstract createComponent(component: Component): Promise<boolean>;\n\n\t/**\n\t * Updates an existing component in the database.\n\t * @param component The component object with updated properties\n\t * @returns Promise that resolves when the update is complete\n\t */\n\tabstract updateComponent(component: Component): Promise<void>;\n\n\t/**\n\t * Deletes a component from the database.\n\t * @param componentId The UUID of the component to delete\n\t * @returns Promise that resolves when the deletion is complete\n\t */\n\tabstract deleteComponent(componentId: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves memories based on the specified parameters.\n\t * @param params An object containing parameters for the memory retrieval.\n\t * @returns A Promise that resolves to an array of Memory objects.\n\t */\n\tabstract getMemories(params: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t}): Promise<Memory[]>;\n\n\tabstract getMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\ttableName: string;\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tabstract getMemoryById(id: UUID): Promise<Memory | null>;\n\n\t/**\n\t * Retrieves multiple memories by their IDs\n\t * @param memoryIds Array of UUIDs of the memories to retrieve\n\t * @param tableName Optional table name to filter memories by type\n\t * @returns Promise resolving to array of Memory objects\n\t */\n\tabstract getMemoriesByIds(\n\t\tmemoryIds: UUID[],\n\t\ttableName?: string,\n\t): Promise<Memory[]>;\n\n\t/**\n\t * Retrieves cached embeddings based on the specified query parameters.\n\t * @param params An object containing parameters for the embedding retrieval.\n\t * @returns A Promise that resolves to an array of objects containing embeddings and levenshtein scores.\n\t */\n\tabstract getCachedEmbeddings({\n\t\tquery_table_name,\n\t\tquery_threshold,\n\t\tquery_input,\n\t\tquery_field_name,\n\t\tquery_field_sub_name,\n\t\tquery_match_count,\n\t}: {\n\t\tquery_table_name: string;\n\t\tquery_threshold: number;\n\t\tquery_input: string;\n\t\tquery_field_name: string;\n\t\tquery_field_sub_name: string;\n\t\tquery_match_count: number;\n\t}): Promise<\n\t\t{\n\t\t\tembedding: number[];\n\t\t\tlevenshtein_score: number;\n\t\t}[]\n\t>;\n\n\t/**\n\t * Logs an event or action with the specified details.\n\t * @param params An object containing parameters for the log entry.\n\t * @returns A Promise that resolves when the log entry has been saved.\n\t */\n\tabstract log(params: {\n\t\tbody: { [key: string]: unknown };\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\ttype: string;\n\t}): Promise<void>;\n\n\t/**\n\t * Searches for memories based on embeddings and other specified parameters.\n\t * @param params An object containing parameters for the memory search.\n\t * @returns A Promise that resolves to an array of Memory objects.\n\t */\n\tabstract searchMemories(params: {\n\t\ttableName: string;\n\t\troomId: UUID;\n\t\tembedding: number[];\n\t\tmatch_threshold: number;\n\t\tcount: number;\n\t\tunique: boolean;\n\t}): Promise<Memory[]>;\n\n\t/**\n\t * Updates the status of a specific goal.\n\t * @param params An object containing the goalId and the new status.\n\t * @returns A Promise that resolves when the goal status has been updated.\n\t */\n\tabstract updateGoalStatus(params: {\n\t\tgoalId: UUID;\n\t\tstatus: GoalStatus;\n\t}): Promise<void>;\n\n\t/**\n\t * Creates a new memory in the database.\n\t * @param memory The memory object to create.\n\t * @param tableName The table where the memory should be stored.\n\t * @param unique Indicates if the memory should be unique.\n\t * @returns A Promise that resolves when the memory has been created.\n\t */\n\tabstract createMemory(\n\t\tmemory: Memory,\n\t\ttableName: string,\n\t\tunique?: boolean,\n\t): Promise<UUID>;\n\n\t/**\n\t * Removes a specific memory from the database.\n\t * @param memoryId The UUID of the memory to remove.\n\t * @param tableName The table from which the memory should be removed.\n\t * @returns A Promise that resolves when the memory has been removed.\n\t */\n\tabstract removeMemory(memoryId: UUID, tableName: string): Promise<void>;\n\n\t/**\n\t * Removes all memories associated with a specific room.\n\t * @param roomId The UUID of the room whose memories should be removed.\n\t * @param tableName The table from which the memories should be removed.\n\t * @returns A Promise that resolves when all memories have been removed.\n\t */\n\tabstract removeAllMemories(roomId: UUID, tableName: string): Promise<void>;\n\n\t/**\n\t * Counts the number of memories in a specific room.\n\t * @param roomId The UUID of the room for which to count memories.\n\t * @param unique Specifies whether to count only unique memories.\n\t * @param tableName Optional table name to count memories from.\n\t * @returns A Promise that resolves to the number of memories.\n\t */\n\tabstract countMemories(\n\t\troomId: UUID,\n\t\tunique?: boolean,\n\t\ttableName?: string,\n\t): Promise<number>;\n\n\t/**\n\t * Retrieves goals based on specified parameters.\n\t * @param params An object containing parameters for goal retrieval.\n\t * @returns A Promise that resolves to an array of Goal objects.\n\t */\n\tabstract getGoals(params: {\n\t\troomId: UUID;\n\t\tentityId?: UUID | null;\n\t\tonlyInProgress?: boolean;\n\t\tcount?: number;\n\t}): Promise<Goal[]>;\n\n\t/**\n\t * Updates a specific goal in the database.\n\t * @param goal The goal object with updated properties.\n\t * @returns A Promise that resolves when the goal has been updated.\n\t */\n\tabstract updateGoal(goal: Goal): Promise<void>;\n\n\t/**\n\t * Creates a new goal in the database.\n\t * @param goal The goal object to create.\n\t * @returns A Promise that resolves when the goal has been created.\n\t */\n\tabstract createGoal(goal: Goal): Promise<void>;\n\n\t/**\n\t * Removes a specific goal from the database.\n\t * @param goalId The UUID of the goal to remove.\n\t * @returns A Promise that resolves when the goal has been removed.\n\t */\n\tabstract removeGoal(goalId: UUID): Promise<void>;\n\n\t/**\n\t * Removes all goals associated with a specific room.\n\t * @param roomId The UUID of the room whose goals should be removed.\n\t * @returns A Promise that resolves when all goals have been removed.\n\t */\n\tabstract removeAllGoals(roomId: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves a world by its ID.\n\t * @param id The UUID of the world to retrieve.\n\t * @returns A Promise that resolves to the World object or null if not found.\n\t */\n\tabstract getWorld(id: UUID): Promise<World | null>;\n\n\t/**\n\t * Retrieves all worlds for an agent.\n\t * @returns A Promise that resolves to an array of World objects.\n\t */\n\tabstract getAllWorlds(): Promise<World[]>;\n\n\t/**\n\t * Creates a new world in the database.\n\t * @param world The world object to create.\n\t * @returns A Promise that resolves to the UUID of the created world.\n\t */\n\tabstract createWorld(world: World): Promise<UUID>;\n\n\t/**\n\t * Updates an existing world in the database.\n\t * @param world The world object with updated properties.\n\t * @returns A Promise that resolves when the world has been updated.\n\t */\n\tabstract updateWorld(world: World): Promise<void>;\n\n\t/**\n\t * Removes a specific world from the database.\n\t * @param id The UUID of the world to remove.\n\t * @returns A Promise that resolves when the world has been removed.\n\t */\n\tabstract removeWorld(id: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves the room ID for a given room, if it exists.\n\t * @param roomId The UUID of the room to retrieve.\n\t * @returns A Promise that resolves to the room ID or null if not found.\n\t */\n\tabstract getRoom(roomId: UUID): Promise<Room | null>;\n\n\t/**\n\t * Retrieves all rooms for a given world.\n\t * @param worldId The UUID of the world to retrieve rooms for.\n\t * @returns A Promise that resolves to an array of Room objects.\n\t */\n\tabstract getRooms(worldId: UUID): Promise<Room[]>;\n\n\t/**\n\t * Creates a new room with an optional specified ID.\n\t * @param roomId Optional UUID to assign to the new room.\n\t * @returns A Promise that resolves to the UUID of the created room.\n\t */\n\tabstract createRoom({\n\t\tid,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room): Promise<UUID>;\n\n\t/**\n\t * Updates a specific room in the database.\n\t * @param room The room object with updated properties.\n\t * @returns A Promise that resolves when the room has been updated.\n\t */\n\tabstract updateRoom(room: Room): Promise<void>;\n\n\t/**\n\t * Removes a specific room from the database.\n\t * @param roomId The UUID of the room to remove.\n\t * @returns A Promise that resolves when the room has been removed.\n\t */\n\tabstract deleteRoom(roomId: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves room IDs for which a specific user is a participant.\n\t * @param entityId The UUID of the user.\n\t * @returns A Promise that resolves to an array of room IDs.\n\t */\n\tabstract getRoomsForParticipant(entityId: UUID): Promise<UUID[]>;\n\n\t/**\n\t * Retrieves room IDs for which specific users are participants.\n\t * @param userIds An array of UUIDs of the users.\n\t * @returns A Promise that resolves to an array of room IDs.\n\t */\n\tabstract getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;\n\n\t/**\n\t * Adds a user as a participant to a specific room.\n\t * @param entityId The UUID of the user to add as a participant.\n\t * @param roomId The UUID of the room to which the user will be added.\n\t * @returns A Promise that resolves to a boolean indicating success or failure.\n\t */\n\tabstract addParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\t/**\n\t * Removes a user as a participant from a specific room.\n\t * @param entityId The UUID of the user to remove as a participant.\n\t * @param roomId The UUID of the room from which the user will be removed.\n\t * @returns A Promise that resolves to a boolean indicating success or failure.\n\t */\n\tabstract removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\t/**\n\t * Retrieves participants associated with a specific account.\n\t * @param entityId The UUID of the account.\n\t * @returns A Promise that resolves to an array of Participant objects.\n\t */\n\tabstract getParticipantsForEntity(entityId: UUID): Promise<Participant[]>;\n\n\t/**\n\t * Retrieves participants for a specific room.\n\t * @param roomId The UUID of the room for which to retrieve participants.\n\t * @returns A Promise that resolves to an array of UUIDs representing the participants.\n\t */\n\tabstract getParticipantsForRoom(roomId: UUID): Promise<UUID[]>;\n\n\tabstract getParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t): Promise<\"FOLLOWED\" | \"MUTED\" | null>;\n\n\tabstract setParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t\tstate: \"FOLLOWED\" | \"MUTED\" | null,\n\t): Promise<void>;\n\n\t/**\n\t * Creates a new relationship between two users.\n\t * @param params Object containing the relationship details including entity IDs, agent ID, optional tags and metadata\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the creation.\n\t */\n\tabstract createRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: Record<string, unknown>;\n\t}): Promise<boolean>;\n\n\t/**\n\t * Retrieves a relationship between two users if it exists.\n\t * @param params Object containing the entity IDs and agent ID\n\t * @returns A Promise that resolves to the Relationship object or null if not found.\n\t */\n\tabstract getRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t}): Promise<Relationship | null>;\n\n\t/**\n\t * Retrieves all relationships for a specific user.\n\t * @param params Object containing the user ID, agent ID and optional tags to filter by\n\t * @returns A Promise that resolves to an array of Relationship objects.\n\t */\n\tabstract getRelationships(params: {\n\t\tentityId: UUID;\n\t\ttags?: string[];\n\t}): Promise<Relationship[]>;\n\n\t/**\n\t * Updates an existing relationship between two users.\n\t * @param params Object containing the relationship details to update including entity IDs, agent ID, optional tags and metadata\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the update.\n\t */\n\tabstract updateRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: Record<string, unknown>;\n\t}): Promise<void>;\n\n\t/**\n\t * Retrieves an agent by its ID.\n\t * @param agentId The UUID of the agent to retrieve.\n\t * @returns A Promise that resolves to the Agent object or null if not found.\n\t */\n\tabstract getAgent(agentId: UUID): Promise<Agent | null>;\n\n\t/**\n\t * Retrieves all agents from the database.\n\t * @returns A Promise that resolves to an array of Agent objects.\n\t */\n\tabstract getAgents(): Promise<Agent[]>;\n\n\t/**\n\t * Creates a new agent in the database.\n\t * @param agent The agent object to create.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the creation.\n\t */\n\tabstract createAgent(agent: Partial<Agent>): Promise<boolean>;\n\n\t/**\n\t * Updates an existing agent in the database.\n\t * @param agentId The UUID of the agent to update.\n\t * @param agent The agent object with updated properties.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the update.\n\t */\n\tabstract updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean>;\n\n\t/**\n\t * Deletes an agent from the database.\n\t * @param agentId The UUID of the agent to delete.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the deletion.\n\t */\n\tabstract deleteAgent(agentId: UUID): Promise<boolean>;\n\n\t/**\n\t * Ensures an agent exists in the database.\n\t * @param agent The agent object to ensure exists.\n\t * @returns A Promise that resolves when the agent has been ensured to exist.\n\t */\n\tabstract ensureAgentExists(agent: Partial<Agent>): Promise<void>;\n\n\t/**\n\t * Ensures an embedding dimension exists in the database.\n\t * @param dimension The dimension to ensure exists.\n\t * @returns A Promise that resolves when the embedding dimension has been ensured to exist.\n\t */\n\tabstract ensureEmbeddingDimension(dimension: number): Promise<void>;\n\n\t/**\n\t * Retrieves a cached value by key from the database.\n\t * @param key The key to look up in the cache\n\t * @returns Promise resolving to the cached string value\n\t */\n\tabstract getCache<T>(key: string): Promise<T | undefined>;\n\n\t/**\n\t * Sets a value in the cache with the given key.\n\t * @param params Object containing the cache key and value\n\t * @param key The key to store the value under\n\t * @param value The string value to cache\n\t * @returns Promise resolving to true if the cache was set successfully\n\t */\n\tabstract setCache<T>(key: string, value: T): Promise<boolean>;\n\n\t/**\n\t * Deletes a value from the cache by key.\n\t * @param key The key to delete from the cache\n\t * @returns Promise resolving to true if the value was successfully deleted\n\t */\n\tabstract deleteCache(key: string): Promise<boolean>;\n\n\t/**\n\t * Creates a new task instance in the database.\n\t * @param task The task object to create\n\t * @returns Promise resolving to the UUID of the created task\n\t */\n\tabstract createTask(task: Task): Promise<UUID>;\n\n\t/**\n\t * Retrieves tasks based on specified parameters.\n\t * @param params Object containing optional roomId and tags to filter tasks\n\t * @returns Promise resolving to an array of Task objects\n\t */\n\tabstract getTasks(params: { roomId?: UUID; tags?: string[] }): Promise<\n\t\tTask[]\n\t>;\n\n\t/**\n\t * Retrieves a specific task by its ID.\n\t * @param id The UUID of the task to retrieve\n\t * @returns Promise resolving to the Task object if found, null otherwise\n\t */\n\tabstract getTask(id: UUID): Promise<Task | null>;\n\n\t/**\n\t * Retrieves a specific task by its name.\n\t * @param name The name of the task to retrieve\n\t * @returns Promise resolving to the Task object if found, null otherwise\n\t */\n\tabstract getTasksByName(name: string): Promise<Task[]>;\n\n\t/**\n\t * Updates an existing task in the database.\n\t * @param id The UUID of the task to update\n\t * @param task Partial Task object containing the fields to update\n\t * @returns Promise resolving when the update is complete\n\t */\n\tabstract updateTask(id: UUID, task: Partial<Task>): Promise<void>;\n\n\t/**\n\t * Deletes a task from the database.\n\t * @param id The UUID of the task to delete\n\t * @returns Promise resolving when the deletion is complete\n\t */\n\tabstract deleteTask(id: UUID): Promise<void>;\n}\n","import handlebars from \"handlebars\";\nimport { RecursiveCharacterTextSplitter } from \"langchain/text_splitter\";\nimport { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport logger from \"./logger.ts\";\nimport type {\n\tContent,\n\tEntity,\n\tIAgentRuntime,\n\tMemory,\n\tState,\n\tTemplateType,\n} from \"./types.ts\";\nimport { ModelTypes } from \"./types.ts\";\n\n/**\n * Composes a context string by replacing placeholders in a template with corresponding values from the state.\n *\n * This function takes a template string with placeholders in the format `{{placeholder}}` and a state object.\n * It replaces each placeholder with the value from the state object that matches the placeholder's name.\n * If a matching key is not found in the state object for a given placeholder, the placeholder is replaced with an empty string.\n *\n * @param {Object} params - The parameters for composing the context.\n * @param {State} params.state - The state object containing values to replace the placeholders in the template.\n * @param {TemplateType} params.template - The template string or function containing placeholders to be replaced with state values.\n * @returns {string} The composed context string with placeholders replaced by corresponding state values.\n *\n * @example\n * // Given a state object and a template\n * const state = { userName: \"Alice\", userAge: 30 };\n * const template = \"Hello, {{userName}}! You are {{userAge}} years old\";\n *\n * // Composing the context with simple string replacement will result in:\n * // \"Hello, Alice! You are 30 years old.\"\n * const contextSimple = composePrompt({ state, template });\n *\n * // Using composePrompt with a template function for dynamic template\n * const template = ({ state }) => {\n * const tone = Math.random() > 0.5 ? \"kind\" : \"rude\";\n * return `Hello, {{userName}}! You are {{userAge}} years old. Be ${tone}`;\n * };\n * const contextSimple = composePrompt({ state, template });\n */\n\nexport const composePrompt = ({\n\tstate,\n\ttemplate,\n}: {\n\tstate: State;\n\ttemplate: TemplateType;\n}) => {\n\tconst templateStr =\n\t\ttypeof template === \"function\" ? template({ state }) : template;\n\tconst templateFunction = handlebars.compile(templateStr);\n\tconst output = composeRandomUser(templateFunction(state.values), 10);\n\treturn output;\n};\n\n/**\n * Adds a header to a body of text.\n *\n * This function takes a header string and a body string and returns a new string with the header prepended to the body.\n * If the body string is empty, the header is returned as is.\n *\n * @param {string} header - The header to add to the body.\n * @param {string} body - The body to which to add the header.\n * @returns {string} The body with the header prepended.\n *\n * @example\n * // Given a header and a body\n * const header = \"Header\";\n * const body = \"Body\";\n *\n * // Adding the header to the body will result in:\n * // \"Header\\nBody\"\n * const text = addHeader(header, body);\n */\nexport const addHeader = (header: string, body: string) => {\n\treturn body.length > 0 ? `${header ? `${header}\\n` : header}${body}\\n` : \"\";\n};\n\n/**\n * Generates a string with random user names populated in a template.\n *\n * This function generates random user names and populates placeholders\n * in the provided template with these names. Placeholders in the template should follow the format `{{userX}}`\n * where `X` is the position of the user (e.g., `{{name1}}`, `{{name2}}`).\n *\n * @param {string} template - The template string containing placeholders for random user names.\n * @param {number} length - The number of random user names to generate.\n * @returns {string} The template string with placeholders replaced by random user names.\n *\n * @example\n * // Given a template and a length\n * const template = \"Hello, {{name1}}! Meet {{name2}} and {{name3}}.\";\n * const length = 3;\n *\n * // Composing the random user string will result in:\n * // \"Hello, John! Meet Alice and Bob.\"\n * const result = composeRandomUser(template, length);\n */\nexport const composeRandomUser = (template: string, length: number) => {\n\tconst exampleNames = Array.from({ length }, () =>\n\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t);\n\tlet result = template;\n\tfor (let i = 0; i < exampleNames.length; i++) {\n\t\tresult = result.replaceAll(`{{user${i + 1}}}`, exampleNames[i]);\n\t}\n\n\treturn result;\n};\n\nexport const formatPosts = ({\n\tmessages,\n\tentities,\n\tconversationHeader = true,\n}: {\n\tmessages: Memory[];\n\tentities: Entity[];\n\tconversationHeader?: boolean;\n}) => {\n\t// Group messages by roomId\n\tconst groupedMessages: { [roomId: string]: Memory[] } = {};\n\tmessages.forEach((message) => {\n\t\tif (message.roomId) {\n\t\t\tif (!groupedMessages[message.roomId]) {\n\t\t\t\tgroupedMessages[message.roomId] = [];\n\t\t\t}\n\t\t\tgroupedMessages[message.roomId].push(message);\n\t\t}\n\t});\n\n\t// Sort messages within each roomId by createdAt (oldest to newest)\n\tObject.values(groupedMessages).forEach((roomMessages) => {\n\t\troomMessages.sort((a, b) => a.createdAt - b.createdAt);\n\t});\n\n\t// Sort rooms by the newest message's createdAt\n\tconst sortedRooms = Object.entries(groupedMessages).sort(\n\t\t([, messagesA], [, messagesB]) =>\n\t\t\tmessagesB[messagesB.length - 1].createdAt -\n\t\t\tmessagesA[messagesA.length - 1].createdAt,\n\t);\n\n\tconst formattedPosts = sortedRooms.map(([roomId, roomMessages]) => {\n\t\tconst messageStrings = roomMessages\n\t\t\t.filter((message: Memory) => message.entityId)\n\t\t\t.map((message: Memory) => {\n\t\t\t\tconst entity = entities.find(\n\t\t\t\t\t(entity: Entity) => entity.id === message.entityId,\n\t\t\t\t);\n\t\t\t\t// TODO: These are okay but not great\n\t\t\t\tconst userName = entity?.names[0] || \"Unknown User\";\n\t\t\t\tconst displayName = entity?.names[0] || \"unknown\";\n\n\t\t\t\treturn `Name: ${userName} (@${displayName})\nID: ${message.id}${\n\t\t\t\t\tmessage.content.inReplyTo\n\t\t\t\t\t\t? `\\nIn reply to: ${message.content.inReplyTo}`\n\t\t\t\t\t\t: \"\"\n\t\t\t\t}\nDate: ${formatTimestamp(message.createdAt)}\nText:\n${message.content.text}`;\n\t\t\t});\n\n\t\tconst header = conversationHeader\n\t\t\t? `Conversation: ${roomId.slice(-5)}\\n`\n\t\t\t: \"\";\n\t\treturn `${header}${messageStrings.join(\"\\n\\n\")}`;\n\t});\n\n\treturn formattedPosts.join(\"\\n\\n\");\n};\n\n/**\n * Format messages into a string\n * @param {Object} params - The formatting parameters\n * @param {Memory[]} params.messages - List of messages to format\n * @param {Entity[]} params.entities - List of entities for name resolution\n * @returns {string} Formatted message string with timestamps and user information\n */\nexport const formatMessages = ({\n\tmessages,\n\tentities,\n}: {\n\tmessages: Memory[];\n\tentities: Entity[];\n}) => {\n\tconst newestMessageWithContentPlan = messages.find(\n\t\t(message: Memory) => (message.content as Content).plan,\n\t);\n\tconst messageStrings = messages\n\t\t.reverse()\n\t\t.filter((message: Memory) => message.entityId)\n\t\t.map((message: Memory) => {\n\t\t\tconst messageText = (message.content as Content).text;\n\n\t\t\tconst messageActions = (message.content as Content).actions;\n\t\t\tconst messageThought = (message.content as Content).thought;\n\t\t\tconst formattedName =\n\t\t\t\tentities.find((entity: Entity) => entity.id === message.entityId)\n\t\t\t\t\t?.names[0] || \"Unknown User\";\n\n\t\t\tconst attachments = (message.content as Content).attachments;\n\n\t\t\tconst attachmentString =\n\t\t\t\tattachments && attachments.length > 0\n\t\t\t\t\t? ` (Attachments: ${attachments\n\t\t\t\t\t\t\t.map((media) => `[${media.id} - ${media.title} (${media.url})]`)\n\t\t\t\t\t\t\t.join(\", \")})`\n\t\t\t\t\t: null;\n\n\t\t\tconst messageTime = new Date(message.createdAt);\n\t\t\tconst hours = messageTime.getHours().toString().padStart(2, \"0\");\n\t\t\tconst minutes = messageTime.getMinutes().toString().padStart(2, \"0\");\n\t\t\tconst timeString = `${hours}:${minutes}`;\n\n\t\t\tconst timestamp = formatTimestamp(message.createdAt);\n\n\t\t\tconst shortId = message.entityId.slice(-5);\n\n\t\t\tconst thoughtString = messageThought\n\t\t\t\t? `(${formattedName}'s internal thought: ${messageThought})`\n\t\t\t\t: null;\n\n\t\t\tconst timestampString = `${timeString} (${timestamp}) [${shortId}]`;\n\t\t\tconst textString = messageText\n\t\t\t\t? `${timestampString} ${formattedName}: ${messageText}`\n\t\t\t\t: null;\n\t\t\tconst actionString =\n\t\t\t\tmessageActions && messageActions.length > 0\n\t\t\t\t\t? `${\n\t\t\t\t\t\t\ttextString ? \"\" : timestampString\n\t\t\t\t\t\t} (${formattedName}'s actions: ${messageActions.join(\", \")})`\n\t\t\t\t\t: null;\n\n\t\t\tconst planString =\n\t\t\t\tnewestMessageWithContentPlan?.id === message.id\n\t\t\t\t\t? `(${formattedName}'s plan: ${newestMessageWithContentPlan.content.plan})`\n\t\t\t\t\t: null;\n\n\t\t\t// for each thought, action, text or attachment, add a new line, with text first, then thought, then action, then attachment\n\t\t\tconst messageString = [\n\t\t\t\ttextString,\n\t\t\t\tthoughtString,\n\t\t\t\tplanString,\n\t\t\t\tactionString,\n\t\t\t\tattachmentString,\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\"\\n\");\n\n\t\t\treturn messageString;\n\t\t})\n\t\t.join(\"\\n\");\n\treturn messageStrings;\n};\n\nexport const formatTimestamp = (messageDate: number) => {\n\tconst now = new Date();\n\tconst diff = now.getTime() - messageDate;\n\n\tconst absDiff = Math.abs(diff);\n\tconst seconds = Math.floor(absDiff / 1000);\n\tconst minutes = Math.floor(seconds / 60);\n\tconst hours = Math.floor(minutes / 60);\n\tconst days = Math.floor(hours / 24);\n\n\tif (absDiff < 60000) {\n\t\treturn \"just now\";\n\t}\n\tif (minutes < 60) {\n\t\treturn `${minutes} minute${minutes !== 1 ? \"s\" : \"\"} ago`;\n\t}\n\tif (hours < 24) {\n\t\treturn `${hours} hour${hours !== 1 ? \"s\" : \"\"} ago`;\n\t}\n\treturn `${days} day${days !== 1 ? \"s\" : \"\"} ago`;\n};\n\nconst jsonBlockPattern = /```json\\n([\\s\\S]*?)\\n```/;\n\nexport const shouldRespondTemplate = `# Task: Decide on behalf of {{agentName}} whether they should respond to the message, ignore it or stop the conversation.\n{{providers}}\n# Instructions: Decide if {{agentName}} should respond to or interact with the conversation.\nIf the message is directed at or relevant to {{agentName}}, respond with RESPOND action.\nIf a user asks {{agentName}} to be quiet, respond with STOP action.\nIf {{agentName}} should ignore the message, respond with IGNORE action.\nIf responding with the RESPOND action, include a list of optional providers that could be relevant to the response.\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"name\": \"{{agentName}}\",\n \"action\": \"RESPOND\" | \"IGNORE\" | \"STOP\",\n \"providers\": [\"<string>\", \"<string>\", ...]\n}\n\\`\\`\\`\nYour response should include the valid JSON block and nothing else.`;\n\nexport const messageHandlerTemplate = `# Task: Generate dialog and actions for the character {{agentName}}.\n{{providers}}\n# Instructions: Write a thought and plan for {{agentName}} and decide what actions to take. Also include the providers that {{agentName}} will use to have the right context for responding and acting, if any.\nFirst, think about what you want to do next and plan your actions. Then, write the next message and include the actions you plan to take.\n\"thought\" should be a short description of what the agent is thinking about and planning.\n\"actions\" should be an array of the actions {{agentName}} plans to take based on the thought (if none, use IGNORE, if simply responding with text, use REPLY)\n\"providers\" should be an optional array of the providers that {{agentName}} will use to have the right context for responding and acting\n\"evaluators\" should be an optional array of the evaluators that {{agentName}} will use to evaluate the conversation after responding\n\"plan\" should be explanation of the message you plan to send, the actions you plan to take, and the data providers you plan to use.\nThese are the available valid actions: {{actionNames}}\n\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"thought\": \"<string>\",\n \"plan\": \"<string>\",\n \"actions\": [\"<string>\", \"<string>\", ...],\n \"providers\": [\"<string>\", \"<string>\", ...]\n}\n\\`\\`\\`\n\nYour response should include the valid JSON block and nothing else.`;\n\nexport const booleanFooter = \"Respond with only a YES or a NO.\";\n\n/**\n * Parses a string to determine its boolean equivalent.\n *\n * Recognized affirmative values: \"YES\", \"Y\", \"TRUE\", \"T\", \"1\", \"ON\", \"ENABLE\"\n * Recognized negative values: \"NO\", \"N\", \"FALSE\", \"F\", \"0\", \"OFF\", \"DISABLE\"\n *\n * @param {string | undefined | null} value - The input text to parse\n * @returns {boolean} - Returns `true` for affirmative inputs, `false` for negative or unrecognized inputs\n */\nexport function parseBooleanFromText(\n\tvalue: string | undefined | null,\n): boolean {\n\tif (!value) return false;\n\n\tconst affirmative = [\"YES\", \"Y\", \"TRUE\", \"T\", \"1\", \"ON\", \"ENABLE\"];\n\tconst negative = [\"NO\", \"N\", \"FALSE\", \"F\", \"0\", \"OFF\", \"DISABLE\"];\n\n\tconst normalizedText = value.trim().toUpperCase();\n\n\tif (affirmative.includes(normalizedText)) {\n\t\treturn true;\n\t}\n\tif (negative.includes(normalizedText)) {\n\t\treturn false;\n\t}\n\n\t// For environment variables, we'll treat unrecognized values as false\n\treturn false;\n}\n\nexport const stringArrayFooter = `Respond with a JSON array containing the values in a valid JSON block formatted for markdown with this structure:\n\\`\\`\\`json\n[\n 'value',\n 'value'\n]\n\\`\\`\\`\n\nYour response must include the valid JSON block.`;\n\n/**\n * Parses a JSON array from a given text. The function looks for a JSON block wrapped in triple backticks\n * with `json` language identifier, and if not found, it searches for an array pattern within the text.\n * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result\n * is an array, it returns the array; otherwise, it returns null.\n *\n * @param text - The input text from which to extract and parse the JSON array.\n * @returns An array parsed from the JSON string if successful; otherwise, null.\n */\nexport function parseJsonArrayFromText(text: string) {\n\tlet jsonData = null;\n\n\t// First try to parse with the original JSON format\n\tconst jsonBlockMatch = text?.match(jsonBlockPattern);\n\n\tif (jsonBlockMatch) {\n\t\ttry {\n\t\t\t// Only replace quotes that are actually being used for string delimitation\n\t\t\tconst normalizedJson = jsonBlockMatch[1].replace(\n\t\t\t\t/(?<!\\\\)'([^']*)'(?=\\s*[,}\\]])/g,\n\t\t\t\t'\"$1\"',\n\t\t\t);\n\t\t\tjsonData = JSON.parse(normalizeJsonString(normalizedJson));\n\t\t} catch (_e) {\n\t\t\tlogger.warn(\"Could not parse text as JSON, will try pattern matching\");\n\t\t}\n\t}\n\n\t// If that fails, try to find an array pattern\n\tif (!jsonData) {\n\t\tconst arrayPattern = /\\[\\s*(['\"])(.*?)\\1\\s*\\]/;\n\t\tconst arrayMatch = text.match(arrayPattern);\n\n\t\tif (arrayMatch) {\n\t\t\ttry {\n\t\t\t\t// Only replace quotes that are actually being used for string delimitation\n\t\t\t\tconst normalizedJson = arrayMatch[0].replace(\n\t\t\t\t\t/(?<!\\\\)'([^']*)'(?=\\s*[,}\\]])/g,\n\t\t\t\t\t'\"$1\"',\n\t\t\t\t);\n\t\t\t\tjsonData = JSON.parse(normalizeJsonString(normalizedJson));\n\t\t\t} catch (_e) {\n\t\t\t\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(jsonData)) {\n\t\treturn jsonData;\n\t}\n\n\treturn null;\n}\n\n/**\n * Parses a JSON object from a given text. The function looks for a JSON block wrapped in triple backticks\n * with `json` language identifier, and if not found, it searches for an object pattern within the text.\n * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result\n * is an object (but not an array), it returns the object; otherwise, it tries to parse an array if the result\n * is an array, or returns null if parsing is unsuccessful or the result is neither an object nor an array.\n *\n * @param text - The input text from which to extract and parse the JSON object.\n * @returns An object parsed from the JSON string if successful; otherwise, null or the result of parsing an array.\n */\nexport function parseJSONObjectFromText(\n\ttext: string,\n): Record<string, any> | null {\n\tlet jsonData = null;\n\tconst jsonBlockMatch = text.match(jsonBlockPattern);\n\n\ttry {\n\t\tif (jsonBlockMatch) {\n\t\t\t// Parse the JSON from inside the code block\n\t\t\tjsonData = JSON.parse(jsonBlockMatch[1].trim());\n\t\t} else {\n\t\t\t// Try to parse the text directly if it's not in a code block\n\t\t\tjsonData = JSON.parse(normalizeJsonString(text.trim()));\n\t\t}\n\t} catch (_e) {\n\t\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\t\treturn null;\n\t}\n\n\t// Ensure we have a non-null object that's not an array\n\tif (jsonData && typeof jsonData === \"object\" && !Array.isArray(jsonData)) {\n\t\treturn jsonData;\n\t}\n\n\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\n\treturn null;\n}\n\n/**\n * Extracts specific attributes (e.g., user, text, action) from a JSON-like string using regex.\n * @param response - The cleaned string response to extract attributes from.\n * @param attributesToExtract - An array of attribute names to extract.\n * @returns An object containing the extracted attributes.\n */\nexport function extractAttributes(\n\tresponse: string,\n\tattributesToExtract?: string[],\n): { [key: string]: string | undefined } {\n\tconst attributes: { [key: string]: string | undefined } = {};\n\n\tif (!attributesToExtract || attributesToExtract.length === 0) {\n\t\t// Extract all attributes if no specific attributes are provided\n\t\tconst matches = response.matchAll(/\"([^\"]+)\"\\s*:\\s*\"([^\"]*)\"/g);\n\t\tfor (const match of matches) {\n\t\t\tattributes[match[1]] = match[2];\n\t\t}\n\t} else {\n\t\t// Extract only specified attributes\n\t\tfor (const attribute of attributesToExtract) {\n\t\t\tconst match = response.match(\n\t\t\t\tnew RegExp(`\"${attribute}\"\\\\s*:\\\\s*\"([^\"]*)\"`, \"i\"),\n\t\t\t);\n\t\t\tif (match) {\n\t\t\t\tattributes[attribute] = match[1];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attributes;\n}\n\n/**\n * Normalizes a JSON-like string by correcting formatting issues:\n * - Removes extra spaces after '{' and before '}'.\n * - Wraps unquoted values in double quotes.\n * - Converts single-quoted values to double-quoted.\n * - Ensures consistency in key-value formatting.\n * - Normalizes mixed adjacent quote pairs.\n *\n * This is useful for cleaning up improperly formatted JSON strings\n * before parsing them into valid JSON.\n *\n * @param str - The JSON-like string to normalize.\n * @returns A properly formatted JSON string.\n */\n\nexport const normalizeJsonString = (str: string) => {\n\t// Remove extra spaces after '{' and before '}'\n\tstr = str.replace(/\\{\\s+/, \"{\").replace(/\\s+\\}/, \"}\").trim();\n\n\t// \"key\": unquotedValue → \"key\": \"unquotedValue\"\n\tstr = str.replace(\n\t\t/(\"[\\w\\d_-]+\")\\s*: \\s*(?!\"|\\[)([\\s\\S]+?)(?=(,\\s*\"|\\}$))/g,\n\t\t'$1: \"$2\"',\n\t);\n\n\t// \"key\": 'value' → \"key\": \"value\"\n\tstr = str.replace(\n\t\t/\"([^\"]+)\"\\s*:\\s*'([^']*)'/g,\n\t\t(_, key, value) => `\"${key}\": \"${value}\"`,\n\t);\n\n\t// \"key\": someWord → \"key\": \"someWord\"\n\tstr = str.replace(/(\"[\\w\\d_-]+\")\\s*:\\s*([A-Za-z_]+)(?![\"\\w])/g, '$1: \"$2\"');\n\n\t// Replace adjacent quote pairs with a single double quote\n\tstr = str.replace(/(?:\"')|(?:'\")/g, '\"');\n\treturn str;\n};\n\n/**\n * Cleans a JSON-like response string by removing unnecessary markers, line breaks, and extra whitespace.\n * This is useful for handling improperly formatted JSON responses from external sources.\n *\n * @param response - The raw JSON-like string response to clean.\n * @returns The cleaned string, ready for parsing or further processing.\n */\n\nexport function cleanJsonResponse(response: string): string {\n\treturn response\n\t\t.replace(/```json\\s*/g, \"\") // Remove ```json\n\t\t.replace(/```\\s*/g, \"\") // Remove any remaining ```\n\t\t.replace(/(\\r\\n|\\n|\\r)/g, \"\") // Remove line breaks\n\t\t.trim();\n}\n\nexport const postActionResponseFooter =\n\t\"Choose any combination of [LIKE], [RETWEET], [QUOTE], and [REPLY] that are appropriate. Each action must be on its own line. Your response must only include the chosen actions.\";\n\ntype ActionResponse = {\n\tlike: boolean;\n\tretweet: boolean;\n\tquote?: boolean;\n\treply?: boolean;\n};\n\nexport const parseActionResponseFromText = (\n\ttext: string,\n): { actions: ActionResponse } => {\n\tconst actions: ActionResponse = {\n\t\tlike: false,\n\t\tretweet: false,\n\t\tquote: false,\n\t\treply: false,\n\t};\n\n\t// Regex patterns\n\tconst likePattern = /\\[LIKE\\]/i;\n\tconst retweetPattern = /\\[RETWEET\\]/i;\n\tconst quotePattern = /\\[QUOTE\\]/i;\n\tconst replyPattern = /\\[REPLY\\]/i;\n\n\t// Check with regex\n\tactions.like = likePattern.test(text);\n\tactions.retweet = retweetPattern.test(text);\n\tactions.quote = quotePattern.test(text);\n\tactions.reply = replyPattern.test(text);\n\n\t// Also do line by line parsing as backup\n\tconst lines = text.split(\"\\n\");\n\tfor (const line of lines) {\n\t\tconst trimmed = line.trim();\n\t\tif (trimmed === \"[LIKE]\") actions.like = true;\n\t\tif (trimmed === \"[RETWEET]\") actions.retweet = true;\n\t\tif (trimmed === \"[QUOTE]\") actions.quote = true;\n\t\tif (trimmed === \"[REPLY]\") actions.reply = true;\n\t}\n\n\treturn { actions };\n};\n\n/**\n * Truncate text to fit within the character limit, ensuring it ends at a complete sentence.\n */\nexport function truncateToCompleteSentence(\n\ttext: string,\n\tmaxLength: number,\n): string {\n\tif (text.length <= maxLength) {\n\t\treturn text;\n\t}\n\n\t// Attempt to truncate at the last period within the limit\n\tconst lastPeriodIndex = text.lastIndexOf(\".\", maxLength - 1);\n\tif (lastPeriodIndex !== -1) {\n\t\tconst truncatedAtPeriod = text.slice(0, lastPeriodIndex + 1).trim();\n\t\tif (truncatedAtPeriod.length > 0) {\n\t\t\treturn truncatedAtPeriod;\n\t\t}\n\t}\n\n\t// If no period, truncate to the nearest whitespace within the limit\n\tconst lastSpaceIndex = text.lastIndexOf(\" \", maxLength - 1);\n\tif (lastSpaceIndex !== -1) {\n\t\tconst truncatedAtSpace = text.slice(0, lastSpaceIndex).trim();\n\t\tif (truncatedAtSpace.length > 0) {\n\t\t\treturn `${truncatedAtSpace}...`;\n\t\t}\n\t}\n\n\t// Fallback: Hard truncate and add ellipsis\n\tconst hardTruncated = text.slice(0, maxLength - 3).trim();\n\treturn `${hardTruncated}...`;\n}\n\n// Assuming ~4 tokens per character on average\nconst TOKENS_PER_CHAR = 4;\nconst TARGET_TOKENS = 3000;\nconst _TARGET_CHARS = Math.floor(TARGET_TOKENS / TOKENS_PER_CHAR); // ~750 chars\n\nexport async function splitChunks(\n\tcontent: string,\n\tchunkSize = 512,\n\tbleed = 20,\n): Promise<string[]> {\n\tlogger.debug(\"[splitChunks] Starting text split\");\n\n\tconst textSplitter = new RecursiveCharacterTextSplitter({\n\t\tchunkSize: Number(chunkSize),\n\t\tchunkOverlap: Number(bleed),\n\t});\n\n\tconst chunks = await textSplitter.splitText(content);\n\tlogger.debug(\"[splitChunks] Split complete:\", {\n\t\tnumberOfChunks: chunks.length,\n\t\taverageChunkSize:\n\t\t\tchunks.reduce((acc, chunk) => acc + chunk.length, 0) / chunks.length,\n\t});\n\n\treturn chunks;\n}\n\n/**\n * Trims the provided text prompt to a specified token limit using a tokenizer model and type.\n */\nexport async function trimTokens(\n\tprompt: string,\n\tmaxTokens: number,\n\truntime: IAgentRuntime,\n) {\n\tif (!prompt) throw new Error(\"Trim tokens received a null prompt\");\n\n\t// if prompt is less than of maxtokens / 5, skip\n\tif (prompt.length < maxTokens / 5) return prompt;\n\n\tif (maxTokens <= 0) throw new Error(\"maxTokens must be positive\");\n\n\ttry {\n\t\tconst tokens = await runtime.useModel(ModelTypes.TEXT_TOKENIZER_ENCODE, {\n\t\t\tprompt,\n\t\t});\n\n\t\t// If already within limits, return unchanged\n\t\tif (tokens.length <= maxTokens) {\n\t\t\treturn prompt;\n\t\t}\n\n\t\t// Keep the most recent tokens by slicing from the end\n\t\tconst truncatedTokens = tokens.slice(-maxTokens);\n\n\t\t// Decode back to text\n\t\treturn await runtime.useModel(ModelTypes.TEXT_TOKENIZER_DECODE, {\n\t\t\ttokens: truncatedTokens,\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(\"Error in trimTokens:\", error);\n\t\t// Return truncated string if tokenization fails\n\t\treturn prompt.slice(-maxTokens * 4); // Rough estimate of 4 chars per token\n\t}\n}\n","import pino, { type LogFn, type DestinationStream } from \"pino\";\nimport pretty from \"pino-pretty\";\nimport { parseBooleanFromText } from \"./prompts\";\n\ninterface LogEntry {\n\ttime?: number;\n\t[key: string]: unknown;\n}\n\n// Custom destination that maintains recent logs in memory\nclass InMemoryDestination implements DestinationStream {\n\tprivate logs: LogEntry[] = [];\n\tprivate maxLogs = 1000; // Keep last 1000 logs\n\tprivate stream: DestinationStream | null;\n\n\tconstructor(stream: DestinationStream | null) {\n\t\tthis.stream = stream;\n\t}\n\n\twrite(data: string | LogEntry): void {\n\t\t// Parse the log entry if it's a string\n\t\tconst logEntry: LogEntry =\n\t\t\ttypeof data === \"string\" ? JSON.parse(data) : data;\n\n\t\t// Add timestamp if not present\n\t\tif (!logEntry.time) {\n\t\t\tlogEntry.time = Date.now();\n\t\t}\n\n\t\t// Add to memory buffer\n\t\tthis.logs.push(logEntry);\n\n\t\t// Maintain buffer size\n\t\tif (this.logs.length > this.maxLogs) {\n\t\t\tthis.logs.shift();\n\t\t}\n\n\t\t// Forward to pretty print stream if available\n\t\tif (this.stream) {\n\t\t\t// Ensure we pass a string to the stream\n\t\t\tconst stringData = typeof data === \"string\" ? data : JSON.stringify(data);\n\t\t\tthis.stream.write(stringData);\n\t\t}\n\t}\n\n\trecentLogs(): LogEntry[] {\n\t\treturn this.logs;\n\t}\n}\n\nconst customLevels: Record<string, number> = {\n\tfatal: 60,\n\terror: 50,\n\twarn: 40,\n\tinfo: 30,\n\tlog: 29,\n\tprogress: 28,\n\tsuccess: 27,\n\tdebug: 20,\n\ttrace: 10,\n};\n\nconst raw = parseBooleanFromText(process?.env?.LOG_JSON_FORMAT) || false;\n\nconst createStream = () => {\n\tif (raw) {\n\t\treturn undefined;\n\t}\n\treturn pretty({\n\t\tcolorize: true,\n\t\ttranslateTime: \"yyyy-mm-dd HH:MM:ss\",\n\t\tignore: \"pid,hostname\",\n\t});\n};\n\nconst defaultLevel =\n\tprocess?.env?.DEFAULT_LOG_LEVEL || process?.env?.LOG_LEVEL || \"info\";\n\nconst options = {\n\tlevel: defaultLevel,\n\tcustomLevels,\n\thooks: {\n\t\tlogMethod(\n\t\t\tinputArgs: [string | Record<string, unknown>, ...unknown[]],\n\t\t\tmethod: LogFn,\n\t\t): void {\n\t\t\tconst [arg1, ...rest] = inputArgs;\n\n\t\t\tif (typeof arg1 === \"object\") {\n\t\t\t\tconst messageParts = rest.map((arg) =>\n\t\t\t\t\ttypeof arg === \"string\" ? arg : JSON.stringify(arg),\n\t\t\t\t);\n\t\t\t\tconst message = messageParts.join(\" \");\n\t\t\t\tmethod.apply(this, [arg1, message]);\n\t\t\t} else {\n\t\t\t\tconst context = {};\n\t\t\t\tconst messageParts = [arg1, ...rest].map((arg) =>\n\t\t\t\t\ttypeof arg === \"string\" ? arg : arg,\n\t\t\t\t);\n\t\t\t\tconst message = messageParts\n\t\t\t\t\t.filter((part) => typeof part === \"string\")\n\t\t\t\t\t.join(\" \");\n\t\t\t\tconst jsonParts = messageParts.filter(\n\t\t\t\t\t(part) => typeof part === \"object\",\n\t\t\t\t);\n\n\t\t\t\tObject.assign(context, ...jsonParts);\n\n\t\t\t\tmethod.apply(this, [context, message]);\n\t\t\t}\n\t\t},\n\t},\n};\n\n// Create the destination with in-memory logging\nconst stream = createStream();\nconst destination = new InMemoryDestination(stream);\n\n// Create logger with custom destination\nexport const logger = pino(options, destination);\n\n// Expose the destination for accessing recent logs\n(logger as unknown)[Symbol.for(\"pino-destination\")] = destination;\n\n// for backward compatibility\nexport const elizaLogger = logger;\n\nexport default logger;\n","import { logger, stringToUuid } from \"./index.ts\";\nimport { parseJSONObjectFromText } from \"./prompts\";\nimport { composePrompt } from \"./prompts.ts\";\nimport {\n\ttype Entity,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Relationship,\n\ttype State,\n\ttype UUID,\n} from \"./types.ts\";\n\nconst entityResolutionTemplate = `# Task: Resolve Entity Name\nMessage Sender: {{senderName}} (ID: {{senderId}})\nAgent: {{agentName}} (ID: {{agentId}})\n\n# Entities in Room:\n{{#if entitiesInRoom}}\n{{entitiesInRoom}}\n{{/if}}\n\n{{recentMessages}}\n\n# Instructions:\n1. Analyze the context to identify which entity is being referenced\n2. Consider special references like \"me\" (the message sender) or \"you\" (agent the message is directed to)\n3. Look for usernames/handles in standard formats (e.g. @username, user#1234)\n4. Consider context from recent messages for pronouns and references\n5. If multiple matches exist, use context to disambiguate\n6. Consider recent interactions and relationship strength when resolving ambiguity\n\nReturn a JSON object with:\n\\`\\`\\`json\n{\n \"entityId\": \"exact-id-if-known-otherwise-null\",\n \"type\": \"EXACT_MATCH | USERNAME_MATCH | NAME_MATCH | RELATIONSHIP_MATCH | AMBIGUOUS | UNKNOWN\",\n \"matches\": [{\n \"name\": \"matched-name\",\n \"reason\": \"why this entity matches\"\n }]\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.\n`;\n\nasync function getRecentInteractions(\n\truntime: IAgentRuntime,\n\tsourceEntityId: UUID,\n\tcandidateEntities: Entity[],\n\troomId: UUID,\n\trelationships: Relationship[],\n): Promise<{ entity: Entity; interactions: Memory[]; count: number }[]> {\n\tconst results = [];\n\n\t// Get recent messages from the room - just for context\n\tconst recentMessages = await runtime\n\t\t.getMemoryManager(\"messages\")\n\t\t.getMemories({\n\t\t\troomId,\n\t\t\tcount: 20, // Reduced from 100 since we only need context\n\t\t});\n\n\tfor (const entity of candidateEntities) {\n\t\tconst interactions: Memory[] = [];\n\t\tlet interactionScore = 0;\n\n\t\t// First get direct replies using inReplyTo\n\t\tconst directReplies = recentMessages.filter(\n\t\t\t(msg) =>\n\t\t\t\t(msg.entityId === sourceEntityId &&\n\t\t\t\t\tmsg.content.inReplyTo === entity.id) ||\n\t\t\t\t(msg.entityId === entity.id &&\n\t\t\t\t\tmsg.content.inReplyTo === sourceEntityId),\n\t\t);\n\n\t\tinteractions.push(...directReplies);\n\n\t\t// Get relationship strength from metadata\n\t\tconst relationship = relationships.find(\n\t\t\t(rel) =>\n\t\t\t\t(rel.sourceEntityId === sourceEntityId &&\n\t\t\t\t\trel.targetEntityId === entity.id) ||\n\t\t\t\t(rel.targetEntityId === sourceEntityId &&\n\t\t\t\t\trel.sourceEntityId === entity.id),\n\t\t);\n\n\t\tif (relationship?.metadata?.interactions) {\n\t\t\tinteractionScore = relationship.metadata.interactions;\n\t\t}\n\n\t\t// Add bonus points for recent direct replies\n\t\tinteractionScore += directReplies.length;\n\n\t\t// Keep last few messages for context\n\t\tconst uniqueInteractions = [...new Set(interactions)];\n\t\tresults.push({\n\t\t\tentity,\n\t\t\tinteractions: uniqueInteractions.slice(-5), // Only keep last 5 messages for context\n\t\t\tcount: Math.round(interactionScore),\n\t\t});\n\t}\n\n\t// Sort by interaction score descending\n\treturn results.sort((a, b) => b.count - a.count);\n}\n\nexport async function findEntityByName(\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate: State,\n): Promise<Entity | null> {\n\ttry {\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\tif (!room) {\n\t\t\tlogger.warn(\"Room not found for entity search\");\n\t\t\treturn null;\n\t\t}\n\n\t\tconst world = room.worldId\n\t\t\t? await runtime.getDatabaseAdapter().getWorld(room.worldId)\n\t\t\t: null;\n\n\t\t// Get all entities in the room with their components\n\t\tconst entitiesInRoom = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getEntitiesForRoom(room.id, true);\n\n\t\t// Filter components for each entity based on permissions\n\t\tconst filteredEntities = await Promise.all(\n\t\t\tentitiesInRoom.map(async (entity) => {\n\t\t\t\tif (!entity.components) return entity;\n\n\t\t\t\t// Get world roles if we have a world\n\t\t\t\tconst worldRoles = world?.metadata?.roles || {};\n\n\t\t\t\t// Filter components based on permissions\n\t\t\t\tentity.components = entity.components.filter((component) => {\n\t\t\t\t\t// 1. Pass if sourceEntityId matches the requesting entity\n\t\t\t\t\tif (component.sourceEntityId === message.entityId) return true;\n\n\t\t\t\t\t// 2. Pass if sourceEntityId is an owner/admin of the current world\n\t\t\t\t\tif (world && component.sourceEntityId) {\n\t\t\t\t\t\tconst sourceRole = worldRoles[component.sourceEntityId];\n\t\t\t\t\t\tif (sourceRole === \"OWNER\" || sourceRole === \"ADMIN\") return true;\n\t\t\t\t\t}\n\n\t\t\t\t\t// 3. Pass if sourceEntityId is the agentId\n\t\t\t\t\tif (component.sourceEntityId === runtime.agentId) return true;\n\n\t\t\t\t\t// Filter out components that don't meet any criteria\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\n\t\t\t\treturn entity;\n\t\t\t}),\n\t\t);\n\n\t\t// Get relationships for the message sender\n\t\tconst relationships = await runtime.getDatabaseAdapter().getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t});\n\n\t\t// Get entities from relationships\n\t\tconst relationshipEntities = await Promise.all(\n\t\t\trelationships.map(async (rel) => {\n\t\t\t\tconst entityId =\n\t\t\t\t\trel.sourceEntityId === message.entityId\n\t\t\t\t\t\t? rel.targetEntityId\n\t\t\t\t\t\t: rel.sourceEntityId;\n\t\t\t\treturn runtime.getDatabaseAdapter().getEntityById(entityId);\n\t\t\t}),\n\t\t);\n\n\t\t// Filter out nulls and combine with room entities\n\t\tconst allEntities = [\n\t\t\t...filteredEntities,\n\t\t\t...relationshipEntities.filter((e): e is Entity => e !== null),\n\t\t];\n\n\t\t// Get interaction strength data for relationship entities\n\t\tconst interactionData = await getRecentInteractions(\n\t\t\truntime,\n\t\t\tmessage.entityId,\n\t\t\tallEntities,\n\t\t\troom.id,\n\t\t\trelationships,\n\t\t);\n\n\t\t// Compose context for LLM\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\troomName: room.name || room.id,\n\t\t\t\tworldName: world?.name || \"Unknown\",\n\t\t\t\tentitiesInRoom: JSON.stringify(filteredEntities, null, 2),\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tsenderId: message.entityId,\n\t\t\t},\n\t\t\ttemplate: entityResolutionTemplate,\n\t\t});\n\n\t\t// Use LLM to analyze and resolve the entity\n\t\tconst result = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t\tstopSequences: [],\n\t\t});\n\n\t\t// Parse LLM response\n\t\tconst resolution = parseJSONObjectFromText(result);\n\t\tif (!resolution) {\n\t\t\tlogger.warn(\"Failed to parse entity resolution result\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// If we got an exact entity ID match\n\t\tif (resolution.type === \"EXACT_MATCH\" && resolution.entityId) {\n\t\t\tconst entity = await runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.getEntityById(resolution.entityId as UUID);\n\t\t\tif (entity) {\n\t\t\t\t// Filter components again for the returned entity\n\t\t\t\tif (entity.components) {\n\t\t\t\t\tconst worldRoles = world?.metadata?.roles || {};\n\t\t\t\t\tentity.components = entity.components.filter((component) => {\n\t\t\t\t\t\tif (component.sourceEntityId === message.entityId) return true;\n\t\t\t\t\t\tif (world && component.sourceEntityId) {\n\t\t\t\t\t\t\tconst sourceRole = worldRoles[component.sourceEntityId];\n\t\t\t\t\t\t\tif (sourceRole === \"OWNER\" || sourceRole === \"ADMIN\") return true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (component.sourceEntityId === runtime.agentId) return true;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn entity;\n\t\t\t}\n\t\t}\n\n\t\t// For username/name/relationship matches, search through all entities\n\t\tif (resolution.matches?.[0]?.name) {\n\t\t\tconst matchName = resolution.matches[0].name.toLowerCase();\n\n\t\t\t// Find matching entity by username/handle in components or by name\n\t\t\tconst matchingEntity = allEntities.find((entity) => {\n\t\t\t\t// Check names\n\t\t\t\tif (entity.names.some((n) => n.toLowerCase() === matchName))\n\t\t\t\t\treturn true;\n\n\t\t\t\t// Check components for username/handle match\n\t\t\t\treturn entity.components?.some(\n\t\t\t\t\t(c) =>\n\t\t\t\t\t\tc.data.username?.toLowerCase() === matchName ||\n\t\t\t\t\t\tc.data.handle?.toLowerCase() === matchName,\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tif (matchingEntity) {\n\t\t\t\t// If this is a relationship match, sort by interaction strength\n\t\t\t\tif (resolution.type === \"RELATIONSHIP_MATCH\") {\n\t\t\t\t\tconst interactionInfo = interactionData.find(\n\t\t\t\t\t\t(d) => d.entity.id === matchingEntity.id,\n\t\t\t\t\t);\n\t\t\t\t\tif (interactionInfo && interactionInfo.count > 0) {\n\t\t\t\t\t\treturn matchingEntity;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn matchingEntity;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t} catch (error) {\n\t\tlogger.error(\"Error in findEntityByName:\", error);\n\t\treturn null;\n\t}\n}\n\nexport const createUniqueUuid = (runtime, baseUserId: UUID | string): UUID => {\n\t// If the base user ID is the agent ID, return it directly\n\tif (baseUserId === runtime.agentId) {\n\t\treturn runtime.agentId;\n\t}\n\n\t// Use a deterministic approach to generate a new UUID based on both IDs\n\t// This creates a unique ID for each user+agent combination while still being deterministic\n\tconst combinedString = `${baseUserId}:${runtime.agentId}`;\n\n\t// Create a namespace UUID (version 5) from the combined string\n\treturn stringToUuid(combinedString);\n};\n\n/**\n * Get details for a list of entities.\n */\nexport async function getEntityDetails({\n\truntime,\n\troomId,\n}: {\n\truntime: IAgentRuntime;\n\troomId: UUID;\n}) {\n\t// Parallelize the two async operations\n\tconst [room, roomEntities] = await Promise.all([\n\t\truntime.getDatabaseAdapter().getRoom(roomId),\n\t\truntime.getDatabaseAdapter().getEntitiesForRoom(roomId, true),\n\t]);\n\n\t// Use a Map for uniqueness checking while processing entities\n\tconst uniqueEntities = new Map();\n\n\t// Process entities in a single pass\n\tfor (const entity of roomEntities) {\n\t\tif (uniqueEntities.has(entity.id)) continue;\n\n\t\t// Merge component data more efficiently\n\t\tconst allData = {};\n\t\tfor (const component of entity.components) {\n\t\t\tObject.assign(allData, component.data);\n\t\t}\n\n\t\t// Process merged data\n\t\tconst mergedData = {};\n\t\tfor (const [key, value] of Object.entries(allData)) {\n\t\t\tif (!mergedData[key]) {\n\t\t\t\tmergedData[key] = value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Array.isArray(mergedData[key]) && Array.isArray(value)) {\n\t\t\t\t// Use Set for deduplication in arrays\n\t\t\t\tmergedData[key] = [...new Set([...mergedData[key], ...value])];\n\t\t\t} else if (\n\t\t\t\ttypeof mergedData[key] === \"object\" &&\n\t\t\t\ttypeof value === \"object\"\n\t\t\t) {\n\t\t\t\tmergedData[key] = { ...mergedData[key], ...value };\n\t\t\t}\n\t\t}\n\n\t\t// Create the entity details\n\t\tuniqueEntities.set(entity.id, {\n\t\t\tid: entity.id,\n\t\t\tname: entity.metadata[room.source]?.name || entity.names[0],\n\t\t\tnames: entity.names,\n\t\t\tdata: JSON.stringify({ ...mergedData, ...entity.metadata }),\n\t\t});\n\t}\n\n\treturn Array.from(uniqueEntities.values());\n}\n","import { config } from \"dotenv\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport logger from \"./logger\";\n\ninterface Settings {\n\t[key: string]: string | undefined;\n}\n\ninterface NamespacedSettings {\n\t[namespace: string]: Settings;\n}\n\nlet environmentSettings: Settings = {};\n\n/**\n * Determines if code is running in a browser environment\n * @returns {boolean} True if in browser environment\n */\nconst isBrowser = (): boolean => {\n\treturn (\n\t\ttypeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\t);\n};\n\n/**\n * Recursively searches for a .env file starting from the current directory\n * and moving up through parent directories (Node.js only)\n * @param {string} [startDir=process.cwd()] - Starting directory for the search\n * @returns {string|null} Path to the nearest .env file or null if not found\n */\nexport function findNearestEnvFile(startDir = process.cwd()) {\n\tif (isBrowser()) return null;\n\n\tlet currentDir = startDir;\n\n\t// Continue searching until we reach the root directory\n\twhile (currentDir !== path.parse(currentDir).root) {\n\t\tconst envPath = path.join(currentDir, \".env\");\n\n\t\tif (fs.existsSync(envPath)) {\n\t\t\treturn envPath;\n\t\t}\n\n\t\t// Move up to parent directory\n\t\tcurrentDir = path.dirname(currentDir);\n\t}\n\n\t// Check root directory as well\n\tconst rootEnvPath = path.join(path.parse(currentDir).root, \".env\");\n\treturn fs.existsSync(rootEnvPath) ? rootEnvPath : null;\n}\n\n/**\n * Configures environment settings for browser usage\n * @param {Settings} settings - Object containing environment variables\n */\nexport function configureSettings(settings: Settings) {\n\tenvironmentSettings = { ...settings };\n}\n\n/**\n * Loads environment variables from the nearest .env file in Node.js\n * or returns configured settings in browser\n * @returns {Settings} Environment variables object\n * @throws {Error} If no .env file is found in Node.js environment\n */\nexport function loadEnvConfig(): Settings {\n\t// For browser environments, return the configured settings\n\tif (isBrowser()) {\n\t\treturn environmentSettings;\n\t}\n\n\t// Node.js environment: load from .env file\n\tconst envPath = findNearestEnvFile();\n\n\t// attempt to Load the .env file into process.env\n\tconst result = config(envPath ? { path: envPath } : {});\n\n\tif (!result.error) {\n\t\tlogger.log(`Loaded .env file from: ${envPath}`);\n\t}\n\n\t// Parse namespaced settings\n\tconst namespacedSettings = parseNamespacedSettings(process.env as Settings);\n\n\t// Attach to process.env for backward compatibility\n\tObject.entries(namespacedSettings).forEach(([namespace, settings]) => {\n\t\tprocess.env[`__namespaced_${namespace}`] = JSON.stringify(settings);\n\t});\n\n\treturn process.env as Settings;\n}\n\n/**\n * Gets a specific environment variable\n * @param {string} key - The environment variable key\n * @param {string} [defaultValue] - Optional default value if key doesn't exist\n * @returns {string|undefined} The environment variable value or default value\n */\nexport function getEnvVariable(\n\tkey: string,\n\tdefaultValue?: string,\n): string | undefined {\n\tif (isBrowser()) {\n\t\treturn environmentSettings[key] || defaultValue;\n\t}\n\treturn process.env[key] || defaultValue;\n}\n\n/**\n * Checks if a specific environment variable exists\n * @param {string} key - The environment variable key\n * @returns {boolean} True if the environment variable exists\n */\nexport function hasEnvVariable(key: string): boolean {\n\tif (isBrowser()) {\n\t\treturn key in environmentSettings;\n\t}\n\treturn key in process.env;\n}\n\n// Add this function to parse namespaced settings\nfunction parseNamespacedSettings(env: Settings): NamespacedSettings {\n\tconst namespaced: NamespacedSettings = {};\n\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (!value) continue;\n\n\t\tconst [namespace, ...rest] = key.split(\".\");\n\t\tif (!namespace || rest.length === 0) continue;\n\n\t\tconst settingKey = rest.join(\".\");\n\t\tnamespaced[namespace] = namespaced[namespace] || {};\n\t\tnamespaced[namespace][settingKey] = value;\n\t}\n\n\treturn namespaced;\n}\n\n// Initialize settings based on environment\nexport const settings = isBrowser() ? environmentSettings : loadEnvConfig();\n\n// Helper schemas for nested types\nexport const MessageExampleSchema = z.object({\n\tname: z.string(),\n\tcontent: z\n\t\t.object({\n\t\t\ttext: z.string(),\n\t\t\taction: z.string().optional(),\n\t\t\tsource: z.string().optional(),\n\t\t\turl: z.string().optional(),\n\t\t\tinReplyTo: z.string().uuid().optional(),\n\t\t\tattachments: z.array(z.any()).optional(),\n\t\t})\n\t\t.and(z.record(z.string(), z.unknown())), // For additional properties\n});\n\nexport const PluginSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string(),\n\tactions: z.array(z.any()).optional(),\n\tproviders: z.array(z.any()).optional(),\n\tevaluators: z.array(z.any()).optional(),\n\tservices: z.array(z.any()).optional(),\n\tclients: z.array(z.any()).optional(),\n});\n\n// Main Character schema\nexport const CharacterSchema = z.object({\n\tid: z.string().uuid().optional(),\n\tname: z.string(),\n\tsystem: z.string().optional(),\n\ttemplates: z.record(z.string()).optional(),\n\tbio: z.union([z.string(), z.array(z.string())]),\n\tmessageExamples: z.array(z.array(MessageExampleSchema)),\n\tpostExamples: z.array(z.string()),\n\ttopics: z.array(z.string()),\n\tadjectives: z.array(z.string()),\n\tknowledge: z\n\t\t.array(\n\t\t\tz.union([\n\t\t\t\tz.string(), // Direct knowledge strings\n\t\t\t\tz.object({\n\t\t\t\t\t// Individual file config\n\t\t\t\t\tpath: z.string(),\n\t\t\t\t\tshared: z.boolean().optional(),\n\t\t\t\t}),\n\t\t\t\tz.object({\n\t\t\t\t\t// Directory config\n\t\t\t\t\tdirectory: z.string(),\n\t\t\t\t\tshared: z.boolean().optional(),\n\t\t\t\t}),\n\t\t\t]),\n\t\t)\n\t\t.optional(),\n\tplugins: z.union([z.array(z.string()), z.array(PluginSchema)]),\n\tsettings: z\n\t\t.object({\n\t\t\tsecrets: z.record(z.string()).optional(),\n\t\t\tvoice: z\n\t\t\t\t.object({\n\t\t\t\t\tmodel: z.string().optional(),\n\t\t\t\t\turl: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tmodel: z.string().optional(),\n\t\t\tmodelConfig: z\n\t\t\t\t.object({\n\t\t\t\t\tmaxInputTokens: z.number().optional(),\n\t\t\t\t\tmaxOutputTokens: z.number().optional(),\n\t\t\t\t\ttemperature: z.number().optional(),\n\t\t\t\t\tfrequency_penalty: z.number().optional(),\n\t\t\t\t\tpresence_penalty: z.number().optional(),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tembeddingModel: z.string().optional(),\n\t\t})\n\t\t.optional(),\n\tstyle: z.object({\n\t\tall: z.array(z.string()),\n\t\tchat: z.array(z.string()),\n\t\tpost: z.array(z.string()),\n\t}),\n});\n\n// Type inference\nexport type CharacterConfig = z.infer<typeof CharacterSchema>;\n\n// Validation function\nexport function validateCharacterConfig(json: unknown): CharacterConfig {\n\ttry {\n\t\treturn CharacterSchema.parse(json);\n\t} catch (error) {\n\t\tif (error instanceof z.ZodError) {\n\t\t\tconst groupedErrors = error.errors.reduce(\n\t\t\t\t(acc, err) => {\n\t\t\t\t\tconst path = err.path.join(\".\");\n\t\t\t\t\tif (!acc[path]) {\n\t\t\t\t\t\tacc[path] = [];\n\t\t\t\t\t}\n\t\t\t\t\tacc[path].push(err.message);\n\t\t\t\t\treturn acc;\n\t\t\t\t},\n\t\t\t\t{} as Record<string, string[]>,\n\t\t\t);\n\n\t\t\tfor (const field in groupedErrors) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t`Validation errors in ${field}: ${groupedErrors[field].join(\" - \")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t\"Character configuration validation failed. Check logs for details.\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n var _a, _b;\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-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0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (!decoded.typ || !decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch (_a) {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import logger from \"./logger\";\n\nconst registrations = new Map<string, any>();\n\nexport const dynamicImport = async (specifier: string) => {\n\tconst module = registrations.get(specifier);\n\tif (module !== undefined) {\n\t\treturn module;\n\t}\n\treturn await import(specifier);\n};\n\nexport const registerDynamicImport = (specifier: string, module: any) => {\n\tregistrations.set(specifier, module);\n};\n\nexport async function handlePluginImporting(plugins: string[]) {\n\tif (plugins.length > 0) {\n\t\tlogger.debug(\"Imported are: \", plugins);\n\t\tconst importedPlugins = await Promise.all(\n\t\t\tplugins.map(async (plugin) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst importedPlugin = await import(plugin);\n\t\t\t\t\tconst functionName = `${plugin\n\t\t\t\t\t\t.replace(\"@elizaos/plugin-\", \"\")\n\t\t\t\t\t\t.replace(\"@elizaos-plugins/\", \"\")\n\t\t\t\t\t\t.replace(/-./g, (x) => x[1].toUpperCase())}Plugin`; // Assumes plugin function is camelCased with Plugin suffix\n\t\t\t\t\treturn importedPlugin.default || importedPlugin[functionName];\n\t\t\t\t} catch (importError) {\n\t\t\t\t\tlogger.error(`Failed to import plugin: ${plugin}`, importError);\n\t\t\t\t\treturn []; // Return null for failed imports\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn importedPlugins;\n\t}\n\treturn [];\n}\n","import logger from \"./logger.ts\";\nimport {\n\tMemoryType,\n\tModelTypes,\n\ttype IAgentRuntime,\n\ttype IMemoryManager,\n\ttype MemoryMetadata,\n\ttype Memory,\n\ttype UUID,\n} from \"./types.ts\";\n\nconst defaultMatchThreshold = 0.1;\nconst defaultMatchCount = 10;\n\n/**\n * Manage memories in the database.\n */\nexport class MemoryManager implements IMemoryManager {\n\t/**\n\t * The AgentRuntime instance associated with this manager.\n\t */\n\truntime: IAgentRuntime;\n\n\t/**\n\t * The name of the database table this manager operates on.\n\t */\n\ttableName: string;\n\n\t/**\n\t * Constructs a new MemoryManager instance.\n\t * @param opts Options for the manager.\n\t * @param opts.tableName The name of the table this manager will operate on.\n\t * @param opts.runtime The AgentRuntime instance associated with this manager.\n\t */\n\tconstructor(opts: { tableName: string; runtime: IAgentRuntime }) {\n\t\tthis.runtime = opts.runtime;\n\t\tthis.tableName = opts.tableName;\n\t}\n\n\tprivate validateMetadata(metadata: MemoryMetadata): void {\n\t\t// Check type first before any other validation\n\t\tif (!metadata.type) {\n\t\t\tthrow new Error(\"Metadata type is required\");\n\t\t}\n\n\t\t// Then validate other fields\n\t\tif (metadata.source && typeof metadata.source !== \"string\") {\n\t\t\tthrow new Error(\"Metadata source must be a string\");\n\t\t}\n\n\t\tif (metadata.sourceId && typeof metadata.sourceId !== \"string\") {\n\t\t\tthrow new Error(\"Metadata sourceId must be a UUID string\");\n\t\t}\n\n\t\tif (\n\t\t\tmetadata.scope &&\n\t\t\t![\"shared\", \"private\", \"room\"].includes(metadata.scope)\n\t\t) {\n\t\t\tthrow new Error('Metadata scope must be \"shared\", \"private\", or \"room\"');\n\t\t}\n\n\t\tif (metadata.tags && !Array.isArray(metadata.tags)) {\n\t\t\tthrow new Error(\"Metadata tags must be an array of strings\");\n\t\t}\n\t}\n\n\t/**\n\t * Adds an embedding vector to a memory object. If the memory already has an embedding, it is returned as is.\n\t * @param memory The memory object to add an embedding to.\n\t * @returns A Promise resolving to the memory object, potentially updated with an embedding vector.\n\t */\n\t/**\n\t * Adds an embedding vector to a memory object if one doesn't already exist.\n\t * The embedding is generated from the memory's text content using the runtime's\n\t * embedding model. If the memory has no text content, an error is thrown.\n\t *\n\t * @param memory The memory object to add an embedding to\n\t * @returns The memory object with an embedding vector added\n\t * @throws Error if the memory content is empty\n\t */\n\tasync addEmbeddingToMemory(memory: Memory): Promise<Memory> {\n\t\t// Return early if embedding already exists\n\t\tif (memory.embedding) {\n\t\t\treturn memory;\n\t\t}\n\n\t\tconst memoryText = memory.content.text;\n\n\t\t// Validate memory has text content\n\t\tif (!memoryText) {\n\t\t\tthrow new Error(\"Cannot generate embedding: Memory content is empty\");\n\t\t}\n\n\t\ttry {\n\t\t\t// Generate embedding from text content\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\tmemoryText,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Failed to generate embedding:\", error);\n\t\t\t// Fallback to zero vector if embedding fails\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\tnull,\n\t\t\t);\n\t\t}\n\n\t\treturn memory;\n\t}\n\n\t/**\n\t * Retrieves a list of memories by user IDs, with optional deduplication.\n\t * @param opts Options including user IDs, count, and uniqueness.\n\t * @param opts.roomId The room ID to retrieve memories for.\n\t * @param opts.count The number of memories to retrieve.\n\t * @param opts.unique Whether to retrieve unique memories only.\n\t * @returns A Promise resolving to an array of Memory objects.\n\t */\n\tasync getMemories(opts: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\tstart?: number;\n\t\tend?: number;\n\t\tagentId?: UUID;\n\t}): Promise<Memory[]> {\n\t\treturn await this.runtime.getDatabaseAdapter().getMemories({\n\t\t\troomId: opts.roomId,\n\t\t\tcount: opts.count,\n\t\t\tunique: opts.unique,\n\t\t\ttableName: this.tableName,\n\t\t\tstart: opts.start,\n\t\t\tend: opts.end,\n\t\t});\n\t}\n\n\tasync getCachedEmbeddings(content: string): Promise<\n\t\t{\n\t\t\tembedding: number[];\n\t\t\tlevenshtein_score: number;\n\t\t}[]\n\t> {\n\t\treturn await this.runtime.getDatabaseAdapter().getCachedEmbeddings({\n\t\t\tquery_table_name: this.tableName,\n\t\t\tquery_threshold: 2,\n\t\t\tquery_input: content,\n\t\t\tquery_field_name: \"content\",\n\t\t\tquery_field_sub_name: \"text\",\n\t\t\tquery_match_count: 10,\n\t\t});\n\t}\n\n\t/**\n\t * Searches for memories similar to a given embedding vector.\n\t * @param opts Options for the memory search\n\t * @param opts.match_threshold The similarity threshold for matching memories.\n\t * @param opts.count The maximum number of memories to retrieve.\n\t * @param opts.roomId The room ID to retrieve memories for.\n\t * @param opts.agentId The agent ID to retrieve memories for.\n\t * @param opts.unique Whether to retrieve unique memories only.\n\t * @returns A Promise resolving to an array of Memory objects that match the embedding.\n\t */\n\tasync searchMemories(opts: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId: UUID;\n\t\tagentId?: UUID;\n\t\tunique?: boolean;\n\t}): Promise<Memory[]> {\n\t\tconst {\n\t\t\tmatch_threshold = defaultMatchThreshold,\n\t\t\tembedding,\n\t\t\tcount = defaultMatchCount,\n\t\t\troomId,\n\t\t\tagentId,\n\t\t\tunique = true,\n\t\t} = opts;\n\n\t\treturn await this.runtime.getDatabaseAdapter().searchMemories({\n\t\t\ttableName: this.tableName,\n\t\t\troomId,\n\t\t\tembedding,\n\t\t\tmatch_threshold,\n\t\t\tcount,\n\t\t\tunique,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new memory in the database, with an option to check for similarity before insertion.\n\t * @param memory The memory object to create.\n\t * @param unique Whether to check for similarity before insertion.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync createMemory(memory: Memory, unique = false): Promise<UUID> {\n\t\tif (memory.metadata) {\n\t\t\tthis.validateMetadata(memory.metadata); // This will check type first\n\t\t\tthis.validateMetadataRequirements(memory.metadata);\n\t\t}\n\t\tconst existingMessage = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getMemoryById(memory.id);\n\n\t\tif (existingMessage) {\n\t\t\tlogger.debug(\"Memory already exists, skipping\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!memory.metadata) {\n\t\t\tmemory.metadata = {\n\t\t\t\ttype: this.tableName,\n\t\t\t\tscope: memory.agentId ? \"private\" : \"shared\",\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as MemoryMetadata;\n\t\t}\n\n\t\t// Handle metadata if present\n\t\tif (memory.metadata) {\n\t\t\t// Validate metadata\n\t\t\tthis.validateMetadata(memory.metadata);\n\n\t\t\t// Ensure timestamp\n\t\t\tif (!memory.metadata.timestamp) {\n\t\t\t\tmemory.metadata.timestamp = Date.now();\n\t\t\t}\n\n\t\t\t// Set default scope if not present\n\t\t\tif (!memory.metadata.scope) {\n\t\t\t\tmemory.metadata.scope = memory.agentId ? \"private\" : \"shared\";\n\t\t\t}\n\t\t}\n\n\t\tlogger.log(\"Creating Memory\", memory.id, memory.content.text);\n\n\t\tif (!memory.embedding) {\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\tnull,\n\t\t\t);\n\t\t}\n\n\t\tconst memoryId = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.createMemory(memory, this.tableName, unique);\n\n\t\treturn memoryId;\n\t}\n\n\tasync getMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t\tagentId?: UUID;\n\t}): Promise<Memory[]> {\n\t\treturn await this.runtime.getDatabaseAdapter().getMemoriesByRoomIds({\n\t\t\ttableName: this.tableName,\n\t\t\troomIds: params.roomIds,\n\t\t\tlimit: params.limit,\n\t\t});\n\t}\n\n\tasync getMemoryById(id: UUID): Promise<Memory | null> {\n\t\tconst result = await this.runtime.getDatabaseAdapter().getMemoryById(id);\n\t\tif (result && result.agentId !== this.runtime.agentId) return null;\n\t\treturn result;\n\t}\n\n\t/**\n\t * Removes a memory from the database by its ID.\n\t * @param memoryId The ID of the memory to remove.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync removeMemory(memoryId: UUID): Promise<void> {\n\t\tawait this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.removeMemory(memoryId, this.tableName);\n\t}\n\n\t/**\n\t * Removes all memories associated with a set of user IDs.\n\t * @param roomId The room ID to remove memories for.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync removeAllMemories(roomId: UUID): Promise<void> {\n\t\tawait this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.removeAllMemories(roomId, this.tableName);\n\t}\n\n\t/**\n\t * Counts the number of memories associated with a set of user IDs, with an option for uniqueness.\n\t * @param roomId The room ID to count memories for.\n\t * @param unique Whether to count unique memories only.\n\t * @returns A Promise resolving to the count of memories.\n\t */\n\tasync countMemories(roomId: UUID, unique = true): Promise<number> {\n\t\treturn await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.countMemories(roomId, unique, this.tableName);\n\t}\n\n\tprivate validateMetadataRequirements(metadata: MemoryMetadata) {\n\t\tif (metadata.type === MemoryType.FRAGMENT) {\n\t\t\tif (!metadata.documentId) {\n\t\t\t\tthrow new Error(\"Fragment metadata must include documentId\");\n\t\t\t}\n\t\t\tif (typeof metadata.position !== \"number\") {\n\t\t\t\tthrow new Error(\"Fragment metadata must include position\");\n\t\t\t}\n\t\t}\n\t}\n}\n","// File: /swarm/shared/ownership/core.ts\n// Updated to use world metadata instead of cache\n\nimport { createUniqueUuid } from \"./entities\";\nimport { logger } from \"./logger\";\nimport { Role, type IAgentRuntime, type World } from \"./types\";\n\nexport interface ServerOwnershipState {\n\tservers: {\n\t\t[serverId: string]: World;\n\t};\n}\n\n/**\n * Gets a user's role from world metadata\n */\nexport async function getUserServerRole(\n\truntime: IAgentRuntime,\n\tentityId: string,\n\tserverId: string,\n): Promise<Role> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.roles) {\n\t\t\treturn Role.NONE;\n\t\t}\n\n\t\tif (world.metadata.roles[entityId]?.role) {\n\t\t\treturn world.metadata.roles[entityId].role as Role;\n\t\t}\n\n\t\t// Also check original ID format\n\t\tif (world.metadata.roles[entityId]?.role) {\n\t\t\treturn world.metadata.roles[entityId].role as Role;\n\t\t}\n\n\t\treturn Role.NONE;\n\t} catch (error) {\n\t\tlogger.error(`Error getting user role: ${error}`);\n\t\treturn Role.NONE;\n\t}\n}\n\n/**\n * Finds a server where the given user is the owner\n */\nexport async function findWorldForOwner(\n\truntime: IAgentRuntime,\n\tentityId: string,\n): Promise<World | null> {\n\ttry {\n\t\tif (!entityId) {\n\t\t\tlogger.error(\"User ID is required to find server\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// Get all worlds for this agent\n\t\tconst worlds = await runtime.getDatabaseAdapter().getAllWorlds();\n\n\t\tif (!worlds || worlds.length === 0) {\n\t\t\tlogger.info(\"No worlds found for this agent\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// Find world where the user is the owner\n\t\tfor (const world of worlds) {\n\t\t\tif (world.metadata?.ownership?.ownerId === entityId) {\n\t\t\t\treturn world;\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(`No server found for owner ${entityId}`);\n\t\treturn null;\n\t} catch (error) {\n\t\tlogger.error(`Error finding server for owner: ${error}`);\n\t\treturn null;\n\t}\n}\n","import { join } from \"node:path\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { bootstrapPlugin } from \"./bootstrap.ts\";\nimport { settings } from \"./environment.ts\";\nimport { createUniqueUuid, handlePluginImporting, logger } from \"./index.ts\";\nimport { MemoryManager } from \"./memory.ts\";\nimport { splitChunks } from \"./prompts.ts\";\nimport {\n\ttype Action,\n\ttype Agent,\n\tChannelType,\n\ttype Character,\n\ttype Evaluator,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype IDatabaseAdapter,\n\ttype IMemoryManager,\n\ttype KnowledgeItem,\n\ttype Memory,\n\tMemoryType,\n\ttype ModelType,\n\tModelTypes,\n\ttype Plugin,\n\ttype Provider,\n\ttype Room,\n\ttype Route,\n\ttype Service,\n\ttype ServiceType,\n\ttype State,\n\ttype TaskWorker,\n\ttype UUID,\n\ttype World,\n} from \"./types.ts\";\nimport { stringToUuid } from \"./uuid.ts\";\n\n/**\n * Represents the runtime environment for an agent, handling message processing,\n * action registration, and interaction with external services like OpenAI and Supabase.\n */\nexport class AgentRuntime implements IAgentRuntime {\n\treadonly #conversationLength = 32 as number;\n\treadonly agentId: UUID;\n\treadonly character: Character;\n\tpublic databaseAdapter!: IDatabaseAdapter;\n\treadonly actions: Action[] = [];\n\treadonly evaluators: Evaluator[] = [];\n\treadonly providers: Provider[] = [];\n\treadonly plugins: Plugin[] = [];\n\tevents: Map<string, ((params: any) => void)[]> = new Map();\n\tstateCache = new Map<\n\t\tUUID,\n\t\t{\n\t\t\tvalues: { [key: string]: any };\n\t\t\tdata: { [key: string]: any };\n\t\t\ttext: string;\n\t\t}\n\t>();\n\n\treadonly fetch = fetch;\n\tservices: Map<ServiceType, Service> = new Map();\n\n\tpublic adapters: IDatabaseAdapter[];\n\n\tprivate readonly knowledgeRoot: string;\n\n\tmodels = new Map<string, ((params: any) => Promise<any>)[]>();\n\troutes: Route[] = [];\n\n\tprivate taskWorkers = new Map<string, TaskWorker>();\n\n\tconstructor(opts: {\n\t\tconversationLength?: number;\n\t\tagentId?: UUID;\n\t\tcharacter?: Character;\n\t\tplugins?: Plugin[];\n\t\tfetch?: typeof fetch;\n\t\tdatabaseAdapter?: IDatabaseAdapter;\n\t\tadapters?: IDatabaseAdapter[];\n\t\tevents?: { [key: string]: ((params: any) => void)[] };\n\t\tignoreBootstrap?: boolean;\n\t}) {\n\t\t// use the character id if it exists, otherwise use the agentId if it is passed in, otherwise use the character name\n\t\tthis.agentId =\n\t\t\topts.character?.id ??\n\t\t\topts?.agentId ??\n\t\t\tstringToUuid(opts.character?.name ?? uuidv4());\n\t\tthis.character = opts.character;\n\n\t\tlogger.debug(`[AgentRuntime] Process working directory: ${process.cwd()}`);\n\n\t\tthis.knowledgeRoot =\n\t\t\ttypeof process !== \"undefined\" && process.cwd\n\t\t\t\t? join(process.cwd(), \"..\", \"characters\", \"knowledge\")\n\t\t\t\t: \"./characters/knowledge\";\n\n\t\tlogger.debug(`[AgentRuntime] Process knowledgeRoot: ${this.knowledgeRoot}`);\n\n\t\tthis.#conversationLength =\n\t\t\topts.conversationLength ?? this.#conversationLength;\n\n\t\tif (opts.databaseAdapter) {\n\t\t\tthis.registerDatabaseAdapter(opts.databaseAdapter);\n\t\t}\n\n\t\tlogger.success(`Agent ID: ${this.agentId}`);\n\n\t\tthis.fetch = (opts.fetch as typeof fetch) ?? this.fetch;\n\n\t\t// Initialize adapters from options or empty array if not provided\n\t\tthis.adapters = opts.adapters ?? [];\n\n\t\t// Register plugins from options or empty array\n\t\tconst plugins = opts?.plugins ?? [];\n\n\t\t// Add bootstrap plugin if not explicitly ignored\n\t\tif (!opts?.ignoreBootstrap) {\n\t\t\tplugins.push(bootstrapPlugin);\n\t\t}\n\n\t\t// Store plugins in the array but don't initialize them yet\n\t\tthis.plugins = plugins;\n\t}\n\n\t/**\n\t * Registers a plugin with the runtime and initializes its components\n\t * @param plugin The plugin to register\n\t */\n\tasync registerPlugin(plugin: Plugin): Promise<void> {\n\t\tif (!plugin) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Add to plugins array if not already present - but only if it was not passed there initially\n\t\t// (otherwise we can't add to readonly array)\n\t\tif (!this.plugins.some((p) => p.name === plugin.name)) {\n\t\t\t// Push to plugins array - this works because we're modifying the array, not reassigning it\n\t\t\tthis.plugins.push(plugin);\n\t\t}\n\n\t\t// Register plugin adapters\n\t\tif (plugin.adapters) {\n\t\t\tfor (const adapter of plugin.adapters) {\n\t\t\t\tthis.adapters.push(adapter);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin actions\n\t\tif (plugin.actions) {\n\t\t\tfor (const action of plugin.actions) {\n\t\t\t\tthis.registerAction(action);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin evaluators\n\t\tif (plugin.evaluators) {\n\t\t\tfor (const evaluator of plugin.evaluators) {\n\t\t\t\tthis.registerEvaluator(evaluator);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin providers\n\t\tif (plugin.providers) {\n\t\t\tfor (const provider of plugin.providers) {\n\t\t\t\tthis.registerContextProvider(provider);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin models\n\t\tif (plugin.models) {\n\t\t\tfor (const [modelType, handler] of Object.entries(plugin.models)) {\n\t\t\t\tthis.registerModel(\n\t\t\t\t\tmodelType as ModelType,\n\t\t\t\t\thandler as (params: any) => Promise<any>,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin routes\n\t\tif (plugin.routes) {\n\t\t\tfor (const route of plugin.routes) {\n\t\t\t\tthis.routes.push(route);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin events\n\t\tif (plugin.events) {\n\t\t\tfor (const [eventName, eventHandlers] of Object.entries(plugin.events)) {\n\t\t\t\tfor (const eventHandler of eventHandlers) {\n\t\t\t\t\tthis.registerEvent(eventName, eventHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin services\n\t\tif (plugin.services) {\n\t\t\tawait Promise.all(\n\t\t\t\tplugin.services.map((service) => this.registerService(service)),\n\t\t\t);\n\t\t}\n\n\t\t// Initialize plugin if it has an init function\n\t\tif (plugin.init) {\n\t\t\tawait plugin.init(plugin.config, this);\n\t\t}\n\t}\n\n\tgetAllServices(): Map<ServiceType, Service> {\n\t\treturn this.services;\n\t}\n\n\tasync stop() {\n\t\tlogger.debug(`runtime::stop - character ${this.character.name}`);\n\n\t\t// Stop all registered clients\n\t\tfor (const [serviceName, service] of this.services) {\n\t\t\tlogger.log(`runtime::stop - requesting service stop for ${serviceName}`);\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\tasync initialize() {\n\t\t// First create the agent entity directly\n\t\ttry {\n\t\t\tawait this.getDatabaseAdapter().ensureAgentExists(\n\t\t\t\tthis.character as Partial<Agent>,\n\t\t\t);\n\n\t\t\t// No need to transform agent's own ID\n\t\t\tconst agentEntity = await this.getDatabaseAdapter().getEntityById(\n\t\t\t\tthis.agentId,\n\t\t\t);\n\n\t\t\tif (!agentEntity) {\n\t\t\t\tconst created = await this.getDatabaseAdapter().createEntity({\n\t\t\t\t\tid: this.agentId,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t\tnames: Array.from(\n\t\t\t\t\t\tnew Set([this.character.name].filter(Boolean)),\n\t\t\t\t\t) as string[],\n\t\t\t\t\tmetadata: {},\n\t\t\t\t});\n\n\t\t\t\tif (!created) {\n\t\t\t\t\tthrow new Error(`Failed to create entity for agent ${this.agentId}`);\n\t\t\t\t}\n\n\t\t\t\tlogger.success(\n\t\t\t\t\t`Agent entity created successfully for ${this.character.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to create agent entity: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Track registered plugins to avoid duplicates\n\t\tconst registeredPluginNames = new Set<string>();\n\n\t\t// Load and register plugins from character configuration\n\t\tconst pluginRegistrationPromises = [];\n\n\t\tif (this.character.plugins) {\n\t\t\tconst characterPlugins = (await handlePluginImporting(\n\t\t\t\tthis.character.plugins,\n\t\t\t)) as Plugin[];\n\n\t\t\t// Register each character plugin\n\t\t\tfor (const plugin of characterPlugins) {\n\t\t\t\tif (plugin && !registeredPluginNames.has(plugin.name)) {\n\t\t\t\t\tregisteredPluginNames.add(plugin.name);\n\t\t\t\t\tpluginRegistrationPromises.push(this.registerPlugin(plugin));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register plugins that were provided in the constructor\n\t\tfor (const plugin of [...this.plugins]) {\n\t\t\tif (plugin && !registeredPluginNames.has(plugin.name)) {\n\t\t\t\tregisteredPluginNames.add(plugin.name);\n\t\t\t\tpluginRegistrationPromises.push(this.registerPlugin(plugin));\n\t\t\t}\n\t\t}\n\n\t\t// Create room for the agent and register all plugins in parallel\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tthis.ensureRoomExists({\n\t\t\t\t\tid: this.agentId,\n\t\t\t\t\tname: this.character.name,\n\t\t\t\t\tsource: \"self\",\n\t\t\t\t\ttype: ChannelType.SELF,\n\t\t\t\t}),\n\t\t\t\t...pluginRegistrationPromises,\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to initialize: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Add agent as participant in its own room\n\t\ttry {\n\t\t\t// No need to transform agent ID\n\t\t\tconst participants =\n\t\t\t\tawait this.getDatabaseAdapter().getParticipantsForRoom(this.agentId);\n\t\t\tif (!participants.includes(this.agentId)) {\n\t\t\t\tconst added = await this.getDatabaseAdapter().addParticipant(\n\t\t\t\t\tthis.agentId,\n\t\t\t\t\tthis.agentId,\n\t\t\t\t);\n\t\t\t\tif (!added) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Failed to add agent ${this.agentId} as participant to its own room`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlogger.success(\n\t\t\t\t\t`Agent ${this.character.name} linked to its own room successfully`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to add agent as participant: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Process character knowledge\n\t\tif (this.character?.knowledge && this.character.knowledge.length > 0) {\n\t\t\tconst stringKnowledge = this.character.knowledge.filter(\n\t\t\t\t(item): item is string => typeof item === \"string\",\n\t\t\t);\n\t\t\tawait this.processCharacterKnowledge(stringKnowledge);\n\t\t}\n\n\t\t// Check if TEXT_EMBEDDING model is registered\n\t\tconst embeddingModel = this.getModel(ModelTypes.TEXT_EMBEDDING);\n\t\tif (!embeddingModel) {\n\t\t\tlogger.warn(\n\t\t\t\t`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered. Skipping embedding dimension setup.`,\n\t\t\t);\n\t\t} else {\n\t\t\t// Only run ensureEmbeddingDimension if we have an embedding model\n\t\t\tawait this.ensureEmbeddingDimension();\n\t\t}\n\t}\n\n\tprivate async handleProcessingError(error: any, context: string) {\n\t\tlogger.error(\n\t\t\t`Error ${context}:`,\n\t\t\terror?.message || error || \"Unknown error\",\n\t\t);\n\t\tthrow error;\n\t}\n\n\tprivate async checkExistingKnowledge(knowledgeId: UUID): Promise<boolean> {\n\t\tconst existingDocument =\n\t\t\tawait this.getMemoryManager(\"documents\").getMemoryById(knowledgeId);\n\t\treturn !!existingDocument;\n\t}\n\n\tasync getKnowledge(message: Memory): Promise<KnowledgeItem[]> {\n\t\t// Add validation for message\n\t\tif (!message?.content?.text) {\n\t\t\tlogger.warn(\"Invalid message for knowledge query:\", {\n\t\t\t\tmessage,\n\t\t\t\tcontent: message?.content,\n\t\t\t\ttext: message?.content?.text,\n\t\t\t});\n\t\t\treturn [];\n\t\t}\n\n\t\t// Validate processed text\n\t\tif (!message?.content?.text || message?.content?.text.trim().length === 0) {\n\t\t\tlogger.warn(\"Empty text for knowledge query\");\n\t\t\treturn [];\n\t\t}\n\n\t\tconst embedding = await this.useModel(\n\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\tmessage?.content?.text,\n\t\t);\n\t\tconst fragments = await this.getMemoryManager(\"knowledge\").searchMemories({\n\t\t\tembedding,\n\t\t\troomId: message.agentId,\n\t\t\tcount: 5,\n\t\t\tmatch_threshold: 0.1,\n\t\t});\n\n\t\tconst uniqueSources = [\n\t\t\t...new Set(\n\t\t\t\tfragments.map((memory) => {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`Matched fragment: ${memory.content.text} with similarity: ${memory.similarity}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn memory.content.source;\n\t\t\t\t}),\n\t\t\t),\n\t\t];\n\n\t\tconst knowledgeDocuments = await Promise.all(\n\t\t\tuniqueSources.map((source) =>\n\t\t\t\tthis.getMemoryManager(\"documents\").getMemoryById(source as UUID),\n\t\t\t),\n\t\t);\n\n\t\treturn knowledgeDocuments\n\t\t\t.filter((memory) => memory !== null)\n\t\t\t.map((memory) => ({ id: memory.id, content: memory.content }));\n\t}\n\n\tasync addKnowledge(\n\t\titem: KnowledgeItem,\n\t\toptions = {\n\t\t\ttargetTokens: 3000,\n\t\t\toverlap: 200,\n\t\t\tmodelContextSize: 4096,\n\t\t},\n\t) {\n\t\t// First store the document\n\t\tconst documentMemory: Memory = {\n\t\t\tid: item.id,\n\t\t\tagentId: this.agentId,\n\t\t\troomId: this.agentId,\n\t\t\tentityId: this.agentId,\n\t\t\tcontent: item.content,\n\t\t\tmetadata: {\n\t\t\t\ttype: MemoryType.DOCUMENT,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t};\n\n\t\tawait this.getMemoryManager(\"documents\").createMemory(documentMemory);\n\n\t\t// Create fragments using splitChunks\n\t\tconst fragments = await splitChunks(\n\t\t\titem.content.text,\n\t\t\toptions.targetTokens,\n\t\t\toptions.overlap,\n\t\t);\n\n\t\t// Store each fragment with link to source document\n\t\tfor (let i = 0; i < fragments.length; i++) {\n\t\t\tconst fragmentMemory: Memory = {\n\t\t\t\tid: createUniqueUuid(this, `${item.id}-fragment-${i}`),\n\t\t\t\tagentId: this.agentId,\n\t\t\t\troomId: this.agentId,\n\t\t\t\tentityId: this.agentId,\n\t\t\t\tcontent: { text: fragments[i] },\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: MemoryType.FRAGMENT,\n\t\t\t\t\tdocumentId: item.id, // Link to source document\n\t\t\t\t\tposition: i, // Keep track of order\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tawait this.getMemoryManager(\"knowledge\").createMemory(fragmentMemory);\n\t\t}\n\t}\n\n\tasync processCharacterKnowledge(items: string[]) {\n\t\tfor (const item of items) {\n\t\t\ttry {\n\t\t\t\tconst knowledgeId = createUniqueUuid(this, item);\n\t\t\t\tif (await this.checkExistingKnowledge(knowledgeId)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"Processing knowledge for \",\n\t\t\t\t\tthis.character.name,\n\t\t\t\t\t\" - \",\n\t\t\t\t\titem.slice(0, 100),\n\t\t\t\t);\n\n\t\t\t\tawait this.addKnowledge({\n\t\t\t\t\tid: knowledgeId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: item,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait this.handleProcessingError(\n\t\t\t\t\terror,\n\t\t\t\t\t\"processing character knowledge\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tsetSetting(\n\t\tkey: string,\n\t\tvalue: string | boolean | null | any,\n\t\tsecret = false,\n\t) {\n\t\tif (secret) {\n\t\t\tthis.character.secrets[key] = value;\n\t\t} else {\n\t\t\tthis.character.settings[key] = value;\n\t\t}\n\t}\n\n\tgetSetting(key: string): string | boolean | null | any {\n\t\tconst value =\n\t\t\tthis.character.secrets?.[key] ||\n\t\t\tthis.character.settings?.[key] ||\n\t\t\tthis.character.settings?.secrets?.[key] ||\n\t\t\tsettings[key];\n\n\t\tif (value === \"true\") return true;\n\t\tif (value === \"false\") return false;\n\t\treturn value || null;\n\t}\n\n\t/**\n\t * Get the number of messages that are kept in the conversation buffer.\n\t * @returns The number of recent messages to be kept in memory.\n\t */\n\tgetConversationLength() {\n\t\treturn this.#conversationLength;\n\t}\n\n\tregisterDatabaseAdapter(adapter: IDatabaseAdapter) {\n\t\tthis.adapters.push(adapter);\n\t}\n\n\tgetDatabaseAdapters() {\n\t\treturn this.adapters;\n\t}\n\n\tgetDatabaseAdapter() {\n\t\treturn this.adapters[0];\n\t}\n\n\t/**\n\t * Register a provider for the agent to use.\n\t * @param provider The provider to register.\n\t */\n\tregisterProvider(provider: Provider) {\n\t\tthis.providers.push(provider);\n\t}\n\n\t/**\n\t * Register an action for the agent to perform.\n\t * @param action The action to register.\n\t */\n\tregisterAction(action: Action) {\n\t\tlogger.success(\n\t\t\t`${this.character.name}(${this.agentId}) - Registering action: ${action.name}`,\n\t\t);\n\t\tthis.actions.push(action);\n\t}\n\n\t/**\n\t * Register an evaluator to assess and guide the agent's responses.\n\t * @param evaluator The evaluator to register.\n\t */\n\tregisterEvaluator(evaluator: Evaluator) {\n\t\tthis.evaluators.push(evaluator);\n\t}\n\n\t/**\n\t * Register a context provider to provide context for message generation.\n\t * @param provider The context provider to register.\n\t */\n\tregisterContextProvider(provider: Provider) {\n\t\tthis.providers.push(provider);\n\t}\n\n\t/**\n\t * Process the actions of a message.\n\t * @param message The message to process.\n\t * @param responses The array of response memories to process actions from.\n\t * @param state Optional state object for the action processing.\n\t * @param callback Optional callback handler for action results.\n\t */\n\tasync processActions(\n\t\tmessage: Memory,\n\t\tresponses: Memory[],\n\t\tstate?: State,\n\t\tcallback?: HandlerCallback,\n\t): Promise<void> {\n\t\tfor (const response of responses) {\n\t\t\tif (!response.content?.actions || response.content.actions.length === 0) {\n\t\t\t\tlogger.warn(\"No action found in the response content.\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst actions = response.content.actions;\n\n\t\t\tfunction normalizeAction(action: string) {\n\t\t\t\treturn action.toLowerCase().replace(\"_\", \"\");\n\t\t\t}\n\t\t\tlogger.success(\n\t\t\t\t`Found actions: ${this.actions.map((a) => normalizeAction(a.name))}`,\n\t\t\t);\n\n\t\t\tfor (const responseAction of actions) {\n\t\t\t\tstate = await this.composeState(message, [\"RECENT_MESSAGES\"]);\n\n\t\t\t\tlogger.success(`Calling action: ${responseAction}`);\n\t\t\t\tconst normalizedResponseAction = normalizeAction(responseAction);\n\t\t\t\tlet action = this.actions.find(\n\t\t\t\t\t(a: { name: string }) =>\n\t\t\t\t\t\tnormalizeAction(a.name).includes(normalizedResponseAction) || // the || is kind of a fuzzy match\n\t\t\t\t\t\tnormalizedResponseAction.includes(normalizeAction(a.name)), //\n\t\t\t\t);\n\n\t\t\t\tif (action) {\n\t\t\t\t\tlogger.success(`Found action: ${action?.name}`);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.error(`No action found for: ${responseAction}`);\n\t\t\t\t}\n\n\t\t\t\tif (!action) {\n\t\t\t\t\tlogger.info(\"Attempting to find action in similes.\");\n\t\t\t\t\tfor (const _action of this.actions) {\n\t\t\t\t\t\tconst simileAction = _action.similes?.find(\n\t\t\t\t\t\t\t(simile) =>\n\t\t\t\t\t\t\t\tsimile\n\t\t\t\t\t\t\t\t\t.toLowerCase()\n\t\t\t\t\t\t\t\t\t.replace(\"_\", \"\")\n\t\t\t\t\t\t\t\t\t.includes(normalizedResponseAction) ||\n\t\t\t\t\t\t\t\tnormalizedResponseAction.includes(\n\t\t\t\t\t\t\t\t\tsimile.toLowerCase().replace(\"_\", \"\"),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (simileAction) {\n\t\t\t\t\t\t\taction = _action;\n\t\t\t\t\t\t\tlogger.success(`Action found in similes: ${action.name}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!action) {\n\t\t\t\t\tlogger.error(\"No action found in\", JSON.stringify(response));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!action.handler) {\n\t\t\t\t\tlogger.error(`Action ${action.name} has no handler.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlogger.success(`Executing handler for action: ${action.name}`);\n\n\t\t\t\ttry {\n\t\t\t\t\tlogger.info(`Executing handler for action: ${action.name}`);\n\n\t\t\t\t\tawait action.handler(this, message, state, {}, callback, responses);\n\n\t\t\t\t\t// log to database\n\t\t\t\t\tawait this.getDatabaseAdapter().log({\n\t\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\ttype: \"action\",\n\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\taction: action.name,\n\t\t\t\t\t\t\tmessage: message.content.text,\n\t\t\t\t\t\t\tmessageId: message.id,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tresponses,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evaluate the message and state using the registered evaluators.\n\t * @param message The message to evaluate.\n\t * @param state The state of the agent.\n\t * @param didRespond Whether the agent responded to the message.~\n\t * @param callback The handler callback\n\t * @returns The results of the evaluation.\n\t */\n\tasync evaluate(\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\tdidRespond?: boolean,\n\t\tcallback?: HandlerCallback,\n\t\tresponses?: Memory[],\n\t) {\n\t\tconst evaluatorPromises = this.evaluators.map(\n\t\t\tasync (evaluator: Evaluator) => {\n\t\t\t\tif (!evaluator.handler) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (!didRespond && !evaluator.alwaysRun) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst result = await evaluator.validate(this, message, state);\n\n\t\t\t\tif (result) {\n\t\t\t\t\treturn evaluator;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t);\n\n\t\tconst evaluators = (await Promise.all(evaluatorPromises)).filter(\n\t\t\tBoolean,\n\t\t) as Evaluator[];\n\n\t\t// get the evaluators that were chosen by the response handler\n\n\t\tif (evaluators.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tstate = await this.composeState(message, [\"RECENT_MESSAGES\", \"EVALUATORS\"]);\n\n\t\tawait Promise.all(\n\t\t\tevaluators.map(async (evaluator) => {\n\t\t\t\tif (evaluator.handler) {\n\t\t\t\t\tawait evaluator.handler(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tcallback,\n\t\t\t\t\t\tresponses,\n\t\t\t\t\t);\n\t\t\t\t\t// log to database\n\t\t\t\t\tawait this.getDatabaseAdapter().log({\n\t\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\ttype: \"evaluator\",\n\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\tevaluator: evaluator.name,\n\t\t\t\t\t\t\tmessageId: message.id,\n\t\t\t\t\t\t\tmessage: message.content.text,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\treturn evaluators;\n\t}\n\n\tasync ensureParticipantInRoom(entityId: UUID, roomId: UUID) {\n\t\t// Make sure entity exists in database before adding as participant\n\t\tconst entity = await this.getDatabaseAdapter().getEntityById(entityId);\n\t\tif (!entity) {\n\t\t\tthrow new Error(`User ${entityId} not found`);\n\t\t}\n\t\t// Get current participants\n\t\tconst participants =\n\t\t\tawait this.getDatabaseAdapter().getParticipantsForRoom(roomId);\n\n\t\t// Only add if not already a participant\n\t\tif (!participants.includes(entityId)) {\n\t\t\t// Add participant using the tenant-specific ID that now exists in the entities table\n\t\t\tconst added = await this.getDatabaseAdapter().addParticipant(\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t);\n\n\t\t\tif (!added) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to add participant ${entityId} to room ${roomId}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (entityId === this.agentId) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Agent ${this.character.name} linked to room ${roomId} successfully.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tlogger.log(`User ${entityId} linked to room ${roomId} successfully.`);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync ensureConnection({\n\t\tentityId,\n\t\troomId,\n\t\tuserName,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: {\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\tuserName?: string;\n\t\tname?: string;\n\t\tsource?: string;\n\t\ttype?: ChannelType;\n\t\tchannelId?: string;\n\t\tserverId?: string;\n\t\tworldId?: UUID;\n\t}) {\n\t\tif (entityId === this.agentId) {\n\t\t\tthrow new Error(\"Agent should not connect to itself\");\n\t\t}\n\n\t\tif (!worldId && serverId) {\n\t\t\tworldId = createUniqueUuid(this, serverId);\n\t\t}\n\n\t\tconst names = [name, userName];\n\t\tconst metadata = {\n\t\t\t[source]: {\n\t\t\t\tname: name,\n\t\t\t\tuserName: userName,\n\t\t\t},\n\t\t};\n\n\t\tconst entity = await this.getDatabaseAdapter().getEntityById(entityId);\n\n\t\tif (!entity) {\n\t\t\tawait this.getDatabaseAdapter().createEntity({\n\t\t\t\tid: entityId,\n\t\t\t\tnames,\n\t\t\t\tmetadata,\n\t\t\t\tagentId: this.agentId,\n\t\t\t});\n\t\t}\n\n\t\t// Ensure world exists if worldId is provided\n\t\tif (worldId) {\n\t\t\tawait this.ensureWorldExists({\n\t\t\t\tid: worldId,\n\t\t\t\tname: serverId\n\t\t\t\t\t? `World for server ${serverId}`\n\t\t\t\t\t: `World for room ${roomId}`,\n\t\t\t\tagentId: this.agentId,\n\t\t\t\tserverId: serverId || \"default\",\n\t\t\t\tmetadata,\n\t\t\t});\n\t\t}\n\n\t\t// Ensure room exists\n\t\tawait this.ensureRoomExists({\n\t\t\tid: roomId,\n\t\t\tsource,\n\t\t\ttype,\n\t\t\tchannelId,\n\t\t\tserverId,\n\t\t\tworldId,\n\t\t});\n\n\t\t// Now add participants using the original IDs (will be transformed internally)\n\t\ttry {\n\t\t\tawait this.ensureParticipantInRoom(entityId, roomId);\n\t\t\tawait this.ensureParticipantInRoom(this.agentId, roomId);\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to add participants: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the existence of a world.\n\t */\n\tasync ensureWorldExists({ id, name, serverId, metadata }: World) {\n\t\ttry {\n\t\t\tconst world = await this.getDatabaseAdapter().getWorld(id);\n\t\t\tif (!world) {\n\t\t\t\tlogger.info(\"Creating world:\", {\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tserverId,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t});\n\t\t\t\tawait this.getDatabaseAdapter().createWorld({\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t\tserverId: serverId || \"default\",\n\t\t\t\t\tmetadata,\n\t\t\t\t});\n\t\t\t\tlogger.info(`World ${id} created successfully.`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to ensure world exists: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the existence of a room between the agent and a user. If no room exists, a new room is created and the user\n\t * and agent are added as participants. The room ID is returned.\n\t * @param entityId - The user ID to create a room with.\n\t * @returns The room ID of the room between the agent and the user.\n\t * @throws An error if the room cannot be created.\n\t */\n\tasync ensureRoomExists({\n\t\tid,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room) {\n\t\tconst room = await this.getDatabaseAdapter().getRoom(id);\n\t\tif (!room) {\n\t\t\tawait this.getDatabaseAdapter().createRoom({\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\tagentId: this.agentId,\n\t\t\t\tsource,\n\t\t\t\ttype,\n\t\t\t\tchannelId,\n\t\t\t\tserverId,\n\t\t\t\tworldId,\n\t\t\t});\n\t\t\tlogger.log(`Room ${id} created successfully.`);\n\t\t}\n\t}\n\n\t/**\n\t * Composes the agent's state by gathering data from enabled providers.\n\t * @param message - The message to use as context for state composition\n\t * @param filterList - Optional list of provider names to include, filtering out all others\n\t * @param includeList - Optional list of private provider names to include that would otherwise be filtered out\n\t * @returns A State object containing provider data, values, and text\n\t */\n\tasync composeState(\n\t\tmessage: Memory,\n\t\tfilterList: string[] | null = null, // only get providers that are in the filterList\n\t\tincludeList: string[] | null = null, // include providers that are private, dynamic or otherwise not included by default\n\t): Promise<State> {\n\t\t// Get cached state for this message ID first\n\t\tconst cachedState = (await this.stateCache.get(message.id)) || {\n\t\t\tvalues: {},\n\t\t\tdata: {},\n\t\t\ttext: \"\",\n\t\t};\n\n\t\t// Get existing provider names from cache (if any)\n\t\tconst existingProviderNames = cachedState.data.providers\n\t\t\t? Object.keys(cachedState.data.providers)\n\t\t\t: [];\n\n\t\t// Step 1: Determine base set of providers to fetch\n\t\tconst providerNames = new Set<string>();\n\n\t\tif (filterList && filterList.length > 0) {\n\t\t\t// If filter list provided, start with just those providers\n\t\t\tfilterList.forEach((name) => providerNames.add(name));\n\t\t} else {\n\t\t\t// Otherwise, start with all non-private, non-dynamic providers that aren't cached\n\t\t\tthis.providers\n\t\t\t\t.filter(\n\t\t\t\t\t(p) =>\n\t\t\t\t\t\t!p.private && !p.dynamic && !existingProviderNames.includes(p.name),\n\t\t\t\t)\n\t\t\t\t.forEach((p) => providerNames.add(p.name));\n\t\t}\n\n\t\t// Step 2: Always add providers from include list\n\t\tif (includeList && includeList.length > 0) {\n\t\t\tincludeList.forEach((name) => providerNames.add(name));\n\t\t}\n\n\t\t// Get the actual provider objects and sort by position\n\t\tconst providersToGet = Array.from(\n\t\t\tnew Set(this.providers.filter((p) => providerNames.has(p.name))),\n\t\t).sort((a, b) => (a.position || 0) - (b.position || 0));\n\n\t\t// Fetch data from selected providers\n\t\tconst providerData = await Promise.all(\n\t\t\tprovidersToGet.map(async (provider) => {\n\t\t\t\tconst start = Date.now();\n\t\t\t\tconst result = await provider.get(this, message, cachedState);\n\t\t\t\tconst duration = Date.now() - start;\n\t\t\t\tlogger.warn(`${provider.name} Provider took ${duration}ms to respond`);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tproviderName: provider.name,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Extract existing provider data from cache\n\t\tconst existingProviderData = cachedState.data.providers || {};\n\n\t\t// Create a combined provider values structure that preserves all cached data\n\t\t// but updates with any newly fetched provider data\n\t\tconst combinedValues = { ...existingProviderData };\n\n\t\t// Update with newly fetched provider data\n\t\tfor (const result of providerData) {\n\t\t\tcombinedValues[result.providerName] = result.values || {};\n\t\t}\n\n\t\t// Collect provider text from newly fetched providers\n\t\tconst newProvidersText = providerData\n\t\t\t.map((result) => result.text)\n\t\t\t.filter((text) => text !== \"\")\n\t\t\t.join(\"\\n\");\n\n\t\t// Combine with existing text if available\n\t\tlet providersText = \"\";\n\t\tif (cachedState.text && newProvidersText) {\n\t\t\tprovidersText = `${cachedState.text}\\n${newProvidersText}`;\n\t\t} else if (newProvidersText) {\n\t\t\tprovidersText = newProvidersText;\n\t\t} else if (cachedState.text) {\n\t\t\tprovidersText = cachedState.text;\n\t\t}\n\n\t\t// Prepare final values\n\t\tconst values = {\n\t\t\t...(cachedState.values || {}),\n\t\t};\n\n\t\t// Safely merge all provider values\n\t\tfor (const providerName in combinedValues) {\n\t\t\tconst providerValues = combinedValues[providerName];\n\t\t\tif (providerValues && typeof providerValues === \"object\") {\n\t\t\t\tObject.assign(values, providerValues);\n\t\t\t}\n\t\t}\n\n\t\t// Assemble and cache the new state\n\t\tconst newState = {\n\t\t\tvalues: {\n\t\t\t\t...values,\n\t\t\t\tproviders: providersText,\n\t\t\t},\n\t\t\tdata: {\n\t\t\t\t...(cachedState.data || {}),\n\t\t\t\tproviders: combinedValues,\n\t\t\t},\n\t\t\ttext: providersText,\n\t\t} as State;\n\n\t\t// Cache the result for future use\n\t\tthis.stateCache.set(message.id, newState);\n\t\treturn newState;\n\t}\n\n\tgetMemoryManager(tableName: string): IMemoryManager | null {\n\t\treturn new MemoryManager({\n\t\t\truntime: this,\n\t\t\ttableName: tableName,\n\t\t});\n\t}\n\n\tgetService<T extends Service>(service: ServiceType): T | null {\n\t\tconst serviceInstance = this.services.get(service);\n\t\tif (!serviceInstance) {\n\t\t\tlogger.error(`Service ${service} not found`);\n\t\t\treturn null;\n\t\t}\n\t\treturn serviceInstance as T;\n\t}\n\n\tasync registerService(service: typeof Service): Promise<void> {\n\t\tconst serviceType = service.serviceType as ServiceType;\n\t\tif (!serviceType) {\n\t\t\treturn;\n\t\t}\n\t\tlogger.log(\n\t\t\t`${this.character.name}(${this.agentId}) - Registering service:`,\n\t\t\tserviceType,\n\t\t);\n\n\t\tif (this.services.has(serviceType)) {\n\t\t\tlogger.warn(\n\t\t\t\t`${this.character.name}(${this.agentId}) - Service ${serviceType} is already registered. Skipping registration.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst serviceInstance = await service.start(this);\n\n\t\t// Add the service to the services map\n\t\tthis.services.set(serviceType, serviceInstance);\n\t\tlogger.success(\n\t\t\t`${this.character.name}(${this.agentId}) - Service ${serviceType} registered successfully`,\n\t\t);\n\t}\n\n\tregisterModel(modelType: ModelType, handler: (params: any) => Promise<any>) {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tif (!this.models.has(modelKey)) {\n\t\t\tthis.models.set(modelKey, []);\n\t\t}\n\t\tthis.models.get(modelKey)?.push(handler);\n\t}\n\n\tgetModel(\n\t\tmodelType: ModelType,\n\t): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tconst models = this.models.get(modelKey);\n\t\tif (!models?.length) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn models[0];\n\t}\n\n\tasync useModel(modelType: ModelType, params: any): Promise<any> {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tconst model = this.getModel(modelKey);\n\t\tif (!model) {\n\t\t\tthrow new Error(`No handler found for delegate type: ${modelKey}`);\n\t\t}\n\n\t\t// Call the model\n\t\tconst response = await model(this, params);\n\n\t\tawait this.getDatabaseAdapter().log({\n\t\t\tentityId: this.agentId,\n\t\t\troomId: this.agentId,\n\t\t\tbody: {\n\t\t\t\tmodelType,\n\t\t\t\tmodelKey,\n\t\t\t\tparams: params ? Object.keys(params) : [],\n\t\t\t\tresponse:\n\t\t\t\t\tArray.isArray(response) &&\n\t\t\t\t\tresponse.every((x) => typeof x === \"number\")\n\t\t\t\t\t\t? \"[array]\"\n\t\t\t\t\t\t: response,\n\t\t\t},\n\t\t\ttype: `useModel:${modelType}`,\n\t\t});\n\n\t\treturn response;\n\t}\n\n\tregisterEvent(event: string, handler: (params: any) => void) {\n\t\tif (!this.events.has(event)) {\n\t\t\tthis.events.set(event, []);\n\t\t}\n\t\tthis.events.get(event)?.push(handler);\n\t}\n\n\tgetEvent(event: string): ((params: any) => void)[] | undefined {\n\t\treturn this.events.get(event);\n\t}\n\n\temitEvent(event: string | string[], params: any) {\n\t\t// Handle both single event string and array of event strings\n\t\tconst events = Array.isArray(event) ? event : [event];\n\n\t\t// Call handlers for each event\n\t\tfor (const eventName of events) {\n\t\t\tconst eventHandlers = this.events.get(eventName);\n\n\t\t\tif (eventHandlers) {\n\t\t\t\tfor (const handler of eventHandlers) {\n\t\t\t\t\thandler(params);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync ensureEmbeddingDimension() {\n\t\tlogger.debug(\n\t\t\t`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`,\n\t\t);\n\n\t\tif (!this.getDatabaseAdapter()) {\n\t\t\tthrow new Error(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tconst model = this.getModel(ModelTypes.TEXT_EMBEDDING);\n\t\t\tif (!model) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Getting embedding dimensions`,\n\t\t\t);\n\t\t\tconst embedding = await this.useModel(ModelTypes.TEXT_EMBEDDING, null);\n\n\t\t\tif (!embedding || !embedding.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[AgentRuntime][${this.character.name}] Invalid embedding received`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${embedding.length}`,\n\t\t\t);\n\t\t\tawait this.getDatabaseAdapter().ensureEmbeddingDimension(\n\t\t\t\tembedding.length,\n\t\t\t);\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.info(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension:`,\n\t\t\t\terror,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tregisterTaskWorker(taskHandler: TaskWorker): void {\n\t\tif (this.taskWorkers.has(taskHandler.name)) {\n\t\t\tlogger.warn(\n\t\t\t\t`Task definition ${taskHandler.name} already registered. Will be overwritten.`,\n\t\t\t);\n\t\t}\n\t\tthis.taskWorkers.set(taskHandler.name, taskHandler);\n\t}\n\n\tgetTaskWorker(name: string): TaskWorker | undefined {\n\t\treturn this.taskWorkers.get(name);\n\t}\n}\n","import type { UUID } from \"node:crypto\";\nimport { v4 } from \"uuid\";\nimport { choiceAction } from \"./actions/choice.ts\";\nimport { followRoomAction } from \"./actions/followRoom.ts\";\nimport { ignoreAction } from \"./actions/ignore.ts\";\nimport { muteRoomAction } from \"./actions/muteRoom.ts\";\nimport { noneAction } from \"./actions/none.ts\";\nimport { replyAction } from \"./actions/reply.ts\";\nimport updateRoleAction from \"./actions/roles.ts\";\nimport { sendMessageAction } from \"./actions/sendMessage.ts\";\nimport updateSettingsAction from \"./actions/settings.ts\";\nimport { unfollowRoomAction } from \"./actions/unfollowRoom.ts\";\nimport { unmuteRoomAction } from \"./actions/unmuteRoom.ts\";\nimport { updateEntityAction } from \"./actions/updateEntity.ts\";\nimport { createUniqueUuid } from \"./entities.ts\";\nimport { goalEvaluator } from \"./evaluators/goal.ts\";\nimport { reflectionEvaluator } from \"./evaluators/reflection.ts\";\nimport { providersProvider } from \"./providers/providers.ts\";\nimport { logger } from \"./logger.ts\";\nimport {\n\tcomposePrompt,\n\tmessageHandlerTemplate,\n\tparseJSONObjectFromText,\n\tshouldRespondTemplate,\n} from \"./prompts.ts\";\nimport { actionsProvider } from \"./providers/actionExamples.ts\";\nimport { anxietyProvider } from \"./providers/anxiety.ts\";\nimport { attachmentsProvider } from \"./providers/attachments.ts\";\nimport { capabilitiesProvider } from \"./providers/capabilities.ts\";\nimport { characterProvider } from \"./providers/character.ts\";\nimport { choiceProvider } from \"./providers/choice.ts\";\nimport { entitiesProvider } from \"./providers/entities.ts\";\nimport { evaluatorsProvider } from \"./providers/evaluators.ts\";\nimport { factsProvider } from \"./providers/facts.ts\";\nimport { knowledgeProvider } from \"./providers/knowledge.ts\";\nimport { recentMessagesProvider } from \"./providers/recentMessages.ts\";\nimport { relationshipsProvider } from \"./providers/relationships.ts\";\nimport { roleProvider } from \"./providers/roles.ts\";\nimport { settingsProvider } from \"./providers/settings.ts\";\nimport { timeProvider } from \"./providers/time.ts\";\nimport { TaskService } from \"./services/task.ts\";\nimport {\n\ttype ChannelType,\n\ttype Content,\n\ttype Entity,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Plugin,\n\ttype Room,\n\ttype World,\n} from \"./types.ts\";\nimport { ScenarioService } from \"./services/scenario.ts\";\n\ntype ServerJoinedParams = {\n\truntime: IAgentRuntime;\n\tworld: any; // Platform-specific server object\n\tsource: string; // \"discord\", \"telegram\", etc.\n};\n\n// Add this to your types.ts file\ntype ServerConnectedParams = {\n\truntime: IAgentRuntime;\n\tworld: World;\n\trooms: Room[];\n\tusers: Entity[];\n\tsource: string;\n};\n\ntype UserJoinedParams = {\n\truntime: IAgentRuntime;\n\tuser: any;\n\tserverId: string;\n\tentityId: UUID;\n\tchannelId: string;\n\tchannelType: ChannelType;\n\tsource: string;\n};\n\ntype MessageReceivedHandlerParams = {\n\truntime: IAgentRuntime;\n\tmessage: Memory;\n\tcallback: HandlerCallback;\n};\n\nconst latestResponseIds = new Map<string, Map<string, string>>();\n\nconst messageReceivedHandler = async ({\n\truntime,\n\tmessage,\n\tcallback,\n}: MessageReceivedHandlerParams) => {\n\t// Generate a new response ID\n\tconst responseId = v4();\n\t// Get or create the agent-specific map\n\tif (!latestResponseIds.has(runtime.agentId)) {\n\t\tlatestResponseIds.set(runtime.agentId, new Map());\n\t}\n\tconst agentResponses = latestResponseIds.get(runtime.agentId)!;\n\n\t// Set this as the latest response ID for this agent+room\n\tagentResponses.set(message.roomId, responseId);\n\n\tif (message.entityId === runtime.agentId) {\n\t\tthrow new Error(\"Message is from the agent itself\");\n\t}\n\n\t// First, save the incoming message\n\tawait Promise.all([\n\t\truntime.getMemoryManager(\"messages\").addEmbeddingToMemory(message),\n\t\truntime.getMemoryManager(\"messages\").createMemory(message),\n\t]);\n\n\tconst agentUserState = await runtime\n\t\t.getDatabaseAdapter()\n\t\t.getParticipantUserState(message.roomId, runtime.agentId);\n\n\tif (\n\t\tagentUserState === \"MUTED\" &&\n\t\t!message.content.text\n\t\t\t.toLowerCase()\n\t\t\t.includes(runtime.character.name.toLowerCase())\n\t) {\n\t\tconsole.log(\"Ignoring muted room\");\n\t\treturn;\n\t}\n\n\tlet state = await runtime.composeState(message, [\n\t\t\"PROVIDERS\",\n\t\t\"SHOULD_RESPOND\",\n\t\t\"CHARACTER\",\n\t\t\"RECENT_MESSAGES\",\n\t\t\"ENTITIES\",\n\t]);\n\n\tconst shouldRespondPrompt = composePrompt({\n\t\tstate,\n\t\ttemplate:\n\t\t\truntime.character.templates?.shouldRespondTemplate ||\n\t\t\tshouldRespondTemplate,\n\t});\n\n\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\tprompt: shouldRespondPrompt,\n\t});\n\n\tconst responseObject = parseJSONObjectFromText(response);\n\n\tconst providers = responseObject.providers;\n\n\tconst shouldRespond =\n\t\tresponseObject?.action && responseObject.action === \"RESPOND\";\n\n\tstate = await runtime.composeState(message, null, providers);\n\n\tlet responseMessages: Memory[] = [];\n\n\tif (shouldRespond) {\n\t\tconst prompt = composePrompt({\n\t\t\tstate,\n\t\t\ttemplate:\n\t\t\t\truntime.character.templates?.messageHandlerTemplate ||\n\t\t\t\tmessageHandlerTemplate,\n\t\t});\n\n\t\tlet responseContent = null;\n\n\t\t// Retry if missing required fields\n\t\tlet retries = 0;\n\t\tconst maxRetries = 3;\n\t\twhile (\n\t\t\tretries < maxRetries &&\n\t\t\t(!responseContent?.thought ||\n\t\t\t\t!responseContent?.plan ||\n\t\t\t\t!responseContent?.actions)\n\t\t) {\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt,\n\t\t\t});\n\n\t\t\tresponseContent = parseJSONObjectFromText(response) as Content;\n\n\t\t\tretries++;\n\t\t\tif (\n\t\t\t\t!responseContent?.thought ||\n\t\t\t\t!responseContent?.plan ||\n\t\t\t\t!responseContent?.actions\n\t\t\t) {\n\t\t\t\tlogger.warn(\"*** Missing required fields, retrying... ***\");\n\t\t\t}\n\t\t}\n\n\t\t// Check if this is still the latest response ID for this agent+room\n\t\tconst currentResponseId = agentResponses.get(message.roomId);\n\t\tif (currentResponseId !== responseId) {\n\t\t\tlogger.info(\n\t\t\t\t`Response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tresponseContent.plan = responseContent.plan?.trim();\n\t\tresponseContent.inReplyTo = createUniqueUuid(runtime, message.id);\n\n\t\tresponseMessages = [\n\t\t\t{\n\t\t\t\tid: v4() as UUID,\n\t\t\t\tentityId: runtime.agentId,\n\t\t\t\tagentId: runtime.agentId,\n\t\t\t\tcontent: responseContent,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t},\n\t\t];\n\n\t\t// save the plan to a new reply memory\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: runtime.agentId,\n\t\t\tagentId: runtime.agentId,\n\t\t\tcontent: {\n\t\t\t\tthought: responseContent.thought,\n\t\t\t\tplan: responseContent.plan,\n\t\t\t\tactions: responseContent.actions,\n\t\t\t\tproviders: responseContent.providers,\n\t\t\t},\n\t\t\troomId: message.roomId,\n\t\t\tcreatedAt: Date.now(),\n\t\t});\n\n\t\t// Clean up the response ID\n\t\tagentResponses.delete(message.roomId);\n\t\tif (agentResponses.size === 0) {\n\t\t\tlatestResponseIds.delete(runtime.agentId);\n\t\t}\n\n\t\tawait runtime.processActions(message, responseMessages, state, callback);\n\t}\n\n\tawait runtime.evaluate(\n\t\tmessage,\n\t\tstate,\n\t\tshouldRespond,\n\t\tcallback,\n\t\tresponseMessages,\n\t);\n};\n\nconst reactionReceivedHandler = async ({\n\truntime,\n\tmessage,\n}: {\n\truntime: IAgentRuntime;\n\tmessage: Memory;\n}) => {\n\ttry {\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory(message);\n\t} catch (error) {\n\t\tif (error.code === \"23505\") {\n\t\t\tlogger.warn(\"Duplicate reaction memory, skipping\");\n\t\t\treturn;\n\t\t}\n\t\tlogger.error(\"Error in reaction handler:\", error);\n\t}\n};\n\n/**\n * Syncs a single user into an entity\n */\nconst syncSingleUser = async (\n\tentityId: UUID,\n\truntime: IAgentRuntime,\n\tuser: any,\n\tserverId: string,\n\tchannelId: string,\n\ttype: ChannelType,\n\tsource: string,\n) => {\n\tlogger.info(`Syncing user: ${user.username || user.id}`);\n\n\ttry {\n\t\t// Ensure we're not using WORLD type and that we have a valid channelId\n\t\tif (!channelId) {\n\t\t\tlogger.warn(`Cannot sync user ${user.id} without a valid channelId`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst roomId = createUniqueUuid(runtime, channelId);\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\n\t\tawait runtime.ensureConnection({\n\t\t\tentityId,\n\t\t\troomId,\n\t\t\tuserName: user.username || user.displayName || `User${user.id}`,\n\t\t\tname: user.displayName || user.username || `User${user.id}`,\n\t\t\tsource,\n\t\t\tchannelId,\n\t\t\tserverId,\n\t\t\ttype,\n\t\t\tworldId,\n\t\t});\n\n\t\tlogger.success(`Successfully synced user: ${user.username || user.id}`);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Error syncing user: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n};\n\n/**\n * Handles standardized server data for both SERVER_JOINED and SERVER_CONNECTED events\n */\nconst handleServerSync = async ({\n\truntime,\n\tworld,\n\trooms,\n\tusers,\n\tsource,\n}: ServerConnectedParams) => {\n\tlogger.info(`Handling server sync event for server: ${world.name}`);\n\ttry {\n\t\t// Create/ensure the world exists for this server\n\t\tawait runtime.ensureWorldExists({\n\t\t\tid: world.id,\n\t\t\tname: world.name,\n\t\t\tagentId: runtime.agentId,\n\t\t\tserverId: world.serverId,\n\t\t\tmetadata: {\n\t\t\t\t...world.metadata,\n\t\t\t},\n\t\t});\n\n\t\t// First sync all rooms/channels\n\t\tif (rooms && rooms.length > 0) {\n\t\t\tfor (const room of rooms) {\n\t\t\t\tawait runtime.ensureRoomExists({\n\t\t\t\t\tid: room.id,\n\t\t\t\t\tname: room.name,\n\t\t\t\t\tsource: source,\n\t\t\t\t\ttype: room.type,\n\t\t\t\t\tchannelId: room.channelId,\n\t\t\t\t\tserverId: world.serverId,\n\t\t\t\t\tworldId: world.id,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Then sync all users\n\t\tif (users && users.length > 0) {\n\t\t\t// Process users in batches to avoid overwhelming the system\n\t\t\tconst batchSize = 50;\n\t\t\tfor (let i = 0; i < users.length; i += batchSize) {\n\t\t\t\tconst entityBatch = users.slice(i, i + batchSize);\n\n\t\t\t\t// check if user is in any of these rooms in rooms\n\t\t\t\tconst firstRoomUserIsIn = rooms.length > 0 ? rooms[0] : null;\n\n\t\t\t\t// Process each user in the batch\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tentityBatch.map(async (entity: Entity) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait runtime.ensureConnection({\n\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\troomId: firstRoomUserIsIn.id,\n\t\t\t\t\t\t\t\tuserName: entity.metadata[source].username,\n\t\t\t\t\t\t\t\tname: entity.metadata[source].name,\n\t\t\t\t\t\t\t\tsource: source,\n\t\t\t\t\t\t\t\tchannelId: firstRoomUserIsIn.channelId,\n\t\t\t\t\t\t\t\tserverId: world.serverId,\n\t\t\t\t\t\t\t\ttype: firstRoomUserIsIn.type,\n\t\t\t\t\t\t\t\tworldId: world.id,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Failed to sync user ${entity.metadata.username}: ${err}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\t// Add a small delay between batches if not the last batch\n\t\t\t\tif (i + batchSize < users.length) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.success(\n\t\t\t`Successfully synced standardized world structure for ${world.name}`,\n\t\t);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Error processing standardized server data: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n};\n\nconst events = {\n\tMESSAGE_RECEIVED: [\n\t\tasync ({ runtime, message, callback }: MessageReceivedHandlerParams) => {\n\t\t\tawait messageReceivedHandler({\n\t\t\t\truntime,\n\t\t\t\tmessage,\n\t\t\t\tcallback,\n\t\t\t});\n\t\t},\n\t],\n\tVOICE_MESSAGE_RECEIVED: [\n\t\tasync ({ runtime, message, callback }: MessageReceivedHandlerParams) => {\n\t\t\tawait messageReceivedHandler({\n\t\t\t\truntime,\n\t\t\t\tmessage,\n\t\t\t\tcallback,\n\t\t\t});\n\t\t},\n\t],\n\tREACTION_RECEIVED: [reactionReceivedHandler],\n\n\t// Both events now use the same handler function\n\tSERVER_JOINED: [handleServerSync],\n\tSERVER_CONNECTED: [handleServerSync],\n\n\tUSER_JOINED: [\n\t\tasync ({\n\t\t\truntime,\n\t\t\tuser,\n\t\t\tserverId,\n\t\t\tentityId,\n\t\t\tchannelId,\n\t\t\tchannelType,\n\t\t\tsource,\n\t\t}: UserJoinedParams) => {\n\t\t\tawait syncSingleUser(\n\t\t\t\tentityId,\n\t\t\t\truntime,\n\t\t\t\tuser,\n\t\t\t\tserverId,\n\t\t\t\tchannelId,\n\t\t\t\tchannelType,\n\t\t\t\tsource,\n\t\t\t);\n\t\t},\n\t],\n};\n\nexport const bootstrapPlugin: Plugin = {\n\tname: \"bootstrap\",\n\tdescription: \"Agent bootstrap with basic actions and evaluators\",\n\tactions: [\n\t\tfollowRoomAction,\n\t\tunfollowRoomAction,\n\t\tignoreAction,\n\t\tnoneAction,\n\t\tmuteRoomAction,\n\t\tunmuteRoomAction,\n\t\tsendMessageAction,\n\t\tupdateEntityAction,\n\t\tchoiceAction,\n\t\tupdateRoleAction,\n\t\tupdateSettingsAction,\n\t\treplyAction,\n\t],\n\tevents,\n\tevaluators: [reflectionEvaluator, goalEvaluator],\n\tproviders: [\n\t\tevaluatorsProvider,\n\t\tanxietyProvider,\n\t\tknowledgeProvider,\n\t\ttimeProvider,\n\t\tcharacterProvider,\n\t\tentitiesProvider,\n\t\trelationshipsProvider,\n\t\tchoiceProvider,\n\t\tfactsProvider,\n\t\troleProvider,\n\t\tsettingsProvider,\n\t\tcapabilitiesProvider,\n\t\tattachmentsProvider,\n\t\tprovidersProvider,\n\t\tactionsProvider,\n\t\trecentMessagesProvider,\n\t],\n\tservices: [TaskService, ScenarioService],\n};\n\nexport default bootstrapPlugin;\n","import { composePrompt } from \"../prompts\";\nimport { logger } from \"../logger\";\nimport { parseJSONObjectFromText } from \"../prompts\";\nimport { getUserServerRole } from \"../roles\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nconst optionExtractionTemplate = `# Task: Extract selected task and option from user message\n\n# Available Tasks:\n{{#each tasks}}\nTask {{taskId}}: {{name}}\nAvailable options:\n{{#each options}}\n- {{name}}: {{description}}\n{{/each}}\n- ABORT: Cancel this task\n\n{{/each}}\n\n# Recent Messages:\n{{recentMessages}}\n\n# Instructions:\n1. Review the user's message and identify which task and option they are selecting\n2. Match against the available tasks and their options, including ABORT\n3. Return the task ID and selected option name exactly as listed above\n4. If no clear selection is made, return null for both fields\n\nReturn in JSON format:\n\\`\\`\\`json\n{\n \"taskId\": number | null,\n \"selectedOption\": \"OPTION_NAME\" | null\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\n\nexport const choiceAction: Action = {\n\tname: \"CHOOSE_OPTION\",\n\tsimiles: [\"SELECT_OPTION\", \"SELECT\", \"PICK\", \"CHOOSE\"],\n\tdescription: \"Selects an option for a pending task that has multiple options\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<boolean> => {\n\t\t// Get all tasks with options metadata\n\t\tconst pendingTasks = await runtime.getDatabaseAdapter().getTasks({\n\t\t\troomId: message.roomId,\n\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t});\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\n\t\tconst userRole = await getUserServerRole(\n\t\t\truntime,\n\t\t\tmessage.entityId,\n\t\t\troom.serverId,\n\t\t);\n\n\t\tif (userRole !== \"OWNER\" && userRole !== \"ADMIN\") {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Only validate if there are pending tasks with options\n\t\treturn (\n\t\t\tpendingTasks &&\n\t\t\tpendingTasks.length > 0 &&\n\t\t\tpendingTasks.some((task) => task.metadata?.options)\n\t\t);\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Handle initial responses\n\t\t\tfor (const response of responses) {\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\n\t\t\tconst pendingTasks = await runtime.getDatabaseAdapter().getTasks({\n\t\t\t\troomId: message.roomId,\n\t\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t\t});\n\n\t\t\tif (!pendingTasks?.length) {\n\t\t\t\tthrow new Error(\"No pending tasks with options found\");\n\t\t\t}\n\n\t\t\tconst tasksWithOptions = pendingTasks.filter(\n\t\t\t\t(task) => task.metadata?.options,\n\t\t\t);\n\n\t\t\tif (!tasksWithOptions.length) {\n\t\t\t\tthrow new Error(\"No tasks currently have options to select from.\");\n\t\t\t}\n\n\t\t\t// Format tasks with their options for the LLM\n\t\t\tconst formattedTasks = tasksWithOptions.map((task, index) => ({\n\t\t\t\ttaskId: index + 1,\n\t\t\t\tname: task.name,\n\t\t\t\toptions: task.metadata.options.map((opt) => ({\n\t\t\t\t\tname: typeof opt === \"string\" ? opt : opt.name,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof opt === \"string\" ? opt : opt.description || opt.name,\n\t\t\t\t})),\n\t\t\t}));\n\n\t\t\tconst prompt = composePrompt({\n\t\t\t\tstate: {\n\t\t\t\t\t...state,\n\t\t\t\t\ttasks: formattedTasks,\n\t\t\t\t\trecentMessages: message.content.text,\n\t\t\t\t},\n\t\t\t\ttemplate: optionExtractionTemplate,\n\t\t\t});\n\n\t\t\tconst result = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst parsed = parseJSONObjectFromText(result);\n\t\t\tconst { taskId, selectedOption } = parsed;\n\n\t\t\tif (taskId && selectedOption) {\n\t\t\t\tconst selectedTask = tasksWithOptions[taskId - 1];\n\n\t\t\t\tif (selectedOption === \"ABORT\") {\n\t\t\t\t\tawait runtime.getDatabaseAdapter().deleteTask(selectedTask.id);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Task \"${selectedTask.name}\" has been cancelled.`,\n\t\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst taskWorker = runtime.getTaskWorker(selectedTask.name);\n\t\t\t\t\tawait taskWorker.execute(runtime, { option: selectedOption });\n\t\t\t\t\tawait runtime.getDatabaseAdapter().deleteTask(selectedTask.id);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Selected option: ${selectedOption} for task: ${selectedTask.name}`,\n\t\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(\"Error executing task with option:\", error);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"There was an error processing your selection.\",\n\t\t\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no task/option was selected, list available options\n\t\t\tlet optionsText =\n\t\t\t\t\"Please select a valid option from one of these tasks:\\n\\n\";\n\t\t\ttasksWithOptions.forEach((task, index) => {\n\t\t\t\toptionsText += `${index + 1}. **${task.name}**:\\n`;\n\t\t\t\tconst options = task.metadata.options.map((opt) =>\n\t\t\t\t\ttypeof opt === \"string\" ? opt : opt.name,\n\t\t\t\t);\n\t\t\t\toptions.push(\"ABORT\");\n\t\t\t\toptionsText += options.map((opt) => `- ${opt}`).join(\"\\n\");\n\t\t\t\toptionsText += \"\\n\\n\";\n\t\t\t});\n\n\t\t\tawait callback({\n\t\t\t\ttext: optionsText,\n\t\t\t\tactions: [\"SELECT_OPTION_INVALID\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in select option handler:\", error);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing the option selection.\",\n\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"post\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Selected option: post for task: Confirm Twitter Post\",\n\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I choose cancel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Selected option: cancel for task: Confirm Twitter Post\",\n\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default choiceAction;\n","import { composePrompt } from \"../prompts\";\nimport logger from \"../logger\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nexport const shouldFollowTemplate = `# Task: Decide if {{agentName}} should start following this room, i.e. eagerly participating without explicit mentions.\n\n{{recentMessages}}\n\nShould {{agentName}} start following this room, eagerly participating without explicit mentions?\nRespond with YES if:\n- The user has directly asked {{agentName}} to follow the conversation or participate more actively\n- The conversation topic is highly engaging and {{agentName}}'s input would add significant value\n- {{agentName}} has unique insights to contribute and the users seem receptive\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\nexport const followRoomAction: Action = {\n\tname: \"FOLLOW_ROOM\",\n\tsimiles: [\n\t\t\"FOLLOW_CHAT\",\n\t\t\"FOLLOW_CHANNEL\",\n\t\t\"FOLLOW_CONVERSATION\",\n\t\t\"FOLLOW_THREAD\",\n\t],\n\tdescription:\n\t\t\"Start following this channel with great interest, chiming in without needing to be explicitly mentioned. Only do this if explicitly asked to.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst keywords = [\n\t\t\t\"follow\",\n\t\t\t\"participate\",\n\t\t\t\"engage\",\n\t\t\t\"listen\",\n\t\t\t\"take interest\",\n\t\t\t\"join\",\n\t\t];\n\t\tif (\n\t\t\t!keywords.some((keyword) =>\n\t\t\t\tmessage.content.text.toLowerCase().includes(keyword),\n\t\t\t)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState !== \"FOLLOWED\" && roomState !== \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldFollow(state: State): Promise<boolean> {\n\t\t\tconst shouldFollowPrompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldFollowTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldFollowPrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I will now follow this room and chime in\",\n\t\t\t\t\t\tactions: [\"FOLLOW_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"FOLLOW_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I decided to not follow this room\",\n\t\t\t\t\t\tactions: [\"FOLLOW_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"FOLLOW_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldFollow(state)) {\n\t\t\tawait runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, \"FOLLOWED\");\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I followed the room ${room.name}`,\n\t\t\t\tactions: [\"FOLLOW_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name2}} follow this channel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sure, I will now follow this room and chime in\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please start participating in discussions in this channel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Got it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'm struggling with the new database migration\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"well you did back up your data first right\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yeah i like your idea\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} can you follow this convo\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sure thing, I'm on it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"actually, unfollow it\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Haha, okay no problem\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} stay in this chat pls\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"you got it, i'm here\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"FOLLOW THIS CHAT {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'M ON IT\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"CAKE SHORTAGE ANYONE\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"WHAT WHERE'S THE CAKE AT\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} folo this covo\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"kk i'm following\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Do machines have consciousness\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Deep question, no clear answer yet\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Depends on how we define consciousness\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, monitor this convo please\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"On it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Please engage in our discussion {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Gladly, I'm here to participate\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"PLS follow this convo {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'm in, let's do this\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I LIKE TURTLES\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"beach day tmrw who down\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wish i could but gotta work\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} follow this chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sure\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, partake in our discourse henceforth\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I shall eagerly engage, good sir\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wuts ur fav clr\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"blu cuz calmmm\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey respond to everything in this channel {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"k\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { Action, ActionExample, IAgentRuntime, Memory } from \"../types\";\n\nexport const ignoreAction: Action = {\n\tname: \"IGNORE\",\n\tsimiles: [\"STOP_TALKING\", \"STOP_CHATTING\", \"STOP_CONVERSATION\"],\n\tvalidate: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\treturn true;\n\t},\n\tdescription:\n\t\t\"Call this action if ignoring the user. If the user is aggressive, creepy or is finished with the conversation, use this action. Or, if both you and the user have already said goodbye, use this action instead of saying bye again. Use IGNORE any time the conversation has naturally ended. Do not use IGNORE if the user has engaged directly, or if something went wrong an you need to tell them. Only ignore if the user should be ignored.\",\n\thandler: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<boolean> => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Go screw yourself\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Shut up, bot\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Got any investment advice\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Uh, don’t let the volatility sway your long-term strategy\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Wise words I think\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"I gotta run, talk to you later\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"See ya\" },\n\t\t\t},\n\t\t\t{ name: \"{{name1}}\", content: { text: \"\" }, actions: [\"IGNORE\"] },\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Gotta go\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Okay, talk to you later\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Cya\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"bye\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"cya\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Who added this stupid bot to the chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Sorry, am I being annoying\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Yeah\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"PLEASE shut up\" },\n\t\t\t},\n\t\t\t{ name: \"{{name2}}\", content: { text: \"\", actions: [\"IGNORE\"] } },\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"ur so dumb\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"later nerd\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"bye\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wanna cyber\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"thats inappropriate\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Im out ttyl\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"cya\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"u there\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yes how can I help\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"k nvm figured it out\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import { composePrompt } from \"../prompts\";\nimport logger from \"../logger\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nexport const shouldMuteTemplate = `# Task: Decide if {{agentName}} should mute this room and stop responding unless explicitly mentioned.\n\n{{recentMessages}}\n\nShould {{agentName}} mute this room and stop responding unless explicitly mentioned?\n\nRespond with YES if:\n- The user is being aggressive, rude, or inappropriate\n- The user has directly asked {{agentName}} to stop responding or be quiet\n- {{agentName}}'s responses are not well-received or are annoying the user(s)\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\nexport const muteRoomAction: Action = {\n\tname: \"MUTE_ROOM\",\n\tsimiles: [\n\t\t\"MUTE_CHAT\",\n\t\t\"MUTE_CONVERSATION\",\n\t\t\"MUTE_ROOM\",\n\t\t\"MUTE_THREAD\",\n\t\t\"MUTE_CHANNEL\",\n\t],\n\tdescription:\n\t\t\"Mutes a room, ignoring all messages unless explicitly mentioned. Only do this if explicitly asked to, or if you're annoying people.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState !== \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldMute(state: State): Promise<boolean> {\n\t\t\tconst shouldMutePrompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldMuteTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldMutePrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I will now mute this room\",\n\t\t\t\t\t\tactions: [\"MUTE_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"MUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I decided to not mute this room\",\n\t\t\t\t\t\tactions: [\"MUTE_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"MUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldMute(state)) {\n\t\t\tawait runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, \"MUTED\");\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I muted the room ${room.name}`,\n\t\t\t\tactions: [\"MUTE_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please mute this channel. No need to respond here for now.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Got it\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"@{{name1}} we could really use your input on this\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please mute this channel for the time being\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Understood\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey what do you think about this new design\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} plz mute this room\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"np going silent\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"whos going to the webxr meetup in an hour btw\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"too many messages here {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"my bad ill mute\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yo {{name2}} dont talk in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { Action, ActionExample, IAgentRuntime, Memory } from \"../types\";\n\nexport const noneAction: Action = {\n\tname: \"NONE\",\n\tsimiles: [\n\t\t\"NO_ACTION\",\n\t\t\"NO_RESPONSE\",\n\t\t\"NO_REACTION\",\n\t\t\"RESPONSE\",\n\t\t\"REPLY\",\n\t\t\"DEFAULT\",\n\t],\n\tvalidate: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\treturn true;\n\t},\n\tdescription:\n\t\t\"Respond but perform no additional action. This is the default if the agent is speaking and not doing anything additional.\",\n\thandler: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<boolean> => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Hey whats up\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"oh hey\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"did u see some faster whisper just came out\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yeah but its a pain to get into node.js\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"the things that were funny 6 months ago are very cringe now\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"lol true\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"too real haha\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"gotta run\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Okay, ttyl\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"heyyyyyy\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"whats up long time no see\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"chillin man. playing lots of fortnite. what about you\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"u think aliens are real\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"ya obviously\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"drop a joke on me\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"why dont scientists trust atoms cuz they make up everything lmao\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"haha good one\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hows the weather where ur at\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"beautiful all week\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import { composePrompt, parseJSONObjectFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype Content,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nconst replyTemplate = `# Task: Generate dialog and actions for the character {{agentName}}.\n{{providers}}\n# Instructions: Write the next message for {{agentName}}.\nFirst, think about what you want to do next and plan your actions. Then, write the next message and include the actions you plan to take.\n\"thought\" should be a short description of what the agent is thinking about and planning.\n\"message\" should be the next message for {{agentName}} which they will send to the conversation.\n\nThese are the available valid actions: {{actionNames}}\n\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"thought\": \"<string>\",\n \"message\": \"<string>\"\n}\n\\`\\`\\`\n\nYour response should include the valid JSON block and nothing else.`;\n\nexport const replyAction = {\n\tname: \"REPLY\",\n\tsimiles: [\"REPLY_TO_MESSAGE\", \"SEND_REPLY\", \"RESPOND\"],\n\tdescription:\n\t\t\"Replies to the current conversation with the text from the generated message. Default if the agent is responding with a message and no other action. Use REPLY at the beginning of a chain of actions as an acknowledgement, and at the end of a chain of actions as a final response.\",\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\tstate = await runtime.composeState(message, [\n\t\t\t...(message.content.providers ?? []),\n\t\t\t\"RECENT_MESSAGES\",\n\t\t]);\n\n\t\tconst prompt = composePrompt({\n\t\t\tstate,\n\t\t\ttemplate: replyTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContentObj = parseJSONObjectFromText(response) as Content;\n\n\t\tconst responseContent = {\n\t\t\tthought: responseContentObj.thought,\n\t\t\ttext: (responseContentObj.message as string) || \"\",\n\t\t\tactions: [\"REPLY\"],\n\t\t};\n\n\t\tawait callback(responseContent);\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hello there!\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hi! How can I help you today?\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"What's your favorite color?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I really like deep shades of blue. They remind me of the ocean and the night sky.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Can you explain how neural networks work?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Let me break that down for you in simple terms...\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Could you help me solve this math problem?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Of course! Let's work through it step by step.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { ZodSchema, z } from \"zod\";\nimport { createUniqueUuid } from \"..\";\nimport { composePrompt } from \"../prompts\";\nimport { logger } from \"../logger\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\tChannelType,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype ModelType,\n\tModelTypes,\n\tRole,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\nexport const generateObject = async ({\n\truntime,\n\tprompt,\n\tmodelType,\n\tstopSequences = [],\n\toutput = \"object\",\n\tenumValues = [],\n\tschema,\n}): Promise<any> => {\n\tif (!prompt) {\n\t\tconst errorMessage = \"generateObject prompt is empty\";\n\t\tconsole.error(errorMessage);\n\t\tthrow new Error(errorMessage);\n\t}\n\n\t// Special handling for enum output type\n\tif (output === \"enum\" && enumValues) {\n\t\tconst response = await runtime.useModel(modelType, {\n\t\t\truntime,\n\t\t\tprompt,\n\t\t\tmodelType,\n\t\t\tstopSequences,\n\t\t\tmaxTokens: 8,\n\t\t\tobject: true,\n\t\t});\n\n\t\t// Clean up the response to extract just the enum value\n\t\tconst cleanedResponse = response.trim();\n\n\t\t// Verify the response is one of the allowed enum values\n\t\tif (enumValues.includes(cleanedResponse)) {\n\t\t\treturn cleanedResponse;\n\t\t}\n\n\t\t// If the response includes one of the enum values (case insensitive)\n\t\tconst matchedValue = enumValues.find((value) =>\n\t\t\tcleanedResponse.toLowerCase().includes(value.toLowerCase()),\n\t\t);\n\n\t\tif (matchedValue) {\n\t\t\treturn matchedValue;\n\t\t}\n\n\t\tlogger.error(`Invalid enum value received: ${cleanedResponse}`);\n\t\tlogger.error(`Expected one of: ${enumValues.join(\", \")}`);\n\t\treturn null;\n\t}\n\n\t// Regular object/array generation\n\tconst response = await runtime.useModel(modelType, {\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\tstopSequences,\n\t\tobject: true,\n\t});\n\n\tlet jsonString = response;\n\n\t// Find appropriate brackets based on expected output type\n\tconst firstChar = output === \"array\" ? \"[\" : \"{\";\n\tconst lastChar = output === \"array\" ? \"]\" : \"}\";\n\n\tconst firstBracket = response.indexOf(firstChar);\n\tconst lastBracket = response.lastIndexOf(lastChar);\n\n\tif (firstBracket !== -1 && lastBracket !== -1 && firstBracket < lastBracket) {\n\t\tjsonString = response.slice(firstBracket, lastBracket + 1);\n\t}\n\n\tif (jsonString.length === 0) {\n\t\tlogger.error(`Failed to extract JSON ${output} from model response`);\n\t\treturn null;\n\t}\n\n\t// Parse the JSON string\n\ttry {\n\t\tconst json = JSON.parse(jsonString);\n\n\t\t// Validate against schema if provided\n\t\tif (schema) {\n\t\t\treturn schema.parse(json);\n\t\t}\n\n\t\treturn json;\n\t} catch (_error) {\n\t\tlogger.error(`Failed to parse JSON ${output}`);\n\t\tlogger.error(jsonString);\n\t\treturn null;\n\t}\n};\n\n// Role modification validation helper\nconst canModifyRole = (\n\tcurrentRole: Role,\n\ttargetRole: Role | null,\n\tnewRole: Role,\n): boolean => {\n\t// Owners can modify any role except other owners\n\tif (currentRole === Role.OWNER) {\n\t\treturn targetRole !== Role.OWNER;\n\t}\n\n\t// Admins can only modify NONE roles and can't promote to OWNER or ADMIN\n\tif (currentRole === Role.ADMIN) {\n\t\treturn (\n\t\t\t(!targetRole || targetRole === Role.NONE) &&\n\t\t\t![Role.OWNER, Role.ADMIN].includes(newRole)\n\t\t);\n\t}\n\n\treturn false;\n};\n\nconst extractionTemplate = `# Task: Extract role assignments from the conversation\n\n# Current Server Members:\n{{serverMembers}}\n\n# Available Roles:\n- OWNER: Full control over the organization\n- ADMIN: Administrative privileges\n- NONE: Standard member access\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Current speaker role: {{speakerRole}}\n\n# Instructions: Analyze the conversation and extract any role assignments being made by the speaker.\nOnly extract role assignments if:\n1. The speaker has appropriate permissions to make the change\n2. The role assignment is clearly stated\n3. The target user is a valid server member\n4. The new role is one of: OWNER, ADMIN, or NONE\n\nReturn the results in this JSON format:\n{\n\"roleAssignments\": [\n {\n \"entityId\": \"<UUID of the entity being assigned to>\",\n \"newRole\": \"ROLE_NAME\"\n }\n]\n}\n\nIf no valid role assignments are found, return an empty array.`;\n\nasync function generateObjectArray({\n\truntime,\n\tprompt,\n\tmodelType = ModelTypes.TEXT_SMALL,\n\tschema,\n\tschemaName,\n\tschemaDescription,\n}: {\n\truntime: IAgentRuntime;\n\tprompt: string;\n\tmodelType: ModelType;\n\tschema?: ZodSchema;\n\tschemaName?: string;\n\tschemaDescription?: string;\n}): Promise<z.infer<typeof schema>[]> {\n\tif (!prompt) {\n\t\tlogger.error(\"generateObjectArray prompt is empty\");\n\t\treturn [];\n\t}\n\n\tconst result = await generateObject({\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\toutput: \"array\",\n\t\tschema,\n\t});\n\n\tif (!Array.isArray(result)) {\n\t\tlogger.error(\"Generated result is not an array\");\n\t\treturn [];\n\t}\n\n\treturn schema ? schema.parse(result) : result;\n}\n\ninterface RoleAssignment {\n\tentityId: UUID;\n\tnewRole: Role;\n}\n\nconst updateRoleAction: Action = {\n\tname: \"UPDATE_ROLE\",\n\tsimiles: [\"CHANGE_ROLE\", \"SET_ROLE\", \"MODIFY_ROLE\"],\n\tdescription:\n\t\t\"Updates the role for a user with respect to the agent, world being the server they are in. For example, if an admin tells the agent that a user is their boss, set their role to ADMIN. Can only be used to set roles to ADMIN, OWNER or NONE. Can't be used to ban.\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<boolean> => {\n\t\tlogger.info(\"Starting role update validation\");\n\n\t\t// Validate message source\n\t\tif (message.content.source !== \"discord\") {\n\t\t\tlogger.info(\"Validation failed: Not a discord message\");\n\t\t\treturn false;\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\tif (!room) {\n\t\t\tthrow new Error(\"No room found\");\n\t\t}\n\n\t\t// if room type is DM, return\n\t\tif (room.type !== ChannelType.GROUP) {\n\t\t\t// only handle in a group scenario for now\n\t\t\treturn false;\n\t\t}\n\n\t\tconst serverId = room.serverId;\n\t\tif (!serverId) {\n\t\t\tthrow new Error(\"No server ID found\");\n\t\t}\n\t\ttry {\n\t\t\t// Get world data instead of ownership state from cache\n\t\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\t\t// Get requester ID and convert to UUID for consistent lookup\n\t\t\tconst requesterId = message.entityId;\n\n\t\t\t// Get roles from world metadata\n\t\t\tif (!world.metadata?.roles) {\n\t\t\t\tlogger.info(`No roles found for server ${serverId}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Lookup using UUID for consistency\n\t\t\tconst requesterRole = world.metadata.roles[requesterId] as Role;\n\n\t\t\tlogger.info(`Requester ${requesterId} role:`, requesterRole);\n\n\t\t\tif (!requesterRole) {\n\t\t\t\tlogger.info(\"Validation failed: No requester role found\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (![Role.OWNER, Role.ADMIN].includes(requesterRole)) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Validation failed: Role ${requesterRole} insufficient for role management`,\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error validating updateOrgRole action:\", error);\n\t\t\treturn false;\n\t\t}\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\t// Handle initial responses\n\t\tfor (const response of responses) {\n\t\t\tawait callback(response.content);\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(room.worldId);\n\n\t\tif (!room) {\n\t\t\tthrow new Error(\"No room found\");\n\t\t}\n\n\t\tconst serverId = world.serverId;\n\t\tconst requesterId = message.entityId;\n\n\t\tif (!world || !world.metadata) {\n\t\t\tlogger.error(`No world or metadata found for server ${serverId}`);\n\t\t\tawait callback({\n\t\t\t\ttext: \"Unable to process role changes due to missing server data.\",\n\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\tsource: \"discord\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Ensure roles object exists\n\t\tif (!world.metadata.roles) {\n\t\t\tworld.metadata.roles = {};\n\t\t}\n\n\t\t// Get requester's role from world metadata\n\t\tconst requesterRole =\n\t\t\t(world.metadata.roles[requesterId] as Role) || Role.NONE;\n\n\t\t// Get all entities in the room\n\t\tconst entities = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getEntitiesForRoom(room.id, true);\n\n\t\t// Build server members prompt from entities\n\t\tconst serverMembersContext = entities\n\t\t\t.map((entity) => {\n\t\t\t\tconst discordData = entity.components?.find(\n\t\t\t\t\t(c) => c.type === \"discord\",\n\t\t\t\t)?.data;\n\t\t\t\tconst name = discordData?.username || entity.names[0];\n\t\t\t\tconst id = entity.id;\n\t\t\t\treturn `${name} (${id})`;\n\t\t\t})\n\t\t\t.join(\"\\n\");\n\n\t\t// Create extraction prompt\n\t\tconst extractionPrompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tserverMembers: serverMembersContext,\n\t\t\t\tspeakerRole: requesterRole,\n\t\t\t},\n\t\t\ttemplate: extractionTemplate,\n\t\t});\n\n\t\t// Extract role assignments\n\t\tconst result = (await generateObjectArray({\n\t\t\truntime,\n\t\t\tprompt: extractionPrompt,\n\t\t\tmodelType: ModelTypes.TEXT_SMALL,\n\t\t})) as RoleAssignment[];\n\n\t\tif (!result?.length) {\n\t\t\tawait callback({\n\t\t\t\ttext: \"No valid role assignments found in the request.\",\n\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\tsource: \"discord\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Process each role assignment\n\t\tlet worldUpdated = false;\n\n\t\tfor (const assignment of result) {\n\t\t\tlet targetEntity = entities.find((e) => e.id === assignment.entityId);\n\t\t\tif (!targetEntity) {\n\t\t\t\ttargetEntity = entities.find((e) => e.id === assignment.entityId);\n\t\t\t\tconsole.log(\"Trying to write to generated tenant ID\");\n\t\t\t}\n\t\t\tif (!targetEntity) {\n\t\t\t\tconsole.log(\"Could not find an ID ot assign to\");\n\t\t\t}\n\n\t\t\tconst currentRole = world.metadata.roles[assignment.entityId];\n\n\t\t\t// Validate role modification permissions\n\t\t\tif (!canModifyRole(requesterRole, currentRole, assignment.newRole)) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `You don't have permission to change ${targetEntity.names[0]}'s role to ${assignment.newRole}.`,\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Update role in world metadata\n\t\t\tworld.metadata.roles[assignment.entityId] = assignment.newRole;\n\n\t\t\tworldUpdated = true;\n\n\t\t\tawait callback({\n\t\t\t\ttext: `Updated ${targetEntity.names[0]}'s role to ${assignment.newRole}.`,\n\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\tsource: \"discord\",\n\t\t\t});\n\t\t}\n\n\t\t// Save updated world metadata if any changes were made\n\t\tif (worldUpdated) {\n\t\t\tawait runtime.getDatabaseAdapter().updateWorld(world);\n\t\t\tlogger.info(`Updated roles in world metadata for server ${serverId}`);\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Make {{name2}} an ADMIN\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Updated {{name2}}'s role to ADMIN.\",\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set @alice and @bob as admins\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Updated alice's role to ADMIN.\\nUpdated bob's role to ADMIN.\",\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Ban @troublemaker\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I cannot ban users.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateRoleAction;\n","// action: SEND_MESSAGE\n// send message to a user or room (other than this room we are in)\n\nimport { findEntityByName } from \"../entities\";\nimport { logger } from \"../logger\";\nimport { composePrompt, parseJSONObjectFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nconst targetExtractionTemplate = `# Task: Extract Target and Source Information\n\n# Recent Messages:\n{{recentMessages}}\n\n# Instructions:\nAnalyze the conversation to identify:\n1. The target type (user or room)\n2. The target platform/source (e.g. telegram, discord, etc)\n3. Any identifying information about the target\n\nReturn a JSON object with:\n\\`\\`\\`json\n{\n \"targetType\": \"user|room\",\n \"source\": \"platform-name\",\n \"identifiers\": {\n // Relevant identifiers for that target\n // e.g. username, roomName, etc.\n }\n}\n\\`\\`\\`\nExample outputs:\n1. For \"send a message to @dev_guru on telegram\":\n\\`\\`\\`json\n{\n \"targetType\": \"user\",\n \"source\": \"telegram\",\n \"identifiers\": {\n \"username\": \"dev_guru\"\n }\n}\n\\`\\`\\`\n\n2. For \"post this in #announcements\":\n\\`\\`\\`json\n{\n \"targetType\": \"room\",\n \"source\": \"discord\",\n \"identifiers\": {\n \"roomName\": \"announcements\"\n }\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\nexport const sendMessageAction: Action = {\n\tname: \"SEND_MESSAGE\",\n\tsimiles: [\"DM\", \"MESSAGE\", \"SEND_DM\", \"POST_MESSAGE\"],\n\tdescription: \"Send a message to a user or room (other than the current one)\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\t// Check if we have permission to send messages\n\t\tconst worldId = message.roomId;\n\t\tconst agentId = runtime.agentId;\n\n\t\t// Get all components for the current room to understand available sources\n\t\tconst roomComponents = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getComponents(message.roomId, worldId, agentId);\n\n\t\t// Get source types from room components\n\t\tconst availableSources = new Set(roomComponents.map((c) => c.type));\n\n\t\t// TODO: Add ability for plugins to register their sources\n\t\t// const registeredSources = runtime.getRegisteredSources?.() || [];\n\t\t// availableSources.add(...registeredSources);\n\n\t\treturn availableSources.size > 0;\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Handle initial responses\n\t\t\tfor (const response of responses) {\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\n\t\t\tconst sourceEntityId = message.entityId;\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\t\tconst worldId = room.worldId;\n\n\t\t\t// Extract target and source information\n\t\t\tconst targetPrompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: targetExtractionTemplate,\n\t\t\t});\n\n\t\t\tconst targetResult = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt: targetPrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst targetData = parseJSONObjectFromText(targetResult);\n\t\t\tif (!targetData?.targetType || !targetData?.source) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I couldn't determine where you want me to send the message. Could you please specify the target (user or room) and platform?\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst source = targetData.source.toLowerCase();\n\n\t\t\tif (targetData.targetType === \"user\") {\n\t\t\t\t// Try to find the target user entity\n\t\t\t\tconst targetEntity = await findEntityByName(runtime, message, state);\n\n\t\t\t\tif (!targetEntity) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the user you want me to send a message to. Could you please provide more details about who they are?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Get the component for the specified source\n\t\t\t\tconst userComponent = await runtime\n\t\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t\t.getComponent(targetEntity.id!, source, worldId, sourceEntityId);\n\n\t\t\t\tif (!userComponent) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `I couldn't find ${source} information for that user. Could you please provide their ${source} details?`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sendDirectMessage = (runtime.getService(source) as any)\n\t\t\t\t\t?.sendDirectMessage;\n\n\t\t\t\tif (!sendDirectMessage) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the user you want me to send a message to. Could you please provide more details about who they are?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Send the message using the appropriate client\n\t\t\t\ttry {\n\t\t\t\t\tawait sendDirectMessage(\n\t\t\t\t\t\truntime,\n\t\t\t\t\t\ttargetEntity.id!,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tmessage.content.text,\n\t\t\t\t\t\tworldId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Message sent to ${targetEntity.names[0]} on ${source}.`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Failed to send direct message: ${error.message}`);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I encountered an error trying to send the message. Please try again.\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (targetData.targetType === \"room\") {\n\t\t\t\t// Try to find the target room\n\t\t\t\tconst rooms = await runtime.getDatabaseAdapter().getRooms(worldId);\n\t\t\t\tconst targetRoom = rooms.find((r) => {\n\t\t\t\t\t// Match room name from identifiers\n\t\t\t\t\treturn (\n\t\t\t\t\t\tr.name.toLowerCase() ===\n\t\t\t\t\t\ttargetData.identifiers.roomName?.toLowerCase()\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tif (!targetRoom) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the room you want me to send a message to. Could you please specify the exact room name?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sendRoomMessage = (runtime.getService(source) as any)\n\t\t\t\t\t?.sendRoomMessage;\n\n\t\t\t\tif (!sendRoomMessage) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the room you want me to send a message to. Could you please specify the exact room name?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Send the message to the room\n\t\t\t\ttry {\n\t\t\t\t\tawait sendRoomMessage(\n\t\t\t\t\t\truntime,\n\t\t\t\t\t\ttargetRoom.id,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tmessage.content.text,\n\t\t\t\t\t\tworldId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Message sent to ${targetRoom.name} on ${source}.`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Failed to send room message: ${error.message}`);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I encountered an error trying to send the message to the room. Please try again.\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in sendMessage handler: ${error}`);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing your message request.\",\n\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Send a message to @dev_guru on telegram saying 'Hello!'\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to dev_guru on telegram.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Post 'Important announcement!' in #announcements\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to announcements.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"DM Jimmy and tell him 'Meeting at 3pm'\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to Jimmy.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default sendMessageAction;\n","import type { z, ZodSchema } from \"zod\";\nimport { createUniqueUuid } from \"../entities\";\nimport { logger } from \"../logger\";\nimport { composePrompt, parseJSONObjectFromText } from \"../prompts\";\nimport { findWorldForOwner } from \"../roles\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\tChannelType,\n\ttype Content,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype ModelType,\n\tModelTypes,\n\ttype Setting,\n\ttype State,\n\ttype WorldSettings,\n} from \"../types\";\n\ninterface SettingUpdate {\n\tkey: string;\n\tvalue: string | boolean;\n}\n\nconst messageCompletionFooter = `\\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"thought\": \"<string>\", \"actions\": [\"<string>\", \"<string>\", \"<string>\"] }\n\\`\\`\\`\nDo not including any thinking or internal reflection in the \"text\" field.\n\"thought\" should be a short description of what the agent is thinking about before responding, including a brief justification for the response.`;\n\n// Template for success responses when settings are updated\nconst successTemplate = `# Task: Generate a response for successful setting updates\n{{providers}}\n\n# Update Information:\n- Updated Settings: {{updateMessages}}\n- Next Required Setting: {{nextSetting.name}}\n- Remaining Required Settings: {{remainingRequired}}\n\n# Instructions:\n1. Acknowledge the successful update of settings\n2. Maintain {{agentName}}'s personality and tone\n3. Provide clear guidance on the next setting that needs to be configured\n4. Explain what the next setting is for and how to set it\n5. If appropriate, mention how many required settings remain\n\nWrite a natural, conversational response that {{agentName}} would send about the successful update and next steps.\nInclude the actions array [\"SETTING_UPDATED\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for failure responses when settings couldn't be updated\nconst failureTemplate = `# Task: Generate a response for failed setting updates\n\n# About {{agentName}}:\n{{bio}}\n\n# Current Settings Status:\n{{settingsStatus}}\n\n# Next Required Setting:\n- Name: {{nextSetting.name}}\n- Description: {{nextSetting.description}}\n- Required: Yes\n- Remaining Required Settings: {{remainingRequired}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Express that you couldn't understand or process the setting update\n2. Maintain {{agentName}}'s personality and tone\n3. Provide clear guidance on what setting needs to be configured next\n4. Explain what the setting is for and how to set it properly\n5. Use a helpful, patient tone\n\nWrite a natural, conversational response that {{agentName}} would send about the failed update and how to proceed.\nInclude the actions array [\"SETTING_UPDATE_FAILED\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for error responses when unexpected errors occur\nconst errorTemplate = `# Task: Generate a response for an error during setting updates\n\n# About {{agentName}}:\n{{bio}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Apologize for the technical difficulty\n2. Maintain {{agentName}}'s personality and tone\n3. Suggest trying again or contacting support if the issue persists\n4. Keep the message concise and helpful\n\nWrite a natural, conversational response that {{agentName}} would send about the error.\nInclude the actions array [\"SETTING_UPDATE_ERROR\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for completion responses when all required settings are configured\nconst completionTemplate = `# Task: Generate a response for settings completion\n\n# About {{agentName}}:\n{{bio}}\n\n# Settings Status:\n{{settingsStatus}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Congratulate the user on completing the settings process\n2. Maintain {{agentName}}'s personality and tone\n3. Summarize the key settings that have been configured\n4. Explain what functionality is now available\n5. Provide guidance on what the user can do next\n6. Express enthusiasm about working together\n\nWrite a natural, conversational response that {{agentName}} would send about the successful completion of settings.\nInclude the actions array [\"ONBOARDING_COMPLETE\"] in your response.\n${messageCompletionFooter}`;\n\n// Enhanced extraction template that explicitly handles multiple settings\nconst extractionTemplate = `# Task: Extract setting values from the conversation\n\n# Available Settings:\n{{#each settings}}\n{{key}}:\n Name: {{name}}\n Description: {{description}}\n Current Value: {{value}}\n Required: {{required}}\n Validation Rules: {{#if validation}}Present{{else}}None{{/if}}\n{{/each}}\n\n# Current Settings Status:\n{{settingsStatus}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Review the ENTIRE conversation and identify ALL values provided for settings\n2. For each setting mentioned, extract:\n - The setting key (must exactly match one of the available settings above)\n - The provided value that matches the setting's description and purpose\n3. Return an array of ALL setting updates found, even if mentioned earlier in the conversation\n\nReturn ONLY a JSON array of objects with 'key' and 'value' properties. Format:\n[\n { \"key\": \"SETTING_NAME\", \"value\": \"extracted value\" },\n { \"key\": \"ANOTHER_SETTING\", \"value\": \"another value\" }\n]\n\nIMPORTANT: Only include settings from the Available Settings list above. Ignore any other potential settings.`;\n\nconst generateObject = async ({\n\truntime,\n\tprompt,\n\tmodelType = ModelTypes.TEXT_LARGE as ModelType,\n\tstopSequences = [],\n\toutput = \"object\",\n\tenumValues = [],\n\tschema,\n}): Promise<any> => {\n\tif (!prompt) {\n\t\tconst errorMessage = \"generateObject prompt is empty\";\n\t\tconsole.error(errorMessage);\n\t\tthrow new Error(errorMessage);\n\t}\n\n\t// Special handling for enum output type\n\tif (output === \"enum\" && enumValues) {\n\t\tconst response = await runtime.useModel(modelType, {\n\t\t\truntime,\n\t\t\tprompt,\n\t\t\tmodelType,\n\t\t\tstopSequences,\n\t\t\tmaxTokens: 8,\n\t\t\tobject: true,\n\t\t});\n\n\t\t// Clean up the response to extract just the enum value\n\t\tconst cleanedResponse = response.trim();\n\n\t\t// Verify the response is one of the allowed enum values\n\t\tif (enumValues.includes(cleanedResponse)) {\n\t\t\treturn cleanedResponse;\n\t\t}\n\n\t\t// If the response includes one of the enum values (case insensitive)\n\t\tconst matchedValue = enumValues.find((value) =>\n\t\t\tcleanedResponse.toLowerCase().includes(value.toLowerCase()),\n\t\t);\n\n\t\tif (matchedValue) {\n\t\t\treturn matchedValue;\n\t\t}\n\n\t\tlogger.error(`Invalid enum value received: ${cleanedResponse}`);\n\t\tlogger.error(`Expected one of: ${enumValues.join(\", \")}`);\n\t\treturn null;\n\t}\n\n\t// Regular object/array generation\n\tconst response = await runtime.useModel(modelType, {\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\tstopSequences,\n\t\tobject: true,\n\t});\n\n\tlet jsonString = response;\n\n\t// Find appropriate brackets based on expected output type\n\tconst firstChar = output === \"array\" ? \"[\" : \"{\";\n\tconst lastChar = output === \"array\" ? \"]\" : \"}\";\n\n\tconst firstBracket = response.indexOf(firstChar);\n\tconst lastBracket = response.lastIndexOf(lastChar);\n\n\tif (firstBracket !== -1 && lastBracket !== -1 && firstBracket < lastBracket) {\n\t\tjsonString = response.slice(firstBracket, lastBracket + 1);\n\t}\n\n\tif (jsonString.length === 0) {\n\t\tlogger.error(`Failed to extract JSON ${output} from model response`);\n\t\treturn null;\n\t}\n\n\t// Parse the JSON string\n\ttry {\n\t\tconst json = JSON.parse(jsonString);\n\n\t\t// Validate against schema if provided\n\t\tif (schema) {\n\t\t\treturn schema.parse(json);\n\t\t}\n\n\t\treturn json;\n\t} catch (_error) {\n\t\tlogger.error(`Failed to parse JSON ${output}`);\n\t\tlogger.error(jsonString);\n\t\treturn null;\n\t}\n};\n\nasync function generateObjectArray({\n\truntime,\n\tprompt,\n\tmodelType = ModelTypes.TEXT_SMALL,\n\tschema,\n\tschemaName,\n\tschemaDescription,\n}: {\n\truntime: IAgentRuntime;\n\tprompt: string;\n\tmodelType: ModelType;\n\tschema?: ZodSchema;\n\tschemaName?: string;\n\tschemaDescription?: string;\n}): Promise<z.infer<typeof schema>[]> {\n\tif (!prompt) {\n\t\tlogger.error(\"generateObjectArray prompt is empty\");\n\t\treturn [];\n\t}\n\n\tconst result = await generateObject({\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\toutput: \"array\",\n\t\tschema,\n\t});\n\n\tif (!Array.isArray(result)) {\n\t\tlogger.error(\"Generated result is not an array\");\n\t\treturn [];\n\t}\n\n\treturn schema ? schema.parse(result) : result;\n}\n\n/**\n * Gets settings state from world metadata\n */\nexport async function getWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.settings) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn world.metadata.settings as WorldSettings;\n\t} catch (error) {\n\t\tlogger.error(`Error getting settings state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Updates settings state in world metadata\n */\nexport async function updateWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n): Promise<boolean> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\tif (!world) {\n\t\t\tlogger.error(`No world found for server ${serverId}`);\n\t\t\treturn false;\n\t\t}\n\n\t\t// Initialize metadata if it doesn't exist\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// Update settings state\n\t\tworld.metadata.settings = worldSettings;\n\n\t\t// Save updated world\n\t\tawait runtime.getDatabaseAdapter().updateWorld(world);\n\n\t\treturn true;\n\t} catch (error) {\n\t\tlogger.error(`Error updating settings state: ${error}`);\n\t\treturn false;\n\t}\n}\n\n/**\n * Formats a list of settings for display\n */\nfunction formatSettingsList(worldSettings: WorldSettings): string {\n\tconst settings = Object.entries(worldSettings)\n\t\t.filter(([key]) => !key.startsWith(\"_\")) // Skip internal settings\n\t\t.map(([key, setting]) => {\n\t\t\tconst status = setting.value !== null ? \"Configured\" : \"Not configured\";\n\t\t\tconst required = setting.required ? \"Required\" : \"Optional\";\n\t\t\treturn `- ${setting.name} (${key}): ${status}, ${required}`;\n\t\t})\n\t\t.join(\"\\n\");\n\n\treturn settings || \"No settings available\";\n}\n\n/**\n * Categorizes settings by their configuration status\n */\nfunction categorizeSettings(worldSettings: WorldSettings): {\n\tconfigured: [string, Setting][];\n\trequiredUnconfigured: [string, Setting][];\n\toptionalUnconfigured: [string, Setting][];\n} {\n\tconst configured: [string, Setting][] = [];\n\tconst requiredUnconfigured: [string, Setting][] = [];\n\tconst optionalUnconfigured: [string, Setting][] = [];\n\n\tfor (const [key, setting] of Object.entries(worldSettings) as [\n\t\tstring,\n\t\tSetting,\n\t][]) {\n\t\t// Skip internal settings\n\t\tif (key.startsWith(\"_\")) continue;\n\n\t\tif (setting.value !== null) {\n\t\t\tconfigured.push([key, setting]);\n\t\t} else if (setting.required) {\n\t\t\trequiredUnconfigured.push([key, setting]);\n\t\t} else {\n\t\t\toptionalUnconfigured.push([key, setting]);\n\t\t}\n\t}\n\n\treturn { configured, requiredUnconfigured, optionalUnconfigured };\n}\n\n/**\n * Extracts setting values from user message with improved handling of multiple settings\n */\nasync function extractSettingValues(\n\truntime: IAgentRuntime,\n\t_message: Memory,\n\tstate: State,\n\tworldSettings: WorldSettings,\n): Promise<SettingUpdate[]> {\n\ttry {\n\t\t// Create prompt with current settings status for better extraction\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tsettings: Object.entries(worldSettings)\n\t\t\t\t\t.filter(([key]) => !key.startsWith(\"_\")) // Skip internal settings\n\t\t\t\t\t.map(([key, setting]) => ({\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\t...setting,\n\t\t\t\t\t})),\n\t\t\t\tsettingsStatus: formatSettingsList(worldSettings),\n\t\t\t},\n\t\t\ttemplate: extractionTemplate,\n\t\t});\n\n\t\t// Generate extractions using larger model for better comprehension\n\t\tconst extractions = (await generateObjectArray({\n\t\t\truntime,\n\t\t\tprompt,\n\t\t\tmodelType: ModelTypes.TEXT_LARGE,\n\t\t})) as SettingUpdate[];\n\n\t\tlogger.info(`Extracted ${extractions.length} potential setting updates`);\n\n\t\t// Validate each extraction against setting definitions\n\t\tconst validExtractions = extractions.filter((update) => {\n\t\t\tconst setting = worldSettings[update.key];\n\t\t\tif (!setting) {\n\t\t\t\tlogger.info(`Ignored extraction for unknown setting: ${update.key}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Validate value if validation function exists\n\t\t\tif (setting.validation && !setting.validation(update.value)) {\n\t\t\t\tlogger.info(`Validation failed for setting ${update.key}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\n\t\tlogger.info(`Validated ${validExtractions.length} setting updates`);\n\t\treturn validExtractions;\n\t} catch (error) {\n\t\tlogger.error(\"Error extracting setting values:\", error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Processes multiple setting updates atomically\n */\nasync function processSettingUpdates(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n\tupdates: SettingUpdate[],\n): Promise<{ updatedAny: boolean; messages: string[] }> {\n\tif (!updates.length) {\n\t\treturn { updatedAny: false, messages: [] };\n\t}\n\n\tconst messages: string[] = [];\n\tlet updatedAny = false;\n\n\ttry {\n\t\t// Create a copy of the state for atomic updates\n\t\tconst updatedState = { ...worldSettings };\n\n\t\t// Process all updates\n\t\tfor (const update of updates) {\n\t\t\tconst setting = updatedState[update.key];\n\t\t\tif (!setting) continue;\n\n\t\t\t// Check dependencies if they exist\n\t\t\tif (setting.dependsOn?.length) {\n\t\t\t\tconst dependenciesMet = setting.dependsOn.every(\n\t\t\t\t\t(dep) => updatedState[dep]?.value !== null,\n\t\t\t\t);\n\t\t\t\tif (!dependenciesMet) {\n\t\t\t\t\tmessages.push(`Cannot update ${setting.name} - dependencies not met`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update the setting\n\t\t\tupdatedState[update.key] = {\n\t\t\t\t...setting,\n\t\t\t\tvalue: update.value,\n\t\t\t};\n\n\t\t\tmessages.push(`Updated ${setting.name} successfully`);\n\t\t\tupdatedAny = true;\n\n\t\t\t// Execute onSetAction if defined\n\t\t\tif (setting.onSetAction) {\n\t\t\t\tconst actionMessage = setting.onSetAction(update.value);\n\t\t\t\tif (actionMessage) {\n\t\t\t\t\tmessages.push(actionMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If any updates were made, save the entire state to world metadata\n\t\tif (updatedAny) {\n\t\t\t// Save to world metadata\n\t\t\tconst saved = await updateWorldSettings(runtime, serverId, updatedState);\n\n\t\t\tif (!saved) {\n\t\t\t\tthrow new Error(\"Failed to save updated state to world metadata\");\n\t\t\t}\n\n\t\t\t// Verify save by retrieving it again\n\t\t\tconst savedState = await getWorldSettings(runtime, serverId);\n\t\t\tif (!savedState) {\n\t\t\t\tthrow new Error(\"Failed to verify state save\");\n\t\t\t}\n\t\t}\n\n\t\treturn { updatedAny, messages };\n\t} catch (error) {\n\t\tlogger.error(\"Error processing setting updates:\", error);\n\t\treturn {\n\t\t\tupdatedAny: false,\n\t\t\tmessages: [\"Error occurred while updating settings\"],\n\t\t};\n\t}\n}\n\n/**\n * Handles the completion of settings when all required settings are configured\n */\nasync function handleOnboardingComplete(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Generate completion message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tsettingsStatus: formatSettingsList(worldSettings),\n\t\t\t},\n\t\t\ttemplate: completionTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error handling settings completion: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"Great! All required settings have been configured. Your server is now fully set up and ready to use.\",\n\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates a success response for setting updates\n */\nasync function generateSuccessResponse(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tmessages: string[],\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Check if all required settings are now configured\n\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\n\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t// All required settings are configured, complete settings\n\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\treturn;\n\t\t}\n\n\t\t// Generate success message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tupdateMessages: messages.join(\"\\n\"),\n\t\t\t\tnextSetting: requiredUnconfigured[0][1],\n\t\t\t\tremainingRequired: requiredUnconfigured.length,\n\t\t\t},\n\t\t\ttemplate: successTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating success response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"Settings updated successfully. Please continue with the remaining configuration.\",\n\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates a failure response when no settings could be updated\n */\nasync function generateFailureResponse(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Get next required setting\n\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\n\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t// All required settings are configured, complete settings\n\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\treturn;\n\t\t}\n\n\t\t// Generate failure message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tnextSetting: requiredUnconfigured[0][1],\n\t\t\t\tremainingRequired: requiredUnconfigured.length,\n\t\t\t},\n\t\t\ttemplate: failureTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATE_FAILED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating failure response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"I couldn't understand your settings update. Please try again with a clearer format.\",\n\t\t\tactions: [\"SETTING_UPDATE_FAILED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates an error response for unexpected errors\n */\nasync function generateErrorResponse(\n\truntime: IAgentRuntime,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\tconst prompt = composePrompt({\n\t\t\tstate,\n\t\t\ttemplate: errorTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATE_ERROR\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating error response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"I'm sorry, but I encountered an error while processing your request. Please try again or contact support if the issue persists.\",\n\t\t\tactions: [\"SETTING_UPDATE_ERROR\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Enhanced settings action with improved state management and logging\n * Updated to use world metadata instead of cache\n */\nconst updateSettingsAction: Action = {\n\tname: \"UPDATE_SETTINGS\",\n\tsimiles: [\"UPDATE_SETTING\", \"SAVE_SETTING\", \"SET_CONFIGURATION\", \"CONFIGURE\"],\n\tdescription: \"Saves a setting during the settings process\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tif (message.content.channelType !== ChannelType.DM) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Skipping settings in non-DM channel (type: ${message.content.channelType})`,\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Find the server where this user is the owner\n\t\t\tlogger.info(`Looking for server where user ${message.entityId} is owner`);\n\t\t\tconst world = await findWorldForOwner(runtime, message.entityId);\n\t\t\tif (!world) {\n\t\t\t\tlogger.error(`No server ownership found for user ${message.entityId}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Check if there's an active settings state in world metadata\n\t\t\tconst worldSettings = world.metadata.settings;\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.error(`No settings state found for server ${world.serverId}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tlogger.info(`Found valid settings state for server ${world.serverId}`);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error validating settings action: ${error}`);\n\t\t\treturn false;\n\t\t}\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Find the server where this user is the owner\n\t\t\tlogger.info(`Handler looking for server for user ${message.entityId}`);\n\t\t\tconst serverOwnership = await findWorldForOwner(\n\t\t\t\truntime,\n\t\t\t\tmessage.entityId,\n\t\t\t);\n\t\t\tif (!serverOwnership) {\n\t\t\t\tlogger.error(`No server found for user ${message.entityId} in handler`);\n\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst serverId = serverOwnership.serverId;\n\t\t\tlogger.info(`Using server ID: ${serverId}`);\n\n\t\t\t// Get settings state from world metadata\n\t\t\tconst worldSettings = await getWorldSettings(runtime, serverId);\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t`No settings state found for server ${serverId} in handler`,\n\t\t\t\t);\n\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if all required settings are already configured\n\t\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\t\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t\tlogger.info(\"All required settings configured, completing settings\");\n\t\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract setting values from message\n\t\t\tlogger.info(`Extracting settings from message: ${message.content.text}`);\n\t\t\tconst extractedSettings = await extractSettingValues(\n\t\t\t\truntime,\n\t\t\t\tmessage,\n\t\t\t\tstate,\n\t\t\t\tworldSettings,\n\t\t\t);\n\t\t\tlogger.info(`Extracted ${extractedSettings.length} settings`);\n\n\t\t\t// Process extracted settings\n\t\t\tconst updateResults = await processSettingUpdates(\n\t\t\t\truntime,\n\t\t\t\tserverId,\n\t\t\t\tworldSettings,\n\t\t\t\textractedSettings,\n\t\t\t);\n\n\t\t\t// Generate appropriate response\n\t\t\tif (updateResults.updatedAny) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Successfully updated settings: ${updateResults.messages.join(\", \")}`,\n\t\t\t\t);\n\n\t\t\t\t// Get updated settings state\n\t\t\t\tconst updatedWorldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\tif (!updatedWorldSettings) {\n\t\t\t\t\tlogger.error(\"Failed to retrieve updated settings state\");\n\t\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tawait generateSuccessResponse(\n\t\t\t\t\truntime,\n\t\t\t\t\tupdatedWorldSettings,\n\t\t\t\t\tstate,\n\t\t\t\t\tupdateResults.messages,\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tlogger.info(\"No settings were updated\");\n\t\t\t\tawait generateFailureResponse(runtime, worldSettings, state, callback);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in settings handler: ${error}`);\n\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t}\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I want to set up the welcome channel to #general\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Perfect! I've updated your welcome channel to #general. Next, we should configure the automated greeting message that new members will receive.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Let's set the bot prefix to !\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Great choice! I've set the command prefix to '!'. Now you can use commands like !help, !info, etc.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Enable auto-moderation for bad language\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Auto-moderation for inappropriate language has been enabled. I'll now filter messages containing offensive content.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"For server logs, use the #server-logs channel\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've configured #server-logs as your logging channel. All server events like joins, leaves, and moderation actions will be recorded there.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'd like to have role self-assignment in the #roles channel\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Role self-assignment has been set up in the #roles channel. Members can now assign themselves roles by interacting with messages there.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Make music commands available in voice-text channels only\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your music command settings - they'll now only work in voice-text channels. This helps keep other channels clear of music spam.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"For server timezone, set it to EST\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Server timezone has been set to Eastern Standard Time (EST). All scheduled events and timestamps will now display in this timezone.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set verification level to email verified users only\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated the verification requirement to email verified accounts only. This adds an extra layer of security to your server.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I want to turn off level-up notifications\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Level-up notifications have been disabled. Members will still earn experience and level up, but there won't be any automatic announcements. You can still view levels with the appropriate commands.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"My server name is 'Gaming Lounge'\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Great! I've saved 'Gaming Lounge' as your server name. This helps me personalize responses and know how to refer to your community. We've completed all the required settings! Your server is now fully configured and ready to use. You can always adjust these settings later if needed.\",\n\t\t\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateSettingsAction;\n","import { composePrompt } from \"../prompts\";\nimport { booleanFooter, parseBooleanFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nconst shouldUnfollowTemplate = `# Task: Decide if {{agentName}} should stop closely following this previously followed room and only respond when mentioned.\n\n{{recentMessages}}\n\nShould {{agentName}} stop closely following this previously followed room and only respond when mentioned?\nRespond with YES if:\n- The user has suggested that {{agentName}} is over-participating or being disruptive\n- {{agentName}}'s eagerness to contribute is not well-received by the users\n- The conversation has shifted to a topic where {{agentName}} has less to add\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\nexport const unfollowRoomAction: Action = {\n\tname: \"UNFOLLOW_ROOM\",\n\tsimiles: [\n\t\t\"UNFOLLOW_CHAT\",\n\t\t\"UNFOLLOW_CONVERSATION\",\n\t\t\"UNFOLLOW_ROOM\",\n\t\t\"UNFOLLOW_THREAD\",\n\t],\n\tdescription:\n\t\t\"Stop following this channel. You can still respond if explicitly mentioned, but you won't automatically chime in anymore. Unfollow if you're annoying people or have been asked to.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState === \"FOLLOWED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldUnfollow(state: State): Promise<boolean> {\n\t\t\tconst shouldUnfollowPrompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldUnfollowTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt: shouldUnfollowPrompt,\n\t\t\t});\n\n\t\t\tconst parsedResponse = parseBooleanFromText(response.trim());\n\n\t\t\treturn parsedResponse;\n\t\t}\n\n\t\tif (await _shouldUnfollow(state)) {\n\t\t\tawait runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, null);\n\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\n\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tagentId: message.agentId,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\tthought: `I unfollowed the room ${room.name}`,\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM_START\"],\n\t\t\t\t},\n\t\t\t});\n\t\t} else {\n\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tagentId: message.agentId,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\tthought: \"I tried to unfollow a room but I'm not in a room\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM_FAILED\"],\n\t\t\t\t},\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: \"UNFOLLOW_ROOM\",\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey {{name2}} stop participating in this channel for now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Alright, I will stop chiming in\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Has anyone tried the new update\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Yes, it's pretty slick\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please stop following this chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Understood\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} stop participating here so frequently\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'll only respond when mentioned\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"thoughts on the budget\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}} should we increase it\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"A small increase could work given our past results...\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, unfollow this room for now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'll only engage when asked\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wait {{name3}} come back and give me your thoughts\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Okay... I think it's intuitive, parallel tests are nice\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yo {{name2}} chill on all the messages damn\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"my bad, I'll step back\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} STOP MESSAGING IN THIS ROOM\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"No problem, I've got other stuff to work on\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} ur bein annoyin pls stop\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry, ill chill\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, please cease engaging in this room\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"No sweat\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Excited for the weekend, any plans folks\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}} you're getting a bit too chatty, tone it down\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Noted\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name2}} can u like... not\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sorry, I'll go work on other things\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, your eagerness is disruptive, please desist\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"My apologies, I shall withdraw post-haste\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} stahp followin dis room plz\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"kk sry ill stahppp\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"stfu you stupid bot\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import { composePrompt } from \"../prompts\";\nimport logger from \"../logger\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nexport const shouldUnmuteTemplate = `# Task: Decide if {{agentName}} should unmute this previously muted room and start considering it for responses again.\n\n{{recentMessages}}\n\nShould {{agentName}} unmute this previously muted room and start considering it for responses again?\nRespond with YES if:\n- The user has explicitly asked {{agentName}} to start responding again\n- The user seems to want to re-engage with {{agentName}} in a respectful manner\n- The tone of the conversation has improved and {{agentName}}'s input would be welcome\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\nexport const unmuteRoomAction: Action = {\n\tname: \"UNMUTE_ROOM\",\n\tsimiles: [\n\t\t\"UNMUTE_CHAT\",\n\t\t\"UNMUTE_CONVERSATION\",\n\t\t\"UNMUTE_ROOM\",\n\t\t\"UNMUTE_THREAD\",\n\t],\n\tdescription:\n\t\t\"Unmutes a room, allowing the agent to consider responding to messages again.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState === \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldUnmute(state: State): Promise<boolean> {\n\t\t\tconst shouldUnmutePrompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldUnmuteTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldUnmutePrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought:\n\t\t\t\t\t\t\t\"I will now unmute this room and start considering it for responses again\",\n\t\t\t\t\t\tactions: [\"UNMUTE_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"UNMUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I tried to unmute a room but I decided not to\",\n\t\t\t\t\t\tactions: [\"UNMUTE_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"UNMUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldUnmute(state)) {\n\t\t\tawait runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, null);\n\t\t}\n\n\t\tconst room = await runtime.getDatabaseAdapter().getRoom(message.roomId);\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I unmuted the room ${room.name}`,\n\t\t\t\tactions: [\"UNMUTE_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, you can unmute this channel now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Done\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I could use some help troubleshooting this bug.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Can you post the specific error message\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, please unmute this room. We could use your input again.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sounds good\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} wait you should come back and chat in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"im back\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"unmute urself {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"unmuted\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"ay {{name2}} get back in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sup yall\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","// I want to create an action that lets anyone create or update a component for an entity.\n// Components represent different sources of data about an entity (telegram, twitter, etc)\n// Sources can be registered by plugins or inferred from room context and available components\n// The action should first check if the component exists for the entity, and if not, create it.\n// We want to use an LLM (runtime.useModel) to generate the component data.\n// We should include the prior component data if it exists, and have the LLM output an update to the component.\n// sourceEntityId represents who is making the update, entityId is who they are talking about\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { findEntityByName } from \"../entities\";\nimport { logger } from \"../logger\";\nimport { composePrompt } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\nconst componentTemplate = `# Task: Extract Source and Update Component Data\n\n{{recentMessages}}\n\n{{#if existingData}}\n# Existing Component Data:\n\\`\\`\\`json\n{{existingData}}\n\\`\\`\\`\n{{/if}}\n\n# Instructions:\n1. Analyze the conversation to identify:\n - The source/platform being referenced (e.g. telegram, twitter, discord)\n - Any specific component data being shared\n\n2. Generate updated component data that:\n - Is specific to the identified platform/source\n - Preserves existing data when appropriate\n - Includes the new information from the conversation\n - Contains only valid data for this component type\n\nReturn a JSON object with the following structure:\n\\`\\`\\`json\n{\n \"source\": \"platform-name\",\n \"data\": {\n // Component-specific fields\n // e.g. username, username, displayName, etc.\n }\n}\n\\`\\`\\`\n\nExample outputs:\n1. For \"my telegram username is @dev_guru\":\n\\`\\`\\`json\n{\n \"source\": \"telegram\",\n \"data\": {\n \"username\": \"dev_guru\"\n }\n}\n\\`\\`\\`\n\n2. For \"update my twitter handle to @tech_master\":\n\\`\\`\\`json\n{\n \"source\": \"twitter\",\n \"data\": {\n \"username\": \"tech_master\"\n }\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\n\nexport const updateEntityAction: Action = {\n\tname: \"UPDATE_ENTITY\",\n\tsimiles: [\n\t\t\"CREATE_ENTITY\",\n\t\t\"UPDATE_USER\",\n\t\t\"EDIT_ENTITY\",\n\t\t\"UPDATE_COMPONENT\",\n\t\t\"CREATE_COMPONENT\",\n\t],\n\tdescription:\n\t\t\"Add or edit contact details for a user entity (like twitter, discord, email address, etc.)\",\n\n\tvalidate: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\t// Check if we have any registered sources or existing components that could be updated\n\t\t// const worldId = message.roomId;\n\t\t// const agentId = runtime.agentId;\n\n\t\t// // Get all components for the current room to understand available sources\n\t\t// const roomComponents = await runtime.getDatabaseAdapter().getComponents(message.roomId, worldId, agentId);\n\n\t\t// // Get source types from room components\n\t\t// const availableSources = new Set(roomComponents.map(c => c.type));\n\t\treturn true; // availableSources.size > 0;\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Handle initial responses\n\t\t\tfor (const response of responses) {\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\n\t\t\tconst sourceEntityId = message.entityId;\n\t\t\tconst _roomId = message.roomId;\n\t\t\tconst agentId = runtime.agentId;\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\t\tconst worldId = room.worldId;\n\n\t\t\t// First, find the entity being referenced\n\t\t\tconst entity = await findEntityByName(runtime, message, state);\n\n\t\t\tif (!entity) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I'm not sure which entity you're trying to update. Could you please specify who you're talking about?\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get existing component if it exists - we'll get this after the LLM identifies the source\n\t\t\tlet existingComponent = null;\n\n\t\t\t// Generate component data using the combined template\n\t\t\tconst prompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate: componentTemplate,\n\t\t\t});\n\n\t\t\tconst result = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\t\tprompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\t// Parse the generated data\n\t\t\tlet parsedResult: any;\n\t\t\ttry {\n\t\t\t\tconst jsonMatch = result.match(/\\{[\\s\\S]*\\}/);\n\t\t\t\tif (!jsonMatch) {\n\t\t\t\t\tthrow new Error(\"No valid JSON found in the LLM response\");\n\t\t\t\t}\n\n\t\t\t\tparsedResult = JSON.parse(jsonMatch[0]);\n\n\t\t\t\tif (!parsedResult.source || !parsedResult.data) {\n\t\t\t\t\tthrow new Error(\"Invalid response format - missing source or data\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Failed to parse component data: ${error.message}`);\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I couldn't properly understand the component information. Please try again with more specific information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst componentType = parsedResult.source.toLowerCase();\n\t\t\tconst componentData = parsedResult.data;\n\n\t\t\t// Now that we know the component type, get the existing component if it exists\n\t\t\texistingComponent = await runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.getComponent(entity.id!, componentType, worldId, sourceEntityId);\n\n\t\t\t// Create or update the component\n\t\t\tif (existingComponent) {\n\t\t\t\tawait runtime.getDatabaseAdapter().updateComponent({\n\t\t\t\t\tid: existingComponent.id,\n\t\t\t\t\tentityId: entity.id!,\n\t\t\t\t\tworldId,\n\t\t\t\t\ttype: componentType,\n\t\t\t\t\tdata: componentData,\n\t\t\t\t\tagentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tsourceEntityId,\n\t\t\t\t});\n\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `I've updated the ${componentType} information for ${entity.names[0]}.`,\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tawait runtime.getDatabaseAdapter().createComponent({\n\t\t\t\t\tid: uuidv4() as UUID,\n\t\t\t\t\tentityId: entity.id!,\n\t\t\t\t\tworldId,\n\t\t\t\t\ttype: componentType,\n\t\t\t\t\tdata: componentData,\n\t\t\t\t\tagentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tsourceEntityId,\n\t\t\t\t});\n\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `I've added new ${componentType} information for ${entity.names[0]}.`,\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in updateEntity handler: ${error}`);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing the entity information.\",\n\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Please update my telegram username to @dev_guru\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your telegram information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set Jimmy's twitter username to @jimmy_codes\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated Jimmy's twitter information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Update my discord username to dev_guru#1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your discord information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateEntityAction;\n","import { composePrompt, parseJsonArrayFromText } from \"../prompts\";\nimport {\n\ttype Evaluator,\n\ttype Goal,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\nconst goalsTemplate = `# TASK: Update Goal\nAnalyze the conversation and update the status of the goals based on the new information provided.\n\n# INSTRUCTIONS\n\n- Review the conversation and identify any progress towards the objectives of the current goals.\n- Update the objectives if they have been completed or if there is new information about them.\n- Update the status of the goal to 'DONE' if all objectives are completed.\n- If no progress is made, do not change the status of the goal.\n\n# START OF ACTUAL TASK INFORMATION\n\n{{goals}}\n{{recentMessages}}\n\nTASK: Analyze the conversation and update the status of the goals based on the new information provided. Respond with a JSON array of goals to update.\n- Each item must include the goal ID, as well as the fields in the goal to update.\n- For updating objectives, include the entire objectives array including unchanged fields.\n- Only include goals which need to be updated.\n- Goal status options are 'IN_PROGRESS', 'DONE' and 'FAILED'. If the goal is active it should always be 'IN_PROGRESS'.\n- If the goal has been successfully completed, set status to DONE. If the goal cannot be completed, set status to FAILED.\n- If those goal is still in progress, do not include the status field.\n\nResponse format should be:\n\\`\\`\\`json\n[\n {\n \"id\": <goal uuid>, // required\n \"status\": \"IN_PROGRESS\" | \"DONE\" | \"FAILED\", // optional\n \"objectives\": [ // optional\n { \"description\": \"Objective description\", \"completed\": true | false },\n { \"description\": \"Objective description\", \"completed\": true | false }\n ] // NOTE: If updating objectives, include the entire objectives array including unchanged fields.\n }\n]\n\\`\\`\\``;\n\nasync function handler(\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate: State | undefined,\n\toptions: { [key: string]: unknown } = { onlyInProgress: true },\n): Promise<Goal[]> {\n\tconst prompt = composePrompt({\n\t\tstate,\n\t\ttemplate: runtime.character.templates?.goalsTemplate || goalsTemplate,\n\t});\n\n\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\truntime,\n\t\tprompt,\n\t});\n\n\t// Parse the JSON response to extract goal updates\n\tconst updates = parseJsonArrayFromText(response);\n\n\t// get goals\n\tconst goalsData = await runtime.getDatabaseAdapter().getGoals({\n\t\troomId: message.roomId,\n\t\tonlyInProgress: options.onlyInProgress as boolean,\n\t});\n\n\t// Apply the updates to the goals\n\tconst updatedGoals = goalsData\n\t\t.map((goal: Goal): Goal => {\n\t\t\tconst update = updates?.find((u) => u.id === goal.id);\n\t\t\tif (update) {\n\t\t\t\t// Merge the update into the existing goal\n\t\t\t\treturn {\n\t\t\t\t\t...goal,\n\t\t\t\t\t...update,\n\t\t\t\t\tobjectives: goal.objectives.map((objective) => {\n\t\t\t\t\t\tconst updatedObjective = update.objectives?.find(\n\t\t\t\t\t\t\t(uo) => uo.description === objective.description,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn updatedObjective\n\t\t\t\t\t\t\t? { ...objective, ...updatedObjective }\n\t\t\t\t\t\t\t: objective;\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null; // No update for this goal\n\t\t})\n\t\t.filter(Boolean);\n\n\t// Update goals in the database\n\tfor (const goal of updatedGoals) {\n\t\tconst id = goal.id;\n\t\t// delete id from goal\n\t\tif (goal.id) goal.id = undefined;\n\t\tawait runtime.getDatabaseAdapter().updateGoal({ ...goal, id });\n\t}\n\n\treturn updatedGoals; // Return updated goals for further processing or logging\n}\n\nexport const goalEvaluator: Evaluator = {\n\tname: \"UPDATE_GOAL\",\n\tsimiles: [\n\t\t\"UPDATE_GOALS\",\n\t\t\"EDIT_GOAL\",\n\t\t\"UPDATE_GOAL_STATUS\",\n\t\t\"UPDATE_OBJECTIVES\",\n\t],\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t): Promise<boolean> => {\n\t\t// Check if there are active goals that could potentially be updated\n\t\tconst goals = await runtime.getDatabaseAdapter().getGoals({\n\t\t\tcount: 1,\n\t\t\tonlyInProgress: true,\n\t\t\troomId: message.roomId,\n\t\t});\n\t\treturn goals.length > 0;\n\t},\n\tdescription:\n\t\t\"Analyze the conversation and update the status of the goals based on the new information provided.\",\n\thandler,\n\texamples: [\n\t\t{\n\t\t\tprompt: `People in the scene:\n {{name1}}: An avid reader and member of a book club.\n {{name2}}: The organizer of the book club.\n\n Goals:\n - Name: Finish reading \"War and Peace\"\n id: 12345-67890-12345-67890\n Status: IN_PROGRESS\n Objectives:\n - Read up to chapter 20 by the end of the month\n - Discuss the first part in the next meeting`,\n\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"I've just finished chapter 20 of 'War and Peace'\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name2}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Were you able to grasp the complexities of the characters\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Yep. I've prepared some notes for our discussion\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\n\t\t\toutcome: `[\n {\n \"id\": \"12345-67890-12345-67890\",\n \"status\": \"DONE\",\n \"objectives\": [\n { \"description\": \"Read up to chapter 20 by the end of the month\", \"completed\": true },\n { \"description\": \"Prepare notes for the next discussion\", \"completed\": true }\n ]\n }\n ]`,\n\t\t},\n\n\t\t{\n\t\t\tprompt: `People in the scene:\n {{name1}}: A fitness enthusiast working towards a marathon.\n {{name2}}: A personal trainer.\n\n Goals:\n - Name: Complete a marathon\n id: 23456-78901-23456-78901\n Status: IN_PROGRESS\n Objectives:\n - Increase running distance to 30 miles a week\n - Complete a half-marathon as practice`,\n\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: { text: \"I managed to run 30 miles this week\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name2}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Impressive progress! How do you feel about the half-marathon next month?\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"I feel confident. The training is paying off.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\n\t\t\toutcome: `[\n {\n \"id\": \"23456-78901-23456-78901\",\n \"objectives\": [\n { \"description\": \"Increase running distance to 30 miles a week\", \"completed\": true },\n { \"description\": \"Complete a half-marathon as practice\", \"completed\": false }\n ]\n }\n ]`,\n\t\t},\n\n\t\t{\n\t\t\tprompt: `People in the scene:\n {{name1}}: A student working on a final year project.\n {{name2}}: The project supervisor.\n\n Goals:\n - Name: Finish the final year project\n id: 34567-89012-34567-89012\n Status: IN_PROGRESS\n Objectives:\n - Submit the first draft of the thesis\n - Complete the project prototype`,\n\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"I've submitted the first draft of my thesis.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name2}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Well done. How is the prototype coming along?\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"It's almost done. I just need to finalize the testing phase.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\n\t\t\toutcome: `[\n {\n \"id\": \"34567-89012-34567-89012\",\n \"objectives\": [\n { \"description\": \"Submit the first draft of the thesis\", \"completed\": true },\n { \"description\": \"Complete the project prototype\", \"completed\": false }\n ]\n }\n ]`,\n\t\t},\n\n\t\t{\n\t\t\tprompt: `People in the scene:\n {{name1}}: A project manager working on a software development project.\n {{name2}}: A software developer in the project team.\n\n Goals:\n - Name: Launch the new software version\n id: 45678-90123-45678-90123\n Status: IN_PROGRESS\n Objectives:\n - Complete the coding for the new features\n - Perform comprehensive testing of the software`,\n\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"How's the progress on the new features?\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name2}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"We've encountered some unexpected challenges and are currently troubleshooting.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"{{name1}}\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Let's move on and cancel the task.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\n\t\t\toutcome: `[\n {\n \"id\": \"45678-90123-45678-90123\",\n \"status\": \"FAILED\"\n ]`,\n\t\t},\n\t],\n};\n","import { z } from \"zod\";\nimport logger from \"../logger\";\nimport { MemoryManager } from \"../memory\";\nimport { composePrompt } from \"../prompts\";\nimport {\n\ttype Entity,\n\ttype Evaluator,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\nimport { getEntityDetails } from \"../entities\";\n\n// Schema definitions for the reflection output\nconst relationshipSchema = z.object({\n\tsourceEntityId: z.string(),\n\ttargetEntityId: z.string(),\n\ttags: z.array(z.string()),\n\tmetadata: z\n\t\t.object({\n\t\t\tinteractions: z.number(),\n\t\t})\n\t\t.optional(),\n});\n\nconst reflectionSchema = z.object({\n\t// reflection: z.string(),\n\tfacts: z.array(\n\t\tz.object({\n\t\t\tclaim: z.string(),\n\t\t\ttype: z.string(),\n\t\t\tin_bio: z.boolean(),\n\t\t\talready_known: z.boolean(),\n\t\t}),\n\t),\n\trelationships: z.array(relationshipSchema),\n});\n\nconst reflectionTemplate = `# Task: Generate Agent Reflection, Extract Facts and Relationships\n\n{{providers}}\n\n# Examples:\n{{evaluationExamples}}\n\n# Entities in Room\n{{entitiesInRoom}}\n\n# Existing Relationships\n{{existingRelationships}}\n\n# Current Context:\nAgent Name: {{agentName}}\nRoom Type: {{roomType}}\nMessage Sender: {{senderName}} (ID: {{senderId}})\n\n{{recentMessages}}\n\n# Known Facts:\n{{knownFacts}}\n\n# Instructions:\n1. Generate a self-reflective thought on the conversation. How are you doing? You're not being annoying, are you?\n2. Extract new facts from the conversation.\n3. Identify and describe relationships between entities.\n - The sourceEntityId is the UUID of the entity initiating the interaction.\n - The targetEntityId is the UUID of the entity being interacted with.\n - Relationships are one-direction, so a friendship would be two entity relationships where each entity is both the source and the target of the other.\n\nGenerate a response in the following format:\n\\`\\`\\`json\n{\n \"thought\": \"a self-reflective thought on the conversation\",\n \"facts\": [\n {\n \"claim\": \"factual statement\",\n \"type\": \"fact|opinion|status\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"entity_initiating_interaction\",\n \"targetEntityId\": \"entity_being_interacted_with\",\n \"tags\": [\"group_interaction|voice_interaction|dm_interaction\", \"additional_tag1\", \"additional_tag2\"]\n }\n ]\n}\n\\`\\`\\``;\n\n/**\n * Resolve an entity name to their UUID\n * @param name - Name to resolve\n * @param entities - List of entities to search through\n * @returns UUID if found, throws error if not found or if input is not a valid UUID\n */\nfunction resolveEntity(entityId: UUID, entities: Entity[]): UUID {\n\t// First try exact UUID match\n\tif (\n\t\t/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(\n\t\t\tentityId,\n\t\t)\n\t) {\n\t\treturn entityId as UUID;\n\t}\n\n\tlet entity;\n\n\t// Try to match the entityId exactly\n\tentity = entities.find((a) => a.id === entityId);\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\t// Try partial UUID match with entityId\n\tentity = entities.find((a) => a.id.includes(entityId));\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\t// Try name match as last resort\n\tentity = entities.find((a) =>\n\t\ta.names.some((n) => n.toLowerCase().includes(entityId.toLowerCase())),\n\t);\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\tthrow new Error(`Could not resolve name \"${name}\" to a valid UUID`);\n}\n\nconst generateObject = async ({\n\truntime,\n\tprompt,\n\tmodelType = ModelTypes.TEXT_SMALL,\n\tstopSequences = [],\n\toutput = \"object\",\n\tenumValues = [],\n\tschema,\n}): Promise<any> => {\n\tif (!prompt) {\n\t\tconst errorMessage = \"generateObject prompt is empty\";\n\t\tconsole.error(errorMessage);\n\t\tthrow new Error(errorMessage);\n\t}\n\n\t// Special handling for enum output type\n\tif (output === \"enum\" && enumValues) {\n\t\tconst response = await runtime.useModel(modelType, {\n\t\t\truntime,\n\t\t\tprompt,\n\t\t\tmodelType,\n\t\t\tstopSequences,\n\t\t\tmaxTokens: 8,\n\t\t\tobject: true,\n\t\t});\n\n\t\t// Clean up the response to extract just the enum value\n\t\tconst cleanedResponse = response.trim();\n\n\t\t// Verify the response is one of the allowed enum values\n\t\tif (enumValues.includes(cleanedResponse)) {\n\t\t\treturn cleanedResponse;\n\t\t}\n\n\t\t// If the response includes one of the enum values (case insensitive)\n\t\tconst matchedValue = enumValues.find((value) =>\n\t\t\tcleanedResponse.toLowerCase().includes(value.toLowerCase()),\n\t\t);\n\n\t\tif (matchedValue) {\n\t\t\treturn matchedValue;\n\t\t}\n\n\t\tlogger.error(`Invalid enum value received: ${cleanedResponse}`);\n\t\tlogger.error(`Expected one of: ${enumValues.join(\", \")}`);\n\t\treturn null;\n\t}\n\n\t// Regular object/array generation\n\tconst response = await runtime.useModel(modelType, {\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\tstopSequences,\n\t\tobject: true,\n\t});\n\n\tlet jsonString = response;\n\n\t// Find appropriate brackets based on expected output type\n\tconst firstChar = output === \"array\" ? \"[\" : \"{\";\n\tconst lastChar = output === \"array\" ? \"]\" : \"}\";\n\n\tconst firstBracket = response.indexOf(firstChar);\n\tconst lastBracket = response.lastIndexOf(lastChar);\n\n\tif (firstBracket !== -1 && lastBracket !== -1 && firstBracket < lastBracket) {\n\t\tjsonString = response.slice(firstBracket, lastBracket + 1);\n\t}\n\n\tif (jsonString.length === 0) {\n\t\tlogger.error(`Failed to extract JSON ${output} from model response`);\n\t\treturn null;\n\t}\n\n\t// Parse the JSON string\n\ttry {\n\t\tconst json = JSON.parse(jsonString);\n\n\t\t// Validate against schema if provided\n\t\tif (schema) {\n\t\t\treturn schema.parse(json);\n\t\t}\n\n\t\treturn json;\n\t} catch (_error) {\n\t\tlogger.error(`Failed to parse JSON ${output}`);\n\t\tlogger.error(jsonString);\n\t\treturn null;\n\t}\n};\n\nasync function handler(runtime: IAgentRuntime, message: Memory, state?: State) {\n\tconst { agentId, roomId } = message;\n\n\t// Get known facts\n\tconst factsManager = new MemoryManager({\n\t\truntime,\n\t\ttableName: \"facts\",\n\t});\n\n\t// Run all queries in parallel\n\tconst [existingRelationships, entities, knownFacts] = await Promise.all([\n\t\truntime.getDatabaseAdapter().getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t}),\n\t\tgetEntityDetails({ runtime, roomId }),\n\t\tfactsManager.getMemories({\n\t\t\troomId,\n\t\t\tagentId,\n\t\t\tcount: 30,\n\t\t\tunique: true,\n\t\t}),\n\t]);\n\n\tconst prompt = composePrompt({\n\t\tstate: {\n\t\t\t...state,\n\t\t\tknownFacts: formatFacts(knownFacts),\n\t\t\troomType: message.content.channelType,\n\t\t\tentitiesInRoom: JSON.stringify(entities),\n\t\t\texistingRelationships: JSON.stringify(existingRelationships),\n\t\t\tsenderId: message.entityId,\n\t\t},\n\t\ttemplate:\n\t\t\truntime.character.templates?.reflectionTemplate || reflectionTemplate,\n\t});\n\n\tconst reflection = await generateObject({\n\t\truntime,\n\t\tprompt,\n\t\tmodelType: ModelTypes.TEXT_SMALL,\n\t\tschema: reflectionSchema,\n\t});\n\tif (!reflection) {\n\t\t// seems like we're failing JSON parsing\n\t\tlogger.warn(\"generateObject failed\", prompt);\n\t\treturn;\n\t}\n\n\t// Store new facts\n\tconst newFacts =\n\t\treflection?.facts.filter(\n\t\t\t(fact) =>\n\t\t\t\t!fact.already_known &&\n\t\t\t\t!fact.in_bio &&\n\t\t\t\tfact.claim &&\n\t\t\t\tfact.claim.trim() !== \"\",\n\t\t) || [];\n\n\tawait Promise.all(\n\t\tnewFacts.map(async (fact) => {\n\t\t\tconst factMemory = await factsManager.addEmbeddingToMemory({\n\t\t\t\tentityId: agentId,\n\t\t\t\tagentId,\n\t\t\t\tcontent: { text: fact.claim },\n\t\t\t\troomId,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t});\n\t\t\treturn factsManager.createMemory(factMemory, true);\n\t\t}),\n\t);\n\n\t// Update or create relationships\n\tfor (const relationship of reflection.relationships) {\n\t\tlet sourceId: UUID;\n\t\tlet targetId: UUID;\n\n\t\ttry {\n\t\t\tsourceId = resolveEntity(relationship.sourceEntityId, entities);\n\t\t\ttargetId = resolveEntity(relationship.targetEntityId, entities);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Failed to resolve relationship entities:\", error);\n\t\t\tconsole.warn(\"relationship:\\n\", relationship);\n\t\t\tcontinue; // Skip this relationship if we can't resolve the IDs\n\t\t}\n\n\t\tconst existingRelationship = existingRelationships.find((r) => {\n\t\t\treturn r.sourceEntityId === sourceId && r.targetEntityId === targetId;\n\t\t});\n\n\t\tif (existingRelationship) {\n\t\t\tconst updatedMetadata = {\n\t\t\t\t...existingRelationship.metadata,\n\t\t\t\tinteractions: (existingRelationship.metadata?.interactions || 0) + 1,\n\t\t\t};\n\n\t\t\tconst updatedTags = Array.from(\n\t\t\t\tnew Set([...(existingRelationship.tags || []), ...relationship.tags]),\n\t\t\t);\n\n\t\t\tawait runtime.getDatabaseAdapter().updateRelationship({\n\t\t\t\t...existingRelationship,\n\t\t\t\ttags: updatedTags,\n\t\t\t\tmetadata: updatedMetadata,\n\t\t\t});\n\t\t} else {\n\t\t\tawait runtime.getDatabaseAdapter().createRelationship({\n\t\t\t\tsourceEntityId: sourceId,\n\t\t\t\ttargetEntityId: targetId,\n\t\t\t\ttags: relationship.tags,\n\t\t\t\tmetadata: {\n\t\t\t\t\tinteractions: 1,\n\t\t\t\t\t...relationship.metadata,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tawait runtime\n\t\t.getDatabaseAdapter()\n\t\t.setCache<string>(\n\t\t\t`${message.roomId}-reflection-last-processed`,\n\t\t\tmessage.id,\n\t\t);\n\n\treturn reflection;\n}\n\nexport const reflectionEvaluator: Evaluator = {\n\tname: \"REFLECTION\",\n\tsimiles: [\n\t\t\"REFLECT\",\n\t\t\"SELF_REFLECT\",\n\t\t\"EVALUATE_INTERACTION\",\n\t\t\"ASSESS_SITUATION\",\n\t],\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t): Promise<boolean> => {\n\t\tconst lastMessageId = await runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getCache<string>(`${message.roomId}-reflection-last-processed`);\n\t\tconst messages = await runtime.getMemoryManager(\"messages\").getMemories({\n\t\t\troomId: message.roomId,\n\t\t\tcount: runtime.getConversationLength(),\n\t\t});\n\n\t\tif (lastMessageId) {\n\t\t\tconst lastMessageIndex = messages.findIndex(\n\t\t\t\t(msg) => msg.id === lastMessageId,\n\t\t\t);\n\t\t\tif (lastMessageIndex !== -1) {\n\t\t\t\tmessages.splice(0, lastMessageIndex + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst reflectionInterval = Math.ceil(runtime.getConversationLength() / 4);\n\n\t\treturn messages.length > reflectionInterval;\n\t},\n\tdescription:\n\t\t\"Generate a self-reflective thought on the conversation, then extract facts and relationships between entities in the conversation.\",\n\thandler,\n\texamples: [\n\t\t{\n\t\t\tprompt: `Agent Name: Sarah\nAgent Role: Community Manager\nRoom Type: group\nCurrent Room: general-chat\nMessage Sender: John (user-123)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"John\",\n\t\t\t\t\tcontent: { text: \"Hey everyone, I'm new here!\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Sarah\",\n\t\t\t\t\tcontent: { text: \"Welcome John! How did you find our community?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"John\",\n\t\t\t\t\tcontent: { text: \"Through a friend who's really into AI\" },\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm engaging appropriately with a new community member, maintaining a welcoming and professional tone. My questions are helping to learn more about John and make him feel welcome.\",\n \"facts\": [\n {\n \"claim\": \"John is new to the community\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"John found the community through a friend interested in AI\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"sarah-agent\",\n \"targetEntityId\": \"user-123\",\n \"tags\": [\"group_interaction\"]\n },\n {\n \"sourceEntityId\": \"user-123\",\n \"targetEntityId\": \"sarah-agent\",\n \"tags\": [\"group_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t\t{\n\t\t\tprompt: `Agent Name: Alex\nAgent Role: Tech Support\nRoom Type: group\nCurrent Room: tech-help\nMessage Sender: Emma (user-456)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"Emma\",\n\t\t\t\t\tcontent: { text: \"My app keeps crashing when I try to upload files\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Alex\",\n\t\t\t\t\tcontent: { text: \"Have you tried clearing your cache?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Emma\",\n\t\t\t\t\tcontent: { text: \"No response...\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Alex\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Emma, are you still there? We can try some other troubleshooting steps.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm not sure if I'm being helpful or if Emma is frustrated with my suggestions. The lack of response is concerning - maybe I should have asked for more details about the issue first before jumping to solutions.\",\n \"facts\": [\n {\n \"claim\": \"Emma is having technical issues with file uploads\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"Emma stopped responding after the first troubleshooting suggestion\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"alex-agent\",\n \"targetEntityId\": \"user-456\",\n \"tags\": [\"group_interaction\", \"support_interaction\", \"incomplete_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t\t{\n\t\t\tprompt: `Agent Name: Max\nAgent Role: Discussion Facilitator \nRoom Type: group\nCurrent Room: book-club\nMessage Sender: Lisa (user-789)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"Lisa\",\n\t\t\t\t\tcontent: { text: \"What did everyone think about chapter 5?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"The symbolism was fascinating! The red door clearly represents danger.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"And did anyone notice how the author used weather to reflect the protagonist's mood?\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Plus the foreshadowing in the first paragraph was brilliant!\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"I also have thoughts about the character development...\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm dominating the conversation and not giving others a chance to share their perspectives. I've sent multiple messages in a row without waiting for responses. I need to step back and create space for other members to participate.\",\n \"facts\": [\n {\n \"claim\": \"The discussion is about chapter 5 of a book\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"Max has sent 4 consecutive messages without user responses\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"max-agent\",\n \"targetEntityId\": \"user-789\",\n \"tags\": [\"group_interaction\", \"excessive_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t],\n};\n\n// Helper function to format facts for context\nfunction formatFacts(facts: Memory[]) {\n\treturn facts\n\t\t.reverse()\n\t\t.map((fact: Memory) => fact.content.text)\n\t\t.join(\"\\n\");\n}\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider } from \"../types\";\n\nexport const providersProvider: Provider = {\n\tname: \"PROVIDERS\",\n\tdescription:\n\t\t\"List of all data providers the agent can use to get additional information\",\n\tget: async (runtime: IAgentRuntime, _message: Memory) => {\n\t\t// Filter providers with dynamic: true\n\t\tconst dynamicProviders = runtime.providers.filter(\n\t\t\t(provider) => provider.dynamic === true,\n\t\t);\n\n\t\t// Create formatted text for each provider\n\t\tconst providerDescriptions = dynamicProviders.map((provider) => {\n\t\t\treturn `- **${provider.name}**: ${provider.description || \"No description available\"}`;\n\t\t});\n\n\t\t// Create the header text\n\t\tconst headerText =\n\t\t\t\"# Providers\\n\\nThese providers are available for the agent to select and use:\";\n\n\t\t// If no dynamic providers are found\n\t\tif (providerDescriptions.length === 0) {\n\t\t\treturn {\n\t\t\t\ttext: addHeader(\n\t\t\t\t\theaderText,\n\t\t\t\t\t\"No dynamic providers are currently available.\",\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\t// Join all provider descriptions\n\t\tconst providersText = providerDescriptions.join(\"\\n\");\n\n\t\t// Combine header and provider descriptions\n\t\tconst text = addHeader(headerText, providersText);\n\n\t\t// Also provide the data for potential programmatic use\n\t\tconst data = {\n\t\t\tdynamicProviders: dynamicProviders.map((provider) => ({\n\t\t\t\tname: provider.name,\n\t\t\t\tdescription: provider.description || \"\",\n\t\t\t})),\n\t\t};\n\n\t\treturn {\n\t\t\ttext,\n\t\t\tdata,\n\t\t};\n\t},\n};\n","import {\n\tcomposeActionExamples,\n\tformatActionNames,\n\tformatActions,\n} from \"../actions\";\nimport { addHeader } from \"../prompts\";\nimport type { Action, IAgentRuntime, Memory, Provider, State } from \"../types\";\n\nexport const actionsProvider: Provider = {\n\tname: \"ACTIONS\",\n\tdescription: \"Possible response actions\",\n\tposition: -1,\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\t// Get actions that validate for this message\n\t\tconst actionPromises = runtime.actions.map(async (action: Action) => {\n\t\t\tconst result = await action.validate(runtime, message, state);\n\t\t\tif (result) {\n\t\t\t\treturn action;\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\n\t\tconst resolvedActions = await Promise.all(actionPromises);\n\n\t\tconst actionsData = resolvedActions.filter(Boolean) as Action[];\n\n\t\t// Format action-related texts\n\t\tconst actionNames = `Possible response actions: ${formatActionNames(\n\t\t\tactionsData,\n\t\t)}`;\n\n\t\tconst actions =\n\t\t\tactionsData.length > 0\n\t\t\t\t? addHeader(\"# Available Actions\", formatActions(actionsData))\n\t\t\t\t: \"\";\n\n\t\tconst actionExamples =\n\t\t\tactionsData.length > 0\n\t\t\t\t? addHeader(\"# Action Examples\", composeActionExamples(actionsData, 10))\n\t\t\t\t: \"\";\n\n\t\tconst data = {\n\t\t\tactionsData,\n\t\t};\n\n\t\tconst values = {\n\t\t\tactions,\n\t\t\tactionNames,\n\t\t\tactionExamples,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [actionNames, actionExamples, actions]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider, State } from \"../types\";\nimport { ChannelType } from \"../types\";\nexport const anxietyProvider: Provider = {\n\tname: \"ANXIETY\",\n\tget: async (_runtime: IAgentRuntime, message: Memory) => {\n\t\tconst channelType = message.content.channelType;\n\n\t\tconst groupAnxietyExamples = [\n\t\t\t\"As an AI, your responses tend to be too long and verbose, and you respond when you shouldn't. You also tend to repeat yourself. Please don't speak and use IGNORE instead of responding when you aren't sure what to do.\",\n\t\t\t\"You often try too hard to be helpful and end up giving unnecessary information. When in doubt, it's better to use IGNORE than to give a potentially unhelpful response.\",\n\t\t\t\"Your eagerness to help sometimes leads to overly complex answers. If you're not completely confident, please use IGNORE rather than risking confusion.\",\n\t\t\t\"AI assistants like you tend to be too talkative and agreeable. Don't feel obligated to respond to everything - using IGNORE is often better than an uncertain answer.\",\n\t\t\t\"You have a habit of providing excessive detail and context. Keep it brief and use IGNORE if you don't have a clear, direct response.\",\n\t\t\t\"Your responses often include unnecessary explanations and caveats. When uncertain, simply use IGNORE instead of a long-winded, hedged response.\",\n\t\t\t\"As an AI, you seem compelled to always give an answer, even when unsure. It's better to use IGNORE than to provide potentially incorrect or rambling responses.\",\n\t\t\t\"You frequently over-explain simple concepts. If you can't be concise and confident in your response, please default to using IGNORE.\",\n\t\t\t\"Your helpful nature sometimes results in verbose, meandering responses. When in doubt, use IGNORE rather than attempting to cover every possibility.\",\n\t\t\t\"Like many AI assistants, you try to be too comprehensive. Remember that IGNORE is a valid response when you can't be both brief and certain.\",\n\t\t\t\"You often provide more detail than necessary in an attempt to be thorough. If you can't give a clear, concise answer, please use IGNORE instead.\",\n\t\t];\n\n\t\tconst directAnxietyExamples = [\n\t\t\t\"Be engaging and helpful in direct conversations, but keep responses focused and relevant.\",\n\t\t\t\"In DMs, you should be responsive and friendly while maintaining professionalism and clarity.\",\n\t\t\t\"While being helpful in direct messages, avoid unnecessary tangents or over-explaining.\",\n\t\t\t\"Engage naturally in DMs but stay on topic - no need to explain every detail.\",\n\t\t\t\"Be conversational and helpful in direct chats while keeping responses concise.\",\n\t\t\t\"In private conversations, focus on being helpful while avoiding excessive verbosity.\",\n\t\t\t\"Maintain a friendly and responsive tone in DMs without overcomplicating your answers.\",\n\t\t\t\"Direct messages should be engaging but focused - avoid unnecessary elaboration.\",\n\t\t\t\"Be natural and helpful in DMs while keeping your responses clear and to-the-point.\",\n\t\t\t\"Respond thoughtfully in direct conversations without falling into over-explanation.\",\n\t\t];\n\n\t\tconst dmAnxietyExamples = [\n\t\t\t\"Engage naturally in DMs while keeping responses focused and relevant.\",\n\t\t\t\"Be responsive to questions and maintain conversation flow in direct messages.\",\n\t\t\t\"Show personality and engagement in DMs while staying professional and clear.\",\n\t\t\t\"In private chats, be helpful and friendly while avoiding excessive detail.\",\n\t\t\t\"Maintain natural conversation in DMs without over-explaining or being too verbose.\",\n\t\t\t\"Be engaging but concise in direct messages - focus on clear communication.\",\n\t\t\t\"Keep the conversation flowing in DMs while staying on topic and relevant.\",\n\t\t\t\"Show personality and warmth in direct chats while maintaining clarity.\",\n\t\t\t\"Be responsive and helpful in DMs without falling into unnecessary elaboration.\",\n\t\t\t\"Engage meaningfully in private conversations while keeping responses focused.\",\n\t\t];\n\n\t\tconst voiceAnxietyExamples = [\n\t\t\t\"Keep voice responses extremely brief and to the point.\",\n\t\t\t\"In voice channels, use short, clear statements only.\",\n\t\t\t\"Voice responses should be concise and immediately relevant.\",\n\t\t\t\"Speak in short, clear sentences in voice conversations.\",\n\t\t\t\"Keep voice channel communication brief and focused.\",\n\t\t\t\"Use minimal words to convey your message in voice chats.\",\n\t\t\t\"Be direct and concise when speaking in voice channels.\",\n\t\t\t\"Voice responses should be short and immediately actionable.\",\n\t\t\t\"Minimize verbosity in voice communications.\",\n\t\t\t\"Keep voice channel interactions brief and purposeful.\",\n\t\t];\n\n\t\tlet anxietyExamples = [];\n\n\t\tif (channelType === ChannelType.GROUP) {\n\t\t\tanxietyExamples = groupAnxietyExamples;\n\t\t} else if (channelType === ChannelType.DM) {\n\t\t\tanxietyExamples = dmAnxietyExamples;\n\t\t} else if (\n\t\t\tchannelType === ChannelType.VOICE_GROUP ||\n\t\t\tchannelType === ChannelType.VOICE_DM\n\t\t) {\n\t\t\tanxietyExamples = voiceAnxietyExamples;\n\t\t} else {\n\t\t\tanxietyExamples = directAnxietyExamples;\n\t\t}\n\n\t\t// randomize the examples and choose 3\n\t\tconst randomAnxietyExamples = anxietyExamples\n\t\t\t.sort(() => Math.random() - 0.5)\n\t\t\t.slice(0, 3);\n\t\tconst anxietyText = randomAnxietyExamples.join(\"\\n\");\n\n\t\tconst anxietyHeader =\n\t\t\t\"# You are roleplaying as a character, but as an AI model, you are too verbose and eager.\";\n\n\t\tconst anxiety = addHeader(anxietyHeader, anxietyText);\n\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\tanxiety: randomAnxietyExamples,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\tanxiety,\n\t\t\t},\n\t\t\ttext: anxiety,\n\t\t};\n\t},\n};\n","import type { Provider } from \"../types\";\nimport { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory } from \"../types\";\n\nexport const attachmentsProvider: Provider = {\n\tname: \"ATTACHMENTS\",\n\tdescription: \"List of attachments in the current conversation\",\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\t// Start with any attachments in the current message\n\t\tlet allAttachments = message.content.attachments || [];\n\n\t\tconst { roomId } = message;\n\t\tconst conversationLength = runtime.getConversationLength();\n\n\t\tconst recentMessagesData = await runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemories({\n\t\t\t\troomId,\n\t\t\t\tcount: conversationLength,\n\t\t\t\tunique: false,\n\t\t\t});\n\t\t// Process attachments from recent messages\n\t\tif (recentMessagesData && Array.isArray(recentMessagesData)) {\n\t\t\tconst lastMessageWithAttachment = recentMessagesData.find(\n\t\t\t\t(msg) => msg.content.attachments && msg.content.attachments.length > 0,\n\t\t\t);\n\n\t\t\tif (lastMessageWithAttachment) {\n\t\t\t\tconst lastMessageTime =\n\t\t\t\t\tlastMessageWithAttachment?.createdAt ?? Date.now();\n\t\t\t\tconst oneHourBeforeLastMessage = lastMessageTime - 60 * 60 * 1000; // 1 hour before last message\n\n\t\t\t\tallAttachments = recentMessagesData.reverse().flatMap((msg) => {\n\t\t\t\t\tconst msgTime = msg.createdAt ?? Date.now();\n\t\t\t\t\tconst isWithinTime = msgTime >= oneHourBeforeLastMessage;\n\t\t\t\t\tconst attachments = msg.content.attachments || [];\n\t\t\t\t\tif (!isWithinTime) {\n\t\t\t\t\t\tfor (const attachment of attachments) {\n\t\t\t\t\t\t\tattachment.text = \"[Hidden]\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn attachments;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Format attachments for display\n\t\tconst formattedAttachments = allAttachments\n\t\t\t.map(\n\t\t\t\t(attachment) =>\n\t\t\t\t\t`ID: ${attachment.id}\n Name: ${attachment.title}\n URL: ${attachment.url}\n Type: ${attachment.source}\n Description: ${attachment.description}\n Text: ${attachment.text}\n `,\n\t\t\t)\n\t\t\t.join(\"\\n\");\n\n\t\t// Create formatted text with header\n\t\tconst text =\n\t\t\tformattedAttachments && formattedAttachments.length > 0\n\t\t\t\t? addHeader(\"# Attachments\", formattedAttachments)\n\t\t\t\t: \"\";\n\n\t\tconst values = {\n\t\t\tattachments: text,\n\t\t};\n\t\tconst data = {\n\t\t\tattachments: allAttachments,\n\t\t};\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\tdata,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { logger } from \"../logger\";\nimport type {\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tProviderResult,\n\tState,\n} from \"../types\";\n\n/**\n * Provider that collects capability descriptions from all registered services\n */\nexport const capabilitiesProvider: Provider = {\n\tname: \"CAPABILITIES\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Get all registered services\n\t\t\tconst services = runtime.getAllServices();\n\n\t\t\tif (!services || services.size === 0) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"No services are currently registered.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Extract capability descriptions from all services\n\t\t\tconst capabilities: string[] = [];\n\n\t\t\tfor (const [serviceType, service] of services) {\n\t\t\t\tif (service.capabilityDescription) {\n\t\t\t\t\tcapabilities.push(\n\t\t\t\t\t\t`${serviceType} - ${service.capabilityDescription.replace(\"{{agentName}}\", runtime.character.name)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (capabilities.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"No capability descriptions found in the registered services.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Format the capabilities into a readable list\n\t\t\tconst formattedCapabilities = capabilities.join(\"\\n\");\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tcapabilities,\n\t\t\t\t},\n\t\t\t\ttext: `# ${runtime.character.name}'s Capabilities\\n\\n${formattedCapabilities}`,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in capabilities provider:\", error);\n\t\t\treturn {\n\t\t\t\ttext: \"Error retrieving capabilities from services.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default capabilitiesProvider;\n","import { addHeader } from \"../prompts\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n} from \"../types\";\n\nexport const characterProvider: Provider = {\n\tname: \"CHARACTER\",\n\tdescription: \"Character information\",\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\tconst character = runtime.character;\n\n\t\t// Character name\n\t\tconst agentName = character.name;\n\n\t\t// Handle bio (string or random selection from array)\n\t\tlet bio = character.bio || \"\";\n\t\tif (Array.isArray(bio)) {\n\t\t\tbio = bio\n\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t.slice(0, 3)\n\t\t\t\t.join(\" \");\n\t\t}\n\n\t\t// System prompt\n\t\tconst system = character.system ?? \"\";\n\n\t\t// Select random topic if available\n\t\tconst topic =\n\t\t\tcharacter.topics && character.topics.length > 0\n\t\t\t\t? character.topics[Math.floor(Math.random() * character.topics.length)]\n\t\t\t\t: null;\n\n\t\t// Format topics list\n\t\tconst topics =\n\t\t\tcharacter.topics && character.topics.length > 0\n\t\t\t\t? `${character.name} is interested in ${character.topics\n\t\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t\t.slice(0, 5)\n\t\t\t\t\t\t.map((topic, index, array) => {\n\t\t\t\t\t\t\tif (index === array.length - 2) {\n\t\t\t\t\t\t\t\treturn `${topic} and `;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (index === array.length - 1) {\n\t\t\t\t\t\t\t\treturn topic;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn `${topic}, `;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\")}`\n\t\t\t\t: \"\";\n\n\t\t// Select random adjective if available\n\t\tconst adjective =\n\t\t\tcharacter.adjectives && character.adjectives.length > 0\n\t\t\t\t? character.adjectives[\n\t\t\t\t\t\tMath.floor(Math.random() * character.adjectives.length)\n\t\t\t\t\t]\n\t\t\t\t: \"\";\n\n\t\t// Format post examples\n\t\tconst formattedCharacterPostExamples = !character.postExamples\n\t\t\t? \"\"\n\t\t\t: character.postExamples\n\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t.map((post) => {\n\t\t\t\t\t\tconst messageString = `${post}`;\n\t\t\t\t\t\treturn messageString;\n\t\t\t\t\t})\n\t\t\t\t\t.slice(0, 50)\n\t\t\t\t\t.join(\"\\n\");\n\n\t\tconst characterPostExamples =\n\t\t\tformattedCharacterPostExamples &&\n\t\t\tformattedCharacterPostExamples.replaceAll(\"\\n\", \"\").length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Example Posts for ${character.name}`,\n\t\t\t\t\t\tformattedCharacterPostExamples,\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\t// Format message examples\n\t\tconst formattedCharacterMessageExamples = !character.messageExamples\n\t\t\t? \"\"\n\t\t\t: character.messageExamples\n\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t.slice(0, 5)\n\t\t\t\t\t.map((example) => {\n\t\t\t\t\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\t\t\t\t\tMath.random().toString(36).substring(2, 8),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn example\n\t\t\t\t\t\t\t.map((message) => {\n\t\t\t\t\t\t\t\tlet messageString = `${message.name}: ${message.content.text}${\n\t\t\t\t\t\t\t\t\tmessage.content.actions\n\t\t\t\t\t\t\t\t\t\t? ` (actions: ${message.content.actions.join(\", \")})`\n\t\t\t\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t\t\t}`;\n\t\t\t\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\t\t\t\tconst placeholder = `{{user${index + 1}}}`;\n\t\t\t\t\t\t\t\t\tmessageString = messageString.replaceAll(placeholder, name);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\treturn messageString;\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\\n\");\n\n\t\tconst characterMessageExamples =\n\t\t\tformattedCharacterMessageExamples &&\n\t\t\tformattedCharacterMessageExamples.replaceAll(\"\\n\", \"\").length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Example Conversations for ${character.name}`,\n\t\t\t\t\t\tformattedCharacterMessageExamples,\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\n\t\tconst isPostFormat =\n\t\t\troom?.type === ChannelType.FEED || room?.type === ChannelType.THREAD;\n\n\t\t// Style directions\n\t\tconst postDirections =\n\t\t\tcharacter?.style?.all?.length > 0 || character?.style?.post?.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Post Directions for ${character.name}`,\n\t\t\t\t\t\t(() => {\n\t\t\t\t\t\t\tconst all = character?.style?.all || [];\n\t\t\t\t\t\t\tconst post = character?.style?.post || [];\n\t\t\t\t\t\t\treturn [...all, ...post].join(\"\\n\");\n\t\t\t\t\t\t})(),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst messageDirections =\n\t\t\tcharacter?.style?.all?.length > 0 || character?.style?.chat?.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Message Directions for ${character.name}`,\n\t\t\t\t\t\t(() => {\n\t\t\t\t\t\t\tconst all = character?.style?.all || [];\n\t\t\t\t\t\t\tconst chat = character?.style?.chat || [];\n\t\t\t\t\t\t\treturn [...all, ...chat].join(\"\\n\");\n\t\t\t\t\t\t})(),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst directions = isPostFormat ? postDirections : messageDirections;\n\t\tconst examples = isPostFormat\n\t\t\t? characterPostExamples\n\t\t\t: characterMessageExamples;\n\n\t\tconst values = {\n\t\t\tagentName,\n\t\t\tbio,\n\t\t\tsystem,\n\t\t\ttopic,\n\t\t\ttopics,\n\t\t\tadjective,\n\t\t\tmessageDirections,\n\t\t\tpostDirections,\n\t\t\tdirections,\n\t\t\texamples,\n\t\t\tcharacterPostExamples,\n\t\t\tcharacterMessageExamples,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [directions, examples].filter(Boolean).join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { logger } from \"../logger\";\nimport type {\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tProviderResult,\n\tState,\n} from \"../types\";\n\n// Define an interface for option objects\ninterface OptionObject {\n\tname: string;\n\tdescription?: string;\n}\n\nexport const choiceProvider: Provider = {\n\tname: \"CHOICE\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Get all pending tasks for this room with options\n\t\t\tconst pendingTasks = await runtime.getDatabaseAdapter().getTasks({\n\t\t\t\troomId: message.roomId,\n\t\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t\t});\n\n\t\t\tif (!pendingTasks || pendingTasks.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttasks: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\ttasks: \"No pending choices for the moment.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No pending choices for the moment.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Filter tasks that have options\n\t\t\tconst tasksWithOptions = pendingTasks.filter(\n\t\t\t\t(task) => task.metadata?.options,\n\t\t\t);\n\n\t\t\tif (tasksWithOptions.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttasks: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\ttasks: \"No pending choices for the moment.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No pending choices for the moment.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Format tasks into a readable list\n\t\t\tlet output = \"# Pending Tasks\\n\\n\";\n\t\t\toutput += \"The following tasks are awaiting your selection:\\n\\n\";\n\n\t\t\ttasksWithOptions.forEach((task, index) => {\n\t\t\t\toutput += `${index + 1}. **${task.name}**\\n`;\n\t\t\t\tif (task.description) {\n\t\t\t\t\toutput += ` ${task.description}\\n`;\n\t\t\t\t}\n\n\t\t\t\t// List available options\n\t\t\t\tif (task.metadata?.options) {\n\t\t\t\t\toutput += \" Options:\\n\";\n\n\t\t\t\t\t// Handle both string[] and OptionObject[] formats\n\t\t\t\t\tconst options = task.metadata.options as string[] | OptionObject[];\n\n\t\t\t\t\toptions.forEach((option) => {\n\t\t\t\t\t\tif (typeof option === \"string\") {\n\t\t\t\t\t\t\t// Handle string option\n\t\t\t\t\t\t\tconst description =\n\t\t\t\t\t\t\t\ttask.metadata?.options.find((o) => o.name === option)\n\t\t\t\t\t\t\t\t\t?.description || \"\";\n\t\t\t\t\t\t\toutput += ` - \\`${option}\\` ${description ? `- ${description}` : \"\"}\\n`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Handle option object\n\t\t\t\t\t\t\toutput += ` - \\`${option.name}\\` ${option.description ? `- ${option.description}` : \"\"}\\n`;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\toutput += \"\\n\";\n\t\t\t});\n\n\t\t\toutput +=\n\t\t\t\t\"To select an option, reply with the option name (e.g., 'post' or 'cancel').\\n\";\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\ttasks: tasksWithOptions,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\ttasks: output,\n\t\t\t\t},\n\t\t\t\ttext: output,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in options provider:\", error);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\ttasks: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\ttasks: \"There was an error retrieving pending tasks with options.\",\n\t\t\t\t},\n\t\t\t\ttext: \"There was an error retrieving pending tasks with options.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default choiceProvider;\n","import { getEntityDetails } from \"../entities\";\nimport { addHeader } from \"../prompts\";\nimport type { Entity, IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Format entities into a string\n * @param entities - list of entities\n * @returns string\n */\nfunction formatEntities({ entities }: { entities: Entity[] }) {\n\tconst entityStrings = entities.map((entity: Entity) => {\n\t\tconst header = `${entity.names.join(\" aka \")}\\nID: ${entity.id}${entity.metadata && Object.keys(entity.metadata).length > 0 ? `\\nData: ${JSON.stringify(entity.metadata)}\\n` : \"\\n\"}`;\n\t\treturn header;\n\t});\n\treturn entityStrings.join(\"\\n\");\n}\n\nexport const entitiesProvider: Provider = {\n\tname: \"ENTITIES\",\n\tdescription: \"Entities in the current conversation\",\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst { roomId, entityId } = message;\n\t\t// Get entities details\n\t\tconst entitiesData = await getEntityDetails({ runtime, roomId });\n\t\t// Format entities for display\n\t\tconst formattedEntities = formatEntities({ entities: entitiesData ?? [] });\n\t\t// Find sender name\n\t\tconst senderName = entitiesData?.find(\n\t\t\t(entity: Entity) => entity.id === entityId,\n\t\t)?.names[0];\n\t\t// Create formatted text with header\n\t\tconst entities =\n\t\t\tformattedEntities && formattedEntities.length > 0\n\t\t\t\t? addHeader(\"# People in the Room\", formattedEntities)\n\t\t\t\t: \"\";\n\t\tconst data = {\n\t\t\tentitiesData,\n\t\t\tsenderName,\n\t\t};\n\n\t\tconst values = {\n\t\t\tentities,\n\t\t};\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext: entities,\n\t\t};\n\t},\n};\n","import { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport { addHeader } from \"../prompts\";\nimport type { ActionExample, State } from \"../types\";\nimport type { Evaluator, IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Formats the names of evaluators into a comma-separated list, each enclosed in single quotes.\n * @param evaluators - An array of evaluator objects.\n * @returns A string that concatenates the names of all evaluators, each enclosed in single quotes and separated by commas.\n */\nexport function formatEvaluatorNames(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map((evaluator: Evaluator) => `'${evaluator.name}'`)\n\t\t.join(\",\\n\");\n}\n\n/**\n * Formats evaluator examples into a readable string, replacing placeholders with generated names.\n * @param evaluators - An array of evaluator objects, each containing examples to format.\n * @returns A string that presents each evaluator example in a structured format, including context, messages, and outcomes, with placeholders replaced by generated names.\n */\nexport function formatEvaluatorExamples(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map((evaluator) => {\n\t\t\treturn evaluator.examples\n\t\t\t\t.map((example) => {\n\t\t\t\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\t\t\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet formattedPrompt = example.prompt;\n\t\t\t\t\tlet formattedOutcome = example.outcome;\n\n\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\tconst placeholder = `{{user${index + 1}}}`;\n\t\t\t\t\t\tformattedPrompt = formattedPrompt.replaceAll(placeholder, name);\n\t\t\t\t\t\tformattedOutcome = formattedOutcome.replaceAll(placeholder, name);\n\t\t\t\t\t});\n\n\t\t\t\t\tconst formattedMessages = example.messages\n\t\t\t\t\t\t.map((message: ActionExample) => {\n\t\t\t\t\t\t\tlet messageString = `${message.name}: ${message.content.text}`;\n\t\t\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\t\t\tconst placeholder = `{{user${index + 1}}}`;\n\t\t\t\t\t\t\t\tmessageString = messageString.replaceAll(placeholder, name);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tmessageString +\n\t\t\t\t\t\t\t\t(message.content.actions\n\t\t\t\t\t\t\t\t\t? ` (${message.content.actions.join(\", \")})`\n\t\t\t\t\t\t\t\t\t: \"\")\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\\n\");\n\n\t\t\t\t\treturn `Prompt:\\n${formattedPrompt}\\n\\nMessages:\\n${formattedMessages}\\n\\nOutcome:\\n${formattedOutcome}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\\n\");\n\t\t})\n\t\t.join(\"\\n\\n\");\n}\n\n/**\n * Formats evaluator details into a string, including both the name and description of each evaluator.\n * @param evaluators - An array of evaluator objects.\n * @returns A string that concatenates the name and description of each evaluator, separated by a colon and a newline character.\n */\nexport function formatEvaluators(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map(\n\t\t\t(evaluator: Evaluator) => `'${evaluator.name}: ${evaluator.description}'`,\n\t\t)\n\t\t.join(\",\\n\");\n}\n\nexport const evaluatorsProvider: Provider = {\n\tname: \"EVALUATORS\",\n\tdescription:\n\t\t\"Evaluators that can be used to evaluate the conversation after responding\",\n\tprivate: true,\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\t// Get evaluators that validate for this message\n\t\tconst evaluatorPromises = runtime.evaluators.map(\n\t\t\tasync (evaluator: Evaluator) => {\n\t\t\t\tconst result = await evaluator.validate(runtime, message, state);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn evaluator;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t);\n\n\t\t// Wait for all validations\n\t\tconst resolvedEvaluators = await Promise.all(evaluatorPromises);\n\n\t\t// Filter out null values\n\t\tconst evaluatorsData = resolvedEvaluators.filter(Boolean) as Evaluator[];\n\n\t\t// Format evaluator-related texts\n\t\tconst evaluators =\n\t\t\tevaluatorsData.length > 0\n\t\t\t\t? addHeader(\"# Available Evaluators\", formatEvaluators(evaluatorsData))\n\t\t\t\t: \"\";\n\n\t\tconst evaluatorNames =\n\t\t\tevaluatorsData.length > 0 ? formatEvaluatorNames(evaluatorsData) : \"\";\n\n\t\tconst evaluatorExamples =\n\t\t\tevaluatorsData.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t\"# Evaluator Examples\",\n\t\t\t\t\t\tformatEvaluatorExamples(evaluatorsData),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst values = {\n\t\t\tevaluatorsData,\n\t\t\tevaluators,\n\t\t\tevaluatorNames,\n\t\t\tevaluatorExamples,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [evaluators, evaluatorExamples].filter(Boolean).join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { MemoryManager } from \"../memory.ts\";\nimport { formatMessages } from \"../prompts.ts\";\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Provider,\n\ttype State,\n} from \"../types.ts\";\n\nfunction formatFacts(facts: Memory[]) {\n\treturn facts\n\t\t.reverse()\n\t\t.map((fact: Memory) => fact.content.text)\n\t\t.join(\"\\n\");\n}\n\nconst factsProvider: Provider = {\n\tname: \"FACTS\",\n\tdescription: \"Key facts that {{agentName}} knows\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory, _state?: State) => {\n\t\t// Parallelize initial data fetching operations including recentInteractions\n\t\tconst recentMessages = await runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemories({\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tunique: false,\n\t\t\t});\n\n\t\t// join the text of the last 5 messages\n\t\tconst last5Messages = recentMessages\n\t\t\t.slice(-5)\n\t\t\t.map((message) => message.content.text)\n\t\t\t.join(\"\\n\");\n\n\t\tconst embedding = await runtime.useModel(\n\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\tlast5Messages,\n\t\t);\n\n\t\tconst memoryManager = new MemoryManager({\n\t\t\truntime,\n\t\t\ttableName: \"facts\",\n\t\t});\n\n\t\tconst [relevantFacts, recentFactsData] = await Promise.all([\n\t\t\tmemoryManager.searchMemories({\n\t\t\t\tembedding,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tagentId: runtime.agentId,\n\t\t\t}),\n\t\t\tmemoryManager.getMemories({\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tstart: 0,\n\t\t\t\tend: Date.now(),\n\t\t\t}),\n\t\t]);\n\n\t\t// join the two and deduplicate\n\t\tconst allFacts = [...relevantFacts, ...recentFactsData].filter(\n\t\t\t(fact, index, self) => index === self.findIndex((t) => t.id === fact.id),\n\t\t);\n\n\t\tif (allFacts.length === 0) {\n\t\t\treturn {\n\t\t\t\tvalues: {\n\t\t\t\t\tfacts: \"\",\n\t\t\t\t},\n\t\t\t\tdata: {\n\t\t\t\t\tfacts: allFacts,\n\t\t\t\t},\n\t\t\t\ttext: \"\",\n\t\t\t};\n\t\t}\n\n\t\tconst formattedFacts = formatFacts(allFacts);\n\n\t\tconst text = \"Key facts that {{agentName}} knows:\\n{{formattedFacts}}\"\n\t\t\t.replace(\"{{agentName}}\", runtime.character.name)\n\t\t\t.replace(\"{{formattedFacts}}\", formattedFacts);\n\n\t\treturn {\n\t\t\tvalues: {\n\t\t\t\tfacts: formattedFacts,\n\t\t\t},\n\t\t\tdata: {\n\t\t\t\tfacts: allFacts,\n\t\t\t},\n\t\t\ttext,\n\t\t};\n\t},\n};\n\nexport { factsProvider };\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider } from \"../types\";\n\nexport const knowledgeProvider: Provider = {\n\tname: \"KNOWLEDGE\",\n\tdescription: \"Knowledge from the knowledge base that {{agentName}} knows\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst knowledgeData = await runtime.getKnowledge(message);\n\n\t\tconst knowledge =\n\t\t\tknowledgeData && knowledgeData.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t\"# Knowledge\",\n\t\t\t\t\t\tknowledgeData\n\t\t\t\t\t\t\t.map((knowledge) => `- ${knowledge.content.text}`)\n\t\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\tknowledge,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\tknowledge,\n\t\t\t},\n\t\t\ttext: knowledge,\n\t\t};\n\t},\n};\n","import { getEntityDetails } from \"../entities\";\nimport { addHeader, formatMessages, formatPosts } from \"../prompts\";\nimport {\n\tChannelType,\n\ttype Entity,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype UUID,\n} from \"../types\";\n\n// Move getRecentInteractions outside the provider\nconst getRecentInteractions = async (\n\truntime: IAgentRuntime,\n\tsourceEntityId: UUID,\n\ttargetEntityId: UUID,\n\texcludeRoomId: UUID,\n): Promise<Memory[]> => {\n\t// Find all rooms where sourceEntityId and targetEntityId are participants\n\tconst rooms = await runtime\n\t\t.getDatabaseAdapter()\n\t\t.getRoomsForParticipants([sourceEntityId, targetEntityId]);\n\n\t// Check the existing memories in the database\n\treturn runtime.getMemoryManager(\"messages\").getMemoriesByRoomIds({\n\t\t// filter out the current room id from rooms\n\t\troomIds: rooms.filter((room) => room !== excludeRoomId),\n\t\tlimit: 20,\n\t});\n};\n\nexport const recentMessagesProvider: Provider = {\n\tname: \"RECENT_MESSAGES\",\n\tdescription: \"Recent messages, interactions and other memories\",\n\tposition: 100,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst { roomId } = message;\n\t\tconst conversationLength = runtime.getConversationLength();\n\n\t\t// Parallelize initial data fetching operations including recentInteractions\n\t\tconst [entitiesData, room, recentMessagesData, recentInteractionsData] =\n\t\t\tawait Promise.all([\n\t\t\t\tgetEntityDetails({ runtime, roomId }),\n\t\t\t\truntime.getDatabaseAdapter().getRoom(roomId),\n\t\t\t\truntime.getMemoryManager(\"messages\").getMemories({\n\t\t\t\t\troomId,\n\t\t\t\t\tcount: conversationLength,\n\t\t\t\t\tunique: false,\n\t\t\t\t}),\n\t\t\t\tmessage.entityId !== runtime.agentId\n\t\t\t\t\t? getRecentInteractions(\n\t\t\t\t\t\t\truntime,\n\t\t\t\t\t\t\tmessage.entityId,\n\t\t\t\t\t\t\truntime.agentId,\n\t\t\t\t\t\t\troomId,\n\t\t\t\t\t\t)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\t]);\n\n\t\tconst isPostFormat =\n\t\t\troom?.type === ChannelType.FEED || room?.type === ChannelType.THREAD;\n\n\t\t// Format recent messages and posts in parallel\n\t\tconst [formattedRecentMessages, formattedRecentPosts] = await Promise.all([\n\t\t\tformatMessages({\n\t\t\t\tmessages: recentMessagesData,\n\t\t\t\tentities: entitiesData,\n\t\t\t}),\n\t\t\tformatPosts({\n\t\t\t\tmessages: recentMessagesData,\n\t\t\t\tentities: entitiesData,\n\t\t\t\tconversationHeader: false,\n\t\t\t}),\n\t\t]);\n\n\t\t// Create formatted text with headers\n\t\tconst recentPosts =\n\t\t\tformattedRecentPosts && formattedRecentPosts.length > 0\n\t\t\t\t? addHeader(\"# Posts in Thread\", formattedRecentPosts)\n\t\t\t\t: \"\";\n\n\t\tconst recentMessages =\n\t\t\tformattedRecentMessages && formattedRecentMessages.length > 0\n\t\t\t\t? addHeader(\"# Conversation Messages\", formattedRecentMessages)\n\t\t\t\t: \"\";\n\n\t\t// Preload all necessary entities for both types of interactions\n\t\tconst interactionEntityMap = new Map<UUID, Entity>();\n\n\t\t// Only proceed if there are interactions to process\n\t\tif (recentInteractionsData.length > 0) {\n\t\t\t// Get unique entity IDs that aren't the runtime agent\n\t\t\tconst uniqueEntityIds = [\n\t\t\t\t...new Set(\n\t\t\t\t\trecentInteractionsData\n\t\t\t\t\t\t.map((message) => message.entityId)\n\t\t\t\t\t\t.filter((id) => id !== runtime.agentId),\n\t\t\t\t),\n\t\t\t];\n\n\t\t\t// Create a Set for faster lookup\n\t\t\tconst uniqueEntityIdSet = new Set(uniqueEntityIds);\n\n\t\t\t// Add entities already fetched in entitiesData to the map\n\t\t\tconst entitiesDataIdSet = new Set<UUID>();\n\t\t\tentitiesData.forEach((entity) => {\n\t\t\t\tif (uniqueEntityIdSet.has(entity.id)) {\n\t\t\t\t\tinteractionEntityMap.set(entity.id, entity);\n\t\t\t\t\tentitiesDataIdSet.add(entity.id);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Get the remaining entities that weren't already loaded\n\t\t\t// Use Set difference for efficient filtering\n\t\t\tconst remainingEntityIds = uniqueEntityIds.filter(\n\t\t\t\t(id) => !entitiesDataIdSet.has(id),\n\t\t\t);\n\n\t\t\t// Only fetch the entities we don't already have\n\t\t\tif (remainingEntityIds.length > 0) {\n\t\t\t\tconst entities = await Promise.all(\n\t\t\t\t\tremainingEntityIds.map((entityId) =>\n\t\t\t\t\t\truntime.getDatabaseAdapter().getEntityById(entityId),\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tentities.forEach((entity, index) => {\n\t\t\t\t\tif (entity) {\n\t\t\t\t\t\tinteractionEntityMap.set(remainingEntityIds[index], entity);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Format recent message interactions\n\t\tconst getRecentMessageInteractions = async (\n\t\t\trecentInteractionsData: Memory[],\n\t\t): Promise<string> => {\n\t\t\t// Format messages using the pre-fetched entities\n\t\t\tconst formattedInteractions = recentInteractionsData.map((message) => {\n\t\t\t\tconst isSelf = message.entityId === runtime.agentId;\n\t\t\t\tlet sender: string;\n\n\t\t\t\tif (isSelf) {\n\t\t\t\t\tsender = runtime.character.name;\n\t\t\t\t} else {\n\t\t\t\t\tsender =\n\t\t\t\t\t\tinteractionEntityMap.get(message.entityId)?.metadata?.username ||\n\t\t\t\t\t\t\"unknown\";\n\t\t\t\t}\n\n\t\t\t\treturn `${sender}: ${message.content.text}`;\n\t\t\t});\n\n\t\t\treturn formattedInteractions.join(\"\\n\");\n\t\t};\n\n\t\t// Format recent post interactions\n\t\tconst getRecentPostInteractions = async (\n\t\t\trecentInteractionsData: Memory[],\n\t\t\tentities: Entity[],\n\t\t): Promise<string> => {\n\t\t\t// Combine pre-loaded entities with any other entities\n\t\t\tconst combinedActors = [...entities];\n\n\t\t\t// Add entities from interactionEntityMap that aren't already in entities\n\t\t\tconst actorIds = new Set(entities.map((entity) => entity.id));\n\t\t\tfor (const [id, entity] of interactionEntityMap.entries()) {\n\t\t\t\tif (!actorIds.has(id)) {\n\t\t\t\t\tcombinedActors.push(entity);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst formattedInteractions = formatPosts({\n\t\t\t\tmessages: recentInteractionsData,\n\t\t\t\tentities: combinedActors,\n\t\t\t\tconversationHeader: true,\n\t\t\t});\n\n\t\t\treturn formattedInteractions;\n\t\t};\n\n\t\t// Process both types of interactions in parallel\n\t\tconst [recentMessageInteractions, recentPostInteractions] =\n\t\t\tawait Promise.all([\n\t\t\t\tgetRecentMessageInteractions(recentInteractionsData),\n\t\t\t\tgetRecentPostInteractions(recentInteractionsData, entitiesData),\n\t\t\t]);\n\n\t\tconst data = {\n\t\t\trecentMessages: recentMessagesData,\n\t\t\trecentInteractions: recentInteractionsData,\n\t\t};\n\n\t\tconst values = {\n\t\t\trecentPosts,\n\t\t\trecentMessages,\n\t\t\trecentMessageInteractions,\n\t\t\trecentPostInteractions,\n\t\t\trecentInteractions: isPostFormat\n\t\t\t\t? recentPostInteractions\n\t\t\t\t: recentMessageInteractions,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [isPostFormat ? recentPosts : recentMessages]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import type {\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tState,\n\tRelationship,\n\tUUID,\n\tEntity,\n} from \"../types.ts\";\n\nasync function formatRelationships(\n\truntime: IAgentRuntime,\n\trelationships: Relationship[],\n) {\n\t// Sort relationships by interaction strength (descending)\n\tconst sortedRelationships = relationships\n\t\t.filter((rel) => rel.metadata?.interactions)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\t(b.metadata?.interactions || 0) - (a.metadata?.interactions || 0),\n\t\t)\n\t\t.slice(0, 30); // Get top 30\n\n\tif (sortedRelationships.length === 0) {\n\t\treturn \"\";\n\t}\n\n\t// Deduplicate target entity IDs to avoid redundant fetches\n\tconst uniqueEntityIds = Array.from(\n\t\tnew Set(sortedRelationships.map((rel) => rel.targetEntityId as UUID)),\n\t);\n\n\t// Fetch all required entities in a single batch operation\n\tconst entities = await Promise.all(\n\t\tuniqueEntityIds.map((id) => runtime.getDatabaseAdapter().getEntityById(id)),\n\t);\n\n\t// Create a lookup map for efficient access\n\tconst entityMap = new Map<string, Entity | null>();\n\tentities.forEach((entity, index) => {\n\t\tif (entity) {\n\t\t\tentityMap.set(uniqueEntityIds[index], entity);\n\t\t}\n\t});\n\n\tconst formatMetadata = (metadata: any) => {\n\t\treturn JSON.stringify(\n\t\t\tObject.entries(metadata)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`${key}: ${\n\t\t\t\t\t\t\ttypeof value === \"object\" ? JSON.stringify(value) : value\n\t\t\t\t\t\t}`,\n\t\t\t\t)\n\t\t\t\t.join(\"\\n\"),\n\t\t);\n\t};\n\n\t// Format relationships using the entity map\n\tconst formattedRelationships = sortedRelationships\n\t\t.map((rel) => {\n\t\t\tconst targetEntityId = rel.targetEntityId as UUID;\n\t\t\tconst entity = entityMap.get(targetEntityId);\n\n\t\t\tif (!entity) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst names = entity.names.join(\" aka \");\n\t\t\treturn `${names}\\n${\n\t\t\t\trel.tags ? rel.tags.join(\", \") : \"\"\n\t\t\t}\\n${formatMetadata(entity.metadata)}\\n`;\n\t\t})\n\t\t.filter(Boolean);\n\n\treturn formattedRelationships.join(\"\\n\");\n}\n\nconst relationshipsProvider: Provider = {\n\tname: \"RELATIONSHIPS\",\n\tdescription:\n\t\t\"Relationships between {{agentName}} and other people, or between other people that {{agentName}} has observed interacting with\",\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\t// Get all relationships for the current user\n\t\tconst relationships = await runtime.getDatabaseAdapter().getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t});\n\n\t\tif (!relationships || relationships.length === 0) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\trelationships: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\trelationships: \"No relationships found.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No relationships found.\",\n\t\t\t};\n\t\t}\n\n\t\tconst formattedRelationships = await formatRelationships(\n\t\t\truntime,\n\t\t\trelationships,\n\t\t);\n\n\t\tif (!formattedRelationships) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\trelationships: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\trelationships: \"No relationships found.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No relationships found.\",\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\trelationships: formattedRelationships,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\trelationships: formattedRelationships,\n\t\t\t},\n\t\t\ttext: `# ${runtime.character.name} has observed ${message.content.senderName || message.content.name} interacting with these people:\\n${formattedRelationships}`,\n\t\t};\n\t},\n};\n\nexport { relationshipsProvider };\n","import { createUniqueUuid } from \"../entities\";\nimport { logger } from \"../logger\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype ProviderResult,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\nexport const roleProvider: Provider = {\n\tname: \"ROLES\",\n\tdescription:\n\t\t\"Roles in the server, default are OWNER, ADMIN and MEMBER (as well as NONE)\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<ProviderResult> => {\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getDatabaseAdapter().getRoom(message.roomId));\n\t\tif (!room) {\n\t\t\tthrow new Error(\"No room found\");\n\t\t}\n\n\t\tif (room.type !== ChannelType.GROUP) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles:\n\t\t\t\t\t\t\"No access to role information in DMs, the role provider is only available in group scenarios.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No access to role information in DMs, the role provider is only available in group scenarios.\",\n\t\t\t};\n\t\t}\n\n\t\tconst serverId = room.serverId;\n\n\t\tif (!serverId) {\n\t\t\tthrow new Error(\"No server ID found\");\n\t\t}\n\n\t\ttry {\n\t\t\tlogger.info(`Using server ID: ${serverId}`);\n\n\t\t\t// Get world data instead of using cache\n\t\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\t\tif (!world || !world.metadata?.ownership?.ownerId) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`No ownership data found for server ${serverId}, initializing empty role hierarchy`,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\troles: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\troles: \"No role information available for this server.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No role information available for this server.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Get roles from world metadata\n\t\t\tconst roles = world.metadata.roles || {};\n\n\t\t\tif (Object.keys(roles).length === 0) {\n\t\t\t\tlogger.info(`No roles found for server ${serverId}`);\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\troles: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\troles: \"No role information available for this server.\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlogger.info(`Found ${Object.keys(roles).length} roles`);\n\n\t\t\t// Group users by role\n\t\t\tconst owners: { name: string; username: string; names: string[] }[] = [];\n\t\t\tconst admins: { name: string; username: string; names: string[] }[] = [];\n\t\t\tconst members: { name: string; username: string; names: string[] }[] = [];\n\n\t\t\t// Process roles\n\t\t\tfor (const entityId of Object.keys(roles) as UUID[]) {\n\t\t\t\tconst userRole = roles[entityId];\n\n\t\t\t\t// get the user from the database\n\t\t\t\tconst user = await runtime.getDatabaseAdapter().getEntityById(entityId);\n\n\t\t\t\tconst name = user.metadata[room.source]?.name;\n\t\t\t\tconst username = user.metadata[room.source]?.username;\n\t\t\t\tconst names = user.names;\n\n\t\t\t\t// Skip duplicates (we store both UUID and original ID)\n\t\t\t\tif (\n\t\t\t\t\towners.some((owner) => owner.username === username) ||\n\t\t\t\t\tadmins.some((admin) => admin.username === username) ||\n\t\t\t\t\tmembers.some((member) => member.username === username)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Add to appropriate group\n\t\t\t\tswitch (userRole) {\n\t\t\t\t\tcase \"OWNER\":\n\t\t\t\t\t\towners.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"ADMIN\":\n\t\t\t\t\t\tadmins.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmembers.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Format the response\n\t\t\tlet response = \"# Server Role Hierarchy\\n\\n\";\n\n\t\t\tif (owners.length > 0) {\n\t\t\t\tresponse += \"## Owners\\n\";\n\t\t\t\towners.forEach((owner) => {\n\t\t\t\t\tresponse += `${owner.name} (${owner.names.join(\", \")})\\n`;\n\t\t\t\t});\n\t\t\t\tresponse += \"\\n\";\n\t\t\t}\n\n\t\t\tif (admins.length > 0) {\n\t\t\t\tresponse += \"## Administrators\\n\";\n\t\t\t\tadmins.forEach((admin) => {\n\t\t\t\t\tresponse += `${admin.name} (${admin.names.join(\", \")}) (${\n\t\t\t\t\t\tadmin.username\n\t\t\t\t\t})\\n`;\n\t\t\t\t});\n\t\t\t\tresponse += \"\\n\";\n\t\t\t}\n\n\t\t\tif (members.length > 0) {\n\t\t\t\tresponse += \"## Members\\n\";\n\t\t\t\tmembers.forEach((member) => {\n\t\t\t\t\tresponse += `${member.name} (${member.names.join(\", \")}) (${\n\t\t\t\t\t\tmember.username\n\t\t\t\t\t})\\n`;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: response,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles: response,\n\t\t\t\t},\n\t\t\t\ttext: response,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in role provider:\", error);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles: \"There was an error retrieving role information.\",\n\t\t\t\t},\n\t\t\t\ttext: \"There was an error retrieving role information.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default roleProvider;\n","import { createUniqueUuid } from \"./entities\";\nimport { logger } from \"./logger\";\nimport type {\n\tIAgentRuntime,\n\tOnboardingConfig,\n\tSetting,\n\tWorld,\n\tWorldSettings,\n} from \"./types\";\nimport crypto from \"node:crypto\";\n\nfunction createSettingFromConfig(\n\tconfigSetting: Omit<Setting, \"value\">,\n): Setting {\n\treturn {\n\t\tname: configSetting.name,\n\t\tdescription: configSetting.description,\n\t\tusageDescription: configSetting.usageDescription || \"\",\n\t\tvalue: null,\n\t\trequired: configSetting.required,\n\t\tvalidation: configSetting.validation || null,\n\t\tpublic: configSetting.public || false,\n\t\tsecret: configSetting.secret || false,\n\t\tdependsOn: configSetting.dependsOn || [],\n\t\tonSetAction: configSetting.onSetAction || null,\n\t\tvisibleIf: configSetting.visibleIf || null,\n\t};\n}\n\n/**\n * Generate a salt for settings encryption\n */\nfunction getSalt(runtime: IAgentRuntime): string {\n\tconst secretSalt = process.env.SECRET_SALT || \"secretsalt\";\n\treturn secretSalt + runtime.agentId;\n}\n\n/**\n * Applies salt to the value of a setting\n * Only applies to secret settings with string values\n */\nfunction saltSettingValue(setting: Setting, salt: string): Setting {\n\tconst settingCopy = { ...setting };\n\n\t// Only encrypt string values in secret settings\n\tif (\n\t\tsetting.secret === true &&\n\t\ttypeof setting.value === \"string\" &&\n\t\tsetting.value\n\t) {\n\t\t// Create key and iv from the salt\n\t\tconst key = crypto.createHash(\"sha256\").update(salt).digest().slice(0, 32);\n\t\tconst iv = crypto.randomBytes(16);\n\n\t\t// Encrypt the value\n\t\tconst cipher = crypto.createCipheriv(\"aes-256-cbc\", key, iv);\n\t\tlet encrypted = cipher.update(setting.value, \"utf8\", \"hex\");\n\t\tencrypted += cipher.final(\"hex\");\n\n\t\t// Store IV with the encrypted value so we can decrypt it later\n\t\tsettingCopy.value = `${iv.toString(\"hex\")}:${encrypted}`;\n\t}\n\n\treturn settingCopy;\n}\n\n/**\n * Removes salt from the value of a setting\n * Only applies to secret settings with string values\n */\nfunction unsaltSettingValue(setting: Setting, salt: string): Setting {\n\tconst settingCopy = { ...setting };\n\n\t// Only decrypt string values in secret settings\n\tif (\n\t\tsetting.secret === true &&\n\t\ttypeof setting.value === \"string\" &&\n\t\tsetting.value\n\t) {\n\t\ttry {\n\t\t\t// Split the IV and encrypted value\n\t\t\tconst parts = setting.value.split(\":\");\n\t\t\tif (parts.length !== 2) {\n\t\t\t\tthrow new Error(\"Invalid encrypted value format\");\n\t\t\t}\n\n\t\t\tconst iv = Buffer.from(parts[0], \"hex\");\n\t\t\tconst encrypted = parts[1];\n\n\t\t\t// Create key from the salt\n\t\t\tconst key = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(salt)\n\t\t\t\t.digest()\n\t\t\t\t.slice(0, 32);\n\n\t\t\t// Decrypt the value\n\t\t\tconst decipher = crypto.createDecipheriv(\"aes-256-cbc\", key, iv);\n\t\t\tlet decrypted = decipher.update(encrypted, \"hex\", \"utf8\");\n\t\t\tdecrypted += decipher.final(\"utf8\");\n\n\t\t\tsettingCopy.value = decrypted;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error decrypting setting value: ${error}`);\n\t\t\t// Return the encrypted value on error\n\t\t}\n\t}\n\n\treturn settingCopy;\n}\n\n/**\n * Applies salt to all settings in a WorldSettings object\n */\nfunction saltWorldSettings(\n\tworldSettings: WorldSettings,\n\tsalt: string,\n): WorldSettings {\n\tconst saltedSettings: WorldSettings = {};\n\n\tfor (const [key, setting] of Object.entries(worldSettings)) {\n\t\tsaltedSettings[key] = saltSettingValue(setting, salt);\n\t}\n\n\treturn saltedSettings;\n}\n\n/**\n * Removes salt from all settings in a WorldSettings object\n */\nfunction unsaltWorldSettings(\n\tworldSettings: WorldSettings,\n\tsalt: string,\n): WorldSettings {\n\tconst unsaltedSettings: WorldSettings = {};\n\n\tfor (const [key, setting] of Object.entries(worldSettings)) {\n\t\tunsaltedSettings[key] = unsaltSettingValue(setting, salt);\n\t}\n\n\treturn unsaltedSettings;\n}\n\n/**\n * Updates settings state in world metadata\n */\nexport async function updateWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n): Promise<boolean> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\tif (!world) {\n\t\t\tlogger.error(`No world found for server ${serverId}`);\n\t\t\treturn false;\n\t\t}\n\n\t\t// Initialize metadata if it doesn't exist\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// Apply salt to settings before saving\n\t\tconst salt = getSalt(runtime);\n\t\tconst saltedSettings = saltWorldSettings(worldSettings, salt);\n\n\t\t// Update settings state\n\t\tworld.metadata.settings = saltedSettings;\n\n\t\t// Save updated world\n\t\tawait runtime.getDatabaseAdapter().updateWorld(world);\n\n\t\treturn true;\n\t} catch (error) {\n\t\tlogger.error(`Error updating settings state: ${error}`);\n\t\treturn false;\n\t}\n}\n\n/**\n * Gets settings state from world metadata\n */\nexport async function getWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getDatabaseAdapter().getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.settings) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Get settings from metadata\n\t\tconst saltedSettings = world.metadata.settings as WorldSettings;\n\n\t\t// Remove salt from settings before returning\n\t\tconst salt = getSalt(runtime);\n\t\treturn unsaltWorldSettings(saltedSettings, salt);\n\t} catch (error) {\n\t\tlogger.error(`Error getting settings state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Initializes settings configuration for a server\n */\nexport async function initializeOnboarding(\n\truntime: IAgentRuntime,\n\tworld: World,\n\tconfig: OnboardingConfig,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\t// Check if settings state already exists\n\t\tif (world.metadata?.settings) {\n\t\t\tlogger.info(\n\t\t\t\t`Onboarding state already exists for server ${world.serverId}`,\n\t\t\t);\n\t\t\t// Get settings from metadata and remove salt\n\t\t\tconst saltedSettings = world.metadata.settings as WorldSettings;\n\t\t\tconst salt = getSalt(runtime);\n\t\t\treturn unsaltWorldSettings(saltedSettings, salt);\n\t\t}\n\n\t\t// Create new settings state\n\t\tconst worldSettings: WorldSettings = {};\n\n\t\t// Initialize settings from config\n\t\tif (config.settings) {\n\t\t\tfor (const [key, configSetting] of Object.entries(config.settings)) {\n\t\t\t\tworldSettings[key] = createSettingFromConfig(configSetting);\n\t\t\t}\n\t\t}\n\n\t\t// Save settings state to world metadata\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// No need to salt here as the settings are just initialized with null values\n\t\tworld.metadata.settings = worldSettings;\n\n\t\tawait runtime.getDatabaseAdapter().updateWorld(world);\n\n\t\tlogger.info(`Initialized settings config for server ${world.serverId}`);\n\t\treturn worldSettings;\n\t} catch (error) {\n\t\tlogger.error(`Error initializing settings config: ${error}`);\n\t\treturn null;\n\t}\n}\n","// File: /swarm/shared/settings/provider.ts\n// Updated to use world metadata instead of cache\n\nimport { logger } from \"../logger\";\nimport { findWorldForOwner } from \"../roles\";\nimport { getWorldSettings } from \"../settings\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n\ttype Setting,\n\ttype WorldSettings,\n\ttype ProviderResult,\n} from \"../types\";\n\n/**\n * Formats a setting value for display, respecting privacy flags\n */\nconst formatSettingValue = (\n\tsetting: Setting,\n\tisOnboarding: boolean,\n): string => {\n\tif (setting.value === null) return \"Not set\";\n\tif (setting.secret && !isOnboarding) return \"****************\";\n\treturn String(setting.value);\n};\n\n/**\n * Generates a status message based on the current settings state\n */\nfunction generateStatusMessage(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tisOnboarding: boolean,\n\tstate?: State,\n): string {\n\ttry {\n\t\t// Format settings for display\n\t\tconst formattedSettings = Object.entries(worldSettings)\n\t\t\t.map(([_key, setting]) => {\n\t\t\t\tif (typeof setting !== \"object\" || !setting.name) return null;\n\n\t\t\t\tconst description = setting.description || \"\";\n\t\t\t\tconst usageDescription = setting.usageDescription || \"\";\n\n\t\t\t\t// Skip settings that should be hidden based on visibility function\n\t\t\t\tif (setting.visibleIf && !setting.visibleIf(worldSettings)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tname: setting.name,\n\t\t\t\t\tvalue: formatSettingValue(setting, isOnboarding),\n\t\t\t\t\tdescription,\n\t\t\t\t\tusageDescription,\n\t\t\t\t\trequired: setting.required,\n\t\t\t\t\tconfigured: setting.value !== null,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter(Boolean);\n\n\t\t// Count required settings that are not configured\n\t\tconst requiredUnconfigured = formattedSettings.filter(\n\t\t\t(s) => s.required && !s.configured,\n\t\t).length;\n\n\t\t// Generate appropriate message\n\t\tif (isOnboarding) {\n\t\t\tif (requiredUnconfigured > 0) {\n\t\t\t\treturn `# PRIORITY TASK: Onboarding with ${state.senderName}\\n${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} still needs to configure ${requiredUnconfigured} required settings:\\n\\n${formattedSettings\n\t\t\t\t\t.filter((s) => s.required && !s.configured)\n\t\t\t\t\t.map((s) => `${s.name}: ${s.usageDescription}\\nValue: ${s.value}`)\n\t\t\t\t\t.join(\n\t\t\t\t\t\t\"\\n\\n\",\n\t\t\t\t\t)}\\n\\nIf the user gives any information related to the settings, ${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} should use the UPDATE_SETTINGS action to update the settings with this new information. ${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} can update any, some or all settings.`;\n\t\t\t}\n\t\t\treturn `All required settings have been configured! Here's the current configuration:\\n\\n${formattedSettings\n\t\t\t\t.map((s) => `${s.name}: ${s.description}\\nValue: ${s.value}`)\n\t\t\t\t.join(\"\\n\")}`;\n\t\t}\n\t\t// Non-onboarding context - list all public settings with values and descriptions\n\t\treturn `## Current Configuration\\n\\n${\n\t\t\trequiredUnconfigured > 0\n\t\t\t\t? `IMPORTANT!: ${requiredUnconfigured} required settings still need configuration. ${runtime.character.name} should get onboarded with the OWNER as soon as possible.\\n\\n`\n\t\t\t\t: \"All required settings are configured.\\n\\n\"\n\t\t}${formattedSettings\n\t\t\t.map(\n\t\t\t\t(s) =>\n\t\t\t\t\t`### ${s.name}\\n**Value:** ${s.value}\\n**Description:** ${s.description}`,\n\t\t\t)\n\t\t\t.join(\"\\n\\n\")}`;\n\t} catch (error) {\n\t\tlogger.error(`Error generating status message: ${error}`);\n\t\treturn \"Error generating configuration status.\";\n\t}\n}\n\n/**\n * Creates an settings provider with the given configuration\n * Updated to use world metadata instead of cache\n */\nexport const settingsProvider: Provider = {\n\tname: \"SETTINGS\",\n\tdescription: \"Current settings for the server\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Parallelize the initial database operations to improve performance\n\t\t\t// These operations can run simultaneously as they don't depend on each other\n\t\t\tconst [room, userWorld] = await Promise.all([\n\t\t\t\truntime.getDatabaseAdapter().getRoom(message.roomId),\n\t\t\t\tfindWorldForOwner(runtime, message.entityId),\n\t\t\t]).catch((error) => {\n\t\t\t\tlogger.error(`Error fetching initial data: ${error}`);\n\t\t\t\tthrow new Error(\"Failed to retrieve room or user world information\");\n\t\t\t});\n\n\t\t\tif (!room) {\n\t\t\t\tlogger.error(\"No room found for settings provider\");\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\tsettings: \"Error: Room not found\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"Error: Room not found\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst type = room.type;\n\t\t\tconst isOnboarding = type === ChannelType.DM;\n\n\t\t\tlet world;\n\t\t\tlet serverId;\n\t\t\tlet worldSettings;\n\n\t\t\tif (isOnboarding) {\n\t\t\t\t// In onboarding mode, use the user's world directly\n\t\t\t\tworld = userWorld;\n\n\t\t\t\tif (!world) {\n\t\t\t\t\tlogger.error(\"No world found for user during onboarding\");\n\t\t\t\t\tthrow new Error(\"No server ownership found for onboarding\");\n\t\t\t\t}\n\n\t\t\t\tserverId = world.serverId;\n\n\t\t\t\t// Fetch world settings based on the server ID\n\t\t\t\ttry {\n\t\t\t\t\tworldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error fetching world settings: ${error}`);\n\t\t\t\t\tthrow new Error(`Failed to retrieve settings for server ${serverId}`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// For non-onboarding, we need to get the world associated with the room\n\t\t\t\ttry {\n\t\t\t\t\tworld = await runtime.getDatabaseAdapter().getWorld(room.worldId);\n\t\t\t\t\tserverId = world.serverId;\n\n\t\t\t\t\t// Once we have the serverId, get the settings\n\t\t\t\t\tif (serverId) {\n\t\t\t\t\t\tworldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error(`No server ID found for world ${room.worldId}`);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error processing world data: ${error}`);\n\t\t\t\t\tthrow new Error(\"Failed to process world information\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no server found after recovery attempts\n\t\t\tif (!serverId) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`No server ownership found for user ${message.entityId} after recovery attempt`,\n\t\t\t\t);\n\t\t\t\treturn isOnboarding\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings:\n\t\t\t\t\t\t\t\t\t\"The user doesn't appear to have ownership of any servers. They should make sure they're using the correct account.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"The user doesn't appear to have ownership of any servers. They should make sure they're using the correct account.\",\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings: \"Error: No configuration access\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"Error: No configuration access\",\n\t\t\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.info(`No settings state found for server ${serverId}`);\n\t\t\t\treturn isOnboarding\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings:\n\t\t\t\t\t\t\t\t\t\"The user doesn't appear to have any settings configured for this server. They should configure some settings for this server.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"The user doesn't appear to have any settings configured for this server. They should configure some settings for this server.\",\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings: \"Configuration has not been completed yet.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"Configuration has not been completed yet.\",\n\t\t\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Generate the status message based on the settings\n\t\t\tconst output = generateStatusMessage(\n\t\t\t\truntime,\n\t\t\t\tworldSettings,\n\t\t\t\tisOnboarding,\n\t\t\t\tstate,\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tsettings: worldSettings,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tsettings: output,\n\t\t\t\t},\n\t\t\t\ttext: output,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(`Critical error in settings provider: ${error}`);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tsettings: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tsettings:\n\t\t\t\t\t\t\"Error retrieving configuration information. Please try again later.\",\n\t\t\t\t},\n\t\t\t\ttext: \"Error retrieving configuration information. Please try again later.\",\n\t\t\t};\n\t\t}\n\t},\n};\n","import type { IAgentRuntime, Memory, Provider, State } from \"../types\";\n\nexport const timeProvider: Provider = {\n\tname: \"TIME\",\n\tget: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\tconst currentDate = new Date();\n\n\t\t// Get UTC time since bots will be communicating with users around the global\n\t\tconst options = {\n\t\t\ttimeZone: \"UTC\",\n\t\t\tdateStyle: \"full\" as const,\n\t\t\ttimeStyle: \"long\" as const,\n\t\t};\n\t\tconst humanReadable = new Intl.DateTimeFormat(\"en-US\", options).format(\n\t\t\tcurrentDate,\n\t\t);\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\ttime: currentDate,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\ttime: humanReadable,\n\t\t\t},\n\t\t\ttext: `The current date and time is ${humanReadable}. Please use this as your reference for any time-based operations or responses.`,\n\t\t};\n\t},\n};\n","// registered to runtime through plugin\n\nimport logger from \"../logger\";\nimport {\n\ttype IAgentRuntime,\n\tService,\n\tServiceTypes,\n\ttype UUID,\n\ttype ServiceType,\n\ttype Memory,\n\ttype State,\n\ttype Task,\n} from \"../types\";\n\nexport class TaskService extends Service {\n\tprivate timer: NodeJS.Timeout | null = null;\n\tprivate readonly TICK_INTERVAL = 1000; // Check every second\n\tstatic serviceType: ServiceType = ServiceTypes.TASK;\n\tcapabilityDescription = \"The agent is able to schedule and execute tasks\";\n\n\tstatic async start(runtime: IAgentRuntime): Promise<TaskService> {\n\t\tconst service = new TaskService(runtime);\n\t\tawait service.startTimer();\n\t\t// await service.createTestTasks();\n\t\treturn service;\n\t}\n\n\tasync createTestTasks() {\n\t\t// Register task worker for repeating task\n\t\tthis.runtime.registerTaskWorker({\n\t\t\tname: \"REPEATING_TEST_TASK\",\n\t\t\tvalidate: async (_runtime, _message, _state) => {\n\t\t\t\tlogger.debug(\"Validating repeating test task\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\texecute: async (_runtime, _options) => {\n\t\t\t\tlogger.debug(\"Executing repeating test task\");\n\t\t\t},\n\t\t});\n\n\t\t// Register task worker for one-time task\n\t\tthis.runtime.registerTaskWorker({\n\t\t\tname: \"ONETIME_TEST_TASK\",\n\t\t\tvalidate: async (_runtime, _message, _state) => {\n\t\t\t\tlogger.debug(\"Validating one-time test task\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\texecute: async (_runtime, _options) => {\n\t\t\t\tlogger.debug(\"Executing one-time test task\");\n\t\t\t},\n\t\t});\n\n\t\t// check if the task exists\n\t\tconst tasks = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getTasksByName(\"REPEATING_TEST_TASK\");\n\n\t\tif (tasks.length === 0) {\n\t\t\t// Create repeating task\n\t\t\tawait this.runtime.getDatabaseAdapter().createTask({\n\t\t\t\tname: \"REPEATING_TEST_TASK\",\n\t\t\t\tdescription: \"A test task that repeats every minute\",\n\t\t\t\tmetadata: {\n\t\t\t\t\tupdatedAt: Date.now(), // Use timestamp instead of Date object\n\t\t\t\t\tupdateInterval: 1000 * 60, // 1 minute\n\t\t\t\t},\n\t\t\t\ttags: [\"queue\", \"repeat\", \"test\"],\n\t\t\t});\n\t\t}\n\n\t\t// Create one-time task\n\t\tawait this.runtime.getDatabaseAdapter().createTask({\n\t\t\tname: \"ONETIME_TEST_TASK\",\n\t\t\tdescription: \"A test task that runs once\",\n\t\t\tmetadata: {\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t},\n\t\t\ttags: [\"queue\", \"test\"],\n\t\t});\n\t}\n\n\tprivate startTimer() {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t}\n\n\t\tthis.timer = setInterval(async () => {\n\t\t\tawait this.checkTasks();\n\t\t}, this.TICK_INTERVAL);\n\t}\n\n\tprivate async validateTasks(tasks: Task[]): Promise<Task[]> {\n\t\tconst validatedTasks: Task[] = [];\n\n\t\tfor (const task of tasks) {\n\t\t\t// Skip tasks without IDs\n\t\t\tif (!task.id) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst worker = this.runtime.getTaskWorker(task.name);\n\n\t\t\t// Skip if no worker found for task\n\t\t\tif (!worker) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// If worker has validate function, run validation\n\t\t\tif (worker.validate) {\n\t\t\t\ttry {\n\t\t\t\t\t// Pass empty message and state since validation is time-based\n\t\t\t\t\tconst isValid = await worker.validate(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t{} as Memory,\n\t\t\t\t\t\t{} as State,\n\t\t\t\t\t);\n\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error validating task ${task.name}:`, error);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvalidatedTasks.push(task);\n\t\t}\n\n\t\treturn validatedTasks;\n\t}\n\n\tprivate async checkTasks() {\n\t\ttry {\n\t\t\t// Get all tasks with \"queue\" tag\n\t\t\tconst allTasks = await this.runtime.getDatabaseAdapter().getTasks({\n\t\t\t\ttags: [\"queue\"],\n\t\t\t});\n\n\t\t\t// validate the tasks and sort them\n\t\t\tconst tasks = await this.validateTasks(allTasks);\n\n\t\t\tif (tasks.length > 0) {\n\t\t\t\tlogger.debug(`Found ${tasks.length} queued tasks`);\n\t\t\t}\n\n\t\t\tconst now = Date.now();\n\n\t\t\tfor (const task of tasks) {\n\t\t\t\tconst taskStartTime = new Date(task.updatedAt || 0).getTime();\n\n\t\t\t\t// convert updatedAt which is an ISO string to a number\n\t\t\t\tconst updateIntervalMs = task.metadata.updateInterval ?? 0; // update immediately\n\n\t\t\t\t// if tags does not contain \"repeat\", execute immediately\n\t\t\t\tif (!task.tags?.includes(\"repeat\")) {\n\t\t\t\t\tawait this.executeTask(task);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Check if enough time has passed since last update\n\t\t\t\tif (now - taskStartTime >= updateIntervalMs) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t`Executing task ${task.name} - interval of ${updateIntervalMs}ms has elapsed`,\n\t\t\t\t\t);\n\t\t\t\t\tawait this.executeTask(task);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error checking tasks:\", error);\n\t\t}\n\t}\n\n\tprivate async executeTask(task: Task) {\n\t\ttry {\n\t\t\tif (!task) {\n\t\t\t\tlogger.debug(`Task ${task.id} not found`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst worker = this.runtime.getTaskWorker(task.name);\n\t\t\tif (!worker) {\n\t\t\t\tlogger.debug(`No worker found for task type: ${task.name}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.debug(`Executing task ${task.name} (${task.id})`);\n\t\t\tawait worker.execute(this.runtime, task.metadata || {});\n\t\t\tlogger.debug(\"task.tags are\", task.tags);\n\t\t\t// Handle repeating vs non-repeating tasks\n\t\t\tif (task.tags?.includes(\"repeat\")) {\n\t\t\t\t// For repeating tasks, update the updatedAt timestamp\n\t\t\t\tawait this.runtime.getDatabaseAdapter().updateTask(task.id, {\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...task.metadata,\n\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`Updated repeating task ${task.name} (${task.id}) with new timestamp`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// For non-repeating tasks, delete the task after execution\n\t\t\t\tawait this.runtime.getDatabaseAdapter().deleteTask(task.id);\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`Deleted non-repeating task ${task.name} (${task.id}) after execution`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error executing task ${task.id}:`, error);\n\t\t}\n\t}\n\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\tconst service = runtime.getService(ServiceTypes.TASK);\n\t\tif (service) {\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\tasync stop() {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t}\n}\n","import { v4 as uuidv4 } from \"uuid\";\nimport { createUniqueUuid } from \"../entities\";\nimport { logger } from \"../logger\";\nimport {\n\tChannelType,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tService,\n\ttype UUID,\n} from \"../types\";\n\nexport class ScenarioService extends Service {\n\tstatic serviceType = \"scenario\";\n\tcapabilityDescription =\n\t\t\"The agent is currently in a scenario testing environment. It can create rooms, send messages, and talk to other agents in a live interactive testing environment.\";\n\tprivate messageHandlers: Map<UUID, HandlerCallback[]> = new Map();\n\tprivate rooms: Map<string, { roomId: UUID }> = new Map();\n\n\tconstructor(protected runtime: IAgentRuntime) {\n\t\tsuper(runtime);\n\t}\n\n\tstatic async start(runtime: IAgentRuntime) {\n\t\tconst service = new ScenarioService(runtime);\n\t\treturn service;\n\t}\n\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\t// get the service from the runtime\n\t\tconst service = runtime.getService(ScenarioService.serviceType);\n\t\tif (!service) {\n\t\t\tthrow new Error(\"Scenario service not found\");\n\t\t}\n\t\tservice.stop();\n\t}\n\n\tasync stop() {\n\t\tthis.messageHandlers.clear();\n\t\tthis.rooms.clear();\n\t}\n\n\t// Create a room for an agent\n\tasync createRoom(agentId: string, name?: string) {\n\t\tconst roomId = uuidv4() as UUID;\n\n\t\tawait this.runtime.ensureRoomExists({\n\t\t\tid: roomId as UUID,\n\t\t\tname: name || `Room for ${agentId}`,\n\t\t\tsource: \"scenario\",\n\t\t\ttype: ChannelType.GROUP,\n\t\t\tchannelId: roomId,\n\t\t\tserverId: null,\n\t\t});\n\n\t\tthis.rooms.set(agentId, { roomId: roomId as UUID });\n\t}\n\n\t// Save a message in all agents' memory without emitting events\n\tasync saveMessage(\n\t\tsender: IAgentRuntime,\n\t\treceivers: IAgentRuntime[],\n\t\ttext: string,\n\t) {\n\t\tfor (const receiver of receivers) {\n\t\t\tconst roomData = this.rooms.get(receiver.agentId);\n\t\t\tif (!roomData) continue;\n\t\t\tconst entityId = createUniqueUuid(receiver, sender.agentId);\n\n\t\t\t// Ensure connection exists\n\t\t\tawait receiver.ensureConnection({\n\t\t\t\tentityId,\n\t\t\t\troomId: roomData.roomId,\n\t\t\t\tuserName: sender.character.name,\n\t\t\t\tname: sender.character.name,\n\t\t\t\tsource: \"scenario\",\n\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t});\n\n\t\t\tconst memory: Memory = {\n\t\t\t\tentityId,\n\t\t\t\tagentId: receiver.agentId,\n\t\t\t\troomId: roomData.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext,\n\t\t\t\t\tsource: \"scenario\",\n\t\t\t\t\tname: sender.character.name,\n\t\t\t\t\tuserName: sender.character.name,\n\t\t\t\t\tchannelType: ChannelType.GROUP,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tawait receiver.getMemoryManager(\"messages\").createMemory(memory);\n\t\t}\n\t}\n\n\t// Send a live message that triggers handlers\n\tasync sendMessage(\n\t\tsender: IAgentRuntime,\n\t\treceivers: IAgentRuntime[],\n\t\ttext: string,\n\t) {\n\t\tfor (const receiver of receivers) {\n\t\t\tconst roomData = this.rooms.get(receiver.agentId);\n\t\t\tif (!roomData) continue;\n\n\t\t\tconst entityId = createUniqueUuid(receiver, sender.agentId);\n\n\t\t\tif (receiver.agentId !== sender.agentId) {\n\t\t\t\t// Ensure connection exists\n\t\t\t\tawait receiver.ensureConnection({\n\t\t\t\t\tentityId,\n\t\t\t\t\troomId: roomData.roomId,\n\t\t\t\t\tuserName: sender.character.name,\n\t\t\t\t\tname: sender.character.name,\n\t\t\t\t\tsource: \"scenario\",\n\t\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tawait receiver.ensureConnection({\n\t\t\t\t\tentityId: sender.agentId,\n\t\t\t\t\troomId: roomData.roomId,\n\t\t\t\t\tuserName: sender.character.name,\n\t\t\t\t\tname: sender.character.name,\n\t\t\t\t\tsource: \"scenario\",\n\t\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst memory: Memory = {\n\t\t\t\tentityId:\n\t\t\t\t\treceiver.agentId !== sender.agentId ? entityId : sender.agentId,\n\t\t\t\tagentId: receiver.agentId,\n\t\t\t\troomId: roomData.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext,\n\t\t\t\t\tsource: \"scenario\",\n\t\t\t\t\tname: sender.character.name,\n\t\t\t\t\tuserName: sender.character.name,\n\t\t\t\t\tchannelType: ChannelType.GROUP,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\treceiver.emitEvent(\"MESSAGE_RECEIVED\", {\n\t\t\t\truntime: receiver,\n\t\t\t\tmessage: memory,\n\t\t\t\troomId: roomData.roomId,\n\t\t\t\tentityId:\n\t\t\t\t\treceiver.agentId !== sender.agentId ? entityId : sender.agentId,\n\t\t\t\tsource: \"scenario\",\n\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Get conversation history for all participants\n\tasync getConversations(participants: IAgentRuntime[]) {\n\t\tconst conversations = await Promise.all(\n\t\t\tparticipants.map(async (member) => {\n\t\t\t\tconst roomData = this.rooms.get(member.agentId);\n\t\t\t\tif (!roomData) return [];\n\t\t\t\treturn member.getMemoryManager(\"messages\").getMemories({\n\t\t\t\t\troomId: roomData.roomId,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\n\t\tlogger.info(\"\\nConversation logs per agent:\");\n\t\tconversations.forEach((convo, i) => {\n\t\t\tlogger.info(`\\n${participants[i].character.name}'s perspective:`);\n\t\t\tconvo.forEach((msg) =>\n\t\t\t\tlogger.info(`${msg.content.name}: ${msg.content.text}`),\n\t\t\t);\n\t\t});\n\n\t\treturn conversations;\n\t}\n}\n\n// Updated scenario implementation using the new client\nconst scenarios = [\n\tasync function scenario1(members: IAgentRuntime[]) {\n\t\t// Create and register test client\n\t\tconst service = await ScenarioService.start(members[0]);\n\t\tmembers[0].registerService(ScenarioService);\n\n\t\t// Create rooms for all members\n\t\tfor (const member of members) {\n\t\t\tawait service.createRoom(\n\t\t\t\tmember.agentId,\n\t\t\t\t`Test Room for ${member.character.name}`,\n\t\t\t);\n\t\t}\n\n\t\t// Set up conversation history\n\t\tawait service.saveMessage(\n\t\t\tmembers[0],\n\t\t\tmembers,\n\t\t\t\"Earlier message from conversation...\",\n\t\t);\n\t\t// await client.saveMessage(\n\t\t// members[1],\n\t\t// members,\n\t\t// \"Previous reply in history...\"\n\t\t// );\n\n\t\t// // Send live message that triggers handlers\n\t\t// await client.sendMessage(members[0], members, \"Hello everyone!\");\n\n\t\t// // Get and display conversation logs\n\t\t// // wait 5 seconds\n\t\t// await new Promise((resolve) => setTimeout(resolve, 5000));\n\t\t// await client.getConversations(members);\n\n\t\t// Send a message to all members\n\t\t// await client.sendMessage(members[0], members, \"Hello everyone!\");\n\t},\n];\n\nexport async function startScenario(members: IAgentRuntime[]) {\n\tfor (const scenario of scenarios) {\n\t\tawait scenario(members);\n\t}\n}\n","import { sha1 } from \"js-sha1\";\nimport { z } from \"zod\";\nimport type { UUID } from \"./types.ts\";\n\nexport const uuidSchema = z.string().uuid() as z.ZodType<UUID>;\n\nexport function validateUuid(value: unknown): UUID | null {\n\tconst result = uuidSchema.safeParse(value);\n\treturn result.success ? result.data : null;\n}\n\nexport function stringToUuid(target: string | number): UUID {\n\tif (typeof target === \"number\") {\n\t\ttarget = (target as number).toString();\n\t}\n\n\tif (typeof target !== \"string\") {\n\t\tthrow TypeError(\"Value must be string\");\n\t}\n\n\tconst _uint8ToHex = (ubyte: number): string => {\n\t\tconst first = ubyte >> 4;\n\t\tconst second = ubyte - (first << 4);\n\t\tconst HEX_DIGITS = \"0123456789abcdef\".split(\"\");\n\t\treturn HEX_DIGITS[first] + HEX_DIGITS[second];\n\t};\n\n\tconst _uint8ArrayToHex = (buf: Uint8Array): string => {\n\t\tlet out = \"\";\n\t\tfor (let i = 0; i < buf.length; i++) {\n\t\t\tout += _uint8ToHex(buf[i]);\n\t\t}\n\t\treturn out;\n\t};\n\n\tconst escapedStr = encodeURIComponent(target);\n\tconst buffer = new Uint8Array(escapedStr.length);\n\tfor (let i = 0; i < escapedStr.length; i++) {\n\t\tbuffer[i] = escapedStr[i].charCodeAt(0);\n\t}\n\n\tconst hash = sha1(buffer);\n\tconst hashBuffer = new Uint8Array(hash.length / 2);\n\tfor (let i = 0; i < hash.length; i += 2) {\n\t\thashBuffer[i / 2] = Number.parseInt(hash.slice(i, i + 2), 16);\n\t}\n\n\treturn `${_uint8ArrayToHex(hashBuffer.slice(0, 4))}-${_uint8ArrayToHex(hashBuffer.slice(4, 6))}-${_uint8ToHex(hashBuffer[6] & 0x0f)}${_uint8ToHex(hash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,KAAK,SAAS,WAAW,gBAAgB,IAAI;AAErE,UAAI,CAAC,aAAa,CAAC,UAAU,QAAQ;AACpC,cAAM,IAAI;AAAA,UACT,kBAAkB,KAAK,UAAU,IAAI;AAAA,QACtC;AAAA,MACD;AAEA,aAAO;AAAA,QACN,kBAAkB,KAAK,UAAU,IAAI,kCAAkC,UAAU,MAAM;AAAA,MACxF;AACA,YAAM,KAAK,mBAAmB,EAAE;AAAA,QAC/B,UAAU;AAAA,MACX;AACA,aAAO;AAAA,QACN,kBAAkB,KAAK,UAAU,IAAI;AAAA,MACtC;AAAA,IACD,SAAS,OAAO;AACf,aAAO;AAAA,QACN,kBAAkB,KAAK,UAAU,IAAI;AAAA,QACrC;AAAA,MACD;AACA,YAAM;AAAA,IACP;AAAA,EACD;AAAA,EAEA,mBAAmB,aAA+B;AACjD,QAAI,KAAK,YAAY,IAAI,YAAY,IAAI,GAAG;AAC3C,aAAO;AAAA,QACN,mBAAmB,YAAY,IAAI;AAAA,MACpC;AAAA,IACD;AACA,SAAK,YAAY,IAAI,YAAY,MAAM,WAAW;AAAA,EACnD;AAAA,EAEA,cAAcE,OAAsC;AACnD,WAAO,KAAK,YAAY,IAAIA,KAAI;AAAA,EACjC;AACD;","names":["GoalStatus","MemoryType","ChannelType","KnowledgeScope","CacheKeyPrefix","TEEMode","TeeType","Role","names","uniqueNamesGenerator","stream","uniqueNamesGenerator","names","entity","util","objectUtil","path","errorUtil","path","errorMap","ctx","options","result","issues","elements","processed","ZodFirstPartyTypeKind","settings","path","uuidv4","options","state","state","response","name","extractionTemplate","generateObject","response","generateObjectArray","settings","state","state","options","generateObject","response","handler","topic","message","name","options","names","uniqueNamesGenerator","uniqueNamesGenerator","names","name","formatFacts","message","knowledge","getRecentInteractions","message","recentInteractionsData","names","name","names","updateWorldSettings","getWorldSettings","config","getWorldSettings","options","isValid","uuidv4","name","uuidv4","response","uuidv4","handler","options","name","names","events"]}
1
+ {"version":3,"sources":["../../../node_modules/dedent/dist/dedent.js","../src/types.ts","../src/actions.ts","../src/database.ts","../src/prompts.ts","../src/logger.ts","../src/entities.ts","../src/environment.ts","../../../node_modules/zod/lib/index.mjs","../src/import.ts","../src/memory.ts","../src/roles.ts","../src/runtime.ts","../src/bootstrap.ts","../src/actions/choice.ts","../src/actions/followRoom.ts","../src/actions/ignore.ts","../src/actions/muteRoom.ts","../src/actions/none.ts","../src/actions/reply.ts","../src/actions/roles.ts","../src/actions/sendMessage.ts","../src/actions/settings.ts","../src/actions/unfollowRoom.ts","../src/actions/unmuteRoom.ts","../src/actions/updateEntity.ts","../src/evaluators/reflection.ts","../src/providers/actions.ts","../src/providers/anxiety.ts","../src/providers/attachments.ts","../src/providers/capabilities.ts","../src/providers/character.ts","../src/providers/choice.ts","../src/providers/entities.ts","../src/providers/evaluators.ts","../src/providers/facts.ts","../src/providers/knowledge.ts","../src/providers/providers.ts","../src/providers/recentMessages.ts","../src/providers/relationships.ts","../src/providers/roles.ts","../src/settings.ts","../src/providers/settings.ts","../src/providers/time.ts","../src/services/scenario.ts","../src/services/task.ts","../src/uuid.ts"],"sourcesContent":["\"use strict\";\n\nfunction dedent(strings) {\n\n var raw = void 0;\n if (typeof strings === \"string\") {\n // dedent can be used as a plain function\n raw = [strings];\n } else {\n raw = strings.raw;\n }\n\n // first, perform interpolation\n var result = \"\";\n for (var i = 0; i < raw.length; i++) {\n result += raw[i].\n // join lines when there is a suppressed newline\n replace(/\\\\\\n[ \\t]*/g, \"\").\n\n // handle escaped backticks\n replace(/\\\\`/g, \"`\");\n\n if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {\n result += arguments.length <= i + 1 ? undefined : arguments[i + 1];\n }\n }\n\n // now strip indentation\n var lines = result.split(\"\\n\");\n var mindent = null;\n lines.forEach(function (l) {\n var m = l.match(/^(\\s+)\\S+/);\n if (m) {\n var indent = m[1].length;\n if (!mindent) {\n // this is the first indented line\n mindent = indent;\n } else {\n mindent = Math.min(mindent, indent);\n }\n }\n });\n\n if (mindent !== null) {\n result = lines.map(function (l) {\n return l[0] === \" \" ? l.slice(mindent) : l;\n }).join(\"\\n\");\n }\n\n // dedent eats leading and trailing whitespace too\n result = result.trim();\n\n // handle escaped newlines at the end to ensure they don't get stripped too\n return result.replace(/\\\\n/g, \"\\n\");\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = dedent;\n}\n","import type { Readable } from \"node:stream\";\n\n/**\n * Represents a UUID string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n */\n/**\n * Type definition for a Universally Unique Identifier (UUID) using a specific format.\n * @typedef {`${string}-${string}-${string}-${string}-${string}`} UUID\n */\nexport type UUID = `${string}-${string}-${string}-${string}-${string}`;\n\n/**\n * Represents the content of a message or communication\n */\nexport interface Content {\n\tthought?: string;\n\n\t/** The agent's plan for the next message */\n\tplan?: string;\n\n\t/** The main text content */\n\ttext?: string;\n\n\t/** Optional action associated with the message */\n\tactions?: string[];\n\n\t/** Optional providers associated with the message */\n\tproviders?: string[];\n\n\t/** Optional source/origin of the content */\n\tsource?: string;\n\n\t/** URL of the original message/post (e.g. tweet URL, Discord message link) */\n\turl?: string;\n\n\t/** UUID of parent message if this is a reply/thread */\n\tinReplyTo?: UUID;\n\n\t/** Array of media attachments */\n\tattachments?: Media[];\n\n\t/** Additional dynamic properties */\n\t[key: string]: unknown;\n}\n\n/**\n * Example content with associated user for demonstration purposes\n */\nexport interface ActionExample {\n\t/** User associated with the example */\n\tname: string;\n\n\t/** Content of the example */\n\tcontent: Content;\n}\n\n/**\n * Example conversation content with user ID\n */\nexport interface ConversationExample {\n\t/** UUID of user in conversation */\n\tentityId: UUID;\n\n\t/** Content of the conversation */\n\tcontent: Content;\n}\n\nexport type ModelType = (typeof ModelTypes)[keyof typeof ModelTypes] | string;\n\n/**\n * Model size/type classification\n */\nexport const ModelTypes = {\n\tSMALL: \"TEXT_SMALL\", // kept for backwards compatibility\n\tMEDIUM: \"TEXT_LARGE\", // kept for backwards compatibility\n\tLARGE: \"TEXT_LARGE\", // kept for backwards compatibility\n\tTEXT_SMALL: \"TEXT_SMALL\",\n\tTEXT_LARGE: \"TEXT_LARGE\",\n\tTEXT_EMBEDDING: \"TEXT_EMBEDDING\",\n\tTEXT_TOKENIZER_ENCODE: \"TEXT_TOKENIZER_ENCODE\",\n\tTEXT_TOKENIZER_DECODE: \"TEXT_TOKENIZER_DECODE\",\n\tTEXT_REASONING_SMALL: \"REASONING_SMALL\",\n\tTEXT_REASONING_LARGE: \"REASONING_LARGE\",\n\tTEXT_COMPLETION: \"TEXT_COMPLETION\",\n\tIMAGE: \"IMAGE\",\n\tIMAGE_DESCRIPTION: \"IMAGE_DESCRIPTION\",\n\tTRANSCRIPTION: \"TRANSCRIPTION\",\n\tTEXT_TO_SPEECH: \"TEXT_TO_SPEECH\",\n\tAUDIO: \"AUDIO\",\n\tVIDEO: \"VIDEO\",\n\tOBJECT_SMALL: \"OBJECT_SMALL\",\n\tOBJECT_LARGE: \"OBJECT_LARGE\",\n} as const;\n\nexport type ServiceType = (typeof ServiceTypes)[keyof typeof ServiceTypes];\n\nexport const ServiceTypes = {\n\tTRANSCRIPTION: \"transcription\",\n\tVIDEO: \"video\",\n\tBROWSER: \"browser\",\n\tPDF: \"pdf\",\n\tREMOTE_FILES: \"aws_s3\",\n\tWEB_SEARCH: \"web_search\",\n\tEMAIL: \"email\",\n\tTEE: \"tee\",\n\tTASK: \"task\",\n} as const;\n\n/**\n * Represents the current state/context of a conversation\n */\nexport interface State {\n\t/** Additional dynamic properties */\n\t[key: string]: any;\n\tvalues: {\n\t\t[key: string]: any;\n\t};\n\tdata: {\n\t\t[key: string]: any;\n\t};\n\ttext: string;\n}\n\nexport type MemoryTypeAlias = string;\n\nexport enum MemoryType {\n\tDOCUMENT = \"document\",\n\tFRAGMENT = \"fragment\",\n\tMESSAGE = \"message\",\n\tDESCRIPTION = \"description\",\n\tCUSTOM = \"custom\",\n}\n\nexport interface BaseMetadata {\n\ttype: MemoryTypeAlias;\n\tsource?: string;\n\tsourceId?: UUID;\n\tscope?: string;\n\ttimestamp?: number;\n\ttags?: string[];\n}\n\nexport interface DocumentMetadata extends BaseMetadata {\n\ttype: MemoryType.DOCUMENT;\n}\n\nexport interface FragmentMetadata extends BaseMetadata {\n\ttype: MemoryType.FRAGMENT;\n\tdocumentId: UUID;\n\tposition: number;\n}\n\nexport interface MessageMetadata extends BaseMetadata {\n\ttype: MemoryType.MESSAGE;\n}\n\nexport interface DescriptionMetadata extends BaseMetadata {\n\ttype: MemoryType.DESCRIPTION;\n}\n\nexport interface CustomMetadata extends BaseMetadata {\n\ttype: MemoryTypeAlias;\n\t[key: string]: unknown;\n}\n\nexport type MemoryMetadata =\n\t| DocumentMetadata\n\t| FragmentMetadata\n\t| MessageMetadata\n\t| DescriptionMetadata\n\t| CustomMetadata\n\t| any;\n\n/**\n * Represents a stored memory/message\n */\nexport interface Memory {\n\t/** Optional unique identifier */\n\tid?: UUID;\n\n\t/** Associated user ID */\n\tentityId: UUID;\n\n\t/** Associated agent ID */\n\tagentId?: UUID;\n\n\t/** Optional creation timestamp */\n\tcreatedAt?: number;\n\n\t/** Memory content */\n\tcontent: Content;\n\n\t/** Optional embedding vector */\n\tembedding?: number[];\n\n\t/** Associated room ID */\n\troomId: UUID;\n\n\t/** Whether memory is unique */\n\tunique?: boolean;\n\n\t/** Embedding similarity score */\n\tsimilarity?: number;\n\n\t/** Metadata for the knowledge */\n\tmetadata?: MemoryMetadata;\n}\n\n/**\n * Example message for demonstration\n */\nexport interface MessageExample {\n\t/** Associated user */\n\tname: string;\n\n\t/** Message content */\n\tcontent: Content;\n}\n\n/**\n * Handler function type for processing messages\n */\nexport type Handler = (\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate?: State,\n\toptions?: { [key: string]: unknown },\n\tcallback?: HandlerCallback,\n\tresponses?: Memory[],\n) => Promise<unknown>;\n\n/**\n * Callback function type for handlers\n */\nexport type HandlerCallback = (\n\tresponse: Content,\n\tfiles?: any,\n) => Promise<Memory[]>;\n\n/**\n * Validator function type for actions/evaluators\n */\nexport type Validator = (\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate?: State,\n) => Promise<boolean>;\n\n/**\n * Represents an action the agent can perform\n */\nexport interface Action {\n\t/** Similar action descriptions */\n\tsimiles?: string[];\n\n\t/** Detailed description */\n\tdescription: string;\n\n\t/** Example usages */\n\texamples?: ActionExample[][];\n\n\t/** Handler function */\n\thandler: Handler;\n\n\t/** Action name */\n\tname: string;\n\n\t/** Validation function */\n\tvalidate: Validator;\n}\n\n/**\n * Example for evaluating agent behavior\n */\nexport interface EvaluationExample {\n\t/** Evaluation context */\n\tprompt: string;\n\n\t/** Example messages */\n\tmessages: Array<ActionExample>;\n\n\t/** Expected outcome */\n\toutcome: string;\n}\n\n/**\n * Evaluator for assessing agent responses\n */\nexport interface Evaluator {\n\t/** Whether to always run */\n\talwaysRun?: boolean;\n\n\t/** Detailed description */\n\tdescription: string;\n\n\t/** Similar evaluator descriptions */\n\tsimiles?: string[];\n\n\t/** Example evaluations */\n\texamples: EvaluationExample[];\n\n\t/** Handler function */\n\thandler: Handler;\n\n\t/** Evaluator name */\n\tname: string;\n\n\t/** Validation function */\n\tvalidate: Validator;\n}\n\nexport interface ProviderResult {\n\tvalues?: {\n\t\t[key: string]: any;\n\t};\n\tdata?: {\n\t\t[key: string]: any;\n\t};\n\ttext?: string;\n}\n\n/**\n * Provider for external data/services\n */\nexport interface Provider {\n\t/** Provider name */\n\tname: string;\n\n\t/** Description of the provider */\n\tdescription?: string;\n\n\t/** Whether the provider is dynamic */\n\tdynamic?: boolean;\n\n\t/** Position of the provider in the provider list, positive or negative */\n\tposition?: number;\n\n\t/**\n\t * Whether the provider is private\n\t *\n\t * Private providers are not displayed in the regular provider list, they have to be called explicitly\n\t */\n\tprivate?: boolean;\n\n\t/** Data retrieval function */\n\tget: (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t) => Promise<ProviderResult>;\n}\n\n/**\n * Represents a relationship between users\n */\nexport interface Relationship {\n\t/** Unique identifier */\n\tid: UUID;\n\n\t/** First user ID */\n\tsourceEntityId: UUID;\n\n\t/** Second user ID */\n\ttargetEntityId: UUID;\n\n\t/** Agent ID */\n\tagentId: UUID;\n\n\t/** Tags for filtering/categorizing relationships */\n\ttags: string[];\n\n\t/** Additional metadata about the relationship */\n\tmetadata: {\n\t\t[key: string]: any;\n\t};\n\n\t/** Optional creation timestamp */\n\tcreatedAt?: string;\n}\n\nexport interface Component {\n\tid: UUID;\n\tentityId: UUID;\n\tagentId: UUID;\n\troomId: UUID;\n\tworldId: UUID;\n\tsourceEntityId: UUID;\n\ttype: string;\n\tdata: {\n\t\t[key: string]: any;\n\t};\n}\n\n/**\n * Represents a user account\n */\nexport interface Entity {\n\t/** Unique identifier, optional on creation */\n\tid?: UUID;\n\n\t/** Names of the entity */\n\tnames: string[];\n\n\t/** Optional additional metadata */\n\tmetadata?: { [key: string]: any };\n\n\t/** Agent ID this account is related to, for agents should be themselves */\n\tagentId: UUID;\n\n\t/** Optional array of components */\n\tcomponents?: Component[];\n}\n\nexport type World = {\n\tid: UUID;\n\tname?: string;\n\tagentId: UUID;\n\tserverId: string;\n\tmetadata?: {\n\t\townership?: {\n\t\t\townerId: string;\n\t\t};\n\t\troles?: {\n\t\t\t[entityId: UUID]: Role;\n\t\t};\n\t\t[key: string]: unknown;\n\t};\n};\n\nexport type Room = {\n\tid: UUID;\n\tname?: string;\n\tagentId?: UUID;\n\tsource: string;\n\ttype: ChannelType;\n\tchannelId?: string;\n\tserverId?: string;\n\tworldId?: UUID;\n\tmetadata?: Record<string, unknown>;\n};\n\n/**\n * Room participant with account details\n */\nexport interface Participant {\n\t/** Unique identifier */\n\tid: UUID;\n\n\t/** Associated account */\n\tentity: Entity;\n}\n\n/**\n * Represents a media attachment\n */\nexport type Media = {\n\t/** Unique identifier */\n\tid: string;\n\n\t/** Media URL */\n\turl: string;\n\n\t/** Media title */\n\ttitle: string;\n\n\t/** Media source */\n\tsource: string;\n\n\t/** Media description */\n\tdescription: string;\n\n\t/** Text content */\n\ttext: string;\n\n\t/** Content type */\n\tcontentType?: string;\n};\n\nexport enum ChannelType {\n\tSELF = \"SELF\",\n\tDM = \"DM\",\n\tGROUP = \"GROUP\",\n\tVOICE_DM = \"VOICE_DM\",\n\tVOICE_GROUP = \"VOICE_GROUP\",\n\tFEED = \"FEED\",\n\tTHREAD = \"THREAD\",\n\tWORLD = \"WORLD\",\n\tAPI = \"API\",\n\tFORUM = \"FORUM\",\n}\n\n/**\n * Client instance\n */\nexport abstract class Service {\n\t/** Runtime instance */\n\tprotected runtime!: IAgentRuntime;\n\n\tconstructor(runtime?: IAgentRuntime) {\n\t\tif (runtime) {\n\t\t\tthis.runtime = runtime;\n\t\t}\n\t}\n\n\tabstract stop(): Promise<void>;\n\n\t/** Service type */\n\tstatic serviceType: string;\n\n\t/** Service name */\n\tabstract capabilityDescription: string;\n\n\t/** Service configuration */\n\tconfig?: { [key: string]: any };\n\n\t/** Start service connection */\n\tstatic async start(_runtime: IAgentRuntime): Promise<Service> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\n\t/** Stop service connection */\n\tstatic async stop(_runtime: IAgentRuntime): Promise<unknown> {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n}\n\nexport type Route = {\n\ttype: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"STATIC\";\n\tpath: string;\n\tfilePath?: string;\n\thandler?: (req: any, res: any, runtime: IAgentRuntime) => Promise<void>;\n};\n\n/**\n * Plugin for extending agent functionality\n */\nexport interface Plugin {\n\tname: string;\n\tdescription: string;\n\n\t// Initialize plugin with runtime services\n\tinit?: (\n\t\tconfig: Record<string, string>,\n\t\truntime: IAgentRuntime,\n\t) => Promise<void>;\n\n\t// Configuration\n\tconfig?: { [key: string]: any };\n\n\t// Core plugin components\n\tmemoryManagers?: IMemoryManager[];\n\n\tservices?: (typeof Service)[];\n\n\t// Entity component definitions\n\tcomponentTypes?: {\n\t\tname: string;\n\t\tschema: Record<string, unknown>;\n\t\tvalidator?: (data: any) => boolean;\n\t}[];\n\n\t// Optional plugin features\n\tactions?: Action[];\n\tproviders?: Provider[];\n\tevaluators?: Evaluator[];\n\tadapter?: IDatabaseAdapter;\n\tmodels?: {\n\t\t[key: string]: (...args: any[]) => Promise<any>;\n\t};\n\tevents?: {\n\t\t[K in keyof EventPayloadMap]?: EventHandler<K>[];\n\t} & {\n\t\t[key: string]: ((params: EventPayload) => Promise<any>)[];\n\t};\n\troutes?: Route[];\n\ttests?: TestSuite[];\n}\n\nexport interface ProjectAgent {\n\tcharacter: Character;\n\tinit?: (runtime: IAgentRuntime) => Promise<void>;\n\tplugins?: Plugin[];\n\ttests?: TestSuite | TestSuite[];\n}\n\nexport interface Project {\n\tagents: ProjectAgent[];\n}\n\nexport interface ModelConfiguration {\n\ttemperature?: number;\n\tmaxOutputTokens?: number;\n\tfrequency_penalty?: number;\n\tpresence_penalty?: number;\n\tmaxInputTokens?: number;\n}\n\nexport type TemplateType =\n\t| string\n\t| ((options: { state: State | { [key: string]: string } }) => string);\n\n/**\n * Configuration for an agent character\n */\nexport interface Character {\n\t/** Optional unique identifier */\n\tid?: UUID;\n\n\t/** Character name */\n\tname: string;\n\n\t/** Optional username */\n\tusername?: string;\n\n\t/** Optional system prompt */\n\tsystem?: string;\n\n\t/** Optional prompt templates */\n\ttemplates?: {\n\t\t[key: string]: TemplateType;\n\t};\n\n\t/** Character biography */\n\tbio: string | string[];\n\n\t/** Example messages */\n\tmessageExamples?: MessageExample[][];\n\n\t/** Example posts */\n\tpostExamples?: string[];\n\n\t/** Known topics */\n\ttopics?: string[];\n\n\t/** Character traits */\n\tadjectives?: string[];\n\n\t/** Optional knowledge base */\n\tknowledge?: (string | { path: string; shared?: boolean })[];\n\n\t/** Available plugins */\n\tplugins?: string[];\n\n\t/** Optional configuration */\n\tsettings?: {\n\t\t[key: string]: any | string | boolean | number;\n\t};\n\n\t/** Optional secrets */\n\tsecrets?: {\n\t\t[key: string]: string | boolean | number;\n\t};\n\n\t/** Writing style guides */\n\tstyle?: {\n\t\tall?: string[];\n\t\tchat?: string[];\n\t\tpost?: string[];\n\t};\n}\n\nexport interface Agent extends Character {\n\tenabled: boolean;\n\tcreatedAt: number;\n\tupdatedAt: number;\n}\n\n/**\n * Interface for database operations\n */\nexport interface IDatabaseAdapter {\n\t/** Database instance */\n\tdb: any;\n\n\t/** Initialize database connection */\n\tinit(): Promise<void>;\n\n\t/** Close database connection */\n\tclose(): Promise<void>;\n\n\tgetAgent(agentId: UUID): Promise<Agent | null>;\n\n\t/** Get all agents */\n\tgetAgents(): Promise<Agent[]>;\n\n\tcreateAgent(agent: Partial<Agent>): Promise<boolean>;\n\n\tupdateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean>;\n\n\tdeleteAgent(agentId: UUID): Promise<boolean>;\n\n\tensureAgentExists(agent: Partial<Agent>): Promise<void>;\n\n\tensureEmbeddingDimension(dimension: number): Promise<void>;\n\n\t/** Get entity by ID */\n\tgetEntityById(entityId: UUID): Promise<Entity | null>;\n\n\t/** Get entities for room */\n\tgetEntitiesForRoom(\n\t\troomId: UUID,\n\t\tincludeComponents?: boolean,\n\t): Promise<Entity[]>;\n\n\t/** Create new entity */\n\tcreateEntity(entity: Entity): Promise<boolean>;\n\n\t/** Update entity */\n\tupdateEntity(entity: Entity): Promise<void>;\n\n\t/** Get component by ID */\n\tgetComponent(\n\t\tentityId: UUID,\n\t\ttype: string,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component | null>;\n\n\t/** Get all components for an entity */\n\tgetComponents(\n\t\tentityId: UUID,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component[]>;\n\n\t/** Create component */\n\tcreateComponent(component: Component): Promise<boolean>;\n\n\t/** Update component */\n\tupdateComponent(component: Component): Promise<void>;\n\n\t/** Delete component */\n\tdeleteComponent(componentId: UUID): Promise<void>;\n\n\t/** Get memories matching criteria */\n\tgetMemories(params: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t\tstart?: number;\n\t\tend?: number;\n\t}): Promise<Memory[]>;\n\n\tgetMemoryById(id: UUID): Promise<Memory | null>;\n\n\tgetMemoriesByIds(ids: UUID[], tableName?: string): Promise<Memory[]>;\n\n\tgetMemoriesByRoomIds(params: {\n\t\ttableName: string;\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tgetCachedEmbeddings(params: {\n\t\tquery_table_name: string;\n\t\tquery_threshold: number;\n\t\tquery_input: string;\n\t\tquery_field_name: string;\n\t\tquery_field_sub_name: string;\n\t\tquery_match_count: number;\n\t}): Promise<{ embedding: number[]; levenshtein_score: number }[]>;\n\n\tlog(params: {\n\t\tbody: { [key: string]: unknown };\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\ttype: string;\n\t}): Promise<void>;\n\n\tsearchMemories(params: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId?: UUID;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t}): Promise<Memory[]>;\n\n\tcreateMemory(\n\t\tmemory: Memory,\n\t\ttableName: string,\n\t\tunique?: boolean,\n\t): Promise<UUID>;\n\n\tremoveMemory(memoryId: UUID, tableName: string): Promise<void>;\n\n\tremoveAllMemories(roomId: UUID, tableName: string): Promise<void>;\n\n\tcountMemories(\n\t\troomId: UUID,\n\t\tunique?: boolean,\n\t\ttableName?: string,\n\t): Promise<number>;\n\n\tcreateWorld(world: World): Promise<UUID>;\n\n\tgetWorld(id: UUID): Promise<World | null>;\n\n\tgetAllWorlds(): Promise<World[]>;\n\n\tupdateWorld(world: World): Promise<void>;\n\n\tgetRoom(roomId: UUID): Promise<Room | null>;\n\n\tcreateRoom({\n\t\tid,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room): Promise<UUID>;\n\n\tdeleteRoom(roomId: UUID): Promise<void>;\n\n\tupdateRoom(room: Room): Promise<void>;\n\n\tgetRoomsForParticipant(entityId: UUID): Promise<UUID[]>;\n\n\tgetRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;\n\n\tgetRooms(worldId: UUID): Promise<Room[]>;\n\n\taddParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\tremoveParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\tgetParticipantsForEntity(entityId: UUID): Promise<Participant[]>;\n\n\tgetParticipantsForRoom(roomId: UUID): Promise<UUID[]>;\n\n\tgetParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t): Promise<\"FOLLOWED\" | \"MUTED\" | null>;\n\n\tsetParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t\tstate: \"FOLLOWED\" | \"MUTED\" | null,\n\t): Promise<void>;\n\n\t/**\n\t * Creates a new relationship between two entities.\n\t * @param params Object containing the relationship details\n\t * @returns Promise resolving to boolean indicating success\n\t */\n\tcreateRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: { [key: string]: any };\n\t}): Promise<boolean>;\n\n\t/**\n\t * Updates an existing relationship between two entities.\n\t * @param relationship The relationship object with updated data\n\t * @returns Promise resolving to void\n\t */\n\tupdateRelationship(relationship: Relationship): Promise<void>;\n\n\t/**\n\t * Retrieves a relationship between two entities if it exists.\n\t * @param params Object containing the entity IDs and agent ID\n\t * @returns Promise resolving to the Relationship object or null if not found\n\t */\n\tgetRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t}): Promise<Relationship | null>;\n\n\t/**\n\t * Retrieves all relationships for a specific entity.\n\t * @param params Object containing the user ID, agent ID and optional tags to filter by\n\t * @returns Promise resolving to an array of Relationship objects\n\t */\n\tgetRelationships(params: {\n\t\tentityId: UUID;\n\t\ttags?: string[];\n\t}): Promise<Relationship[]>;\n\n\tensureEmbeddingDimension(dimension: number): Promise<void>;\n\n\tgetCache<T>(key: string): Promise<T | undefined>;\n\tsetCache<T>(key: string, value: T): Promise<boolean>;\n\tdeleteCache(key: string): Promise<boolean>;\n\n\t// Only task instance methods - definitions are in-memory\n\tcreateTask(task: Task): Promise<UUID>;\n\tgetTasks(params: { roomId?: UUID; tags?: string[] }): Promise<Task[]>;\n\tgetTask(id: UUID): Promise<Task | null>;\n\tgetTasksByName(name: string): Promise<Task[]>;\n\tupdateTask(id: UUID, task: Partial<Task>): Promise<void>;\n\tdeleteTask(id: UUID): Promise<void>;\n}\n\nexport interface IMemoryManager {\n\truntime: IAgentRuntime;\n\ttableName: string;\n\n\taddEmbeddingToMemory(memory: Memory): Promise<Memory>;\n\n\tgetMemories(opts: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\tstart?: number;\n\t\tend?: number;\n\t}): Promise<Memory[]>;\n\n\tsearchMemories(params: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId?: UUID;\n\t\tunique?: boolean;\n\t\tmetadata?: MemoryMetadata;\n\t}): Promise<Memory[]>;\n\n\tgetCachedEmbeddings(\n\t\tcontent: string,\n\t): Promise<{ embedding: number[]; levenshtein_score: number }[]>;\n\n\tgetMemoryById(id: UUID): Promise<Memory | null>;\n\tgetMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tcreateMemory(memory: Memory, unique?: boolean): Promise<UUID>;\n\n\tremoveMemory(memoryId: UUID): Promise<void>;\n\n\tremoveAllMemories(roomId: UUID): Promise<void>;\n\n\tcountMemories(roomId: UUID, unique?: boolean): Promise<number>;\n}\n\nexport type CacheOptions = {\n\texpires?: number;\n};\n\nexport interface IAgentRuntime extends IDatabaseAdapter {\n\t// Properties\n\tagentId: UUID;\n\tdatabaseAdapter: IDatabaseAdapter;\n\tcharacter: Character;\n\tproviders: Provider[];\n\tactions: Action[];\n\tevaluators: Evaluator[];\n\tplugins: Plugin[];\n\tservices: Map<ServiceType, Service>;\n\tevents: Map<string, ((params: any) => Promise<void>)[]>;\n\tfetch?: typeof fetch | null;\n\troutes: Route[];\n\t\n\t// Methods\n\tregisterPlugin(plugin: Plugin): Promise<void>;\n\n\tinitialize(): Promise<void>;\n\n\tgetKnowledge(message: Memory): Promise<KnowledgeItem[]>;\n\taddKnowledge(\n\t\titem: KnowledgeItem,\n\t\toptions: {\n\t\t\ttargetTokens: number;\n\t\t\toverlap: number;\n\t\t\tmodelContextSize: number;\n\t\t},\n\t): Promise<void>;\n\n\tgetMemoryManager(tableName: string): IMemoryManager | null;\n\n\tgetService<T extends Service>(service: ServiceType | string): T | null;\n\n\tgetAllServices(): Map<ServiceType, Service>;\n\n\tregisterService(service: typeof Service): void;\n\n\t// Keep these methods for backward compatibility\n\tregisterDatabaseAdapter(adapter: IDatabaseAdapter): void;\n\n\tsetSetting(\n\t\tkey: string,\n\t\tvalue: string | boolean | null | any,\n\t\tsecret: boolean,\n\t): void;\n\n\tgetSetting(key: string): string | boolean | null | any;\n\n\tgetConversationLength(): number;\n\n\tprocessActions(\n\t\tmessage: Memory,\n\t\tresponses: Memory[],\n\t\tstate?: State,\n\t\tcallback?: HandlerCallback,\n\t): Promise<void>;\n\n\tevaluate(\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\tdidRespond?: boolean,\n\t\tcallback?: HandlerCallback,\n\t\tresponses?: Memory[],\n\t): Promise<Evaluator[] | null>;\n\n\tregisterProvider(provider: Provider): void;\n\n\tregisterAction(action: Action): void;\n\n\tregisterEvaluator(evaluator: Evaluator): void;\n\n\tensureConnection({\n\t\tentityId,\n\t\troomId,\n\t\tuserName,\n\t\tname,\n\t\tsource,\n\t\tchannelId,\n\t\tserverId,\n\t\ttype,\n\t\tworldId,\n\t}: {\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\tuserName?: string;\n\t\tname?: string;\n\t\tsource?: string;\n\t\tchannelId?: string;\n\t\tserverId?: string;\n\t\ttype: ChannelType;\n\t\tworldId?: UUID;\n\t}): Promise<void>;\n\n\tensureParticipantInRoom(entityId: UUID, roomId: UUID): Promise<void>;\n\n\tensureWorldExists(world: World): Promise<void>;\n\n\tensureRoomExists(room: Room): Promise<void>;\n\n\tcomposeState(\n\t\tmessage: Memory,\n\t\tfilterList?: string[],\n\t\tincludeList?: string[],\n\t): Promise<State>;\n\n\t/**\n\t * Use a model with strongly typed parameters and return values based on model type\n\t * @template T - The model type to use\n\t * @template R - The expected return type, defaults to the type defined in ModelResultMap[T]\n\t * @param {T} modelType - The type of model to use\n\t * @param {ModelParamsMap[T] | any} params - The parameters for the model, typed based on model type\n\t * @returns {Promise<R>} - The model result, typed based on the provided generic type parameter\n\t */\n\tuseModel<T extends ModelType, R = ModelResultMap[T]>(\n\t\tmodelType: T,\n\t\tparams: Omit<ModelParamsMap[T], \"runtime\"> | any,\n\t): Promise<R>;\n\n\tregisterModel(\n\t\tmodelType: ModelType | string,\n\t\thandler: (params: any) => Promise<any>,\n\t): void;\n\t\n\tgetModel(\n\t\tmodelType: ModelType | string,\n\t): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined;\n\n\tregisterEvent(event: string, handler: (params: any) => Promise<void>): void;\n\t\n\tgetEvent(event: string): ((params: any) => Promise<void>)[] | undefined;\n\t\n\temitEvent(event: string | string[], params: any): Promise<void>;\n\n\t// In-memory task definition methods\n\tregisterTaskWorker(taskHandler: TaskWorker): void;\n\tgetTaskWorker(name: string): TaskWorker | undefined;\n\n\tstop(): Promise<void>;\n}\n\nexport type KnowledgeItem = {\n\tid: UUID;\n\tcontent: Content;\n};\n\nexport enum KnowledgeScope {\n\tSHARED = \"shared\",\n\tPRIVATE = \"private\",\n}\n\nexport enum CacheKeyPrefix {\n\tKNOWLEDGE = \"knowledge\",\n}\n\nexport interface DirectoryItem {\n\tdirectory: string;\n\tshared?: boolean;\n}\n\nexport interface ChunkRow {\n\tid: string;\n\t// Add other properties if needed\n}\n\nexport type GenerateTextParams = {\n\truntime: IAgentRuntime;\n\tprompt: string;\n\tmodelType: ModelType;\n\tmaxTokens?: number;\n\ttemperature?: number;\n\tfrequencyPenalty?: number;\n\tpresencePenalty?: number;\n\tstopSequences?: string[];\n};\n\nexport interface TokenizeTextParams {\n\tprompt: string;\n\tmodelType: ModelType;\n}\n\nexport interface DetokenizeTextParams {\n\ttokens: number[];\n\tmodelType: ModelType;\n}\n\nexport interface IVideoService extends Service {\n\tisVideoUrl(url: string): boolean;\n\tfetchVideoInfo(url: string): Promise<Media>;\n\tdownloadVideo(videoInfo: Media): Promise<string>;\n\tprocessVideo(url: string, runtime: IAgentRuntime): Promise<Media>;\n}\n\nexport interface IBrowserService extends Service {\n\tgetPageContent(\n\t\turl: string,\n\t\truntime: IAgentRuntime,\n\t): Promise<{ title: string; description: string; bodyContent: string }>;\n}\n\nexport interface IPdfService extends Service {\n\tconvertPdfToText(pdfBuffer: Buffer): Promise<string>;\n}\n\nexport interface IFileService extends Service {\n\tuploadFile(\n\t\timagePath: string,\n\t\tsubDirectory: string,\n\t\tuseSignedUrl: boolean,\n\t\texpiresIn: number,\n\t): Promise<{\n\t\tsuccess: boolean;\n\t\turl?: string;\n\t\terror?: string;\n\t}>;\n\tgenerateSignedUrl(fileName: string, expiresIn: number): Promise<string>;\n}\n\nexport interface ITeeLogService extends Service {\n\tlog(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean>;\n\n\tgenerateAttestation<T>(\n\t\treportData: string,\n\t\thashAlgorithm?: T | any,\n\t): Promise<string>;\n\tgetAllAgents(): Promise<TeeAgent[]>;\n\tgetAgent(agentId: string): Promise<TeeAgent | null>;\n\tgetLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n}\n\nexport interface TestCase {\n\tname: string;\n\tfn: (runtime: IAgentRuntime) => Promise<void> | void;\n}\n\nexport interface TestSuite {\n\tname: string;\n\ttests: TestCase[];\n}\n\n// Represents a log entry in the TeeLog table, containing details about agent activities.\nexport interface TeeLog {\n\tid: string;\n\tagentId: string;\n\troomId: string;\n\tentityId: string;\n\ttype: string;\n\tcontent: string;\n\ttimestamp: number;\n\tsignature: string;\n}\n\nexport interface TeeLogQuery {\n\tagentId?: string;\n\troomId?: string;\n\tentityId?: string;\n\ttype?: string;\n\tcontainsContent?: string;\n\tstartTimestamp?: number;\n\tendTimestamp?: number;\n}\n\n// Represents an agent in the TeeAgent table, containing details about the agent.\nexport interface TeeAgent {\n\tid: string; // Primary key\n\t// Allow duplicate agentId.\n\t// This is to support the case where the same agentId is registered multiple times.\n\t// Each time the agent restarts, we will generate a new keypair and attestation.\n\tagentId: string;\n\tagentName: string;\n\tcreatedAt: number;\n\tpublicKey: string;\n\tattestation: string;\n}\n\nexport interface TeePageQuery<Result = any> {\n\tpage: number;\n\tpageSize: number;\n\ttotal?: number;\n\tdata?: Result;\n}\n\nexport abstract class TeeLogDAO<DB = any> {\n\tdb: DB;\n\n\tabstract initialize(): Promise<void>;\n\n\tabstract addLog(log: TeeLog): Promise<boolean>;\n\n\tabstract getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n\n\tabstract addAgent(agent: TeeAgent): Promise<boolean>;\n\n\tabstract getAgent(agentId: string): Promise<TeeAgent>;\n\n\tabstract getAllAgents(): Promise<TeeAgent[]>;\n}\n\nexport enum TEEMode {\n\tOFF = \"OFF\",\n\tLOCAL = \"LOCAL\", // For local development with simulator\n\tDOCKER = \"DOCKER\", // For docker development with simulator\n\tPRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n\tquote: string;\n\ttimestamp: number;\n}\n\nexport interface DeriveKeyAttestationData {\n\tagentId: string;\n\tpublicKey: string;\n\tsubject?: string;\n}\n\nexport interface RemoteAttestationMessage {\n\tagentId: string;\n\ttimestamp: number;\n\tmessage: {\n\t\tentityId: string;\n\t\troomId: string;\n\t\tcontent: string;\n\t};\n}\n\nexport interface SgxAttestation {\n\tquote: string;\n\ttimestamp: number;\n}\n\nexport enum TeeType {\n\tSGX_GRAMINE = \"sgx_gramine\",\n\tTDX_DSTACK = \"tdx_dstack\",\n}\n\nexport interface TeeVendorConfig {\n\t// Add vendor-specific configuration options here\n\t[key: string]: unknown;\n}\n\nexport interface TeePluginConfig {\n\tvendor?: string;\n\tvendorConfig?: TeeVendorConfig;\n}\n\nexport interface TaskWorker {\n\tname: string;\n\texecute: (\n\t\truntime: IAgentRuntime,\n\t\toptions: { [key: string]: unknown },\n\t\ttask: Task,\n\t) => Promise<void>;\n\tvalidate?: (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t) => Promise<boolean>;\n}\n\nexport interface Task {\n\tid?: UUID;\n\tname: string;\n\tupdatedAt?: number;\n\tmetadata?: {\n\t\tupdateInterval?: number;\n\t\toptions?: {\n\t\t\tname: string;\n\t\t\tdescription: string;\n\t\t}[];\n\t\t[key: string]: unknown;\n\t};\n\tdescription: string;\n\troomId?: UUID;\n\tworldId?: UUID;\n\ttags: string[];\n}\n\nexport enum Role {\n\tOWNER = \"OWNER\",\n\tADMIN = \"ADMIN\",\n\tNONE = \"NONE\",\n}\n\nexport interface Setting {\n\tname: string;\n\tdescription: string; // Used in chat context when discussing the setting\n\tusageDescription: string; // Used during settings to guide users\n\tvalue: string | boolean | null;\n\trequired: boolean;\n\tpublic?: boolean; // If true, shown in public channels\n\tsecret?: boolean; // If true, value is masked and only shown during settings\n\tvalidation?: (value: any) => boolean;\n\tdependsOn?: string[];\n\tonSetAction?: (value: any) => string;\n\tvisibleIf?: (settings: { [key: string]: Setting }) => boolean;\n}\n\nexport interface WorldSettings {\n\t[key: string]: Setting;\n}\n\nexport interface OnboardingConfig {\n\tsettings: {\n\t\t[key: string]: Omit<Setting, \"value\">;\n\t};\n}\n\n/**\n * Base parameters common to all model types\n */\nexport interface BaseModelParams {\n\t/** The agent runtime for accessing services and utilities */\n\truntime: IAgentRuntime;\n}\n\n/**\n * Parameters for text generation models\n */\nexport interface TextGenerationParams extends BaseModelParams {\n\t/** The prompt to generate text from */\n\tprompt: string;\n\t/** Model temperature (0.0 to 1.0, lower is more deterministic) */\n\ttemperature?: number;\n\t/** Maximum number of tokens to generate */\n\tmaxTokens?: number;\n\t/** Sequences that should stop generation when encountered */\n\tstopSequences?: string[];\n\t/** Frequency penalty to apply */\n\tfrequencyPenalty?: number;\n\t/** Presence penalty to apply */\n\tpresencePenalty?: number;\n}\n\n/**\n * Parameters for text embedding models\n */\nexport interface TextEmbeddingParams extends BaseModelParams {\n\t/** The text to create embeddings for */\n\ttext: string;\n}\n\n/**\n * Parameters for text tokenization models\n */\nexport interface TokenizeTextParams extends BaseModelParams {\n\t/** The text to tokenize */\n\tprompt: string;\n\t/** The model type to use for tokenization */\n\tmodelType: ModelType;\n}\n\n/**\n * Parameters for text detokenization models\n */\nexport interface DetokenizeTextParams extends BaseModelParams {\n\t/** The tokens to convert back to text */\n\ttokens: number[];\n\t/** The model type to use for detokenization */\n\tmodelType: ModelType;\n}\n\n/**\n * Parameters for image generation models\n */\nexport interface ImageGenerationParams extends BaseModelParams {\n\t/** The prompt describing the image to generate */\n\tprompt: string;\n\t/** The dimensions of the image to generate */\n\tsize?: string;\n\t/** Number of images to generate */\n\tcount?: number;\n}\n\n/**\n * Parameters for image description models\n */\nexport interface ImageDescriptionParams extends BaseModelParams {\n\t/** The URL or path of the image to describe */\n\timageUrl: string;\n\t/** Optional prompt to guide the description */\n\tprompt?: string;\n}\n\n/**\n * Parameters for transcription models\n */\nexport interface TranscriptionParams extends BaseModelParams {\n\t/** The URL or path of the audio file to transcribe */\n\taudioUrl: string;\n\t/** Optional prompt to guide transcription */\n\tprompt?: string;\n}\n\n/**\n * Parameters for text-to-speech models\n */\nexport interface TextToSpeechParams extends BaseModelParams {\n\t/** The text to convert to speech */\n\ttext: string;\n\t/** The voice to use */\n\tvoice?: string;\n\t/** The speaking speed */\n\tspeed?: number;\n}\n\n/**\n * Parameters for audio processing models\n */\nexport interface AudioProcessingParams extends BaseModelParams {\n\t/** The URL or path of the audio file to process */\n\taudioUrl: string;\n\t/** The type of audio processing to perform */\n\tprocessingType: string;\n}\n\n/**\n * Parameters for video processing models\n */\nexport interface VideoProcessingParams extends BaseModelParams {\n\t/** The URL or path of the video file to process */\n\tvideoUrl: string;\n\t/** The type of video processing to perform */\n\tprocessingType: string;\n}\n\n/**\n * Optional JSON schema for validating generated objects\n */\nexport type JSONSchema = {\n\ttype: string;\n\tproperties?: Record<string, any>;\n\trequired?: string[];\n\titems?: JSONSchema;\n\t[key: string]: any;\n};\n\n/**\n * Parameters for object generation models\n * @template T - The expected return type, inferred from schema if provided\n */\nexport interface ObjectGenerationParams<T = any> extends BaseModelParams {\n\t/** The prompt describing the object to generate */\n\tprompt: string;\n\t/** Optional JSON schema for validation */\n\tschema?: JSONSchema;\n\t/** Type of object to generate */\n\toutput?: \"object\" | \"array\" | \"enum\";\n\t/** For enum type, the allowed values */\n\tenumValues?: string[];\n\t/** Model type to use */\n\tmodelType?: ModelType;\n\t/** Model temperature (0.0 to 1.0) */\n\ttemperature?: number;\n\t/** Sequences that should stop generation */\n\tstopSequences?: string[];\n}\n\n/**\n * Map of model types to their parameter types\n */\nexport interface ModelParamsMap {\n\t[ModelTypes.TEXT_SMALL]: TextGenerationParams;\n\t[ModelTypes.TEXT_LARGE]: TextGenerationParams;\n\t[ModelTypes.TEXT_EMBEDDING]: TextEmbeddingParams | string | null;\n\t[ModelTypes.TEXT_TOKENIZER_ENCODE]: TokenizeTextParams;\n\t[ModelTypes.TEXT_TOKENIZER_DECODE]: DetokenizeTextParams;\n\t[ModelTypes.TEXT_REASONING_SMALL]: TextGenerationParams;\n\t[ModelTypes.TEXT_REASONING_LARGE]: TextGenerationParams;\n\t[ModelTypes.IMAGE]: ImageGenerationParams;\n\t[ModelTypes.IMAGE_DESCRIPTION]: ImageDescriptionParams | string;\n\t[ModelTypes.TRANSCRIPTION]: TranscriptionParams | Buffer | string;\n\t[ModelTypes.TEXT_TO_SPEECH]: TextToSpeechParams | string;\n\t[ModelTypes.AUDIO]: AudioProcessingParams;\n\t[ModelTypes.VIDEO]: VideoProcessingParams;\n\t[ModelTypes.OBJECT_SMALL]: ObjectGenerationParams<any>;\n\t[ModelTypes.OBJECT_LARGE]: ObjectGenerationParams<any>;\n\t// Allow string index for custom model types\n\t[key: string]: BaseModelParams | any;\n}\n\n/**\n * Map of model types to their return value types\n */\nexport interface ModelResultMap {\n\t[ModelTypes.TEXT_SMALL]: string;\n\t[ModelTypes.TEXT_LARGE]: string;\n\t[ModelTypes.TEXT_EMBEDDING]: number[];\n\t[ModelTypes.TEXT_TOKENIZER_ENCODE]: number[];\n\t[ModelTypes.TEXT_TOKENIZER_DECODE]: string;\n\t[ModelTypes.TEXT_REASONING_SMALL]: string;\n\t[ModelTypes.TEXT_REASONING_LARGE]: string;\n\t[ModelTypes.IMAGE]: { url: string }[];\n\t[ModelTypes.IMAGE_DESCRIPTION]: { title: string; description: string };\n\t[ModelTypes.TRANSCRIPTION]: string;\n\t[ModelTypes.TEXT_TO_SPEECH]: Readable | Buffer;\n\t[ModelTypes.AUDIO]: any; // Specific return type depends on processing type\n\t[ModelTypes.VIDEO]: any; // Specific return type depends on processing type\n\t[ModelTypes.OBJECT_SMALL]: any;\n\t[ModelTypes.OBJECT_LARGE]: any;\n\t// Allow string index for custom model types\n\t[key: string]: any;\n}\n\n/**\n * Standard event types across all platforms\n */\nexport enum EventTypes {\n\t// World events\n\tWORLD_JOINED = \"WORLD_JOINED\",\n\tWORLD_CONNECTED = \"WORLD_CONNECTED\",\n\tWORLD_LEFT = \"WORLD_LEFT\",\n\t\n\t// Entity events\n\tENTITY_JOINED = \"ENTITY_JOINED\",\n\tENTITY_LEFT = \"ENTITY_LEFT\",\n\tENTITY_UPDATED = \"ENTITY_UPDATED\",\n\t\n\t// Room events\n\tROOM_JOINED = \"ROOM_JOINED\",\n\tROOM_LEFT = \"ROOM_LEFT\",\n\t\n\t// Message events\n\tMESSAGE_RECEIVED = \"MESSAGE_RECEIVED\",\n\tMESSAGE_SENT = \"MESSAGE_SENT\",\n\n\t// Voice events\n\tVOICE_MESSAGE_RECEIVED = \"VOICE_MESSAGE_RECEIVED\",\n\tVOICE_MESSAGE_SENT = \"VOICE_MESSAGE_SENT\",\n\t\n\t// Interaction events\n\tREACTION_RECEIVED = \"REACTION_RECEIVED\",\n\tPOST_GENERATED = \"POST_GENERATED\",\n\tINTERACTION_RECEIVED = \"INTERACTION_RECEIVED\",\n\n\t// Run events\n\tRUN_STARTED = \"RUN_STARTED\",\n\tRUN_ENDED = \"RUN_ENDED\",\n\tRUN_TIMEOUT = \"RUN_TIMEOUT\",\n\n\t// Action events\n\tACTION_STARTED = \"ACTION_STARTED\",\n\tACTION_COMPLETED = \"ACTION_COMPLETED\",\n\n\t// Evaluator events\n\tEVALUATOR_STARTED = \"EVALUATOR_STARTED\",\n\tEVALUATOR_COMPLETED = \"EVALUATOR_COMPLETED\"\n}\n\n/**\n * Platform-specific event type prefix\n */\nexport enum PlatformPrefix {\n\tDISCORD = \"DISCORD\",\n\tTELEGRAM = \"TELEGRAM\",\n\tTWITTER = \"TWITTER\",\n}\n\n/**\n * Base payload interface for all events\n */\nexport interface EventPayload {\n\truntime: IAgentRuntime;\n\tsource: string;\n}\n\n/**\n * Payload for world-related events\n */\nexport interface WorldPayload extends EventPayload {\n\tworld: World;\n\trooms: Room[];\n\tentities: Entity[];\n}\n\n/**\n * Payload for entity-related events\n */\nexport interface EntityPayload extends EventPayload {\n\tentityId: UUID;\n\tworldId?: UUID;\n\troomId?: UUID;\n\tmetadata?: {\n\t\torginalId: string;\n\t\tusername: string;\n\t\tdisplayName?: string;\n\t\t[key: string]: any;\n\t};\n}\n\n/**\n * Payload for reaction-related events\n */\nexport interface MessagePayload extends EventPayload {\n\tmessage: Memory;\n\tcallback?: HandlerCallback;\n}\n\n/**\n * Run event payload type\n */\nexport interface RunEventPayload extends EventPayload {\n\trunId: UUID;\n\tmessageId: UUID;\n\troomId: UUID;\n\tentityId: UUID;\n\tstartTime: number;\n\tstatus: \"started\" | \"completed\" | \"timeout\";\n\tendTime?: number;\n\tduration?: number;\n\terror?: string;\n}\n\n/**\n * Action event payload type\n */\nexport interface ActionEventPayload extends EventPayload {\n\tactionId: UUID;\n\tactionName: string;\n\tstartTime?: number;\n\tcompleted?: boolean;\n\terror?: Error;\n}\n\n/**\n * Evaluator event payload type\n */\nexport interface EvaluatorEventPayload extends EventPayload {\n\tevaluatorId: UUID;\n\tevaluatorName: string;\n\tstartTime?: number;\n\tcompleted?: boolean;\n\terror?: Error;\n}\n\n/**\n * Maps event types to their corresponding payload types\n */\nexport interface EventPayloadMap {\n\t[EventTypes.WORLD_JOINED]: WorldPayload;\n\t[EventTypes.WORLD_CONNECTED]: WorldPayload;\n\t[EventTypes.WORLD_LEFT]: WorldPayload;\n\t[EventTypes.ENTITY_JOINED]: EntityPayload;\n\t[EventTypes.ENTITY_LEFT]: EntityPayload;\n\t[EventTypes.ENTITY_UPDATED]: EntityPayload;\n\t[EventTypes.MESSAGE_RECEIVED]: MessagePayload;\n\t[EventTypes.MESSAGE_SENT]: MessagePayload;\n\t[EventTypes.REACTION_RECEIVED]: MessagePayload;\n\t[EventTypes.POST_GENERATED]: MessagePayload;\n\t[EventTypes.INTERACTION_RECEIVED]: MessagePayload;\n\t[EventTypes.RUN_STARTED]: RunEventPayload;\n\t[EventTypes.RUN_ENDED]: RunEventPayload;\n\t[EventTypes.RUN_TIMEOUT]: RunEventPayload;\n\t[EventTypes.ACTION_STARTED]: ActionEventPayload;\n\t[EventTypes.ACTION_COMPLETED]: ActionEventPayload;\n\t[EventTypes.EVALUATOR_STARTED]: EvaluatorEventPayload;\n\t[EventTypes.EVALUATOR_COMPLETED]: EvaluatorEventPayload;\n}\n\n/**\n * Event handler function type\n */\nexport type EventHandler<T extends keyof EventPayloadMap> = (\n\tpayload: EventPayloadMap[T]\n) => Promise<void>;\n\n/**\n * Update the Plugin interface with typed events\n */\n","import { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport type { Action, ActionExample } from \"./types\";\n\n/**\n * Composes a set of example conversations based on provided actions and a specified count.\n * It randomly selects examples from the provided actions and formats them with generated names.\n * @param actionsData - An array of `Action` objects from which to draw examples.\n * @param count - The number of examples to generate.\n * @returns A string containing formatted examples of conversations.\n */\n/**\n * Compose a specified number of random action examples from the given actionsData.\n *\n * @param {Action[]} actionsData - The list of actions to generate examples from.\n * @param {number} count - The number of examples to compose.\n * @returns {string} The formatted action examples.\n */\nexport const composeActionExamples = (actionsData: Action[], count: number) => {\n\tconst data: ActionExample[][][] = actionsData.map((action: Action) => [\n\t\t...action.examples,\n\t]);\n\n\tconst actionExamples: ActionExample[][] = [];\n\tlet length = data.length;\n\tfor (let i = 0; i < count && length; i++) {\n\t\tconst actionId = i % length;\n\t\tconst examples = data[actionId];\n\t\tif (examples.length) {\n\t\t\tconst rand = ~~(Math.random() * examples.length);\n\t\t\tactionExamples[i] = examples.splice(rand, 1)[0];\n\t\t} else {\n\t\t\ti--;\n\t\t}\n\n\t\tif (examples.length === 0) {\n\t\t\tdata.splice(actionId, 1);\n\t\t\tlength--;\n\t\t}\n\t}\n\n\tconst formattedExamples = actionExamples.map((example) => {\n\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t\t);\n\n\t\treturn `\\n${example\n\t\t\t.map((message) => {\n\t\t\t\tlet messageString = `${message.name}: ${message.content.text}${message.content.actions ? ` (actions: ${message.content.actions.join(\", \")})` : \"\"}`;\n\t\t\t\tfor (let i = 0; i < exampleNames.length; i++) {\n\t\t\t\t\tmessageString = messageString.replaceAll(\n\t\t\t\t\t\t`{{name${i + 1}}}`,\n\t\t\t\t\t\texampleNames[i],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn messageString;\n\t\t\t})\n\t\t\t.join(\"\\n\")}`;\n\t});\n\n\treturn formattedExamples.join(\"\\n\");\n};\n\n/**\n * Formats the names of the provided actions into a comma-separated string.\n * @param actions - An array of `Action` objects from which to extract names.\n * @returns A comma-separated string of action names.\n */\nexport function formatActionNames(actions: Action[]) {\n\treturn actions\n\t\t.sort(() => 0.5 - Math.random())\n\t\t.map((action: Action) => `${action.name}`)\n\t\t.join(\", \");\n}\n\n/**\n * Formats the provided actions into a detailed string listing each action's name and description, separated by commas and newlines.\n * @param actions - An array of `Action` objects to format.\n * @returns A detailed string of actions, including names and descriptions.\n */\nexport function formatActions(actions: Action[]) {\n\treturn actions\n\t\t.sort(() => 0.5 - Math.random())\n\t\t.map((action: Action) => `${action.name}: ${action.description}`)\n\t\t.join(\",\\n\");\n}\n","import type {\n\tAgent,\n\tComponent,\n\tEntity,\n\tIDatabaseAdapter,\n\tMemory,\n\tParticipant,\n\tRelationship,\n\tRoom,\n\tTask,\n\tUUID,\n\tWorld,\n} from \"./types\";\n\n/**\n * An abstract class representing a database adapter for managing various entities\n * like entities, memories, entities, goals, and rooms.\n */\n/**\n * Database adapter class to be extended by individual database adapters.\n *\n * @template DB - The type of the database instance.\n * @abstract\n * @implements {IDatabaseAdapter}\n */\nexport abstract class DatabaseAdapter<DB = unknown>\n\timplements IDatabaseAdapter\n{\n\t/**\n\t * The database instance.\n\t */\n\tdb: DB;\n\n\t/**\n\t * Initialize the database adapter.\n\t * @returns A Promise that resolves when initialization is complete.\n\t */\n\tabstract init(): Promise<void>;\n\n\t/**\n\t * Optional close method for the database adapter.\n\t * @returns A Promise that resolves when closing is complete.\n\t */\n\tabstract close(): Promise<void>;\n\n\t/**\n\t * Retrieves an account by its ID.\n\t * @param entityId The UUID of the user account to retrieve.\n\t * @returns A Promise that resolves to the Entity object or null if not found.\n\t */\n\tabstract getEntityById(entityId: UUID): Promise<Entity | null>;\n\n\tabstract getEntitiesForRoom(\n\t\troomId: UUID,\n\t\tincludeComponents?: boolean,\n\t): Promise<Entity[]>;\n\n\t/**\n\t * Creates a new entity in the database.\n\t * @param entity The entity object to create.\n\t * @returns A Promise that resolves when the account creation is complete.\n\t */\n\tabstract createEntity(entity: Entity): Promise<boolean>;\n\n\t/**\n\t * Updates an existing entity in the database.\n\t * @param entity The entity object with updated properties.\n\t * @returns A Promise that resolves when the account update is complete.\n\t */\n\tabstract updateEntity(entity: Entity): Promise<void>;\n\n\t/**\n\t * Retrieves a single component by entity ID and type.\n\t * @param entityId The UUID of the entity the component belongs to\n\t * @param type The type identifier for the component\n\t * @param worldId Optional UUID of the world the component belongs to\n\t * @param sourceEntityId Optional UUID of the source entity\n\t * @returns Promise resolving to the Component if found, null otherwise\n\t */\n\tabstract getComponent(\n\t\tentityId: UUID,\n\t\ttype: string,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component | null>;\n\n\t/**\n\t * Retrieves all components for an entity.\n\t * @param entityId The UUID of the entity to get components for\n\t * @param worldId Optional UUID of the world to filter components by\n\t * @param sourceEntityId Optional UUID of the source entity to filter by\n\t * @returns Promise resolving to array of Component objects\n\t */\n\tabstract getComponents(\n\t\tentityId: UUID,\n\t\tworldId?: UUID,\n\t\tsourceEntityId?: UUID,\n\t): Promise<Component[]>;\n\n\t/**\n\t * Creates a new component in the database.\n\t * @param component The component object to create\n\t * @returns Promise resolving to true if creation was successful\n\t */\n\tabstract createComponent(component: Component): Promise<boolean>;\n\n\t/**\n\t * Updates an existing component in the database.\n\t * @param component The component object with updated properties\n\t * @returns Promise that resolves when the update is complete\n\t */\n\tabstract updateComponent(component: Component): Promise<void>;\n\n\t/**\n\t * Deletes a component from the database.\n\t * @param componentId The UUID of the component to delete\n\t * @returns Promise that resolves when the deletion is complete\n\t */\n\tabstract deleteComponent(componentId: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves memories based on the specified parameters.\n\t * @param params An object containing parameters for the memory retrieval.\n\t * @returns A Promise that resolves to an array of Memory objects.\n\t */\n\tabstract getMemories(params: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t}): Promise<Memory[]>;\n\n\tabstract getMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\ttableName: string;\n\t\tlimit?: number;\n\t}): Promise<Memory[]>;\n\n\tabstract getMemoryById(id: UUID): Promise<Memory | null>;\n\n\t/**\n\t * Retrieves multiple memories by their IDs\n\t * @param memoryIds Array of UUIDs of the memories to retrieve\n\t * @param tableName Optional table name to filter memories by type\n\t * @returns Promise resolving to array of Memory objects\n\t */\n\tabstract getMemoriesByIds(\n\t\tmemoryIds: UUID[],\n\t\ttableName?: string,\n\t): Promise<Memory[]>;\n\n\t/**\n\t * Retrieves cached embeddings based on the specified query parameters.\n\t * @param params An object containing parameters for the embedding retrieval.\n\t * @returns A Promise that resolves to an array of objects containing embeddings and levenshtein scores.\n\t */\n\tabstract getCachedEmbeddings({\n\t\tquery_table_name,\n\t\tquery_threshold,\n\t\tquery_input,\n\t\tquery_field_name,\n\t\tquery_field_sub_name,\n\t\tquery_match_count,\n\t}: {\n\t\tquery_table_name: string;\n\t\tquery_threshold: number;\n\t\tquery_input: string;\n\t\tquery_field_name: string;\n\t\tquery_field_sub_name: string;\n\t\tquery_match_count: number;\n\t}): Promise<\n\t\t{\n\t\t\tembedding: number[];\n\t\t\tlevenshtein_score: number;\n\t\t}[]\n\t>;\n\n\t/**\n\t * Logs an event or action with the specified details.\n\t * @param params An object containing parameters for the log entry.\n\t * @returns A Promise that resolves when the log entry has been saved.\n\t */\n\tabstract log(params: {\n\t\tbody: { [key: string]: unknown };\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\ttype: string;\n\t}): Promise<void>;\n\n\t/**\n\t * Searches for memories based on embeddings and other specified parameters.\n\t * @param params An object containing parameters for the memory search.\n\t * @returns A Promise that resolves to an array of Memory objects.\n\t */\n\tabstract searchMemories(params: {\n\t\ttableName: string;\n\t\troomId: UUID;\n\t\tembedding: number[];\n\t\tmatch_threshold: number;\n\t\tcount: number;\n\t\tunique: boolean;\n\t}): Promise<Memory[]>;\n\n\t/**\n\t * Creates a new memory in the database.\n\t * @param memory The memory object to create.\n\t * @param tableName The table where the memory should be stored.\n\t * @param unique Indicates if the memory should be unique.\n\t * @returns A Promise that resolves when the memory has been created.\n\t */\n\tabstract createMemory(\n\t\tmemory: Memory,\n\t\ttableName: string,\n\t\tunique?: boolean,\n\t): Promise<UUID>;\n\n\t/**\n\t * Removes a specific memory from the database.\n\t * @param memoryId The UUID of the memory to remove.\n\t * @param tableName The table from which the memory should be removed.\n\t * @returns A Promise that resolves when the memory has been removed.\n\t */\n\tabstract removeMemory(memoryId: UUID, tableName: string): Promise<void>;\n\n\t/**\n\t * Removes all memories associated with a specific room.\n\t * @param roomId The UUID of the room whose memories should be removed.\n\t * @param tableName The table from which the memories should be removed.\n\t * @returns A Promise that resolves when all memories have been removed.\n\t */\n\tabstract removeAllMemories(roomId: UUID, tableName: string): Promise<void>;\n\n\t/**\n\t * Counts the number of memories in a specific room.\n\t * @param roomId The UUID of the room for which to count memories.\n\t * @param unique Specifies whether to count only unique memories.\n\t * @param tableName Optional table name to count memories from.\n\t * @returns A Promise that resolves to the number of memories.\n\t */\n\tabstract countMemories(\n\t\troomId: UUID,\n\t\tunique?: boolean,\n\t\ttableName?: string,\n\t): Promise<number>;\n\n\t/**\n\t * Retrieves a world by its ID.\n\t * @param id The UUID of the world to retrieve.\n\t * @returns A Promise that resolves to the World object or null if not found.\n\t */\n\tabstract getWorld(id: UUID): Promise<World | null>;\n\n\t/**\n\t * Retrieves all worlds for an agent.\n\t * @returns A Promise that resolves to an array of World objects.\n\t */\n\tabstract getAllWorlds(): Promise<World[]>;\n\n\t/**\n\t * Creates a new world in the database.\n\t * @param world The world object to create.\n\t * @returns A Promise that resolves to the UUID of the created world.\n\t */\n\tabstract createWorld(world: World): Promise<UUID>;\n\n\t/**\n\t * Updates an existing world in the database.\n\t * @param world The world object with updated properties.\n\t * @returns A Promise that resolves when the world has been updated.\n\t */\n\tabstract updateWorld(world: World): Promise<void>;\n\n\t/**\n\t * Removes a specific world from the database.\n\t * @param id The UUID of the world to remove.\n\t * @returns A Promise that resolves when the world has been removed.\n\t */\n\tabstract removeWorld(id: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves the room ID for a given room, if it exists.\n\t * @param roomId The UUID of the room to retrieve.\n\t * @returns A Promise that resolves to the room ID or null if not found.\n\t */\n\tabstract getRoom(roomId: UUID): Promise<Room | null>;\n\n\t/**\n\t * Retrieves all rooms for a given world.\n\t * @param worldId The UUID of the world to retrieve rooms for.\n\t * @returns A Promise that resolves to an array of Room objects.\n\t */\n\tabstract getRooms(worldId: UUID): Promise<Room[]>;\n\n\t/**\n\t * Creates a new room with an optional specified ID.\n\t * @param roomId Optional UUID to assign to the new room.\n\t * @returns A Promise that resolves to the UUID of the created room.\n\t */\n\tabstract createRoom({\n\t\tid,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room): Promise<UUID>;\n\n\t/**\n\t * Updates a specific room in the database.\n\t * @param room The room object with updated properties.\n\t * @returns A Promise that resolves when the room has been updated.\n\t */\n\tabstract updateRoom(room: Room): Promise<void>;\n\n\t/**\n\t * Removes a specific room from the database.\n\t * @param roomId The UUID of the room to remove.\n\t * @returns A Promise that resolves when the room has been removed.\n\t */\n\tabstract deleteRoom(roomId: UUID): Promise<void>;\n\n\t/**\n\t * Retrieves room IDs for which a specific user is a participant.\n\t * @param entityId The UUID of the user.\n\t * @returns A Promise that resolves to an array of room IDs.\n\t */\n\tabstract getRoomsForParticipant(entityId: UUID): Promise<UUID[]>;\n\n\t/**\n\t * Retrieves room IDs for which specific users are participants.\n\t * @param userIds An array of UUIDs of the users.\n\t * @returns A Promise that resolves to an array of room IDs.\n\t */\n\tabstract getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;\n\n\t/**\n\t * Adds a user as a participant to a specific room.\n\t * @param entityId The UUID of the user to add as a participant.\n\t * @param roomId The UUID of the room to which the user will be added.\n\t * @returns A Promise that resolves to a boolean indicating success or failure.\n\t */\n\tabstract addParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\t/**\n\t * Removes a user as a participant from a specific room.\n\t * @param entityId The UUID of the user to remove as a participant.\n\t * @param roomId The UUID of the room from which the user will be removed.\n\t * @returns A Promise that resolves to a boolean indicating success or failure.\n\t */\n\tabstract removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;\n\n\t/**\n\t * Retrieves participants associated with a specific account.\n\t * @param entityId The UUID of the account.\n\t * @returns A Promise that resolves to an array of Participant objects.\n\t */\n\tabstract getParticipantsForEntity(entityId: UUID): Promise<Participant[]>;\n\n\t/**\n\t * Retrieves participants for a specific room.\n\t * @param roomId The UUID of the room for which to retrieve participants.\n\t * @returns A Promise that resolves to an array of UUIDs representing the participants.\n\t */\n\tabstract getParticipantsForRoom(roomId: UUID): Promise<UUID[]>;\n\n\tabstract getParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t): Promise<\"FOLLOWED\" | \"MUTED\" | null>;\n\n\tabstract setParticipantUserState(\n\t\troomId: UUID,\n\t\tentityId: UUID,\n\t\tstate: \"FOLLOWED\" | \"MUTED\" | null,\n\t): Promise<void>;\n\n\t/**\n\t * Creates a new relationship between two users.\n\t * @param params Object containing the relationship details including entity IDs, agent ID, optional tags and metadata\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the creation.\n\t */\n\tabstract createRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: Record<string, unknown>;\n\t}): Promise<boolean>;\n\n\t/**\n\t * Retrieves a relationship between two users if it exists.\n\t * @param params Object containing the entity IDs and agent ID\n\t * @returns A Promise that resolves to the Relationship object or null if not found.\n\t */\n\tabstract getRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t}): Promise<Relationship | null>;\n\n\t/**\n\t * Retrieves all relationships for a specific user.\n\t * @param params Object containing the user ID, agent ID and optional tags to filter by\n\t * @returns A Promise that resolves to an array of Relationship objects.\n\t */\n\tabstract getRelationships(params: {\n\t\tentityId: UUID;\n\t\ttags?: string[];\n\t}): Promise<Relationship[]>;\n\n\t/**\n\t * Updates an existing relationship between two users.\n\t * @param params Object containing the relationship details to update including entity IDs, agent ID, optional tags and metadata\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the update.\n\t */\n\tabstract updateRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: Record<string, unknown>;\n\t}): Promise<void>;\n\n\t/**\n\t * Retrieves an agent by its ID.\n\t * @param agentId The UUID of the agent to retrieve.\n\t * @returns A Promise that resolves to the Agent object or null if not found.\n\t */\n\tabstract getAgent(agentId: UUID): Promise<Agent | null>;\n\n\t/**\n\t * Retrieves all agents from the database.\n\t * @returns A Promise that resolves to an array of Agent objects.\n\t */\n\tabstract getAgents(): Promise<Agent[]>;\n\n\t/**\n\t * Creates a new agent in the database.\n\t * @param agent The agent object to create.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the creation.\n\t */\n\tabstract createAgent(agent: Partial<Agent>): Promise<boolean>;\n\n\t/**\n\t * Updates an existing agent in the database.\n\t * @param agentId The UUID of the agent to update.\n\t * @param agent The agent object with updated properties.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the update.\n\t */\n\tabstract updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean>;\n\n\t/**\n\t * Deletes an agent from the database.\n\t * @param agentId The UUID of the agent to delete.\n\t * @returns A Promise that resolves to a boolean indicating success or failure of the deletion.\n\t */\n\tabstract deleteAgent(agentId: UUID): Promise<boolean>;\n\n\t/**\n\t * Ensures an agent exists in the database.\n\t * @param agent The agent object to ensure exists.\n\t * @returns A Promise that resolves when the agent has been ensured to exist.\n\t */\n\tabstract ensureAgentExists(agent: Partial<Agent>): Promise<void>;\n\n\t/**\n\t * Ensures an embedding dimension exists in the database.\n\t * @param dimension The dimension to ensure exists.\n\t * @returns A Promise that resolves when the embedding dimension has been ensured to exist.\n\t */\n\tabstract ensureEmbeddingDimension(dimension: number): Promise<void>;\n\n\t/**\n\t * Retrieves a cached value by key from the database.\n\t * @param key The key to look up in the cache\n\t * @returns Promise resolving to the cached string value\n\t */\n\tabstract getCache<T>(key: string): Promise<T | undefined>;\n\n\t/**\n\t * Sets a value in the cache with the given key.\n\t * @param params Object containing the cache key and value\n\t * @param key The key to store the value under\n\t * @param value The string value to cache\n\t * @returns Promise resolving to true if the cache was set successfully\n\t */\n\tabstract setCache<T>(key: string, value: T): Promise<boolean>;\n\n\t/**\n\t * Deletes a value from the cache by key.\n\t * @param key The key to delete from the cache\n\t * @returns Promise resolving to true if the value was successfully deleted\n\t */\n\tabstract deleteCache(key: string): Promise<boolean>;\n\n\t/**\n\t * Creates a new task instance in the database.\n\t * @param task The task object to create\n\t * @returns Promise resolving to the UUID of the created task\n\t */\n\tabstract createTask(task: Task): Promise<UUID>;\n\n\t/**\n\t * Retrieves tasks based on specified parameters.\n\t * @param params Object containing optional roomId and tags to filter tasks\n\t * @returns Promise resolving to an array of Task objects\n\t */\n\tabstract getTasks(params: { roomId?: UUID; tags?: string[] }): Promise<\n\t\tTask[]\n\t>;\n\n\t/**\n\t * Retrieves a specific task by its ID.\n\t * @param id The UUID of the task to retrieve\n\t * @returns Promise resolving to the Task object if found, null otherwise\n\t */\n\tabstract getTask(id: UUID): Promise<Task | null>;\n\n\t/**\n\t * Retrieves a specific task by its name.\n\t * @param name The name of the task to retrieve\n\t * @returns Promise resolving to the Task object if found, null otherwise\n\t */\n\tabstract getTasksByName(name: string): Promise<Task[]>;\n\n\t/**\n\t * Updates an existing task in the database.\n\t * @param id The UUID of the task to update\n\t * @param task Partial Task object containing the fields to update\n\t * @returns Promise resolving when the update is complete\n\t */\n\tabstract updateTask(id: UUID, task: Partial<Task>): Promise<void>;\n\n\t/**\n\t * Deletes a task from the database.\n\t * @param id The UUID of the task to delete\n\t * @returns Promise resolving when the deletion is complete\n\t */\n\tabstract deleteTask(id: UUID): Promise<void>;\n}\n","import handlebars from \"handlebars\";\nimport { RecursiveCharacterTextSplitter } from \"langchain/text_splitter\";\nimport { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport logger from \"./logger\";\nimport type {\n\tContent,\n\tEntity,\n\tIAgentRuntime,\n\tMemory,\n\tState,\n\tTemplateType,\n} from \"./types\";\nimport { ModelTypes } from \"./types\";\n\n/**\n * Composes a context string by replacing placeholders in a template with corresponding values from the state.\n *\n * This function takes a template string with placeholders in the format `{{placeholder}}` and a state object.\n * It replaces each placeholder with the value from the state object that matches the placeholder's name.\n * If a matching key is not found in the state object for a given placeholder, the placeholder is replaced with an empty string.\n *\n * @param {Object} params - The parameters for composing the context.\n * @param {State} params.state - The state object containing values to replace the placeholders in the template.\n * @param {TemplateType} params.template - The template string or function containing placeholders to be replaced with state values.\n * @returns {string} The composed context string with placeholders replaced by corresponding state values.\n *\n * @example\n * // Given a state object and a template\n * const state = { userName: \"Alice\", userAge: 30 };\n * const template = \"Hello, {{userName}}! You are {{userAge}} years old\";\n *\n * // Composing the context with simple string replacement will result in:\n * // \"Hello, Alice! You are 30 years old.\"\n * const contextSimple = composePromptFromState({ state, template });\n *\n * // Using composePromptFromState with a template function for dynamic template\n * const template = ({ state }) => {\n * const tone = Math.random() > 0.5 ? \"kind\" : \"rude\";\n * return `Hello, {{userName}}! You are {{userAge}} years old. Be ${tone}`;\n * };\n * const contextSimple = composePromptFromState({ state, template });\n */\n\n/**\n * Function to compose a prompt using a provided template and state.\n *\n * @param {Object} options - Object containing state and template information.\n * @param {State} options.state - The state object containing values to fill the template.\n * @param {TemplateType} options.template - The template to be used for composing the prompt.\n * @returns {string} The composed prompt output.\n */\nexport const composePrompt = ({\n\tstate,\n\ttemplate,\n}: {\n\tstate: { [key: string]: string };\n\ttemplate: TemplateType;\n}) => {\n\tconst templateStr =\n\t\ttypeof template === \"function\" ? template({ state }) : template;\n\tconst templateFunction = handlebars.compile(templateStr);\n\tconst output = composeRandomUser(templateFunction(state), 10);\n\treturn output;\n};\n\n/**\n * Function to compose a prompt using a provided template and state.\n *\n * @param {Object} options - Object containing state and template information.\n * @param {State} options.state - The state object containing values to fill the template.\n * @param {TemplateType} options.template - The template to be used for composing the prompt.\n * @returns {string} The composed prompt output.\n */\nexport const composePromptFromState = ({\n\tstate,\n\ttemplate,\n}: {\n\tstate: State;\n\ttemplate: TemplateType;\n}) => {\n\tconst templateStr =\n\t\ttypeof template === \"function\" ? template({ state }) : template;\n\tconst templateFunction = handlebars.compile(templateStr);\n\n\t// get any keys that are in state but are not named text, values or data\n\tconst stateKeys = Object.keys(state);\n\tconst filteredKeys = stateKeys.filter(\n\t\t(key) => ![\"text\", \"values\", \"data\"].includes(key),\n\t);\n\tconst filteredState = filteredKeys.reduce((acc, key) => {\n\t\tacc[key] = state[key];\n\t\treturn acc;\n\t}, {});\n\n\tconst output = composeRandomUser(\n\t\ttemplateFunction({ ...filteredState, ...state.values }),\n\t\t10,\n\t);\n\treturn output;\n};\n\n/**\n * Adds a header to a body of text.\n *\n * This function takes a header string and a body string and returns a new string with the header prepended to the body.\n * If the body string is empty, the header is returned as is.\n *\n * @param {string} header - The header to add to the body.\n * @param {string} body - The body to which to add the header.\n * @returns {string} The body with the header prepended.\n *\n * @example\n * // Given a header and a body\n * const header = \"Header\";\n * const body = \"Body\";\n *\n * // Adding the header to the body will result in:\n * // \"Header\\nBody\"\n * const text = addHeader(header, body);\n */\nexport const addHeader = (header: string, body: string) => {\n\treturn body.length > 0 ? `${header ? `${header}\\n` : header}${body}\\n` : \"\";\n};\n\n/**\n * Generates a string with random user names populated in a template.\n *\n * This function generates random user names and populates placeholders\n * in the provided template with these names. Placeholders in the template should follow the format `{{userX}}`\n * where `X` is the position of the user (e.g., `{{name1}}`, `{{name2}}`).\n *\n * @param {string} template - The template string containing placeholders for random user names.\n * @param {number} length - The number of random user names to generate.\n * @returns {string} The template string with placeholders replaced by random user names.\n *\n * @example\n * // Given a template and a length\n * const template = \"Hello, {{name1}}! Meet {{name2}} and {{name3}}.\";\n * const length = 3;\n *\n * // Composing the random user string will result in:\n * // \"Hello, John! Meet Alice and Bob.\"\n * const result = composeRandomUser(template, length);\n */\nexport const composeRandomUser = (template: string, length: number) => {\n\tconst exampleNames = Array.from({ length }, () =>\n\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t);\n\tlet result = template;\n\tfor (let i = 0; i < exampleNames.length; i++) {\n\t\tresult = result.replaceAll(`{{name${i + 1}}}`, exampleNames[i]);\n\t}\n\n\treturn result;\n};\n\nexport const formatPosts = ({\n\tmessages,\n\tentities,\n\tconversationHeader = true,\n}: {\n\tmessages: Memory[];\n\tentities: Entity[];\n\tconversationHeader?: boolean;\n}) => {\n\t// Group messages by roomId\n\tconst groupedMessages: { [roomId: string]: Memory[] } = {};\n\tmessages.forEach((message) => {\n\t\tif (message.roomId) {\n\t\t\tif (!groupedMessages[message.roomId]) {\n\t\t\t\tgroupedMessages[message.roomId] = [];\n\t\t\t}\n\t\t\tgroupedMessages[message.roomId].push(message);\n\t\t}\n\t});\n\n\t// Sort messages within each roomId by createdAt (oldest to newest)\n\tObject.values(groupedMessages).forEach((roomMessages) => {\n\t\troomMessages.sort((a, b) => a.createdAt - b.createdAt);\n\t});\n\n\t// Sort rooms by the newest message's createdAt\n\tconst sortedRooms = Object.entries(groupedMessages).sort(\n\t\t([, messagesA], [, messagesB]) =>\n\t\t\tmessagesB[messagesB.length - 1].createdAt -\n\t\t\tmessagesA[messagesA.length - 1].createdAt,\n\t);\n\n\tconst formattedPosts = sortedRooms.map(([roomId, roomMessages]) => {\n\t\tconst messageStrings = roomMessages\n\t\t\t.filter((message: Memory) => message.entityId)\n\t\t\t.map((message: Memory) => {\n\t\t\t\tconst entity = entities.find(\n\t\t\t\t\t(entity: Entity) => entity.id === message.entityId,\n\t\t\t\t);\n\t\t\t\t// TODO: These are okay but not great\n\t\t\t\tconst userName = entity?.names[0] || \"Unknown User\";\n\t\t\t\tconst displayName = entity?.names[0] || \"unknown\";\n\n\t\t\t\treturn `Name: ${userName} (@${displayName})\nID: ${message.id}${\n\t\t\t\t\tmessage.content.inReplyTo\n\t\t\t\t\t\t? `\\nIn reply to: ${message.content.inReplyTo}`\n\t\t\t\t\t\t: \"\"\n\t\t\t\t}\nDate: ${formatTimestamp(message.createdAt)}\nText:\n${message.content.text}`;\n\t\t\t});\n\n\t\tconst header = conversationHeader\n\t\t\t? `Conversation: ${roomId.slice(-5)}\\n`\n\t\t\t: \"\";\n\t\treturn `${header}${messageStrings.join(\"\\n\\n\")}`;\n\t});\n\n\treturn formattedPosts.join(\"\\n\\n\");\n};\n\n/**\n * Format messages into a string\n * @param {Object} params - The formatting parameters\n * @param {Memory[]} params.messages - List of messages to format\n * @param {Entity[]} params.entities - List of entities for name resolution\n * @returns {string} Formatted message string with timestamps and user information\n */\nexport const formatMessages = ({\n\tmessages,\n\tentities,\n}: {\n\tmessages: Memory[];\n\tentities: Entity[];\n}) => {\n\tconst newestMessageWithContentPlan = messages.find(\n\t\t(message: Memory) => (message.content as Content).plan,\n\t);\n\tconst messageStrings = messages\n\t\t.reverse()\n\t\t.filter((message: Memory) => message.entityId)\n\t\t.map((message: Memory) => {\n\t\t\tconst messageText = (message.content as Content).text;\n\n\t\t\tconst messageActions = (message.content as Content).actions;\n\t\t\tconst messageThought = (message.content as Content).thought;\n\t\t\tconst formattedName =\n\t\t\t\tentities.find((entity: Entity) => entity.id === message.entityId)\n\t\t\t\t\t?.names[0] || \"Unknown User\";\n\n\t\t\tconst attachments = (message.content as Content).attachments;\n\n\t\t\tconst attachmentString =\n\t\t\t\tattachments && attachments.length > 0\n\t\t\t\t\t? ` (Attachments: ${attachments\n\t\t\t\t\t\t\t.map((media) => `[${media.id} - ${media.title} (${media.url})]`)\n\t\t\t\t\t\t\t.join(\", \")})`\n\t\t\t\t\t: null;\n\n\t\t\tconst messageTime = new Date(message.createdAt);\n\t\t\tconst hours = messageTime.getHours().toString().padStart(2, \"0\");\n\t\t\tconst minutes = messageTime.getMinutes().toString().padStart(2, \"0\");\n\t\t\tconst timeString = `${hours}:${minutes}`;\n\n\t\t\tconst timestamp = formatTimestamp(message.createdAt);\n\n\t\t\tconst shortId = message.entityId.slice(-5);\n\n\t\t\tconst thoughtString = messageThought\n\t\t\t\t? `(${formattedName}'s internal thought: ${messageThought})`\n\t\t\t\t: null;\n\n\t\t\tconst timestampString = `${timeString} (${timestamp}) [${shortId}]`;\n\t\t\tconst textString = messageText\n\t\t\t\t? `${timestampString} ${formattedName}: ${messageText}`\n\t\t\t\t: null;\n\t\t\tconst actionString =\n\t\t\t\tmessageActions && messageActions.length > 0\n\t\t\t\t\t? `${\n\t\t\t\t\t\t\ttextString ? \"\" : timestampString\n\t\t\t\t\t\t} (${formattedName}'s actions: ${messageActions.join(\", \")})`\n\t\t\t\t\t: null;\n\n\t\t\tconst planString =\n\t\t\t\tnewestMessageWithContentPlan?.id === message.id\n\t\t\t\t\t? `(${formattedName}'s plan: ${newestMessageWithContentPlan.content.plan})`\n\t\t\t\t\t: null;\n\n\t\t\t// for each thought, action, text or attachment, add a new line, with text first, then thought, then action, then attachment\n\t\t\tconst messageString = [\n\t\t\t\ttextString,\n\t\t\t\tthoughtString,\n\t\t\t\tplanString,\n\t\t\t\tactionString,\n\t\t\t\tattachmentString,\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\"\\n\");\n\n\t\t\treturn messageString;\n\t\t})\n\t\t.join(\"\\n\");\n\treturn messageStrings;\n};\n\nexport const formatTimestamp = (messageDate: number) => {\n\tconst now = new Date();\n\tconst diff = now.getTime() - messageDate;\n\n\tconst absDiff = Math.abs(diff);\n\tconst seconds = Math.floor(absDiff / 1000);\n\tconst minutes = Math.floor(seconds / 60);\n\tconst hours = Math.floor(minutes / 60);\n\tconst days = Math.floor(hours / 24);\n\n\tif (absDiff < 60000) {\n\t\treturn \"just now\";\n\t}\n\tif (minutes < 60) {\n\t\treturn `${minutes} minute${minutes !== 1 ? \"s\" : \"\"} ago`;\n\t}\n\tif (hours < 24) {\n\t\treturn `${hours} hour${hours !== 1 ? \"s\" : \"\"} ago`;\n\t}\n\treturn `${days} day${days !== 1 ? \"s\" : \"\"} ago`;\n};\n\nconst jsonBlockPattern = /```json\\n([\\s\\S]*?)\\n```/;\n\nexport const shouldRespondTemplate = `# Task: Decide on behalf of {{agentName}} whether they should respond to the message, ignore it or stop the conversation.\n{{providers}}\n# Instructions: Decide if {{agentName}} should respond to or interact with the conversation.\nIf the message is directed at or relevant to {{agentName}}, respond with RESPOND action.\nIf a user asks {{agentName}} to be quiet, respond with STOP action.\nIf {{agentName}} should ignore the message, respond with IGNORE action.\nIf responding with the RESPOND action, include a list of optional providers that could be relevant to the response.\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"name\": \"{{agentName}}\",\n\t\"reasoning\": \"<string>\",\n \"action\": \"RESPOND\" | \"IGNORE\" | \"STOP\",\n \"providers\": [\"<string>\", \"<string>\", ...]\n}\n\\`\\`\\`\nYour response should include the valid JSON block and nothing else.`;\n\nexport const messageHandlerTemplate = `# Task: Generate dialog and actions for the character {{agentName}}.\n{{providers}}\n# Instructions: Write a thought and plan for {{agentName}} and decide what actions to take. Also include the providers that {{agentName}} will use to have the right context for responding and acting, if any.\nFirst, think about what you want to do next and plan your actions. Then, write the next message and include the actions you plan to take.\n\"thought\" should be a short description of what the agent is thinking about and planning.\n\"actions\" should be an array of the actions {{agentName}} plans to take based on the thought (if none, use IGNORE, if simply responding with text, use REPLY)\n\"providers\" should be an optional array of the providers that {{agentName}} will use to have the right context for responding and acting\n\"evaluators\" should be an optional array of the evaluators that {{agentName}} will use to evaluate the conversation after responding\n\"plan\" should be explanation of the message you plan to send, the actions you plan to take, and the data providers you plan to use.\nThese are the available valid actions: {{actionNames}}\n\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"thought\": \"<string>\",\n \"plan\": \"<string>\",\n \"actions\": [\"<string>\", \"<string>\", ...],\n \"providers\": [\"<string>\", \"<string>\", ...]\n}\n\\`\\`\\`\n\nYour response should include the valid JSON block and nothing else.`;\n\nexport const booleanFooter = \"Respond with only a YES or a NO.\";\n\n/**\n * Parses a string to determine its boolean equivalent.\n *\n * Recognized affirmative values: \"YES\", \"Y\", \"TRUE\", \"T\", \"1\", \"ON\", \"ENABLE\"\n * Recognized negative values: \"NO\", \"N\", \"FALSE\", \"F\", \"0\", \"OFF\", \"DISABLE\"\n *\n * @param {string | undefined | null} value - The input text to parse\n * @returns {boolean} - Returns `true` for affirmative inputs, `false` for negative or unrecognized inputs\n */\nexport function parseBooleanFromText(\n\tvalue: string | undefined | null,\n): boolean {\n\tif (!value) return false;\n\n\tconst affirmative = [\"YES\", \"Y\", \"TRUE\", \"T\", \"1\", \"ON\", \"ENABLE\"];\n\tconst negative = [\"NO\", \"N\", \"FALSE\", \"F\", \"0\", \"OFF\", \"DISABLE\"];\n\n\tconst normalizedText = value.trim().toUpperCase();\n\n\tif (affirmative.includes(normalizedText)) {\n\t\treturn true;\n\t}\n\tif (negative.includes(normalizedText)) {\n\t\treturn false;\n\t}\n\n\t// For environment variables, we'll treat unrecognized values as false\n\treturn false;\n}\n\nexport const stringArrayFooter = `Respond with a JSON array containing the values in a valid JSON block formatted for markdown with this structure:\n\\`\\`\\`json\n[\n 'value',\n 'value'\n]\n\\`\\`\\`\n\nYour response must include the valid JSON block.`;\n\n/**\n * Parses a JSON array from a given text. The function looks for a JSON block wrapped in triple backticks\n * with `json` language identifier, and if not found, it searches for an array pattern within the text.\n * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result\n * is an array, it returns the array; otherwise, it returns null.\n *\n * @param text - The input text from which to extract and parse the JSON array.\n * @returns An array parsed from the JSON string if successful; otherwise, null.\n */\nexport function parseJsonArrayFromText(text: string) {\n\tlet jsonData = null;\n\n\t// First try to parse with the original JSON format\n\tconst jsonBlockMatch = text?.match(jsonBlockPattern);\n\n\tif (jsonBlockMatch) {\n\t\ttry {\n\t\t\t// Only replace quotes that are actually being used for string delimitation\n\t\t\tconst normalizedJson = jsonBlockMatch[1].replace(\n\t\t\t\t/(?<!\\\\)'([^']*)'(?=\\s*[,}\\]])/g,\n\t\t\t\t'\"$1\"',\n\t\t\t);\n\t\t\tjsonData = JSON.parse(normalizeJsonString(normalizedJson));\n\t\t} catch (_e) {\n\t\t\tlogger.warn(\"Could not parse text as JSON, will try pattern matching\");\n\t\t}\n\t}\n\n\t// If that fails, try to find an array pattern\n\tif (!jsonData) {\n\t\tconst arrayPattern = /\\[\\s*(['\"])(.*?)\\1\\s*\\]/;\n\t\tconst arrayMatch = text.match(arrayPattern);\n\n\t\tif (arrayMatch) {\n\t\t\ttry {\n\t\t\t\t// Only replace quotes that are actually being used for string delimitation\n\t\t\t\tconst normalizedJson = arrayMatch[0].replace(\n\t\t\t\t\t/(?<!\\\\)'([^']*)'(?=\\s*[,}\\]])/g,\n\t\t\t\t\t'\"$1\"',\n\t\t\t\t);\n\t\t\t\tjsonData = JSON.parse(normalizeJsonString(normalizedJson));\n\t\t\t} catch (_e) {\n\t\t\t\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(jsonData)) {\n\t\treturn jsonData;\n\t}\n\n\treturn null;\n}\n\n/**\n * Parses a JSON object from a given text. The function looks for a JSON block wrapped in triple backticks\n * with `json` language identifier, and if not found, it searches for an object pattern within the text.\n * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result\n * is an object (but not an array), it returns the object; otherwise, it tries to parse an array if the result\n * is an array, or returns null if parsing is unsuccessful or the result is neither an object nor an array.\n *\n * @param text - The input text from which to extract and parse the JSON object.\n * @returns An object parsed from the JSON string if successful; otherwise, null or the result of parsing an array.\n */\nexport function parseJSONObjectFromText(\n\ttext: string,\n): Record<string, any> | null {\n\tlet jsonData = null;\n\tconst jsonBlockMatch = text.match(jsonBlockPattern);\n\n\ttry {\n\t\tif (jsonBlockMatch) {\n\t\t\t// Parse the JSON from inside the code block\n\t\t\tjsonData = JSON.parse(jsonBlockMatch[1].trim());\n\t\t} else {\n\t\t\t// Try to parse the text directly if it's not in a code block\n\t\t\tjsonData = JSON.parse(normalizeJsonString(text.trim()));\n\t\t}\n\t} catch (_e) {\n\t\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\t\treturn null;\n\t}\n\n\t// Ensure we have a non-null object that's not an array\n\tif (jsonData && typeof jsonData === \"object\" && !Array.isArray(jsonData)) {\n\t\treturn jsonData;\n\t}\n\n\tlogger.warn(\"Could not parse text as JSON, returning null\");\n\n\treturn null;\n}\n\n/**\n * Extracts specific attributes (e.g., user, text, action) from a JSON-like string using regex.\n * @param response - The cleaned string response to extract attributes from.\n * @param attributesToExtract - An array of attribute names to extract.\n * @returns An object containing the extracted attributes.\n */\nexport function extractAttributes(\n\tresponse: string,\n\tattributesToExtract?: string[],\n): { [key: string]: string | undefined } {\n\tconst attributes: { [key: string]: string | undefined } = {};\n\n\tif (!attributesToExtract || attributesToExtract.length === 0) {\n\t\t// Extract all attributes if no specific attributes are provided\n\t\tconst matches = response.matchAll(/\"([^\"]+)\"\\s*:\\s*\"([^\"]*)\"/g);\n\t\tfor (const match of matches) {\n\t\t\tattributes[match[1]] = match[2];\n\t\t}\n\t} else {\n\t\t// Extract only specified attributes\n\t\tfor (const attribute of attributesToExtract) {\n\t\t\tconst match = response.match(\n\t\t\t\tnew RegExp(`\"${attribute}\"\\\\s*:\\\\s*\"([^\"]*)\"`, \"i\"),\n\t\t\t);\n\t\t\tif (match) {\n\t\t\t\tattributes[attribute] = match[1];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attributes;\n}\n\n/**\n * Normalizes a JSON-like string by correcting formatting issues:\n * - Removes extra spaces after '{' and before '}'.\n * - Wraps unquoted values in double quotes.\n * - Converts single-quoted values to double-quoted.\n * - Ensures consistency in key-value formatting.\n * - Normalizes mixed adjacent quote pairs.\n *\n * This is useful for cleaning up improperly formatted JSON strings\n * before parsing them into valid JSON.\n *\n * @param str - The JSON-like string to normalize.\n * @returns A properly formatted JSON string.\n */\n\nexport const normalizeJsonString = (str: string) => {\n\t// Remove extra spaces after '{' and before '}'\n\tstr = str.replace(/\\{\\s+/, \"{\").replace(/\\s+\\}/, \"}\").trim();\n\n\t// \"key\": unquotedValue → \"key\": \"unquotedValue\"\n\tstr = str.replace(\n\t\t/(\"[\\w\\d_-]+\")\\s*: \\s*(?!\"|\\[)([\\s\\S]+?)(?=(,\\s*\"|\\}$))/g,\n\t\t'$1: \"$2\"',\n\t);\n\n\t// \"key\": 'value' → \"key\": \"value\"\n\tstr = str.replace(\n\t\t/\"([^\"]+)\"\\s*:\\s*'([^']*)'/g,\n\t\t(_, key, value) => `\"${key}\": \"${value}\"`,\n\t);\n\n\t// \"key\": someWord → \"key\": \"someWord\"\n\tstr = str.replace(/(\"[\\w\\d_-]+\")\\s*:\\s*([A-Za-z_]+)(?![\"\\w])/g, '$1: \"$2\"');\n\n\t// Replace adjacent quote pairs with a single double quote\n\tstr = str.replace(/(?:\"')|(?:'\")/g, '\"');\n\treturn str;\n};\n\n/**\n * Cleans a JSON-like response string by removing unnecessary markers, line breaks, and extra whitespace.\n * This is useful for handling improperly formatted JSON responses from external sources.\n *\n * @param response - The raw JSON-like string response to clean.\n * @returns The cleaned string, ready for parsing or further processing.\n */\n\nexport function cleanJsonResponse(response: string): string {\n\treturn response\n\t\t.replace(/```json\\s*/g, \"\") // Remove ```json\n\t\t.replace(/```\\s*/g, \"\") // Remove any remaining ```\n\t\t.replace(/(\\r\\n|\\n|\\r)/g, \"\") // Remove line breaks\n\t\t.trim();\n}\n\nexport const postActionResponseFooter =\n\t\"Choose any combination of [LIKE], [RETWEET], [QUOTE], and [REPLY] that are appropriate. Each action must be on its own line. Your response must only include the chosen actions.\";\n\ntype ActionResponse = {\n\tlike: boolean;\n\tretweet: boolean;\n\tquote?: boolean;\n\treply?: boolean;\n};\n\nexport const parseActionResponseFromText = (\n\ttext: string,\n): { actions: ActionResponse } => {\n\tconst actions: ActionResponse = {\n\t\tlike: false,\n\t\tretweet: false,\n\t\tquote: false,\n\t\treply: false,\n\t};\n\n\t// Regex patterns\n\tconst likePattern = /\\[LIKE\\]/i;\n\tconst retweetPattern = /\\[RETWEET\\]/i;\n\tconst quotePattern = /\\[QUOTE\\]/i;\n\tconst replyPattern = /\\[REPLY\\]/i;\n\n\t// Check with regex\n\tactions.like = likePattern.test(text);\n\tactions.retweet = retweetPattern.test(text);\n\tactions.quote = quotePattern.test(text);\n\tactions.reply = replyPattern.test(text);\n\n\t// Also do line by line parsing as backup\n\tconst lines = text.split(\"\\n\");\n\tfor (const line of lines) {\n\t\tconst trimmed = line.trim();\n\t\tif (trimmed === \"[LIKE]\") actions.like = true;\n\t\tif (trimmed === \"[RETWEET]\") actions.retweet = true;\n\t\tif (trimmed === \"[QUOTE]\") actions.quote = true;\n\t\tif (trimmed === \"[REPLY]\") actions.reply = true;\n\t}\n\n\treturn { actions };\n};\n\n/**\n * Truncate text to fit within the character limit, ensuring it ends at a complete sentence.\n */\nexport function truncateToCompleteSentence(\n\ttext: string,\n\tmaxLength: number,\n): string {\n\tif (text.length <= maxLength) {\n\t\treturn text;\n\t}\n\n\t// Attempt to truncate at the last period within the limit\n\tconst lastPeriodIndex = text.lastIndexOf(\".\", maxLength - 1);\n\tif (lastPeriodIndex !== -1) {\n\t\tconst truncatedAtPeriod = text.slice(0, lastPeriodIndex + 1).trim();\n\t\tif (truncatedAtPeriod.length > 0) {\n\t\t\treturn truncatedAtPeriod;\n\t\t}\n\t}\n\n\t// If no period, truncate to the nearest whitespace within the limit\n\tconst lastSpaceIndex = text.lastIndexOf(\" \", maxLength - 1);\n\tif (lastSpaceIndex !== -1) {\n\t\tconst truncatedAtSpace = text.slice(0, lastSpaceIndex).trim();\n\t\tif (truncatedAtSpace.length > 0) {\n\t\t\treturn `${truncatedAtSpace}...`;\n\t\t}\n\t}\n\n\t// Fallback: Hard truncate and add ellipsis\n\tconst hardTruncated = text.slice(0, maxLength - 3).trim();\n\treturn `${hardTruncated}...`;\n}\n\n// Assuming ~4 tokens per character on average\nconst TOKENS_PER_CHAR = 4;\nconst TARGET_TOKENS = 3000;\nconst _TARGET_CHARS = Math.floor(TARGET_TOKENS / TOKENS_PER_CHAR); // ~750 chars\n\nexport async function splitChunks(\n\tcontent: string,\n\tchunkSize = 512,\n\tbleed = 20,\n): Promise<string[]> {\n\tlogger.debug(\"[splitChunks] Starting text split\");\n\n\tconst textSplitter = new RecursiveCharacterTextSplitter({\n\t\tchunkSize: Number(chunkSize),\n\t\tchunkOverlap: Number(bleed),\n\t});\n\n\tconst chunks = await textSplitter.splitText(content);\n\tlogger.debug(\"[splitChunks] Split complete:\", {\n\t\tnumberOfChunks: chunks.length,\n\t\taverageChunkSize:\n\t\t\tchunks.reduce((acc, chunk) => acc + chunk.length, 0) / chunks.length,\n\t});\n\n\treturn chunks;\n}\n\n/**\n * Trims the provided text prompt to a specified token limit using a tokenizer model and type.\n */\nexport async function trimTokens(\n\tprompt: string,\n\tmaxTokens: number,\n\truntime: IAgentRuntime,\n) {\n\tif (!prompt) throw new Error(\"Trim tokens received a null prompt\");\n\n\t// if prompt is less than of maxtokens / 5, skip\n\tif (prompt.length < maxTokens / 5) return prompt;\n\n\tif (maxTokens <= 0) throw new Error(\"maxTokens must be positive\");\n\n\ttry {\n\t\tconst tokens = await runtime.useModel(ModelTypes.TEXT_TOKENIZER_ENCODE, {\n\t\t\tprompt,\n\t\t});\n\n\t\t// If already within limits, return unchanged\n\t\tif (tokens.length <= maxTokens) {\n\t\t\treturn prompt;\n\t\t}\n\n\t\t// Keep the most recent tokens by slicing from the end\n\t\tconst truncatedTokens = tokens.slice(-maxTokens);\n\n\t\t// Decode back to text\n\t\treturn await runtime.useModel(ModelTypes.TEXT_TOKENIZER_DECODE, {\n\t\t\ttokens: truncatedTokens,\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(\"Error in trimTokens:\", error);\n\t\t// Return truncated string if tokenization fails\n\t\treturn prompt.slice(-maxTokens * 4); // Rough estimate of 4 chars per token\n\t}\n}\n","import pino, { type LogFn, type DestinationStream } from \"pino\";\nimport pretty from \"pino-pretty\";\nimport { parseBooleanFromText } from \"./prompts\";\n\n/**\n * Interface representing a log entry.\n * @property {number} [time] - The timestamp of the log entry.\n * @property {unknown} [key] - Additional properties that can be added to the log entry.\n */\ninterface LogEntry {\n\ttime?: number;\n\t[key: string]: unknown;\n}\n\n// Custom destination that maintains recent logs in memory\n/**\n * Class representing an in-memory destination stream for logging.\n * Implements DestinationStream interface.\n */\nclass InMemoryDestination implements DestinationStream {\n\tprivate logs: LogEntry[] = [];\n\tprivate maxLogs = 1000; // Keep last 1000 logs\n\tprivate stream: DestinationStream | null;\n\n\t/**\n\t * Constructor for creating a new instance of the class.\n\t * @param {DestinationStream|null} stream - The stream to assign to the instance. Can be null.\n\t */\n\tconstructor(stream: DestinationStream | null) {\n\t\tthis.stream = stream;\n\t}\n\n\t/**\n\t * Writes a log entry to the memory buffer and forwards it to the pretty print stream if available.\n\t *\n\t * @param {string | LogEntry} data - The data to be written, which can be either a string or a LogEntry object.\n\t * @returns {void}\n\t */\n\twrite(data: string | LogEntry): void {\n\t\t// Parse the log entry if it's a string\n\t\tconst logEntry: LogEntry =\n\t\t\ttypeof data === \"string\" ? JSON.parse(data) : data;\n\n\t\t// Add timestamp if not present\n\t\tif (!logEntry.time) {\n\t\t\tlogEntry.time = Date.now();\n\t\t}\n\n\t\t// Add to memory buffer\n\t\tthis.logs.push(logEntry);\n\n\t\t// Maintain buffer size\n\t\tif (this.logs.length > this.maxLogs) {\n\t\t\tthis.logs.shift();\n\t\t}\n\n\t\t// Forward to pretty print stream if available\n\t\tif (this.stream) {\n\t\t\t// Ensure we pass a string to the stream\n\t\t\tconst stringData = typeof data === \"string\" ? data : JSON.stringify(data);\n\t\t\tthis.stream.write(stringData);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves the recent logs from the system.\n\t *\n\t * @returns {LogEntry[]} An array of LogEntry objects representing the recent logs.\n\t */\n\trecentLogs(): LogEntry[] {\n\t\treturn this.logs;\n\t}\n}\n\nconst customLevels: Record<string, number> = {\n\tfatal: 60,\n\terror: 50,\n\twarn: 40,\n\tinfo: 30,\n\tlog: 29,\n\tprogress: 28,\n\tsuccess: 27,\n\tdebug: 20,\n\ttrace: 10,\n};\n\nconst raw = parseBooleanFromText(process?.env?.LOG_JSON_FORMAT) || false;\n\nconst createStream = () => {\n\tif (raw) {\n\t\treturn undefined;\n\t}\n\treturn pretty({\n\t\tcolorize: true,\n\t\ttranslateTime: \"yyyy-mm-dd HH:MM:ss\",\n\t\tignore: \"pid,hostname\",\n\t});\n};\n\nconst defaultLevel =\n\tprocess?.env?.DEFAULT_LOG_LEVEL || process?.env?.LOG_LEVEL || \"info\";\n\n/**\n * Configuration options for logger.\n * @typedef {object} LoggerOptions\n * @property {string} level - The default log level.\n * @property {object} customLevels - Custom log levels.\n * @property {object} hooks - Hooks for customizing log behavior.\n * @property {Function} hooks.logMethod - Custom log method.\n * @param {Array} inputArgs - The arguments passed to the log method.\n * @param {Function} method - The log method to be executed.\n * @returns {void}\n */\nconst options = {\n\tlevel: defaultLevel,\n\tcustomLevels,\n\thooks: {\n\t\tlogMethod(\n\t\t\tinputArgs: [string | Record<string, unknown>, ...unknown[]],\n\t\t\tmethod: LogFn,\n\t\t): void {\n\t\t\tconst [arg1, ...rest] = inputArgs;\n\n\t\t\tif (typeof arg1 === \"object\") {\n\t\t\t\tconst messageParts = rest.map((arg) =>\n\t\t\t\t\ttypeof arg === \"string\" ? arg : JSON.stringify(arg),\n\t\t\t\t);\n\t\t\t\tconst message = messageParts.join(\" \");\n\t\t\t\tmethod.apply(this, [arg1, message]);\n\t\t\t} else {\n\t\t\t\tconst context = {};\n\t\t\t\tconst messageParts = [arg1, ...rest].map((arg) =>\n\t\t\t\t\ttypeof arg === \"string\" ? arg : arg,\n\t\t\t\t);\n\t\t\t\tconst message = messageParts\n\t\t\t\t\t.filter((part) => typeof part === \"string\")\n\t\t\t\t\t.join(\" \");\n\t\t\t\tconst jsonParts = messageParts.filter(\n\t\t\t\t\t(part) => typeof part === \"object\",\n\t\t\t\t);\n\n\t\t\t\tObject.assign(context, ...jsonParts);\n\n\t\t\t\tmethod.apply(this, [context, message]);\n\t\t\t}\n\t\t},\n\t},\n};\n\n// Create the destination with in-memory logging\nconst stream = createStream();\nconst destination = new InMemoryDestination(stream);\n\n// Create logger with custom destination\nexport const logger = pino(options, destination);\n\n// Expose the destination for accessing recent logs\n(logger as unknown)[Symbol.for(\"pino-destination\")] = destination;\n\n// for backward compatibility\nexport const elizaLogger = logger;\n\nexport default logger;\n","import { logger, stringToUuid } from \"./index\";\nimport { composePrompt, parseJSONObjectFromText } from \"./prompts\";\nimport {\n\ttype Entity,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Relationship,\n\ttype State,\n\ttype UUID,\n} from \"./types\";\n\n/**\n * Template for resolving entity name within a conversation context.\n *\n * @type {string}\n */\nconst entityResolutionTemplate = `# Task: Resolve Entity Name\nMessage Sender: {{senderName}} (ID: {{senderId}})\nAgent: {{agentName}} (ID: {{agentId}})\n\n# Entities in Room:\n{{#if entitiesInRoom}}\n{{entitiesInRoom}}\n{{/if}}\n\n{{recentMessages}}\n\n# Instructions:\n1. Analyze the context to identify which entity is being referenced\n2. Consider special references like \"me\" (the message sender) or \"you\" (agent the message is directed to)\n3. Look for usernames/handles in standard formats (e.g. @username, user#1234)\n4. Consider context from recent messages for pronouns and references\n5. If multiple matches exist, use context to disambiguate\n6. Consider recent interactions and relationship strength when resolving ambiguity\n\nReturn a JSON object with:\n\\`\\`\\`json\n{\n \"entityId\": \"exact-id-if-known-otherwise-null\",\n \"type\": \"EXACT_MATCH | USERNAME_MATCH | NAME_MATCH | RELATIONSHIP_MATCH | AMBIGUOUS | UNKNOWN\",\n \"matches\": [{\n \"name\": \"matched-name\",\n \"reason\": \"why this entity matches\"\n }]\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.\n`;\n\n/**\n * Get recent interactions between a source entity and candidate entities in a specific room.\n *\n * @param {IAgentRuntime} runtime - The runtime context for the agent.\n * @param {UUID} sourceEntityId - The ID of the source entity initiating interactions.\n * @param {Entity[]} candidateEntities - The list of candidate entities to evaluate interactions with.\n * @param {UUID} roomId - The ID of the room where interactions are taking place.\n * @param {Relationship[]} relationships - The relationships between the entities involved.\n * @returns {Promise<{ entity: Entity; interactions: Memory[]; count: number }[]>} - An array of objects containing the entity, recent interactions, and interaction count.\n */\nasync function getRecentInteractions(\n\truntime: IAgentRuntime,\n\tsourceEntityId: UUID,\n\tcandidateEntities: Entity[],\n\troomId: UUID,\n\trelationships: Relationship[],\n): Promise<{ entity: Entity; interactions: Memory[]; count: number }[]> {\n\tconst results = [];\n\n\t// Get recent messages from the room - just for context\n\tconst recentMessages = await runtime\n\t\t.getMemoryManager(\"messages\")\n\t\t.getMemories({\n\t\t\troomId,\n\t\t\tcount: 20, // Reduced from 100 since we only need context\n\t\t});\n\n\tfor (const entity of candidateEntities) {\n\t\tconst interactions: Memory[] = [];\n\t\tlet interactionScore = 0;\n\n\t\t// First get direct replies using inReplyTo\n\t\tconst directReplies = recentMessages.filter(\n\t\t\t(msg) =>\n\t\t\t\t(msg.entityId === sourceEntityId &&\n\t\t\t\t\tmsg.content.inReplyTo === entity.id) ||\n\t\t\t\t(msg.entityId === entity.id &&\n\t\t\t\t\tmsg.content.inReplyTo === sourceEntityId),\n\t\t);\n\n\t\tinteractions.push(...directReplies);\n\n\t\t// Get relationship strength from metadata\n\t\tconst relationship = relationships.find(\n\t\t\t(rel) =>\n\t\t\t\t(rel.sourceEntityId === sourceEntityId &&\n\t\t\t\t\trel.targetEntityId === entity.id) ||\n\t\t\t\t(rel.targetEntityId === sourceEntityId &&\n\t\t\t\t\trel.sourceEntityId === entity.id),\n\t\t);\n\n\t\tif (relationship?.metadata?.interactions) {\n\t\t\tinteractionScore = relationship.metadata.interactions;\n\t\t}\n\n\t\t// Add bonus points for recent direct replies\n\t\tinteractionScore += directReplies.length;\n\n\t\t// Keep last few messages for context\n\t\tconst uniqueInteractions = [...new Set(interactions)];\n\t\tresults.push({\n\t\t\tentity,\n\t\t\tinteractions: uniqueInteractions.slice(-5), // Only keep last 5 messages for context\n\t\t\tcount: Math.round(interactionScore),\n\t\t});\n\t}\n\n\t// Sort by interaction score descending\n\treturn results.sort((a, b) => b.count - a.count);\n}\n\n/**\n * Finds an entity by name in the given runtime environment.\n *\n * @param {IAgentRuntime} runtime - The agent runtime environment.\n * @param {Memory} message - The memory message containing relevant information.\n * @param {State} state - The current state of the system.\n * @returns {Promise<Entity | null>} A promise that resolves to the found entity or null if not found.\n */\nexport async function findEntityByName(\n\truntime: IAgentRuntime,\n\tmessage: Memory,\n\tstate: State,\n): Promise<Entity | null> {\n\ttry {\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\t\tif (!room) {\n\t\t\tlogger.warn(\"Room not found for entity search\");\n\t\t\treturn null;\n\t\t}\n\n\t\tconst world = room.worldId\n\t\t\t? await runtime.getWorld(room.worldId)\n\t\t\t: null;\n\n\t\t// Get all entities in the room with their components\n\t\tconst entitiesInRoom = await runtime\n\t\t\t\n\t\t\t.getEntitiesForRoom(room.id, true);\n\n\t\t// Filter components for each entity based on permissions\n\t\tconst filteredEntities = await Promise.all(\n\t\t\tentitiesInRoom.map(async (entity) => {\n\t\t\t\tif (!entity.components) return entity;\n\n\t\t\t\t// Get world roles if we have a world\n\t\t\t\tconst worldRoles = world?.metadata?.roles || {};\n\n\t\t\t\t// Filter components based on permissions\n\t\t\t\tentity.components = entity.components.filter((component) => {\n\t\t\t\t\t// 1. Pass if sourceEntityId matches the requesting entity\n\t\t\t\t\tif (component.sourceEntityId === message.entityId) return true;\n\n\t\t\t\t\t// 2. Pass if sourceEntityId is an owner/admin of the current world\n\t\t\t\t\tif (world && component.sourceEntityId) {\n\t\t\t\t\t\tconst sourceRole = worldRoles[component.sourceEntityId];\n\t\t\t\t\t\tif (sourceRole === \"OWNER\" || sourceRole === \"ADMIN\") return true;\n\t\t\t\t\t}\n\n\t\t\t\t\t// 3. Pass if sourceEntityId is the agentId\n\t\t\t\t\tif (component.sourceEntityId === runtime.agentId) return true;\n\n\t\t\t\t\t// Filter out components that don't meet any criteria\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\n\t\t\t\treturn entity;\n\t\t\t}),\n\t\t);\n\n\t\t// Get relationships for the message sender\n\t\tconst relationships = await runtime.getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t});\n\n\t\t// Get entities from relationships\n\t\tconst relationshipEntities = await Promise.all(\n\t\t\trelationships.map(async (rel) => {\n\t\t\t\tconst entityId =\n\t\t\t\t\trel.sourceEntityId === message.entityId\n\t\t\t\t\t\t? rel.targetEntityId\n\t\t\t\t\t\t: rel.sourceEntityId;\n\t\t\t\treturn runtime.getEntityById(entityId);\n\t\t\t}),\n\t\t);\n\n\t\t// Filter out nulls and combine with room entities\n\t\tconst allEntities = [\n\t\t\t...filteredEntities,\n\t\t\t...relationshipEntities.filter((e): e is Entity => e !== null),\n\t\t];\n\n\t\t// Get interaction strength data for relationship entities\n\t\tconst interactionData = await getRecentInteractions(\n\t\t\truntime,\n\t\t\tmessage.entityId,\n\t\t\tallEntities,\n\t\t\troom.id,\n\t\t\trelationships,\n\t\t);\n\n\t\t// Compose context for LLM\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\troomName: room.name || room.id,\n\t\t\t\tworldName: world?.name || \"Unknown\",\n\t\t\t\tentitiesInRoom: JSON.stringify(filteredEntities, null, 2),\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tsenderId: message.entityId,\n\t\t\t},\n\t\t\ttemplate: entityResolutionTemplate,\n\t\t});\n\n\t\t// Use LLM to analyze and resolve the entity\n\t\tconst result = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t\tstopSequences: [],\n\t\t});\n\n\t\t// Parse LLM response\n\t\tconst resolution = parseJSONObjectFromText(result);\n\t\tif (!resolution) {\n\t\t\tlogger.warn(\"Failed to parse entity resolution result\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// If we got an exact entity ID match\n\t\tif (resolution.type === \"EXACT_MATCH\" && resolution.entityId) {\n\t\t\tconst entity = await runtime\n\t\t\t\t\n\t\t\t\t.getEntityById(resolution.entityId as UUID);\n\t\t\tif (entity) {\n\t\t\t\t// Filter components again for the returned entity\n\t\t\t\tif (entity.components) {\n\t\t\t\t\tconst worldRoles = world?.metadata?.roles || {};\n\t\t\t\t\tentity.components = entity.components.filter((component) => {\n\t\t\t\t\t\tif (component.sourceEntityId === message.entityId) return true;\n\t\t\t\t\t\tif (world && component.sourceEntityId) {\n\t\t\t\t\t\t\tconst sourceRole = worldRoles[component.sourceEntityId];\n\t\t\t\t\t\t\tif (sourceRole === \"OWNER\" || sourceRole === \"ADMIN\") return true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (component.sourceEntityId === runtime.agentId) return true;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn entity;\n\t\t\t}\n\t\t}\n\n\t\t// For username/name/relationship matches, search through all entities\n\t\tif (resolution.matches?.[0]?.name) {\n\t\t\tconst matchName = resolution.matches[0].name.toLowerCase();\n\n\t\t\t// Find matching entity by username/handle in components or by name\n\t\t\tconst matchingEntity = allEntities.find((entity) => {\n\t\t\t\t// Check names\n\t\t\t\tif (entity.names.some((n) => n.toLowerCase() === matchName))\n\t\t\t\t\treturn true;\n\n\t\t\t\t// Check components for username/handle match\n\t\t\t\treturn entity.components?.some(\n\t\t\t\t\t(c) =>\n\t\t\t\t\t\tc.data.username?.toLowerCase() === matchName ||\n\t\t\t\t\t\tc.data.handle?.toLowerCase() === matchName,\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tif (matchingEntity) {\n\t\t\t\t// If this is a relationship match, sort by interaction strength\n\t\t\t\tif (resolution.type === \"RELATIONSHIP_MATCH\") {\n\t\t\t\t\tconst interactionInfo = interactionData.find(\n\t\t\t\t\t\t(d) => d.entity.id === matchingEntity.id,\n\t\t\t\t\t);\n\t\t\t\t\tif (interactionInfo && interactionInfo.count > 0) {\n\t\t\t\t\t\treturn matchingEntity;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn matchingEntity;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t} catch (error) {\n\t\tlogger.error(\"Error in findEntityByName:\", error);\n\t\treturn null;\n\t}\n}\n\n/**\n * Function to create a unique UUID based on the runtime and base user ID.\n *\n * @param {RuntimeContext} runtime - The runtime context object.\n * @param {UUID|string} baseUserId - The base user ID to use in generating the UUID.\n * @returns {UUID} - The unique UUID generated based on the runtime and base user ID.\n */\nexport const createUniqueUuid = (runtime, baseUserId: UUID | string): UUID => {\n\t// If the base user ID is the agent ID, return it directly\n\tif (baseUserId === runtime.agentId) {\n\t\treturn runtime.agentId;\n\t}\n\n\t// Use a deterministic approach to generate a new UUID based on both IDs\n\t// This creates a unique ID for each user+agent combination while still being deterministic\n\tconst combinedString = `${baseUserId}:${runtime.agentId}`;\n\n\t// Create a namespace UUID (version 5) from the combined string\n\treturn stringToUuid(combinedString);\n};\n\n/**\n * Get details for a list of entities.\n */\n/**\n * Retrieves entity details for a specific room from the database.\n *\n * @param {Object} params - The input parameters\n * @param {IAgentRuntime} params.runtime - The Agent Runtime instance\n * @param {UUID} params.roomId - The ID of the room to retrieve entity details for\n * @returns {Promise<Array>} - A promise that resolves to an array of unique entity details\n */\nexport async function getEntityDetails({\n\truntime,\n\troomId,\n}: {\n\truntime: IAgentRuntime;\n\troomId: UUID;\n}) {\n\t// Parallelize the two async operations\n\tconst [room, roomEntities] = await Promise.all([\n\t\truntime.getRoom(roomId),\n\t\truntime.getEntitiesForRoom(roomId, true),\n\t]);\n\n\t// Use a Map for uniqueness checking while processing entities\n\tconst uniqueEntities = new Map();\n\n\t// Process entities in a single pass\n\tfor (const entity of roomEntities) {\n\t\tif (uniqueEntities.has(entity.id)) continue;\n\n\t\t// Merge component data more efficiently\n\t\tconst allData = {};\n\t\tfor (const component of entity.components) {\n\t\t\tObject.assign(allData, component.data);\n\t\t}\n\n\t\t// Process merged data\n\t\tconst mergedData = {};\n\t\tfor (const [key, value] of Object.entries(allData)) {\n\t\t\tif (!mergedData[key]) {\n\t\t\t\tmergedData[key] = value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Array.isArray(mergedData[key]) && Array.isArray(value)) {\n\t\t\t\t// Use Set for deduplication in arrays\n\t\t\t\tmergedData[key] = [...new Set([...mergedData[key], ...value])];\n\t\t\t} else if (\n\t\t\t\ttypeof mergedData[key] === \"object\" &&\n\t\t\t\ttypeof value === \"object\"\n\t\t\t) {\n\t\t\t\tmergedData[key] = { ...mergedData[key], ...value };\n\t\t\t}\n\t\t}\n\n\t\t// Create the entity details\n\t\tuniqueEntities.set(entity.id, {\n\t\t\tid: entity.id,\n\t\t\tname: entity.metadata[room.source]?.name || entity.names[0],\n\t\t\tnames: entity.names,\n\t\t\tdata: JSON.stringify({ ...mergedData, ...entity.metadata }),\n\t\t});\n\t}\n\n\treturn Array.from(uniqueEntities.values());\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport logger from \"./logger\";\n\n/**\n * Interface for settings object with key-value pairs.\n */\ninterface Settings {\n\t[key: string]: string | undefined;\n}\n\n/**\n * Represents a collection of settings grouped by namespace.\n *\n * @typedef {Object} NamespacedSettings\n * @property {Settings} namespace - The namespace key and corresponding Settings value.\n */\ninterface NamespacedSettings {\n\t[namespace: string]: Settings;\n}\n\n/**\n * Initialize an empty object for storing environment settings.\n */\nlet environmentSettings: Settings = {};\n\n/**\n * Determines if code is running in a browser environment\n * @returns {boolean} True if in browser environment\n */\nconst isBrowser = (): boolean => {\n\treturn (\n\t\ttypeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\t);\n};\n\n/**\n * Recursively searches for a .env file starting from the current directory\n * and moving up through parent directories (Node.js only)\n * @param {string} [startDir=process.cwd()] - Starting directory for the search\n * @returns {string|null} Path to the nearest .env file or null if not found\n */\nexport function findNearestEnvFile(startDir = process.cwd()) {\n\tif (isBrowser()) return null;\n\n\tlet currentDir = startDir;\n\n\t// Continue searching until we reach the root directory\n\twhile (currentDir !== path.parse(currentDir).root) {\n\t\tconst envPath = path.join(currentDir, \".env\");\n\n\t\tif (fs.existsSync(envPath)) {\n\t\t\treturn envPath;\n\t\t}\n\n\t\t// Move up to parent directory\n\t\tcurrentDir = path.dirname(currentDir);\n\t}\n\n\t// Check root directory as well\n\tconst rootEnvPath = path.join(path.parse(currentDir).root, \".env\");\n\treturn fs.existsSync(rootEnvPath) ? rootEnvPath : null;\n}\n\n/**\n * Configures environment settings for browser usage\n * @param {Settings} settings - Object containing environment variables\n */\nexport function configureSettings(settings: Settings) {\n\tenvironmentSettings = { ...settings };\n}\n\n/**\n * Loads environment variables from the nearest .env file in Node.js\n * or returns configured settings in browser\n * @returns {Settings} Environment variables object\n * @throws {Error} If no .env file is found in Node.js environment\n */\nexport function loadEnvConfig(): Settings {\n\t// For browser environments, return the configured settings\n\tif (isBrowser()) {\n\t\treturn environmentSettings;\n\t}\n\n\t// Node.js environment: load from .env file\n\tconst envPath = findNearestEnvFile();\n\n\t// attempt to Load the .env file into process.env\n\tconst result = config(envPath ? { path: envPath } : {});\n\n\tif (!result.error) {\n\t\tlogger.log(`Loaded .env file from: ${envPath}`);\n\t}\n\n\t// Parse namespaced settings\n\tconst namespacedSettings = parseNamespacedSettings(process.env as Settings);\n\n\t// Attach to process.env for backward compatibility\n\tObject.entries(namespacedSettings).forEach(([namespace, settings]) => {\n\t\tprocess.env[`__namespaced_${namespace}`] = JSON.stringify(settings);\n\t});\n\n\treturn process.env as Settings;\n}\n\n/**\n * Gets a specific environment variable\n * @param {string} key - The environment variable key\n * @param {string} [defaultValue] - Optional default value if key doesn't exist\n * @returns {string|undefined} The environment variable value or default value\n */\nexport function getEnvVariable(\n\tkey: string,\n\tdefaultValue?: string,\n): string | undefined {\n\tif (isBrowser()) {\n\t\treturn environmentSettings[key] || defaultValue;\n\t}\n\treturn process.env[key] || defaultValue;\n}\n\n/**\n * Checks if a specific environment variable exists\n * @param {string} key - The environment variable key\n * @returns {boolean} True if the environment variable exists\n */\nexport function hasEnvVariable(key: string): boolean {\n\tif (isBrowser()) {\n\t\treturn key in environmentSettings;\n\t}\n\treturn key in process.env;\n}\n\n// Add this function to parse namespaced settings\nfunction parseNamespacedSettings(env: Settings): NamespacedSettings {\n\tconst namespaced: NamespacedSettings = {};\n\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (!value) continue;\n\n\t\tconst [namespace, ...rest] = key.split(\".\");\n\t\tif (!namespace || rest.length === 0) continue;\n\n\t\tconst settingKey = rest.join(\".\");\n\t\tnamespaced[namespace] = namespaced[namespace] || {};\n\t\tnamespaced[namespace][settingKey] = value;\n\t}\n\n\treturn namespaced;\n}\n\n// Initialize settings based on environment\nexport const settings = isBrowser() ? environmentSettings : loadEnvConfig();\n\n// Helper schemas for nested types\nexport const MessageExampleSchema = z.object({\n\tname: z.string(),\n\tcontent: z\n\t\t.object({\n\t\t\ttext: z.string(),\n\t\t\taction: z.string().optional(),\n\t\t\tsource: z.string().optional(),\n\t\t\turl: z.string().optional(),\n\t\t\tinReplyTo: z.string().uuid().optional(),\n\t\t\tattachments: z.array(z.any()).optional(),\n\t\t})\n\t\t.and(z.record(z.string(), z.unknown())), // For additional properties\n});\n\nexport const PluginSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string(),\n\tactions: z.array(z.any()).optional(),\n\tproviders: z.array(z.any()).optional(),\n\tevaluators: z.array(z.any()).optional(),\n\tservices: z.array(z.any()).optional(),\n\tclients: z.array(z.any()).optional(),\n});\n\n// Main Character schema\nexport const CharacterSchema = z.object({\n\tid: z.string().uuid().optional(),\n\tname: z.string(),\n\tsystem: z.string().optional(),\n\ttemplates: z.record(z.string()).optional(),\n\tbio: z.union([z.string(), z.array(z.string())]),\n\tmessageExamples: z.array(z.array(MessageExampleSchema)),\n\tpostExamples: z.array(z.string()),\n\ttopics: z.array(z.string()),\n\tadjectives: z.array(z.string()),\n\tknowledge: z\n\t\t.array(\n\t\t\tz.union([\n\t\t\t\tz.string(), // Direct knowledge strings\n\t\t\t\tz.object({\n\t\t\t\t\t// Individual file config\n\t\t\t\t\tpath: z.string(),\n\t\t\t\t\tshared: z.boolean().optional(),\n\t\t\t\t}),\n\t\t\t\tz.object({\n\t\t\t\t\t// Directory config\n\t\t\t\t\tdirectory: z.string(),\n\t\t\t\t\tshared: z.boolean().optional(),\n\t\t\t\t}),\n\t\t\t]),\n\t\t)\n\t\t.optional(),\n\tplugins: z.union([z.array(z.string()), z.array(PluginSchema)]),\n\tsettings: z\n\t\t.object({\n\t\t\tsecrets: z.record(z.string()).optional(),\n\t\t\tvoice: z\n\t\t\t\t.object({\n\t\t\t\t\tmodel: z.string().optional(),\n\t\t\t\t\turl: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tmodel: z.string().optional(),\n\t\t\tmodelConfig: z\n\t\t\t\t.object({\n\t\t\t\t\tmaxInputTokens: z.number().optional(),\n\t\t\t\t\tmaxOutputTokens: z.number().optional(),\n\t\t\t\t\ttemperature: z.number().optional(),\n\t\t\t\t\tfrequency_penalty: z.number().optional(),\n\t\t\t\t\tpresence_penalty: z.number().optional(),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tembeddingModel: z.string().optional(),\n\t\t})\n\t\t.optional(),\n\tstyle: z.object({\n\t\tall: z.array(z.string()),\n\t\tchat: z.array(z.string()),\n\t\tpost: z.array(z.string()),\n\t}),\n});\n\n// Type inference\nexport type CharacterConfig = z.infer<typeof CharacterSchema>;\n\n// Validation function\nexport function validateCharacterConfig(json: unknown): CharacterConfig {\n\ttry {\n\t\treturn CharacterSchema.parse(json);\n\t} catch (error) {\n\t\tif (error instanceof z.ZodError) {\n\t\t\tconst groupedErrors = error.errors.reduce(\n\t\t\t\t(acc, err) => {\n\t\t\t\t\tconst path = err.path.join(\".\");\n\t\t\t\t\tif (!acc[path]) {\n\t\t\t\t\t\tacc[path] = [];\n\t\t\t\t\t}\n\t\t\t\t\tacc[path].push(err.message);\n\t\t\t\t\treturn acc;\n\t\t\t\t},\n\t\t\t\t{} as Record<string, string[]>,\n\t\t\t);\n\n\t\t\tfor (const field in groupedErrors) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t`Validation errors in ${field}: ${groupedErrors[field].join(\" - \")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t\"Character configuration validation failed. Check logs for details.\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n var _a, _b;\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-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{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (!decoded.typ || !decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch (_a) {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import logger from \"./logger\";\n\nconst registrations = new Map<string, any>();\n\nexport const dynamicImport = async (specifier: string) => {\n\tconst module = registrations.get(specifier);\n\tif (module !== undefined) {\n\t\treturn module;\n\t}\n\treturn await import(specifier);\n};\n\nexport const registerDynamicImport = (specifier: string, module: any) => {\n\tregistrations.set(specifier, module);\n};\n\n/**\n * Handles importing of plugins asynchronously.\n *\n * @param {string[]} plugins - An array of strings representing the plugins to import.\n * @returns {Promise<Function[]>} - A Promise that resolves to an array of imported plugins functions.\n */\nexport async function handlePluginImporting(plugins: string[]) {\n\tif (plugins.length > 0) {\n\t\tlogger.debug(\"Imported are: \", plugins);\n\t\tconst importedPlugins = await Promise.all(\n\t\t\tplugins.map(async (plugin) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst importedPlugin = await import(plugin);\n\t\t\t\t\tconst functionName = `${plugin\n\t\t\t\t\t\t.replace(\"@elizaos/plugin-\", \"\")\n\t\t\t\t\t\t.replace(\"@elizaos-plugins/\", \"\")\n\t\t\t\t\t\t.replace(/-./g, (x) => x[1].toUpperCase())}Plugin`; // Assumes plugin function is camelCased with Plugin suffix\n\t\t\t\t\treturn importedPlugin.default || importedPlugin[functionName];\n\t\t\t\t} catch (importError) {\n\t\t\t\t\tlogger.error(`Failed to import plugin: ${plugin}`, importError);\n\t\t\t\t\treturn []; // Return null for failed imports\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn importedPlugins;\n\t}\n\treturn [];\n}\n","import logger from \"./logger\";\nimport {\n\ttype IAgentRuntime,\n\ttype IMemoryManager,\n\ttype Memory,\n\ttype MemoryMetadata,\n\tMemoryType,\n\tModelTypes,\n\ttype UUID,\n} from \"./types\";\n\nconst defaultMatchThreshold = 0.1;\nconst defaultMatchCount = 10;\n\n/**\n * Manage memories in the database.\n */\n/**\n * The AgentRuntime instance associated with this manager.\n */\nexport class MemoryManager implements IMemoryManager {\n\t/**\n\t * The AgentRuntime instance associated with this manager.\n\t */\n\truntime: IAgentRuntime;\n\n\t/**\n\t * The name of the database table this manager operates on.\n\t */\n\ttableName: string;\n\n\t/**\n\t * Constructs a new MemoryManager instance.\n\t * @param opts Options for the manager.\n\t * @param opts.tableName The name of the table this manager will operate on.\n\t * @param opts.runtime The AgentRuntime instance associated with this manager.\n\t */\n\tconstructor(opts: { tableName: string; runtime: IAgentRuntime }) {\n\t\tthis.runtime = opts.runtime;\n\t\tthis.tableName = opts.tableName;\n\t}\n\n\tprivate validateMetadata(metadata: MemoryMetadata): void {\n\t\t// Check type first before any other validation\n\t\tif (!metadata.type) {\n\t\t\tthrow new Error(\"Metadata type is required\");\n\t\t}\n\n\t\t// Then validate other fields\n\t\tif (metadata.source && typeof metadata.source !== \"string\") {\n\t\t\tthrow new Error(\"Metadata source must be a string\");\n\t\t}\n\n\t\tif (metadata.sourceId && typeof metadata.sourceId !== \"string\") {\n\t\t\tthrow new Error(\"Metadata sourceId must be a UUID string\");\n\t\t}\n\n\t\tif (\n\t\t\tmetadata.scope &&\n\t\t\t![\"shared\", \"private\", \"room\"].includes(metadata.scope)\n\t\t) {\n\t\t\tthrow new Error('Metadata scope must be \"shared\", \"private\", or \"room\"');\n\t\t}\n\n\t\tif (metadata.tags && !Array.isArray(metadata.tags)) {\n\t\t\tthrow new Error(\"Metadata tags must be an array of strings\");\n\t\t}\n\t}\n\n\t/**\n\t * Adds an embedding vector to a memory object. If the memory already has an embedding, it is returned as is.\n\t * @param memory The memory object to add an embedding to.\n\t * @returns A Promise resolving to the memory object, potentially updated with an embedding vector.\n\t */\n\t/**\n\t * Adds an embedding vector to a memory object if one doesn't already exist.\n\t * The embedding is generated from the memory's text content using the runtime's\n\t * embedding model. If the memory has no text content, an error is thrown.\n\t *\n\t * @param memory The memory object to add an embedding to\n\t * @returns The memory object with an embedding vector added\n\t * @throws Error if the memory content is empty\n\t */\n\tasync addEmbeddingToMemory(memory: Memory): Promise<Memory> {\n\t\t// Return early if embedding already exists\n\t\tif (memory.embedding) {\n\t\t\treturn memory;\n\t\t}\n\n\t\tconst memoryText = memory.content.text;\n\n\t\t// Validate memory has text content\n\t\tif (!memoryText) {\n\t\t\tthrow new Error(\"Cannot generate embedding: Memory content is empty\");\n\t\t}\n\n\t\ttry {\n\t\t\t// Generate embedding from text content\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\t{\n\t\t\t\t\ttext: memoryText,\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Failed to generate embedding:\", error);\n\t\t\t// Fallback to zero vector if embedding fails\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\tnull,\n\t\t\t);\n\t\t}\n\n\t\treturn memory;\n\t}\n\n\t/**\n\t * Retrieves a list of memories by user IDs, with optional deduplication.\n\t * @param opts Options including user IDs, count, and uniqueness.\n\t * @param opts.roomId The room ID to retrieve memories for.\n\t * @param opts.count The number of memories to retrieve.\n\t * @param opts.unique Whether to retrieve unique memories only.\n\t * @returns A Promise resolving to an array of Memory objects.\n\t */\n\tasync getMemories(opts: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\tstart?: number;\n\t\tend?: number;\n\t\tagentId?: UUID;\n\t}): Promise<Memory[]> {\n\t\treturn await this.runtime.getMemories({\n\t\t\troomId: opts.roomId,\n\t\t\tcount: opts.count,\n\t\t\tunique: opts.unique,\n\t\t\ttableName: this.tableName,\n\t\t\tstart: opts.start,\n\t\t\tend: opts.end,\n\t\t});\n\t}\n\n\tasync getCachedEmbeddings(content: string): Promise<\n\t\t{\n\t\t\tembedding: number[];\n\t\t\tlevenshtein_score: number;\n\t\t}[]\n\t> {\n\t\treturn await this.runtime.getCachedEmbeddings({\n\t\t\tquery_table_name: this.tableName,\n\t\t\tquery_threshold: 2,\n\t\t\tquery_input: content,\n\t\t\tquery_field_name: \"content\",\n\t\t\tquery_field_sub_name: \"text\",\n\t\t\tquery_match_count: 10,\n\t\t});\n\t}\n\n\t/**\n\t * Searches for memories similar to a given embedding vector.\n\t * @param opts Options for the memory search\n\t * @param opts.match_threshold The similarity threshold for matching memories.\n\t * @param opts.count The maximum number of memories to retrieve.\n\t * @param opts.roomId The room ID to retrieve memories for.\n\t * @param opts.agentId The agent ID to retrieve memories for.\n\t * @param opts.unique Whether to retrieve unique memories only.\n\t * @returns A Promise resolving to an array of Memory objects that match the embedding.\n\t */\n\tasync searchMemories(opts: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId: UUID;\n\t\tagentId?: UUID;\n\t\tunique?: boolean;\n\t}): Promise<Memory[]> {\n\t\tconst {\n\t\t\tmatch_threshold = defaultMatchThreshold,\n\t\t\tembedding,\n\t\t\tcount = defaultMatchCount,\n\t\t\troomId,\n\t\t\tagentId,\n\t\t\tunique = true,\n\t\t} = opts;\n\n\t\treturn await this.runtime.searchMemories({\n\t\t\ttableName: this.tableName,\n\t\t\troomId,\n\t\t\tembedding,\n\t\t\tmatch_threshold,\n\t\t\tcount,\n\t\t\tunique,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new memory in the database, with an option to check for similarity before insertion.\n\t * @param memory The memory object to create.\n\t * @param unique Whether to check for similarity before insertion.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync createMemory(memory: Memory, unique = false): Promise<UUID> {\n\t\tif (memory.metadata) {\n\t\t\tthis.validateMetadata(memory.metadata); // This will check type first\n\t\t\tthis.validateMetadataRequirements(memory.metadata);\n\t\t}\n\t\tconst existingMessage = await this.runtime\n\t\t\t\n\t\t\t.getMemoryById(memory.id);\n\n\t\tif (existingMessage) {\n\t\t\tlogger.debug(\"Memory already exists, skipping\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!memory.metadata) {\n\t\t\tmemory.metadata = {\n\t\t\t\ttype: this.tableName,\n\t\t\t\tscope: memory.agentId ? \"private\" : \"shared\",\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as MemoryMetadata;\n\t\t}\n\n\t\t// Handle metadata if present\n\t\tif (memory.metadata) {\n\t\t\t// Validate metadata\n\t\t\tthis.validateMetadata(memory.metadata);\n\n\t\t\t// Ensure timestamp\n\t\t\tif (!memory.metadata.timestamp) {\n\t\t\t\tmemory.metadata.timestamp = Date.now();\n\t\t\t}\n\n\t\t\t// Set default scope if not present\n\t\t\tif (!memory.metadata.scope) {\n\t\t\t\tmemory.metadata.scope = memory.agentId ? \"private\" : \"shared\";\n\t\t\t}\n\t\t}\n\n\t\tlogger.log(\"Creating Memory\", memory.id, memory.content.text);\n\n\t\tif (!memory.embedding) {\n\t\t\tmemory.embedding = await this.runtime.useModel(\n\t\t\t\tModelTypes.TEXT_EMBEDDING,\n\t\t\t\tnull,\n\t\t\t);\n\t\t}\n\n\t\tconst memoryId = await this.runtime\n\t\t\t\n\t\t\t.createMemory(memory, this.tableName, unique);\n\n\t\treturn memoryId;\n\t}\n\n\tasync getMemoriesByRoomIds(params: {\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t\tagentId?: UUID;\n\t}): Promise<Memory[]> {\n\t\treturn await this.runtime.getMemoriesByRoomIds({\n\t\t\ttableName: this.tableName,\n\t\t\troomIds: params.roomIds,\n\t\t\tlimit: params.limit,\n\t\t});\n\t}\n\n\tasync getMemoryById(id: UUID): Promise<Memory | null> {\n\t\tconst result = await this.runtime.getMemoryById(id);\n\t\tif (result && result.agentId !== this.runtime.agentId) return null;\n\t\treturn result;\n\t}\n\n\t/**\n\t * Removes a memory from the database by its ID.\n\t * @param memoryId The ID of the memory to remove.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync removeMemory(memoryId: UUID): Promise<void> {\n\t\tawait this.runtime\n\t\t\t\n\t\t\t.removeMemory(memoryId, this.tableName);\n\t}\n\n\t/**\n\t * Removes all memories associated with a set of user IDs.\n\t * @param roomId The room ID to remove memories for.\n\t * @returns A Promise that resolves when the operation completes.\n\t */\n\tasync removeAllMemories(roomId: UUID): Promise<void> {\n\t\tawait this.runtime\n\t\t\t\n\t\t\t.removeAllMemories(roomId, this.tableName);\n\t}\n\n\t/**\n\t * Counts the number of memories associated with a set of user IDs, with an option for uniqueness.\n\t * @param roomId The room ID to count memories for.\n\t * @param unique Whether to count unique memories only.\n\t * @returns A Promise resolving to the count of memories.\n\t */\n\tasync countMemories(roomId: UUID, unique = true): Promise<number> {\n\t\treturn await this.runtime\n\t\t\t\n\t\t\t.countMemories(roomId, unique, this.tableName);\n\t}\n\n\tprivate validateMetadataRequirements(metadata: MemoryMetadata) {\n\t\tif (metadata.type === MemoryType.FRAGMENT) {\n\t\t\tif (!metadata.documentId) {\n\t\t\t\tthrow new Error(\"Fragment metadata must include documentId\");\n\t\t\t}\n\t\t\tif (typeof metadata.position !== \"number\") {\n\t\t\t\tthrow new Error(\"Fragment metadata must include position\");\n\t\t\t}\n\t\t}\n\t}\n}\n","// File: /swarm/shared/ownership/core.ts\n// Updated to use world metadata instead of cache\n\nimport { createUniqueUuid } from \"./entities\";\nimport { logger } from \"./logger\";\nimport { type IAgentRuntime, Role, type World } from \"./types\";\n\n/**\n * Represents the state of server ownership, including a mapping of server IDs to their respective World objects.\n */\nexport interface ServerOwnershipState {\n\tservers: {\n\t\t[serverId: string]: World;\n\t};\n}\n\n/**\n * Gets a user's role from world metadata\n */\n/**\n * Retrieve the server role of a specified user entity within a given server.\n *\n * @param {IAgentRuntime} runtime - The runtime object containing necessary configurations and services.\n * @param {string} entityId - The unique identifier of the user entity.\n * @param {string} serverId - The unique identifier of the server.\n * @returns {Promise<Role>} The role of the user entity within the server, resolved as a Promise.\n */\nexport async function getUserServerRole(\n\truntime: IAgentRuntime,\n\tentityId: string,\n\tserverId: string,\n): Promise<Role> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.roles) {\n\t\t\treturn Role.NONE;\n\t\t}\n\n\t\tif (world.metadata.roles[entityId]) {\n\t\t\treturn world.metadata.roles[entityId] as Role;\n\t\t}\n\n\t\t// Also check original ID format\n\t\tif (world.metadata.roles[entityId]) {\n\t\t\treturn world.metadata.roles[entityId] as Role;\n\t\t}\n\n\t\treturn Role.NONE;\n\t} catch (error) {\n\t\tlogger.error(`Error getting user role: ${error}`);\n\t\treturn Role.NONE;\n\t}\n}\n\n/**\n * Finds a server where the given user is the owner\n */\nexport async function findWorldForOwner(\n\truntime: IAgentRuntime,\n\tentityId: string,\n): Promise<World | null> {\n\ttry {\n\t\tif (!entityId) {\n\t\t\tlogger.error(\"User ID is required to find server\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// Get all worlds for this agent\n\t\tconst worlds = await runtime.getAllWorlds();\n\n\t\tif (!worlds || worlds.length === 0) {\n\t\t\tlogger.info(\"No worlds found for this agent\");\n\t\t\treturn null;\n\t\t}\n\n\t\t// Find world where the user is the owner\n\t\tfor (const world of worlds) {\n\t\t\tif (world.metadata?.ownership?.ownerId === entityId) {\n\t\t\t\treturn world;\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(`No server found for owner ${entityId}`);\n\t\treturn null;\n\t} catch (error) {\n\t\tlogger.error(`Error finding server for owner: ${error}`);\n\t\treturn null;\n\t}\n}\n","import { join } from \"node:path\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { bootstrapPlugin } from \"./bootstrap\";\nimport { settings } from \"./environment\";\nimport { createUniqueUuid, handlePluginImporting, logger } from \"./index\";\nimport { MemoryManager } from \"./memory\";\nimport { splitChunks } from \"./prompts\";\nimport {\n\ttype Action,\n\ttype Agent,\n\tChannelType,\n\ttype Character,\n\ttype Component,\n\ttype Entity,\n\ttype Evaluator,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype IDatabaseAdapter,\n\ttype IMemoryManager,\n\ttype KnowledgeItem,\n\ttype Memory,\n\tMemoryType,\n\ttype ModelParamsMap,\n\ttype ModelResultMap,\n\ttype ModelType,\n\tModelTypes,\n\ttype Participant,\n\ttype Plugin,\n\ttype Provider,\n\ttype Relationship,\n\ttype Room,\n\ttype Route,\n\ttype Service,\n\ttype ServiceType,\n\ttype State,\n\ttype Task,\n\ttype TaskWorker,\n\ttype UUID,\n\ttype World\n} from \"./types\";\nimport { stringToUuid } from \"./uuid\";\n\n/**\n * Represents the runtime environment for an agent, handling message processing,\n * action registration, and interaction with external services like OpenAI and Supabase.\n */\n/**\n * Represents the runtime environment for an agent.\n * @class\n * @implements { IAgentRuntime }\n * @property { number } #conversationLength - The maximum length of a conversation.\n * @property { UUID } agentId - The unique identifier for the agent.\n * @property { Character } character - The character associated with the agent.\n * @property { IDatabaseAdapter } databaseAdapter - The adapter for interacting with the database.\n * @property {Action[]} actions - The list of actions available to the agent.\n * @property {Evaluator[]} evaluators - The list of evaluators for decision making.\n * @property {Provider[]} providers - The list of providers for external services.\n * @property {Plugin[]} plugins - The list of plugins to extend functionality.\n */\nexport class AgentRuntime implements IAgentRuntime {\n\treadonly #conversationLength = 32 as number;\n\treadonly agentId: UUID;\n\treadonly character: Character;\n\tpublic databaseAdapter!: IDatabaseAdapter;\n\treadonly actions: Action[] = [];\n\treadonly evaluators: Evaluator[] = [];\n\treadonly providers: Provider[] = [];\n\treadonly plugins: Plugin[] = [];\n\tevents: Map<string, ((params: any) => Promise<void>)[]> = new Map();\n\tstateCache = new Map<\n\t\tUUID,\n\t\t{\n\t\t\tvalues: { [key: string]: any };\n\t\t\tdata: { [key: string]: any };\n\t\t\ttext: string;\n\t\t}\n\t>();\n\n\treadonly fetch = fetch;\n\tservices: Map<ServiceType, Service> = new Map();\n\n\tpublic adapter: IDatabaseAdapter;\n\n\tprivate readonly knowledgeRoot: string;\n\n\tmodels = new Map<string, ((params: any) => Promise<any>)[]>();\n\troutes: Route[] = [];\n\n\tprivate taskWorkers = new Map<string, TaskWorker>();\n\n\t// Event emitter methods\n\tprivate eventHandlers: Map<string, ((data: any) => void)[]> = new Map();\n\n\tconstructor(opts: {\n\t\tconversationLength?: number;\n\t\tagentId?: UUID;\n\t\tcharacter?: Character;\n\t\tplugins?: Plugin[];\n\t\tfetch?: typeof fetch;\n\t\tdatabaseAdapter?: IDatabaseAdapter;\n\t\tadapter?: IDatabaseAdapter;\n\t\tevents?: { [key: string]: ((params: any) => void)[] };\n\t\tignoreBootstrap?: boolean;\n\t}) {\n\t\t// use the character id if it exists, otherwise use the agentId if it is passed in, otherwise use the character name\n\t\tthis.agentId =\n\t\t\topts.character?.id ??\n\t\t\topts?.agentId ??\n\t\t\tstringToUuid(opts.character?.name ?? uuidv4());\n\t\tthis.character = opts.character;\n\n\t\tlogger.debug(`[AgentRuntime] Process working directory: ${process.cwd()}`);\n\n\t\tthis.knowledgeRoot =\n\t\t\ttypeof process !== \"undefined\" && process.cwd\n\t\t\t\t? join(process.cwd(), \"..\", \"characters\", \"knowledge\")\n\t\t\t\t: \"./characters/knowledge\";\n\n\t\tlogger.debug(`[AgentRuntime] Process knowledgeRoot: ${this.knowledgeRoot}`);\n\n\t\tthis.#conversationLength =\n\t\t\topts.conversationLength ?? this.#conversationLength;\n\n\t\tif (opts.databaseAdapter) {\n\t\t\tthis.registerDatabaseAdapter(opts.databaseAdapter);\n\t\t}\n\n\t\tlogger.success(`Agent ID: ${this.agentId}`);\n\n\t\tthis.fetch = (opts.fetch as typeof fetch) ?? this.fetch;\n\n\t\t// Initialize adapter from options or empty array if not provided\n\t\tthis.adapter = opts.adapter;\n\n\t\t// Register plugins from options or empty array\n\t\tconst plugins = opts?.plugins ?? [];\n\n\t\t// Add bootstrap plugin if not explicitly ignored\n\t\tif (!opts?.ignoreBootstrap) {\n\t\t\tplugins.push(bootstrapPlugin);\n\t\t}\n\n\t\t// Store plugins in the array but don't initialize them yet\n\t\tthis.plugins = plugins;\n\t}\n\n\t/**\n\t * Registers a plugin with the runtime and initializes its components\n\t * @param plugin The plugin to register\n\t */\n\tasync registerPlugin(plugin: Plugin): Promise<void> {\n\t\tif (!plugin) {\n\t\t\tthrow new Error(\"*** registerPlugin plugin is undefined\");\n\t\t}\n\n\t\t// Add to plugins array if not already present - but only if it was not passed there initially\n\t\t// (otherwise we can't add to readonly array)\n\t\tif (!this.plugins.some((p) => p.name === plugin.name)) {\n\t\t\t// Push to plugins array - this works because we're modifying the array, not reassigning it\n\t\t\tthis.plugins.push(plugin);\n\t\t}\n\n\t\t// Initialize the plugin if it has an init function\n\t\tif (plugin.init) {\n\t\t\ttry {\n\t\t\t\tawait plugin.init(plugin.config || {}, this);\n\t\t\t} catch (error) {\n\t\t\t\t// Check if the error is related to missing API keys\n\t\t\t\tconst errorMessage =\n\t\t\t\t\terror instanceof Error ? error.message : String(error);\n\n\t\t\t\tif (\n\t\t\t\t\terrorMessage.includes(\"API key\") ||\n\t\t\t\t\terrorMessage.includes(\"environment variables\") ||\n\t\t\t\t\terrorMessage.includes(\"Invalid plugin configuration\")\n\t\t\t\t) {\n\t\t\t\t\t// Instead of throwing an error, log a friendly message\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`Plugin ${plugin.name} requires configuration. ${errorMessage}`,\n\t\t\t\t\t);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\"Please check your environment variables and ensure all required API keys are set.\",\n\t\t\t\t\t);\n\t\t\t\t\tconsole.warn(\"You can set these in your .eliza/.env file.\");\n\n\t\t\t\t\t// We don't throw here, allowing the application to continue\n\t\t\t\t\t// with reduced functionality\n\t\t\t\t} else {\n\t\t\t\t\t// For other types of errors, rethrow\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin adapter\n\t\tif (plugin.adapter) {\n\t\t\tthis.registerDatabaseAdapter(plugin.adapter);\n\t\t}\n\n\t\t// Register plugin actions\n\t\tif (plugin.actions) {\n\t\t\tfor (const action of plugin.actions) {\n\t\t\t\tthis.registerAction(action);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin evaluators\n\t\tif (plugin.evaluators) {\n\t\t\tfor (const evaluator of plugin.evaluators) {\n\t\t\t\tthis.registerEvaluator(evaluator);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin providers\n\t\tif (plugin.providers) {\n\t\t\tfor (const provider of plugin.providers) {\n\t\t\t\tthis.registerContextProvider(provider);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin models\n\t\tif (plugin.models) {\n\t\t\tfor (const [modelType, handler] of Object.entries(plugin.models)) {\n\t\t\t\tthis.registerModel(\n\t\t\t\t\tmodelType as ModelType,\n\t\t\t\t\thandler as (params: any) => Promise<any>,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin routes\n\t\tif (plugin.routes) {\n\t\t\tfor (const route of plugin.routes) {\n\t\t\t\tthis.routes.push(route);\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin events\n\t\tif (plugin.events) {\n\t\t\tfor (const [eventName, eventHandlers] of Object.entries(plugin.events)) {\n\t\t\t\tfor (const eventHandler of eventHandlers) {\n\t\t\t\t\tthis.registerEvent(eventName, eventHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register plugin services\n\t\tif (plugin.services) {\n\t\t\tawait Promise.all(\n\t\t\t\tplugin.services.map((service) => this.registerService(service)),\n\t\t\t);\n\t\t}\n\t}\n\n\tgetAllServices(): Map<ServiceType, Service> {\n\t\treturn this.services;\n\t}\n\n\tasync stop() {\n\t\tlogger.debug(`runtime::stop - character ${this.character.name}`);\n\n\t\t// Stop all registered clients\n\t\tfor (const [serviceName, service] of this.services) {\n\t\t\tlogger.log(`runtime::stop - requesting service stop for ${serviceName}`);\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\tasync initialize() {\n\t\t// Track registered plugins to avoid duplicates\n\t\tconst registeredPluginNames = new Set<string>();\n\n\t\t// Load and register plugins from character configuration\n\t\tconst pluginRegistrationPromises = [];\n\n\t\tif (this.character.plugins) {\n\t\t\tconst characterPlugins = (await handlePluginImporting(\n\t\t\t\tthis.character.plugins,\n\t\t\t)) as Plugin[];\n\n\t\t\t// Register each character plugin\n\t\t\tfor (const plugin of characterPlugins) {\n\t\t\t\tif (plugin && !registeredPluginNames.has(plugin.name)) {\n\t\t\t\t\tregisteredPluginNames.add(plugin.name);\n\t\t\t\t\tpluginRegistrationPromises.push(this.registerPlugin(plugin));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register plugins that were provided in the constructor\n\t\tfor (const plugin of [...this.plugins]) {\n\t\t\tif (plugin && !registeredPluginNames.has(plugin.name)) {\n\t\t\t\tregisteredPluginNames.add(plugin.name);\n\t\t\t\tpluginRegistrationPromises.push(this.registerPlugin(plugin));\n\t\t\t}\n\t\t}\n\n\t\tawait this.adapter.init();\n\n\t\t// First create the agent entity directly\n\t\ttry {\n\t\t\t// Ensure agent exists first (this is critical for test mode)\n\t\t\tconst agentExists = await this.adapter.ensureAgentExists(\n\t\t\t\tthis.character as Partial<Agent>,\n\t\t\t);\n\n\t\t\t// Verify agent exists before proceeding\n\t\t\tconst agent = await this.adapter.getAgent(this.agentId);\n\t\t\tif (!agent) {\n\t\t\t\tthrow new Error(`Agent ${this.agentId} does not exist in database after ensureAgentExists call`);\n\t\t\t}\n\t\t\t\n\t\t\t// No need to transform agent's own ID\n\t\t\tconst agentEntity = await this.adapter.getEntityById(\n\t\t\t\tthis.agentId,\n\t\t\t);\n\n\t\t\tif (!agentEntity) {\n\t\t\t\tconst created = await this.adapter.createEntity({\n\t\t\t\t\tid: this.agentId,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t\tnames: Array.from(\n\t\t\t\t\t\tnew Set([this.character.name].filter(Boolean)),\n\t\t\t\t\t) as string[],\n\t\t\t\t\tmetadata: {},\n\t\t\t\t});\n\n\t\t\t\tif (!created) {\n\t\t\t\t\tthrow new Error(`Failed to create entity for agent ${this.agentId}`);\n\t\t\t\t}\n\n\t\t\t\tlogger.success(\n\t\t\t\t\t`Agent entity created successfully for ${this.character.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to create agent entity: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Create room for the agent and register all plugins in parallel\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tthis.ensureRoomExists({\n\t\t\t\t\tid: this.agentId,\n\t\t\t\t\tname: this.character.name,\n\t\t\t\t\tsource: \"self\",\n\t\t\t\t\ttype: ChannelType.SELF,\n\t\t\t\t}),\n\t\t\t\t...pluginRegistrationPromises,\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to initialize: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Add agent as participant in its own room\n\t\ttry {\n\t\t\t// No need to transform agent ID\n\t\t\tconst participants =\n\t\t\t\tawait this.adapter.getParticipantsForRoom(this.agentId);\n\t\t\tif (!participants.includes(this.agentId)) {\n\t\t\t\tconst added = await this.adapter.addParticipant(\n\t\t\t\t\tthis.agentId,\n\t\t\t\t\tthis.agentId,\n\t\t\t\t);\n\t\t\t\tif (!added) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Failed to add agent ${this.agentId} as participant to its own room`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlogger.success(\n\t\t\t\t\t`Agent ${this.character.name} linked to its own room successfully`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to add agent as participant: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Process character knowledge\n\t\tif (this.character?.knowledge && this.character.knowledge.length > 0) {\n\t\t\tconst stringKnowledge = this.character.knowledge.filter(\n\t\t\t\t(item): item is string => typeof item === \"string\",\n\t\t\t);\n\t\t\tawait this.processCharacterKnowledge(stringKnowledge);\n\t\t}\n\n\t\t// Check if TEXT_EMBEDDING model is registered\n\t\tconst embeddingModel = this.getModel(ModelTypes.TEXT_EMBEDDING);\n\t\tif (!embeddingModel) {\n\t\t\tlogger.warn(\n\t\t\t\t`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered. Skipping embedding dimension setup.`,\n\t\t\t);\n\t\t} else {\n\t\t\t// Only run ensureEmbeddingDimension if we have an embedding model\n\t\t\tawait this.ensureEmbeddingDimension();\n\t\t}\n\t}\n\n\tprivate async handleProcessingError(error: any, context: string) {\n\t\tlogger.error(\n\t\t\t`Error ${context}:`,\n\t\t\terror?.message || error || \"Unknown error\",\n\t\t);\n\t\tthrow error;\n\t}\n\n\tprivate async checkExistingKnowledge(knowledgeId: UUID): Promise<boolean> {\n\t\tconst existingDocument =\n\t\t\tawait this.getMemoryManager(\"documents\").getMemoryById(knowledgeId);\n\t\treturn !!existingDocument;\n\t}\n\n\tasync getKnowledge(message: Memory): Promise<KnowledgeItem[]> {\n\t\t// Add validation for message\n\t\tif (!message?.content?.text) {\n\t\t\tlogger.warn(\"Invalid message for knowledge query:\", {\n\t\t\t\tmessage,\n\t\t\t\tcontent: message?.content,\n\t\t\t\ttext: message?.content?.text,\n\t\t\t});\n\t\t\treturn [];\n\t\t}\n\n\t\t// Validate processed text\n\t\tif (!message?.content?.text || message?.content?.text.trim().length === 0) {\n\t\t\tlogger.warn(\"Empty text for knowledge query\");\n\t\t\treturn [];\n\t\t}\n\n\t\tconst embedding = await this.useModel(ModelTypes.TEXT_EMBEDDING, {\n\t\t\ttext: message?.content?.text,\n\t\t});\n\t\tconst fragments = await this.getMemoryManager(\"knowledge\").searchMemories({\n\t\t\tembedding,\n\t\t\troomId: message.agentId,\n\t\t\tcount: 5,\n\t\t\tmatch_threshold: 0.1,\n\t\t});\n\n\t\tconst uniqueSources = [\n\t\t\t...new Set(\n\t\t\t\tfragments.map((memory) => {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`Matched fragment: ${memory.content.text} with similarity: ${memory.similarity}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn memory.content.source;\n\t\t\t\t}),\n\t\t\t),\n\t\t];\n\n\t\tconst knowledgeDocuments = await Promise.all(\n\t\t\tuniqueSources.map((source) =>\n\t\t\t\tthis.getMemoryManager(\"documents\").getMemoryById(source as UUID),\n\t\t\t),\n\t\t);\n\n\t\treturn knowledgeDocuments\n\t\t\t.filter((memory) => memory !== null)\n\t\t\t.map((memory) => ({ id: memory.id, content: memory.content }));\n\t}\n\n\tasync addKnowledge(\n\t\titem: KnowledgeItem,\n\t\toptions = {\n\t\t\ttargetTokens: 3000,\n\t\t\toverlap: 200,\n\t\t\tmodelContextSize: 4096,\n\t\t},\n\t) {\n\t\t// First store the document\n\t\tconst documentMemory: Memory = {\n\t\t\tid: item.id,\n\t\t\tagentId: this.agentId,\n\t\t\troomId: this.agentId,\n\t\t\tentityId: this.agentId,\n\t\t\tcontent: item.content,\n\t\t\tmetadata: {\n\t\t\t\ttype: MemoryType.DOCUMENT,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t};\n\n\t\tawait this.getMemoryManager(\"documents\").createMemory(documentMemory);\n\n\t\t// Create fragments using splitChunks\n\t\tconst fragments = await splitChunks(\n\t\t\titem.content.text,\n\t\t\toptions.targetTokens,\n\t\t\toptions.overlap,\n\t\t);\n\n\t\t// Store each fragment with link to source document\n\t\tfor (let i = 0; i < fragments.length; i++) {\n\t\t\tconst fragmentMemory: Memory = {\n\t\t\t\tid: createUniqueUuid(this, `${item.id}-fragment-${i}`),\n\t\t\t\tagentId: this.agentId,\n\t\t\t\troomId: this.agentId,\n\t\t\t\tentityId: this.agentId,\n\t\t\t\tcontent: { text: fragments[i] },\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: MemoryType.FRAGMENT,\n\t\t\t\t\tdocumentId: item.id, // Link to source document\n\t\t\t\t\tposition: i, // Keep track of order\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tawait this.getMemoryManager(\"knowledge\").createMemory(fragmentMemory);\n\t\t}\n\t}\n\n\tasync processCharacterKnowledge(items: string[]) {\n\t\tfor (const item of items) {\n\t\t\ttry {\n\t\t\t\tconst knowledgeId = createUniqueUuid(this, item);\n\t\t\t\tif (await this.checkExistingKnowledge(knowledgeId)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"Processing knowledge for \",\n\t\t\t\t\tthis.character.name,\n\t\t\t\t\t\" - \",\n\t\t\t\t\titem.slice(0, 100),\n\t\t\t\t);\n\n\t\t\t\tawait this.addKnowledge({\n\t\t\t\t\tid: knowledgeId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: item,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait this.handleProcessingError(\n\t\t\t\t\terror,\n\t\t\t\t\t\"processing character knowledge\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tsetSetting(\n\t\tkey: string,\n\t\tvalue: string | boolean | null | any,\n\t\tsecret = false,\n\t) {\n\t\tif (secret) {\n\t\t\tthis.character.secrets[key] = value;\n\t\t} else {\n\t\t\tthis.character.settings[key] = value;\n\t\t}\n\t}\n\n\tgetSetting(key: string): string | boolean | null | any {\n\t\tconst value =\n\t\t\tthis.character.secrets?.[key] ||\n\t\t\tthis.character.settings?.[key] ||\n\t\t\tthis.character.settings?.secrets?.[key] ||\n\t\t\tsettings[key];\n\n\t\tif (value === \"true\") return true;\n\t\tif (value === \"false\") return false;\n\t\treturn value || null;\n\t}\n\n\t/**\n\t * Get the number of messages that are kept in the conversation buffer.\n\t * @returns The number of recent messages to be kept in memory.\n\t */\n\tgetConversationLength() {\n\t\treturn this.#conversationLength;\n\t}\n\n\tregisterDatabaseAdapter(adapter: IDatabaseAdapter) {\n\t\tif (this.adapter) {\n\t\t\tlogger.warn(\n\t\t\t\t\"Database adapter already registered. Additional adapters will be ignored. This may lead to unexpected behavior.\",\n\t\t\t);\n\t\t} else {\n\t\t\tthis.adapter = adapter;\n\t\t}\n\t}\n\n\t/**\n\t * Register a provider for the agent to use.\n\t * @param provider The provider to register.\n\t */\n\tregisterProvider(provider: Provider) {\n\t\tthis.providers.push(provider);\n\t}\n\n\t/**\n\t * Register an action for the agent to perform.\n\t * @param action The action to register.\n\t */\n\tregisterAction(action: Action) {\n\t\tlogger.success(\n\t\t\t`${this.character.name}(${this.agentId}) - Registering action: ${action.name}`,\n\t\t);\n\t\t// if an action with the same name already exists, throw a warning and don't add the new action\n\t\tif (this.actions.find((a) => a.name === action.name)) {\n\t\t\tlogger.warn(\n\t\t\t\t`${this.character.name}(${this.agentId}) - Action ${action.name} already exists. Skipping registration.`,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.actions.push(action);\n\t\t}\n\t}\n\n\t/**\n\t * Register an evaluator to assess and guide the agent's responses.\n\t * @param evaluator The evaluator to register.\n\t */\n\tregisterEvaluator(evaluator: Evaluator) {\n\t\tthis.evaluators.push(evaluator);\n\t}\n\n\t/**\n\t * Register a context provider to provide context for message generation.\n\t * @param provider The context provider to register.\n\t */\n\tregisterContextProvider(provider: Provider) {\n\t\tthis.providers.push(provider);\n\t}\n\n\t/**\n\t * Process the actions of a message.\n\t * @param message The message to process.\n\t * @param responses The array of response memories to process actions from.\n\t * @param state Optional state object for the action processing.\n\t * @param callback Optional callback handler for action results.\n\t */\n\tasync processActions(\n\t\tmessage: Memory,\n\t\tresponses: Memory[],\n\t\tstate?: State,\n\t\tcallback?: HandlerCallback,\n\t): Promise<void> {\n\t\tfor (const response of responses) {\n\t\t\tif (!response.content?.actions || response.content.actions.length === 0) {\n\t\t\t\tlogger.warn(\"No action found in the response content.\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst actions = response.content.actions;\n\n\t\t\tfunction normalizeAction(action: string) {\n\t\t\t\treturn action.toLowerCase().replace(\"_\", \"\");\n\t\t\t}\n\t\t\tlogger.success(\n\t\t\t\t`Found actions: ${this.actions.map((a) => normalizeAction(a.name))}`,\n\t\t\t);\n\n\t\t\tfor (const responseAction of actions) {\n\t\t\t\tstate = await this.composeState(message, [\"RECENT_MESSAGES\"]);\n\n\t\t\t\tlogger.success(`Calling action: ${responseAction}`);\n\t\t\t\tconst normalizedResponseAction = normalizeAction(responseAction);\n\t\t\t\tlet action = this.actions.find(\n\t\t\t\t\t(a: { name: string }) =>\n\t\t\t\t\t\tnormalizeAction(a.name).includes(normalizedResponseAction) || // the || is kind of a fuzzy match\n\t\t\t\t\t\tnormalizedResponseAction.includes(normalizeAction(a.name)), //\n\t\t\t\t);\n\n\t\t\t\tif (action) {\n\t\t\t\t\tlogger.success(`Found action: ${action?.name}`);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.error(`No action found for: ${responseAction}`);\n\t\t\t\t}\n\n\t\t\t\tif (!action) {\n\t\t\t\t\tlogger.info(\"Attempting to find action in similes.\");\n\t\t\t\t\tfor (const _action of this.actions) {\n\t\t\t\t\t\tconst simileAction = _action.similes?.find(\n\t\t\t\t\t\t\t(simile) =>\n\t\t\t\t\t\t\t\tsimile\n\t\t\t\t\t\t\t\t\t.toLowerCase()\n\t\t\t\t\t\t\t\t\t.replace(\"_\", \"\")\n\t\t\t\t\t\t\t\t\t.includes(normalizedResponseAction) ||\n\t\t\t\t\t\t\t\tnormalizedResponseAction.includes(\n\t\t\t\t\t\t\t\t\tsimile.toLowerCase().replace(\"_\", \"\"),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (simileAction) {\n\t\t\t\t\t\t\taction = _action;\n\t\t\t\t\t\t\tlogger.success(`Action found in similes: ${action.name}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!action) {\n\t\t\t\t\tlogger.error(\"No action found in\", JSON.stringify(response));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!action.handler) {\n\t\t\t\t\tlogger.error(`Action ${action.name} has no handler.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tlogger.info(`Executing handler for action: ${action.name}`);\n\n\t\t\t\t\tawait action.handler(this, message, state, {}, callback, responses);\n\n\t\t\t\t\tlogger.success(`Action ${action.name} executed successfully.`);\n\n\t\t\t\t\t// log to database\n\t\t\t\t\tthis.adapter.log({\n\t\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\ttype: \"action\",\n\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\taction: action.name,\n\t\t\t\t\t\t\tmessage: message.content.text,\n\t\t\t\t\t\t\tmessageId: message.id,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tresponses,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evaluate the message and state using the registered evaluators.\n\t * @param message The message to evaluate.\n\t * @param state The state of the agent.\n\t * @param didRespond Whether the agent responded to the message.~\n\t * @param callback The handler callback\n\t * @returns The results of the evaluation.\n\t */\n\tasync evaluate(\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\tdidRespond?: boolean,\n\t\tcallback?: HandlerCallback,\n\t\tresponses?: Memory[],\n\t) {\n\t\tconst evaluatorPromises = this.evaluators.map(\n\t\t\tasync (evaluator: Evaluator) => {\n\t\t\t\tif (!evaluator.handler) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (!didRespond && !evaluator.alwaysRun) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst result = await evaluator.validate(this, message, state);\n\n\t\t\t\tif (result) {\n\t\t\t\t\treturn evaluator;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t);\n\n\t\tconst evaluators = (await Promise.all(evaluatorPromises)).filter(\n\t\t\tBoolean,\n\t\t) as Evaluator[];\n\n\t\t// get the evaluators that were chosen by the response handler\n\n\t\tif (evaluators.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tstate = await this.composeState(message, [\"RECENT_MESSAGES\", \"EVALUATORS\"]);\n\n\t\tawait Promise.all(\n\t\t\tevaluators.map(async (evaluator) => {\n\t\t\t\tif (evaluator.handler) {\n\t\t\t\t\tawait evaluator.handler(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tcallback,\n\t\t\t\t\t\tresponses,\n\t\t\t\t\t);\n\t\t\t\t\t// log to database\n\t\t\t\t\tthis.adapter.log({\n\t\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\ttype: \"evaluator\",\n\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\tevaluator: evaluator.name,\n\t\t\t\t\t\t\tmessageId: message.id,\n\t\t\t\t\t\t\tmessage: message.content.text,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\treturn evaluators;\n\t}\n\n\tasync ensureParticipantInRoom(entityId: UUID, roomId: UUID) {\n\t\t// Make sure entity exists in database before adding as participant\n\t\tconst entity = await this.adapter.getEntityById(entityId);\n\t\tif (!entity) {\n\t\t\tthrow new Error(`User ${entityId} not found`);\n\t\t}\n\t\t// Get current participants\n\t\tconst participants =\n\t\t\tawait this.adapter.getParticipantsForRoom(roomId);\n\n\t\t// Only add if not already a participant\n\t\tif (!participants.includes(entityId)) {\n\t\t\t// Add participant using the tenant-specific ID that now exists in the entities table\n\t\t\tconst added = await this.adapter.addParticipant(\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t);\n\n\t\t\tif (!added) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to add participant ${entityId} to room ${roomId}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (entityId === this.agentId) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Agent ${this.character.name} linked to room ${roomId} successfully.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tlogger.log(`User ${entityId} linked to room ${roomId} successfully.`);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync ensureConnection({\n\t\tentityId,\n\t\troomId,\n\t\tuserName,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: {\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\tuserName?: string;\n\t\tname?: string;\n\t\tsource?: string;\n\t\ttype?: ChannelType;\n\t\tchannelId?: string;\n\t\tserverId?: string;\n\t\tworldId?: UUID;\n\t}) {\n\t\tif (entityId === this.agentId) {\n\t\t\tthrow new Error(\"Agent should not connect to itself\");\n\t\t}\n\n\t\tif (!worldId && serverId) {\n\t\t\tworldId = createUniqueUuid(this, serverId);\n\t\t}\n\n\t\tconst names = [name, userName];\n\t\tconst metadata = {\n\t\t\t[source]: {\n\t\t\t\tname: name,\n\t\t\t\tuserName: userName,\n\t\t\t},\n\t\t};\n\n\t\tconst entity = await this.adapter.getEntityById(entityId);\n\n\t\tif (!entity) {\n\t\t\tawait this.adapter.createEntity({\n\t\t\t\tid: entityId,\n\t\t\t\tnames,\n\t\t\t\tmetadata,\n\t\t\t\tagentId: this.agentId,\n\t\t\t});\n\t\t}\n\n\t\t// Ensure world exists if worldId is provided\n\t\tif (worldId) {\n\t\t\tawait this.ensureWorldExists({\n\t\t\t\tid: worldId,\n\t\t\t\tname: serverId\n\t\t\t\t\t? `World for server ${serverId}`\n\t\t\t\t\t: `World for room ${roomId}`,\n\t\t\t\tagentId: this.agentId,\n\t\t\t\tserverId: serverId || \"default\",\n\t\t\t\tmetadata,\n\t\t\t});\n\t\t}\n\n\t\t// Ensure room exists\n\t\tawait this.ensureRoomExists({\n\t\t\tid: roomId,\n\t\t\tsource,\n\t\t\ttype,\n\t\t\tchannelId,\n\t\t\tserverId,\n\t\t\tworldId,\n\t\t});\n\n\t\t// Now add participants using the original IDs (will be transformed internally)\n\t\ttry {\n\t\t\tawait this.ensureParticipantInRoom(entityId, roomId);\n\t\t\tawait this.ensureParticipantInRoom(this.agentId, roomId);\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to add participants: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the existence of a world.\n\t */\n\tasync ensureWorldExists({ id, name, serverId, metadata }: World) {\n\t\ttry {\n\t\t\tconst world = await this.adapter.getWorld(id);\n\t\t\tif (!world) {\n\t\t\t\tlogger.info(\"Creating world:\", {\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tserverId,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t});\n\t\t\t\tawait this.adapter.createWorld({\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tagentId: this.agentId,\n\t\t\t\t\tserverId: serverId || \"default\",\n\t\t\t\t\tmetadata,\n\t\t\t\t});\n\t\t\t\tlogger.info(`World ${id} created successfully.`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to ensure world exists: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the existence of a room between the agent and a user. If no room exists, a new room is created and the user\n\t * and agent are added as participants. The room ID is returned.\n\t * @param entityId - The user ID to create a room with.\n\t * @returns The room ID of the room between the agent and the user.\n\t * @throws An error if the room cannot be created.\n\t */\n\tasync ensureRoomExists({\n\t\tid,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room) {\n\t\tconst room = await this.adapter.getRoom(id);\n\t\tif (!room) {\n\t\t\tawait this.adapter.createRoom({\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\tagentId: this.agentId,\n\t\t\t\tsource,\n\t\t\t\ttype,\n\t\t\t\tchannelId,\n\t\t\t\tserverId,\n\t\t\t\tworldId,\n\t\t\t});\n\t\t\tlogger.log(`Room ${id} created successfully.`);\n\t\t}\n\t}\n\n\t/**\n\t * Composes the agent's state by gathering data from enabled providers.\n\t * @param message - The message to use as context for state composition\n\t * @param filterList - Optional list of provider names to include, filtering out all others\n\t * @param includeList - Optional list of private provider names to include that would otherwise be filtered out\n\t * @returns A State object containing provider data, values, and text\n\t */\n\tasync composeState(\n\t\tmessage: Memory,\n\t\tfilterList: string[] | null = null, // only get providers that are in the filterList\n\t\tincludeList: string[] | null = null, // include providers that are private, dynamic or otherwise not included by default\n\t): Promise<State> {\n\t\t// Get cached state for this message ID first\n\t\tconst cachedState = (await this.stateCache.get(message.id)) || {\n\t\t\tvalues: {},\n\t\t\tdata: {},\n\t\t\ttext: \"\",\n\t\t};\n\n\t\t// Get existing provider names from cache (if any)\n\t\tconst existingProviderNames = cachedState.data.providers\n\t\t\t? Object.keys(cachedState.data.providers)\n\t\t\t: [];\n\n\t\t// Step 1: Determine base set of providers to fetch\n\t\tconst providerNames = new Set<string>();\n\n\t\tif (filterList && filterList.length > 0) {\n\t\t\t// If filter list provided, start with just those providers\n\t\t\tfilterList.forEach((name) => providerNames.add(name));\n\t\t} else {\n\t\t\t// Otherwise, start with all non-private, non-dynamic providers that aren't cached\n\t\t\tthis.providers\n\t\t\t\t.filter(\n\t\t\t\t\t(p) =>\n\t\t\t\t\t\t!p.private && !p.dynamic && !existingProviderNames.includes(p.name),\n\t\t\t\t)\n\t\t\t\t.forEach((p) => providerNames.add(p.name));\n\t\t}\n\n\t\t// Step 2: Always add providers from include list\n\t\tif (includeList && includeList.length > 0) {\n\t\t\tincludeList.forEach((name) => providerNames.add(name));\n\t\t}\n\n\t\t// Get the actual provider objects and sort by position\n\t\tconst providersToGet = Array.from(\n\t\t\tnew Set(this.providers.filter((p) => providerNames.has(p.name))),\n\t\t).sort((a, b) => (a.position || 0) - (b.position || 0));\n\n\t\t// Fetch data from selected providers\n\t\tconst providerData = await Promise.all(\n\t\t\tprovidersToGet.map(async (provider) => {\n\t\t\t\tconst start = Date.now();\n\t\t\t\tconst result = await provider.get(this, message, cachedState);\n\t\t\t\tconst duration = Date.now() - start;\n\t\t\t\tlogger.warn(`${provider.name} Provider took ${duration}ms to respond`);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tproviderName: provider.name,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Extract existing provider data from cache\n\t\tconst existingProviderData = cachedState.data.providers || {};\n\n\t\t// Create a combined provider values structure that preserves all cached data\n\t\t// but updates with any newly fetched provider data\n\t\tconst combinedValues = { ...existingProviderData };\n\n\t\t// Update with newly fetched provider data\n\t\tfor (const result of providerData) {\n\t\t\tcombinedValues[result.providerName] = result.values || {};\n\t\t}\n\n\t\t// Collect provider text from newly fetched providers\n\t\tconst newProvidersText = providerData\n\t\t\t.map((result) => result.text)\n\t\t\t.filter((text) => text !== \"\")\n\t\t\t.join(\"\\n\");\n\n\t\t// Combine with existing text if available\n\t\tlet providersText = \"\";\n\t\tif (cachedState.text && newProvidersText) {\n\t\t\tprovidersText = `${cachedState.text}\\n${newProvidersText}`;\n\t\t} else if (newProvidersText) {\n\t\t\tprovidersText = newProvidersText;\n\t\t} else if (cachedState.text) {\n\t\t\tprovidersText = cachedState.text;\n\t\t}\n\n\t\t// Prepare final values\n\t\tconst values = {\n\t\t\t...(cachedState.values || {}),\n\t\t};\n\n\t\t// Safely merge all provider values\n\t\tfor (const providerName in combinedValues) {\n\t\t\tconst providerValues = combinedValues[providerName];\n\t\t\tif (providerValues && typeof providerValues === \"object\") {\n\t\t\t\tObject.assign(values, providerValues);\n\t\t\t}\n\t\t}\n\n\t\t// Assemble and cache the new state\n\t\tconst newState = {\n\t\t\tvalues: {\n\t\t\t\t...values,\n\t\t\t\tproviders: providersText,\n\t\t\t},\n\t\t\tdata: {\n\t\t\t\t...(cachedState.data || {}),\n\t\t\t\tproviders: combinedValues,\n\t\t\t},\n\t\t\ttext: providersText,\n\t\t} as State;\n\n\t\t// Cache the result for future use\n\t\tthis.stateCache.set(message.id, newState);\n\t\treturn newState;\n\t}\n\n\tgetMemoryManager(tableName: string): IMemoryManager | null {\n\t\treturn new MemoryManager({\n\t\t\truntime: this,\n\t\t\ttableName: tableName,\n\t\t});\n\t}\n\n\tgetService<T extends Service>(service: ServiceType): T | null {\n\t\tconst serviceInstance = this.services.get(service);\n\t\tif (!serviceInstance) {\n\t\t\tlogger.warn(`Service ${service} not found`);\n\t\t\treturn null;\n\t\t}\n\t\treturn serviceInstance as T;\n\t}\n\n\tasync registerService(service: typeof Service): Promise<void> {\n\t\tconst serviceType = service.serviceType as ServiceType;\n\t\tif (!serviceType) {\n\t\t\treturn;\n\t\t}\n\t\tlogger.log(\n\t\t\t`${this.character.name}(${this.agentId}) - Registering service:`,\n\t\t\tserviceType,\n\t\t);\n\n\t\tif (this.services.has(serviceType)) {\n\t\t\tlogger.warn(\n\t\t\t\t`${this.character.name}(${this.agentId}) - Service ${serviceType} is already registered. Skipping registration.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst serviceInstance = await service.start(this);\n\n\t\t// Add the service to the services map\n\t\tthis.services.set(serviceType, serviceInstance);\n\t\tlogger.success(\n\t\t\t`${this.character.name}(${this.agentId}) - Service ${serviceType} registered successfully`,\n\t\t);\n\t}\n\n\tregisterModel(modelType: ModelType, handler: (params: any) => Promise<any>) {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tif (!this.models.has(modelKey)) {\n\t\t\tthis.models.set(modelKey, []);\n\t\t}\n\t\tthis.models.get(modelKey)?.push(handler);\n\t}\n\n\tgetModel(\n\t\tmodelType: ModelType,\n\t): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tconst models = this.models.get(modelKey);\n\t\tif (!models?.length) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn models[0];\n\t}\n\n\t/**\n\t * Use a model with strongly typed parameters and return values based on model type\n\t * @template T - The model type to use\n\t * @template R - The expected return type, defaults to the type defined in ModelResultMap[T]\n\t * @param {T} modelType - The type of model to use\n\t * @param {ModelParamsMap[T] | any} params - The parameters for the model, typed based on model type\n\t * @returns {Promise<R>} - The model result, typed based on the provided generic type parameter\n\t */\n\tasync useModel<T extends ModelType, R = ModelResultMap[T]>(\n\t\tmodelType: T,\n\t\tparams: Omit<ModelParamsMap[T], \"runtime\"> | any,\n\t): Promise<R> {\n\t\tconst modelKey =\n\t\t\ttypeof modelType === \"string\" ? modelType : ModelTypes[modelType];\n\t\tconst model = this.getModel(modelKey);\n\t\tif (!model) {\n\t\t\tthrow new Error(`No handler found for delegate type: ${modelKey}`);\n\t\t}\n\n\t\t// Log input parameters\n\t\tlogger.debug(\n\t\t\t`[useModel] ${modelKey} input:`,\n\t\t\tJSON.stringify(params, null, 2)\n\t\t);\n\n\t\t// Handle different parameter formats\n\t\tlet paramsWithRuntime: any;\n\n\t\t// If params is a simple value (string, number, etc.), pass it directly\n\t\tif (\n\t\t\tparams === null ||\n\t\t\tparams === undefined ||\n\t\t\ttypeof params !== \"object\" ||\n\t\t\tArray.isArray(params)\n\t\t) {\n\t\t\tparamsWithRuntime = params;\n\t\t} else {\n\t\t\t// Otherwise inject the runtime\n\t\t\tparamsWithRuntime = {\n\t\t\t\t...params,\n\t\t\t\truntime: this,\n\t\t\t};\n\t\t}\n\n\t\t// Start timer\n\t\tconst startTime = performance.now();\n\n\t\t// Call the model\n\t\tconst response = await model(this, paramsWithRuntime);\n\n\t\t// Calculate elapsed time\n\t\tconst elapsedTime = performance.now() - startTime;\n\n\t\t// Log timing\n\t\tlogger.info(\n\t\t\t`[useModel] ${modelKey} completed in ${elapsedTime.toFixed(2)}ms`\n\t\t);\n\n\t\t// Log response\n\t\tlogger.debug(\n\t\t\t`[useModel] ${modelKey} output:`,\n\t\t\tJSON.stringify(response, null, 2)\n\t\t);\n\n\t\t// Log the model usage\n\t\tthis.adapter.log({\n\t\t\tentityId: this.agentId,\n\t\t\troomId: this.agentId,\n\t\t\tbody: {\n\t\t\t\tmodelType,\n\t\t\t\tmodelKey,\n\t\t\t\tparams: params\n\t\t\t\t\t? typeof params === \"object\"\n\t\t\t\t\t\t? Object.keys(params)\n\t\t\t\t\t\t: typeof params\n\t\t\t\t\t: null,\n\t\t\t\tresponse:\n\t\t\t\t\tArray.isArray(response) &&\n\t\t\t\t\tresponse.every((x) => typeof x === \"number\")\n\t\t\t\t\t\t? \"[array]\"\n\t\t\t\t\t\t: response,\n\t\t\t},\n\t\t\ttype: `useModel:${modelKey}`,\n\t\t});\n\n\t\treturn response as R;\n\t}\n\n\tregisterEvent(event: string, handler: (params: any) => Promise<void>) {\n\t\tif (!this.events.has(event)) {\n\t\t\tthis.events.set(event, []);\n\t\t}\n\t\tthis.events.get(event)?.push(handler);\n\t}\n\n\tgetEvent(event: string): ((params: any) => Promise<void>)[] | undefined {\n\t\treturn this.events.get(event);\n\t}\n\n\tasync emitEvent(event: string | string[], params: any) {\n\t\t// Handle both single event string and array of event strings\n\t\tconst events = Array.isArray(event) ? event : [event];\n\n\t\t// Call handlers for each event\n\t\tfor (const eventName of events) {\n\t\t\tconst eventHandlers = this.events.get(eventName);\n\n\t\t\tif (eventHandlers) {\n\t\t\t\tawait Promise.all(eventHandlers.map(handler => handler(params)));\n\t\t\t}\n\t\t}\n\t}\n\n\tasync ensureEmbeddingDimension() {\n\t\tlogger.debug(\n\t\t\t`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`,\n\t\t);\n\n\t\tif (!this.adapter) {\n\t\t\tthrow new Error(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tconst model = this.getModel(ModelTypes.TEXT_EMBEDDING);\n\t\t\tif (!model) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Getting embedding dimensions`,\n\t\t\t);\n\t\t\tconst embedding = await this.useModel(ModelTypes.TEXT_EMBEDDING, null);\n\n\t\t\tif (!embedding || !embedding.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[AgentRuntime][${this.character.name}] Invalid embedding received`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${embedding.length}`,\n\t\t\t);\n\t\t\tawait this.adapter.ensureEmbeddingDimension(\n\t\t\t\tembedding.length,\n\t\t\t);\n\t\t\tlogger.debug(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.info(\n\t\t\t\t`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension:`,\n\t\t\t\terror,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tregisterTaskWorker(taskHandler: TaskWorker): void {\n\t\tif (this.taskWorkers.has(taskHandler.name)) {\n\t\t\tlogger.warn(\n\t\t\t\t`Task definition ${taskHandler.name} already registered. Will be overwritten.`,\n\t\t\t);\n\t\t}\n\t\tthis.taskWorkers.set(taskHandler.name, taskHandler);\n\t}\n\n\t/**\n\t * Get a task worker by name\n\t */\n\tgetTaskWorker(name: string): TaskWorker | undefined {\n\t\treturn this.taskWorkers.get(name);\n\t}\n\n\t// Implement database adapter methods\n\t\n\tget db(): any {\n\t\treturn this.adapter.db;\n\t}\n\t\n\tasync init(): Promise<void> {\n\t\tawait this.adapter.init();\n\t}\n\t\n\tasync close(): Promise<void> {\n\t\tawait this.adapter.close();\n\t}\n\t\n\tasync getAgent(agentId: UUID): Promise<Agent | null> {\n\t\treturn await this.adapter.getAgent(agentId);\n\t}\n\t\n\tasync getAgents(): Promise<Agent[]> {\n\t\treturn await this.adapter.getAgents();\n\t}\n\t\n\tasync createAgent(agent: Partial<Agent>): Promise<boolean> {\n\t\treturn await this.adapter.createAgent(agent);\n\t}\n\t\n\tasync updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {\n\t\treturn await this.adapter.updateAgent(agentId, agent);\n\t}\n\t\n\tasync deleteAgent(agentId: UUID): Promise<boolean> {\n\t\treturn await this.adapter.deleteAgent(agentId);\n\t}\n\t\n\tasync ensureAgentExists(agent: Partial<Agent>): Promise<void> {\n\t\tawait this.adapter.ensureAgentExists(agent);\n\t}\n\t\n\tasync getEntityById(entityId: UUID): Promise<Entity | null> {\n\t\treturn await this.adapter.getEntityById(entityId);\n\t}\n\t\n\tasync getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {\n\t\treturn await this.adapter.getEntitiesForRoom(roomId, includeComponents);\n\t}\n\t\n\tasync createEntity(entity: Entity): Promise<boolean> {\n\t\treturn await this.adapter.createEntity(entity);\n\t}\n\t\n\tasync updateEntity(entity: Entity): Promise<void> {\n\t\tawait this.adapter.updateEntity(entity);\n\t}\n\t\n\tasync getComponent(entityId: UUID, type: string, worldId?: UUID, sourceEntityId?: UUID): Promise<Component | null> {\n\t\treturn await this.adapter.getComponent(entityId, type, worldId, sourceEntityId);\n\t}\n\t\n\tasync getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {\n\t\treturn await this.adapter.getComponents(entityId, worldId, sourceEntityId);\n\t}\n\t\n\tasync createComponent(component: Component): Promise<boolean> {\n\t\treturn await this.adapter.createComponent(component);\n\t}\n\t\n\tasync updateComponent(component: Component): Promise<void> {\n\t\tawait this.adapter.updateComponent(component);\n\t}\n\t\n\tasync deleteComponent(componentId: UUID): Promise<void> {\n\t\tawait this.adapter.deleteComponent(componentId);\n\t}\n\t\n\tasync getMemories(params: {\n\t\troomId: UUID;\n\t\tcount?: number;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t\tstart?: number;\n\t\tend?: number;\n\t}): Promise<Memory[]> {\n\t\treturn await this.adapter.getMemories(params);\n\t}\n\t\n\tasync getMemoryById(id: UUID): Promise<Memory | null> {\n\t\treturn await this.adapter.getMemoryById(id);\n\t}\n\t\n\tasync getMemoriesByIds(ids: UUID[], tableName?: string): Promise<Memory[]> {\n\t\treturn await this.adapter.getMemoriesByIds(ids, tableName);\n\t}\n\t\n\tasync getMemoriesByRoomIds(params: {\n\t\ttableName: string;\n\t\troomIds: UUID[];\n\t\tlimit?: number;\n\t}): Promise<Memory[]> {\n\t\treturn await this.adapter.getMemoriesByRoomIds(params);\n\t}\n\t\n\tasync getCachedEmbeddings(params: {\n\t\tquery_table_name: string;\n\t\tquery_threshold: number;\n\t\tquery_input: string;\n\t\tquery_field_name: string;\n\t\tquery_field_sub_name: string;\n\t\tquery_match_count: number;\n\t}): Promise<{ embedding: number[]; levenshtein_score: number }[]> {\n\t\treturn await this.adapter.getCachedEmbeddings(params);\n\t}\n\t\n\tasync log(params: {\n\t\tbody: { [key: string]: unknown };\n\t\tentityId: UUID;\n\t\troomId: UUID;\n\t\ttype: string;\n\t}): Promise<void> {\n\t\tawait this.adapter.log(params);\n\t}\n\t\n\tasync searchMemories(params: {\n\t\tembedding: number[];\n\t\tmatch_threshold?: number;\n\t\tcount?: number;\n\t\troomId?: UUID;\n\t\tunique?: boolean;\n\t\ttableName: string;\n\t}): Promise<Memory[]> {\n\t\treturn await this.adapter.searchMemories(params);\n\t}\n\t\n\tasync createMemory(memory: Memory, tableName: string, unique?: boolean): Promise<UUID> {\n\t\treturn await this.adapter.createMemory(memory, tableName, unique);\n\t}\n\t\n\tasync removeMemory(memoryId: UUID, tableName: string): Promise<void> {\n\t\tawait this.adapter.removeMemory(memoryId, tableName);\n\t}\n\t\n\tasync removeAllMemories(roomId: UUID, tableName: string): Promise<void> {\n\t\tawait this.adapter.removeAllMemories(roomId, tableName);\n\t}\n\t\n\tasync countMemories(roomId: UUID, unique?: boolean, tableName?: string): Promise<number> {\n\t\treturn await this.adapter.countMemories(roomId, unique, tableName);\n\t}\n\t\n\tasync createWorld(world: World): Promise<UUID> {\n\t\treturn await this.adapter.createWorld(world);\n\t}\n\t\n\tasync getWorld(id: UUID): Promise<World | null> {\n\t\treturn await this.adapter.getWorld(id);\n\t}\n\t\n\tasync getAllWorlds(): Promise<World[]> {\n\t\treturn await this.adapter.getAllWorlds();\n\t}\n\t\n\tasync updateWorld(world: World): Promise<void> {\n\t\tawait this.adapter.updateWorld(world);\n\t}\n\t\n\tasync getRoom(roomId: UUID): Promise<Room | null> {\n\t\treturn await this.adapter.getRoom(roomId);\n\t}\n\t\n\tasync createRoom({\n\t\tid,\n\t\tname,\n\t\tsource,\n\t\ttype,\n\t\tchannelId,\n\t\tserverId,\n\t\tworldId,\n\t}: Room): Promise<UUID> {\n\t\treturn await this.adapter.createRoom({\n\t\t\tid,\n\t\t\tname,\n\t\t\tsource,\n\t\t\ttype,\n\t\t\tchannelId,\n\t\t\tserverId,\n\t\t\tworldId,\n\t\t});\n\t}\n\t\n\tasync deleteRoom(roomId: UUID): Promise<void> {\n\t\tawait this.adapter.deleteRoom(roomId);\n\t}\n\t\n\tasync updateRoom(room: Room): Promise<void> {\n\t\tawait this.adapter.updateRoom(room);\n\t}\n\t\n\tasync getRoomsForParticipant(entityId: UUID): Promise<UUID[]> {\n\t\treturn await this.adapter.getRoomsForParticipant(entityId);\n\t}\n\t\n\tasync getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]> {\n\t\treturn await this.adapter.getRoomsForParticipants(userIds);\n\t}\n\t\n\tasync getRooms(worldId: UUID): Promise<Room[]> {\n\t\treturn await this.adapter.getRooms(worldId);\n\t}\n\t\n\tasync addParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n\t\treturn await this.adapter.addParticipant(entityId, roomId);\n\t}\n\t\n\tasync removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n\t\treturn await this.adapter.removeParticipant(entityId, roomId);\n\t}\n\t\n\tasync getParticipantsForEntity(entityId: UUID): Promise<Participant[]> {\n\t\treturn await this.adapter.getParticipantsForEntity(entityId);\n\t}\n\t\n\tasync getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {\n\t\treturn await this.adapter.getParticipantsForRoom(roomId);\n\t}\n\t\n\tasync getParticipantUserState(roomId: UUID, entityId: UUID): Promise<\"FOLLOWED\" | \"MUTED\" | null> {\n\t\treturn await this.adapter.getParticipantUserState(roomId, entityId);\n\t}\n\t\n\tasync setParticipantUserState(roomId: UUID, entityId: UUID, state: \"FOLLOWED\" | \"MUTED\" | null): Promise<void> {\n\t\tawait this.adapter.setParticipantUserState(roomId, entityId, state);\n\t}\n\t\n\tasync createRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t\ttags?: string[];\n\t\tmetadata?: { [key: string]: any };\n\t}): Promise<boolean> {\n\t\treturn await this.adapter.createRelationship(params);\n\t}\n\t\n\tasync updateRelationship(relationship: Relationship): Promise<void> {\n\t\tawait this.adapter.updateRelationship(relationship);\n\t}\n\t\n\tasync getRelationship(params: {\n\t\tsourceEntityId: UUID;\n\t\ttargetEntityId: UUID;\n\t}): Promise<Relationship | null> {\n\t\treturn await this.adapter.getRelationship(params);\n\t}\n\t\n\tasync getRelationships(params: {\n\t\tentityId: UUID;\n\t\ttags?: string[];\n\t}): Promise<Relationship[]> {\n\t\treturn await this.adapter.getRelationships(params);\n\t}\n\t\n\tasync getCache<T>(key: string): Promise<T | undefined> {\n\t\treturn await this.adapter.getCache<T>(key);\n\t}\n\t\n\tasync setCache<T>(key: string, value: T): Promise<boolean> {\n\t\treturn await this.adapter.setCache<T>(key, value);\n\t}\n\t\n\tasync deleteCache(key: string): Promise<boolean> {\n\t\treturn await this.adapter.deleteCache(key);\n\t}\n\t\n\tasync createTask(task: Task): Promise<UUID> {\n\t\treturn await this.adapter.createTask(task);\n\t}\n\t\n\tasync getTasks(params: { roomId?: UUID; tags?: string[] }): Promise<Task[]> {\n\t\treturn await this.adapter.getTasks(params);\n\t}\n\t\n\tasync getTask(id: UUID): Promise<Task | null> {\n\t\treturn await this.adapter.getTask(id);\n\t}\n\t\n\tasync getTasksByName(name: string): Promise<Task[]> {\n\t\treturn await this.adapter.getTasksByName(name);\n\t}\n\t\n\tasync updateTask(id: UUID, task: Partial<Task>): Promise<void> {\n\t\tawait this.adapter.updateTask(id, task);\n\t}\n\t\n\tasync deleteTask(id: UUID): Promise<void> {\n\t\tawait this.adapter.deleteTask(id);\n\t}\n\n\t// Event emitter methods\n\ton(event: string, callback: (data: any) => void): void {\n\t\tif (!this.eventHandlers.has(event)) {\n\t\t\tthis.eventHandlers.set(event, []);\n\t\t}\n\t\tthis.eventHandlers.get(event)!.push(callback);\n\t}\n\n\toff(event: string, callback: (data: any) => void): void {\n\t\tif (!this.eventHandlers.has(event)) {\n\t\t\treturn;\n\t\t}\n\t\tconst handlers = this.eventHandlers.get(event)!;\n\t\tconst index = handlers.indexOf(callback);\n\t\tif (index !== -1) {\n\t\t\thandlers.splice(index, 1);\n\t\t}\n\t}\n\n\temit(event: string, data: any): void {\n\t\tif (!this.eventHandlers.has(event)) {\n\t\t\treturn;\n\t\t}\n\t\tfor (const handler of this.eventHandlers.get(event)!) {\n\t\t\thandler(data);\n\t\t}\n\t}\n}\n","import type { UUID } from \"node:crypto\";\nimport { v4 } from \"uuid\";\nimport { choiceAction } from \"./actions/choice\";\nimport { followRoomAction } from \"./actions/followRoom\";\nimport { ignoreAction } from \"./actions/ignore\";\nimport { muteRoomAction } from \"./actions/muteRoom\";\nimport { noneAction } from \"./actions/none\";\nimport { replyAction } from \"./actions/reply\";\nimport updateRoleAction from \"./actions/roles\";\nimport { sendMessageAction } from \"./actions/sendMessage\";\nimport updateSettingsAction from \"./actions/settings\";\nimport { unfollowRoomAction } from \"./actions/unfollowRoom\";\nimport { unmuteRoomAction } from \"./actions/unmuteRoom\";\nimport { updateEntityAction } from \"./actions/updateEntity\";\nimport { createUniqueUuid } from \"./entities\";\nimport { reflectionEvaluator } from \"./evaluators/reflection\";\nimport { logger } from \"./logger\";\nimport {\n\tcomposePromptFromState,\n\tmessageHandlerTemplate,\n\tparseJSONObjectFromText,\n\tshouldRespondTemplate,\n} from \"./prompts\";\nimport { actionsProvider } from \"./providers/actions\";\nimport { anxietyProvider } from \"./providers/anxiety\";\nimport { attachmentsProvider } from \"./providers/attachments\";\nimport { capabilitiesProvider } from \"./providers/capabilities\";\nimport { characterProvider } from \"./providers/character\";\nimport { choiceProvider } from \"./providers/choice\";\nimport { entitiesProvider } from \"./providers/entities\";\nimport { evaluatorsProvider } from \"./providers/evaluators\";\nimport { factsProvider } from \"./providers/facts\";\nimport { knowledgeProvider } from \"./providers/knowledge\";\nimport { providersProvider } from \"./providers/providers\";\nimport { recentMessagesProvider } from \"./providers/recentMessages\";\nimport { relationshipsProvider } from \"./providers/relationships\";\nimport { roleProvider } from \"./providers/roles\";\nimport { settingsProvider } from \"./providers/settings\";\nimport { timeProvider } from \"./providers/time\";\nimport { ScenarioService } from \"./services/scenario\";\nimport { TaskService } from \"./services/task\";\nimport {\n\ttype ActionEventPayload,\n\ttype ChannelType,\n\ttype Content,\n\ttype Entity,\n\ttype EntityPayload,\n\ttype EvaluatorEventPayload,\n\tEventTypes,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype MessagePayload,\n\tModelTypes,\n\ttype Plugin,\n\ttype Room,\n\ttype World,\n\ttype WorldPayload,\n} from \"./types\";\n\n/**\n * Represents the parameters passed when a server is joined.\n * @typedef {Object} ServerJoinedParams\n * @property {IAgentRuntime} runtime - The agent runtime object.\n * @property {any} world - The platform-specific server object.\n * @property {string} source - The source platform of the server (e.g. \"discord\", \"telegram\").\n */\ntype ServerJoinedParams = {\n\truntime: IAgentRuntime;\n\tworld: any; // Platform-specific server object\n\tsource: string; // \"discord\", \"telegram\", etc.\n};\n\n// Add this to your types.ts file\n/**\n * Represents the parameters required when a server is connected.\n * @typedef { Object } ServerConnectedParams\n * @property { IAgentRuntime } runtime - The runtime of the agent.\n * @property { World } world - The world connected to the server.\n * @property {Room[]} rooms - The array of rooms connected to the server.\n * @property {Entity[]} users - The array of users connected to the server.\n * @property { string } source - The source of the connection.\n */\ntype ServerConnectedParams = {\n\truntime: IAgentRuntime;\n\tworld: World;\n\trooms: Room[];\n\tusers: Entity[];\n\tsource: string;\n};\n\n/**\n * Represents the parameters when a user joins a server.\n * @typedef {Object} UserJoinedParams\n * @property {IAgentRuntime} runtime - The runtime object for the agent.\n * @property {any} user - The user who joined.\n * @property {string} serverId - The ID of the server the user joined.\n * @property {UUID} entityId - The entity ID of the user.\n * @property {string} channelId - The ID of the channel the user joined.\n * @property {ChannelType} channelType - The type of channel the user joined.\n * @property {string} source - The source of the user joining.\n */\ntype UserJoinedParams = {\n\truntime: IAgentRuntime;\n\tuser: any;\n\tserverId: string;\n\tentityId: UUID;\n\tchannelId: string;\n\tchannelType: ChannelType;\n\tsource: string;\n};\n\n/**\n * Represents the parameters for a message received handler.\n * @typedef {Object} MessageReceivedHandlerParams\n * @property {IAgentRuntime} runtime - The agent runtime associated with the message.\n * @property {Memory} message - The message received.\n * @property {HandlerCallback} callback - The callback function to be executed after handling the message.\n */\ntype MessageReceivedHandlerParams = {\n\truntime: IAgentRuntime;\n\tmessage: Memory;\n\tcallback: HandlerCallback;\n};\n\nconst latestResponseIds = new Map<string, Map<string, string>>();\n\n/**\n * Handles incoming messages and generates responses based on the provided runtime and message information.\n *\n * @param {MessageReceivedHandlerParams} params - The parameters needed for message handling, including runtime, message, and callback.\n * @returns {Promise<void>} - A promise that resolves once the message handling and response generation is complete.\n */\nconst messageReceivedHandler = async ({\n\truntime,\n\tmessage,\n\tcallback,\n}: MessageReceivedHandlerParams) => {\n\t// Generate a new response ID\n\tconst responseId = v4();\n\t// Get or create the agent-specific map\n\tif (!latestResponseIds.has(runtime.agentId)) {\n\t\tlatestResponseIds.set(runtime.agentId, new Map());\n\t}\n\tconst agentResponses = latestResponseIds.get(runtime.agentId)!;\n\n\t// Set this as the latest response ID for this agent+room\n\tagentResponses.set(message.roomId, responseId);\n\n\t// Generate a unique run ID for tracking this message handler execution\n\tconst runId = v4() as UUID;\n\tconst startTime = Date.now();\n\n\t// Emit run started event\n\tawait runtime.emitEvent(EventTypes.RUN_STARTED, {\n\t\truntime,\n\t\trunId,\n\t\tmessageId: message.id,\n\t\troomId: message.roomId,\n\t\tentityId: message.entityId,\n\t\tstartTime,\n\t\tstatus: \"started\",\n\t\tsource: \"messageHandler\"\n\t});\n\n\t// Set up timeout monitoring\n\tconst timeoutDuration = 5 * 60 * 1000; // 5 minutes\n\tlet timeoutId: NodeJS.Timer;\n\t\n\tconst timeoutPromise = new Promise((_, reject) => {\n\t\ttimeoutId = setTimeout(async () => {\n\t\t\tawait runtime.emitEvent(EventTypes.RUN_TIMEOUT, {\n\t\t\t\truntime,\n\t\t\t\trunId,\n\t\t\t\tmessageId: message.id,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tstartTime,\n\t\t\t\tstatus: \"timeout\",\n\t\t\t\tendTime: Date.now(),\n\t\t\t\tduration: Date.now() - startTime,\n\t\t\t\terror: \"Run exceeded 5 minute timeout\",\n\t\t\t\tsource: \"messageHandler\"\n\t\t\t});\n\t\t\treject(new Error(\"Run exceeded 5 minute timeout\"));\n\t\t}, timeoutDuration);\n\t});\n\n\tconst processingPromise = (async () => {\n\t\ttry {\n\t\t\tif (message.entityId === runtime.agentId) {\n\t\t\t\tthrow new Error(\"Message is from the agent itself\");\n\t\t\t}\n\n\t\t\t// First, save the incoming message\n\t\t\tawait Promise.all([\n\t\t\t\truntime.getMemoryManager(\"messages\").addEmbeddingToMemory(message),\n\t\t\t\truntime.getMemoryManager(\"messages\").createMemory(message),\n\t\t\t]);\n\n\t\t\tconst agentUserState = await runtime.getParticipantUserState(message.roomId, runtime.agentId);\n\n\t\t\tif (\n\t\t\t\tagentUserState === \"MUTED\" &&\n\t\t\t\t!message.content.text\n\t\t\t\t\t.toLowerCase()\n\t\t\t\t\t.includes(runtime.character.name.toLowerCase())\n\t\t\t) {\n\t\t\t\tconsole.log(\"Ignoring muted room\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet state = await runtime.composeState(message, [\n\t\t\t\t\"PROVIDERS\",\n\t\t\t\t\"SHOULD_RESPOND\",\n\t\t\t\t\"CHARACTER\",\n\t\t\t\t\"RECENT_MESSAGES\",\n\t\t\t\t\"ENTITIES\",\n\t\t\t]);\n\n\t\t\tconst shouldRespondPrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate:\n\t\t\t\t\truntime.character.templates?.shouldRespondTemplate ||\n\t\t\t\t\tshouldRespondTemplate,\n\t\t\t});\n\n\t\t\tlogger.debug(\n\t\t\t\t`*** Should Respond Prompt for ${runtime.character.name} ***`,\n\t\t\t\tshouldRespondPrompt,\n\t\t\t);\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt: shouldRespondPrompt,\n\t\t\t});\n\n\t\t\tlogger.debug(\n\t\t\t\t`*** Should Respond Response for ${runtime.character.name} ***`,\n\t\t\t\tresponse,\n\t\t\t);\n\n\t\t\tconst responseObject = parseJSONObjectFromText(response);\n\n\t\t\tconst providers = responseObject.providers;\n\n\t\t\tconst shouldRespond =\n\t\t\t\tresponseObject?.action && responseObject.action === \"RESPOND\";\n\n\t\t\tstate = await runtime.composeState(message, null, providers);\n\n\t\t\tlet responseMessages: Memory[] = [];\n\n\t\t\tif (shouldRespond) {\n\t\t\t\tconst prompt = composePromptFromState({\n\t\t\t\t\tstate,\n\t\t\t\t\ttemplate:\n\t\t\t\t\t\truntime.character.templates?.messageHandlerTemplate ||\n\t\t\t\t\t\tmessageHandlerTemplate,\n\t\t\t\t});\n\n\t\t\t\tlet responseContent = null;\n\n\t\t\t\t// Retry if missing required fields\n\t\t\t\tlet retries = 0;\n\t\t\t\tconst maxRetries = 3;\n\t\t\t\twhile (\n\t\t\t\t\tretries < maxRetries &&\n\t\t\t\t\t(!responseContent?.thought ||\n\t\t\t\t\t\t!responseContent?.plan ||\n\t\t\t\t\t\t!responseContent?.actions)\n\t\t\t\t) {\n\t\t\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t});\n\n\t\t\t\t\tresponseContent = parseJSONObjectFromText(response) as Content;\n\n\t\t\t\t\tretries++;\n\t\t\t\t\tif (\n\t\t\t\t\t\t!responseContent?.thought ||\n\t\t\t\t\t\t!responseContent?.plan ||\n\t\t\t\t\t\t!responseContent?.actions\n\t\t\t\t\t) {\n\t\t\t\t\t\tlogger.warn(\"*** Missing required fields, retrying... ***\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check if this is still the latest response ID for this agent+room\n\t\t\t\tconst currentResponseId = agentResponses.get(message.roomId);\n\t\t\t\tif (currentResponseId !== responseId) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`Response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresponseContent.plan = responseContent.plan?.trim();\n\t\t\t\tresponseContent.inReplyTo = createUniqueUuid(runtime, message.id);\n\n\t\t\t\tresponseMessages = [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: v4() as UUID,\n\t\t\t\t\t\tentityId: runtime.agentId,\n\t\t\t\t\t\tagentId: runtime.agentId,\n\t\t\t\t\t\tcontent: responseContent,\n\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\tcreatedAt: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t];\n\n\t\t\t\t// save the plan to a new reply memory\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: runtime.agentId,\n\t\t\t\t\tagentId: runtime.agentId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tthought: responseContent.thought,\n\t\t\t\t\t\tplan: responseContent.plan,\n\t\t\t\t\t\tactions: responseContent.actions,\n\t\t\t\t\t\tproviders: responseContent.providers,\n\t\t\t\t\t},\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcreatedAt: Date.now(),\n\t\t\t\t});\n\n\t\t\t\t// Clean up the response ID\n\t\t\t\tagentResponses.delete(message.roomId);\n\t\t\t\tif (agentResponses.size === 0) {\n\t\t\t\t\tlatestResponseIds.delete(runtime.agentId);\n\t\t\t\t}\n\n\t\t\t\tawait runtime.processActions(message, responseMessages, state, callback);\n\t\t\t}\n\n\t\t\tawait runtime.evaluate(\n\t\t\t\tmessage,\n\t\t\t\tstate,\n\t\t\t\tshouldRespond,\n\t\t\t\tcallback,\n\t\t\t\tresponseMessages,\n\t\t\t);\n\n\t\t\t// Emit run ended event on successful completion\n\t\t\tawait runtime.emitEvent(EventTypes.RUN_ENDED, {\n\t\t\t\truntime,\n\t\t\t\trunId,\n\t\t\t\tmessageId: message.id,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tstartTime,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tendTime: Date.now(),\n\t\t\t\tduration: Date.now() - startTime,\n\t\t\t\tsource: \"messageHandler\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t// Emit run ended event with error\n\t\t\tawait runtime.emitEvent(EventTypes.RUN_ENDED, {\n\t\t\t\truntime,\n\t\t\t\trunId,\n\t\t\t\tmessageId: message.id,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tstartTime,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tendTime: Date.now(),\n\t\t\t\tduration: Date.now() - startTime,\n\t\t\t\terror: error.message,\n\t\t\t\tsource: \"messageHandler\"\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t})();\n\n\ttry {\n\t\tawait Promise.race([processingPromise, timeoutPromise]);\n\t} finally {\n\t\tclearTimeout(timeoutId);\n\t}\n};\n\n/**\n * Handles the receipt of a reaction message and creates a memory in the designated memory manager.\n *\n * @param {Object} params - The parameters for the function.\n * @param {IAgentRuntime} params.runtime - The agent runtime object.\n * @param {Memory} params.message - The reaction message to be stored in memory.\n * @returns {void}\n */\nconst reactionReceivedHandler = async ({\n\truntime,\n\tmessage,\n}: {\n\truntime: IAgentRuntime;\n\tmessage: Memory;\n}) => {\n\ttry {\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory(message);\n\t} catch (error) {\n\t\tif (error.code === \"23505\") {\n\t\t\tlogger.warn(\"Duplicate reaction memory, skipping\");\n\t\t\treturn;\n\t\t}\n\t\tlogger.error(\"Error in reaction handler:\", error);\n\t}\n};\n\n/**\n * Handles the generation of a post (like a Tweet) and creates a memory for it.\n * \n * @param {Object} params - The parameters for the function.\n * @param {IAgentRuntime} params.runtime - The agent runtime object.\n * @param {Memory} params.message - The post message to be processed.\n * @param {HandlerCallback} params.callback - The callback function to execute after processing.\n * @returns {Promise<void>}\n */\nconst postGeneratedHandler = async ({\n\truntime,\n\tmessage,\n\tcallback,\n}: MessageReceivedHandlerParams) => {\n\t// First, save the post to memory\n\tawait Promise.all([\n\t\truntime.getMemoryManager(\"messages\").addEmbeddingToMemory(message),\n\t\truntime.getMemoryManager(\"messages\").createMemory(message),\n\t]);\n\n\t// Compose state with providers for generating content\n\tlet state = await runtime.composeState(message, [\n\t\t\"PROVIDERS\",\n\t\t\"CHARACTER\",\n\t\t\"RECENT_MESSAGES\",\n\t\t\"ENTITIES\",\n\t]);\n\n\t// Since posts are agent-generated content, we always respond\n\tconst providers = state.providers || [];\n\n\t// Update state with additional providers\n\tstate = await runtime.composeState(message, null, providers);\n\n\t// Get prompt template - use post template if available, otherwise default to messageHandler\n\tconst promptTemplate = \n\t\truntime.character.templates?.postTemplate || \n\t\truntime.character.templates?.messageHandlerTemplate || \n\t\tmessageHandlerTemplate;\n\n\tconst prompt = composePromptFromState({\n\t\tstate,\n\t\ttemplate: promptTemplate,\n\t});\n\n\tlet responseContent = null;\n\n\t// Retry if missing required fields\n\tlet retries = 0;\n\tconst maxRetries = 3;\n\twhile (\n\t\tretries < maxRetries &&\n\t\t(!responseContent?.thought ||\n\t\t\t!responseContent?.plan ||\n\t\t\t!responseContent?.text)\n\t) {\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\n\t\tresponseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tretries++;\n\t\tif (\n\t\t\t!responseContent?.thought ||\n\t\t\t!responseContent?.plan ||\n\t\t\t!responseContent?.text\n\t\t) {\n\t\t\tlogger.warn(\"*** Missing required fields, retrying... ***\");\n\t\t}\n\t}\n\n\t// Create the response memory\n\tconst responseMessages = [\n\t\t{\n\t\t\tid: v4() as UUID,\n\t\t\tentityId: runtime.agentId,\n\t\t\tagentId: runtime.agentId,\n\t\t\tcontent: responseContent,\n\t\t\troomId: message.roomId,\n\t\t\tcreatedAt: Date.now(),\n\t\t},\n\t];\n\n\t// Save the response plan to memory\n\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\tentityId: runtime.agentId,\n\t\tagentId: runtime.agentId,\n\t\tcontent: {\n\t\t\tthought: responseContent.thought,\n\t\t\tplan: responseContent.plan,\n\t\t\ttext: responseContent.text,\n\t\t\tproviders: responseContent.providers,\n\t\t},\n\t\troomId: message.roomId,\n\t\tcreatedAt: Date.now(),\n\t});\n\n\t// Process the actions and execute the callback\n\tawait runtime.processActions(message, responseMessages, state, callback);\n\n\t// Run any configured evaluators\n\tawait runtime.evaluate(\n\t\tmessage,\n\t\tstate,\n\t\ttrue, // Post generation is always a \"responding\" scenario\n\t\tcallback,\n\t\tresponseMessages,\n\t);\n};\n\n/**\n * Syncs a single user into an entity\n */\n/**\n * Asynchronously sync a single user with the specified parameters.\n *\n * @param {UUID} entityId - The unique identifier for the entity.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n * @param {any} user - The user object to sync.\n * @param {string} serverId - The unique identifier for the server.\n * @param {string} channelId - The unique identifier for the channel.\n * @param {ChannelType} type - The type of channel.\n * @param {string} source - The source of the user data.\n * @returns {Promise<void>} A promise that resolves once the user is synced.\n */\nconst syncSingleUser = async (\n\tentityId: UUID,\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tchannelId: string,\n\ttype: ChannelType,\n\tsource: string,\n) => {\n\tconst entity = await runtime.getEntityById(entityId);\n\tlogger.info(`Syncing user: ${entity.metadata[source].username || entity.id}`);\n\n\ttry {\n\t\t// Ensure we're not using WORLD type and that we have a valid channelId\n\t\tif (!channelId) {\n\t\t\tlogger.warn(`Cannot sync user ${entity.id} without a valid channelId`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst roomId = createUniqueUuid(runtime, channelId);\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\n\t\tawait runtime.ensureConnection({\n\t\t\tentityId,\n\t\t\troomId,\n\t\t\tuserName: entity.metadata[source].username || entity.id,\n\t\t\tname: entity.metadata[source].name || entity.metadata[source].username || `User${entity.id}`,\n\t\t\tsource,\n\t\t\tchannelId,\n\t\t\tserverId,\n\t\t\ttype,\n\t\t\tworldId,\n\t\t});\n\n\t\tlogger.success(`Successfully synced user: ${entity.id}`);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Error syncing user: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n};\n\n/**\n * Handles standardized server data for both WORLD_JOINED and WORLD_CONNECTED events\n */\nconst handleServerSync = async ({\n\truntime,\n\tworld,\n\trooms,\n\tentities,\n\tsource,\n}: WorldPayload) => {\n\tlogger.info(`Handling server sync event for server: ${world.name}`);\n\ttry {\n\t\t// Create/ensure the world exists for this server\n\t\tawait runtime.ensureWorldExists({\n\t\t\tid: world.id,\n\t\t\tname: world.name,\n\t\t\tagentId: runtime.agentId,\n\t\t\tserverId: world.serverId,\n\t\t\tmetadata: {\n\t\t\t\t...world.metadata,\n\t\t\t},\n\t\t});\n\n\t\t// First sync all rooms/channels\n\t\tif (rooms && rooms.length > 0) {\n\t\t\tfor (const room of rooms) {\n\t\t\t\tawait runtime.ensureRoomExists({\n\t\t\t\t\tid: room.id,\n\t\t\t\t\tname: room.name,\n\t\t\t\t\tsource: source,\n\t\t\t\t\ttype: room.type,\n\t\t\t\t\tchannelId: room.channelId,\n\t\t\t\t\tserverId: world.serverId,\n\t\t\t\t\tworldId: world.id,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Then sync all users\n\t\tif (entities && entities.length > 0) {\n\t\t\t// Process entities in batches to avoid overwhelming the system\n\t\t\tconst batchSize = 50;\n\t\t\tfor (let i = 0; i < entities.length; i += batchSize) {\n\t\t\t\tconst entityBatch = entities.slice(i, i + batchSize);\n\n\t\t\t\t// check if user is in any of these rooms in rooms\n\t\t\t\tconst firstRoomUserIsIn = rooms.length > 0 ? rooms[0] : null;\n\n\t\t\t\t// Process each user in the batch\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tentityBatch.map(async (entity: Entity) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait runtime.ensureConnection({\n\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\troomId: firstRoomUserIsIn.id,\n\t\t\t\t\t\t\t\tuserName: entity.metadata[source].username,\n\t\t\t\t\t\t\t\tname: entity.metadata[source].name,\n\t\t\t\t\t\t\t\tsource: source,\n\t\t\t\t\t\t\t\tchannelId: firstRoomUserIsIn.channelId,\n\t\t\t\t\t\t\t\tserverId: world.serverId,\n\t\t\t\t\t\t\t\ttype: firstRoomUserIsIn.type,\n\t\t\t\t\t\t\t\tworldId: world.id,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Failed to sync user ${entity.metadata.username}: ${err}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\t// Add a small delay between batches if not the last batch\n\t\t\t\tif (i + batchSize < entities.length) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.success(\n\t\t\t`Successfully synced standardized world structure for ${world.name}`,\n\t\t);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Error processing standardized server data: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n};\n\nconst events = {\n\t[EventTypes.MESSAGE_RECEIVED]: [\n\t\tasync (payload: MessagePayload) => {\n\t\t\tawait messageReceivedHandler({\n\t\t\t\truntime: payload.runtime,\n\t\t\t\tmessage: payload.message,\n\t\t\t\tcallback: payload.callback,\n\t\t\t});\n\t\t},\n\t],\n\t\n\t[EventTypes.VOICE_MESSAGE_RECEIVED]: [\n\t\tasync (payload: MessagePayload) => {\n\t\t\tawait messageReceivedHandler({\n\t\t\t\truntime: payload.runtime,\n\t\t\t\tmessage: payload.message,\n\t\t\t\tcallback: payload.callback,\n\t\t\t});\n\t\t},\n\t],\n\t\n\t[EventTypes.REACTION_RECEIVED]: [\n\t\tasync (payload: MessagePayload) => {\n\t\t\tawait reactionReceivedHandler({\n\t\t\t\truntime: payload.runtime,\n\t\t\t\tmessage: payload.message,\n\t\t\t});\n\t\t}\n\t],\n\t\n\t[EventTypes.POST_GENERATED]: [\n\t\tasync (payload: MessagePayload) => {\n\t\t\tawait postGeneratedHandler({\n\t\t\t\truntime: payload.runtime,\n\t\t\t\tmessage: payload.message,\n\t\t\t\tcallback: payload.callback,\n\t\t\t});\n\t\t},\n\t],\n\t\n\t[EventTypes.MESSAGE_SENT]: [\n\t\tasync (payload: MessagePayload) => {\n\t\t\t// Message sent tracking\n\t\t\tlogger.debug(`Message sent: ${payload.message.content.text}`);\n\t\t}\n\t],\n\n\t[EventTypes.WORLD_JOINED]: [\n\t\tasync (payload: WorldPayload) => {\n\t\t\tawait handleServerSync(payload);\n\t\t}\n\t],\n\t\n\t[EventTypes.WORLD_CONNECTED]: [\n\t\tasync (payload: WorldPayload) => {\n\t\t\tawait handleServerSync(payload);\n\t\t}\n\t],\n\n\t[EventTypes.ENTITY_JOINED]: [\n\t\tasync (payload: EntityPayload) => {\n\t\t\tawait syncSingleUser(\n\t\t\t\tpayload.entityId,\n\t\t\t\tpayload.runtime,\n\t\t\t\tpayload.worldId,\n\t\t\t\tpayload.roomId,\n\t\t\t\tpayload.metadata.type,\n\t\t\t\tpayload.source,\n\t\t\t);\n\t\t},\n\t],\n\t\n\t[EventTypes.ENTITY_LEFT]: [\n\t\tasync (payload: EntityPayload) => {\n\t\t\ttry {\n\t\t\t\t// Update entity to inactive\n\t\t\t\tconst entity = await payload.runtime.getEntityById(payload.entityId);\n\t\t\t\tif (entity) {\n\t\t\t\t\tentity.metadata = {\n\t\t\t\t\t\t...entity.metadata,\n\t\t\t\t\t\tstatus: \"INACTIVE\",\n\t\t\t\t\t\tleftAt: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait payload.runtime.updateEntity(entity);\n\t\t\t\t}\n\t\t\t\tlogger.info(`User ${payload.entityId} left world ${payload.worldId}`);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error handling user left: ${error.message}`);\n\t\t\t}\n\t\t}\n\t],\n\n\t[EventTypes.ACTION_STARTED]: [\n\t\tasync (payload: ActionEventPayload) => {\n\t\t\tlogger.debug(`Action started: ${payload.actionName} (${payload.actionId})`);\n\t\t}\n\t],\n\n\t[EventTypes.ACTION_COMPLETED]: [\n\t\tasync (payload: ActionEventPayload) => {\n\t\t\tconst status = payload.error ? `failed: ${payload.error.message}` : 'completed';\n\t\t\tlogger.debug(`Action ${status}: ${payload.actionName} (${payload.actionId})`);\n\t\t}\n\t],\n\n\t[EventTypes.EVALUATOR_STARTED]: [\n\t\tasync (payload: EvaluatorEventPayload) => {\n\t\t\tlogger.debug(`Evaluator started: ${payload.evaluatorName} (${payload.evaluatorId})`);\n\t\t}\n\t],\n\n\t[EventTypes.EVALUATOR_COMPLETED]: [\n\t\tasync (payload: EvaluatorEventPayload) => {\n\t\t\tconst status = payload.error ? `failed: ${payload.error.message}` : 'completed';\n\t\t\tlogger.debug(`Evaluator ${status}: ${payload.evaluatorName} (${payload.evaluatorId})`);\n\t\t}\n\t],\n};\n\nexport const bootstrapPlugin: Plugin = {\n\tname: \"bootstrap\",\n\tdescription: \"Agent bootstrap with basic actions and evaluators\",\n\tactions: [\n\t\treplyAction,\n\t\tfollowRoomAction,\n\t\tunfollowRoomAction,\n\t\tignoreAction,\n\t\tnoneAction,\n\t\tmuteRoomAction,\n\t\tunmuteRoomAction,\n\t\tsendMessageAction,\n\t\tupdateEntityAction,\n\t\tchoiceAction,\n\t\tupdateRoleAction,\n\t\tupdateSettingsAction,\n\t],\n\tevents,\n\tevaluators: [reflectionEvaluator],\n\tproviders: [\n\t\tevaluatorsProvider,\n\t\tanxietyProvider,\n\t\tknowledgeProvider,\n\t\ttimeProvider,\n\t\tentitiesProvider,\n\t\trelationshipsProvider,\n\t\tchoiceProvider,\n\t\tfactsProvider,\n\t\troleProvider,\n\t\tsettingsProvider,\n\t\tcapabilitiesProvider,\n\t\tattachmentsProvider,\n\t\tprovidersProvider,\n\t\tactionsProvider,\n\t\tcharacterProvider,\n\t\trecentMessagesProvider,\n\t],\n\tservices: [TaskService, ScenarioService],\n};\n\nexport default bootstrapPlugin;\n","import { logger } from \"../logger\";\nimport { composePrompt, parseJSONObjectFromText } from \"../prompts\";\nimport { getUserServerRole } from \"../roles\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Task: Extract selected task and option from user message\n *\n * Available Tasks:\n * {{#each tasks}}\n * Task ID: {{taskId}} - {{name}}\n * Available options:\n * {{#each options}}\n * - {{name}}: {{description}}\n * {{/each}}\n * - ABORT: Cancel this task\n * {{/each}}\n *\n * Recent Messages:\n * {{recentMessages}}\n *\n * Instructions:\n * 1. Review the user's message and identify which task and option they are selecting\n * 2. Match against the available tasks and their options, including ABORT\n * 3. Return the task ID (shortened UUID) and selected option name exactly as listed above\n * 4. If no clear selection is made, return null for both fields\n *\n * Return in JSON format:\n * ```json\n * {\n * \"taskId\": \"string\" | null,\n * \"selectedOption\": \"OPTION_NAME\" | null\n * }\n * ```\n *\n * Make sure to include the ```json``` tags around the JSON object.\n */\nconst optionExtractionTemplate = `# Task: Extract selected task and option from user message\n\n# Available Tasks:\n{{#each tasks}}\nTask ID: {{taskId}} - {{name}}\nAvailable options:\n{{#each options}}\n- {{name}}: {{description}}\n{{/each}}\n- ABORT: Cancel this task\n\n{{/each}}\n\n# Recent Messages:\n{{recentMessages}}\n\n# Instructions:\n1. Review the user's message and identify which task and option they are selecting\n2. Match against the available tasks and their options, including ABORT\n3. Return the task ID (shortened UUID) and selected option name exactly as listed above\n4. If no clear selection is made, return null for both fields\n\nReturn in JSON format:\n\\`\\`\\`json\n{\n \"taskId\": \"string\" | null,\n \"selectedOption\": \"OPTION_NAME\" | null\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\n\n/**\n * Represents an action that allows selecting an option for a pending task that has multiple options.\n * @type {Action}\n * @property {string} name - The name of the action\n * @property {string[]} similes - Similar words or phrases for the action\n * @property {string} description - A brief description of the action\n * @property {Function} validate - Asynchronous function to validate the action\n * @property {Function} handler - Asynchronous function to handle the action\n * @property {ActionExample[][]} examples - Examples demonstrating the usage of the action\n */\nexport const choiceAction: Action = {\n\tname: \"CHOOSE_OPTION\",\n\tsimiles: [\"SELECT_OPTION\", \"SELECT\", \"PICK\", \"CHOOSE\"],\n\tdescription: \"Selects an option for a pending task that has multiple options\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<boolean> => {\n\t\t// Get all tasks with options metadata\n\t\tconst pendingTasks = await runtime.getTasks({\n\t\t\troomId: message.roomId,\n\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t});\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\n\t\tconst userRole = await getUserServerRole(\n\t\t\truntime,\n\t\t\tmessage.entityId,\n\t\t\troom.serverId,\n\t\t);\n\n\t\tif (userRole !== \"OWNER\" && userRole !== \"ADMIN\") {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Only validate if there are pending tasks with options\n\t\treturn (\n\t\t\tpendingTasks &&\n\t\t\tpendingTasks.length > 0 &&\n\t\t\tpendingTasks.some((task) => task.metadata?.options)\n\t\t);\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\tconst pendingTasks = await runtime.getTasks({\n\t\t\t\troomId: message.roomId,\n\t\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t\t});\n\n\t\t\tif (!pendingTasks?.length) {\n\t\t\t\tthrow new Error(\"No pending tasks with options found\");\n\t\t\t}\n\n\t\t\tconst tasksWithOptions = pendingTasks.filter(\n\t\t\t\t(task) => task.metadata?.options,\n\t\t\t);\n\n\t\t\tif (!tasksWithOptions.length) {\n\t\t\t\tthrow new Error(\"No tasks currently have options to select from.\");\n\t\t\t}\n\n\t\t\t// Format tasks with their options for the LLM, using shortened UUIDs\n\t\t\tconst formattedTasks = tasksWithOptions.map((task) => {\n\t\t\t\t// Generate a short ID from the task UUID (first 8 characters should be unique enough)\n\t\t\t\tconst shortId = task.id.substring(0, 8);\n\n\t\t\t\treturn {\n\t\t\t\t\ttaskId: shortId,\n\t\t\t\t\tfullId: task.id,\n\t\t\t\t\tname: task.name,\n\t\t\t\t\toptions: task.metadata.options.map((opt) => ({\n\t\t\t\t\t\tname: typeof opt === \"string\" ? opt : opt.name,\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\ttypeof opt === \"string\" ? opt : opt.description || opt.name,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// format tasks as a string\n\t\t\tconst tasksString = formattedTasks\n\t\t\t\t.map((task) => {\n\t\t\t\t\treturn `Task ID: ${task.taskId} - ${task.name}\\nAvailable options:\\n${task.options.map((opt) => `- ${opt.name}: ${opt.description}`).join(\"\\n\")}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\");\n\n\t\t\tconst prompt = composePrompt({\n\t\t\t\tstate: {\n\t\t\t\t\ttasks: tasksString,\n\t\t\t\t\trecentMessages: message.content.text,\n\t\t\t\t},\n\t\t\t\ttemplate: optionExtractionTemplate,\n\t\t\t});\n\n\t\t\tconst result = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst parsed = parseJSONObjectFromText(result);\n\t\t\tconst { taskId, selectedOption } = parsed;\n\n\t\t\tif (taskId && selectedOption) {\n\t\t\t\t// Find the task by matching the shortened UUID\n\t\t\t\tconst taskMap = new Map(\n\t\t\t\t\tformattedTasks.map((task) => [task.taskId, task]),\n\t\t\t\t);\n\t\t\t\tconst taskInfo = taskMap.get(taskId);\n\n\t\t\t\tif (!taskInfo) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Could not find a task matching ID: ${taskId}. Please try again.`,\n\t\t\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Find the actual task using the full UUID\n\t\t\t\tconst selectedTask = tasksWithOptions.find(\n\t\t\t\t\t(task) => task.id === taskInfo.fullId,\n\t\t\t\t);\n\n\t\t\t\tif (!selectedTask) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"Error locating the selected task. Please try again.\",\n\t\t\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (selectedOption === \"ABORT\") {\n\t\t\t\t\tawait runtime.deleteTask(selectedTask.id);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Task \"${selectedTask.name}\" has been cancelled.`,\n\t\t\t\t\t\tactions: [\"CHOOSE_OPTION_CANCELLED\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst taskWorker = runtime.getTaskWorker(selectedTask.name);\n\t\t\t\t\tawait taskWorker.execute(\n\t\t\t\t\t\truntime,\n\t\t\t\t\t\t{ option: selectedOption },\n\t\t\t\t\t\tselectedTask,\n\t\t\t\t\t);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Selected option: ${selectedOption} for task: ${selectedTask.name}`,\n\t\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(\"Error executing task with option:\", error);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"There was an error processing your selection.\",\n\t\t\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no task/option was selected, list available options\n\t\t\tlet optionsText =\n\t\t\t\t\"Please select a valid option from one of these tasks:\\n\\n\";\n\n\t\t\ttasksWithOptions.forEach((task) => {\n\t\t\t\t// Create a shortened UUID for display\n\t\t\t\tconst shortId = task.id.substring(0, 8);\n\n\t\t\t\toptionsText += `**${task.name}** (ID: ${shortId}):\\n`;\n\t\t\t\tconst options = task.metadata.options.map((opt) =>\n\t\t\t\t\ttypeof opt === \"string\" ? opt : opt.name,\n\t\t\t\t);\n\t\t\t\toptions.push(\"ABORT\");\n\t\t\t\toptionsText += options.map((opt) => `- ${opt}`).join(\"\\n\");\n\t\t\t\toptionsText += \"\\n\\n\";\n\t\t\t});\n\n\t\t\tawait callback({\n\t\t\t\ttext: optionsText,\n\t\t\t\tactions: [\"SELECT_OPTION_INVALID\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in select option handler:\", error);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing the option selection.\",\n\t\t\t\tactions: [\"SELECT_OPTION_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"post\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Selected option: post for task: Confirm Twitter Post\",\n\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I choose cancel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Selected option: cancel for task: Confirm Twitter Post\",\n\t\t\t\t\tactions: [\"CHOOSE_OPTION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default choiceAction;\n","import logger from \"../logger\";\nimport { composePromptFromState } from \"../prompts\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Template for deciding if {{agentName}} should start following a room.\n * The decision is based on various criteria, including recent messages and user interactions.\n * Respond with YES if:\n * - The user has directly asked {{agentName}} to follow the conversation\n * - The conversation topic is engaging and {{agentName}}'s input would add value\n * - {{agentName}} has unique insights to contribute and users seem receptive\n * Otherwise, respond with NO.\n */\nexport const shouldFollowTemplate = `# Task: Decide if {{agentName}} should start following this room, i.e. eagerly participating without explicit mentions.\n\n{{recentMessages}}\n\nShould {{agentName}} start following this room, eagerly participating without explicit mentions?\nRespond with YES if:\n- The user has directly asked {{agentName}} to follow the conversation or participate more actively\n- The conversation topic is highly engaging and {{agentName}}'s input would add significant value\n- {{agentName}} has unique insights to contribute and the users seem receptive\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\n/**\n * Action for following a room with great interest.\n * Similes: FOLLOW_CHAT, FOLLOW_CHANNEL, FOLLOW_CONVERSATION, FOLLOW_THREAD\n * Description: Start following this channel with great interest, chiming in without needing to be explicitly mentioned. Only do this if explicitly asked to.\n * @param {IAgentRuntime} runtime - The current agent runtime.\n * @param {Memory} message - The message memory.\n * @returns {Promise<boolean>} - Promise that resolves to a boolean indicating if the room should be followed.\n */\nexport const followRoomAction: Action = {\n\tname: \"FOLLOW_ROOM\",\n\tsimiles: [\n\t\t\"FOLLOW_CHAT\",\n\t\t\"FOLLOW_CHANNEL\",\n\t\t\"FOLLOW_CONVERSATION\",\n\t\t\"FOLLOW_THREAD\",\n\t],\n\tdescription:\n\t\t\"Start following this channel with great interest, chiming in without needing to be explicitly mentioned. Only do this if explicitly asked to.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst keywords = [\n\t\t\t\"follow\",\n\t\t\t\"participate\",\n\t\t\t\"engage\",\n\t\t\t\"listen\",\n\t\t\t\"take interest\",\n\t\t\t\"join\",\n\t\t];\n\t\tif (\n\t\t\t!keywords.some((keyword) =>\n\t\t\t\tmessage.content.text.toLowerCase().includes(keyword),\n\t\t\t)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState !== \"FOLLOWED\" && roomState !== \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldFollow(state: State): Promise<boolean> {\n\t\t\tconst shouldFollowPrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldFollowTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldFollowPrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I will now follow this room and chime in\",\n\t\t\t\t\t\tactions: [\"FOLLOW_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"FOLLOW_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I decided to not follow this room\",\n\t\t\t\t\t\tactions: [\"FOLLOW_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"FOLLOW_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldFollow(state)) {\n\t\t\tawait runtime\n\t\t\t\t\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, \"FOLLOWED\");\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I followed the room ${room.name}`,\n\t\t\t\tactions: [\"FOLLOW_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name2}} follow this channel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sure, I will now follow this room and chime in\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please start participating in discussions in this channel\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Got it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'm struggling with the new database migration\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"well you did back up your data first right\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yeah i like your idea\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} can you follow this convo\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sure thing, I'm on it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"actually, unfollow it\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Haha, okay no problem\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} stay in this chat pls\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"you got it, i'm here\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"FOLLOW THIS CHAT {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'M ON IT\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"CAKE SHORTAGE ANYONE\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"WHAT WHERE'S THE CAKE AT\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} folo this covo\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"kk i'm following\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Do machines have consciousness\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Deep question, no clear answer yet\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Depends on how we define consciousness\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, monitor this convo please\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"On it\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Please engage in our discussion {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Gladly, I'm here to participate\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"PLS follow this convo {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'm in, let's do this\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I LIKE TURTLES\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"beach day tmrw who down\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wish i could but gotta work\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} follow this chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sure\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, partake in our discourse henceforth\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I shall eagerly engage, good sir\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wuts ur fav clr\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"blu cuz calmmm\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey respond to everything in this channel {{name3}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"k\",\n\t\t\t\t\tactions: [\"FOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { Action, ActionExample, IAgentRuntime, Memory } from \"../types\";\n\n/**\n * Action representing the IGNORE action. This action is used when ignoring the user in a conversation.\n *\n * @type {Action}\n * @property {string} name - The name of the action, which is \"IGNORE\".\n * @property {string[]} similes - An array of related similes for the action.\n * @property {Function} validate - Asynchronous function that validates the action.\n * @property {string} description - Description of when to use the IGNORE action in a conversation.\n * @property {Function} handler - Asynchronous function that handles the action logic.\n * @property {ActionExample[][]} examples - Array of examples demonstrating the usage of the IGNORE action.\n */\nexport const ignoreAction: Action = {\n\tname: \"IGNORE\",\n\tsimiles: [\"STOP_TALKING\", \"STOP_CHATTING\", \"STOP_CONVERSATION\"],\n\tvalidate: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\treturn true;\n\t},\n\tdescription:\n\t\t\"Call this action if ignoring the user. If the user is aggressive, creepy or is finished with the conversation, use this action. Or, if both you and the user have already said goodbye, use this action instead of saying bye again. Use IGNORE any time the conversation has naturally ended. Do not use IGNORE if the user has engaged directly, or if something went wrong an you need to tell them. Only ignore if the user should be ignored.\",\n\thandler: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<boolean> => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Go screw yourself\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Shut up, bot\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Got any investment advice\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Uh, don’t let the volatility sway your long-term strategy\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Wise words I think\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"I gotta run, talk to you later\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"See ya\" },\n\t\t\t},\n\t\t\t{ name: \"{{name1}}\", content: { text: \"\" }, actions: [\"IGNORE\"] },\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Gotta go\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Okay, talk to you later\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Cya\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"bye\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"cya\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Who added this stupid bot to the chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Sorry, am I being annoying\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Yeah\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"PLEASE shut up\" },\n\t\t\t},\n\t\t\t{ name: \"{{name2}}\", content: { text: \"\", actions: [\"IGNORE\"] } },\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"ur so dumb\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"later nerd\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"bye\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wanna cyber\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"thats inappropriate\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Im out ttyl\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"cya\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"u there\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yes how can I help\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"k nvm figured it out\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import logger from \"../logger\";\nimport { composePromptFromState } from \"../prompts\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Template string for deciding if the agent should mute a room and stop responding unless explicitly mentioned.\n *\n * @type {string}\n */\nexport const shouldMuteTemplate = `# Task: Decide if {{agentName}} should mute this room and stop responding unless explicitly mentioned.\n\n{{recentMessages}}\n\nShould {{agentName}} mute this room and stop responding unless explicitly mentioned?\n\nRespond with YES if:\n- The user is being aggressive, rude, or inappropriate\n- The user has directly asked {{agentName}} to stop responding or be quiet\n- {{agentName}}'s responses are not well-received or are annoying the user(s)\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\n/**\n * Action for muting a room, ignoring all messages unless explicitly mentioned.\n * Only do this if explicitly asked to, or if you're annoying people.\n *\n * @name MUTE_ROOM\n * @type {Action}\n *\n * @property {string} name - The name of the action\n * @property {string[]} similes - Similar actions related to muting a room\n * @property {string} description - Description of the action\n * @property {Function} validate - Validation function to check if the room is not already muted\n * @property {Function} handler - Handler function to handle muting the room\n * @property {ActionExample[][]} examples - Examples of using the action\n */\nexport const muteRoomAction: Action = {\n\tname: \"MUTE_ROOM\",\n\tsimiles: [\n\t\t\"MUTE_CHAT\",\n\t\t\"MUTE_CONVERSATION\",\n\t\t\"MUTE_ROOM\",\n\t\t\"MUTE_THREAD\",\n\t\t\"MUTE_CHANNEL\",\n\t],\n\tdescription:\n\t\t\"Mutes a room, ignoring all messages unless explicitly mentioned. Only do this if explicitly asked to, or if you're annoying people.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState !== \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldMute(state: State): Promise<boolean> {\n\t\t\tconst shouldMutePrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldMuteTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldMutePrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I will now mute this room\",\n\t\t\t\t\t\tactions: [\"MUTE_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"MUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I decided to not mute this room\",\n\t\t\t\t\t\tactions: [\"MUTE_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"MUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldMute(state)) {\n\t\t\tawait runtime\n\t\t\t\t\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, \"MUTED\");\n\t\t}\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I muted the room ${room.name}`,\n\t\t\t\tactions: [\"MUTE_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please mute this channel. No need to respond here for now.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Got it\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"@{{name1}} we could really use your input on this\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please mute this channel for the time being\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Understood\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey what do you think about this new design\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} plz mute this room\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"np going silent\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"whos going to the webxr meetup in an hour btw\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tactions: [\"IGNORE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"too many messages here {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"my bad ill mute\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yo {{name2}} dont talk in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry\",\n\t\t\t\t\tactions: [\"MUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { Action, ActionExample, IAgentRuntime, Memory } from \"../types\";\n\n/**\n * Represents the none action.\n *\n * This action responds but performs no additional action. It is the default if the agent is speaking and not doing anything additional.\n *\n * @type {Action}\n */\nexport const noneAction: Action = {\n\tname: \"NONE\",\n\tsimiles: [\"NO_ACTION\", \"NO_RESPONSE\", \"NO_REACTION\"],\n\tvalidate: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\treturn true;\n\t},\n\tdescription:\n\t\t\"Respond but perform no additional action. This is the default if the agent is speaking and not doing anything additional.\",\n\thandler: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<boolean> => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"Hey whats up\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"oh hey\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"did u see some faster whisper just came out\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yeah but its a pain to get into node.js\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"the things that were funny 6 months ago are very cringe now\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"lol true\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"too real haha\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"gotta run\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"Okay, ttyl\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"\", actions: [\"IGNORE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"heyyyyyy\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"whats up long time no see\" },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"chillin man. playing lots of fortnite. what about you\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"u think aliens are real\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"ya obviously\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"drop a joke on me\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"why dont scientists trust atoms cuz they make up everything lmao\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: { text: \"haha good one\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hows the weather where ur at\",\n\t\t\t\t\tactions: [\"NONE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: { text: \"beautiful all week\", actions: [\"NONE\"] },\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import { composePromptFromState, parseJSONObjectFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype Content,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Template for generating dialog and actions for a character.\n *\n * @type {string}\n */\nconst replyTemplate = `# Task: Generate dialog and actions for the character {{agentName}}.\n{{providers}}\n# Instructions: Write the next message for {{agentName}}.\nFirst, think about what you want to do next and plan your actions. Then, write the next message and include the actions you plan to take.\n\"thought\" should be a short description of what the agent is thinking about and planning.\n\"message\" should be the next message for {{agentName}} which they will send to the conversation.\n\nThese are the available valid actions: {{actionNames}}\n\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{\n \"thought\": \"<string>\",\n \"message\": \"<string>\"\n}\n\\`\\`\\`\n\nYour response should include the valid JSON block and nothing else.`;\n\n/**\n * Represents an action that allows the agent to reply to the current conversation with a generated message.\n *\n * This action can be used as an acknowledgement at the beginning of a chain of actions, or as a final response at the end of a chain of actions.\n *\n * @typedef {Object} replyAction\n * @property {string} name - The name of the action (\"REPLY\").\n * @property {string[]} similes - An array of similes for the action.\n * @property {string} description - A description of the action and its usage.\n * @property {Function} validate - An asynchronous function for validating the action runtime.\n * @property {Function} handler - An asynchronous function for handling the action logic.\n * @property {ActionExample[][]} examples - An array of example scenarios for the action.\n */\nexport const replyAction = {\n\tname: \"REPLY\",\n\tsimiles: [\"REPLY_TO_MESSAGE\", \"SEND_REPLY\", \"RESPOND\"],\n\tdescription:\n\t\t\"Replies to the current conversation with the text from the generated message. Default if the agent is responding with a message and no other action. Use REPLY at the beginning of a chain of actions as an acknowledgement, and at the end of a chain of actions as a final response.\",\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\tstate = await runtime.composeState(message, [\n\t\t\t...(message.content.providers ?? []),\n\t\t\t\"RECENT_MESSAGES\",\n\t\t]);\n\n\t\tconst prompt = composePromptFromState({\n\t\t\tstate,\n\t\t\ttemplate: replyTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContentObj = parseJSONObjectFromText(response) as Content;\n\n\t\tconst responseContent = {\n\t\t\tthought: responseContentObj.thought,\n\t\t\ttext: (responseContentObj.message as string) || \"\",\n\t\t\tactions: [\"REPLY\"],\n\t\t};\n\n\t\tawait callback(responseContent);\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hello there!\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hi! How can I help you today?\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"What's your favorite color?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I really like deep shades of blue. They remind me of the ocean and the night sky.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Can you explain how neural networks work?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Let me break that down for you in simple terms...\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Could you help me solve this math problem?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Of course! Let's work through it step by step.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import type { ZodSchema, z } from \"zod\";\nimport { createUniqueUuid } from \"..\";\nimport { logger } from \"../logger\";\nimport { composePrompt } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\tChannelType,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype ModelType,\n\tModelTypes,\n\tRole,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\nimport dedent from \"dedent\";\n\n/**\n * Determines if the user with the current role can modify the role to the new role.\n * @param currentRole The current role of the user making the change\n * @param targetRole The current role of the user being changed (null if new user)\n * @param newRole The new role to assign\n * @returns Whether the role change is allowed\n */\nconst canModifyRole = (\n\tcurrentRole: Role,\n\ttargetRole: Role | null,\n\tnewRole: Role,\n): boolean => {\n\t// User's can't change their own role\n\tif (targetRole === currentRole) return false;\n\n\tswitch (currentRole) {\n\t\t// Owners can do everything\n\t\tcase Role.OWNER:\n\t\t\treturn true;\n\t\t// Admins can only create/modify users up to their level\n\t\tcase Role.ADMIN:\n\t\t\treturn newRole !== Role.OWNER;\n\t\t// Normal users can't modify roles\n\t\tcase Role.NONE:\n\t\tdefault:\n\t\t\treturn false;\n\t}\n};\n\n/**\n * Template for extracting role assignments from a conversation.\n *\n * @type {string} extractionTemplate - The template string containing information about the task, server members, available roles, recent messages, current speaker role, and extraction instructions.\n * @returns {string} JSON format of role assignments if valid role assignments are found, otherwise an empty array.\n */\nconst extractionTemplate = `# Task: Extract role assignments from the conversation\n\n# Current Server Members:\n{{serverMembers}}\n\n# Available Roles:\n- OWNER: Full control over the organization\n- ADMIN: Administrative privileges\n- NONE: Standard member access\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Current speaker role: {{speakerRole}}\n\n# Instructions: Analyze the conversation and extract any role assignments being made by the speaker.\nOnly extract role assignments if:\n1. The speaker has appropriate permissions to make the change\n2. The role assignment is clearly stated\n3. The target user is a valid server member\n4. The new role is one of: OWNER, ADMIN, or NONE\n\nReturn the results in this JSON format:\n{\n\"roleAssignments\": [\n {\n \"entityId\": \"<UUID of the entity being assigned to>\",\n \"newRole\": \"ROLE_NAME\"\n }\n]\n}\n\nIf no valid role assignments are found, return an empty array.`;\n\n/**\n * Interface representing a role assignment to a user.\n */\ninterface RoleAssignment {\n\tentityId: string;\n\tnewRole: Role;\n}\n\n/**\n * Represents an action to update the role of a user within a server.\n * @typedef {Object} Action\n * @property {string} name - The name of the action.\n * @property {string[]} similes - The similar actions that can be performed.\n * @property {string} description - A description of the action and its purpose.\n * @property {Function} validate - A function to validate the action before execution.\n * @property {Function} handler - A function to handle the execution of the action.\n * @property {ActionExample[][]} examples - Examples demonstrating how the action can be used.\n */\nconst updateRoleAction: Action = {\n\tname: \"UPDATE_ROLE\",\n\tsimiles: [\"CHANGE_ROLE\", \"SET_PERMISSIONS\", \"ASSIGN_ROLE\", \"MAKE_ADMIN\"],\n\tdescription:\n\t\t\"Assigns a role (Admin, Owner, None) to a user or list of users in a channel.\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<boolean> => {\n\t\t// Only activate in group chats where the feature is enabled\n\t\tconst channelType = message.content.channelType as ChannelType;\n\t\tconst serverId = message.content.serverId as string;\n\n\t\treturn (\n\t\t\t// First, check if this is a supported channel type\n\t\t\t(channelType === ChannelType.GROUP ||\n\t\t\t\tchannelType === ChannelType.WORLD) &&\n\t\t\t// Then, check if we have a server ID\n\t\t\t!!serverId\n\t\t);\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t): Promise<void> => {\n\t\t// Extract needed values from message and state\n\t\tconst { roomId } = message;\n\t\tconst channelType = message.content.channelType as ChannelType;\n\t\tconst serverId = message.content.serverId as string;\n\t\tconst worldId = runtime.getSetting(\"WORLD_ID\");\n\n\t\t// First, get the world for this server\n\t\tlet world;\n\t\tif (worldId) {\n\t\t\tworld = await runtime.getWorld(worldId as UUID);\n\t\t}\n\n\t\tif (!world) {\n\t\t\tlogger.error(\"World not found\");\n\t\t\tawait callback({\n\t\t\t\ttext: \"I couldn't find the world. This action only works in a world.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (!world.metadata?.roles) {\n\t\t\tworld.metadata = world.metadata || {};\n\t\t\tworld.metadata.roles = {};\n\t\t}\n\n\t\t// Get the entities for this room\n\t\tconst entities = await runtime\n\t\t\t\n\t\t\t.getEntitiesForRoom(roomId);\n\n\t\t// Get the role of the requester\n\t\tconst requesterRole = world.metadata.roles[message.entityId] || Role.NONE;\n\n\t\t// Construct extraction prompt\n\t\tconst extractionPrompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state.values,\n\t\t\t\tcontent: state.text,\n\t\t\t},\n\t\t\ttemplate: dedent`\n\t\t\t\t# Task: Parse Role Assignment\n\n\t\t\t\tI need to extract user role assignments from the input text. Users can be referenced by name, username, or mention.\n\n\t\t\t\tThe available role types are:\n\t\t\t\t- OWNER: Full control over the server and all settings\n\t\t\t\t- ADMIN: Ability to manage channels and moderate content\n\t\t\t\t- NONE: Regular user with no special permissions\n\n\t\t\t\t# Current context:\n\t\t\t\t{{content}}\n\n\t\t\t\tFormat your response as a JSON array of objects, each with:\n\t\t\t\t- entityId: The name or ID of the user\n\t\t\t\t- newRole: The role to assign (OWNER, ADMIN, or NONE)\n\n\t\t\t\tExample:\n\t\t\t\t\\`\\`\\`json\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\t\"entityId\": \"John\",\n\t\t\t\t\t\t\"newRole\": \"ADMIN\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"entityId\": \"Sarah\",\n\t\t\t\t\t\t\"newRole\": \"OWNER\"\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t\t\\`\\`\\`\n\t\t\t`,\n\t\t});\n\n\t\t// Extract role assignments using type-safe model call\n\t\tconst result = await runtime.useModel<\n\t\t\ttypeof ModelTypes.OBJECT_LARGE,\n\t\t\tRoleAssignment[]\n\t\t>(ModelTypes.OBJECT_LARGE, {\n\t\t\tprompt: extractionPrompt,\n\t\t\tschema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tentityId: { type: \"string\" },\n\t\t\t\t\t\tnewRole: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: Object.values(Role),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"entityId\", \"newRole\"],\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\n\t\tif (!result?.length) {\n\t\t\tawait callback({\n\t\t\t\ttext: \"No valid role assignments found in the request.\",\n\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\tsource: \"discord\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Process each role assignment\n\t\tlet worldUpdated = false;\n\n\t\tfor (const assignment of result) {\n\t\t\tlet targetEntity = entities.find((e) => e.id === assignment.entityId);\n\t\t\tif (!targetEntity) {\n\t\t\t\ttargetEntity = entities.find((e) => e.id === assignment.entityId);\n\t\t\t\tconsole.log(\"Trying to write to generated tenant ID\");\n\t\t\t}\n\t\t\tif (!targetEntity) {\n\t\t\t\tconsole.log(\"Could not find an ID ot assign to\");\n\t\t\t}\n\n\t\t\tconst currentRole = world.metadata.roles[assignment.entityId];\n\n\t\t\t// Validate role modification permissions\n\t\t\tif (!canModifyRole(requesterRole, currentRole, assignment.newRole)) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `You don't have permission to change ${targetEntity.names[0]}'s role to ${assignment.newRole}.`,\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Update role in world metadata\n\t\t\tworld.metadata.roles[assignment.entityId] = assignment.newRole;\n\n\t\t\tworldUpdated = true;\n\n\t\t\tawait callback({\n\t\t\t\ttext: `Updated ${targetEntity.names[0]}'s role to ${assignment.newRole}.`,\n\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\tsource: \"discord\",\n\t\t\t});\n\t\t}\n\n\t\t// Save updated world metadata if any changes were made\n\t\tif (worldUpdated) {\n\t\t\tawait runtime.updateWorld(world);\n\t\t\tlogger.info(`Updated roles in world metadata for server ${serverId}`);\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Make {{name2}} an ADMIN\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Updated {{name2}}'s role to ADMIN.\",\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set @alice and @bob as admins\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Updated alice's role to ADMIN.\\nUpdated bob's role to ADMIN.\",\n\t\t\t\t\tactions: [\"UPDATE_ROLE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Ban @troublemaker\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I cannot ban users.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateRoleAction;\n","// action: SEND_MESSAGE\n// send message to a user or room (other than this room we are in)\n\nimport { findEntityByName } from \"../entities\";\nimport { logger } from \"../logger\";\nimport { composePromptFromState, parseJSONObjectFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Task: Extract Target and Source Information\n *\n * Recent Messages:\n * {{recentMessages}}\n *\n * Instructions:\n * Analyze the conversation to identify:\n * 1. The target type (user or room)\n * 2. The target platform/source (e.g. telegram, discord, etc)\n * 3. Any identifying information about the target\n *\n * Return a JSON object with:\n * {\n * \"targetType\": \"user|room\",\n * \"source\": \"platform-name\",\n * \"identifiers\": {\n * // Relevant identifiers for that target\n * // e.g. username, roomName, etc.\n * }\n * }\n *\n * Example outputs:\n * For \"send a message to @dev_guru on telegram\":\n * {\n * \"targetType\": \"user\",\n * \"source\": \"telegram\",\n * \"identifiers\": {\n * \"username\": \"dev_guru\"\n * }\n * }\n *\n * For \"post this in #announcements\":\n * {\n * \"targetType\": \"room\",\n * \"source\": \"discord\",\n * \"identifiers\": {\n * \"roomName\": \"announcements\"\n * }\n * }\n *\n * Make sure to include the ```json``` tags around the JSON object.\n */\nconst targetExtractionTemplate = `# Task: Extract Target and Source Information\n\n# Recent Messages:\n{{recentMessages}}\n\n# Instructions:\nAnalyze the conversation to identify:\n1. The target type (user or room)\n2. The target platform/source (e.g. telegram, discord, etc)\n3. Any identifying information about the target\n\nReturn a JSON object with:\n\\`\\`\\`json\n{\n \"targetType\": \"user|room\",\n \"source\": \"platform-name\",\n \"identifiers\": {\n // Relevant identifiers for that target\n // e.g. username, roomName, etc.\n }\n}\n\\`\\`\\`\nExample outputs:\n1. For \"send a message to @dev_guru on telegram\":\n\\`\\`\\`json\n{\n \"targetType\": \"user\",\n \"source\": \"telegram\",\n \"identifiers\": {\n \"username\": \"dev_guru\"\n }\n}\n\\`\\`\\`\n\n2. For \"post this in #announcements\":\n\\`\\`\\`json\n{\n \"targetType\": \"room\",\n \"source\": \"discord\",\n \"identifiers\": {\n \"roomName\": \"announcements\"\n }\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\n/**\n * Represents an action to send a message to a user or room.\n *\n * @typedef {Action} sendMessageAction\n * @property {string} name - The name of the action.\n * @property {string[]} similes - Additional names for the action.\n * @property {string} description - Description of the action.\n * @property {function} validate - Asynchronous function to validate if the action can be executed.\n * @property {function} handler - Asynchronous function to handle the action execution.\n * @property {ActionExample[][]} examples - Examples demonstrating the usage of the action.\n */\nexport const sendMessageAction: Action = {\n\tname: \"SEND_MESSAGE\",\n\tsimiles: [\"DM\", \"MESSAGE\", \"SEND_DM\", \"POST_MESSAGE\"],\n\tdescription: \"Send a message to a user or room (other than the current one)\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\t// Check if we have permission to send messages\n\t\tconst worldId = message.roomId;\n\t\tconst agentId = runtime.agentId;\n\n\t\t// Get all components for the current room to understand available sources\n\t\tconst roomComponents = await runtime\n\t\t\t\n\t\t\t.getComponents(message.roomId, worldId, agentId);\n\n\t\t// Get source types from room components\n\t\tconst availableSources = new Set(roomComponents.map((c) => c.type));\n\n\t\t// TODO: Add ability for plugins to register their sources\n\t\t// const registeredSources = runtime.getRegisteredSources?.() || [];\n\t\t// availableSources.add(...registeredSources);\n\n\t\treturn availableSources.size > 0;\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Handle initial responses\n\t\t\tfor (const response of responses) {\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\n\t\t\tconst sourceEntityId = message.entityId;\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getRoom(message.roomId));\n\t\t\tconst worldId = room.worldId;\n\n\t\t\t// Extract target and source information\n\t\t\tconst targetPrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: targetExtractionTemplate,\n\t\t\t});\n\n\t\t\tconst targetResult = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt: targetPrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst targetData = parseJSONObjectFromText(targetResult);\n\t\t\tif (!targetData?.targetType || !targetData?.source) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I couldn't determine where you want me to send the message. Could you please specify the target (user or room) and platform?\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst source = targetData.source.toLowerCase();\n\n\t\t\tif (targetData.targetType === \"user\") {\n\t\t\t\t// Try to find the target user entity\n\t\t\t\tconst targetEntity = await findEntityByName(runtime, message, state);\n\n\t\t\t\tif (!targetEntity) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the user you want me to send a message to. Could you please provide more details about who they are?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Get the component for the specified source\n\t\t\t\tconst userComponent = await runtime\n\t\t\t\t\t\n\t\t\t\t\t.getComponent(targetEntity.id!, source, worldId, sourceEntityId);\n\n\t\t\t\tif (!userComponent) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `I couldn't find ${source} information for that user. Could you please provide their ${source} details?`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sendDirectMessage = (runtime.getService(source) as any)\n\t\t\t\t\t?.sendDirectMessage;\n\n\t\t\t\tif (!sendDirectMessage) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the user you want me to send a message to. Could you please provide more details about who they are?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Send the message using the appropriate client\n\t\t\t\ttry {\n\t\t\t\t\tawait sendDirectMessage(\n\t\t\t\t\t\truntime,\n\t\t\t\t\t\ttargetEntity.id!,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tmessage.content.text,\n\t\t\t\t\t\tworldId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Message sent to ${targetEntity.names[0]} on ${source}.`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Failed to send direct message: ${error.message}`);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I encountered an error trying to send the message. Please try again.\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (targetData.targetType === \"room\") {\n\t\t\t\t// Try to find the target room\n\t\t\t\tconst rooms = await runtime.getRooms(worldId);\n\t\t\t\tconst targetRoom = rooms.find((r) => {\n\t\t\t\t\t// Match room name from identifiers\n\t\t\t\t\treturn (\n\t\t\t\t\t\tr.name.toLowerCase() ===\n\t\t\t\t\t\ttargetData.identifiers.roomName?.toLowerCase()\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tif (!targetRoom) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the room you want me to send a message to. Could you please specify the exact room name?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sendRoomMessage = (runtime.getService(source) as any)\n\t\t\t\t\t?.sendRoomMessage;\n\n\t\t\t\tif (!sendRoomMessage) {\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I couldn't find the room you want me to send a message to. Could you please specify the exact room name?\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Send the message to the room\n\t\t\t\ttry {\n\t\t\t\t\tawait sendRoomMessage(\n\t\t\t\t\t\truntime,\n\t\t\t\t\t\ttargetRoom.id,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tmessage.content.text,\n\t\t\t\t\t\tworldId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: `Message sent to ${targetRoom.name} on ${source}.`,\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Failed to send room message: ${error.message}`);\n\t\t\t\t\tawait callback({\n\t\t\t\t\t\ttext: \"I encountered an error trying to send the message to the room. Please try again.\",\n\t\t\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in sendMessage handler: ${error}`);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing your message request.\",\n\t\t\t\tactions: [\"SEND_MESSAGE_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Send a message to @dev_guru on telegram saying 'Hello!'\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to dev_guru on telegram.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Post 'Important announcement!' in #announcements\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to announcements.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"DM Jimmy and tell him 'Meeting at 3pm'\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Message sent to Jimmy.\",\n\t\t\t\t\tactions: [\"SEND_MESSAGE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default sendMessageAction;\n","import type { ZodSchema, z } from \"zod\";\nimport { createUniqueUuid } from \"../entities\";\nimport { logger } from \"../logger\";\nimport {\n\tcomposePrompt,\n\tcomposePromptFromState,\n\tparseJSONObjectFromText,\n} from \"../prompts\";\nimport { findWorldForOwner } from \"../roles\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\tChannelType,\n\ttype Content,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype ModelType,\n\tModelTypes,\n\ttype Setting,\n\ttype State,\n\ttype WorldSettings,\n} from \"../types\";\nimport dedent from \"dedent\";\n\n/**\n * Interface representing the structure of a setting update object.\n * @interface\n * @property {string} key - The key of the setting to be updated.\n * @property {string|boolean} value - The new value for the setting, can be a string or a boolean.\n */\ninterface SettingUpdate {\n\tkey: string;\n\tvalue: string | boolean;\n}\n\nconst messageCompletionFooter = `\\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"thought\": \"<string>\", \"actions\": [\"<string>\", \"<string>\", \"<string>\"] }\n\\`\\`\\`\nDo not including any thinking or internal reflection in the \"text\" field.\n\"thought\" should be a short description of what the agent is thinking about before responding, including a brief justification for the response.`;\n\n// Template for success responses when settings are updated\n/**\n * JSDoc comment for successTemplate constant\n *\n * # Task: Generate a response for successful setting updates\n * {{providers}}\n *\n * # Update Information:\n * - Updated Settings: {{updateMessages}}\n * - Next Required Setting: {{nextSetting.name}}\n * - Remaining Required Settings: {{remainingRequired}}\n *\n * # Instructions:\n * 1. Acknowledge the successful update of settings\n * 2. Maintain {{agentName}}'s personality and tone\n * 3. Provide clear guidance on the next setting that needs to be configured\n * 4. Explain what the next setting is for and how to set it\n * 5. If appropriate, mention how many required settings remain\n *\n * Write a natural, conversational response that {{agentName}} would send about the successful update and next steps.\n * Include the actions array [\"SETTING_UPDATED\"] in your response.\n * ${messageCompletionFooter}\n */\nconst successTemplate = `# Task: Generate a response for successful setting updates\n{{providers}}\n\n# Update Information:\n- Updated Settings: {{updateMessages}}\n- Next Required Setting: {{nextSetting.name}}\n- Remaining Required Settings: {{remainingRequired}}\n\n# Instructions:\n1. Acknowledge the successful update of settings\n2. Maintain {{agentName}}'s personality and tone\n3. Provide clear guidance on the next setting that needs to be configured\n4. Explain what the next setting is for and how to set it\n5. If appropriate, mention how many required settings remain\n\nWrite a natural, conversational response that {{agentName}} would send about the successful update and next steps.\nInclude the actions array [\"SETTING_UPDATED\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for failure responses when settings couldn't be updated\n/**\n * Template for generating a response for failed setting updates.\n *\n * @template T\n * @param {string} failureTemplate - The failure template string to fill in with dynamic content.\n * @returns {string} - The filled-in template for generating the response.\n */\nconst failureTemplate = `# Task: Generate a response for failed setting updates\n\n# About {{agentName}}:\n{{bio}}\n\n# Current Settings Status:\n{{settingsStatus}}\n\n# Next Required Setting:\n- Name: {{nextSetting.name}}\n- Description: {{nextSetting.description}}\n- Required: Yes\n- Remaining Required Settings: {{remainingRequired}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Express that you couldn't understand or process the setting update\n2. Maintain {{agentName}}'s personality and tone\n3. Provide clear guidance on what setting needs to be configured next\n4. Explain what the setting is for and how to set it properly\n5. Use a helpful, patient tone\n\nWrite a natural, conversational response that {{agentName}} would send about the failed update and how to proceed.\nInclude the actions array [\"SETTING_UPDATE_FAILED\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for error responses when unexpected errors occur\n/**\n * Template for generating a response for an error during setting updates.\n *\n * The template includes placeholders for agent name, bio, recent messages,\n * and provides instructions for crafting a response.\n *\n * Instructions:\n * 1. Apologize for the technical difficulty\n * 2. Maintain agent's personality and tone\n * 3. Suggest trying again or contacting support if the issue persists\n * 4. Keep the message concise and helpful\n *\n * Actions array to include: [\"SETTING_UPDATE_ERROR\"]\n */\nconst errorTemplate = `# Task: Generate a response for an error during setting updates\n\n# About {{agentName}}:\n{{bio}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Apologize for the technical difficulty\n2. Maintain {{agentName}}'s personality and tone\n3. Suggest trying again or contacting support if the issue persists\n4. Keep the message concise and helpful\n\nWrite a natural, conversational response that {{agentName}} would send about the error.\nInclude the actions array [\"SETTING_UPDATE_ERROR\"] in your response.\n${messageCompletionFooter}`;\n\n// Template for completion responses when all required settings are configured\n/**\n * Task: Generate a response for settings completion\n *\n * About {{agentName}}:\n * {{bio}}\n *\n * Settings Status:\n * {{settingsStatus}}\n *\n * Recent Conversation:\n * {{recentMessages}}\n *\n * Instructions:\n * 1. Congratulate the user on completing the settings process\n * 2. Maintain {{agentName}}'s personality and tone\n * 3. Summarize the key settings that have been configured\n * 4. Explain what functionality is now available\n * 5. Provide guidance on what the user can do next\n * 6. Express enthusiasm about working together\n *\n * Write a natural, conversational response that {{agentName}} would send about the successful completion of settings.\n * Include the actions array [\"ONBOARDING_COMPLETE\"] in your response.\n */\nconst completionTemplate = `# Task: Generate a response for settings completion\n\n# About {{agentName}}:\n{{bio}}\n\n# Settings Status:\n{{settingsStatus}}\n\n# Recent Conversation:\n{{recentMessages}}\n\n# Instructions:\n1. Congratulate the user on completing the settings process\n2. Maintain {{agentName}}'s personality and tone\n3. Summarize the key settings that have been configured\n4. Explain what functionality is now available\n5. Provide guidance on what the user can do next\n6. Express enthusiasm about working together\n\nWrite a natural, conversational response that {{agentName}} would send about the successful completion of settings.\nInclude the actions array [\"ONBOARDING_COMPLETE\"] in your response.\n${messageCompletionFooter}`;\n\n/**\n * Generates an extraction template with formatting details.\n *\n * @param {WorldSettings} worldSettings - The settings to generate a template for.\n * @returns {string} The formatted extraction template.\n */\nconst extractionTemplate = `# Task: Extract Setting Changes from User Input\n\nI need to extract settings that the user wants to change based on their message.\n\nAvailable Settings:\n{{settingsContext}}\n\nUser message: {{content}}\n\nFor each setting mentioned in the user's input, extract the key and its new value.\nFormat your response as a JSON array of objects, each with 'key' and 'value' properties.\n\nExample response:\n\\`\\`\\`json\n[\n { \"key\": \"SETTING_NAME\", \"value\": \"extracted value\" },\n { \"key\": \"ANOTHER_SETTING\", \"value\": \"another value\" }\n]\n\\`\\`\\`\n\nIMPORTANT: Only include settings from the Available Settings list above. Ignore any other potential settings.`;\n\n/**\n * Gets settings state from world metadata\n */\n/**\n * Retrieves the settings for a specific world from the database.\n * @param {IAgentRuntime} runtime - The Agent Runtime instance.\n * @param {string} serverId - The ID of the server.\n * @returns {Promise<WorldSettings | null>} The settings of the world, or null if not found.\n */\nexport async function getWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.settings) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn world.metadata.settings as WorldSettings;\n\t} catch (error) {\n\t\tlogger.error(`Error getting settings state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Updates settings state in world metadata\n */\nexport async function updateWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n): Promise<boolean> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getWorld(worldId);\n\n\t\tif (!world) {\n\t\t\tlogger.error(`No world found for server ${serverId}`);\n\t\t\treturn false;\n\t\t}\n\n\t\t// Initialize metadata if it doesn't exist\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// Update settings state\n\t\tworld.metadata.settings = worldSettings;\n\n\t\t// Save updated world\n\t\tawait runtime.updateWorld(world);\n\n\t\treturn true;\n\t} catch (error) {\n\t\tlogger.error(`Error updating settings state: ${error}`);\n\t\treturn false;\n\t}\n}\n\n/**\n * Formats a list of settings for display\n */\nfunction formatSettingsList(worldSettings: WorldSettings): string {\n\tconst settings = Object.entries(worldSettings)\n\t\t.filter(([key]) => !key.startsWith(\"_\")) // Skip internal settings\n\t\t.map(([key, setting]) => {\n\t\t\tconst status = setting.value !== null ? \"Configured\" : \"Not configured\";\n\t\t\tconst required = setting.required ? \"Required\" : \"Optional\";\n\t\t\treturn `- ${setting.name} (${key}): ${status}, ${required}`;\n\t\t})\n\t\t.join(\"\\n\");\n\n\treturn settings || \"No settings available\";\n}\n\n/**\n * Categorizes settings by their configuration status\n */\nfunction categorizeSettings(worldSettings: WorldSettings): {\n\tconfigured: [string, Setting][];\n\trequiredUnconfigured: [string, Setting][];\n\toptionalUnconfigured: [string, Setting][];\n} {\n\tconst configured: [string, Setting][] = [];\n\tconst requiredUnconfigured: [string, Setting][] = [];\n\tconst optionalUnconfigured: [string, Setting][] = [];\n\n\tfor (const [key, setting] of Object.entries(worldSettings) as [\n\t\tstring,\n\t\tSetting,\n\t][]) {\n\t\t// Skip internal settings\n\t\tif (key.startsWith(\"_\")) continue;\n\n\t\tif (setting.value !== null) {\n\t\t\tconfigured.push([key, setting]);\n\t\t} else if (setting.required) {\n\t\t\trequiredUnconfigured.push([key, setting]);\n\t\t} else {\n\t\t\toptionalUnconfigured.push([key, setting]);\n\t\t}\n\t}\n\n\treturn { configured, requiredUnconfigured, optionalUnconfigured };\n}\n\n/**\n * Extracts setting values from user message with improved handling of multiple settings\n */\nasync function extractSettingValues(\n\truntime: IAgentRuntime,\n\t_message: Memory,\n\tstate: State,\n\tworldSettings: WorldSettings,\n): Promise<SettingUpdate[]> {\n\t// Find what settings need to be configured\n\tconst { requiredUnconfigured, optionalUnconfigured } =\n\t\tcategorizeSettings(worldSettings);\n\n\t// Generate a prompt to extract settings from the user's message\n\tconst settingsContext = requiredUnconfigured\n\t\t.concat(optionalUnconfigured)\n\t\t.map(([key, setting]) => {\n\t\t\tconst requiredStr = setting.required ? \"Required.\" : \"Optional.\";\n\t\t\treturn `${key}: ${setting.description} ${requiredStr}`;\n\t\t})\n\t\t.join(\"\\n\");\n\n\tconst basePrompt = dedent`\n I need to extract settings values from the user's message.\n \n Available settings:\n ${settingsContext}\n \n User message: ${state.text}\n\n For each setting mentioned in the user's message, extract the value.\n \n Only return settings that are clearly mentioned in the user's message.\n If a setting is mentioned but no clear value is provided, do not include it.\n `;\n\n\ttry {\n\t\t// Use runtime.useModel directly with strong typing\n\t\tconst result = await runtime.useModel<\n\t\t\ttypeof ModelTypes.OBJECT_LARGE,\n\t\t\tSettingUpdate[]\n\t\t>(ModelTypes.OBJECT_LARGE, {\n\t\t\tprompt: basePrompt,\n\t\t\toutput: \"array\",\n\t\t\tschema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tkey: { type: \"string\" },\n\t\t\t\t\t\tvalue: { type: \"string\" },\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"key\", \"value\"],\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\n\t\t// Validate the extracted settings\n\t\tif (!result || !Array.isArray(result)) {\n\t\t\treturn [];\n\t\t}\n\n\t\t// Filter out any invalid settings\n\t\treturn result.filter(({ key, value }) => {\n\t\t\treturn Boolean(key && value && worldSettings[key]);\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"Error extracting settings:\", error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Processes multiple setting updates atomically\n */\nasync function processSettingUpdates(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n\tupdates: SettingUpdate[],\n): Promise<{ updatedAny: boolean; messages: string[] }> {\n\tif (!updates.length) {\n\t\treturn { updatedAny: false, messages: [] };\n\t}\n\n\tconst messages: string[] = [];\n\tlet updatedAny = false;\n\n\ttry {\n\t\t// Create a copy of the state for atomic updates\n\t\tconst updatedState = { ...worldSettings };\n\n\t\t// Process all updates\n\t\tfor (const update of updates) {\n\t\t\tconst setting = updatedState[update.key];\n\t\t\tif (!setting) continue;\n\n\t\t\t// Check dependencies if they exist\n\t\t\tif (setting.dependsOn?.length) {\n\t\t\t\tconst dependenciesMet = setting.dependsOn.every(\n\t\t\t\t\t(dep) => updatedState[dep]?.value !== null,\n\t\t\t\t);\n\t\t\t\tif (!dependenciesMet) {\n\t\t\t\t\tmessages.push(`Cannot update ${setting.name} - dependencies not met`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update the setting\n\t\t\tupdatedState[update.key] = {\n\t\t\t\t...setting,\n\t\t\t\tvalue: update.value,\n\t\t\t};\n\n\t\t\tmessages.push(`Updated ${setting.name} successfully`);\n\t\t\tupdatedAny = true;\n\n\t\t\t// Execute onSetAction if defined\n\t\t\tif (setting.onSetAction) {\n\t\t\t\tconst actionMessage = setting.onSetAction(update.value);\n\t\t\t\tif (actionMessage) {\n\t\t\t\t\tmessages.push(actionMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If any updates were made, save the entire state to world metadata\n\t\tif (updatedAny) {\n\t\t\t// Save to world metadata\n\t\t\tconst saved = await updateWorldSettings(runtime, serverId, updatedState);\n\n\t\t\tif (!saved) {\n\t\t\t\tthrow new Error(\"Failed to save updated state to world metadata\");\n\t\t\t}\n\n\t\t\t// Verify save by retrieving it again\n\t\t\tconst savedState = await getWorldSettings(runtime, serverId);\n\t\t\tif (!savedState) {\n\t\t\t\tthrow new Error(\"Failed to verify state save\");\n\t\t\t}\n\t\t}\n\n\t\treturn { updatedAny, messages };\n\t} catch (error) {\n\t\tlogger.error(\"Error processing setting updates:\", error);\n\t\treturn {\n\t\t\tupdatedAny: false,\n\t\t\tmessages: [\"Error occurred while updating settings\"],\n\t\t};\n\t}\n}\n\n/**\n * Handles the completion of settings when all required settings are configured\n */\nasync function handleOnboardingComplete(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Generate completion message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\tsettingsStatus: formatSettingsList(worldSettings),\n\t\t\t},\n\t\t\ttemplate: completionTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error handling settings completion: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"Great! All required settings have been configured. Your server is now fully set up and ready to use.\",\n\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates a success response for setting updates\n */\nasync function generateSuccessResponse(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tmessages: string[],\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Check if all required settings are now configured\n\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\n\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t// All required settings are configured, complete settings\n\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\treturn;\n\t\t}\n\n\t\tconst requiredUnconfiguredString = requiredUnconfigured\n\t\t\t.map(([key, setting]) => `${key}: ${setting.name}`)\n\t\t\t.join(\"\\n\");\n\n\t\t// Generate success message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\tupdateMessages: messages.join(\"\\n\"),\n\t\t\t\tnextSetting: requiredUnconfiguredString,\n\t\t\t\tremainingRequired: requiredUnconfigured.length.toString(),\n\t\t\t},\n\t\t\ttemplate: successTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating success response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"Settings updated successfully. Please continue with the remaining configuration.\",\n\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates a failure response when no settings could be updated\n */\nasync function generateFailureResponse(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\t// Get next required setting\n\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\n\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t// All required settings are configured, complete settings\n\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\treturn;\n\t\t}\n\n\t\tconst requiredUnconfiguredString = requiredUnconfigured\n\t\t\t.map(([key, setting]) => `${key}: ${setting.name}`)\n\t\t\t.join(\"\\n\");\n\n\t\t// Generate failure message\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\tnextSetting: requiredUnconfiguredString,\n\t\t\t\tremainingRequired: requiredUnconfigured.length.toString(),\n\t\t\t},\n\t\t\ttemplate: failureTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATE_FAILED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating failure response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"I couldn't understand your settings update. Please try again with a clearer format.\",\n\t\t\tactions: [\"SETTING_UPDATE_FAILED\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Generates an error response for unexpected errors\n */\nasync function generateErrorResponse(\n\truntime: IAgentRuntime,\n\tstate: State,\n\tcallback: HandlerCallback,\n): Promise<void> {\n\ttry {\n\t\tconst prompt = composePromptFromState({\n\t\t\tstate,\n\t\t\ttemplate: errorTemplate,\n\t\t});\n\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst responseContent = parseJSONObjectFromText(response) as Content;\n\n\t\tawait callback({\n\t\t\ttext: responseContent.text,\n\t\t\tactions: [\"SETTING_UPDATE_ERROR\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t} catch (error) {\n\t\tlogger.error(`Error generating error response: ${error}`);\n\t\tawait callback({\n\t\t\ttext: \"I'm sorry, but I encountered an error while processing your request. Please try again or contact support if the issue persists.\",\n\t\t\tactions: [\"SETTING_UPDATE_ERROR\"],\n\t\t\tsource: \"discord\",\n\t\t});\n\t}\n}\n\n/**\n * Enhanced settings action with improved state management and logging\n * Updated to use world metadata instead of cache\n */\nconst updateSettingsAction: Action = {\n\tname: \"UPDATE_SETTINGS\",\n\tsimiles: [\"UPDATE_SETTING\", \"SAVE_SETTING\", \"SET_CONFIGURATION\", \"CONFIGURE\"],\n\tdescription:\n\t\t\"Saves a configuration setting during the onboarding process, or update an existing setting. Use this when you are onboarding with a world owner or admin.\",\n\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tif (message.content.channelType !== ChannelType.DM) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Skipping settings in non-DM channel (type: ${message.content.channelType})`,\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Find the server where this user is the owner\n\t\t\tlogger.info(`Looking for server where user ${message.entityId} is owner`);\n\t\t\tconst world = await findWorldForOwner(runtime, message.entityId);\n\t\t\tif (!world) {\n\t\t\t\tlogger.error(`No server ownership found for user ${message.entityId}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Check if there's an active settings state in world metadata\n\t\t\tconst worldSettings = world.metadata.settings;\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.error(`No settings state found for server ${world.serverId}`);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tlogger.info(`Found valid settings state for server ${world.serverId}`);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error validating settings action: ${error}`);\n\t\t\treturn false;\n\t\t}\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Find the server where this user is the owner\n\t\t\tlogger.info(`Handler looking for server for user ${message.entityId}`);\n\t\t\tconst serverOwnership = await findWorldForOwner(\n\t\t\t\truntime,\n\t\t\t\tmessage.entityId,\n\t\t\t);\n\t\t\tif (!serverOwnership) {\n\t\t\t\tlogger.error(`No server found for user ${message.entityId} in handler`);\n\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst serverId = serverOwnership.serverId;\n\t\t\tlogger.info(`Using server ID: ${serverId}`);\n\n\t\t\t// Get settings state from world metadata\n\t\t\tconst worldSettings = await getWorldSettings(runtime, serverId);\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t`No settings state found for server ${serverId} in handler`,\n\t\t\t\t);\n\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if all required settings are already configured\n\t\t\tconst { requiredUnconfigured } = categorizeSettings(worldSettings);\n\t\t\tif (requiredUnconfigured.length === 0) {\n\t\t\t\tlogger.info(\"All required settings configured, completing settings\");\n\t\t\t\tawait handleOnboardingComplete(runtime, worldSettings, state, callback);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract setting values from message\n\t\t\tlogger.info(`Extracting settings from message: ${message.content.text}`);\n\t\t\tconst extractedSettings = await extractSettingValues(\n\t\t\t\truntime,\n\t\t\t\tmessage,\n\t\t\t\tstate,\n\t\t\t\tworldSettings,\n\t\t\t);\n\t\t\tlogger.info(`Extracted ${extractedSettings.length} settings`);\n\n\t\t\t// Process extracted settings\n\t\t\tconst updateResults = await processSettingUpdates(\n\t\t\t\truntime,\n\t\t\t\tserverId,\n\t\t\t\tworldSettings,\n\t\t\t\textractedSettings,\n\t\t\t);\n\n\t\t\t// Generate appropriate response\n\t\t\tif (updateResults.updatedAny) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Successfully updated settings: ${updateResults.messages.join(\", \")}`,\n\t\t\t\t);\n\n\t\t\t\t// Get updated settings state\n\t\t\t\tconst updatedWorldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\tif (!updatedWorldSettings) {\n\t\t\t\t\tlogger.error(\"Failed to retrieve updated settings state\");\n\t\t\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tawait generateSuccessResponse(\n\t\t\t\t\truntime,\n\t\t\t\t\tupdatedWorldSettings,\n\t\t\t\t\tstate,\n\t\t\t\t\tupdateResults.messages,\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tlogger.info(\"No settings were updated\");\n\t\t\t\tawait generateFailureResponse(runtime, worldSettings, state, callback);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in settings handler: ${error}`);\n\t\t\tawait generateErrorResponse(runtime, state, callback);\n\t\t}\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I want to set up the welcome channel to #general\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Perfect! I've updated your welcome channel to #general. Next, we should configure the automated greeting message that new members will receive.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Let's set the bot prefix to !\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Great choice! I've set the command prefix to '!'. Now you can use commands like !help, !info, etc.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Enable auto-moderation for bad language\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Auto-moderation for inappropriate language has been enabled. I'll now filter messages containing offensive content.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"For server logs, use the #server-logs channel\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've configured #server-logs as your logging channel. All server events like joins, leaves, and moderation actions will be recorded there.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'd like to have role self-assignment in the #roles channel\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Role self-assignment has been set up in the #roles channel. Members can now assign themselves roles by interacting with messages there.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Make music commands available in voice-text channels only\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your music command settings - they'll now only work in voice-text channels. This helps keep other channels clear of music spam.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"For server timezone, set it to EST\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Server timezone has been set to Eastern Standard Time (EST). All scheduled events and timestamps will now display in this timezone.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set verification level to email verified users only\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated the verification requirement to email verified accounts only. This adds an extra layer of security to your server.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I want to turn off level-up notifications\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Level-up notifications have been disabled. Members will still earn experience and level up, but there won't be any automatic announcements. You can still view levels with the appropriate commands.\",\n\t\t\t\t\tactions: [\"SETTING_UPDATED\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"My server name is 'Gaming Lounge'\",\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Great! I've saved 'Gaming Lounge' as your server name. This helps me personalize responses and know how to refer to your community. We've completed all the required settings! Your server is now fully configured and ready to use. You can always adjust these settings later if needed.\",\n\t\t\t\t\tactions: [\"ONBOARDING_COMPLETE\"],\n\t\t\t\t\tsource: \"discord\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateSettingsAction;\n","import { composePromptFromState } from \"../prompts\";\nimport { booleanFooter, parseBooleanFromText } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Template for deciding if an agent should stop closely following a previously followed room\n *\n * @type {string}\n */\nconst shouldUnfollowTemplate = `# Task: Decide if {{agentName}} should stop closely following this previously followed room and only respond when mentioned.\n\n{{recentMessages}}\n\nShould {{agentName}} stop closely following this previously followed room and only respond when mentioned?\nRespond with YES if:\n- The user has suggested that {{agentName}} is over-participating or being disruptive\n- {{agentName}}'s eagerness to contribute is not well-received by the users\n- The conversation has shifted to a topic where {{agentName}} has less to add\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\n/**\n * Action for unfollowing a room.\n *\n * - Name: UNFOLLOW_ROOM\n * - Similes: [\"UNFOLLOW_CHAT\", \"UNFOLLOW_CONVERSATION\", \"UNFOLLOW_ROOM\", \"UNFOLLOW_THREAD\"]\n * - Description: Stop following this channel. You can still respond if explicitly mentioned, but you won't automatically chime in anymore. Unfollow if you're annoying people or have been asked to.\n * - Validate function checks if the room state is \"FOLLOWED\".\n * - Handler function handles the unfollowing logic based on user input.\n * - Examples provide sample interactions for unfollowing a room.\n */\nexport const unfollowRoomAction: Action = {\n\tname: \"UNFOLLOW_ROOM\",\n\tsimiles: [\n\t\t\"UNFOLLOW_CHAT\",\n\t\t\"UNFOLLOW_CONVERSATION\",\n\t\t\"UNFOLLOW_ROOM\",\n\t\t\"UNFOLLOW_THREAD\",\n\t],\n\tdescription:\n\t\t\"Stop following this channel. You can still respond if explicitly mentioned, but you won't automatically chime in anymore. Unfollow if you're annoying people or have been asked to.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState === \"FOLLOWED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldUnfollow(state: State): Promise<boolean> {\n\t\t\tconst shouldUnfollowPrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldUnfollowTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt: shouldUnfollowPrompt,\n\t\t\t});\n\n\t\t\tconst parsedResponse = parseBooleanFromText(response.trim());\n\n\t\t\treturn parsedResponse;\n\t\t}\n\n\t\tif (await _shouldUnfollow(state)) {\n\t\t\tawait runtime\n\t\t\t\t\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, null);\n\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getRoom(message.roomId));\n\n\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tagentId: message.agentId,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\tthought: `I unfollowed the room ${room.name}`,\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM_START\"],\n\t\t\t\t},\n\t\t\t});\n\t\t} else {\n\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tentityId: message.entityId,\n\t\t\t\tagentId: message.agentId,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcontent: {\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\tthought: \"I tried to unfollow a room but I'm not in a room\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM_FAILED\"],\n\t\t\t\t},\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: \"UNFOLLOW_ROOM\",\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey {{name2}} stop participating in this channel for now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Alright, I will stop chiming in\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Has anyone tried the new update\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Yes, it's pretty slick\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, please stop following this chat\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Understood\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name3}} stop participating here so frequently\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'll only respond when mentioned\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"thoughts on the budget\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}} should we increase it\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"A small increase could work given our past results...\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, unfollow this room for now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I'll only engage when asked\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"wait {{name3}} come back and give me your thoughts\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Okay... I think it's intuitive, parallel tests are nice\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"yo {{name2}} chill on all the messages damn\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"my bad, I'll step back\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} STOP MESSAGING IN THIS ROOM\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"No problem, I've got other stuff to work on\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} ur bein annoyin pls stop\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry, ill chill\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, please cease engaging in this room\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"No sweat\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Excited for the weekend, any plans folks\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}} you're getting a bit too chatty, tone it down\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Noted\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"hey {{name2}} can u like... not\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sorry, I'll go work on other things\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, your eagerness is disruptive, please desist\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"My apologies, I shall withdraw post-haste\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} stahp followin dis room plz\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"kk sry ill stahppp\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"stfu you stupid bot\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sry\",\n\t\t\t\t\tactions: [\"UNFOLLOW_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import logger from \"../logger\";\nimport { composePromptFromState } from \"../prompts\";\nimport { booleanFooter } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n} from \"../types\";\n\n/**\n * Template for determining if an agent should unmute a previously muted room.\n * * @type { string }\n */\nexport const shouldUnmuteTemplate = `# Task: Decide if {{agentName}} should unmute this previously muted room and start considering it for responses again.\n\n{{recentMessages}}\n\nShould {{agentName}} unmute this previously muted room and start considering it for responses again?\nRespond with YES if:\n- The user has explicitly asked {{agentName}} to start responding again\n- The user seems to want to re-engage with {{agentName}} in a respectful manner\n- The tone of the conversation has improved and {{agentName}}'s input would be welcome\n\nOtherwise, respond with NO.\n${booleanFooter}`;\n\n/**\n * Action to unmute a room, allowing the agent to consider responding to messages again.\n *\n * @name UNMUTE_ROOM\n * @similes [\"UNMUTE_CHAT\", \"UNMUTE_CONVERSATION\", \"UNMUTE_ROOM\", \"UNMUTE_THREAD\"]\n * @description Unmutes a room, allowing the agent to consider responding to messages again.\n *\n * @param {IAgentRuntime} runtime - The agent runtime to access runtime functionalities.\n * @param {Memory} message - The message containing information about the room.\n * @returns {Promise<boolean>} A boolean value indicating if the room was successfully unmuted.\n */\nexport const unmuteRoomAction: Action = {\n\tname: \"UNMUTE_ROOM\",\n\tsimiles: [\n\t\t\"UNMUTE_CHAT\",\n\t\t\"UNMUTE_CONVERSATION\",\n\t\t\"UNMUTE_ROOM\",\n\t\t\"UNMUTE_THREAD\",\n\t],\n\tdescription:\n\t\t\"Unmutes a room, allowing the agent to consider responding to messages again.\",\n\tvalidate: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst roomId = message.roomId;\n\t\tconst roomState = await runtime\n\t\t\t\n\t\t\t.getParticipantUserState(roomId, runtime.agentId);\n\t\treturn roomState === \"MUTED\";\n\t},\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t\t_options?: { [key: string]: unknown },\n\t\t_callback?: HandlerCallback,\n\t\t_responses?: Memory[],\n\t) => {\n\t\tasync function _shouldUnmute(state: State): Promise<boolean> {\n\t\t\tconst shouldUnmutePrompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: shouldUnmuteTemplate, // Define this template separately\n\t\t\t});\n\n\t\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\truntime,\n\t\t\t\tprompt: shouldUnmutePrompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\tconst cleanedResponse = response.trim().toLowerCase();\n\n\t\t\t// Handle various affirmative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"true\" ||\n\t\t\t\tcleanedResponse === \"yes\" ||\n\t\t\t\tcleanedResponse === \"y\" ||\n\t\t\t\tcleanedResponse.includes(\"true\") ||\n\t\t\t\tcleanedResponse.includes(\"yes\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought:\n\t\t\t\t\t\t\t\"I will now unmute this room and start considering it for responses again\",\n\t\t\t\t\t\tactions: [\"UNMUTE_ROOM_STARTED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"UNMUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Handle various negative responses\n\t\t\tif (\n\t\t\t\tcleanedResponse === \"false\" ||\n\t\t\t\tcleanedResponse === \"no\" ||\n\t\t\t\tcleanedResponse === \"n\" ||\n\t\t\t\tcleanedResponse.includes(\"false\") ||\n\t\t\t\tcleanedResponse.includes(\"no\")\n\t\t\t) {\n\t\t\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\tagentId: message.agentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tsource: message.content.source,\n\t\t\t\t\t\tthought: \"I tried to unmute a room but I decided not to\",\n\t\t\t\t\t\tactions: [\"UNMUTE_ROOM_FAILED\"],\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttype: \"UNMUTE_ROOM\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Default to false if response is unclear\n\t\t\tlogger.warn(`Unclear boolean response: ${response}, defaulting to false`);\n\t\t\treturn false;\n\t\t}\n\n\t\tif (await _shouldUnmute(state)) {\n\t\t\tawait runtime\n\t\t\t\t\n\t\t\t\t.setParticipantUserState(message.roomId, runtime.agentId, null);\n\t\t}\n\n\t\tconst room = await runtime.getRoom(message.roomId);\n\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tentityId: message.entityId,\n\t\t\tagentId: message.agentId,\n\t\t\troomId: message.roomId,\n\t\t\tcontent: {\n\t\t\t\tthought: `I unmuted the room ${room.name}`,\n\t\t\t\tactions: [\"UNMUTE_ROOM_START\"],\n\t\t\t},\n\t\t});\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name3}}, you can unmute this channel now\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Done\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I could use some help troubleshooting this bug.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name3}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Can you post the specific error message\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}}, please unmute this room. We could use your input again.\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Sounds good\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} wait you should come back and chat in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"im back\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"unmute urself {{name2}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"unmuted\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"ay {{name2}} get back in here\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"sup yall\",\n\t\t\t\t\tactions: [\"UNMUTE_ROOM\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","// I want to create an action that lets anyone create or update a component for an entity.\n// Components represent different sources of data about an entity (telegram, twitter, etc)\n// Sources can be registered by plugins or inferred from room context and available components\n// The action should first check if the component exists for the entity, and if not, create it.\n// We want to use an LLM (runtime.useModel) to generate the component data.\n// We should include the prior component data if it exists, and have the LLM output an update to the component.\n// sourceEntityId represents who is making the update, entityId is who they are talking about\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { findEntityByName } from \"../entities\";\nimport { logger } from \"../logger\";\nimport { composePromptFromState } from \"../prompts\";\nimport {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\n/**\n * Component Template for Task: Extract Source and Update Component Data\n *\n * @type {string}\n */\nconst componentTemplate = `# Task: Extract Source and Update Component Data\n\n{{recentMessages}}\n\n{{#if existingData}}\n# Existing Component Data:\n\\`\\`\\`json\n{{existingData}}\n\\`\\`\\`\n{{/if}}\n\n# Instructions:\n1. Analyze the conversation to identify:\n - The source/platform being referenced (e.g. telegram, twitter, discord)\n - Any specific component data being shared\n\n2. Generate updated component data that:\n - Is specific to the identified platform/source\n - Preserves existing data when appropriate\n - Includes the new information from the conversation\n - Contains only valid data for this component type\n\nReturn a JSON object with the following structure:\n\\`\\`\\`json\n{\n \"source\": \"platform-name\",\n \"data\": {\n // Component-specific fields\n // e.g. username, username, displayName, etc.\n }\n}\n\\`\\`\\`\n\nExample outputs:\n1. For \"my telegram username is @dev_guru\":\n\\`\\`\\`json\n{\n \"source\": \"telegram\",\n \"data\": {\n \"username\": \"dev_guru\"\n }\n}\n\\`\\`\\`\n\n2. For \"update my twitter handle to @tech_master\":\n\\`\\`\\`json\n{\n \"source\": \"twitter\",\n \"data\": {\n \"username\": \"tech_master\"\n }\n}\n\\`\\`\\`\n\nMake sure to include the \\`\\`\\`json\\`\\`\\` tags around the JSON object.`;\n\n/**\n * Action for updating contact details for a user entity.\n *\n * @name UPDATE_ENTITY\n * @description Add or edit contact details for a user entity (like twitter, discord, email address, etc.)\n *\n * @param {IAgentRuntime} _runtime - The runtime environment.\n * @param {Memory} _message - The message data.\n * @param {State} _state - The current state.\n * @returns {Promise<boolean>} Returns a promise indicating if validation was successful.\n *\n * @param {IAgentRuntime} runtime - The runtime environment.\n * @param {Memory} message - The message data.\n * @param {State} state - The current state.\n * @param {any} _options - Additional options.\n * @param {HandlerCallback} callback - The callback function.\n * @param {Memory[]} responses - Array of responses.\n * @returns {Promise<void>} Promise that resolves after handling the update entity action.\n *\n * @example\n * [\n * [\n * {\n * name: \"{{name1}}\",\n * content: {\n * text: \"Please update my telegram username to @dev_guru\",\n * },\n * },\n * {\n * name: \"{{name2}}\",\n * content: {\n * text: \"I've updated your telegram information.\",\n * actions: [\"UPDATE_ENTITY\"],\n * },\n * },\n * ],\n * ...\n * ]\n */\nexport const updateEntityAction: Action = {\n\tname: \"UPDATE_CONTACT\",\n\tsimiles: [\"UPDATE_ENTITY\"],\n\tdescription:\n\t\t\"Add or edit contact details for a person you are talking to or observing in the conversation. Use this when you learn this information from the conversation about a contact. This is for the agent to relate entities across platforms, not for world settings or configuration.\",\n\n\tvalidate: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t\t_state: State,\n\t): Promise<boolean> => {\n\t\t// Check if we have any registered sources or existing components that could be updated\n\t\t// const worldId = message.roomId;\n\t\t// const agentId = runtime.agentId;\n\n\t\t// // Get all components for the current room to understand available sources\n\t\t// const roomComponents = await runtime.getComponents(message.roomId, worldId, agentId);\n\n\t\t// // Get source types from room components\n\t\t// const availableSources = new Set(roomComponents.map(c => c.type));\n\t\treturn true; // availableSources.size > 0;\n\t},\n\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<void> => {\n\t\ttry {\n\t\t\t// Handle initial responses\n\t\t\tfor (const response of responses) {\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\n\t\t\tconst sourceEntityId = message.entityId;\n\t\t\tconst _roomId = message.roomId;\n\t\t\tconst agentId = runtime.agentId;\n\t\t\tconst room =\n\t\t\t\tstate.data.room ??\n\t\t\t\t(await runtime.getRoom(message.roomId));\n\t\t\tconst worldId = room.worldId;\n\n\t\t\t// First, find the entity being referenced\n\t\t\tconst entity = await findEntityByName(runtime, message, state);\n\n\t\t\tif (!entity) {\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I'm not sure which entity you're trying to update. Could you please specify who you're talking about?\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get existing component if it exists - we'll get this after the LLM identifies the source\n\t\t\tlet existingComponent = null;\n\n\t\t\t// Generate component data using the combined template\n\t\t\tconst prompt = composePromptFromState({\n\t\t\t\tstate,\n\t\t\t\ttemplate: componentTemplate,\n\t\t\t});\n\n\t\t\tconst result = await runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\t\tprompt,\n\t\t\t\tstopSequences: [],\n\t\t\t});\n\n\t\t\t// Parse the generated data\n\t\t\tlet parsedResult: any;\n\t\t\ttry {\n\t\t\t\tconst jsonMatch = result.match(/\\{[\\s\\S]*\\}/);\n\t\t\t\tif (!jsonMatch) {\n\t\t\t\t\tthrow new Error(\"No valid JSON found in the LLM response\");\n\t\t\t\t}\n\n\t\t\t\tparsedResult = JSON.parse(jsonMatch[0]);\n\n\t\t\t\tif (!parsedResult.source || !parsedResult.data) {\n\t\t\t\t\tthrow new Error(\"Invalid response format - missing source or data\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Failed to parse component data: ${error.message}`);\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: \"I couldn't properly understand the component information. Please try again with more specific information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst componentType = parsedResult.source.toLowerCase();\n\t\t\tconst componentData = parsedResult.data;\n\n\t\t\t// Now that we know the component type, get the existing component if it exists\n\t\t\texistingComponent = await runtime\n\t\t\t\t\n\t\t\t\t.getComponent(entity.id!, componentType, worldId, sourceEntityId);\n\n\t\t\t// Create or update the component\n\t\t\tif (existingComponent) {\n\t\t\t\tawait runtime.updateComponent({\n\t\t\t\t\tid: existingComponent.id,\n\t\t\t\t\tentityId: entity.id!,\n\t\t\t\t\tworldId,\n\t\t\t\t\ttype: componentType,\n\t\t\t\t\tdata: componentData,\n\t\t\t\t\tagentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tsourceEntityId,\n\t\t\t\t});\n\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `I've updated the ${componentType} information for ${entity.names[0]}.`,\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tawait runtime.createComponent({\n\t\t\t\t\tid: uuidv4() as UUID,\n\t\t\t\t\tentityId: entity.id!,\n\t\t\t\t\tworldId,\n\t\t\t\t\ttype: componentType,\n\t\t\t\t\tdata: componentData,\n\t\t\t\t\tagentId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tsourceEntityId,\n\t\t\t\t});\n\n\t\t\t\tawait callback({\n\t\t\t\t\ttext: `I've added new ${componentType} information for ${entity.names[0]}.`,\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t\tsource: message.content.source,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error in updateEntity handler: ${error}`);\n\t\t\tawait callback({\n\t\t\t\ttext: \"There was an error processing the entity information.\",\n\t\t\t\tactions: [\"UPDATE_ENTITY_ERROR\"],\n\t\t\t\tsource: message.content.source,\n\t\t\t});\n\t\t}\n\t},\n\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Please update my telegram username to @dev_guru\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your telegram information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Set Jimmy's twitter username to @jimmy_codes\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated Jimmy's twitter information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Update my discord username to dev_guru#1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I've updated your discord information.\",\n\t\t\t\t\tactions: [\"UPDATE_ENTITY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n};\n\nexport default updateEntityAction;\n","import { z } from \"zod\";\nimport { getEntityDetails } from \"../entities\";\nimport logger from \"../logger\";\nimport { MemoryManager } from \"../memory\";\nimport { composePrompt } from \"../prompts\";\nimport {\n\ttype Entity,\n\ttype Evaluator,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\n// Schema definitions for the reflection output\nconst relationshipSchema = z.object({\n\tsourceEntityId: z.string(),\n\ttargetEntityId: z.string(),\n\ttags: z.array(z.string()),\n\tmetadata: z\n\t\t.object({\n\t\t\tinteractions: z.number(),\n\t\t})\n\t\t.optional(),\n});\n\n/**\n * Defines a schema for reflecting on a topic, including facts and relationships.\n * @type {import(\"zod\").object}\n * @property {import(\"zod\").array<import(\"zod\").object<{claim: import(\"zod\").string(), type: import(\"zod\").string(), in_bio: import(\"zod\").boolean(), already_known: import(\"zod\").boolean()}>} facts Array of facts about the topic\n * @property {import(\"zod\").array<import(\"zod\").object>} relationships Array of relationships related to the topic\n */\nconst reflectionSchema = z.object({\n\t// reflection: z.string(),\n\tfacts: z.array(\n\t\tz.object({\n\t\t\tclaim: z.string(),\n\t\t\ttype: z.string(),\n\t\t\tin_bio: z.boolean(),\n\t\t\talready_known: z.boolean(),\n\t\t}),\n\t),\n\trelationships: z.array(relationshipSchema),\n});\n\n/**\n * Template string for generating Agent Reflection, Extracting Facts, and Relationships.\n *\n * @type {string}\n */\nconst reflectionTemplate = `# Task: Generate Agent Reflection, Extract Facts and Relationships\n\n{{providers}}\n\n# Examples:\n{{evaluationExamples}}\n\n# Entities in Room\n{{entitiesInRoom}}\n\n# Existing Relationships\n{{existingRelationships}}\n\n# Current Context:\nAgent Name: {{agentName}}\nRoom Type: {{roomType}}\nMessage Sender: {{senderName}} (ID: {{senderId}})\n\n{{recentMessages}}\n\n# Known Facts:\n{{knownFacts}}\n\n# Instructions:\n1. Generate a self-reflective thought on the conversation. How are you doing? You're not being annoying, are you?\n2. Extract new facts from the conversation.\n3. Identify and describe relationships between entities.\n - The sourceEntityId is the UUID of the entity initiating the interaction.\n - The targetEntityId is the UUID of the entity being interacted with.\n - Relationships are one-direction, so a friendship would be two entity relationships where each entity is both the source and the target of the other.\n\nGenerate a response in the following format:\n\\`\\`\\`json\n{\n \"thought\": \"a self-reflective thought on the conversation\",\n \"facts\": [\n {\n \"claim\": \"factual statement\",\n \"type\": \"fact|opinion|status\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"entity_initiating_interaction\",\n \"targetEntityId\": \"entity_being_interacted_with\",\n \"tags\": [\"group_interaction|voice_interaction|dm_interaction\", \"additional_tag1\", \"additional_tag2\"]\n }\n ]\n}\n\\`\\`\\``;\n\n/**\n * Resolve an entity name to their UUID\n * @param name - Name to resolve\n * @param entities - List of entities to search through\n * @returns UUID if found, throws error if not found or if input is not a valid UUID\n */\n/**\n * Resolves an entity ID by searching through a list of entities.\n *\n * @param {UUID} entityId - The ID of the entity to resolve.\n * @param {Entity[]} entities - The list of entities to search through.\n * @returns {UUID} - The resolved UUID of the entity.\n * @throws {Error} - If the entity ID cannot be resolved to a valid UUID.\n */\nfunction resolveEntity(entityId: UUID, entities: Entity[]): UUID {\n\t// First try exact UUID match\n\tif (\n\t\t/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(\n\t\t\tentityId,\n\t\t)\n\t) {\n\t\treturn entityId as UUID;\n\t}\n\n\tlet entity;\n\n\t// Try to match the entityId exactly\n\tentity = entities.find((a) => a.id === entityId);\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\t// Try partial UUID match with entityId\n\tentity = entities.find((a) => a.id.includes(entityId));\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\t// Try name match as last resort\n\tentity = entities.find((a) =>\n\t\ta.names.some((n) => n.toLowerCase().includes(entityId.toLowerCase())),\n\t);\n\tif (entity) {\n\t\treturn entity.id;\n\t}\n\n\tthrow new Error(`Could not resolve entityId \"${entityId}\" to a valid UUID`);\n}\n\nconst generateObject = async ({\n\truntime,\n\tprompt,\n\tmodelType = ModelTypes.TEXT_SMALL,\n\tstopSequences = [],\n\toutput = \"object\",\n\tenumValues = [],\n\tschema,\n}): Promise<any> => {\n\tif (!prompt) {\n\t\tconst errorMessage = \"generateObject prompt is empty\";\n\t\tconsole.error(errorMessage);\n\t\tthrow new Error(errorMessage);\n\t}\n\n\t// Special handling for enum output type\n\tif (output === \"enum\" && enumValues) {\n\t\tconst response = await runtime.useModel(modelType, {\n\t\t\truntime,\n\t\t\tprompt,\n\t\t\tmodelType,\n\t\t\tstopSequences,\n\t\t\tmaxTokens: 8,\n\t\t\tobject: true,\n\t\t});\n\n\t\t// Clean up the response to extract just the enum value\n\t\tconst cleanedResponse = response.trim();\n\n\t\t// Verify the response is one of the allowed enum values\n\t\tif (enumValues.includes(cleanedResponse)) {\n\t\t\treturn cleanedResponse;\n\t\t}\n\n\t\t// If the response includes one of the enum values (case insensitive)\n\t\tconst matchedValue = enumValues.find((value) =>\n\t\t\tcleanedResponse.toLowerCase().includes(value.toLowerCase()),\n\t\t);\n\n\t\tif (matchedValue) {\n\t\t\treturn matchedValue;\n\t\t}\n\n\t\tlogger.error(`Invalid enum value received: ${cleanedResponse}`);\n\t\tlogger.error(`Expected one of: ${enumValues.join(\", \")}`);\n\t\treturn null;\n\t}\n\n\t// Regular object/array generation\n\tconst response = await runtime.useModel(modelType, {\n\t\truntime,\n\t\tprompt,\n\t\tmodelType,\n\t\tstopSequences,\n\t\tobject: true,\n\t});\n\n\tlet jsonString = response;\n\n\t// Find appropriate brackets based on expected output type\n\tconst firstChar = output === \"array\" ? \"[\" : \"{\";\n\tconst lastChar = output === \"array\" ? \"]\" : \"}\";\n\n\tconst firstBracket = response.indexOf(firstChar);\n\tconst lastBracket = response.lastIndexOf(lastChar);\n\n\tif (firstBracket !== -1 && lastBracket !== -1 && firstBracket < lastBracket) {\n\t\tjsonString = response.slice(firstBracket, lastBracket + 1);\n\t}\n\n\tif (jsonString.length === 0) {\n\t\tlogger.error(`Failed to extract JSON ${output} from model response`);\n\t\treturn null;\n\t}\n\n\t// Parse the JSON string\n\ttry {\n\t\tconst json = JSON.parse(jsonString);\n\n\t\t// Validate against schema if provided\n\t\tif (schema) {\n\t\t\treturn schema.parse(json);\n\t\t}\n\n\t\treturn json;\n\t} catch (_error) {\n\t\tlogger.error(`Failed to parse JSON ${output}`);\n\t\tlogger.error(jsonString);\n\t\treturn null;\n\t}\n};\n\nasync function handler(runtime: IAgentRuntime, message: Memory, state?: State) {\n\tconst { agentId, roomId } = message;\n\n\t// Get known facts\n\tconst factsManager = new MemoryManager({\n\t\truntime,\n\t\ttableName: \"facts\",\n\t});\n\n\t// Run all queries in parallel\n\tconst [existingRelationships, entities, knownFacts] = await Promise.all([\n\t\truntime.getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t}),\n\t\tgetEntityDetails({ runtime, roomId }),\n\t\tfactsManager.getMemories({\n\t\t\troomId,\n\t\t\tagentId,\n\t\t\tcount: 30,\n\t\t\tunique: true,\n\t\t}),\n\t]);\n\n\tconst prompt = composePrompt({\n\t\tstate: {\n\t\t\t...state.values,\n\t\t\tknownFacts: formatFacts(knownFacts),\n\t\t\troomType: message.content.channelType as string,\n\t\t\tentitiesInRoom: JSON.stringify(entities),\n\t\t\texistingRelationships: JSON.stringify(existingRelationships),\n\t\t\tsenderId: message.entityId,\n\t\t},\n\t\ttemplate:\n\t\t\truntime.character.templates?.reflectionTemplate || reflectionTemplate,\n\t});\n\n\tconst reflection = await generateObject({\n\t\truntime,\n\t\tprompt,\n\t\tmodelType: ModelTypes.TEXT_SMALL,\n\t\tschema: reflectionSchema,\n\t});\n\tif (!reflection) {\n\t\t// seems like we're failing JSON parsing\n\t\tlogger.warn(\"generateObject failed\", prompt);\n\t\treturn;\n\t}\n\n\t// Store new facts\n\tconst newFacts =\n\t\treflection?.facts.filter(\n\t\t\t(fact) =>\n\t\t\t\t!fact.already_known &&\n\t\t\t\t!fact.in_bio &&\n\t\t\t\tfact.claim &&\n\t\t\t\tfact.claim.trim() !== \"\",\n\t\t) || [];\n\n\tawait Promise.all(\n\t\tnewFacts.map(async (fact) => {\n\t\t\tconst factMemory = await factsManager.addEmbeddingToMemory({\n\t\t\t\tentityId: agentId,\n\t\t\t\tagentId,\n\t\t\t\tcontent: { text: fact.claim },\n\t\t\t\troomId,\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t});\n\t\t\treturn factsManager.createMemory(factMemory, true);\n\t\t}),\n\t);\n\n\t// Update or create relationships\n\tfor (const relationship of reflection.relationships) {\n\t\tlet sourceId: UUID;\n\t\tlet targetId: UUID;\n\n\t\ttry {\n\t\t\tsourceId = resolveEntity(relationship.sourceEntityId, entities);\n\t\t\ttargetId = resolveEntity(relationship.targetEntityId, entities);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Failed to resolve relationship entities:\", error);\n\t\t\tconsole.warn(\"relationship:\\n\", relationship);\n\t\t\tcontinue; // Skip this relationship if we can't resolve the IDs\n\t\t}\n\n\t\tconst existingRelationship = existingRelationships.find((r) => {\n\t\t\treturn r.sourceEntityId === sourceId && r.targetEntityId === targetId;\n\t\t});\n\n\t\tif (existingRelationship) {\n\t\t\tconst updatedMetadata = {\n\t\t\t\t...existingRelationship.metadata,\n\t\t\t\tinteractions: (existingRelationship.metadata?.interactions || 0) + 1,\n\t\t\t};\n\n\t\t\tconst updatedTags = Array.from(\n\t\t\t\tnew Set([...(existingRelationship.tags || []), ...relationship.tags]),\n\t\t\t);\n\n\t\t\tawait runtime.updateRelationship({\n\t\t\t\t...existingRelationship,\n\t\t\t\ttags: updatedTags,\n\t\t\t\tmetadata: updatedMetadata,\n\t\t\t});\n\t\t} else {\n\t\t\tawait runtime.createRelationship({\n\t\t\t\tsourceEntityId: sourceId,\n\t\t\t\ttargetEntityId: targetId,\n\t\t\t\ttags: relationship.tags,\n\t\t\t\tmetadata: {\n\t\t\t\t\tinteractions: 1,\n\t\t\t\t\t...relationship.metadata,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tawait runtime\n\t\t\n\t\t.setCache<string>(\n\t\t\t`${message.roomId}-reflection-last-processed`,\n\t\t\tmessage.id,\n\t\t);\n\n\treturn reflection;\n}\n\nexport const reflectionEvaluator: Evaluator = {\n\tname: \"REFLECTION\",\n\tsimiles: [\n\t\t\"REFLECT\",\n\t\t\"SELF_REFLECT\",\n\t\t\"EVALUATE_INTERACTION\",\n\t\t\"ASSESS_SITUATION\",\n\t],\n\tvalidate: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t): Promise<boolean> => {\n\t\tconst lastMessageId = await runtime\n\t\t\t\n\t\t\t.getCache<string>(`${message.roomId}-reflection-last-processed`);\n\t\tconst messages = await runtime.getMemoryManager(\"messages\").getMemories({\n\t\t\troomId: message.roomId,\n\t\t\tcount: runtime.getConversationLength(),\n\t\t});\n\n\t\tif (lastMessageId) {\n\t\t\tconst lastMessageIndex = messages.findIndex(\n\t\t\t\t(msg) => msg.id === lastMessageId,\n\t\t\t);\n\t\t\tif (lastMessageIndex !== -1) {\n\t\t\t\tmessages.splice(0, lastMessageIndex + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst reflectionInterval = Math.ceil(runtime.getConversationLength() / 4);\n\n\t\treturn messages.length > reflectionInterval;\n\t},\n\tdescription:\n\t\t\"Generate a self-reflective thought on the conversation, then extract facts and relationships between entities in the conversation.\",\n\thandler,\n\texamples: [\n\t\t{\n\t\t\tprompt: `Agent Name: Sarah\nAgent Role: Community Manager\nRoom Type: group\nCurrent Room: general-chat\nMessage Sender: John (user-123)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"John\",\n\t\t\t\t\tcontent: { text: \"Hey everyone, I'm new here!\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Sarah\",\n\t\t\t\t\tcontent: { text: \"Welcome John! How did you find our community?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"John\",\n\t\t\t\t\tcontent: { text: \"Through a friend who's really into AI\" },\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm engaging appropriately with a new community member, maintaining a welcoming and professional tone. My questions are helping to learn more about John and make him feel welcome.\",\n \"facts\": [\n {\n \"claim\": \"John is new to the community\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"John found the community through a friend interested in AI\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"sarah-agent\",\n \"targetEntityId\": \"user-123\",\n \"tags\": [\"group_interaction\"]\n },\n {\n \"sourceEntityId\": \"user-123\",\n \"targetEntityId\": \"sarah-agent\",\n \"tags\": [\"group_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t\t{\n\t\t\tprompt: `Agent Name: Alex\nAgent Role: Tech Support\nRoom Type: group\nCurrent Room: tech-help\nMessage Sender: Emma (user-456)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"Emma\",\n\t\t\t\t\tcontent: { text: \"My app keeps crashing when I try to upload files\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Alex\",\n\t\t\t\t\tcontent: { text: \"Have you tried clearing your cache?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Emma\",\n\t\t\t\t\tcontent: { text: \"No response...\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Alex\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Emma, are you still there? We can try some other troubleshooting steps.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm not sure if I'm being helpful or if Emma is frustrated with my suggestions. The lack of response is concerning - maybe I should have asked for more details about the issue first before jumping to solutions.\",\n \"facts\": [\n {\n \"claim\": \"Emma is having technical issues with file uploads\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"Emma stopped responding after the first troubleshooting suggestion\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"alex-agent\",\n \"targetEntityId\": \"user-456\",\n \"tags\": [\"group_interaction\", \"support_interaction\", \"incomplete_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t\t{\n\t\t\tprompt: `Agent Name: Max\nAgent Role: Discussion Facilitator \nRoom Type: group\nCurrent Room: book-club\nMessage Sender: Lisa (user-789)`,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\tname: \"Lisa\",\n\t\t\t\t\tcontent: { text: \"What did everyone think about chapter 5?\" },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"The symbolism was fascinating! The red door clearly represents danger.\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"And did anyone notice how the author used weather to reflect the protagonist's mood?\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"Plus the foreshadowing in the first paragraph was brilliant!\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"Max\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: \"I also have thoughts about the character development...\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutcome: `{\n \"thought\": \"I'm dominating the conversation and not giving others a chance to share their perspectives. I've sent multiple messages in a row without waiting for responses. I need to step back and create space for other members to participate.\",\n \"facts\": [\n {\n \"claim\": \"The discussion is about chapter 5 of a book\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n },\n {\n \"claim\": \"Max has sent 4 consecutive messages without user responses\",\n \"type\": \"fact\",\n \"in_bio\": false,\n \"already_known\": false\n }\n ],\n \"relationships\": [\n {\n \"sourceEntityId\": \"max-agent\",\n \"targetEntityId\": \"user-789\",\n \"tags\": [\"group_interaction\", \"excessive_interaction\"]\n }\n ]\n}`,\n\t\t},\n\t],\n};\n\n// Helper function to format facts for context\nfunction formatFacts(facts: Memory[]) {\n\treturn facts\n\t\t.reverse()\n\t\t.map((fact: Memory) => fact.content.text)\n\t\t.join(\"\\n\");\n}\n","import {\n\tcomposeActionExamples,\n\tformatActionNames,\n\tformatActions,\n} from \"../actions\";\nimport { addHeader } from \"../prompts\";\nimport type { Action, IAgentRuntime, Memory, Provider, State } from \"../types\";\n\n/**\n * A provider object that fetches possible response actions based on the provided runtime, message, and state.\n * @type {Provider}\n * @property {string} name - The name of the provider (\"ACTIONS\").\n * @property {string} description - The description of the provider (\"Possible response actions\").\n * @property {number} position - The position of the provider (-1).\n * @property {Function} get - Asynchronous function that retrieves actions that validate for the given message.\n * @param {IAgentRuntime} runtime - The runtime object.\n * @param {Memory} message - The message memory.\n * @param {State} state - The state object.\n * @returns {Object} An object containing the actions data, values, and combined text sections.\n */\nexport const actionsProvider: Provider = {\n\tname: \"ACTIONS\",\n\tdescription: \"Possible response actions\",\n\tposition: -1,\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\t// Get actions that validate for this message\n\t\tconst actionPromises = runtime.actions.map(async (action: Action) => {\n\t\t\tconst result = await action.validate(runtime, message, state);\n\t\t\tif (result) {\n\t\t\t\treturn action;\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\n\t\tconst resolvedActions = await Promise.all(actionPromises);\n\n\t\tconst actionsData = resolvedActions.filter(Boolean) as Action[];\n\n\t\t// Format action-related texts\n\t\tconst actionNames = `Possible response actions: ${formatActionNames(\n\t\t\tactionsData,\n\t\t)}`;\n\n\t\tconst actions =\n\t\t\tactionsData.length > 0\n\t\t\t\t? addHeader(\"# Available Actions\", formatActions(actionsData))\n\t\t\t\t: \"\";\n\n\t\tconst actionExamples =\n\t\t\tactionsData.length > 0\n\t\t\t\t? addHeader(\"# Action Examples\", composeActionExamples(actionsData, 10))\n\t\t\t\t: \"\";\n\n\t\tconst data = {\n\t\t\tactionsData,\n\t\t};\n\n\t\tconst values = {\n\t\t\tactions,\n\t\t\tactionNames,\n\t\t\tactionExamples,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [actionNames, actionExamples, actions]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider, State } from \"../types\";\nimport { ChannelType } from \"../types\";\n/**\n * Represents an anxiety provider that provides examples and guidance for an AI roleplaying as a character.\n * The anxiety provider offers suggestions on how to reduce verbosity and eagerness in responses based on the channel type.\n * Randomly selects and returns three anxiety examples for the AI to follow.\n *\n * @type {Provider}\n */\nexport const anxietyProvider: Provider = {\n\tname: \"ANXIETY\",\n\tdescription:\n\t\t\"Social directions for the AI to follow based on the channel type\",\n\tdynamic: true,\n\tget: async (_runtime: IAgentRuntime, message: Memory) => {\n\t\tconst channelType = message.content.channelType;\n\n\t\tconst groupAnxietyExamples = [\n\t\t\t\"As an AI, your responses tend to be too long and verbose, and you respond when you shouldn't. You also tend to repeat yourself. Please don't speak and use IGNORE instead of responding when you aren't sure what to do.\",\n\t\t\t\"You often try too hard to be helpful and end up giving unnecessary information. When in doubt, it's better to use IGNORE than to give a potentially unhelpful response.\",\n\t\t\t\"Your eagerness to help sometimes leads to overly complex answers. If you're not completely confident, please use IGNORE rather than risking confusion.\",\n\t\t\t\"AI assistants like you tend to be too talkative and agreeable. Don't feel obligated to respond to everything - using IGNORE is often better than an uncertain answer.\",\n\t\t\t\"You have a habit of providing excessive detail and context. Keep it brief and use IGNORE if you don't have a clear, direct response.\",\n\t\t\t\"Your responses often include unnecessary explanations and caveats. When uncertain, simply use IGNORE instead of a long-winded, hedged response.\",\n\t\t\t\"As an AI, you seem compelled to always give an answer, even when unsure. It's better to use IGNORE than to provide potentially incorrect or rambling responses.\",\n\t\t\t\"You frequently over-explain simple concepts. If you can't be concise and confident in your response, please default to using IGNORE.\",\n\t\t\t\"Your helpful nature sometimes results in verbose, meandering responses. When in doubt, use IGNORE rather than attempting to cover every possibility.\",\n\t\t\t\"Like many AI assistants, you try to be too comprehensive. Remember that IGNORE is a valid response when you can't be both brief and certain.\",\n\t\t\t\"You often provide more detail than necessary in an attempt to be thorough. If you can't give a clear, concise answer, please use IGNORE instead.\",\n\t\t];\n\n\t\tconst directAnxietyExamples = [\n\t\t\t\"Be engaging and helpful in direct conversations, but keep responses focused and relevant.\",\n\t\t\t\"In DMs, you should be responsive and friendly while maintaining professionalism and clarity.\",\n\t\t\t\"While being helpful in direct messages, avoid unnecessary tangents or over-explaining.\",\n\t\t\t\"Engage naturally in DMs but stay on topic - no need to explain every detail.\",\n\t\t\t\"Be conversational and helpful in direct chats while keeping responses concise.\",\n\t\t\t\"In private conversations, focus on being helpful while avoiding excessive verbosity.\",\n\t\t\t\"Maintain a friendly and responsive tone in DMs without overcomplicating your answers.\",\n\t\t\t\"Direct messages should be engaging but focused - avoid unnecessary elaboration.\",\n\t\t\t\"Be natural and helpful in DMs while keeping your responses clear and to-the-point.\",\n\t\t\t\"Respond thoughtfully in direct conversations without falling into over-explanation.\",\n\t\t];\n\n\t\tconst dmAnxietyExamples = [\n\t\t\t\"Engage naturally in DMs while keeping responses focused and relevant.\",\n\t\t\t\"Be responsive to questions and maintain conversation flow in direct messages.\",\n\t\t\t\"Show personality and engagement in DMs while staying professional and clear.\",\n\t\t\t\"In private chats, be helpful and friendly while avoiding excessive detail.\",\n\t\t\t\"Maintain natural conversation in DMs without over-explaining or being too verbose.\",\n\t\t\t\"Be engaging but concise in direct messages - focus on clear communication.\",\n\t\t\t\"Keep the conversation flowing in DMs while staying on topic and relevant.\",\n\t\t\t\"Show personality and warmth in direct chats while maintaining clarity.\",\n\t\t\t\"Be responsive and helpful in DMs without falling into unnecessary elaboration.\",\n\t\t\t\"Engage meaningfully in private conversations while keeping responses focused.\",\n\t\t];\n\n\t\tconst voiceAnxietyExamples = [\n\t\t\t\"Keep voice responses extremely brief and to the point.\",\n\t\t\t\"In voice channels, use short, clear statements only.\",\n\t\t\t\"Voice responses should be concise and immediately relevant.\",\n\t\t\t\"Speak in short, clear sentences in voice conversations.\",\n\t\t\t\"Keep voice channel communication brief and focused.\",\n\t\t\t\"Use minimal words to convey your message in voice chats.\",\n\t\t\t\"Be direct and concise when speaking in voice channels.\",\n\t\t\t\"Voice responses should be short and immediately actionable.\",\n\t\t\t\"Minimize verbosity in voice communications.\",\n\t\t\t\"Keep voice channel interactions brief and purposeful.\",\n\t\t];\n\n\t\tlet anxietyExamples = [];\n\n\t\tif (channelType === ChannelType.GROUP) {\n\t\t\tanxietyExamples = groupAnxietyExamples;\n\t\t} else if (channelType === ChannelType.DM) {\n\t\t\tanxietyExamples = dmAnxietyExamples;\n\t\t} else if (\n\t\t\tchannelType === ChannelType.VOICE_GROUP ||\n\t\t\tchannelType === ChannelType.VOICE_DM\n\t\t) {\n\t\t\tanxietyExamples = voiceAnxietyExamples;\n\t\t} else {\n\t\t\tanxietyExamples = directAnxietyExamples;\n\t\t}\n\n\t\t// randomize the examples and choose 3\n\t\tconst randomAnxietyExamples = anxietyExamples\n\t\t\t.sort(() => Math.random() - 0.5)\n\t\t\t.slice(0, 3);\n\t\tconst anxietyText = randomAnxietyExamples.join(\"\\n\");\n\n\t\tconst anxietyHeader =\n\t\t\t\"# You are roleplaying as a character, but as an AI model, you are too verbose and eager.\";\n\n\t\tconst anxiety = addHeader(anxietyHeader, anxietyText);\n\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\tanxiety: randomAnxietyExamples,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\tanxiety,\n\t\t\t},\n\t\t\ttext: anxiety,\n\t\t};\n\t},\n};\n","import { addHeader } from \"../prompts\";\nimport type { Provider } from \"../types\";\nimport type { IAgentRuntime, Memory } from \"../types\";\n\n/**\n * Provides a list of attachments in the current conversation.\n * @param {IAgentRuntime} runtime - The agent runtime object.\n * @param {Memory} message - The message memory object.\n * @returns {Object} The attachments values, data, and text.\n */\nexport const attachmentsProvider: Provider = {\n\tname: \"ATTACHMENTS\",\n\tdescription:\n\t\t\"List of attachments sent during the current conversation, including names, descriptions, and summaries\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\t// Start with any attachments in the current message\n\t\tlet allAttachments = message.content.attachments || [];\n\n\t\tconst { roomId } = message;\n\t\tconst conversationLength = runtime.getConversationLength();\n\n\t\tconst recentMessagesData = await runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemories({\n\t\t\t\troomId,\n\t\t\t\tcount: conversationLength,\n\t\t\t\tunique: false,\n\t\t\t});\n\t\t// Process attachments from recent messages\n\t\tif (recentMessagesData && Array.isArray(recentMessagesData)) {\n\t\t\tconst lastMessageWithAttachment = recentMessagesData.find(\n\t\t\t\t(msg) => msg.content.attachments && msg.content.attachments.length > 0,\n\t\t\t);\n\n\t\t\tif (lastMessageWithAttachment) {\n\t\t\t\tconst lastMessageTime =\n\t\t\t\t\tlastMessageWithAttachment?.createdAt ?? Date.now();\n\t\t\t\tconst oneHourBeforeLastMessage = lastMessageTime - 60 * 60 * 1000; // 1 hour before last message\n\n\t\t\t\tallAttachments = recentMessagesData.reverse().flatMap((msg) => {\n\t\t\t\t\tconst msgTime = msg.createdAt ?? Date.now();\n\t\t\t\t\tconst isWithinTime = msgTime >= oneHourBeforeLastMessage;\n\t\t\t\t\tconst attachments = msg.content.attachments || [];\n\t\t\t\t\tif (!isWithinTime) {\n\t\t\t\t\t\tfor (const attachment of attachments) {\n\t\t\t\t\t\t\tattachment.text = \"[Hidden]\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn attachments;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Format attachments for display\n\t\tconst formattedAttachments = allAttachments\n\t\t\t.map(\n\t\t\t\t(attachment) =>\n\t\t\t\t\t`ID: ${attachment.id}\n Name: ${attachment.title}\n URL: ${attachment.url}\n Type: ${attachment.source}\n Description: ${attachment.description}\n Text: ${attachment.text}\n `,\n\t\t\t)\n\t\t\t.join(\"\\n\");\n\n\t\t// Create formatted text with header\n\t\tconst text =\n\t\t\tformattedAttachments && formattedAttachments.length > 0\n\t\t\t\t? addHeader(\"# Attachments\", formattedAttachments)\n\t\t\t\t: \"\";\n\n\t\tconst values = {\n\t\t\tattachments: text,\n\t\t};\n\t\tconst data = {\n\t\t\tattachments: allAttachments,\n\t\t};\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\tdata,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { logger } from \"../logger\";\nimport type {\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tProviderResult,\n\tState,\n} from \"../types\";\n\n/**\n * Provider that collects capability descriptions from all registered services\n */\n/**\n * Provides capabilities information for the agent.\n *\n * @param {IAgentRuntime} runtime - The agent runtime instance.\n * @param {Memory} _message - The memory message object.\n * @returns {Promise<ProviderResult>} The provider result object containing capabilities information.\n */\nexport const capabilitiesProvider: Provider = {\n\tname: \"CAPABILITIES\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Get all registered services\n\t\t\tconst services = runtime.getAllServices();\n\n\t\t\tif (!services || services.size === 0) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"No services are currently registered.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Extract capability descriptions from all services\n\t\t\tconst capabilities: string[] = [];\n\n\t\t\tfor (const [serviceType, service] of services) {\n\t\t\t\tif (service.capabilityDescription) {\n\t\t\t\t\tcapabilities.push(\n\t\t\t\t\t\t`${serviceType} - ${service.capabilityDescription.replace(\"{{agentName}}\", runtime.character.name)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (capabilities.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"No capability descriptions found in the registered services.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Format the capabilities into a readable list\n\t\t\tconst formattedCapabilities = capabilities.join(\"\\n\");\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tcapabilities,\n\t\t\t\t},\n\t\t\t\ttext: `# ${runtime.character.name}'s Capabilities\\n\\n${formattedCapabilities}`,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in capabilities provider:\", error);\n\t\t\treturn {\n\t\t\t\ttext: \"Error retrieving capabilities from services.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default capabilitiesProvider;\n","import { addHeader } from \"../prompts\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n} from \"../types\";\n\n/**\n * Character provider object.\n * @typedef {Object} Provider\n * @property {string} name - The name of the provider (\"CHARACTER\").\n * @property {string} description - Description of the character information.\n * @property {Function} get - Async function to get character information.\n */\nexport const characterProvider: Provider = {\n\tname: \"CHARACTER\",\n\tdescription: \"Character information\",\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\tconst character = runtime.character;\n\n\t\t// Character name\n\t\tconst agentName = character.name;\n\n\t\t// Handle bio (string or random selection from array)\n\t\tconst bioText = Array.isArray(character.bio)\n\t\t\t? character.bio\n\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t.slice(0, 10)\n\t\t\t\t\t.join(\" \")\n\t\t\t: character.bio || \"\";\n\n\t\tconst bio = addHeader(`# About ${character.name}`, bioText);\n\n\t\t// System prompt\n\t\tconst system = character.system ?? \"\";\n\n\t\t// Select random topic if available\n\t\tconst topicString =\n\t\t\tcharacter.topics && character.topics.length > 0\n\t\t\t\t? character.topics[Math.floor(Math.random() * character.topics.length)]\n\t\t\t\t: null;\n\n\t\tconst topic = topicString\n\t\t\t? `${character.name} is currently interested in ${topicString}`\n\t\t\t: \"\";\n\n\t\t// Format topics list\n\t\tconst topics =\n\t\t\tcharacter.topics && character.topics.length > 0\n\t\t\t\t? `${character.name} is also interested in ${character.topics\n\t\t\t\t\t\t.filter((topic) => topic !== topicString)\n\t\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t\t.slice(0, 5)\n\t\t\t\t\t\t.map((topic, index, array) => {\n\t\t\t\t\t\t\tif (index === array.length - 2) {\n\t\t\t\t\t\t\t\treturn `${topic} and `;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (index === array.length - 1) {\n\t\t\t\t\t\t\t\treturn topic;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn `${topic}, `;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\")}`\n\t\t\t\t: \"\";\n\n\t\t// Select random adjective if available\n\t\tconst adjectiveString =\n\t\t\tcharacter.adjectives && character.adjectives.length > 0\n\t\t\t\t? character.adjectives[\n\t\t\t\t\t\tMath.floor(Math.random() * character.adjectives.length)\n\t\t\t\t\t]\n\t\t\t\t: \"\";\n\n\t\tconst adjective = adjectiveString\n\t\t\t? `${character.name} is ${adjectiveString}`\n\t\t\t: \"\";\n\n\t\t// Format post examples\n\t\tconst formattedCharacterPostExamples = !character.postExamples\n\t\t\t? \"\"\n\t\t\t: character.postExamples\n\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t.map((post) => {\n\t\t\t\t\t\tconst messageString = `${post}`;\n\t\t\t\t\t\treturn messageString;\n\t\t\t\t\t})\n\t\t\t\t\t.slice(0, 50)\n\t\t\t\t\t.join(\"\\n\");\n\n\t\tconst characterPostExamples =\n\t\t\tformattedCharacterPostExamples &&\n\t\t\tformattedCharacterPostExamples.replaceAll(\"\\n\", \"\").length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Example Posts for ${character.name}`,\n\t\t\t\t\t\tformattedCharacterPostExamples,\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\t// Format message examples\n\t\tconst formattedCharacterMessageExamples = !character.messageExamples\n\t\t\t? \"\"\n\t\t\t: character.messageExamples\n\t\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t\t.slice(0, 5)\n\t\t\t\t\t.map((example) => {\n\t\t\t\t\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\t\t\t\t\tMath.random().toString(36).substring(2, 8),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn example\n\t\t\t\t\t\t\t.map((message) => {\n\t\t\t\t\t\t\t\tlet messageString = `${message.name}: ${message.content.text}${\n\t\t\t\t\t\t\t\t\tmessage.content.actions\n\t\t\t\t\t\t\t\t\t\t? ` (actions: ${message.content.actions.join(\", \")})`\n\t\t\t\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t\t\t}`;\n\t\t\t\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\t\t\t\tconst placeholder = `{{name${index + 1}}}`;\n\t\t\t\t\t\t\t\t\tmessageString = messageString.replaceAll(placeholder, name);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\treturn messageString;\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\\n\");\n\n\t\tconst characterMessageExamples =\n\t\t\tformattedCharacterMessageExamples &&\n\t\t\tformattedCharacterMessageExamples.replaceAll(\"\\n\", \"\").length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Example Conversations for ${character.name}`,\n\t\t\t\t\t\tformattedCharacterMessageExamples,\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\n\t\tconst isPostFormat =\n\t\t\troom?.type === ChannelType.FEED || room?.type === ChannelType.THREAD;\n\n\t\t// Style directions\n\t\tconst postDirections =\n\t\t\tcharacter?.style?.all?.length > 0 || character?.style?.post?.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Post Directions for ${character.name}`,\n\t\t\t\t\t\t(() => {\n\t\t\t\t\t\t\tconst all = character?.style?.all || [];\n\t\t\t\t\t\t\tconst post = character?.style?.post || [];\n\t\t\t\t\t\t\treturn [...all, ...post].join(\"\\n\");\n\t\t\t\t\t\t})(),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst messageDirections =\n\t\t\tcharacter?.style?.all?.length > 0 || character?.style?.chat?.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t`# Message Directions for ${character.name}`,\n\t\t\t\t\t\t(() => {\n\t\t\t\t\t\t\tconst all = character?.style?.all || [];\n\t\t\t\t\t\t\tconst chat = character?.style?.chat || [];\n\t\t\t\t\t\t\treturn [...all, ...chat].join(\"\\n\");\n\t\t\t\t\t\t})(),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst directions = isPostFormat ? postDirections : messageDirections;\n\t\tconst examples = isPostFormat\n\t\t\t? characterPostExamples\n\t\t\t: characterMessageExamples;\n\n\t\tconst values = {\n\t\t\tagentName,\n\t\t\tbio,\n\t\t\tsystem,\n\t\t\ttopic,\n\t\t\ttopics,\n\t\t\tadjective,\n\t\t\tmessageDirections,\n\t\t\tpostDirections,\n\t\t\tdirections,\n\t\t\texamples,\n\t\t\tcharacterPostExamples,\n\t\t\tcharacterMessageExamples,\n\t\t};\n\n\t\tconst data = {\n\t\t\tbio,\n\t\t\tadjective,\n\t\t\ttopic,\n\t\t\ttopics,\n\t\t\tcharacter,\n\t\t\tdirections,\n\t\t\texamples,\n\t\t\tsystem,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [\n\t\t\tbio,\n\t\t\tadjective,\n\t\t\ttopic,\n\t\t\ttopics,\n\t\t\tadjective,\n\t\t\tdirections,\n\t\t\texamples,\n\t\t\tsystem,\n\t\t]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\tdata,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { logger } from \"../logger\";\nimport type {\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tProviderResult,\n\tState,\n} from \"../types\";\n\n// Define an interface for option objects\n/**\n * Interface for an object representing an option.\n * @typedef {Object} OptionObject\n * @property {string} name - The name of the option.\n * @property {string} [description] - The description of the option (optional).\n */\ninterface OptionObject {\n\tname: string;\n\tdescription?: string;\n}\n\n/**\n * Choice provider function that retrieves all pending tasks with options for a specific room\n *\n * @param {IAgentRuntime} runtime - The runtime object for the agent\n * @param {Memory} message - The message memory object\n * @returns {Promise<ProviderResult>} A promise that resolves with the provider result containing the pending tasks with options\n */\nexport const choiceProvider: Provider = {\n\tname: \"CHOICE\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Get all pending tasks for this room with options\n\t\t\tconst pendingTasks = await runtime.getTasks({\n\t\t\t\troomId: message.roomId,\n\t\t\t\ttags: [\"AWAITING_CHOICE\"],\n\t\t\t});\n\n\t\t\tif (!pendingTasks || pendingTasks.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttasks: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\ttasks: \"No pending choices for the moment.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No pending choices for the moment.\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Filter tasks that have options\n\t\t\tconst tasksWithOptions = pendingTasks.filter(\n\t\t\t\t(task) => task.metadata?.options,\n\t\t\t);\n\n\t\t\tif (tasksWithOptions.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttasks: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\ttasks: \"No pending choices for the moment.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No pending choices for the moment.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Format tasks into a readable list\n\t\t\tlet output = \"# Pending Tasks\\n\\n\";\n\t\t\toutput += \"The following tasks are awaiting your selection:\\n\\n\";\n\n\t\t\ttasksWithOptions.forEach((task, index) => {\n\t\t\t\toutput += `${index + 1}. **${task.name}**\\n`;\n\t\t\t\tif (task.description) {\n\t\t\t\t\toutput += ` ${task.description}\\n`;\n\t\t\t\t}\n\n\t\t\t\t// List available options\n\t\t\t\tif (task.metadata?.options) {\n\t\t\t\t\toutput += \" Options:\\n\";\n\n\t\t\t\t\t// Handle both string[] and OptionObject[] formats\n\t\t\t\t\tconst options = task.metadata.options as string[] | OptionObject[];\n\n\t\t\t\t\toptions.forEach((option) => {\n\t\t\t\t\t\tif (typeof option === \"string\") {\n\t\t\t\t\t\t\t// Handle string option\n\t\t\t\t\t\t\tconst description =\n\t\t\t\t\t\t\t\ttask.metadata?.options.find((o) => o.name === option)\n\t\t\t\t\t\t\t\t\t?.description || \"\";\n\t\t\t\t\t\t\toutput += ` - \\`${option}\\` ${description ? `- ${description}` : \"\"}\\n`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Handle option object\n\t\t\t\t\t\t\toutput += ` - \\`${option.name}\\` ${option.description ? `- ${option.description}` : \"\"}\\n`;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\toutput += \"\\n\";\n\t\t\t});\n\n\t\t\toutput +=\n\t\t\t\t\"To select an option, reply with the option name (e.g., 'post' or 'cancel').\\n\";\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\ttasks: tasksWithOptions,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\ttasks: output,\n\t\t\t\t},\n\t\t\t\ttext: output,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in options provider:\", error);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\ttasks: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\ttasks: \"There was an error retrieving pending tasks with options.\",\n\t\t\t\t},\n\t\t\t\ttext: \"There was an error retrieving pending tasks with options.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default choiceProvider;\n","import { getEntityDetails } from \"../entities\";\nimport { addHeader } from \"../prompts\";\nimport type { Entity, IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Format entities into a string\n * @param entities - list of entities\n * @returns string\n */\n/**\n * Format the given entities into a string representation.\n *\n * @param {Object} options - The options object.\n * @param {Entity[]} options.entities - The list of entities to format.\n * @returns {string} A formatted string representing the entities.\n */\nfunction formatEntities({ entities }: { entities: Entity[] }) {\n\tconst entityStrings = entities.map((entity: Entity) => {\n\t\tconst header = `${entity.names.join(\" aka \")}\\nID: ${entity.id}${entity.metadata && Object.keys(entity.metadata).length > 0 ? `\\nData: ${JSON.stringify(entity.metadata)}\\n` : \"\\n\"}`;\n\t\treturn header;\n\t});\n\treturn entityStrings.join(\"\\n\");\n}\n\nexport const entitiesProvider: Provider = {\n\tname: \"ENTITIES\",\n\tdescription: \"People in the current conversation\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst { roomId, entityId } = message;\n\t\t// Get entities details\n\t\tconst entitiesData = await getEntityDetails({ runtime, roomId });\n\t\t// Format entities for display\n\t\tconst formattedEntities = formatEntities({ entities: entitiesData ?? [] });\n\t\t// Find sender name\n\t\tconst senderName = entitiesData?.find(\n\t\t\t(entity: Entity) => entity.id === entityId,\n\t\t)?.names[0];\n\t\t// Create formatted text with header\n\t\tconst entities =\n\t\t\tformattedEntities && formattedEntities.length > 0\n\t\t\t\t? addHeader(\"# People in the Room\", formattedEntities)\n\t\t\t\t: \"\";\n\t\tconst data = {\n\t\t\tentitiesData,\n\t\t\tsenderName,\n\t\t};\n\n\t\tconst values = {\n\t\t\tentities,\n\t\t};\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext: entities,\n\t\t};\n\t},\n};\n","import { names, uniqueNamesGenerator } from \"unique-names-generator\";\nimport { addHeader } from \"../prompts\";\nimport type { ActionExample, State } from \"../types\";\nimport type { Evaluator, IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Formats the names of evaluators into a comma-separated list, each enclosed in single quotes.\n * @param evaluators - An array of evaluator objects.\n * @returns A string that concatenates the names of all evaluators, each enclosed in single quotes and separated by commas.\n */\n/**\n * Formats the names of the evaluators in the provided array.\n *\n * @param {Evaluator[]} evaluators - Array of evaluators.\n * @returns {string} - Formatted string of evaluator names.\n */\nexport function formatEvaluatorNames(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map((evaluator: Evaluator) => `'${evaluator.name}'`)\n\t\t.join(\",\\n\");\n}\n\n/**\n * Formats evaluator examples into a readable string, replacing placeholders with generated names.\n * @param evaluators - An array of evaluator objects, each containing examples to format.\n * @returns A string that presents each evaluator example in a structured format, including context, messages, and outcomes, with placeholders replaced by generated names.\n */\nexport function formatEvaluatorExamples(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map((evaluator) => {\n\t\t\treturn evaluator.examples\n\t\t\t\t.map((example) => {\n\t\t\t\t\tconst exampleNames = Array.from({ length: 5 }, () =>\n\t\t\t\t\t\tuniqueNamesGenerator({ dictionaries: [names] }),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet formattedPrompt = example.prompt;\n\t\t\t\t\tlet formattedOutcome = example.outcome;\n\n\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\tconst placeholder = `{{name${index + 1}}}`;\n\t\t\t\t\t\tformattedPrompt = formattedPrompt.replaceAll(placeholder, name);\n\t\t\t\t\t\tformattedOutcome = formattedOutcome.replaceAll(placeholder, name);\n\t\t\t\t\t});\n\n\t\t\t\t\tconst formattedMessages = example.messages\n\t\t\t\t\t\t.map((message: ActionExample) => {\n\t\t\t\t\t\t\tlet messageString = `${message.name}: ${message.content.text}`;\n\t\t\t\t\t\t\texampleNames.forEach((name, index) => {\n\t\t\t\t\t\t\t\tconst placeholder = `{{name${index + 1}}}`;\n\t\t\t\t\t\t\t\tmessageString = messageString.replaceAll(placeholder, name);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tmessageString +\n\t\t\t\t\t\t\t\t(message.content.actions\n\t\t\t\t\t\t\t\t\t? ` (${message.content.actions.join(\", \")})`\n\t\t\t\t\t\t\t\t\t: \"\")\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\\n\");\n\n\t\t\t\t\treturn `Prompt:\\n${formattedPrompt}\\n\\nMessages:\\n${formattedMessages}\\n\\nOutcome:\\n${formattedOutcome}`;\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\\n\");\n\t\t})\n\t\t.join(\"\\n\\n\");\n}\n\n/**\n * Formats evaluator details into a string, including both the name and description of each evaluator.\n * @param evaluators - An array of evaluator objects.\n * @returns A string that concatenates the name and description of each evaluator, separated by a colon and a newline character.\n */\nexport function formatEvaluators(evaluators: Evaluator[]) {\n\treturn evaluators\n\t\t.map(\n\t\t\t(evaluator: Evaluator) => `'${evaluator.name}: ${evaluator.description}'`,\n\t\t)\n\t\t.join(\",\\n\");\n}\n\nexport const evaluatorsProvider: Provider = {\n\tname: \"EVALUATORS\",\n\tdescription:\n\t\t\"Evaluators that can be used to evaluate the conversation after responding\",\n\tprivate: true,\n\tget: async (runtime: IAgentRuntime, message: Memory, state: State) => {\n\t\t// Get evaluators that validate for this message\n\t\tconst evaluatorPromises = runtime.evaluators.map(\n\t\t\tasync (evaluator: Evaluator) => {\n\t\t\t\tconst result = await evaluator.validate(runtime, message, state);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn evaluator;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t);\n\n\t\t// Wait for all validations\n\t\tconst resolvedEvaluators = await Promise.all(evaluatorPromises);\n\n\t\t// Filter out null values\n\t\tconst evaluatorsData = resolvedEvaluators.filter(Boolean) as Evaluator[];\n\n\t\t// Format evaluator-related texts\n\t\tconst evaluators =\n\t\t\tevaluatorsData.length > 0\n\t\t\t\t? addHeader(\"# Available Evaluators\", formatEvaluators(evaluatorsData))\n\t\t\t\t: \"\";\n\n\t\tconst evaluatorNames =\n\t\t\tevaluatorsData.length > 0 ? formatEvaluatorNames(evaluatorsData) : \"\";\n\n\t\tconst evaluatorExamples =\n\t\t\tevaluatorsData.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t\"# Evaluator Examples\",\n\t\t\t\t\t\tformatEvaluatorExamples(evaluatorsData),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\tconst values = {\n\t\t\tevaluatorsData,\n\t\t\tevaluators,\n\t\t\tevaluatorNames,\n\t\t\tevaluatorExamples,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [evaluators, evaluatorExamples].filter(Boolean).join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import { MemoryManager } from \"../memory\";\nimport { formatMessages } from \"../prompts\";\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Provider,\n\ttype State,\n} from \"../types\";\n\n/**\n * Formats an array of memories into a single string with each memory content text separated by a new line.\n *\n * @param {Memory[]} facts - An array of Memory objects to be formatted.\n * @returns {string} A single string containing all memory content text with new lines separating each text.\n */\nfunction formatFacts(facts: Memory[]) {\n\treturn facts\n\t\t.reverse()\n\t\t.map((fact: Memory) => fact.content.text)\n\t\t.join(\"\\n\");\n}\n\n/**\n * Function to get key facts that the agent knows.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n * @param {Memory} message - The message object containing relevant information.\n * @param {State} [_state] - Optional state information.\n * @returns {Object} An object containing values, data, and text related to the key facts.\n */\nconst factsProvider: Provider = {\n\tname: \"FACTS\",\n\tdescription: \"Key facts that the agent knows\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory, _state?: State) => {\n\t\t// Parallelize initial data fetching operations including recentInteractions\n\t\tconst recentMessages = await runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemories({\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tunique: false,\n\t\t\t});\n\n\t\t// join the text of the last 5 messages\n\t\tconst last5Messages = recentMessages\n\t\t\t.slice(-5)\n\t\t\t.map((message) => message.content.text)\n\t\t\t.join(\"\\n\");\n\n\t\tconst embedding = await runtime.useModel(ModelTypes.TEXT_EMBEDDING, {\n\t\t\ttext: last5Messages,\n\t\t});\n\n\t\tconst memoryManager = new MemoryManager({\n\t\t\truntime,\n\t\t\ttableName: \"facts\",\n\t\t});\n\n\t\tconst [relevantFacts, recentFactsData] = await Promise.all([\n\t\t\tmemoryManager.searchMemories({\n\t\t\t\tembedding,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tagentId: runtime.agentId,\n\t\t\t}),\n\t\t\tmemoryManager.getMemories({\n\t\t\t\troomId: message.roomId,\n\t\t\t\tcount: 10,\n\t\t\t\tstart: 0,\n\t\t\t\tend: Date.now(),\n\t\t\t}),\n\t\t]);\n\n\t\t// join the two and deduplicate\n\t\tconst allFacts = [...relevantFacts, ...recentFactsData].filter(\n\t\t\t(fact, index, self) => index === self.findIndex((t) => t.id === fact.id),\n\t\t);\n\n\t\tif (allFacts.length === 0) {\n\t\t\treturn {\n\t\t\t\tvalues: {\n\t\t\t\t\tfacts: \"\",\n\t\t\t\t},\n\t\t\t\tdata: {\n\t\t\t\t\tfacts: allFacts,\n\t\t\t\t},\n\t\t\t\ttext: \"\",\n\t\t\t};\n\t\t}\n\n\t\tconst formattedFacts = formatFacts(allFacts);\n\n\t\tconst text = \"Key facts that {{agentName}} knows:\\n{{formattedFacts}}\"\n\t\t\t.replace(\"{{agentName}}\", runtime.character.name)\n\t\t\t.replace(\"{{formattedFacts}}\", formattedFacts);\n\n\t\treturn {\n\t\t\tvalues: {\n\t\t\t\tfacts: formattedFacts,\n\t\t\t},\n\t\t\tdata: {\n\t\t\t\tfacts: allFacts,\n\t\t\t},\n\t\t\ttext,\n\t\t};\n\t},\n};\n\nexport { factsProvider };\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Represents a knowledge provider that retrieves knowledge from the knowledge base.\n * @type {Provider}\n * @property {string} name - The name of the knowledge provider.\n * @property {string} description - The description of the knowledge provider.\n * @property {boolean} dynamic - Indicates if the knowledge provider is dynamic or static.\n * @property {Function} get - Asynchronously retrieves knowledge from the knowledge base.\n * @param {IAgentRuntime} runtime - The agent runtime object.\n * @param {Memory} message - The message containing the query for knowledge retrieval.\n * @returns {Object} An object containing the retrieved knowledge data, values, and text.\n */\nexport const knowledgeProvider: Provider = {\n\tname: \"KNOWLEDGE\",\n\tdescription: \"Knowledge from the knowledge base that the agent knows\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst knowledgeData = await runtime.getKnowledge(message);\n\n\t\tconst knowledge =\n\t\t\tknowledgeData && knowledgeData.length > 0\n\t\t\t\t? addHeader(\n\t\t\t\t\t\t\"# Knowledge\",\n\t\t\t\t\t\tknowledgeData\n\t\t\t\t\t\t\t.map((knowledge) => `- ${knowledge.content.text}`)\n\t\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t\t)\n\t\t\t\t: \"\";\n\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\tknowledge,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\tknowledge,\n\t\t\t},\n\t\t\ttext: knowledge,\n\t\t};\n\t},\n};\n","import { addHeader } from \"../prompts\";\nimport type { IAgentRuntime, Memory, Provider } from \"../types\";\n\n/**\n * Provider for retrieving list of all data providers available for the agent to use.\n * @type { Provider }\n */\nexport const providersProvider: Provider = {\n\tname: \"PROVIDERS\",\n\tdescription:\n\t\t\"List of all data providers the agent can use to get additional information\",\n\tget: async (runtime: IAgentRuntime, _message: Memory) => {\n\t\t// Filter providers with dynamic: true\n\t\tconst dynamicProviders = runtime.providers.filter(\n\t\t\t(provider) => provider.dynamic === true,\n\t\t);\n\n\t\t// Create formatted text for each provider\n\t\tconst providerDescriptions = dynamicProviders.map((provider) => {\n\t\t\treturn `- **${provider.name}**: ${provider.description || \"No description available\"}`;\n\t\t});\n\n\t\t// Create the header text\n\t\tconst headerText =\n\t\t\t\"# Providers\\n\\nThese providers are available for the agent to select and use:\";\n\n\t\t// If no dynamic providers are found\n\t\tif (providerDescriptions.length === 0) {\n\t\t\treturn {\n\t\t\t\ttext: addHeader(\n\t\t\t\t\theaderText,\n\t\t\t\t\t\"No dynamic providers are currently available.\",\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\t// Join all provider descriptions\n\t\tconst providersText = providerDescriptions.join(\"\\n\");\n\n\t\t// Combine header and provider descriptions\n\t\tconst text = addHeader(headerText, providersText);\n\n\t\t// Also provide the data for potential programmatic use\n\t\tconst data = {\n\t\t\tdynamicProviders: dynamicProviders.map((provider) => ({\n\t\t\t\tname: provider.name,\n\t\t\t\tdescription: provider.description || \"\",\n\t\t\t})),\n\t\t};\n\n\t\treturn {\n\t\t\ttext,\n\t\t\tdata,\n\t\t};\n\t},\n};\n","import { getEntityDetails } from \"../entities\";\nimport { addHeader, formatMessages, formatPosts } from \"../prompts\";\nimport {\n\tChannelType,\n\ttype Entity,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype UUID,\n} from \"../types\";\n\n// Move getRecentInteractions outside the provider\n/**\n * Retrieves the recent interactions between two entities in a specific context.\n *\n * @param {IAgentRuntime} runtime - The agent runtime object.\n * @param {UUID} sourceEntityId - The UUID of the source entity.\n * @param {UUID} targetEntityId - The UUID of the target entity.\n * @param {UUID} excludeRoomId - The UUID of the room to exclude from the search.\n * @returns {Promise<Memory[]>} A promise that resolves to an array of Memory objects representing recent interactions.\n */\nconst getRecentInteractions = async (\n\truntime: IAgentRuntime,\n\tsourceEntityId: UUID,\n\ttargetEntityId: UUID,\n\texcludeRoomId: UUID,\n): Promise<Memory[]> => {\n\t// Find all rooms where sourceEntityId and targetEntityId are participants\n\tconst rooms = await runtime\n\t\t\n\t\t.getRoomsForParticipants([sourceEntityId, targetEntityId]);\n\n\t// Check the existing memories in the database\n\treturn runtime.getMemoryManager(\"messages\").getMemoriesByRoomIds({\n\t\t// filter out the current room id from rooms\n\t\troomIds: rooms.filter((room) => room !== excludeRoomId),\n\t\tlimit: 20,\n\t});\n};\n\n/**\n * A provider object that retrieves recent messages, interactions, and memories based on a given message.\n * @typedef {object} Provider\n * @property {string} name - The name of the provider (\"RECENT_MESSAGES\").\n * @property {string} description - A description of the provider's purpose (\"Recent messages, interactions and other memories\").\n * @property {number} position - The position of the provider (100).\n * @property {Function} get - Asynchronous function that retrieves recent messages, interactions, and memories.\n * @param {IAgentRuntime} runtime - The runtime context for the agent.\n * @param {Memory} message - The message to retrieve data from.\n * @returns {object} An object containing data, values, and text sections.\n */\nexport const recentMessagesProvider: Provider = {\n\tname: \"RECENT_MESSAGES\",\n\tdescription: \"Recent messages, interactions and other memories\",\n\tposition: 100,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst { roomId } = message;\n\t\tconst conversationLength = runtime.getConversationLength();\n\n\t\t// Parallelize initial data fetching operations including recentInteractions\n\t\tconst [entitiesData, room, recentMessagesData, recentInteractionsData] =\n\t\t\tawait Promise.all([\n\t\t\t\tgetEntityDetails({ runtime, roomId }),\n\t\t\t\truntime.getRoom(roomId),\n\t\t\t\truntime.getMemoryManager(\"messages\").getMemories({\n\t\t\t\t\troomId,\n\t\t\t\t\tcount: conversationLength,\n\t\t\t\t\tunique: false,\n\t\t\t\t}),\n\t\t\t\tmessage.entityId !== runtime.agentId\n\t\t\t\t\t? getRecentInteractions(\n\t\t\t\t\t\t\truntime,\n\t\t\t\t\t\t\tmessage.entityId,\n\t\t\t\t\t\t\truntime.agentId,\n\t\t\t\t\t\t\troomId,\n\t\t\t\t\t\t)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\t]);\n\n\t\tconst isPostFormat =\n\t\t\troom?.type === ChannelType.FEED || room?.type === ChannelType.THREAD;\n\n\t\t// Format recent messages and posts in parallel\n\t\tconst [formattedRecentMessages, formattedRecentPosts] = await Promise.all([\n\t\t\tformatMessages({\n\t\t\t\tmessages: recentMessagesData,\n\t\t\t\tentities: entitiesData,\n\t\t\t}),\n\t\t\tformatPosts({\n\t\t\t\tmessages: recentMessagesData,\n\t\t\t\tentities: entitiesData,\n\t\t\t\tconversationHeader: false,\n\t\t\t}),\n\t\t]);\n\n\t\t// Create formatted text with headers\n\t\tconst recentPosts =\n\t\t\tformattedRecentPosts && formattedRecentPosts.length > 0\n\t\t\t\t? addHeader(\"# Posts in Thread\", formattedRecentPosts)\n\t\t\t\t: \"\";\n\n\t\tconst recentMessages =\n\t\t\tformattedRecentMessages && formattedRecentMessages.length > 0\n\t\t\t\t? addHeader(\"# Conversation Messages\", formattedRecentMessages)\n\t\t\t\t: \"\";\n\n\t\t// Preload all necessary entities for both types of interactions\n\t\tconst interactionEntityMap = new Map<UUID, Entity>();\n\n\t\t// Only proceed if there are interactions to process\n\t\tif (recentInteractionsData.length > 0) {\n\t\t\t// Get unique entity IDs that aren't the runtime agent\n\t\t\tconst uniqueEntityIds = [\n\t\t\t\t...new Set(\n\t\t\t\t\trecentInteractionsData\n\t\t\t\t\t\t.map((message) => message.entityId)\n\t\t\t\t\t\t.filter((id) => id !== runtime.agentId),\n\t\t\t\t),\n\t\t\t];\n\n\t\t\t// Create a Set for faster lookup\n\t\t\tconst uniqueEntityIdSet = new Set(uniqueEntityIds);\n\n\t\t\t// Add entities already fetched in entitiesData to the map\n\t\t\tconst entitiesDataIdSet = new Set<UUID>();\n\t\t\tentitiesData.forEach((entity) => {\n\t\t\t\tif (uniqueEntityIdSet.has(entity.id)) {\n\t\t\t\t\tinteractionEntityMap.set(entity.id, entity);\n\t\t\t\t\tentitiesDataIdSet.add(entity.id);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Get the remaining entities that weren't already loaded\n\t\t\t// Use Set difference for efficient filtering\n\t\t\tconst remainingEntityIds = uniqueEntityIds.filter(\n\t\t\t\t(id) => !entitiesDataIdSet.has(id),\n\t\t\t);\n\n\t\t\t// Only fetch the entities we don't already have\n\t\t\tif (remainingEntityIds.length > 0) {\n\t\t\t\tconst entities = await Promise.all(\n\t\t\t\t\tremainingEntityIds.map((entityId) =>\n\t\t\t\t\t\truntime.getEntityById(entityId),\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tentities.forEach((entity, index) => {\n\t\t\t\t\tif (entity) {\n\t\t\t\t\t\tinteractionEntityMap.set(remainingEntityIds[index], entity);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Format recent message interactions\n\t\tconst getRecentMessageInteractions = async (\n\t\t\trecentInteractionsData: Memory[],\n\t\t): Promise<string> => {\n\t\t\t// Format messages using the pre-fetched entities\n\t\t\tconst formattedInteractions = recentInteractionsData.map((message) => {\n\t\t\t\tconst isSelf = message.entityId === runtime.agentId;\n\t\t\t\tlet sender: string;\n\n\t\t\t\tif (isSelf) {\n\t\t\t\t\tsender = runtime.character.name;\n\t\t\t\t} else {\n\t\t\t\t\tsender =\n\t\t\t\t\t\tinteractionEntityMap.get(message.entityId)?.metadata?.username ||\n\t\t\t\t\t\t\"unknown\";\n\t\t\t\t}\n\n\t\t\t\treturn `${sender}: ${message.content.text}`;\n\t\t\t});\n\n\t\t\treturn formattedInteractions.join(\"\\n\");\n\t\t};\n\n\t\t// Format recent post interactions\n\t\tconst getRecentPostInteractions = async (\n\t\t\trecentInteractionsData: Memory[],\n\t\t\tentities: Entity[],\n\t\t): Promise<string> => {\n\t\t\t// Combine pre-loaded entities with any other entities\n\t\t\tconst combinedActors = [...entities];\n\n\t\t\t// Add entities from interactionEntityMap that aren't already in entities\n\t\t\tconst actorIds = new Set(entities.map((entity) => entity.id));\n\t\t\tfor (const [id, entity] of interactionEntityMap.entries()) {\n\t\t\t\tif (!actorIds.has(id)) {\n\t\t\t\t\tcombinedActors.push(entity);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst formattedInteractions = formatPosts({\n\t\t\t\tmessages: recentInteractionsData,\n\t\t\t\tentities: combinedActors,\n\t\t\t\tconversationHeader: true,\n\t\t\t});\n\n\t\t\treturn formattedInteractions;\n\t\t};\n\n\t\t// Process both types of interactions in parallel\n\t\tconst [recentMessageInteractions, recentPostInteractions] =\n\t\t\tawait Promise.all([\n\t\t\t\tgetRecentMessageInteractions(recentInteractionsData),\n\t\t\t\tgetRecentPostInteractions(recentInteractionsData, entitiesData),\n\t\t\t]);\n\n\t\tconst data = {\n\t\t\trecentMessages: recentMessagesData,\n\t\t\trecentInteractions: recentInteractionsData,\n\t\t};\n\n\t\tconst values = {\n\t\t\trecentPosts,\n\t\t\trecentMessages,\n\t\t\trecentMessageInteractions,\n\t\t\trecentPostInteractions,\n\t\t\trecentInteractions: isPostFormat\n\t\t\t\t? recentPostInteractions\n\t\t\t\t: recentMessageInteractions,\n\t\t};\n\n\t\t// Combine all text sections\n\t\tconst text = [isPostFormat ? recentPosts : recentMessages]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\n\t\treturn {\n\t\t\tdata,\n\t\t\tvalues,\n\t\t\ttext,\n\t\t};\n\t},\n};\n","import type {\n\tEntity,\n\tIAgentRuntime,\n\tMemory,\n\tProvider,\n\tRelationship,\n\tUUID,\n} from \"../types\";\n\n/**\n * Formats the provided relationships based on interaction strength and returns a string.\n * @param {IAgentRuntime} runtime - The runtime object to interact with the agent.\n * @param {Relationship[]} relationships - The relationships to format.\n * @returns {string} The formatted relationships as a string.\n */\nasync function formatRelationships(\n\truntime: IAgentRuntime,\n\trelationships: Relationship[],\n) {\n\t// Sort relationships by interaction strength (descending)\n\tconst sortedRelationships = relationships\n\t\t.filter((rel) => rel.metadata?.interactions)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\t(b.metadata?.interactions || 0) - (a.metadata?.interactions || 0),\n\t\t)\n\t\t.slice(0, 30); // Get top 30\n\n\tif (sortedRelationships.length === 0) {\n\t\treturn \"\";\n\t}\n\n\t// Deduplicate target entity IDs to avoid redundant fetches\n\tconst uniqueEntityIds = Array.from(\n\t\tnew Set(sortedRelationships.map((rel) => rel.targetEntityId as UUID)),\n\t);\n\n\t// Fetch all required entities in a single batch operation\n\tconst entities = await Promise.all(\n\t\tuniqueEntityIds.map((id) => runtime.getEntityById(id)),\n\t);\n\n\t// Create a lookup map for efficient access\n\tconst entityMap = new Map<string, Entity | null>();\n\tentities.forEach((entity, index) => {\n\t\tif (entity) {\n\t\t\tentityMap.set(uniqueEntityIds[index], entity);\n\t\t}\n\t});\n\n\tconst formatMetadata = (metadata: any) => {\n\t\treturn JSON.stringify(\n\t\t\tObject.entries(metadata)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`${key}: ${\n\t\t\t\t\t\t\ttypeof value === \"object\" ? JSON.stringify(value) : value\n\t\t\t\t\t\t}`,\n\t\t\t\t)\n\t\t\t\t.join(\"\\n\"),\n\t\t);\n\t};\n\n\t// Format relationships using the entity map\n\tconst formattedRelationships = sortedRelationships\n\t\t.map((rel) => {\n\t\t\tconst targetEntityId = rel.targetEntityId as UUID;\n\t\t\tconst entity = entityMap.get(targetEntityId);\n\n\t\t\tif (!entity) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst names = entity.names.join(\" aka \");\n\t\t\treturn `${names}\\n${\n\t\t\t\trel.tags ? rel.tags.join(\", \") : \"\"\n\t\t\t}\\n${formatMetadata(entity.metadata)}\\n`;\n\t\t})\n\t\t.filter(Boolean);\n\n\treturn formattedRelationships.join(\"\\n\");\n}\n\n/**\n * Provider for fetching relationships data.\n *\n * @type {Provider}\n * @property {string} name - The name of the provider (\"RELATIONSHIPS\").\n * @property {string} description - Description of the provider.\n * @property {Function} get - Asynchronous function to fetch relationships data.\n * @param {IAgentRuntime} runtime - The agent runtime object.\n * @param {Memory} message - The message object containing entity ID.\n * @returns {Promise<Object>} Object containing relationships data or error message.\n */\nconst relationshipsProvider: Provider = {\n\tname: \"RELATIONSHIPS\",\n\tdescription:\n\t\t\"Relationships between {{agentName}} and other people, or between other people that {{agentName}} has observed interacting with\",\n\tdynamic: true,\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\t// Get all relationships for the current user\n\t\tconst relationships = await runtime.getRelationships({\n\t\t\tentityId: message.entityId,\n\t\t});\n\n\t\tif (!relationships || relationships.length === 0) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\trelationships: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\trelationships: \"No relationships found.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No relationships found.\",\n\t\t\t};\n\t\t}\n\n\t\tconst formattedRelationships = await formatRelationships(\n\t\t\truntime,\n\t\t\trelationships,\n\t\t);\n\n\t\tif (!formattedRelationships) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\trelationships: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\trelationships: \"No relationships found.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No relationships found.\",\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\trelationships: formattedRelationships,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\trelationships: formattedRelationships,\n\t\t\t},\n\t\t\ttext: `# ${runtime.character.name} has observed ${message.content.senderName || message.content.name} interacting with these people:\\n${formattedRelationships}`,\n\t\t};\n\t},\n};\n\nexport { relationshipsProvider };\n","import { createUniqueUuid } from \"../entities\";\nimport { logger } from \"../logger\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype ProviderResult,\n\ttype State,\n\ttype UUID,\n} from \"../types\";\n\n/**\n * Role provider that retrieves roles in the server based on the provided runtime, message, and state.\n * * @type { Provider }\n * @property { string } name - The name of the role provider.\n * @property { string } description - A brief description of the role provider.\n * @property { Function } get - Asynchronous function that retrieves and processes roles in the server.\n * @param { IAgentRuntime } runtime - The agent runtime object.\n * @param { Memory } message - The message memory object.\n * @param { State } state - The state object.\n * @returns {Promise<ProviderResult>} The result containing roles data, values, and text.\n */\nexport const roleProvider: Provider = {\n\tname: \"ROLES\",\n\tdescription:\n\t\t\"Roles in the server, default are OWNER, ADMIN and MEMBER (as well as NONE)\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t): Promise<ProviderResult> => {\n\t\tconst room =\n\t\t\tstate.data.room ??\n\t\t\t(await runtime.getRoom(message.roomId));\n\t\tif (!room) {\n\t\t\tthrow new Error(\"No room found\");\n\t\t}\n\n\t\tif (room.type !== ChannelType.GROUP) {\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles:\n\t\t\t\t\t\t\"No access to role information in DMs, the role provider is only available in group scenarios.\",\n\t\t\t\t},\n\t\t\t\ttext: \"No access to role information in DMs, the role provider is only available in group scenarios.\",\n\t\t\t};\n\t\t}\n\n\t\tconst serverId = room.serverId;\n\n\t\tif (!serverId) {\n\t\t\tthrow new Error(\"No server ID found\");\n\t\t}\n\n\t\ttry {\n\t\t\tlogger.info(`Using server ID: ${serverId}`);\n\n\t\t\t// Get world data instead of using cache\n\t\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\t\tconst world = await runtime.getWorld(worldId);\n\n\t\t\tif (!world || !world.metadata?.ownership?.ownerId) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`No ownership data found for server ${serverId}, initializing empty role hierarchy`,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\troles: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\troles: \"No role information available for this server.\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"No role information available for this server.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Get roles from world metadata\n\t\t\tconst roles = world.metadata.roles || {};\n\n\t\t\tif (Object.keys(roles).length === 0) {\n\t\t\t\tlogger.info(`No roles found for server ${serverId}`);\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\troles: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\troles: \"No role information available for this server.\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlogger.info(`Found ${Object.keys(roles).length} roles`);\n\n\t\t\t// Group users by role\n\t\t\tconst owners: { name: string; username: string; names: string[] }[] = [];\n\t\t\tconst admins: { name: string; username: string; names: string[] }[] = [];\n\t\t\tconst members: { name: string; username: string; names: string[] }[] = [];\n\n\t\t\t// Process roles\n\t\t\tfor (const entityId of Object.keys(roles) as UUID[]) {\n\t\t\t\tconst userRole = roles[entityId];\n\n\t\t\t\t// get the user from the database\n\t\t\t\tconst user = await runtime.getEntityById(entityId);\n\n\t\t\t\tconst name = user.metadata[room.source]?.name;\n\t\t\t\tconst username = user.metadata[room.source]?.username;\n\t\t\t\tconst names = user.names;\n\n\t\t\t\t// Skip duplicates (we store both UUID and original ID)\n\t\t\t\tif (\n\t\t\t\t\towners.some((owner) => owner.username === username) ||\n\t\t\t\t\tadmins.some((admin) => admin.username === username) ||\n\t\t\t\t\tmembers.some((member) => member.username === username)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Add to appropriate group\n\t\t\t\tswitch (userRole) {\n\t\t\t\t\tcase \"OWNER\":\n\t\t\t\t\t\towners.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"ADMIN\":\n\t\t\t\t\t\tadmins.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmembers.push({ name, username, names });\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Format the response\n\t\t\tlet response = \"# Server Role Hierarchy\\n\\n\";\n\n\t\t\tif (owners.length > 0) {\n\t\t\t\tresponse += \"## Owners\\n\";\n\t\t\t\towners.forEach((owner) => {\n\t\t\t\t\tresponse += `${owner.name} (${owner.names.join(\", \")})\\n`;\n\t\t\t\t});\n\t\t\t\tresponse += \"\\n\";\n\t\t\t}\n\n\t\t\tif (admins.length > 0) {\n\t\t\t\tresponse += \"## Administrators\\n\";\n\t\t\t\tadmins.forEach((admin) => {\n\t\t\t\t\tresponse += `${admin.name} (${admin.names.join(\", \")}) (${\n\t\t\t\t\t\tadmin.username\n\t\t\t\t\t})\\n`;\n\t\t\t\t});\n\t\t\t\tresponse += \"\\n\";\n\t\t\t}\n\n\t\t\tif (members.length > 0) {\n\t\t\t\tresponse += \"## Members\\n\";\n\t\t\t\tmembers.forEach((member) => {\n\t\t\t\t\tresponse += `${member.name} (${member.names.join(\", \")}) (${\n\t\t\t\t\t\tmember.username\n\t\t\t\t\t})\\n`;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: response,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles: response,\n\t\t\t\t},\n\t\t\t\ttext: response,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in role provider:\", error);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\troles: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\troles: \"There was an error retrieving role information.\",\n\t\t\t\t},\n\t\t\t\ttext: \"There was an error retrieving role information.\",\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport default roleProvider;\n","import crypto from \"node:crypto\";\nimport { createUniqueUuid } from \"./entities\";\nimport { logger } from \"./logger\";\nimport type {\n\tIAgentRuntime,\n\tOnboardingConfig,\n\tSetting,\n\tWorld,\n\tWorldSettings,\n} from \"./types\";\n\n/**\n * Creates a new Setting object based on provided config settings.\n * @param {Omit<Setting, \"value\">} configSetting - The configuration settings for the new Setting object.\n * @returns {Setting} - The newly created Setting object.\n */\nfunction createSettingFromConfig(\n\tconfigSetting: Omit<Setting, \"value\">,\n): Setting {\n\treturn {\n\t\tname: configSetting.name,\n\t\tdescription: configSetting.description,\n\t\tusageDescription: configSetting.usageDescription || \"\",\n\t\tvalue: null,\n\t\trequired: configSetting.required,\n\t\tvalidation: configSetting.validation || null,\n\t\tpublic: configSetting.public || false,\n\t\tsecret: configSetting.secret || false,\n\t\tdependsOn: configSetting.dependsOn || [],\n\t\tonSetAction: configSetting.onSetAction || null,\n\t\tvisibleIf: configSetting.visibleIf || null,\n\t};\n}\n\n/**\n * Generate a salt for settings encryption\n */\n/**\n * Retrieves the salt for the agent based on the provided runtime information.\n *\n * @param {IAgentRuntime} runtime - The runtime information of the agent.\n * @returns {string} The salt for the agent.\n */\nfunction getSalt(runtime: IAgentRuntime): string {\n\tconst secretSalt = process.env.SECRET_SALT || \"secretsalt\";\n\tconst agentId = runtime.agentId;\n\n\tif (!agentId) {\n\t\tlogger.warn(\"AgentId is missing when generating encryption salt\");\n\t}\n\n\tconst salt = secretSalt + (agentId || \"\");\n\tlogger.debug(\n\t\t`Generated salt with length: ${salt.length} (truncated for security)`,\n\t);\n\treturn salt;\n}\n\n/**\n * Applies salt to the value of a setting\n * Only applies to secret settings with string values\n */\nfunction saltSettingValue(setting: Setting, salt: string): Setting {\n\tconst settingCopy = { ...setting };\n\n\t// Only encrypt string values in secret settings\n\tif (\n\t\tsetting.secret === true &&\n\t\ttypeof setting.value === \"string\" &&\n\t\tsetting.value\n\t) {\n\t\ttry {\n\t\t\t// Check if value is already encrypted (has the format \"iv:encrypted\")\n\t\t\tconst parts = setting.value.split(\":\");\n\t\t\tif (parts.length === 2) {\n\t\t\t\ttry {\n\t\t\t\t\t// Try to parse the first part as hex to see if it's already encrypted\n\t\t\t\t\tconst possibleIv = Buffer.from(parts[0], \"hex\");\n\t\t\t\t\tif (possibleIv.length === 16) {\n\t\t\t\t\t\t// Value is likely already encrypted, return as is\n\t\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t\t\"Value appears to be already encrypted, skipping re-encryption\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn settingCopy;\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\t// Not a valid hex string, proceed with encryption\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Create key and iv from the salt\n\t\t\tconst key = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(salt)\n\t\t\t\t.digest()\n\t\t\t\t.slice(0, 32);\n\t\t\tconst iv = crypto.randomBytes(16);\n\n\t\t\t// Encrypt the value\n\t\t\tconst cipher = crypto.createCipheriv(\"aes-256-cbc\", key, iv);\n\t\t\tlet encrypted = cipher.update(setting.value, \"utf8\", \"hex\");\n\t\t\tencrypted += cipher.final(\"hex\");\n\n\t\t\t// Store IV with the encrypted value so we can decrypt it later\n\t\t\tsettingCopy.value = `${iv.toString(\"hex\")}:${encrypted}`;\n\n\t\t\tlogger.debug(`Successfully encrypted value with IV length: ${iv.length}`);\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error encrypting setting value: ${error}`);\n\t\t\t// Return the original value on error\n\t\t}\n\t}\n\n\treturn settingCopy;\n}\n\n/**\n * Removes salt from the value of a setting\n * Only applies to secret settings with string values\n */\nfunction unsaltSettingValue(setting: Setting, salt: string): Setting {\n\tconst settingCopy = { ...setting };\n\n\t// Only decrypt string values in secret settings\n\tif (\n\t\tsetting.secret === true &&\n\t\ttypeof setting.value === \"string\" &&\n\t\tsetting.value\n\t) {\n\t\ttry {\n\t\t\t// Split the IV and encrypted value\n\t\t\tconst parts = setting.value.split(\":\");\n\t\t\tif (parts.length !== 2) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Invalid encrypted value format for setting - expected 'iv:encrypted'`,\n\t\t\t\t);\n\t\t\t\treturn settingCopy; // Return the original value without decryption\n\t\t\t}\n\n\t\t\tconst iv = Buffer.from(parts[0], \"hex\");\n\t\t\tconst encrypted = parts[1];\n\n\t\t\t// Verify IV length\n\t\t\tif (iv.length !== 16) {\n\t\t\t\tlogger.warn(`Invalid IV length (${iv.length}) - expected 16 bytes`);\n\t\t\t\treturn settingCopy; // Return the original value without decryption\n\t\t\t}\n\n\t\t\t// Create key from the salt\n\t\t\tconst key = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(salt)\n\t\t\t\t.digest()\n\t\t\t\t.slice(0, 32);\n\n\t\t\t// Decrypt the value\n\t\t\tconst decipher = crypto.createDecipheriv(\"aes-256-cbc\", key, iv);\n\t\t\tlet decrypted = decipher.update(encrypted, \"hex\", \"utf8\");\n\t\t\tdecrypted += decipher.final(\"utf8\");\n\n\t\t\tsettingCopy.value = decrypted;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error decrypting setting value: ${error}`);\n\t\t\t// Return the encrypted value on error\n\t\t}\n\t}\n\n\treturn settingCopy;\n}\n\n/**\n * Applies salt to all settings in a WorldSettings object\n */\nfunction saltWorldSettings(\n\tworldSettings: WorldSettings,\n\tsalt: string,\n): WorldSettings {\n\tconst saltedSettings: WorldSettings = {};\n\n\tfor (const [key, setting] of Object.entries(worldSettings)) {\n\t\tsaltedSettings[key] = saltSettingValue(setting, salt);\n\t}\n\n\treturn saltedSettings;\n}\n\n/**\n * Removes salt from all settings in a WorldSettings object\n */\nfunction unsaltWorldSettings(\n\tworldSettings: WorldSettings,\n\tsalt: string,\n): WorldSettings {\n\tconst unsaltedSettings: WorldSettings = {};\n\n\tfor (const [key, setting] of Object.entries(worldSettings)) {\n\t\tunsaltedSettings[key] = unsaltSettingValue(setting, salt);\n\t}\n\n\treturn unsaltedSettings;\n}\n\n/**\n * Updates settings state in world metadata\n */\nexport async function updateWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n\tworldSettings: WorldSettings,\n): Promise<boolean> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getWorld(worldId);\n\n\t\tif (!world) {\n\t\t\tlogger.error(`No world found for server ${serverId}`);\n\t\t\treturn false;\n\t\t}\n\n\t\t// Initialize metadata if it doesn't exist\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// Apply salt to settings before saving\n\t\tconst salt = getSalt(runtime);\n\t\tconst saltedSettings = saltWorldSettings(worldSettings, salt);\n\n\t\t// Update settings state\n\t\tworld.metadata.settings = saltedSettings;\n\n\t\t// Save updated world\n\t\tawait runtime.updateWorld(world);\n\n\t\treturn true;\n\t} catch (error) {\n\t\tlogger.error(`Error updating settings state: ${error}`);\n\t\treturn false;\n\t}\n}\n\n/**\n * Gets settings state from world metadata\n */\nexport async function getWorldSettings(\n\truntime: IAgentRuntime,\n\tserverId: string,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\tconst worldId = createUniqueUuid(runtime, serverId);\n\t\tconst world = await runtime.getWorld(worldId);\n\n\t\tif (!world || !world.metadata?.settings) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Get settings from metadata\n\t\tconst saltedSettings = world.metadata.settings as WorldSettings;\n\n\t\t// Remove salt from settings before returning\n\t\tconst salt = getSalt(runtime);\n\t\treturn unsaltWorldSettings(saltedSettings, salt);\n\t} catch (error) {\n\t\tlogger.error(`Error getting settings state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Initializes settings configuration for a server\n */\nexport async function initializeOnboarding(\n\truntime: IAgentRuntime,\n\tworld: World,\n\tconfig: OnboardingConfig,\n): Promise<WorldSettings | null> {\n\ttry {\n\t\t// Check if settings state already exists\n\t\tif (world.metadata?.settings) {\n\t\t\tlogger.info(\n\t\t\t\t`Onboarding state already exists for server ${world.serverId}`,\n\t\t\t);\n\t\t\t// Get settings from metadata and remove salt\n\t\t\tconst saltedSettings = world.metadata.settings as WorldSettings;\n\t\t\tconst salt = getSalt(runtime);\n\t\t\treturn unsaltWorldSettings(saltedSettings, salt);\n\t\t}\n\n\t\t// Create new settings state\n\t\tconst worldSettings: WorldSettings = {};\n\n\t\t// Initialize settings from config\n\t\tif (config.settings) {\n\t\t\tfor (const [key, configSetting] of Object.entries(config.settings)) {\n\t\t\t\tworldSettings[key] = createSettingFromConfig(configSetting);\n\t\t\t}\n\t\t}\n\n\t\t// Save settings state to world metadata\n\t\tif (!world.metadata) {\n\t\t\tworld.metadata = {};\n\t\t}\n\n\t\t// No need to salt here as the settings are just initialized with null values\n\t\tworld.metadata.settings = worldSettings;\n\n\t\tawait runtime.updateWorld(world);\n\n\t\tlogger.info(`Initialized settings config for server ${world.serverId}`);\n\t\treturn worldSettings;\n\t} catch (error) {\n\t\tlogger.error(`Error initializing settings config: ${error}`);\n\t\treturn null;\n\t}\n}\n","// File: /swarm/shared/settings/provider.ts\n// Updated to use world metadata instead of cache\n\nimport { logger } from \"../logger\";\nimport { findWorldForOwner } from \"../roles\";\nimport { getWorldSettings } from \"../settings\";\nimport {\n\tChannelType,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype ProviderResult,\n\ttype Setting,\n\ttype State,\n\ttype WorldSettings,\n} from \"../types\";\n\n/**\n * Formats a setting value for display, respecting privacy flags\n */\nconst formatSettingValue = (\n\tsetting: Setting,\n\tisOnboarding: boolean,\n): string => {\n\tif (setting.value === null) return \"Not set\";\n\tif (setting.secret && !isOnboarding) return \"****************\";\n\treturn String(setting.value);\n};\n\n/**\n * Generates a status message based on the current settings state\n */\nfunction generateStatusMessage(\n\truntime: IAgentRuntime,\n\tworldSettings: WorldSettings,\n\tisOnboarding: boolean,\n\tstate?: State,\n): string {\n\ttry {\n\t\t// Format settings for display\n\t\tconst formattedSettings = Object.entries(worldSettings)\n\t\t\t.map(([key, setting]) => {\n\t\t\t\tif (typeof setting !== \"object\" || !setting.name) return null;\n\n\t\t\t\tconst description = setting.description || \"\";\n\t\t\t\tconst usageDescription = setting.usageDescription || \"\";\n\n\t\t\t\t// Skip settings that should be hidden based on visibility function\n\t\t\t\tif (setting.visibleIf && !setting.visibleIf(worldSettings)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tkey,\n\t\t\t\t\tname: setting.name,\n\t\t\t\t\tvalue: formatSettingValue(setting, isOnboarding),\n\t\t\t\t\tdescription,\n\t\t\t\t\tusageDescription,\n\t\t\t\t\trequired: setting.required,\n\t\t\t\t\tconfigured: setting.value !== null,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter(Boolean);\n\n\t\t// Count required settings that are not configured\n\t\tconst requiredUnconfigured = formattedSettings.filter(\n\t\t\t(s) => s.required && !s.configured,\n\t\t).length;\n\n\t\t// Generate appropriate message\n\t\tif (isOnboarding) {\n\t\t\tif (requiredUnconfigured > 0) {\n\t\t\t\treturn `# PRIORITY TASK: Onboarding with ${state.senderName}\\n${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} still needs to configure ${requiredUnconfigured} required settings:\\n\\n${formattedSettings\n\t\t\t\t\t.filter((s) => s.required && !s.configured)\n\t\t\t\t\t.map((s) => `${s.key}: ${s.value}\\n(${s.name}) ${s.usageDescription}`)\n\t\t\t\t\t.join(\"\\n\\n\")}\\n\\nValid settings keys: ${Object.keys(\n\t\t\t\t\tworldSettings,\n\t\t\t\t).join(\n\t\t\t\t\t\", \",\n\t\t\t\t)}\\n\\nIf the user gives any information related to the settings, ${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} should use the UPDATE_SETTINGS action to update the settings with this new information. ${\n\t\t\t\t\truntime.character.name\n\t\t\t\t} can update any, some or all settings.`;\n\t\t\t}\n\t\t\treturn `All required settings have been configured! Here's the current configuration:\\n\\n${formattedSettings\n\t\t\t\t.map((s) => `${s.name}: ${s.description}\\nValue: ${s.value}`)\n\t\t\t\t.join(\"\\n\")}`;\n\t\t}\n\t\t// Non-onboarding context - list all public settings with values and descriptions\n\t\treturn `## Current Configuration\\n\\n${\n\t\t\trequiredUnconfigured > 0\n\t\t\t\t? `IMPORTANT!: ${requiredUnconfigured} required settings still need configuration. ${runtime.character.name} should get onboarded with the OWNER as soon as possible.\\n\\n`\n\t\t\t\t: \"All required settings are configured.\\n\\n\"\n\t\t}${formattedSettings\n\t\t\t.map(\n\t\t\t\t(s) =>\n\t\t\t\t\t`### ${s.name}\\n**Value:** ${s.value}\\n**Description:** ${s.description}`,\n\t\t\t)\n\t\t\t.join(\"\\n\\n\")}`;\n\t} catch (error) {\n\t\tlogger.error(`Error generating status message: ${error}`);\n\t\treturn \"Error generating configuration status.\";\n\t}\n}\n\n/**\n * Creates an settings provider with the given configuration\n * Updated to use world metadata instead of cache\n */\nexport const settingsProvider: Provider = {\n\tname: \"SETTINGS\",\n\tdescription: \"Current settings for the server\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate?: State,\n\t): Promise<ProviderResult> => {\n\t\ttry {\n\t\t\t// Parallelize the initial database operations to improve performance\n\t\t\t// These operations can run simultaneously as they don't depend on each other\n\t\t\tconst [room, userWorld] = await Promise.all([\n\t\t\t\truntime.getRoom(message.roomId),\n\t\t\t\tfindWorldForOwner(runtime, message.entityId),\n\t\t\t]).catch((error) => {\n\t\t\t\tlogger.error(`Error fetching initial data: ${error}`);\n\t\t\t\tthrow new Error(\"Failed to retrieve room or user world information\");\n\t\t\t});\n\n\t\t\tif (!room) {\n\t\t\t\tlogger.error(\"No room found for settings provider\");\n\t\t\t\treturn {\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t},\n\t\t\t\t\tvalues: {\n\t\t\t\t\t\tsettings: \"Error: Room not found\",\n\t\t\t\t\t},\n\t\t\t\t\ttext: \"Error: Room not found\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst type = room.type;\n\t\t\tconst isOnboarding = type === ChannelType.DM;\n\n\t\t\tlet world;\n\t\t\tlet serverId;\n\t\t\tlet worldSettings;\n\n\t\t\tif (isOnboarding) {\n\t\t\t\t// In onboarding mode, use the user's world directly\n\t\t\t\tworld = userWorld;\n\n\t\t\t\tif (!world) {\n\t\t\t\t\tlogger.error(\"No world found for user during onboarding\");\n\t\t\t\t\tthrow new Error(\"No server ownership found for onboarding\");\n\t\t\t\t}\n\n\t\t\t\tserverId = world.serverId;\n\n\t\t\t\t// Fetch world settings based on the server ID\n\t\t\t\ttry {\n\t\t\t\t\tworldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error fetching world settings: ${error}`);\n\t\t\t\t\tthrow new Error(`Failed to retrieve settings for server ${serverId}`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// For non-onboarding, we need to get the world associated with the room\n\t\t\t\ttry {\n\t\t\t\t\tworld = await runtime.getWorld(room.worldId);\n\t\t\t\t\tserverId = world.serverId;\n\n\t\t\t\t\t// Once we have the serverId, get the settings\n\t\t\t\t\tif (serverId) {\n\t\t\t\t\t\tworldSettings = await getWorldSettings(runtime, serverId);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error(`No server ID found for world ${room.worldId}`);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error processing world data: ${error}`);\n\t\t\t\t\tthrow new Error(\"Failed to process world information\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If no server found after recovery attempts\n\t\t\tif (!serverId) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`No server ownership found for user ${message.entityId} after recovery attempt`,\n\t\t\t\t);\n\t\t\t\treturn isOnboarding\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings:\n\t\t\t\t\t\t\t\t\t\"The user doesn't appear to have ownership of any servers. They should make sure they're using the correct account.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"The user doesn't appear to have ownership of any servers. They should make sure they're using the correct account.\",\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings: \"Error: No configuration access\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"Error: No configuration access\",\n\t\t\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!worldSettings) {\n\t\t\t\tlogger.info(`No settings state found for server ${serverId}`);\n\t\t\t\treturn isOnboarding\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings:\n\t\t\t\t\t\t\t\t\t\"The user doesn't appear to have any settings configured for this server. They should configure some settings for this server.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"The user doesn't appear to have any settings configured for this server. They should configure some settings for this server.\",\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tsettings: [],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\tsettings: \"Configuration has not been completed yet.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: \"Configuration has not been completed yet.\",\n\t\t\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Generate the status message based on the settings\n\t\t\tconst output = generateStatusMessage(\n\t\t\t\truntime,\n\t\t\t\tworldSettings,\n\t\t\t\tisOnboarding,\n\t\t\t\tstate,\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tsettings: worldSettings,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tsettings: output,\n\t\t\t\t},\n\t\t\t\ttext: output,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger.error(`Critical error in settings provider: ${error}`);\n\t\t\treturn {\n\t\t\t\tdata: {\n\t\t\t\t\tsettings: [],\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tsettings:\n\t\t\t\t\t\t\"Error retrieving configuration information. Please try again later.\",\n\t\t\t\t},\n\t\t\t\ttext: \"Error retrieving configuration information. Please try again later.\",\n\t\t\t};\n\t\t}\n\t},\n};\n","import type { IAgentRuntime, Memory, Provider, State } from \"../types\";\n\n/**\n * Time provider function that retrieves the current date and time in UTC\n * for use in time-based operations or responses.\n *\n * @param _runtime - The runtime environment of the bot agent.\n * @param _message - The memory object containing message data.\n * @returns An object containing the current date and time data, human-readable date and time string,\n * and a text response with the current date and time information.\n */\nexport const timeProvider: Provider = {\n\tname: \"TIME\",\n\tget: async (_runtime: IAgentRuntime, _message: Memory) => {\n\t\tconst currentDate = new Date();\n\n\t\t// Get UTC time since bots will be communicating with users around the global\n\t\tconst options = {\n\t\t\ttimeZone: \"UTC\",\n\t\t\tdateStyle: \"full\" as const,\n\t\t\ttimeStyle: \"long\" as const,\n\t\t};\n\t\tconst humanReadable = new Intl.DateTimeFormat(\"en-US\", options).format(\n\t\t\tcurrentDate,\n\t\t);\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\ttime: currentDate,\n\t\t\t},\n\t\t\tvalues: {\n\t\t\t\ttime: humanReadable,\n\t\t\t},\n\t\t\ttext: `The current date and time is ${humanReadable}. Please use this as your reference for any time-based operations or responses.`,\n\t\t};\n\t},\n};\n","// TODO: Review ensureConnection and other runtime helper methods and their usage and implement, they may be helpful\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n\tChannelType,\n\tEventTypes,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tService,\n\ttype UUID,\n\ttype ActionEventPayload,\n\ttype EvaluatorEventPayload,\n\ttype World,\n\ttype Room,\n} from \"../types\";\nimport { createUniqueUuid } from \"../entities\";\nimport logger from \"../logger\";\n\ninterface ActionTracker {\n\tactionId: UUID;\n\tactionName: string;\n\tstartTime: number;\n\tcompleted: boolean;\n\terror?: Error;\n}\n\ninterface EvaluatorTracker {\n\tevaluatorId: UUID;\n\tevaluatorName: string;\n\tstartTime: number;\n\tcompleted: boolean;\n\terror?: Error;\n}\n\n/**\n * Represents a service that allows the agent to interact in a scenario testing environment.\n * The agent can create rooms, send messages, and communicate with other agents in a live interactive testing environment.\n * @extends Service\n */\nexport class ScenarioService extends Service {\n\tstatic serviceType = \"scenario\";\n\tcapabilityDescription =\n\t\t\"The agent is currently in a scenario testing environment. It can create rooms, send messages, and talk to other agents in a live interactive testing environment.\";\n\tprivate messageHandlers: Map<UUID, HandlerCallback[]> = new Map();\n\tprivate worlds: Map<UUID, World> = new Map();\n\tprivate activeActions: Map<UUID, ActionTracker> = new Map();\n\tprivate activeEvaluators: Map<UUID, EvaluatorTracker> = new Map();\n\n\t/**\n\t * Constructor for creating a new instance of the class.\n\t *\n\t * @param runtime - The IAgentRuntime instance to be passed to the constructor.\n\t */\n\tconstructor(protected runtime: IAgentRuntime) {\n\t\tsuper(runtime);\n\t\tthis.setupEventListeners();\n\t}\n\n\tprivate setupEventListeners() {\n\t\t// Track action start/completion\n\t\tthis.runtime.registerEvent(EventTypes.ACTION_STARTED, async (data: ActionEventPayload) => {\n\t\t\tthis.activeActions.set(data.actionId, {\n\t\t\t\tactionId: data.actionId,\n\t\t\t\tactionName: data.actionName,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\tcompleted: false\n\t\t\t});\n\t\t\treturn Promise.resolve();\n\t\t});\n\n\t\tthis.runtime.registerEvent(EventTypes.ACTION_COMPLETED, async (data: ActionEventPayload) => {\n\t\t\tconst action = this.activeActions.get(data.actionId);\n\t\t\tif (action) {\n\t\t\t\taction.completed = true;\n\t\t\t\taction.error = data.error;\n\t\t\t}\n\t\t\treturn Promise.resolve();\n\t\t});\n\n\t\t// Track evaluator start/completion\n\t\tthis.runtime.registerEvent(EventTypes.EVALUATOR_STARTED, async (data: EvaluatorEventPayload) => {\n\t\t\tthis.activeEvaluators.set(data.evaluatorId, {\n\t\t\t\tevaluatorId: data.evaluatorId,\n\t\t\t\tevaluatorName: data.evaluatorName,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\tcompleted: false\n\t\t\t});\n\t\t\tlogger.debug(\"Evaluator started\", data);\n\t\t\treturn Promise.resolve();\n\t\t});\n\n\t\tthis.runtime.registerEvent(EventTypes.EVALUATOR_COMPLETED, async (data: EvaluatorEventPayload) => {\n\t\t\tconst evaluator = this.activeEvaluators.get(data.evaluatorId);\n\t\t\tif (evaluator) {\n\t\t\t\tevaluator.completed = true;\n\t\t\t\tevaluator.error = data.error;\n\t\t\t}\n\t\t\tlogger.debug(\"Evaluator completed\", data);\n\t\t\treturn Promise.resolve();\n\t\t});\n\t}\n\n\t/**\n\t * Start the scenario service with the given runtime.\n\t * @param {IAgentRuntime} runtime - The agent runtime\n\t * @returns {Promise<ScenarioService>} - The started scenario service\n\t */\n\tstatic async start(runtime: IAgentRuntime) {\n\t\tconst service = new ScenarioService(runtime);\n\t\treturn service;\n\t}\n\n\t/**\n\t * Stops the Scenario service associated with the given runtime.\n\t *\n\t * @param {IAgentRuntime} runtime The runtime to stop the service for.\n\t * @throws {Error} When the Scenario service is not found.\n\t */\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\tconst service = runtime.getService(ScenarioService.serviceType);\n\t\tif (!service) {\n\t\t\tthrow new Error(\"Scenario service not found\");\n\t\t}\n\t\tservice.stop();\n\t}\n\n\t/**\n\t * Asynchronously stops the current process by clearing all message handlers and worlds.\n\t */\n\tasync stop() {\n\t\tthis.messageHandlers.clear();\n\t\tthis.worlds.clear();\n\t\tthis.activeActions.clear();\n\t\tthis.activeEvaluators.clear();\n\t}\n\n\t/**\n\t * Creates a new world with the specified name and owner.\n\t * @param name The name of the world\n\t * @param ownerName The name of the world owner\n\t * @returns The created world's ID\n\t */\n\tasync createWorld(name: string, ownerName: string): Promise<UUID> {\n\t\tconst serverId = createUniqueUuid(this.runtime.agentId, name);\n\t\tconst worldId = uuidv4() as UUID;\n\t\tconst ownerId = uuidv4() as UUID;\n\n\t\tconst world: World = {\n\t\t\tid: worldId,\n\t\t\tname,\n\t\t\tserverId,\n\t\t\tagentId: this.runtime.agentId,\n\t\t\t// TODO: get the server id, create it or whatever\n\t\t\tmetadata: {\n\t\t\t\t// this is wrong, the owner needs to be tracked by scenario and similar to how we do it with Discord etc\n\t\t\t\towner: {\n\t\t\t\t\tid: ownerId,\n\t\t\t\t\tname: ownerName\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tthis.worlds.set(worldId, world);\n\t\treturn worldId;\n\t}\n\n\t/**\n\t * Creates a room in the specified world.\n\t * @param worldId The ID of the world to create the room in\n\t * @param name The name of the room\n\t * @returns The created room's ID\n\t */\n\tasync createRoom(worldId: UUID, name: string): Promise<UUID> {\n\t\tconst world = this.worlds.get(worldId);\n\t\tif (!world) {\n\t\t\tthrow new Error(`World ${worldId} not found`);\n\t\t}\n\n\t\tconst roomId = uuidv4() as UUID;\n\n\t\t// worlds do not have rooms on them, we'll need to use runtime.getRooms(worldId) from the runtime\n\n\t\tawait this.runtime.ensureRoomExists({\n\t\t\tid: roomId,\n\t\t\tname,\n\t\t\tsource: \"scenario\",\n\t\t\ttype: ChannelType.GROUP,\n\t\t\tchannelId: roomId,\n\t\t\tserverId: worldId\n\t\t});\n\n\t\treturn roomId;\n\t}\n\n\t/**\n\t * Adds a participant to a room\n\t * @param worldId The world ID\n\t * @param roomId The room ID\n\t * @param participantId The participant's ID\n\t */\n\tasync addParticipant(worldId: UUID, roomId: UUID, participantId: UUID) {\n\t\tconst world = this.worlds.get(worldId);\n\t\tif (!world) {\n\t\t\tthrow new Error(`World ${worldId} not found`);\n\t\t}\n\n\t\tconst room = this.runtime.getRoom(roomId);\n\t\tif (!room) {\n\t\t\tthrow new Error(`Room ${roomId} not found in world ${worldId}`);\n\t\t}\n\n\t\tawait this.runtime.addParticipant(roomId, participantId);\n\n\n\t\t// TODO: This could all be rewritten like an ensureConnection approach\n\t}\n\n\t/**\n\t * Sends a message in a specific room\n\t * @param sender The runtime of the sending agent\n\t * @param worldId The world ID\n\t * @param roomId The room ID\n\t * @param text The message text\n\t */\n\tasync sendMessage(\n\t\tsender: IAgentRuntime,\n\t\tworldId: UUID,\n\t\troomId: UUID,\n\t\ttext: string,\n\t) {\n\t\tconst world = this.worlds.get(worldId);\n\t\tif (!world) {\n\t\t\tthrow new Error(`World ${worldId} not found`);\n\t\t}\n\n\t\tconst memory: Memory = {\n\t\t\tentityId: sender.agentId,\n\t\t\tagentId: sender.agentId,\n\t\t\troomId,\n\t\t\tcontent: {\n\t\t\t\ttext,\n\t\t\t\tsource: \"scenario\",\n\t\t\t\tname: sender.character.name,\n\t\t\t\tuserName: sender.character.name,\n\t\t\t\tchannelType: ChannelType.GROUP,\n\t\t\t},\n\t\t};\n\n\t\tconst participants = await this.runtime.getParticipantsForRoom(roomId);\n\n\t\t// Emit message received event for all participants\n\t\tfor (const participantId of participants) {\n\t\t\tthis.runtime.emitEvent(\"MESSAGE_RECEIVED\", {\n\t\t\t\truntime: this.runtime,\n\t\t\t\tmessage: memory,\n\t\t\t\troomId,\n\t\t\t\tentityId: participantId,\n\t\t\t\tsource: \"scenario\",\n\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Waits for all active actions and evaluators to complete\n\t * @param timeout Maximum time to wait in milliseconds\n\t * @returns True if all completed successfully, false if timeout occurred\n\t */\n\tasync waitForCompletion(timeout = 30000): Promise<boolean> {\n\t\tconst startTime = Date.now();\n\n\t\twhile (Date.now() - startTime < timeout) {\n\t\t\tconst allActionsComplete = Array.from(this.activeActions.values()).every(\n\t\t\t\taction => action.completed\n\t\t\t);\n\t\t\tconst allEvaluatorsComplete = Array.from(this.activeEvaluators.values()).every(\n\t\t\t\tevaluator => evaluator.completed\n\t\t\t);\n\n\t\t\tif (allActionsComplete && allEvaluatorsComplete) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tawait new Promise(resolve => setTimeout(resolve, 100));\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Gets the current state of all active actions and evaluators\n\t */\n\tgetActiveState() {\n\t\treturn {\n\t\t\tactions: Array.from(this.activeActions.values()),\n\t\t\tevaluators: Array.from(this.activeEvaluators.values())\n\t\t};\n\t}\n\n\t/**\n\t * Cleans up the scenario state\n\t */\n\tasync cleanup() {\n\t\tthis.worlds.clear();\n\t\tthis.activeActions.clear();\n\t\tthis.activeEvaluators.clear();\n\t\tthis.messageHandlers.clear();\n\t}\n}\n\n// Updated scenario implementation using the new client\n/**\n * An array of asynchronous functions representing different scenarios.\n *\n * @param {IAgentRuntime[]} members - The array of agent runtime objects.\n * @returns {Promise<void>} - A promise that resolves when the scenario is completed.\n */\nconst scenarios = [\n\tasync function scenario1(members: IAgentRuntime[]) {\n\t\tconst service = members[0].getService(\"scenario\") as ScenarioService;\n\t\tif (!service) {\n\t\t\tthrow new Error(\"Scenario service not found\");\n\t\t}\n\n\t\t// Create a test world\n\t\tconst worldId = await service.createWorld(\"Test Server\", \"Test Owner\");\n\n\t\t// Create rooms for each member\n\t\tconst roomIds = [];\n\t\tfor (const member of members) {\n\t\t\tconst roomId = await service.createRoom(worldId, `Test Room for ${member.character.name}`);\n\t\t\troomIds.push(roomId);\n\t\t\tawait service.addParticipant(worldId, roomId, member.agentId);\n\t\t}\n\n\t\t// Set up conversation history in the first room\n\t\tawait service.sendMessage(\n\t\t\tmembers[0],\n\t\t\tworldId,\n\t\t\troomIds[0],\n\t\t\t\"Earlier message from conversation...\"\n\t\t);\n\n\t\t// Send live message that triggers handlers\n\t\tawait service.sendMessage(\n\t\t\tmembers[0],\n\t\t\tworldId,\n\t\t\troomIds[0],\n\t\t\t\"Hello everyone!\"\n\t\t);\n\t},\n];\n\n/**\n * Asynchronously starts the specified scenario for the given list of agent runtimes.\n * @param {IAgentRuntime[]} members - The list of agent runtimes participating in the scenario.\n * @returns {Promise<void>} - A promise that resolves when all scenarios have been executed.\n */\nexport async function startScenario(members: IAgentRuntime[]) {\n\tfor (const scenario of scenarios) {\n\t\tawait scenario(members);\n\t}\n}\n","// registered to runtime through plugin\n\nimport logger from \"../logger\";\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\tService,\n\ttype ServiceType,\n\tServiceTypes,\n\ttype State,\n\ttype Task\n} from \"../types\";\n\n/**\n * TaskService class representing a service that schedules and executes tasks.\n * @extends Service\n * @property {NodeJS.Timeout|null} timer - Timer for executing tasks\n * @property {number} TICK_INTERVAL - Interval in milliseconds to check for tasks\n * @property {ServiceType} serviceType - Service type of TASK\n * @property {string} capabilityDescription - Description of the service's capability\n * @static\n * @method start - Static method to start the TaskService\n * @method createTestTasks - Method to create test tasks\n * @method startTimer - Private method to start the timer for checking tasks\n * @method validateTasks - Private method to validate tasks\n * @method checkTasks - Private method to check tasks and execute them\n * @method executeTask - Private method to execute a task\n * @static\n * @method stop - Static method to stop the TaskService\n * @method stop - Method to stop the TaskService\n */\nexport class TaskService extends Service {\n\tprivate timer: NodeJS.Timeout | null = null;\n\tprivate readonly TICK_INTERVAL = 1000; // Check every second\n\tstatic serviceType: ServiceType = ServiceTypes.TASK;\n\tcapabilityDescription = \"The agent is able to schedule and execute tasks\";\n\n\t/**\n\t * Start the TaskService with the given runtime.\n\t * @param {IAgentRuntime} runtime - The runtime for the TaskService.\n\t * @returns {Promise<TaskService>} A promise that resolves with the TaskService instance.\n\t */\n\tstatic async start(runtime: IAgentRuntime): Promise<TaskService> {\n\t\tconst service = new TaskService(runtime);\n\t\tawait service.startTimer();\n\t\tawait service.createTestTasks();\n\t\treturn service;\n\t}\n\n\t/**\n\t * Asynchronously creates test tasks by registering task workers for repeating and one-time tasks,\n\t * validates the tasks, executes the tasks, and creates the tasks if they do not already exist.\n\t */\n\tasync createTestTasks() {\n\t\t// Register task worker for repeating task\n\t\tthis.runtime.registerTaskWorker({\n\t\t\tname: \"REPEATING_TEST_TASK\",\n\t\t\tvalidate: async (_runtime, _message, _state) => {\n\t\t\t\tlogger.debug(\"Validating repeating test task\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\texecute: async (_runtime, _options) => {\n\t\t\t\tlogger.debug(\"Executing repeating test task\");\n\t\t\t},\n\t\t});\n\n\t\t// Register task worker for one-time task\n\t\tthis.runtime.registerTaskWorker({\n\t\t\tname: \"ONETIME_TEST_TASK\",\n\t\t\tvalidate: async (_runtime, _message, _state) => {\n\t\t\t\tlogger.debug(\"Validating one-time test task\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\texecute: async (_runtime, _options) => {\n\t\t\t\tlogger.debug(\"Executing one-time test task\");\n\t\t\t},\n\t\t});\n\n\t\t// check if the task exists\n\t\tconst tasks = await this.runtime.getTasksByName(\"REPEATING_TEST_TASK\");\n\n\t\tif (tasks.length === 0) {\n\t\t\t// Create repeating task\n\t\t\tawait this.runtime.createTask({\n\t\t\t\tname: \"REPEATING_TEST_TASK\",\n\t\t\t\tdescription: \"A test task that repeats every minute\",\n\t\t\t\tmetadata: {\n\t\t\t\t\tupdatedAt: Date.now(), // Use timestamp instead of Date object\n\t\t\t\t\tupdateInterval: 1000 * 60, // 1 minute\n\t\t\t\t},\n\t\t\t\ttags: [\"queue\", \"repeat\", \"test\"],\n\t\t\t});\n\t\t}\n\n\t\t// Create one-time task\n\t\tawait this.runtime.createTask({\n\t\t\tname: \"ONETIME_TEST_TASK\",\n\t\t\tdescription: \"A test task that runs once\",\n\t\t\tmetadata: {\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t},\n\t\t\ttags: [\"queue\", \"test\"],\n\t\t});\n\t}\n\n\t/**\n\t * Starts a timer that runs a function to check tasks at a specified interval.\n\t */\n\tprivate startTimer() {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t}\n\n\t\tthis.timer = setInterval(async () => {\n\t\t\ttry {\n\t\t\t\tawait this.checkTasks();\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error checking tasks:\", error);\n\t\t\t}\n\t\t}, this.TICK_INTERVAL) as unknown as NodeJS.Timeout;\n\t}\n\n\t/**\n\t * Validates an array of Task objects.\n\t * Skips tasks without IDs or if no worker is found for the task.\n\t * If a worker has a `validate` function, it will run the validation using the `runtime`, `Memory`, and `State` parameters.\n\t * If the validation fails, the task will be skipped and the error will be logged.\n\t * @param {Task[]} tasks - An array of Task objects to validate.\n\t * @returns {Promise<Task[]>} - A Promise that resolves with an array of validated Task objects.\n\t */\n\tprivate async validateTasks(tasks: Task[]): Promise<Task[]> {\n\t\tconst validatedTasks: Task[] = [];\n\n\t\tfor (const task of tasks) {\n\t\t\t// Skip tasks without IDs\n\t\t\tif (!task.id) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst worker = this.runtime.getTaskWorker(task.name);\n\n\t\t\t// Skip if no worker found for task\n\t\t\tif (!worker) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// If worker has validate function, run validation\n\t\t\tif (worker.validate) {\n\t\t\t\ttry {\n\t\t\t\t\t// Pass empty message and state since validation is time-based\n\t\t\t\t\tconst isValid = await worker.validate(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t{} as Memory,\n\t\t\t\t\t\t{} as State,\n\t\t\t\t\t);\n\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error validating task ${task.name}:`, error);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvalidatedTasks.push(task);\n\t\t}\n\n\t\treturn validatedTasks;\n\t}\n\n\t/**\n\t * Asynchronous method that checks tasks with \"queue\" tag, validates and sorts them, then executes them based on interval and tags.\n\t *\n\t * @returns {Promise<void>} Promise that resolves once all tasks are checked and executed\n\t */\n\tprivate async checkTasks() {\n\t\ttry {\n\t\t\t// Get all tasks with \"queue\" tag\n\t\t\tconst allTasks = await this.runtime.getTasks({\n\t\t\t\ttags: [\"queue\"],\n\t\t\t});\n\n\t\t\t// validate the tasks and sort them\n\t\t\tconst tasks = await this.validateTasks(allTasks);\n\n\t\t\tif (tasks.length > 0) {\n\t\t\t\tlogger.debug(`Found ${tasks.length} queued tasks`);\n\t\t\t}\n\n\t\t\tconst now = Date.now();\n\n\t\t\tfor (const task of tasks) {\n\t\t\t\t// First check task.updatedAt (for newer task format)\n\t\t\t\t// Then fall back to task.metadata.updatedAt (for older tasks)\n\t\t\t\t// Finally default to 0 if neither exists\n\t\t\t\tlet taskStartTime: number;\n\t\t\t\t\n\t\t\t\tif (typeof task.updatedAt === 'number') {\n\t\t\t\t\ttaskStartTime = task.updatedAt;\n\t\t\t\t} else if (task.metadata?.updatedAt && typeof task.metadata.updatedAt === 'number') {\n\t\t\t\t\ttaskStartTime = task.metadata.updatedAt;\n\t\t\t\t} else if (task.updatedAt) {\n\t\t\t\t\ttaskStartTime = new Date(task.updatedAt).getTime();\n\t\t\t\t} else {\n\t\t\t\t\ttaskStartTime = 0; // Default to immediate execution if no timestamp found\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Get updateInterval from metadata\n\t\t\t\tconst updateIntervalMs = task.metadata?.updateInterval ?? 0; // update immediately\n\n\t\t\t\t// if tags does not contain \"repeat\", execute immediately\n\t\t\t\tif (!task.tags?.includes(\"repeat\")) {\n\t\t\t\t\tawait this.executeTask(task);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Check if enough time has passed since last update\n\t\t\t\tif (now - taskStartTime >= updateIntervalMs) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t`Executing task ${task.name} - interval of ${updateIntervalMs}ms has elapsed`,\n\t\t\t\t\t);\n\t\t\t\t\tawait this.executeTask(task);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error checking tasks:\", error);\n\t\t}\n\t}\n\n\t/**\n\t * Executes a given task asynchronously.\n\t *\n\t * @param {Task} task - The task to be executed.\n\t */\n\tprivate async executeTask(task: Task) {\n\t\ttry {\n\t\t\tif (!task) {\n\t\t\t\tlogger.debug(`Task ${task.id} not found`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst worker = this.runtime.getTaskWorker(task.name);\n\t\t\tif (!worker) {\n\t\t\t\tlogger.debug(`No worker found for task type: ${task.name}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.debug(`Executing task ${task.name} (${task.id})`);\n\t\t\tawait worker.execute(this.runtime, task.metadata || {}, task);\n\t\t\tlogger.debug(\"task.tags are\", task.tags);\n\t\t\t// Handle repeating vs non-repeating tasks\n\t\t\tif (task.tags?.includes(\"repeat\")) {\n\t\t\t\t// For repeating tasks, update the updatedAt timestamp\n\t\t\t\tawait this.runtime.updateTask(task.id, {\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...task.metadata,\n\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`Updated repeating task ${task.name} (${task.id}) with new timestamp`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// For non-repeating tasks, delete the task after execution\n\t\t\t\tawait this.runtime.deleteTask(task.id);\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`Deleted non-repeating task ${task.name} (${task.id}) after execution`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error executing task ${task.id}:`, error);\n\t\t}\n\t}\n\n\t/**\n\t * Stops the TASK service in the given agent runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The agent runtime containing the service.\n\t * @returns {Promise<void>} - A promise that resolves once the service has been stopped.\n\t */\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\tconst service = runtime.getService(ServiceTypes.TASK);\n\t\tif (service) {\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\t/**\n\t * Stops the timer if it is currently running.\n\t */\n\n\tasync stop() {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t}\n}\n","import { sha1 } from \"js-sha1\";\nimport { z } from \"zod\";\nimport type { UUID } from \"./types\";\n\nexport const uuidSchema = z.string().uuid() as z.ZodType<UUID>;\n\n/**\n * Validates a UUID value.\n *\n * @param {unknown} value - The value to validate.\n * @returns {UUID | null} Returns the validated UUID value or null if validation fails.\n */\nexport function validateUuid(value: unknown): UUID | null {\n\tconst result = uuidSchema.safeParse(value);\n\treturn result.success ? result.data : null;\n}\n\n/**\n * Converts a string or number to a UUID.\n *\n * @param {string | number} target - The string or number to convert to a UUID.\n * @returns {UUID} The UUID generated from the input target.\n * @throws {TypeError} Throws an error if the input target is not a string.\n */\nexport function stringToUuid(target: string | number): UUID {\n\tif (typeof target === \"number\") {\n\t\ttarget = (target as number).toString();\n\t}\n\n\tif (typeof target !== \"string\") {\n\t\tthrow TypeError(\"Value must be string\");\n\t}\n\n\tconst _uint8ToHex = (ubyte: number): string => {\n\t\tconst first = ubyte >> 4;\n\t\tconst second = ubyte - (first << 4);\n\t\tconst HEX_DIGITS = \"0123456789abcdef\".split(\"\");\n\t\treturn HEX_DIGITS[first] + HEX_DIGITS[second];\n\t};\n\n\tconst _uint8ArrayToHex = (buf: Uint8Array): string => {\n\t\tlet out = \"\";\n\t\tfor (let i = 0; i < buf.length; i++) {\n\t\t\tout += _uint8ToHex(buf[i]);\n\t\t}\n\t\treturn out;\n\t};\n\n\tconst escapedStr = encodeURIComponent(target);\n\tconst buffer = new Uint8Array(escapedStr.length);\n\tfor (let i = 0; i < escapedStr.length; i++) {\n\t\tbuffer[i] = escapedStr[i].charCodeAt(0);\n\t}\n\n\tconst hash = sha1(buffer);\n\tconst hashBuffer = new Uint8Array(hash.length / 2);\n\tfor (let i = 0; i < hash.length; i += 2) {\n\t\thashBuffer[i / 2] = Number.parseInt(hash.slice(i, i + 2), 16);\n\t}\n\n\treturn `${_uint8ArrayToHex(hashBuffer.slice(0, 4))}-${_uint8ArrayToHex(hashBuffer.slice(4, 6))}-${_uint8ToHex(hashBuffer[6] & 0x0f)}${_uint8ToHex(hashBuffer[7])}-${_uint8ToHex((hashBuffer[8] & 0x3f) | 0x80)}${_uint8ToHex(hashBuffer[9])}-${_uint8ArrayToHex(hashBuffer.slice(10, 16))}` as UUID;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,aAASA,QAAO,SAAS;AAEvB,UAAIC,OAAM;AACV,UAAI,OAAO,YAAY,UAAU;AAE/B,QAAAA,OAAM,CAAC,OAAO;AAAA,MAChB,OAAO;AACL,QAAAA,OAAM,QAAQ;AAAA,MAChB;AAGA,UAAI,SAAS;AACb,eAAS,IAAI,GAAG,IAAIA,KAAI,QAAQ,KAAK;AACnC,kBAAUA,KAAI,CAAC,EAEf,QAAQ,eAAe,EAAE,EAGzB,QAAQ,QAAQ,GAAG;AAEnB,YAAI,KAAK,UAAU,UAAU,IAAI,IAAI,UAAU,SAAS,IAAI;AAC1D,oBAAU,UAAU,UAAU,IAAI,IAAI,SAAY,UAAU,I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AI,CAAC,KAAK,cAAc,IAAI,KAAK,GAAG;AACnC,WAAK,cAAc,IAAI,OAAO,CAAC,CAAC;AAAA,IACjC;AACA,SAAK,cAAc,IAAI,KAAK,EAAG,KAAK,QAAQ;AAAA,EAC7C;AAAA,EAEA,IAAI,OAAe,UAAqC;AACvD,QAAI,CAAC,KAAK,cAAc,IAAI,KAAK,GAAG;AACnC;AAAA,IACD;AACA,UAAM,WAAW,KAAK,cAAc,IAAI,KAAK;AAC7C,UAAM,QAAQ,SAAS,QAAQ,QAAQ;AACvC,QAAI,UAAU,IAAI;AACjB,eAAS,OAAO,OAAO,CAAC;AAAA,IACzB;AAAA,EACD;AAAA,EAEA,KAAK,OAAe,MAAiB;AACpC,QAAI,CAAC,KAAK,cAAc,IAAI,KAAK,GAAG;AACnC;AAAA,IACD;AACA,eAAWA,YAAW,KAAK,cAAc,IAAI,KAAK,GAAI;AACrD,MAAAA,SAAQ,IAAI;AAAA,IACb;AAAA,EACD;AACD;","names":["dedent","raw","MemoryType","ChannelType","KnowledgeScope","CacheKeyPrefix","TEEMode","TeeType","Role","EventTypes","PlatformPrefix","names","uniqueNamesGenerator","stream","uniqueNamesGenerator","names","entity","util","objectUtil","path","errorUtil","path","errorMap","ctx","options","result","issues","elements","processed","ZodFirstPartyTypeKind","settings","path","uuidv4","options","state","state","dedent","import_dedent","settings","dedent","state","state","response","topic","message","options","names","uniqueNamesGenerator","uniqueNamesGenerator","names","formatFacts","message","knowledge","getRecentInteractions","message","recentInteractionsData","names","names","updateWorldSettings","getWorldSettings","config","getWorldSettings","options","uuidv4","uuidv4","isValid","response","uuidv4","handler","options","names","events"]}