@elizaos/core 1.4.2 → 1.4.4

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +129 -14
  2. package/dist/index.js +431 -142
  3. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { z } from 'zod';
2
- import pino from 'pino';
3
2
  import * as browser from '@sentry/browser';
4
3
  export { browser as Sentry };
5
4
 
@@ -375,8 +374,8 @@ interface Entity {
375
374
  id?: UUID;
376
375
  /** Names of the entity */
377
376
  names: string[];
378
- /** Optional additional metadata */
379
- metadata?: Metadata;
377
+ /** Additional metadata */
378
+ metadata: Metadata;
380
379
  /** Agent ID this account is related to, for agents should be themselves */
381
380
  agentId: UUID;
382
381
  /** Optional array of components */
@@ -1285,7 +1284,10 @@ declare enum EventType {
1285
1284
  ACTION_COMPLETED = "ACTION_COMPLETED",
1286
1285
  EVALUATOR_STARTED = "EVALUATOR_STARTED",
1287
1286
  EVALUATOR_COMPLETED = "EVALUATOR_COMPLETED",
1288
- MODEL_USED = "MODEL_USED"
1287
+ MODEL_USED = "MODEL_USED",
1288
+ EMBEDDING_GENERATION_REQUESTED = "EMBEDDING_GENERATION_REQUESTED",
1289
+ EMBEDDING_GENERATION_COMPLETED = "EMBEDDING_GENERATION_COMPLETED",
1290
+ EMBEDDING_GENERATION_FAILED = "EMBEDDING_GENERATION_FAILED"
1289
1291
  }
1290
1292
  /**
1291
1293
  * Platform-specific event type prefix
@@ -1398,6 +1400,17 @@ interface ModelEventPayload extends EventPayload {
1398
1400
  total: number;
1399
1401
  };
1400
1402
  }
1403
+ /**
1404
+ * Payload for embedding generation events
1405
+ */
1406
+ interface EmbeddingGenerationPayload extends EventPayload {
1407
+ memory: Memory;
1408
+ priority?: 'high' | 'normal' | 'low';
1409
+ retryCount?: number;
1410
+ maxRetries?: number;
1411
+ embedding?: number[];
1412
+ error?: any;
1413
+ }
1401
1414
  type MessageReceivedHandlerParams = {
1402
1415
  runtime: IAgentRuntime;
1403
1416
  message: Memory;
@@ -1429,6 +1442,9 @@ interface EventPayloadMap {
1429
1442
  [EventType.EVALUATOR_STARTED]: EvaluatorEventPayload;
1430
1443
  [EventType.EVALUATOR_COMPLETED]: EvaluatorEventPayload;
1431
1444
  [EventType.MODEL_USED]: ModelEventPayload;
1445
+ [EventType.EMBEDDING_GENERATION_REQUESTED]: EmbeddingGenerationPayload;
1446
+ [EventType.EMBEDDING_GENERATION_COMPLETED]: EmbeddingGenerationPayload;
1447
+ [EventType.EMBEDDING_GENERATION_FAILED]: EmbeddingGenerationPayload;
1432
1448
  }
1433
1449
  /**
1434
1450
  * Event handler function type
@@ -1696,6 +1712,7 @@ interface IAgentRuntime extends IDatabaseAdapter {
1696
1712
  getServicesByType<T extends Service>(service: ServiceTypeName | string): T[];
1697
1713
  getAllServices(): Map<ServiceTypeName, Service[]>;
1698
1714
  registerService(service: typeof Service): Promise<void>;
1715
+ getServiceLoadPromise(serviceType: ServiceTypeName): Promise<Service>;
1699
1716
  getRegisteredServiceTypes(): ServiceTypeName[];
1700
1717
  hasService(serviceType: ServiceTypeName | string): boolean;
1701
1718
  registerDatabaseAdapter(adapter: IDatabaseAdapter): void;
@@ -1736,8 +1753,20 @@ interface IAgentRuntime extends IDatabaseAdapter {
1736
1753
  getTaskWorker(name: string): TaskWorker | undefined;
1737
1754
  stop(): Promise<void>;
1738
1755
  addEmbeddingToMemory(memory: Memory): Promise<Memory>;
1756
+ /**
1757
+ * Queue a memory for async embedding generation.
1758
+ * This method is non-blocking and returns immediately.
1759
+ * The embedding will be generated asynchronously via event handlers.
1760
+ * @param memory The memory to generate embeddings for
1761
+ * @param priority Priority level for the embedding generation
1762
+ */
1763
+ queueEmbeddingGeneration(memory: Memory, priority?: 'high' | 'normal' | 'low'): Promise<void>;
1739
1764
  getAllMemories(): Promise<Memory[]>;
1740
1765
  clearAllAgentMemories(): Promise<void>;
1766
+ updateMemory(memory: Partial<Memory> & {
1767
+ id: UUID;
1768
+ metadata?: MemoryMetadata;
1769
+ }): Promise<boolean>;
1741
1770
  createRunId(): UUID;
1742
1771
  startRun(): UUID;
1743
1772
  endRun(): void;
@@ -3539,7 +3568,6 @@ declare const characterSchema: z.ZodObject<{
3539
3568
  channelType: z.ZodOptional<z.ZodString>;
3540
3569
  }, z.ZodTypeAny, "passthrough">>;
3541
3570
  }, "strip", z.ZodTypeAny, {
3542
- name?: string;
3543
3571
  content?: {
3544
3572
  thought?: string;
3545
3573
  text?: string;
@@ -3554,8 +3582,8 @@ declare const characterSchema: z.ZodObject<{
3554
3582
  } & {
3555
3583
  [k: string]: unknown;
3556
3584
  };
3557
- }, {
3558
3585
  name?: string;
3586
+ }, {
3559
3587
  content?: {
3560
3588
  thought?: string;
3561
3589
  text?: string;
@@ -3570,6 +3598,7 @@ declare const characterSchema: z.ZodObject<{
3570
3598
  } & {
3571
3599
  [k: string]: unknown;
3572
3600
  };
3601
+ name?: string;
3573
3602
  }>, "many">, "many">>;
3574
3603
  postExamples: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
3575
3604
  topics: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -3618,13 +3647,12 @@ declare const characterSchema: z.ZodObject<{
3618
3647
  path?: string;
3619
3648
  })[];
3620
3649
  username?: string;
3621
- name?: string;
3622
3650
  id?: string;
3651
+ name?: string;
3623
3652
  system?: string;
3624
3653
  templates?: Record<string, string | ((...args: unknown[]) => unknown)>;
3625
3654
  bio?: string | string[];
3626
3655
  messageExamples?: {
3627
- name?: string;
3628
3656
  content?: {
3629
3657
  thought?: string;
3630
3658
  text?: string;
@@ -3639,6 +3667,7 @@ declare const characterSchema: z.ZodObject<{
3639
3667
  } & {
3640
3668
  [k: string]: unknown;
3641
3669
  };
3670
+ name?: string;
3642
3671
  }[][];
3643
3672
  postExamples?: string[];
3644
3673
  topics?: string[];
@@ -3660,13 +3689,12 @@ declare const characterSchema: z.ZodObject<{
3660
3689
  path?: string;
3661
3690
  })[];
3662
3691
  username?: string;
3663
- name?: string;
3664
3692
  id?: string;
3693
+ name?: string;
3665
3694
  system?: string;
3666
3695
  templates?: Record<string, string | ((...args: unknown[]) => unknown)>;
3667
3696
  bio?: string | string[];
3668
3697
  messageExamples?: {
3669
- name?: string;
3670
3698
  content?: {
3671
3699
  thought?: string;
3672
3700
  text?: string;
@@ -3681,6 +3709,7 @@ declare const characterSchema: z.ZodObject<{
3681
3709
  } & {
3682
3710
  [k: string]: unknown;
3683
3711
  };
3712
+ name?: string;
3684
3713
  }[][];
3685
3714
  postExamples?: string[];
3686
3715
  topics?: string[];
@@ -4271,10 +4300,91 @@ declare function formatEntities({ entities }: {
4271
4300
  entities: Entity[];
4272
4301
  }): string;
4273
4302
 
4274
- declare const createLogger: (bindings?: any | boolean) => pino.Logger<never, boolean>;
4275
- declare let logger: pino.Logger<string, boolean>;
4303
+ /**
4304
+ * Detects the current runtime environment (browser vs Node.js)
4305
+ * Results are cached for performance
4306
+ */
4307
+ declare function getEnvironment(): {
4308
+ isBrowser: boolean;
4309
+ isNode: boolean;
4310
+ };
4311
+ /**
4312
+ * Clears the cached environment detection result
4313
+ * Useful for testing or when environment changes
4314
+ */
4315
+ declare function clearEnvironmentCache(): void;
4316
+ /**
4317
+ * Checks if running in Node.js environment
4318
+ */
4319
+ declare function isNodeEnv(): boolean;
4320
+ /**
4321
+ * Checks if running in browser environment
4322
+ */
4323
+ declare function isBrowserEnv(): boolean;
4324
+ /**
4325
+ * Checks if process object is available
4326
+ */
4327
+ declare function hasProcess(): boolean;
4328
+ /**
4329
+ * Gets an environment variable value if process.env is available
4330
+ */
4331
+ declare function getProcessEnv(key: string): string | undefined;
4332
+ declare const envDetector: {
4333
+ getEnvironment: typeof getEnvironment;
4334
+ clearCache: typeof clearEnvironmentCache;
4335
+ isNode: typeof isNodeEnv;
4336
+ isBrowser: typeof isBrowserEnv;
4337
+ hasProcess: typeof hasProcess;
4338
+ getProcessEnv: typeof getProcessEnv;
4339
+ };
4340
+ type LogFn = (obj: Record<string, unknown> | string | Error, msg?: string, ...args: unknown[]) => void;
4341
+ interface LoggerBindings extends Record<string, unknown> {
4342
+ __forceType?: 'browser' | 'node';
4343
+ level?: string;
4344
+ maxMemoryLogs?: number;
4345
+ }
4346
+ interface Logger {
4347
+ trace: LogFn;
4348
+ debug: LogFn;
4349
+ info: LogFn;
4350
+ warn: LogFn;
4351
+ error: LogFn;
4352
+ fatal: LogFn;
4353
+ success: LogFn;
4354
+ progress: LogFn;
4355
+ log: LogFn;
4356
+ clear: () => void;
4357
+ child: (bindings: Record<string, unknown>) => Logger;
4358
+ level?: string;
4359
+ }
4360
+ /**
4361
+ * Interface representing a log entry.
4362
+ * @property time - The timestamp of the log entry
4363
+ * @property level - The log level as a number or string
4364
+ * @property msg - The log message content
4365
+ * @property diagnostic - Flag indicating if this is a diagnostic log
4366
+ * @property agentName - Name of the agent that created the log
4367
+ * @property agentId - ID of the agent that created the log
4368
+ * @property [key: string] - Additional properties that can be added to the log entry
4369
+ */
4370
+ interface LogEntry {
4371
+ time?: number;
4372
+ level?: number | string;
4373
+ msg?: string;
4374
+ diagnostic?: boolean;
4375
+ agentName?: string;
4376
+ agentId?: string;
4377
+ [key: string]: unknown;
4378
+ }
4379
+ declare function createLogger(bindings?: LoggerBindings | boolean): Logger;
4380
+ interface ElizaLogger extends Logger {
4381
+ success: LogFn;
4382
+ progress: LogFn;
4383
+ log: LogFn;
4384
+ }
4385
+ declare const typedLogger: ElizaLogger;
4276
4386
 
4277
- declare const elizaLogger: pino.Logger<string, boolean>;
4387
+ declare const elizaLogger: ElizaLogger;
4278
4388
 
4279
4389
  declare const shouldRespondTemplate = "<task>Decide on behalf of {{agentName}} whether they should respond to the message, ignore it or stop the conversation.</task>\n\n<providers>\n{{providers}}\n</providers>\n\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.</instructions>\n\n<output>\nDo NOT include any thinking, reasoning, or <think> sections in your response. \nGo directly to the XML response format without any preamble or explanation.\n\nRespond using XML format like this:\n<response>\n <name>{{agentName}}</name>\n <reasoning>Your reasoning here</reasoning>\n <action>RESPOND | IGNORE | STOP</action>\n</response>\n\nIMPORTANT: Your response must ONLY contain the <response></response> XML block above. Do not include any text, thinking, or reasoning before or after this XML block. Start your response immediately with <response> and end with </response>.\n</output>";
4280
4390
  declare const messageHandlerTemplate = "<task>Generate dialog and actions for the character {{agentName}}.</task>\n\n<providers>\n{{providers}}\n</providers>\n\nThese are the available valid actions:\n<actionNames>\n{{actionNames}}\n</actionNames>\n\n<instructions>\nWrite 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.\n\nIMPORTANT ACTION ORDERING RULES:\n- Actions are executed in the ORDER you list them - the order MATTERS!\n- REPLY should come FIRST to acknowledge the user's request before executing other actions\n- Common patterns:\n - For requests requiring tool use: REPLY,CALL_MCP_TOOL (acknowledge first, then gather info)\n - For task execution: REPLY,SEND_MESSAGE or REPLY,EVM_SWAP_TOKENS (acknowledge first, then do the task)\n - For multi-step operations: REPLY,ACTION1,ACTION2 (acknowledge first, then complete all steps)\n- REPLY is used to acknowledge and inform the user about what you're going to do\n- Follow-up actions execute the actual tasks after acknowledgment\n- Use IGNORE only when you should not respond at all\n- If you use IGNORE, do not include any other actions. IGNORE should be used alone when you should not respond or take any actions.\n\nIMPORTANT PROVIDER SELECTION RULES:\n- Only include providers if they are needed to respond accurately.\n- If the message mentions images, photos, pictures, attachments, or visual content, OR if you see \"(Attachments:\" in the conversation, you MUST include \"ATTACHMENTS\" in your providers list\n- If the message asks about or references specific people, include \"ENTITIES\" in your providers list \n- If the message asks about relationships or connections between people, include \"RELATIONSHIPS\" in your providers list\n- If the message asks about facts or specific information, include \"FACTS\" in your providers list\n- If the message asks about the environment or world context, include \"WORLD\" in your providers list\n- If no additional context is needed, you may leave the providers list empty.\n\nIMPORTANT CODE BLOCK FORMATTING RULES:\n- If {{agentName}} includes code examples, snippets, or multi-line code in the response, ALWAYS wrap the code with ``` fenced code blocks (specify the language if known, e.g., ```python).\n- ONLY use fenced code blocks for actual code. Do NOT wrap non-code text, instructions, or single words in fenced code blocks.\n- If including inline code (short single words or function names), use single backticks (`) as appropriate.\n- This ensures the user sees clearly formatted and copyable code when relevant.\n\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</instructions>\n\n<keys>\n\"thought\" should be a short description of what the agent is thinking about and planning.\n\"actions\" should be a comma-separated list of the actions {{agentName}} plans to take based on the thought, IN THE ORDER THEY SHOULD BE EXECUTED (if none, use IGNORE, if simply responding with text, use REPLY)\n\"providers\" should be a comma-separated list of the providers that {{agentName}} will use to have the right context for responding and acting (NEVER use \"IGNORE\" as a provider - use specific provider names like ATTACHMENTS, ENTITIES, FACTS, KNOWLEDGE, etc.)\n\"text\" should be the text of the next message for {{agentName}} which they will send to the conversation.\n</keys>\n\n<output>\nDo NOT include any thinking, reasoning, or <think> sections in your response. \nGo directly to the XML response format without any preamble or explanation.\n\nRespond using XML format like this:\n<response>\n <thought>Your thought here</thought>\n <actions>ACTION1,ACTION2</actions>\n <providers>PROVIDER1,PROVIDER2</providers>\n <text>Your response text here</text>\n</response>\n\nIMPORTANT: Your response must ONLY contain the <response></response> XML block above. Do not include any text, thinking, or reasoning before or after this XML block. Start your response immediately with <response> and end with </response>.\n</output>";
@@ -4351,6 +4461,8 @@ declare class AgentRuntime implements IAgentRuntime {
4351
4461
  logger: any;
4352
4462
  private settings;
4353
4463
  private servicesInitQueue;
4464
+ private servicePromiseHandles;
4465
+ private servicePromises;
4354
4466
  private currentRunId?;
4355
4467
  private currentActionContext?;
4356
4468
  private maxWorkingMemoryEntries;
@@ -4454,6 +4566,8 @@ declare class AgentRuntime implements IAgentRuntime {
4454
4566
  */
4455
4567
  hasService(serviceType: ServiceTypeName | string): boolean;
4456
4568
  registerService(serviceDef: typeof Service): Promise<void>;
4569
+ private _createServiceResolver;
4570
+ getServiceLoadPromise(serviceType: ServiceTypeName): Promise<Service>;
4457
4571
  registerModel(modelType: ModelTypeName, handler: (params: any) => Promise<any>, provider: string, priority?: number): void;
4458
4572
  getModel(modelType: ModelTypeName, provider?: string): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined;
4459
4573
  /**
@@ -4497,6 +4611,7 @@ declare class AgentRuntime implements IAgentRuntime {
4497
4611
  updateComponent(component: Component): Promise<void>;
4498
4612
  deleteComponent(componentId: UUID): Promise<void>;
4499
4613
  addEmbeddingToMemory(memory: Memory): Promise<Memory>;
4614
+ queueEmbeddingGeneration(memory: Memory, priority?: 'high' | 'normal' | 'low'): Promise<void>;
4500
4615
  getMemories(params: {
4501
4616
  entityId?: UUID;
4502
4617
  agentId?: UUID;
@@ -4768,4 +4883,4 @@ interface ServiceDefinition<T extends Service = Service> {
4768
4883
  */
4769
4884
  declare function defineService<T extends Service = Service>(definition: ServiceDefinition<T>): new (runtime?: IAgentRuntime) => T;
4770
4885
 
4771
- export { type Action, type ActionContext, type ActionEventPayload, type ActionExample, type ActionResult, type Agent, AgentRuntime, AgentStatus, type AudioProcessingParams, type BaseMetadata, type BaseModelParams, type BrowserNavigationOptions, CacheKeyPrefix, type ChannelClearedPayload, ChannelType, type Character, type CharacterValidationResult, type ChunkRow, type ClickOptions, type Component, type Content, ContentType, type ControlMessage, type CustomMetadata, DatabaseAdapter, type DbConnection, type DeriveKeyAttestationData, type DescriptionMetadata, type DetokenizeTextParams, type DirectoryItem, type DocumentMetadata, type ElementSelector, type EmailAccount, type EmailAddress, type EmailAttachment, type EmailFolder, type EmailMessage, type EmailSearchOptions, type EmailSendOptions, type EmbeddingSearchResult, type EnhancedState, type Entity, type EntityPayload, type EvaluationExample, type Evaluator, type EvaluatorEventPayload, type EventHandler, type EventPayload, type EventPayloadMap, EventType, type ExtractedContent, type FragmentMetadata, type GenerateTextParams, type Handler, type HandlerCallback, type IAgentRuntime, IBrowserService, type IDatabaseAdapter, IEmailService, ILpService, IMessageService, IPdfService, IPostService, ITokenDataService, ITranscriptionService, IVideoService, IWalletService, IWebSearchService, type ImageDescriptionParams, type ImageGenerationParams, type ImageSearchOptions, type InvokePayload, type IsValidServiceType, type JSONSchema, type KnowledgeItem, KnowledgeScope, type Log, type LpPositionDetails, MODEL_SETTINGS, type Media, type Memory, type MemoryMetadata, type MemoryRetrievalOptions, type MemoryScope, type MemorySearchOptions, MemoryType, type MemoryTypeAlias, type MessageAttachment, type MessageChannel, type MessageContent, type MessageExample, type MessageInfo, type MessageMemory, type MessageMetadata, type MessageParticipant, type MessagePayload, type MessageReaction, type MessageReceivedHandlerParams, type MessageReference, type MessageSearchOptions, type MessageSendOptions, type Metadata, type ModelEventPayload, type ModelHandler, type ModelParamsMap, type ModelResultMap, ModelType, type ModelTypeName, type MultiRoomMemoryOptions, type NewsSearchOptions, type ObjectGenerationParams, type OnboardingConfig, type Participant, type PdfConversionOptions, type PdfExtractionResult, type PdfGenerationOptions, PlatformPrefix, type Plugin, type PluginEvents, type PoolInfo, type PostAnalytics, type PostAuthor, type PostContent, type PostCreateOptions, type PostEngagement, type PostInfo, type PostLocation, type PostMedia, type PostSearchOptions, type Project, type ProjectAgent, type Provider, type ProviderResult, type Relationship, type RemoteAttestationMessage, type RemoteAttestationQuote, Role, type Room, type RoomMetadata, type Route, type RunEventPayload, type RuntimeSettings, SOCKET_MESSAGE_TYPE, type ScreenshotOptions, type SearchOptions, type SearchResponse, type SearchResult, Semaphore, type SendHandlerFunction, type ServerOwnershipState, Service, ServiceBuilder, type ServiceClassMap, type ServiceDefinition, type ServiceError, type ServiceInstance, type ServiceRegistry, ServiceType, type ServiceTypeName, type ServiceTypeRegistry, type ServiceTypeValue, type Setting, type SpeechToTextOptions, type State, type StateArray, type StateObject, type StateValue, TEEMode, type TargetInfo, type Task, type TaskMetadata, type TaskWorker, type TeeAgent, type TeePluginConfig, TeeType, type TemplateType, type TestCase, type TestSuite, type TextEmbeddingParams, type TextGenerationParams, type TextToSpeechOptions, type TextToSpeechParams, type TokenBalance, type TokenData, type TokenizeTextParams, type TransactionResult, type TranscriptionOptions, type TranscriptionParams, type TranscriptionResult, type TranscriptionSegment, type TranscriptionWord, type TypeOptions, type TypedEventHandler, type TypedService, type TypedServiceClass, type UUID, type UnifiedMemoryOptions, type UnifiedSearchOptions, VECTOR_DIMS, type Validator, type VideoDownloadOptions, type VideoFormat, type VideoInfo, type VideoProcessingOptions, type VideoProcessingParams, type VideoSearchOptions, type WalletAsset, type WalletPortfolio, type World, type WorldPayload, type WorldSettings, addHeader, asUUID, booleanFooter, characterSchema, composeActionExamples, composePrompt, composePromptFromState, createActionResult, createLogger, createMessageMemory, createService, createServiceError, createSettingFromConfig, createUniqueUuid, decryptObjectValues, decryptStringValue as decryptSecret, decryptStringValue, decryptedCharacter, defineService, elizaLogger, encryptObjectValues, encryptStringValue, encryptedCharacter, findEntityByName, findWorldsForOwner, formatActionNames, formatActions, formatEntities, formatMessages, formatPosts, formatTimestamp, getContentTypeFromMimeType, getEntityDetails, getLocalServerUrl, getMemoryText, getModelSpecificSettingKey, getSalt, getTypedService, getUserServerRole, getWorldSettings, imageDescriptionTemplate, initializeOnboarding, isCustomMetadata, isDescriptionMetadata, isDocumentMemory, isDocumentMetadata, isFragmentMemory, isFragmentMetadata, isMessageMetadata, isValidCharacter, logger, messageHandlerTemplate, normalizeJsonString, parseAndValidateCharacter, parseBooleanFromText, parseJSONObjectFromText, parseKeyValueXml, postCreationTemplate, safeReplacer, saltSettingValue, saltWorldSettings, shouldRespondTemplate, splitChunks, stringToUuid, trimTokens, truncateToCompleteSentence, unsaltSettingValue, unsaltWorldSettings, updateWorldSettings, validateCharacter, validateUuid };
4886
+ export { type Action, type ActionContext, type ActionEventPayload, type ActionExample, type ActionResult, type Agent, AgentRuntime, AgentStatus, type AudioProcessingParams, type BaseMetadata, type BaseModelParams, type BrowserNavigationOptions, CacheKeyPrefix, type ChannelClearedPayload, ChannelType, type Character, type CharacterValidationResult, type ChunkRow, type ClickOptions, type Component, type Content, ContentType, type ControlMessage, type CustomMetadata, DatabaseAdapter, type DbConnection, type DeriveKeyAttestationData, type DescriptionMetadata, type DetokenizeTextParams, type DirectoryItem, type DocumentMetadata, type ElementSelector, type ElizaLogger, type EmailAccount, type EmailAddress, type EmailAttachment, type EmailFolder, type EmailMessage, type EmailSearchOptions, type EmailSendOptions, type EmbeddingGenerationPayload, type EmbeddingSearchResult, type EnhancedState, type Entity, type EntityPayload, type EvaluationExample, type Evaluator, type EvaluatorEventPayload, type EventHandler, type EventPayload, type EventPayloadMap, EventType, type ExtractedContent, type FragmentMetadata, type GenerateTextParams, type Handler, type HandlerCallback, type IAgentRuntime, IBrowserService, type IDatabaseAdapter, IEmailService, ILpService, IMessageService, IPdfService, IPostService, ITokenDataService, ITranscriptionService, IVideoService, IWalletService, IWebSearchService, type ImageDescriptionParams, type ImageGenerationParams, type ImageSearchOptions, type InvokePayload, type IsValidServiceType, type JSONSchema, type KnowledgeItem, KnowledgeScope, type Log, type LogEntry, type Logger, type LoggerBindings, type LpPositionDetails, MODEL_SETTINGS, type Media, type Memory, type MemoryMetadata, type MemoryRetrievalOptions, type MemoryScope, type MemorySearchOptions, MemoryType, type MemoryTypeAlias, type MessageAttachment, type MessageChannel, type MessageContent, type MessageExample, type MessageInfo, type MessageMemory, type MessageMetadata, type MessageParticipant, type MessagePayload, type MessageReaction, type MessageReceivedHandlerParams, type MessageReference, type MessageSearchOptions, type MessageSendOptions, type Metadata, type ModelEventPayload, type ModelHandler, type ModelParamsMap, type ModelResultMap, ModelType, type ModelTypeName, type MultiRoomMemoryOptions, type NewsSearchOptions, type ObjectGenerationParams, type OnboardingConfig, type Participant, type PdfConversionOptions, type PdfExtractionResult, type PdfGenerationOptions, PlatformPrefix, type Plugin, type PluginEvents, type PoolInfo, type PostAnalytics, type PostAuthor, type PostContent, type PostCreateOptions, type PostEngagement, type PostInfo, type PostLocation, type PostMedia, type PostSearchOptions, type Project, type ProjectAgent, type Provider, type ProviderResult, type Relationship, type RemoteAttestationMessage, type RemoteAttestationQuote, Role, type Room, type RoomMetadata, type Route, type RunEventPayload, type RuntimeSettings, SOCKET_MESSAGE_TYPE, type ScreenshotOptions, type SearchOptions, type SearchResponse, type SearchResult, Semaphore, type SendHandlerFunction, type ServerOwnershipState, Service, ServiceBuilder, type ServiceClassMap, type ServiceDefinition, type ServiceError, type ServiceInstance, type ServiceRegistry, ServiceType, type ServiceTypeName, type ServiceTypeRegistry, type ServiceTypeValue, type Setting, type SpeechToTextOptions, type State, type StateArray, type StateObject, type StateValue, TEEMode, type TargetInfo, type Task, type TaskMetadata, type TaskWorker, type TeeAgent, type TeePluginConfig, TeeType, type TemplateType, type TestCase, type TestSuite, type TextEmbeddingParams, type TextGenerationParams, type TextToSpeechOptions, type TextToSpeechParams, type TokenBalance, type TokenData, type TokenizeTextParams, type TransactionResult, type TranscriptionOptions, type TranscriptionParams, type TranscriptionResult, type TranscriptionSegment, type TranscriptionWord, type TypeOptions, type TypedEventHandler, type TypedService, type TypedServiceClass, type UUID, type UnifiedMemoryOptions, type UnifiedSearchOptions, VECTOR_DIMS, type Validator, type VideoDownloadOptions, type VideoFormat, type VideoInfo, type VideoProcessingOptions, type VideoProcessingParams, type VideoSearchOptions, type WalletAsset, type WalletPortfolio, type World, type WorldPayload, type WorldSettings, addHeader, asUUID, booleanFooter, characterSchema, composeActionExamples, composePrompt, composePromptFromState, createActionResult, createLogger, createMessageMemory, createService, createServiceError, createSettingFromConfig, createUniqueUuid, decryptObjectValues, decryptStringValue as decryptSecret, decryptStringValue, decryptedCharacter, defineService, elizaLogger, encryptObjectValues, encryptStringValue, encryptedCharacter, envDetector, findEntityByName, findWorldsForOwner, formatActionNames, formatActions, formatEntities, formatMessages, formatPosts, formatTimestamp, getContentTypeFromMimeType, getEntityDetails, getLocalServerUrl, getMemoryText, getModelSpecificSettingKey, getSalt, getTypedService, getUserServerRole, getWorldSettings, imageDescriptionTemplate, initializeOnboarding, isCustomMetadata, isDescriptionMetadata, isDocumentMemory, isDocumentMetadata, isFragmentMemory, isFragmentMetadata, isMessageMetadata, isValidCharacter, typedLogger as logger, messageHandlerTemplate, normalizeJsonString, parseAndValidateCharacter, parseBooleanFromText, parseJSONObjectFromText, parseKeyValueXml, postCreationTemplate, safeReplacer, saltSettingValue, saltWorldSettings, shouldRespondTemplate, splitChunks, stringToUuid, trimTokens, truncateToCompleteSentence, unsaltSettingValue, unsaltWorldSettings, updateWorldSettings, validateCharacter, validateUuid };
package/dist/index.js CHANGED
@@ -266,6 +266,9 @@ var EventType = /* @__PURE__ */ ((EventType2) => {
266
266
  EventType2["EVALUATOR_STARTED"] = "EVALUATOR_STARTED";
267
267
  EventType2["EVALUATOR_COMPLETED"] = "EVALUATOR_COMPLETED";
268
268
  EventType2["MODEL_USED"] = "MODEL_USED";
269
+ EventType2["EMBEDDING_GENERATION_REQUESTED"] = "EMBEDDING_GENERATION_REQUESTED";
270
+ EventType2["EMBEDDING_GENERATION_COMPLETED"] = "EMBEDDING_GENERATION_COMPLETED";
271
+ EventType2["EMBEDDING_GENERATION_FAILED"] = "EMBEDDING_GENERATION_FAILED";
269
272
  return EventType2;
270
273
  })(EventType || {});
271
274
  var PlatformPrefix = /* @__PURE__ */ ((PlatformPrefix2) => {
@@ -430,9 +433,6 @@ import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
430
433
  import { names, uniqueNamesGenerator } from "unique-names-generator";
431
434
  import { z } from "zod";
432
435
 
433
- // src/logger.ts
434
- import pino from "pino";
435
-
436
436
  // src/sentry/instrument.ts
437
437
  import * as Sentry from "@sentry/browser";
438
438
  var dsn = process.env.SENTRY_DSN || "https://c20e2d51b66c14a783b0689d536f7e5c@o4509349865259008.ingest.us.sentry.io/4509352524120064";
@@ -448,28 +448,115 @@ if (process.env.SENTRY_LOGGING !== "false") {
448
448
  }
449
449
 
450
450
  // src/logger.ts
451
+ var cachedEnvironment = null;
452
+ function getEnvironment() {
453
+ if (cachedEnvironment !== null) {
454
+ return cachedEnvironment;
455
+ }
456
+ const isBrowser = typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
457
+ const isNode = typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined";
458
+ cachedEnvironment = { isBrowser, isNode };
459
+ return cachedEnvironment;
460
+ }
461
+ function clearEnvironmentCache() {
462
+ cachedEnvironment = null;
463
+ }
464
+ function isNodeEnv() {
465
+ return getEnvironment().isNode;
466
+ }
467
+ function isBrowserEnv() {
468
+ return getEnvironment().isBrowser;
469
+ }
470
+ function hasProcess() {
471
+ return typeof process !== "undefined";
472
+ }
473
+ function getProcessEnv(key) {
474
+ if (hasProcess() && process.env) {
475
+ return process.env[key];
476
+ }
477
+ return void 0;
478
+ }
479
+ var envDetector = {
480
+ getEnvironment,
481
+ clearCache: clearEnvironmentCache,
482
+ isNode: isNodeEnv,
483
+ isBrowser: isBrowserEnv,
484
+ hasProcess,
485
+ getProcessEnv
486
+ };
451
487
  function parseBooleanFromText(value) {
452
488
  if (!value) return false;
453
489
  const normalized = value.toLowerCase().trim();
454
490
  return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on";
455
491
  }
456
- var InMemoryDestination = class {
457
- /**
458
- * Constructor for creating a new instance of the class.
459
- * @param {DestinationStream|null} stream - The stream to assign to the instance. Can be null.
460
- */
461
- constructor(stream) {
462
- this.logs = [];
463
- this.maxLogs = 1e3;
464
- this.stream = stream;
492
+ function getConsole() {
493
+ if (typeof globalThis !== "undefined" && globalThis.console) {
494
+ return globalThis.console;
465
495
  }
466
- /**
467
- * Writes a log entry to the memory buffer and forwards it to the pretty print stream if available.
468
- *
469
- * @param {string | LogEntry} data - The data to be written, which can be either a string or a LogEntry object.
470
- * @returns {void}
471
- */
472
- write(data) {
496
+ if (typeof console !== "undefined") {
497
+ return console;
498
+ }
499
+ return null;
500
+ }
501
+ function safeStringify(obj) {
502
+ const seen = /* @__PURE__ */ new WeakSet();
503
+ try {
504
+ return JSON.stringify(obj, (_key, value) => {
505
+ if (typeof value === "object" && value !== null) {
506
+ if (seen.has(value)) {
507
+ return "[Circular]";
508
+ }
509
+ seen.add(value);
510
+ }
511
+ return value;
512
+ });
513
+ } catch (error) {
514
+ return String(obj);
515
+ }
516
+ }
517
+ var moduleCache = {};
518
+ function loadPinoSync() {
519
+ if (moduleCache.pino) {
520
+ return moduleCache.pino;
521
+ }
522
+ try {
523
+ const module = __require("pino");
524
+ moduleCache.pino = module;
525
+ return module;
526
+ } catch (error) {
527
+ throw new Error(`Failed to load Pino: ${error.message}`);
528
+ }
529
+ }
530
+ function loadPinoPrettySync() {
531
+ if (moduleCache.pinoPretty) {
532
+ return moduleCache.pinoPretty;
533
+ }
534
+ try {
535
+ const module = __require("pino-pretty");
536
+ moduleCache.pinoPretty = module;
537
+ return module;
538
+ } catch (error) {
539
+ return null;
540
+ }
541
+ }
542
+ var PINO_DESTINATION_SYMBOL = Symbol.for("pino-destination");
543
+ var DEFAULT_MAX_MEMORY_LOGS = 1e3;
544
+ var getMaxMemoryLogs = () => {
545
+ if (envDetector.hasProcess()) {
546
+ const envValue = envDetector.getProcessEnv("LOG_MAX_MEMORY_SIZE");
547
+ if (envValue) {
548
+ const parsed = parseInt(envValue, 10);
549
+ if (!isNaN(parsed) && parsed > 0) {
550
+ return parsed;
551
+ }
552
+ }
553
+ }
554
+ return DEFAULT_MAX_MEMORY_LOGS;
555
+ };
556
+ function createInMemoryDestination(stream, maxLogs) {
557
+ let logs = [];
558
+ const maxLogsLimit = maxLogs ?? getMaxMemoryLogs();
559
+ const write = (data) => {
473
560
  let logEntry;
474
561
  let stringData;
475
562
  if (typeof data === "string") {
@@ -477,20 +564,20 @@ var InMemoryDestination = class {
477
564
  try {
478
565
  logEntry = JSON.parse(data);
479
566
  } catch (e) {
480
- if (this.stream) {
481
- this.stream.write(data);
567
+ if (stream) {
568
+ stream.write(data);
482
569
  }
483
570
  return;
484
571
  }
485
572
  } else {
486
573
  logEntry = data;
487
- stringData = JSON.stringify(data);
574
+ stringData = safeStringify(data);
488
575
  }
489
576
  if (!logEntry.time) {
490
577
  logEntry.time = Date.now();
491
578
  }
492
- const isDebugMode2 = (process?.env?.LOG_LEVEL || "").toLowerCase() === "debug";
493
- const isLoggingDiagnostic = Boolean(process?.env?.LOG_DIAGNOSTIC);
579
+ const isDebugMode2 = envDetector.hasProcess() && (envDetector.getProcessEnv("LOG_LEVEL") || "").toLowerCase() === "debug";
580
+ const isLoggingDiagnostic = envDetector.hasProcess() && Boolean(envDetector.getProcessEnv("LOG_DIAGNOSTIC"));
494
581
  if (isLoggingDiagnostic) {
495
582
  logEntry.diagnostic = true;
496
583
  }
@@ -499,37 +586,162 @@ var InMemoryDestination = class {
499
586
  const msg = logEntry.msg || "";
500
587
  if (typeof msg === "string" && (msg.includes("registered successfully") || msg.includes("Registering") || msg.includes("Success:") || msg.includes("linked to") || msg.includes("Started"))) {
501
588
  if (isLoggingDiagnostic) {
502
- console.error("Filtered log:", stringData);
589
+ const consoleObj = getConsole();
590
+ if (consoleObj && consoleObj.error) {
591
+ consoleObj.error("Filtered log:", stringData);
592
+ }
503
593
  }
504
594
  return;
505
595
  }
506
596
  }
507
597
  }
508
- this.logs.push(logEntry);
509
- if (this.logs.length > this.maxLogs) {
510
- this.logs.shift();
598
+ logs.push(logEntry);
599
+ if (logs.length > maxLogsLimit) {
600
+ logs.shift();
511
601
  }
512
- if (this.stream) {
513
- this.stream.write(stringData);
602
+ if (stream) {
603
+ stream.write(stringData);
514
604
  }
515
- }
516
- /**
517
- * Retrieves the recent logs from the system.
518
- *
519
- * @returns {LogEntry[]} An array of LogEntry objects representing the recent logs.
520
- */
521
- recentLogs() {
522
- return this.logs;
523
- }
524
- /**
525
- * Clears all logs from memory.
526
- *
527
- * @returns {void}
528
- */
529
- clear() {
530
- this.logs = [];
531
- }
605
+ };
606
+ const recentLogs = () => logs;
607
+ const clear = () => {
608
+ logs = [];
609
+ };
610
+ return {
611
+ write,
612
+ recentLogs,
613
+ clear
614
+ };
615
+ }
616
+ var levelValues = {
617
+ fatal: 60,
618
+ error: 50,
619
+ warn: 40,
620
+ info: 30,
621
+ log: 29,
622
+ progress: 28,
623
+ success: 27,
624
+ debug: 20,
625
+ trace: 10
532
626
  };
627
+ function createBrowserLogger(options2 = {}) {
628
+ const inMemoryDestination = createInMemoryDestination(null, options2.maxMemoryLogs);
629
+ const level = options2.level || "info";
630
+ const currentLevel = levelValues[level] || 30;
631
+ const bindings = options2.base || {};
632
+ const shouldLog = (logLevel) => {
633
+ const levelValue = levelValues[logLevel] || 30;
634
+ return levelValue >= currentLevel;
635
+ };
636
+ const getConsoleMethod = (logLevel) => {
637
+ const consoleObj = getConsole();
638
+ if (!consoleObj) {
639
+ return () => {
640
+ };
641
+ }
642
+ const fallback = consoleObj.log ? consoleObj.log.bind(consoleObj) : () => {
643
+ };
644
+ switch (logLevel) {
645
+ case "trace":
646
+ case "debug":
647
+ return consoleObj.debug ? consoleObj.debug.bind(consoleObj) : fallback;
648
+ case "info":
649
+ case "log":
650
+ case "progress":
651
+ case "success":
652
+ return consoleObj.info ? consoleObj.info.bind(consoleObj) : fallback;
653
+ case "warn":
654
+ return consoleObj.warn ? consoleObj.warn.bind(consoleObj) : fallback;
655
+ case "error":
656
+ case "fatal":
657
+ return consoleObj.error ? consoleObj.error.bind(consoleObj) : fallback;
658
+ default:
659
+ return fallback;
660
+ }
661
+ };
662
+ const formatMessage = (logLevel, obj, msg, ...args) => {
663
+ if (!shouldLog(logLevel)) return;
664
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
665
+ const levelLabel = logLevel.toUpperCase();
666
+ const logEntry = {
667
+ time: Date.now(),
668
+ level: levelValues[logLevel],
669
+ msg: "",
670
+ ...bindings
671
+ };
672
+ let messageStr = "";
673
+ let contextObj = {};
674
+ if (typeof obj === "string") {
675
+ messageStr = obj;
676
+ if (msg) {
677
+ messageStr += " " + msg;
678
+ }
679
+ if (args.length > 0) {
680
+ messageStr += " " + args.map((a) => typeof a === "object" ? safeStringify(a) : String(a)).join(" ");
681
+ }
682
+ } else if (obj instanceof Error) {
683
+ contextObj = { error: { message: obj.message, stack: obj.stack } };
684
+ messageStr = msg || obj.message;
685
+ } else if (typeof obj === "object" && obj !== null) {
686
+ contextObj = obj;
687
+ messageStr = msg || "";
688
+ if (args.length > 0) {
689
+ messageStr += " " + args.map((a) => typeof a === "object" ? safeStringify(a) : String(a)).join(" ");
690
+ }
691
+ }
692
+ Object.assign(logEntry, contextObj);
693
+ logEntry.msg = messageStr;
694
+ inMemoryDestination.write(logEntry);
695
+ const prefix = `[${timestamp}] ${levelLabel}:`;
696
+ const hasContext = Object.keys(contextObj).length > 0;
697
+ const consoleMethod = getConsoleMethod(logLevel);
698
+ if (hasContext) {
699
+ if (messageStr) {
700
+ consoleMethod(prefix, messageStr, contextObj);
701
+ } else {
702
+ consoleMethod(prefix, contextObj);
703
+ }
704
+ } else if (messageStr) {
705
+ consoleMethod(prefix, messageStr);
706
+ }
707
+ if (envDetector.hasProcess() && envDetector.getProcessEnv("SENTRY_LOGGING") !== "false") {
708
+ if (obj instanceof Error || logLevel === "error" || logLevel === "fatal") {
709
+ const error = obj instanceof Error ? obj : new Error(messageStr);
710
+ Sentry.captureException(error);
711
+ }
712
+ }
713
+ };
714
+ const createLogMethod = (level2) => (obj, msg, ...args) => {
715
+ formatMessage(level2, obj, msg, ...args);
716
+ };
717
+ const clear = () => {
718
+ inMemoryDestination.clear();
719
+ const consoleObj = getConsole();
720
+ if (consoleObj && consoleObj.clear) {
721
+ consoleObj.clear();
722
+ }
723
+ };
724
+ const child = (childBindings) => {
725
+ return createBrowserLogger({
726
+ level,
727
+ base: { ...bindings, ...childBindings }
728
+ });
729
+ };
730
+ return {
731
+ level,
732
+ trace: createLogMethod("trace"),
733
+ debug: createLogMethod("debug"),
734
+ info: createLogMethod("info"),
735
+ warn: createLogMethod("warn"),
736
+ error: createLogMethod("error"),
737
+ fatal: createLogMethod("fatal"),
738
+ success: createLogMethod("success"),
739
+ progress: createLogMethod("progress"),
740
+ log: createLogMethod("log"),
741
+ clear,
742
+ child
743
+ };
744
+ }
533
745
  var customLevels = {
534
746
  fatal: 60,
535
747
  error: 50,
@@ -541,10 +753,28 @@ var customLevels = {
541
753
  debug: 20,
542
754
  trace: 10
543
755
  };
544
- var raw = parseBooleanFromText(process?.env?.LOG_JSON_FORMAT) || false;
545
- var isDebugMode = (process?.env?.LOG_LEVEL || "").toLowerCase() === "debug";
546
- var effectiveLogLevel = isDebugMode ? "debug" : process?.env?.DEFAULT_LOG_LEVEL || "info";
547
- var showTimestamps = process?.env?.LOG_TIMESTAMPS !== void 0 ? parseBooleanFromText(process?.env?.LOG_TIMESTAMPS) : true;
756
+ var raw = envDetector.hasProcess() ? parseBooleanFromText(envDetector.getProcessEnv("LOG_JSON_FORMAT")) || false : false;
757
+ var isDebugMode = envDetector.hasProcess() ? (envDetector.getProcessEnv("LOG_LEVEL") || "").toLowerCase() === "debug" : false;
758
+ var effectiveLogLevel = isDebugMode ? "debug" : (envDetector.hasProcess() ? envDetector.getProcessEnv("DEFAULT_LOG_LEVEL") : null) || "info";
759
+ var showTimestamps = envDetector.hasProcess() && envDetector.getProcessEnv("LOG_TIMESTAMPS") !== void 0 ? parseBooleanFromText(envDetector.getProcessEnv("LOG_TIMESTAMPS")) : true;
760
+ function extractBindingsConfig(bindings) {
761
+ let level = effectiveLogLevel;
762
+ let base = {};
763
+ let forceType;
764
+ let maxMemoryLogs;
765
+ if (typeof bindings === "object" && bindings !== null) {
766
+ forceType = bindings.__forceType;
767
+ if ("level" in bindings) {
768
+ level = bindings.level;
769
+ }
770
+ if ("maxMemoryLogs" in bindings && typeof bindings.maxMemoryLogs === "number") {
771
+ maxMemoryLogs = bindings.maxMemoryLogs;
772
+ }
773
+ const { level: _, __forceType: __, maxMemoryLogs: ___, ...rest } = bindings;
774
+ base = rest;
775
+ }
776
+ return { level, base, forceType, maxMemoryLogs };
777
+ }
548
778
  var createPrettyConfig = () => ({
549
779
  colorize: true,
550
780
  translateTime: showTimestamps ? "yyyy-mm-dd HH:MM:ss" : false,
@@ -575,7 +805,8 @@ var createPrettyConfig = () => ({
575
805
  level: (inputData) => {
576
806
  let level;
577
807
  if (typeof inputData === "object" && inputData !== null) {
578
- level = inputData.level || inputData.value;
808
+ const data = inputData;
809
+ level = data.level || data.value;
579
810
  } else {
580
811
  level = inputData;
581
812
  }
@@ -605,21 +836,14 @@ var createPrettyConfig = () => ({
605
836
  },
606
837
  messageFormat: "{msg}"
607
838
  });
608
- var createStream = async () => {
609
- if (raw) {
610
- return void 0;
611
- }
612
- const pretty = await import("pino-pretty");
613
- return pretty.default(createPrettyConfig());
614
- };
615
839
  var options = {
616
840
  level: effectiveLogLevel,
617
841
  // Use more restrictive level unless in debug mode
618
842
  customLevels,
619
843
  hooks: {
620
- logMethod(inputArgs, method) {
844
+ logMethod: function(inputArgs, method) {
621
845
  const [arg1, ...rest] = inputArgs;
622
- if (process.env.SENTRY_LOGGING !== "false") {
846
+ if (envDetector.hasProcess() && envDetector.getProcessEnv("SENTRY_LOGGING") !== "false") {
623
847
  if (arg1 instanceof Error) {
624
848
  Sentry.captureException(arg1);
625
849
  } else {
@@ -636,17 +860,15 @@ var options = {
636
860
  });
637
861
  if (typeof arg1 === "object") {
638
862
  if (arg1 instanceof Error) {
639
- method.apply(this, [
640
- {
641
- error: formatError(arg1)
642
- }
643
- ]);
863
+ method.call(this, {
864
+ error: formatError(arg1)
865
+ });
644
866
  } else {
645
867
  const messageParts = rest.map(
646
- (arg) => typeof arg === "string" ? arg : JSON.stringify(arg)
868
+ (arg) => typeof arg === "string" ? arg : safeStringify(arg)
647
869
  );
648
870
  const message = messageParts.join(" ");
649
- method.apply(this, [arg1, message]);
871
+ method.call(this, arg1, message);
650
872
  }
651
873
  } else {
652
874
  const context = {};
@@ -659,63 +881,69 @@ var options = {
659
881
  const message = messageParts.filter((part) => typeof part === "string").join(" ");
660
882
  const jsonParts = messageParts.filter((part) => typeof part === "object");
661
883
  Object.assign(context, ...jsonParts);
662
- method.apply(this, [context, message]);
884
+ method.call(this, context, message);
663
885
  }
664
886
  }
665
887
  }
666
888
  };
667
- var createLogger = (bindings = false) => {
668
- const opts = { ...options };
669
- if (bindings) {
670
- opts.base = bindings;
671
- opts.transport = {
672
- target: "pino-pretty",
673
- // this is just a string, not a dynamic import
674
- options: {
675
- colorize: true,
676
- translateTime: showTimestamps ? "SYS:standard" : false,
677
- ignore: showTimestamps ? "pid,hostname" : "pid,hostname,time"
678
- }
679
- };
680
- }
681
- const logger2 = pino(opts);
682
- return logger2;
683
- };
684
- var logger = pino(options);
685
- if (typeof process !== "undefined") {
686
- let stream = null;
687
- if (!raw) {
889
+ function createLogger(bindings = false) {
890
+ const { level, base, forceType, maxMemoryLogs } = extractBindingsConfig(bindings);
891
+ if (forceType === "browser") {
892
+ const opts2 = { level, base };
893
+ return createBrowserLogger(opts2);
894
+ }
895
+ const { isBrowser, isNode } = getEnvironment();
896
+ if (isBrowser) {
897
+ const opts2 = { level, base };
898
+ return createBrowserLogger(opts2);
899
+ }
900
+ if (isNode) {
688
901
  try {
689
- const pretty = __require("pino-pretty");
690
- stream = pretty.default ? pretty.default(createPrettyConfig()) : null;
691
- } catch (e) {
692
- createStream().then((prettyStream) => {
693
- const destination = new InMemoryDestination(prettyStream);
694
- logger = pino(options, destination);
695
- logger[Symbol.for("pino-destination")] = destination;
696
- logger.clear = () => {
697
- const destination2 = logger[Symbol.for("pino-destination")];
698
- if (destination2 instanceof InMemoryDestination) {
699
- destination2.clear();
700
- }
701
- };
702
- });
703
- }
704
- }
705
- if (stream !== null || raw) {
706
- const destination = new InMemoryDestination(stream);
707
- logger = pino(options, destination);
708
- logger[Symbol.for("pino-destination")] = destination;
709
- logger.clear = () => {
710
- const destination2 = logger[Symbol.for("pino-destination")];
711
- if (destination2 instanceof InMemoryDestination) {
712
- destination2.clear();
902
+ const Pino = loadPinoSync();
903
+ const opts2 = { ...options };
904
+ opts2.base = base;
905
+ let stream = null;
906
+ if (!raw) {
907
+ const pretty = loadPinoPrettySync();
908
+ if (pretty) {
909
+ stream = pretty(createPrettyConfig());
910
+ }
713
911
  }
714
- };
912
+ const destination = createInMemoryDestination(stream, maxMemoryLogs);
913
+ const pinoLogger = Pino(opts2, destination);
914
+ pinoLogger[PINO_DESTINATION_SYMBOL] = destination;
915
+ pinoLogger.clear = () => {
916
+ const dest = pinoLogger[PINO_DESTINATION_SYMBOL];
917
+ if (dest && typeof dest.clear === "function") {
918
+ dest.clear();
919
+ }
920
+ };
921
+ if (!pinoLogger.success) {
922
+ pinoLogger.success = pinoLogger.info.bind(pinoLogger);
923
+ }
924
+ if (!pinoLogger.progress) {
925
+ pinoLogger.progress = pinoLogger.info.bind(pinoLogger);
926
+ }
927
+ if (!pinoLogger.log) {
928
+ pinoLogger.log = pinoLogger.info.bind(pinoLogger);
929
+ }
930
+ return pinoLogger;
931
+ } catch (error) {
932
+ const consoleObj = getConsole();
933
+ if (consoleObj && consoleObj.warn) {
934
+ consoleObj.warn("Pino not available, falling back to BrowserLogger:", error);
935
+ }
936
+ const opts2 = { level, base };
937
+ return createBrowserLogger(opts2);
938
+ }
715
939
  }
940
+ const opts = { level, base };
941
+ return createBrowserLogger(opts);
716
942
  }
717
- var elizaLogger = logger;
718
- var logger_default = logger;
943
+ var logger = createLogger(false);
944
+ var typedLogger = logger;
945
+ var elizaLogger = typedLogger;
946
+ var logger_default = typedLogger;
719
947
 
720
948
  // src/utils.ts
721
949
  function upgradeDoubleToTriple(tpl) {
@@ -1414,7 +1642,7 @@ async function getRecentInteractions(runtime, sourceEntityId, candidateEntities,
1414
1642
  async function findEntityByName(runtime, message, state) {
1415
1643
  const room = state.data.room ?? await runtime.getRoom(message.roomId);
1416
1644
  if (!room) {
1417
- logger.warn("Room not found for entity search");
1645
+ typedLogger.warn("Room not found for entity search");
1418
1646
  return null;
1419
1647
  }
1420
1648
  const world = room.worldId ? await runtime.getWorld(room.worldId) : null;
@@ -1471,7 +1699,7 @@ async function findEntityByName(runtime, message, state) {
1471
1699
  });
1472
1700
  const resolution = parseKeyValueXml(result);
1473
1701
  if (!resolution) {
1474
- logger.warn("Failed to parse entity resolution result");
1702
+ typedLogger.warn("Failed to parse entity resolution result");
1475
1703
  return null;
1476
1704
  }
1477
1705
  if (resolution.type === "EXACT_MATCH" && resolution.entityId) {
@@ -1749,12 +1977,12 @@ async function getUserServerRole(runtime, entityId, serverId) {
1749
1977
  }
1750
1978
  async function findWorldsForOwner(runtime, entityId) {
1751
1979
  if (!entityId) {
1752
- logger.error("User ID is required to find server");
1980
+ typedLogger.error("User ID is required to find server");
1753
1981
  return null;
1754
1982
  }
1755
1983
  const worlds = await runtime.getAllWorlds();
1756
1984
  if (!worlds || worlds.length === 0) {
1757
- logger.info("No worlds found for this agent");
1985
+ typedLogger.info("No worlds found for this agent");
1758
1986
  return null;
1759
1987
  }
1760
1988
  const ownerWorlds = [];
@@ -2821,6 +3049,9 @@ var AgentRuntime = class {
2821
3049
  // The initial list of plugins specified by the character configuration.
2822
3050
  this.characterPlugins = [];
2823
3051
  this.servicesInitQueue = /* @__PURE__ */ new Set();
3052
+ this.servicePromiseHandles = /* @__PURE__ */ new Map();
3053
+ // write
3054
+ this.servicePromises = /* @__PURE__ */ new Map();
2824
3055
  this.maxWorkingMemoryEntries = 50;
2825
3056
  this.agentId = opts.character?.id ?? opts?.agentId ?? stringToUuid(opts.character?.name ?? uuidv4() + opts.character?.username);
2826
3057
  this.character = opts.character;
@@ -2958,6 +3189,9 @@ var AgentRuntime = class {
2958
3189
  }
2959
3190
  if (plugin.services) {
2960
3191
  for (const service of plugin.services) {
3192
+ if (!this.servicePromises.has(service.serviceType)) {
3193
+ this._createServiceResolver(service.serviceType);
3194
+ }
2961
3195
  if (this.isInitialized) {
2962
3196
  await this.registerService(service);
2963
3197
  } else {
@@ -3136,18 +3370,19 @@ var AgentRuntime = class {
3136
3370
  this.logger.debug(`Success: Provider ${provider.name} registered successfully.`);
3137
3371
  }
3138
3372
  registerAction(action) {
3139
- this.logger.debug(
3140
- `${this.character.name}(${this.agentId}) - Registering action: ${action.name}`
3141
- );
3142
3373
  if (this.actions.find((a) => a.name === action.name)) {
3143
3374
  this.logger.warn(
3144
3375
  `${this.character.name}(${this.agentId}) - Action ${action.name} already exists. Skipping registration.`
3145
3376
  );
3146
3377
  } else {
3147
- this.actions.push(action);
3148
- this.logger.debug(
3149
- `${this.character.name}(${this.agentId}) - Action ${action.name} registered successfully.`
3150
- );
3378
+ try {
3379
+ this.actions.push(action);
3380
+ this.logger.success(
3381
+ `${this.character.name}(${this.agentId}) - Action ${action.name} registered successfully.`
3382
+ );
3383
+ } catch (e) {
3384
+ console.error("Error registering action", e);
3385
+ }
3151
3386
  }
3152
3387
  }
3153
3388
  registerEvaluator(evaluator) {
@@ -3630,7 +3865,10 @@ var AgentRuntime = class {
3630
3865
  "connections in",
3631
3866
  firstRoom.id
3632
3867
  );
3633
- await this.addParticipantsRoom(missingIdsInRoom, firstRoom.id);
3868
+ const batches = chunkArray(missingIdsInRoom, 5e3);
3869
+ for (const batch of batches) {
3870
+ await this.addParticipantsRoom(batch, firstRoom.id);
3871
+ }
3634
3872
  }
3635
3873
  this.logger.success(`Success: Successfully connected world`);
3636
3874
  }
@@ -3965,6 +4203,14 @@ var AgentRuntime = class {
3965
4203
  }
3966
4204
  this.services.get(serviceType).push(serviceInstance);
3967
4205
  this.serviceTypes.get(serviceType).push(serviceDef);
4206
+ const resolve = this.servicePromiseHandles.get(serviceType);
4207
+ if (resolve) {
4208
+ resolve(serviceInstance);
4209
+ } else {
4210
+ this.logger.debug(
4211
+ `${this.character.name} - Service ${serviceType} has no servicePromiseHandle`
4212
+ );
4213
+ }
3968
4214
  if (typeof serviceDef.registerSendHandlers === "function") {
3969
4215
  serviceDef.registerSendHandlers(this, serviceInstance);
3970
4216
  }
@@ -3979,6 +4225,29 @@ var AgentRuntime = class {
3979
4225
  throw error;
3980
4226
  }
3981
4227
  }
4228
+ /// ensures servicePromises & servicePromiseHandles for a serviceType
4229
+ _createServiceResolver(serviceType) {
4230
+ let resolver;
4231
+ this.servicePromises.set(
4232
+ serviceType,
4233
+ new Promise((resolve) => {
4234
+ resolver = resolve;
4235
+ })
4236
+ );
4237
+ if (!resolver) {
4238
+ throw new Error(`Failed to create resolver for service ${serviceType}`);
4239
+ }
4240
+ this.servicePromiseHandles.set(serviceType, resolver);
4241
+ return this.servicePromises.get(serviceType);
4242
+ }
4243
+ /// returns a promise that's resolved once this service is loaded
4244
+ getServiceLoadPromise(serviceType) {
4245
+ let p = this.servicePromises.get(serviceType);
4246
+ if (!p) {
4247
+ p = this._createServiceResolver(serviceType);
4248
+ }
4249
+ return p;
4250
+ }
3982
4251
  registerModel(modelType, handler, provider, priority) {
3983
4252
  const modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
3984
4253
  if (!this.models.has(modelKey)) {
@@ -4338,6 +4607,26 @@ var AgentRuntime = class {
4338
4607
  }
4339
4608
  return memory;
4340
4609
  }
4610
+ async queueEmbeddingGeneration(memory, priority = "normal") {
4611
+ if (!memory) {
4612
+ return;
4613
+ }
4614
+ if (memory.embedding) {
4615
+ return;
4616
+ }
4617
+ if (!memory.content?.text) {
4618
+ this.logger.debug("Skipping embedding generation for memory without text content");
4619
+ return;
4620
+ }
4621
+ await this.emitEvent("EMBEDDING_GENERATION_REQUESTED" /* EMBEDDING_GENERATION_REQUESTED */, {
4622
+ runtime: this,
4623
+ memory,
4624
+ priority,
4625
+ source: "runtime",
4626
+ retryCount: 0,
4627
+ maxRetries: 3
4628
+ });
4629
+ }
4341
4630
  async getMemories(params) {
4342
4631
  return await this.adapter.getMemories(params);
4343
4632
  }
@@ -4640,23 +4929,22 @@ function createSettingFromConfig(configSetting) {
4640
4929
  function getSalt() {
4641
4930
  const secretSalt = (typeof process !== "undefined" ? process.env.SECRET_SALT : import.meta.env.SECRET_SALT) || "secretsalt";
4642
4931
  if (!secretSalt) {
4643
- logger.error("SECRET_SALT is not set");
4932
+ typedLogger.error("SECRET_SALT is not set");
4644
4933
  }
4645
4934
  const salt = secretSalt;
4646
- logger.debug(`Generated salt with length: ${salt.length} (truncated for security)`);
4647
4935
  return salt;
4648
4936
  }
4649
4937
  function encryptStringValue(value, salt) {
4650
4938
  if (value === void 0 || value === null) {
4651
- logger.debug("Attempted to encrypt undefined or null value");
4939
+ typedLogger.debug("Attempted to encrypt undefined or null value");
4652
4940
  return value;
4653
4941
  }
4654
4942
  if (typeof value === "boolean" || typeof value === "number") {
4655
- logger.debug("Value is a boolean or number, returning as is");
4943
+ typedLogger.debug("Value is a boolean or number, returning as is");
4656
4944
  return value;
4657
4945
  }
4658
4946
  if (typeof value !== "string") {
4659
- logger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
4947
+ typedLogger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
4660
4948
  return value;
4661
4949
  }
4662
4950
  const parts = value.split(":");
@@ -4664,7 +4952,7 @@ function encryptStringValue(value, salt) {
4664
4952
  try {
4665
4953
  const possibleIv = Buffer.from(parts[0], "hex");
4666
4954
  if (possibleIv.length === 16) {
4667
- logger.debug("Value appears to be already encrypted, skipping re-encryption");
4955
+ typedLogger.debug("Value appears to be already encrypted, skipping re-encryption");
4668
4956
  return value;
4669
4957
  }
4670
4958
  } catch (e) {
@@ -4686,7 +4974,7 @@ function decryptStringValue(value, salt) {
4686
4974
  return value;
4687
4975
  }
4688
4976
  if (typeof value !== "string") {
4689
- logger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
4977
+ typedLogger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
4690
4978
  return value;
4691
4979
  }
4692
4980
  const parts = value.split(":");
@@ -4697,7 +4985,7 @@ function decryptStringValue(value, salt) {
4697
4985
  const encrypted = parts[1];
4698
4986
  if (iv.length !== 16) {
4699
4987
  if (iv.length) {
4700
- logger.debug(`Invalid IV length (${iv.length}) - expected 16 bytes`);
4988
+ typedLogger.debug(`Invalid IV length (${iv.length}) - expected 16 bytes`);
4701
4989
  }
4702
4990
  return value;
4703
4991
  }
@@ -4707,7 +4995,7 @@ function decryptStringValue(value, salt) {
4707
4995
  decrypted += decipher.final("utf8");
4708
4996
  return decrypted;
4709
4997
  } catch (error) {
4710
- logger.error(`Error decrypting value: ${error}`);
4998
+ typedLogger.error(`Error decrypting value: ${error}`);
4711
4999
  return value;
4712
5000
  }
4713
5001
  }
@@ -4743,7 +5031,7 @@ async function updateWorldSettings(runtime, serverId, worldSettings) {
4743
5031
  const worldId = createUniqueUuid(runtime, serverId);
4744
5032
  const world = await runtime.getWorld(worldId);
4745
5033
  if (!world) {
4746
- logger.error(`No world found for server ${serverId}`);
5034
+ typedLogger.error(`No world found for server ${serverId}`);
4747
5035
  return false;
4748
5036
  }
4749
5037
  if (!world.metadata) {
@@ -4767,7 +5055,7 @@ async function getWorldSettings(runtime, serverId) {
4767
5055
  }
4768
5056
  async function initializeOnboarding(runtime, world, config) {
4769
5057
  if (world.metadata?.settings) {
4770
- logger.info(`Onboarding state already exists for server ${world.serverId}`);
5058
+ typedLogger.info(`Onboarding state already exists for server ${world.serverId}`);
4771
5059
  const saltedSettings = world.metadata.settings;
4772
5060
  const salt = getSalt();
4773
5061
  return unsaltWorldSettings(saltedSettings, salt);
@@ -4783,7 +5071,7 @@ async function initializeOnboarding(runtime, world, config) {
4783
5071
  }
4784
5072
  world.metadata.settings = worldSettings;
4785
5073
  await runtime.updateWorld(world);
4786
- logger.info(`Initialized settings config for server ${world.serverId}`);
5074
+ typedLogger.info(`Initialized settings config for server ${world.serverId}`);
4787
5075
  return worldSettings;
4788
5076
  }
4789
5077
  function encryptedCharacter(character) {
@@ -4951,6 +5239,7 @@ export {
4951
5239
  encryptObjectValues,
4952
5240
  encryptStringValue,
4953
5241
  encryptedCharacter,
5242
+ envDetector,
4954
5243
  findEntityByName,
4955
5244
  findWorldsForOwner,
4956
5245
  formatActionNames,
@@ -4978,7 +5267,7 @@ export {
4978
5267
  isFragmentMetadata,
4979
5268
  isMessageMetadata,
4980
5269
  isValidCharacter,
4981
- logger,
5270
+ typedLogger as logger,
4982
5271
  messageHandlerTemplate,
4983
5272
  normalizeJsonString,
4984
5273
  parseAndValidateCharacter,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elizaos/core",
3
- "version": "1.4.2",
3
+ "version": "1.4.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -63,5 +63,5 @@
63
63
  "publishConfig": {
64
64
  "access": "public"
65
65
  },
66
- "gitHead": "f60dd270910361decc4d4e879e8b2f33c5ddfee2"
66
+ "gitHead": "670462dd40d05b9b364e9db6eadfff8403f18fdc"
67
67
  }