@elizaos/server 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Shaw Walters and elizaOS Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,273 @@
1
+ # @elizaos/server
2
+
3
+ The server package provides the REST API and WebSocket server infrastructure for ElizaOS agents. It's the core runtime server that powers the ElizaOS CLI and can be embedded in other applications.
4
+
5
+ ## Overview
6
+
7
+ `@elizaos/server` exports a complete agent server implementation including:
8
+
9
+ - REST API endpoints for agent management and interaction
10
+ - WebSocket support for real-time communication
11
+ - Database integration with SQLite/PostgreSQL
12
+ - Plugin system integration
13
+ - Multi-agent runtime management
14
+ - Built-in web UI serving
15
+
16
+ This package is used internally by the ElizaOS CLI (`@elizaos/cli`) but can also be imported directly to create custom server implementations.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @elizaos/server
22
+ # or
23
+ bun add @elizaos/server
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ### Basic Server Setup
29
+
30
+ ```typescript
31
+ import { AgentServer } from '@elizaos/server';
32
+
33
+ // Create and initialize server
34
+ const server = new AgentServer();
35
+ await server.initialize();
36
+
37
+ // Start the server
38
+ const port = 3000;
39
+ server.start(port);
40
+
41
+ // Server is now running at http://localhost:3000
42
+ ```
43
+
44
+ ### Advanced Configuration
45
+
46
+ ```typescript
47
+ import { AgentServer, ServerOptions, ServerMiddleware } from '@elizaos/server';
48
+ import { logger } from '@elizaos/core';
49
+
50
+ // Custom middleware
51
+ const customMiddleware: ServerMiddleware = (req, res, next) => {
52
+ logger.info(`${req.method} ${req.path}`);
53
+ next();
54
+ };
55
+
56
+ // Server configuration
57
+ const serverOptions: ServerOptions = {
58
+ dataDir: './data/agents',
59
+ middlewares: [customMiddleware],
60
+ postgresUrl: process.env.DATABASE_URL, // Optional PostgreSQL
61
+ };
62
+
63
+ // Initialize server with options
64
+ const server = new AgentServer();
65
+ await server.initialize(serverOptions);
66
+
67
+ // Register additional middleware
68
+ server.registerMiddleware((req, res, next) => {
69
+ res.setHeader('X-Server', 'ElizaOS');
70
+ next();
71
+ });
72
+
73
+ // Start the server
74
+ server.start(3000);
75
+ ```
76
+
77
+ ## API Endpoints
78
+
79
+ ### Agent Management
80
+
81
+ - `GET /api/agents` - List all running agents
82
+ - `GET /api/agents/:agentId` - Get specific agent details
83
+ - `POST /api/agents` - Create new agent
84
+ - `PUT /api/agents/:agentId` - Update agent configuration
85
+ - `DELETE /api/agents/:agentId` - Stop and remove agent
86
+
87
+ ### Agent Interaction
88
+
89
+ - `POST /api/agents/:agentId/message` - Send message to agent
90
+ - `GET /api/agents/:agentId/history` - Get conversation history
91
+ - `POST /api/agents/:agentId/action` - Trigger specific agent action
92
+
93
+ ### Memory & State
94
+
95
+ - `GET /api/agents/:agentId/memory` - Get agent memory/knowledge
96
+ - `POST /api/agents/:agentId/memory` - Add to agent memory
97
+ - `DELETE /api/agents/:agentId/memory/:memoryId` - Remove memory
98
+
99
+ ### System
100
+
101
+ - `GET /api/health` - Health check endpoint
102
+ - `GET /api/version` - Get server version info
103
+
104
+ ## WebSocket Events
105
+
106
+ Connect to `ws://localhost:3000/ws` for real-time communication:
107
+
108
+ ```javascript
109
+ // Client-side WebSocket connection
110
+ const ws = new WebSocket('ws://localhost:3000/ws');
111
+
112
+ // Send message
113
+ ws.send(
114
+ JSON.stringify({
115
+ type: 'message',
116
+ agentId: 'agent-123',
117
+ content: 'Hello, agent!',
118
+ })
119
+ );
120
+
121
+ // Receive responses
122
+ ws.on('message', (data) => {
123
+ const response = JSON.parse(data);
124
+ console.log('Agent response:', response);
125
+ });
126
+ ```
127
+
128
+ ### WebSocket Message Types
129
+
130
+ - `message` - Send/receive chat messages
131
+ - `action` - Trigger agent actions
132
+ - `status` - Agent status updates
133
+ - `error` - Error notifications
134
+
135
+ ## Programmatic Usage
136
+
137
+ ### Embedding in Express App
138
+
139
+ ```typescript
140
+ import express from 'express';
141
+ import { AgentServer } from '@elizaos/server';
142
+
143
+ const app = express();
144
+
145
+ // Create ElizaOS server
146
+ const elizaServer = new AgentServer();
147
+ await elizaServer.initialize();
148
+
149
+ // Mount ElizaOS APIs on your Express app
150
+ // The server provides its own Express app instance
151
+ app.use('/eliza', elizaServer.app);
152
+
153
+ // Your custom routes
154
+ app.get('/custom', (req, res) => {
155
+ res.json({ message: 'Custom endpoint' });
156
+ });
157
+
158
+ app.listen(3000);
159
+ ```
160
+
161
+ ### Programmatic Agent Management
162
+
163
+ ```typescript
164
+ import { AgentServer } from '@elizaos/server';
165
+ import { AgentRuntime, Character } from '@elizaos/core';
166
+
167
+ // Initialize server
168
+ const server = new AgentServer();
169
+ await server.initialize();
170
+
171
+ // Create and register agent runtime
172
+ const character: Character = {
173
+ name: 'MyAgent',
174
+ // ... character configuration
175
+ };
176
+
177
+ // Note: Full AgentRuntime creation requires more setup
178
+ // This is a simplified example
179
+ const runtime = new AgentRuntime({
180
+ character,
181
+ database: server.database,
182
+ // ... other configuration
183
+ });
184
+
185
+ // Register agent with server
186
+ await server.registerAgent(runtime);
187
+
188
+ // Start server
189
+ server.start(3000);
190
+ ```
191
+
192
+ ## Configuration
193
+
194
+ ### Environment Variables
195
+
196
+ The server respects these environment variables:
197
+
198
+ - `PORT` - Server port (default: 3000)
199
+ - `HOST` - Server host (default: localhost)
200
+ - `DATABASE_URL` - PostgreSQL connection string
201
+ - `SQLITE_PATH` - Path to SQLite database file
202
+ - `LOG_LEVEL` - Logging level (debug, info, warn, error)
203
+ - `CORS_ORIGIN` - CORS allowed origins
204
+
205
+ ### Server Options
206
+
207
+ ```typescript
208
+ interface ServerOptions {
209
+ port?: number;
210
+ host?: string;
211
+ agents?: string[] | Character[];
212
+ database?: DatabaseConfig;
213
+ plugins?: Plugin[];
214
+ cors?: CorsOptions;
215
+ staticDir?: string;
216
+ enableWebUI?: boolean;
217
+ }
218
+ ```
219
+
220
+ ## Architecture
221
+
222
+ The server package is structured as follows:
223
+
224
+ ```
225
+ server/
226
+ ├── api/ # REST API route handlers
227
+ │ ├── agents/ # Agent management endpoints
228
+ │ ├── memory/ # Memory/knowledge endpoints
229
+ │ └── system/ # System/health endpoints
230
+ ├── database/ # Database adapters and migrations
231
+ ├── services/ # Core services (runtime, storage)
232
+ ├── socketio/ # WebSocket implementation
233
+ └── index.ts # Main exports
234
+ ```
235
+
236
+ ## Development
237
+
238
+ ### Running Tests
239
+
240
+ ```bash
241
+ # Run all tests
242
+ npm test
243
+
244
+ # Run specific test suite
245
+ npm test -- api/agents
246
+
247
+ # Run with coverage
248
+ npm test -- --coverage
249
+ ```
250
+
251
+ ### Building
252
+
253
+ ```bash
254
+ # Build the package
255
+ npm run build
256
+
257
+ # Watch mode for development
258
+ npm run dev
259
+ ```
260
+
261
+ ## Examples
262
+
263
+ See the `/examples` directory for complete examples:
264
+
265
+ - Basic server setup
266
+ - Multi-agent configuration
267
+ - Custom plugin integration
268
+ - Database configuration
269
+ - WebSocket chat client
270
+
271
+ ## License
272
+
273
+ MIT
@@ -0,0 +1,249 @@
1
+ import { UUID, ChannelType, Character, DatabaseAdapter, IAgentRuntime } from '@elizaos/core';
2
+ import express from 'express';
3
+ import http from 'node:http';
4
+ import { Server } from 'socket.io';
5
+
6
+ interface MessageServer {
7
+ id: UUID;
8
+ name: string;
9
+ sourceType: string;
10
+ sourceId?: string;
11
+ metadata?: Record<string, any>;
12
+ createdAt: Date;
13
+ updatedAt: Date;
14
+ }
15
+ interface MessageChannel {
16
+ id: UUID;
17
+ messageServerId: UUID;
18
+ name: string;
19
+ type: ChannelType;
20
+ sourceType?: string;
21
+ sourceId?: string;
22
+ topic?: string;
23
+ metadata?: Record<string, any>;
24
+ createdAt: Date;
25
+ updatedAt: Date;
26
+ }
27
+ interface CentralRootMessage {
28
+ id: UUID;
29
+ channelId: UUID;
30
+ authorId: UUID;
31
+ content: string;
32
+ rawMessage?: any;
33
+ inReplyToRootMessageId?: UUID;
34
+ sourceType?: string;
35
+ sourceId?: string;
36
+ createdAt: Date;
37
+ updatedAt: Date;
38
+ metadata?: Record<string, any>;
39
+ }
40
+ interface MessageServiceStructure {
41
+ id: UUID;
42
+ channel_id: UUID;
43
+ server_id: UUID;
44
+ author_id: UUID;
45
+ author_display_name?: string;
46
+ content: string;
47
+ raw_message?: any;
48
+ source_id?: string;
49
+ source_type?: string;
50
+ in_reply_to_message_id?: UUID;
51
+ created_at: number;
52
+ metadata?: any;
53
+ }
54
+
55
+ /**
56
+ * Attempts to load a file from the given file path.
57
+ *
58
+ * @param {string} filePath - The path to the file to load.
59
+ * @returns {string | null} The contents of the file as a string, or null if an error occurred.
60
+ * @throws {Error} If an error occurs while loading the file.
61
+ */
62
+ declare function tryLoadFile(filePath: string): string | null;
63
+ /**
64
+ * Load characters from a specified URL and return them as an array of Character objects.
65
+ * @param {string} url - The URL from which to load character data.
66
+ * @returns {Promise<Character[]>} - A promise that resolves with an array of Character objects.
67
+ */
68
+ declare function loadCharactersFromUrl(url: string): Promise<Character[]>;
69
+ /**
70
+ * Converts a JSON object representing a character into a validated Character object with additional settings and secrets.
71
+ *
72
+ * @param {unknown} character - The input data representing a character.
73
+ * @returns {Promise<Character>} - A Promise that resolves to a validated Character object.
74
+ * @throws {Error} If character validation fails.
75
+ */
76
+ declare function jsonToCharacter(character: unknown): Promise<Character>;
77
+ /**
78
+ * Loads a character from the specified file path with safe JSON parsing and validation.
79
+ *
80
+ * @param {string} filePath - The path to the character file.
81
+ * @returns {Promise<Character>} A Promise that resolves to the validated Character object.
82
+ * @throws {Error} If the character file is not found, has invalid JSON, or fails validation.
83
+ */
84
+ declare function loadCharacter(filePath: string): Promise<Character>;
85
+ /**
86
+ * Asynchronously loads a character from the specified path.
87
+ * If the path is a URL, it loads the character from the URL.
88
+ * If the path is a local file path, it tries multiple possible locations and
89
+ * loads the character from the first valid location found.
90
+ *
91
+ * @param {string} characterPath - The path to load the character from.
92
+ * @returns {Promise<Character>} A Promise that resolves to the loaded character.
93
+ */
94
+ declare function loadCharacterTryPath(characterPath: string): Promise<Character>;
95
+ declare const hasValidRemoteUrls: () => boolean | "" | undefined;
96
+ /**
97
+ * Load characters from local paths or remote URLs based on configuration.
98
+ * @param charactersArg - A comma-separated list of local file paths or remote URLs to load characters from.
99
+ * @returns A promise that resolves to an array of loaded characters.
100
+ */
101
+ declare function loadCharacters(charactersArg: string): Promise<Character[]>;
102
+
103
+ /**
104
+ * Expands a file path starting with `~` to the project directory.
105
+ *
106
+ * @param filepath - The path to expand.
107
+ * @returns The expanded path.
108
+ */
109
+ declare function expandTildePath(filepath: string): string;
110
+ declare function resolvePgliteDir(dir?: string, fallbackDir?: string): string;
111
+ /**
112
+ * Represents a function that acts as a server middleware.
113
+ * @param {express.Request} req - The request object.
114
+ * @param {express.Response} res - The response object.
115
+ * @param {express.NextFunction} next - The next function to be called in the middleware chain.
116
+ * @returns {void}
117
+ */
118
+ type ServerMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => void;
119
+ /**
120
+ * Interface for defining server configuration options.
121
+ * @typedef {Object} ServerOptions
122
+ * @property {ServerMiddleware[]} [middlewares] - Optional array of server middlewares.
123
+ * @property {string} [dataDir] - Optional directory for storing server data.
124
+ * @property {string} [postgresUrl] - Optional URL for connecting to a PostgreSQL database.
125
+ */
126
+ interface ServerOptions {
127
+ middlewares?: ServerMiddleware[];
128
+ dataDir?: string;
129
+ postgresUrl?: string;
130
+ }
131
+ /**
132
+ * Class representing an agent server.
133
+ */ /**
134
+ * Represents an agent server which handles agents, database, and server functionalities.
135
+ */
136
+ declare class AgentServer {
137
+ app: express.Application;
138
+ private agents;
139
+ server: http.Server;
140
+ socketIO: Server;
141
+ isInitialized: boolean;
142
+ database: DatabaseAdapter;
143
+ startAgent: (character: Character) => Promise<IAgentRuntime>;
144
+ stopAgent: (runtime: IAgentRuntime) => void;
145
+ loadCharacterTryPath: (characterPath: string) => Promise<Character>;
146
+ jsonToCharacter: (character: unknown) => Promise<Character>;
147
+ /**
148
+ * Constructor for AgentServer class.
149
+ *
150
+ * @constructor
151
+ */
152
+ constructor();
153
+ /**
154
+ * Initializes the database and server.
155
+ *
156
+ * @param {ServerOptions} [options] - Optional server options.
157
+ * @returns {Promise<void>} A promise that resolves when initialization is complete.
158
+ */
159
+ initialize(options?: ServerOptions): Promise<void>;
160
+ private ensureDefaultServer;
161
+ /**
162
+ * Initializes the server with the provided options.
163
+ *
164
+ * @param {ServerOptions} [options] - Optional server options.
165
+ * @returns {Promise<void>} - A promise that resolves once the server is initialized.
166
+ */
167
+ private initializeServer;
168
+ /**
169
+ * Registers an agent with the provided runtime.
170
+ *
171
+ * @param {IAgentRuntime} runtime - The runtime object containing agent information.
172
+ * @throws {Error} if the runtime is null/undefined, if agentId is missing, if character configuration is missing,
173
+ * or if there are any errors during registration.
174
+ */
175
+ registerAgent(runtime: IAgentRuntime): Promise<void>;
176
+ /**
177
+ * Unregisters an agent from the system.
178
+ *
179
+ * @param {UUID} agentId - The unique identifier of the agent to unregister.
180
+ * @returns {void}
181
+ */
182
+ unregisterAgent(agentId: UUID): void;
183
+ /**
184
+ * Add middleware to the server's request handling pipeline
185
+ * @param {ServerMiddleware} middleware - The middleware function to be registered
186
+ */
187
+ registerMiddleware(middleware: ServerMiddleware): void;
188
+ /**
189
+ * Starts the server on the specified port.
190
+ *
191
+ * @param {number} port - The port number on which the server should listen.
192
+ * @throws {Error} If the port is invalid or if there is an error while starting the server.
193
+ */
194
+ start(port: number): void;
195
+ /**
196
+ * Stops the server if it is running. Closes the server connection,
197
+ * stops the database connection, and logs a success message.
198
+ */
199
+ stop(): Promise<void>;
200
+ createServer(data: Omit<MessageServer, 'id' | 'createdAt' | 'updatedAt'>): Promise<MessageServer>;
201
+ getServers(): Promise<MessageServer[]>;
202
+ getServerById(serverId: UUID): Promise<MessageServer | null>;
203
+ getServerBySourceType(sourceType: string): Promise<MessageServer | null>;
204
+ createChannel(data: Omit<MessageChannel, 'id' | 'createdAt' | 'updatedAt'> & {
205
+ id?: UUID;
206
+ }, participantIds?: UUID[]): Promise<MessageChannel>;
207
+ addParticipantsToChannel(channelId: UUID, userIds: UUID[]): Promise<void>;
208
+ getChannelsForServer(serverId: UUID): Promise<MessageChannel[]>;
209
+ getChannelDetails(channelId: UUID): Promise<MessageChannel | null>;
210
+ getChannelParticipants(channelId: UUID): Promise<UUID[]>;
211
+ deleteMessage(messageId: UUID): Promise<void>;
212
+ updateChannel(channelId: UUID, updates: {
213
+ name?: string;
214
+ participantCentralUserIds?: UUID[];
215
+ metadata?: any;
216
+ }): Promise<MessageChannel>;
217
+ deleteChannel(channelId: UUID): Promise<void>;
218
+ clearChannelMessages(channelId: UUID): Promise<void>;
219
+ findOrCreateCentralDmChannel(user1Id: UUID, user2Id: UUID, messageServerId: UUID): Promise<MessageChannel>;
220
+ createMessage(data: Omit<CentralRootMessage, 'id' | 'createdAt' | 'updatedAt'>): Promise<CentralRootMessage>;
221
+ getMessagesForChannel(channelId: UUID, limit?: number, beforeTimestamp?: Date): Promise<CentralRootMessage[]>;
222
+ removeParticipantFromChannel(): Promise<void>;
223
+ /**
224
+ * Add an agent to a server
225
+ * @param {UUID} serverId - The server ID
226
+ * @param {UUID} agentId - The agent ID to add
227
+ */
228
+ addAgentToServer(serverId: UUID, agentId: UUID): Promise<void>;
229
+ /**
230
+ * Remove an agent from a server
231
+ * @param {UUID} serverId - The server ID
232
+ * @param {UUID} agentId - The agent ID to remove
233
+ */
234
+ removeAgentFromServer(serverId: UUID, agentId: UUID): Promise<void>;
235
+ /**
236
+ * Get all agents associated with a server
237
+ * @param {UUID} serverId - The server ID
238
+ * @returns {Promise<UUID[]>} Array of agent IDs
239
+ */
240
+ getAgentsForServer(serverId: UUID): Promise<UUID[]>;
241
+ /**
242
+ * Get all servers an agent belongs to
243
+ * @param {UUID} agentId - The agent ID
244
+ * @returns {Promise<UUID[]>} Array of server IDs
245
+ */
246
+ getServersForAgent(agentId: UUID): Promise<UUID[]>;
247
+ }
248
+
249
+ export { AgentServer, type CentralRootMessage, type MessageChannel, type MessageServer, type MessageServiceStructure, type ServerMiddleware, type ServerOptions, expandTildePath, hasValidRemoteUrls, jsonToCharacter, loadCharacter, loadCharacterTryPath, loadCharacters, loadCharactersFromUrl, resolvePgliteDir, tryLoadFile };