@elizaos/core 1.0.0-beta.5 → 1.0.0-beta.50

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 (52) hide show
  1. package/LICENSE +1 -1
  2. package/dist/database.d.ts +27 -9
  3. package/dist/index.d.ts +4 -3
  4. package/dist/index.js +9315 -7008
  5. package/dist/instrumentation/index.d.ts +2 -0
  6. package/dist/instrumentation/service.d.ts +21 -0
  7. package/dist/instrumentation/types.d.ts +16 -0
  8. package/dist/prompts.d.ts +3 -200
  9. package/dist/roles.d.ts +5 -1
  10. package/dist/runtime.d.ts +94 -43
  11. package/dist/search.d.ts +316 -0
  12. package/dist/settings.d.ts +79 -1
  13. package/dist/types.d.ts +502 -78
  14. package/dist/utils.d.ts +240 -0
  15. package/package.json +11 -3
  16. package/dist/actions/choice.d.ts +0 -13
  17. package/dist/actions/followRoom.d.ts +0 -20
  18. package/dist/actions/ignore.d.ts +0 -13
  19. package/dist/actions/muteRoom.d.ts +0 -22
  20. package/dist/actions/none.d.ts +0 -9
  21. package/dist/actions/reply.d.ts +0 -15
  22. package/dist/actions/roles.d.ts +0 -13
  23. package/dist/actions/sendMessage.d.ts +0 -14
  24. package/dist/actions/settings.d.ts +0 -21
  25. package/dist/actions/unfollowRoom.d.ts +0 -12
  26. package/dist/actions/unmuteRoom.d.ts +0 -18
  27. package/dist/actions/updateEntity.d.ts +0 -42
  28. package/dist/bootstrap.d.ts +0 -14
  29. package/dist/evaluators/reflection.d.ts +0 -2
  30. package/dist/import.d.ts +0 -9
  31. package/dist/providers/actions.d.ts +0 -14
  32. package/dist/providers/anxiety.d.ts +0 -9
  33. package/dist/providers/attachments.d.ts +0 -8
  34. package/dist/providers/capabilities.d.ts +0 -13
  35. package/dist/providers/character.d.ts +0 -9
  36. package/dist/providers/choice.d.ts +0 -10
  37. package/dist/providers/entities.d.ts +0 -2
  38. package/dist/providers/evaluators.d.ts +0 -26
  39. package/dist/providers/facts.d.ts +0 -10
  40. package/dist/providers/knowledge.d.ts +0 -13
  41. package/dist/providers/providers.d.ts +0 -6
  42. package/dist/providers/recentMessages.d.ts +0 -13
  43. package/dist/providers/relationships.d.ts +0 -14
  44. package/dist/providers/roles.d.ts +0 -14
  45. package/dist/providers/settings.d.ts +0 -6
  46. package/dist/providers/shouldRespond.d.ts +0 -6
  47. package/dist/providers/time.d.ts +0 -11
  48. package/dist/services/index.d.ts +0 -1
  49. package/dist/services/scenario.d.ts +0 -106
  50. package/dist/services/task.d.ts +0 -72
  51. package/dist/services/websocket.d.ts +0 -73
  52. package/dist/uuid.d.ts +0 -18
@@ -0,0 +1,2 @@
1
+ export * from './types';
2
+ export * from './service';
@@ -0,0 +1,21 @@
1
+ import { Tracer, Meter } from '@opentelemetry/api';
2
+ import { IInstrumentationService, InstrumentationConfig } from './types';
3
+ import { Service, IAgentRuntime } from '../types';
4
+ export declare class InstrumentationService extends Service implements IInstrumentationService {
5
+ readonly name = "INSTRUMENTATION";
6
+ readonly capabilityDescription = "Provides OpenTelemetry tracing and metrics capabilities.";
7
+ instrumentationConfig: InstrumentationConfig;
8
+ private resource;
9
+ private tracerProvider;
10
+ private meterProvider;
11
+ private postgresSpanProcessor;
12
+ private isShutdown;
13
+ constructor(config?: InstrumentationConfig);
14
+ private initializeProviders;
15
+ isEnabled(): boolean;
16
+ getTracer(name?: string, version?: string): Tracer | null;
17
+ getMeter(name?: string, version?: string): Meter | null;
18
+ flush(): Promise<void>;
19
+ stop(): Promise<void>;
20
+ static start(runtime: IAgentRuntime, config?: InstrumentationConfig): Promise<InstrumentationService>;
21
+ }
@@ -0,0 +1,16 @@
1
+ import { Tracer, Meter } from '@opentelemetry/api';
2
+ export interface InstrumentationConfig {
3
+ serviceName?: string;
4
+ otlpEndpoint?: string;
5
+ enabled?: boolean;
6
+ }
7
+ export interface IInstrumentationService {
8
+ readonly name: string;
9
+ readonly capabilityDescription: string;
10
+ instrumentationConfig: InstrumentationConfig;
11
+ isEnabled(): boolean;
12
+ getTracer(name?: string, version?: string): Tracer | null;
13
+ getMeter(name?: string, version?: string): Meter | null;
14
+ flush(): Promise<void>;
15
+ stop(): Promise<void>;
16
+ }
package/dist/prompts.d.ts CHANGED
@@ -1,201 +1,4 @@
1
- import type { Entity, IAgentRuntime, Memory, State, TemplateType } from './types';
2
- /**
3
- * Composes a context string by replacing placeholders in a template with corresponding values from the state.
4
- *
5
- * This function takes a template string with placeholders in the format `{{placeholder}}` and a state object.
6
- * It replaces each placeholder with the value from the state object that matches the placeholder's name.
7
- * If a matching key is not found in the state object for a given placeholder, the placeholder is replaced with an empty string.
8
- *
9
- * @param {Object} params - The parameters for composing the context.
10
- * @param {State} params.state - The state object containing values to replace the placeholders in the template.
11
- * @param {TemplateType} params.template - The template string or function containing placeholders to be replaced with state values.
12
- * @returns {string} The composed context string with placeholders replaced by corresponding state values.
13
- *
14
- * @example
15
- * // Given a state object and a template
16
- * const state = { userName: "Alice", userAge: 30 };
17
- * const template = "Hello, {{userName}}! You are {{userAge}} years old";
18
- *
19
- * // Composing the context with simple string replacement will result in:
20
- * // "Hello, Alice! You are 30 years old."
21
- * const contextSimple = composePromptFromState({ state, template });
22
- *
23
- * // Using composePromptFromState with a template function for dynamic template
24
- * const template = ({ state }) => {
25
- * const tone = Math.random() > 0.5 ? "kind" : "rude";
26
- * return `Hello, {{userName}}! You are {{userAge}} years old. Be ${tone}`;
27
- * };
28
- * const contextSimple = composePromptFromState({ state, template });
29
- */
30
- /**
31
- * Function to compose a prompt using a provided template and state.
32
- *
33
- * @param {Object} options - Object containing state and template information.
34
- * @param {State} options.state - The state object containing values to fill the template.
35
- * @param {TemplateType} options.template - The template to be used for composing the prompt.
36
- * @returns {string} The composed prompt output.
37
- */
38
- export declare const composePrompt: ({ state, template, }: {
39
- state: {
40
- [key: string]: string;
41
- };
42
- template: TemplateType;
43
- }) => string;
44
- /**
45
- * Function to compose a prompt using a provided template and state.
46
- *
47
- * @param {Object} options - Object containing state and template information.
48
- * @param {State} options.state - The state object containing values to fill the template.
49
- * @param {TemplateType} options.template - The template to be used for composing the prompt.
50
- * @returns {string} The composed prompt output.
51
- */
52
- export declare const composePromptFromState: ({ state, template, }: {
53
- state: State;
54
- template: TemplateType;
55
- }) => string;
56
- /**
57
- * Adds a header to a body of text.
58
- *
59
- * This function takes a header string and a body string and returns a new string with the header prepended to the body.
60
- * If the body string is empty, the header is returned as is.
61
- *
62
- * @param {string} header - The header to add to the body.
63
- * @param {string} body - The body to which to add the header.
64
- * @returns {string} The body with the header prepended.
65
- *
66
- * @example
67
- * // Given a header and a body
68
- * const header = "Header";
69
- * const body = "Body";
70
- *
71
- * // Adding the header to the body will result in:
72
- * // "Header\nBody"
73
- * const text = addHeader(header, body);
74
- */
75
- export declare const addHeader: (header: string, body: string) => string;
76
- /**
77
- * Generates a string with random user names populated in a template.
78
- *
79
- * This function generates random user names and populates placeholders
80
- * in the provided template with these names. Placeholders in the template should follow the format `{{userX}}`
81
- * where `X` is the position of the user (e.g., `{{name1}}`, `{{name2}}`).
82
- *
83
- * @param {string} template - The template string containing placeholders for random user names.
84
- * @param {number} length - The number of random user names to generate.
85
- * @returns {string} The template string with placeholders replaced by random user names.
86
- *
87
- * @example
88
- * // Given a template and a length
89
- * const template = "Hello, {{name1}}! Meet {{name2}} and {{name3}}.";
90
- * const length = 3;
91
- *
92
- * // Composing the random user string will result in:
93
- * // "Hello, John! Meet Alice and Bob."
94
- * const result = composeRandomUser(template, length);
95
- */
96
- export declare const composeRandomUser: (template: string, length: number) => string;
97
- export declare const formatPosts: ({ messages, entities, conversationHeader, }: {
98
- messages: Memory[];
99
- entities: Entity[];
100
- conversationHeader?: boolean;
101
- }) => string;
102
- /**
103
- * Format messages into a string
104
- * @param {Object} params - The formatting parameters
105
- * @param {Memory[]} params.messages - List of messages to format
106
- * @param {Entity[]} params.entities - List of entities for name resolution
107
- * @returns {string} Formatted message string with timestamps and user information
108
- */
109
- export declare const formatMessages: ({ messages, entities, }: {
110
- messages: Memory[];
111
- entities: Entity[];
112
- }) => string;
113
- export declare const formatTimestamp: (messageDate: number) => string;
114
- export declare 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.";
115
- export declare 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\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 \"actions\": [\"<string>\", \"<string>\", ...],\n \"providers\": [\"<string>\", \"<string>\", ...]\n}\n```\n\nYour response should include the valid JSON block and nothing else.";
116
- export declare const postCreationTemplate = "# Task: Create a post in the voice and style and perspective of {{agentName}} @{{twitterUserName}}.\n\nExample task outputs:\n1. A post about the importance of AI in our lives\n```json\n{ \"thought\": \"I am thinking about writing a post about the importance of AI in our lives\", \"post\": \"AI is changing the world and it is important to understand how it works\", \"imagePrompt\": \"A futuristic cityscape with flying cars and people using AI to do things\" }\n```\n\n2. A post about dogs\n```json\n{ \"thought\": \"I am thinking about writing a post about dogs\", \"post\": \"Dogs are man's best friend and they are loyal and loving\", \"imagePrompt\": \"A dog playing with a ball in a park\" }\n```\n\n3. A post about finding a new job\n```json\n{ \"thought\": \"Getting a job is hard, I bet there's a good tweet in that\", \"post\": \"Just keep going!\", \"imagePrompt\": \"A person looking at a computer screen with a job search website\" }\n```\n\n{{providers}}\n\nWrite a post that is {{adjective}} about {{topic}} (without mentioning {{topic}} directly), from the perspective of {{agentName}}. Do not add commentary or acknowledge this request, just write the post.\nYour response should be 1, 2, or 3 sentences (choose the length at random).\nYour response should not contain any questions. Brief, concise statements only. The total character count MUST be less than 280. No emojis. Use \\n\\n (double spaces) between statements if there are multiple statements in your response.\n\nYour output should be formatted in a valid JSON block like this:\n```json\n{ \"thought\": \"<string>\", \"post\": \"<string>\", \"imagePrompt\": \"<string>\" }\n```\nThe \"post\" field should be the post you want to send. Do not including any thinking or internal reflection in the \"post\" field.\nThe \"imagePrompt\" field is optional and should be a prompt for an image that is relevant to the post. It should be a single sentence that captures the essence of the post. ONLY USE THIS FIELD if it makes sense that the post would benefit from an image.\nThe \"thought\" field should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response. Includate an explanation how the post is relevant to the topic but unique and different than other posts.\nYour reponse should ONLY contain a valid JSON block and nothing else.";
1
+ export 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>\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\nYour response should ONLY include the <response></response> XML block.\n</output>";
2
+ export 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.\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 (if none, use IGNORE, if simply responding with text, use REPLY)\n\"providers\" should be an optional comma-separated list of the providers that {{agentName}} will use to have the right context for responding and acting\n\"evaluators\" should be an optional comma-separated list of the evaluators that {{agentName}} will use to evaluate the conversation after responding\n\"text\" should be the text of the next message for {{agentName}} which they will send to the conversation.\n\"simple\" should be true if the message is a simple response and false if it is a more complex response that requires planning, knowledge or more context to handle or reply to.\n</keys>\n\n<output>\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 <simple>true|false</simple>\n</response>\n\nYour response must ONLY include the <response></response> XML block.\n</output>";
3
+ export declare const postCreationTemplate = "# Task: Create a post in the voice and style and perspective of {{agentName}} @{{twitterUserName}}.\n\nExample task outputs:\n1. A post about the importance of AI in our lives\n<response>\n <thought>I am thinking about writing a post about the importance of AI in our lives</thought>\n <post>AI is changing the world and it is important to understand how it works</post>\n <imagePrompt>A futuristic cityscape with flying cars and people using AI to do things</imagePrompt>\n</response>\n\n2. A post about dogs\n<response>\n <thought>I am thinking about writing a post about dogs</thought>\n <post>Dogs are man's best friend and they are loyal and loving</post>\n <imagePrompt>A dog playing with a ball in a park</imagePrompt>\n</response>\n\n3. A post about finding a new job\n<response>\n <thought>Getting a job is hard, I bet there's a good tweet in that</thought>\n <post>Just keep going!</post>\n <imagePrompt>A person looking at a computer screen with a job search website</imagePrompt>\n</response>\n\n{{providers}}\n\nWrite a post that is {{adjective}} about {{topic}} (without mentioning {{topic}} directly), from the perspective of {{agentName}}. Do not add commentary or acknowledge this request, just write the post.\nYour response should be 1, 2, or 3 sentences (choose the length at random).\nYour response should not contain any questions. Brief, concise statements only. The total character count MUST be less than 280. No emojis. Use \\n\\n (double spaces) between statements if there are multiple statements in your response.\n\nYour output should be formatted in XML like this:\n<response>\n <thought>Your thought here</thought>\n <post>Your post text here</post>\n <imagePrompt>Optional image prompt here</imagePrompt>\n</response>\n\nThe \"post\" field should be the post you want to send. Do not including any thinking or internal reflection in the \"post\" field.\nThe \"imagePrompt\" field is optional and should be a prompt for an image that is relevant to the post. It should be a single sentence that captures the essence of the post. ONLY USE THIS FIELD if it makes sense that the post would benefit from an image.\nThe \"thought\" field should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response. Includate an explanation how the post is relevant to the topic but unique and different than other posts.\nYour reponse should ONLY contain the XML block.";
117
4
  export declare const booleanFooter = "Respond with only a YES or a NO.";
118
- /**
119
- * Parses a string to determine its boolean equivalent.
120
- *
121
- * Recognized affirmative values: "YES", "Y", "TRUE", "T", "1", "ON", "ENABLE"
122
- * Recognized negative values: "NO", "N", "FALSE", "F", "0", "OFF", "DISABLE"
123
- *
124
- * @param {string | undefined | null} value - The input text to parse
125
- * @returns {boolean} - Returns `true` for affirmative inputs, `false` for negative or unrecognized inputs
126
- */
127
- export declare function parseBooleanFromText(value: string | undefined | null): boolean;
128
- export declare 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.";
129
- /**
130
- * Parses a JSON array from a given text. The function looks for a JSON block wrapped in triple backticks
131
- * with `json` language identifier, and if not found, it searches for an array pattern within the text.
132
- * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result
133
- * is an array, it returns the array; otherwise, it returns null.
134
- *
135
- * @param text - The input text from which to extract and parse the JSON array.
136
- * @returns An array parsed from the JSON string if successful; otherwise, null.
137
- */
138
- export declare function parseJsonArrayFromText(text: string): any[];
139
- /**
140
- * Parses a JSON object from a given text. The function looks for a JSON block wrapped in triple backticks
141
- * with `json` language identifier, and if not found, it searches for an object pattern within the text.
142
- * It then attempts to parse the JSON string into a JavaScript object. If parsing is successful and the result
143
- * is an object (but not an array), it returns the object; otherwise, it tries to parse an array if the result
144
- * is an array, or returns null if parsing is unsuccessful or the result is neither an object nor an array.
145
- *
146
- * @param text - The input text from which to extract and parse the JSON object.
147
- * @returns An object parsed from the JSON string if successful; otherwise, null or the result of parsing an array.
148
- */
149
- export declare function parseJSONObjectFromText(text: string): Record<string, any> | null;
150
- /**
151
- * Extracts specific attributes (e.g., user, text, action) from a JSON-like string using regex.
152
- * @param response - The cleaned string response to extract attributes from.
153
- * @param attributesToExtract - An array of attribute names to extract.
154
- * @returns An object containing the extracted attributes.
155
- */
156
- export declare function extractAttributes(response: string, attributesToExtract?: string[]): {
157
- [key: string]: string | undefined;
158
- };
159
- /**
160
- * Normalizes a JSON-like string by correcting formatting issues:
161
- * - Removes extra spaces after '{' and before '}'.
162
- * - Wraps unquoted values in double quotes.
163
- * - Converts single-quoted values to double-quoted.
164
- * - Ensures consistency in key-value formatting.
165
- * - Normalizes mixed adjacent quote pairs.
166
- *
167
- * This is useful for cleaning up improperly formatted JSON strings
168
- * before parsing them into valid JSON.
169
- *
170
- * @param str - The JSON-like string to normalize.
171
- * @returns A properly formatted JSON string.
172
- */
173
- export declare const normalizeJsonString: (str: string) => string;
174
- /**
175
- * Cleans a JSON-like response string by removing unnecessary markers, line breaks, and extra whitespace.
176
- * This is useful for handling improperly formatted JSON responses from external sources.
177
- *
178
- * @param response - The raw JSON-like string response to clean.
179
- * @returns The cleaned string, ready for parsing or further processing.
180
- */
181
- export declare function cleanJsonResponse(response: string): string;
182
- export declare const postActionResponseFooter = "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.";
183
- type ActionResponse = {
184
- like: boolean;
185
- retweet: boolean;
186
- quote?: boolean;
187
- reply?: boolean;
188
- };
189
- export declare const parseActionResponseFromText: (text: string) => {
190
- actions: ActionResponse;
191
- };
192
- /**
193
- * Truncate text to fit within the character limit, ensuring it ends at a complete sentence.
194
- */
195
- export declare function truncateToCompleteSentence(text: string, maxLength: number): string;
196
- export declare function splitChunks(content: string, chunkSize?: number, bleed?: number): Promise<string[]>;
197
- /**
198
- * Trims the provided text prompt to a specified token limit using a tokenizer model and type.
199
- */
200
- export declare function trimTokens(prompt: string, maxTokens: number, runtime: IAgentRuntime): Promise<string>;
201
- export {};
package/dist/roles.d.ts CHANGED
@@ -2,6 +2,10 @@ import { type IAgentRuntime, Role, type World } from './types';
2
2
  /**
3
3
  * Represents the state of server ownership, including a mapping of server IDs to their respective World objects.
4
4
  */
5
+ /**
6
+ * Interface representing the ownership state of servers.
7
+ * @property {Object.<string, World>} servers - The servers and their corresponding worlds, where the key is the server ID and the value is the World object.
8
+ */
5
9
  export interface ServerOwnershipState {
6
10
  servers: {
7
11
  [serverId: string]: World;
@@ -22,4 +26,4 @@ export declare function getUserServerRole(runtime: IAgentRuntime, entityId: stri
22
26
  /**
23
27
  * Finds a server where the given user is the owner
24
28
  */
25
- export declare function findWorldForOwner(runtime: IAgentRuntime, entityId: string): Promise<World | null>;
29
+ export declare function findWorldsForOwner(runtime: IAgentRuntime, entityId: string): Promise<World[] | null>;
package/dist/runtime.d.ts CHANGED
@@ -1,17 +1,9 @@
1
- import { ChannelType } from './types';
2
- import type { Action, Agent, Character, Component, Entity, Evaluator, HandlerCallback, IAgentRuntime, IDatabaseAdapter, KnowledgeItem, Log, Memory, MemoryMetadata, ModelParamsMap, ModelResultMap, ModelTypeName, Participant, Plugin, Provider, Relationship, Room, Route, Service, ServiceTypeName, State, Task, TaskWorker, UUID, World } from './types';
3
- /**
4
- * Interface for settings object with key-value pairs.
5
- */
6
- interface Settings {
7
- [key: string]: string | undefined;
8
- }
9
- /**
10
- * Loads environment variables from the nearest .env file in Node.js
11
- * or returns configured settings in browser
12
- * @returns {Settings} Environment variables object
13
- */
14
- export declare function loadEnvConfig(): Settings;
1
+ import { type Context, type Span } from '@opentelemetry/api';
2
+ import { InstrumentationService } from './instrumentation/service';
3
+ import { ChannelType, type Content } from './types';
4
+ import type { Action, Agent, Character, Component, Entity, Evaluator, HandlerCallback, IAgentRuntime, IDatabaseAdapter, KnowledgeItem, Log, Memory, MemoryMetadata, ModelParamsMap, ModelResultMap, ModelTypeName, Participant, Plugin, Provider, Relationship, Room, Route, RuntimeSettings, Service, ServiceTypeName, State, Task, TaskWorker, UUID, World, TargetInfo, SendHandlerFunction, ModelHandler } from './types';
5
+ import { PGlite } from '@electric-sql/pglite';
6
+ import { Pool } from 'pg';
15
7
  export declare class Semaphore {
16
8
  private permits;
17
9
  private waiting;
@@ -20,21 +12,11 @@ export declare class Semaphore {
20
12
  release(): void;
21
13
  }
22
14
  /**
23
- * Represents the runtime environment for an agent, handling message processing,
24
- * action registration, and interaction with external services like OpenAI and Supabase.
25
- */
26
- /**
27
- * Represents the runtime environment for an agent.
28
- * @class
29
- * @implements { IAgentRuntime }
30
- * @property { number } #conversationLength - The maximum length of a conversation.
31
- * @property { UUID } agentId - The unique identifier for the agent.
32
- * @property { Character } character - The character associated with the agent.
33
- * @property { IDatabaseAdapter } adapter - The adapter for interacting with the database.
34
- * @property {Action[]} actions - The list of actions available to the agent.
35
- * @property {Evaluator[]} evaluators - The list of evaluators for decision making.
36
- * @property {Provider[]} providers - The list of providers for external services.
37
- * @property {Plugin[]} plugins - The list of plugins to extend functionality.
15
+ * AgentRuntime provides the core runtime environment and lifecycle management for agents.
16
+ *
17
+ * Implements the IAgentRuntime interface, managing agent state, actions, plugins, providers, and database interaction.
18
+ *
19
+ * implements IAgentRuntime
38
20
  */
39
21
  export declare class AgentRuntime implements IAgentRuntime {
40
22
  #private;
@@ -45,6 +27,7 @@ export declare class AgentRuntime implements IAgentRuntime {
45
27
  readonly evaluators: Evaluator[];
46
28
  readonly providers: Provider[];
47
29
  readonly plugins: Plugin[];
30
+ private isInitialized;
48
31
  events: Map<string, ((params: any) => Promise<void>)[]>;
49
32
  stateCache: Map<`${string}-${string}-${string}-${string}-${string}`, {
50
33
  values: {
@@ -57,13 +40,17 @@ export declare class AgentRuntime implements IAgentRuntime {
57
40
  }>;
58
41
  readonly fetch: typeof fetch;
59
42
  services: Map<ServiceTypeName, Service>;
60
- models: Map<string, ((runtime: IAgentRuntime, params: any) => Promise<any>)[]>;
43
+ models: Map<string, ModelHandler[]>;
61
44
  routes: Route[];
62
45
  private taskWorkers;
46
+ private sendHandlers;
63
47
  private eventHandlers;
64
48
  private runtimeLogger;
65
49
  private knowledgeProcessingSemaphore;
66
50
  private settings;
51
+ private servicesInitQueue;
52
+ instrumentationService: InstrumentationService;
53
+ tracer: any;
67
54
  constructor(opts: {
68
55
  conversationLength?: number;
69
56
  agentId?: UUID;
@@ -71,11 +58,31 @@ export declare class AgentRuntime implements IAgentRuntime {
71
58
  plugins?: Plugin[];
72
59
  fetch?: typeof fetch;
73
60
  adapter?: IDatabaseAdapter;
61
+ settings?: RuntimeSettings;
74
62
  events?: {
75
63
  [key: string]: ((params: any) => void)[];
76
64
  };
77
- ignoreBootstrap?: boolean;
78
65
  });
66
+ /**
67
+ * Starts a span for the given operation and executes the provided function with the span.
68
+ * @param name The name of the span to create
69
+ * @param fn The function to execute with the span
70
+ * @param parentContext Optional parent context for the span
71
+ * @returns The result of the provided function
72
+ */
73
+ startSpan<T>(name: string, fn: (span: Span) => Promise<T>, parentContext?: Context): Promise<T>;
74
+ /**
75
+ * Ends a span with the provided name in the given context
76
+ * @param ctx Context containing the span to end
77
+ * @param name Name to record in the end event
78
+ */
79
+ endSpan(ctx: Context | undefined, name: string): void;
80
+ /**
81
+ * Start an active span that can be used as a parent for other spans
82
+ * @param name Name of the span
83
+ * @param options Span options
84
+ */
85
+ startActiveSpan(name: string, options?: any): Span;
79
86
  /**
80
87
  * Registers a plugin with the runtime and initializes its components
81
88
  * @param plugin The plugin to register
@@ -84,13 +91,22 @@ export declare class AgentRuntime implements IAgentRuntime {
84
91
  getAllServices(): Map<ServiceTypeName, Service>;
85
92
  stop(): Promise<void>;
86
93
  initialize(): Promise<void>;
94
+ getConnection(): Promise<PGlite | Pool>;
87
95
  private handleProcessingError;
88
96
  private checkExistingKnowledge;
89
- getKnowledge(message: Memory): Promise<KnowledgeItem[]>;
97
+ getKnowledge(message: Memory, scope?: {
98
+ roomId?: UUID;
99
+ worldId?: UUID;
100
+ entityId?: UUID;
101
+ }): Promise<KnowledgeItem[]>;
90
102
  addKnowledge(item: KnowledgeItem, options?: {
91
103
  targetTokens: number;
92
104
  overlap: number;
93
105
  modelContextSize: number;
106
+ }, scope?: {
107
+ roomId: `${string}-${string}-${string}-${string}-${string}`;
108
+ entityId: `${string}-${string}-${string}-${string}-${string}`;
109
+ worldId: `${string}-${string}-${string}-${string}-${string}`;
94
110
  }): Promise<void>;
95
111
  processCharacterKnowledge(items: string[]): Promise<void>;
96
112
  setSetting(key: string, value: string | boolean | null | any, secret?: boolean): void;
@@ -138,16 +154,19 @@ export declare class AgentRuntime implements IAgentRuntime {
138
154
  * @returns The results of the evaluation.
139
155
  */
140
156
  evaluate(message: Memory, state: State, didRespond?: boolean, callback?: HandlerCallback, responses?: Memory[]): Promise<Evaluator[]>;
141
- ensureConnection({ entityId, roomId, userName, name, source, type, channelId, serverId, worldId, }: {
157
+ ensureConnection({ entityId, roomId, worldId, worldName, userName, name, source, type, channelId, serverId, userId, metadata, }: {
142
158
  entityId: UUID;
143
159
  roomId: UUID;
160
+ worldId: UUID;
161
+ worldName?: string;
144
162
  userName?: string;
145
163
  name?: string;
146
164
  source?: string;
147
165
  type?: ChannelType;
148
166
  channelId?: string;
149
167
  serverId?: string;
150
- worldId?: UUID;
168
+ userId?: UUID;
169
+ metadata?: Record<string, any>;
151
170
  }): Promise<void>;
152
171
  /**
153
172
  * Ensures a participant is added to a room, checking that the entity exists first
@@ -173,15 +192,16 @@ export declare class AgentRuntime implements IAgentRuntime {
173
192
  * Composes the agent's state by gathering data from enabled providers.
174
193
  * @param message - The message to use as context for state composition
175
194
  * @param filterList - Optional list of provider names to include, filtering out all others
176
- * @param includeList - Optional list of private provider names to include that would otherwise be filtered out
195
+ * @param onlyInclude - If true, only include providers that are in the includeList, don't get other registered providers
196
+ * @param skipCache - If true, skip the cache and get the latest data from the providers
177
197
  * @returns A State object containing provider data, values, and text
178
198
  */
179
- composeState(message: Memory, filterList?: string[] | null, // only get providers that are in the filterList
180
- includeList?: string[] | null): Promise<State>;
199
+ composeState(message: Memory, includeList?: string[] | null, // include providers that are private, dynamic or otherwise not included by default
200
+ onlyInclude?: boolean, skipCache?: boolean): Promise<State>;
181
201
  getService<T extends Service>(service: ServiceTypeName): T | null;
182
202
  registerService(service: typeof Service): Promise<void>;
183
- registerModel(modelType: ModelTypeName, handler: (params: any) => Promise<any>): void;
184
- getModel(modelType: ModelTypeName): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined;
203
+ registerModel(modelType: ModelTypeName, handler: (params: any) => Promise<any>, provider: string, priority?: number): void;
204
+ getModel(modelType: ModelTypeName, provider?: string): ((runtime: IAgentRuntime, params: any) => Promise<any>) | undefined;
185
205
  /**
186
206
  * Use a model with strongly typed parameters and return values based on model type
187
207
  * @template T - The model type to use
@@ -190,7 +210,7 @@ export declare class AgentRuntime implements IAgentRuntime {
190
210
  * @param {ModelParamsMap[T] | any} params - The parameters for the model, typed based on model type
191
211
  * @returns {Promise<R>} - The model result, typed based on the provided generic type parameter
192
212
  */
193
- useModel<T extends ModelTypeName, R = ModelResultMap[T]>(modelType: T, params: Omit<ModelParamsMap[T], 'runtime'> | any): Promise<R>;
213
+ useModel<T extends ModelTypeName, R = ModelResultMap[T]>(modelType: T, params: Omit<ModelParamsMap[T], 'runtime'> | any, provider?: string): Promise<R>;
194
214
  registerEvent(event: string, handler: (params: any) => Promise<void>): void;
195
215
  getEvent(event: string): ((params: any) => Promise<void>)[] | undefined;
196
216
  emitEvent(event: string | string[], params: any): Promise<void>;
@@ -204,11 +224,11 @@ export declare class AgentRuntime implements IAgentRuntime {
204
224
  init(): Promise<void>;
205
225
  close(): Promise<void>;
206
226
  getAgent(agentId: UUID): Promise<Agent | null>;
207
- getAgents(): Promise<Agent[]>;
227
+ getAgents(): Promise<Partial<Agent>[]>;
208
228
  createAgent(agent: Partial<Agent>): Promise<boolean>;
209
229
  updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean>;
210
230
  deleteAgent(agentId: UUID): Promise<boolean>;
211
- ensureAgentExists(agent: Partial<Agent>): Promise<void>;
231
+ ensureAgentExists(agent: Partial<Agent>): Promise<Agent>;
212
232
  getEntityById(entityId: UUID): Promise<Entity | null>;
213
233
  getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]>;
214
234
  createEntity(entity: Entity): Promise<boolean>;
@@ -257,12 +277,16 @@ export declare class AgentRuntime implements IAgentRuntime {
257
277
  }): Promise<void>;
258
278
  searchMemories(params: {
259
279
  embedding: number[];
280
+ query?: string;
260
281
  match_threshold?: number;
261
282
  count?: number;
262
283
  roomId?: UUID;
263
284
  unique?: boolean;
285
+ worldId?: UUID;
286
+ entityId?: UUID;
264
287
  tableName: string;
265
288
  }): Promise<Memory[]>;
289
+ rerankMemories(query: string, memories: Memory[]): Promise<Memory[]>;
266
290
  createMemory(memory: Memory, tableName: string, unique?: boolean): Promise<UUID>;
267
291
  updateMemory(memory: Partial<Memory> & {
268
292
  id: UUID;
@@ -281,11 +305,13 @@ export declare class AgentRuntime implements IAgentRuntime {
281
305
  deleteLog(logId: UUID): Promise<void>;
282
306
  createWorld(world: World): Promise<UUID>;
283
307
  getWorld(id: UUID): Promise<World | null>;
308
+ removeWorld(worldId: UUID): Promise<void>;
284
309
  getAllWorlds(): Promise<World[]>;
285
310
  updateWorld(world: World): Promise<void>;
286
311
  getRoom(roomId: UUID): Promise<Room | null>;
287
312
  createRoom({ id, name, source, type, channelId, serverId, worldId }: Room): Promise<UUID>;
288
313
  deleteRoom(roomId: UUID): Promise<void>;
314
+ deleteRoomsByServerId(serverId: UUID): Promise<void>;
289
315
  updateRoom(room: Room): Promise<void>;
290
316
  getRoomsForParticipant(entityId: UUID): Promise<UUID[]>;
291
317
  getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;
@@ -316,6 +342,7 @@ export declare class AgentRuntime implements IAgentRuntime {
316
342
  getTasks(params: {
317
343
  roomId?: UUID;
318
344
  tags?: string[];
345
+ entityId?: UUID;
319
346
  }): Promise<Task[]>;
320
347
  getTask(id: UUID): Promise<Task | null>;
321
348
  getTasksByName(name: string): Promise<Task[]>;
@@ -324,5 +351,29 @@ export declare class AgentRuntime implements IAgentRuntime {
324
351
  on(event: string, callback: (data: any) => void): void;
325
352
  off(event: string, callback: (data: any) => void): void;
326
353
  emit(event: string, data: any): void;
354
+ /**
355
+ * Sends a control message to the frontend to enable or disable input
356
+ * @param {Object} params - Parameters for the control message
357
+ * @param {UUID} params.roomId - The ID of the room to send the control message to
358
+ * @param {'enable_input' | 'disable_input'} params.action - The action to perform
359
+ * @param {string} [params.target] - Optional target element identifier
360
+ * @returns {Promise<void>}
361
+ */
362
+ sendControlMessage(params: {
363
+ roomId: UUID;
364
+ action: 'enable_input' | 'disable_input';
365
+ target?: string;
366
+ }): Promise<void>;
367
+ /**
368
+ * Registers a handler function for sending messages to a specific source.
369
+ * @param source - The unique identifier for the source.
370
+ * @param handler - The SendHandlerFunction to register.
371
+ */
372
+ registerSendHandler(source: string, handler: SendHandlerFunction): void;
373
+ /**
374
+ * Sends a message to a target using the registered handler for the target's source.
375
+ * @param target - Information about the message target.
376
+ * @param content - The message content.
377
+ */
378
+ sendMessageToTarget(target: TargetInfo, content: Content): Promise<void>;
327
379
  }
328
- export {};