@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 +21 -0
- package/README.md +273 -0
- package/dist/index.d.ts +249 -0
- package/dist/index.js +6333 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/object-assign/index.js","../../../node_modules/vary/index.js","../../../node_modules/cors/lib/index.js","../src/index.ts","../src/api/index.ts","../src/api/agents/index.ts","../src/api/agents/crud.ts","../src/api/shared/response-utils.ts","../src/api/agents/lifecycle.ts","../src/api/agents/worlds.ts","../src/api/agents/panels.ts","../src/api/agents/logs.ts","../src/api/memory/agents.ts","../src/api/messaging/index.ts","../src/api/messaging/core.ts","../src/bus.ts","../src/api/messaging/servers.ts","../src/api/messaging/channels.ts","../src/upload.ts","../src/api/shared/file-utils.ts","../src/api/shared/constants.ts","../src/api/shared/middleware.ts","../src/api/shared/validation.ts","../src/api/media/index.ts","../src/api/media/agents.ts","../src/api/media/channels.ts","../src/api/memory/index.ts","../src/api/memory/groups.ts","../src/api/memory/rooms.ts","../src/api/audio/index.ts","../src/api/audio/processing.ts","../src/api/audio/synthesis.ts","../src/api/audio/audioBuffer.ts","../src/api/audio/conversation.ts","../src/api/runtime/index.ts","../src/api/runtime/health.ts","../src/api/runtime/logging.ts","../src/api/runtime/debug.ts","../src/api/tee/index.ts","../src/api/system/index.ts","../src/api/system/environment.ts","../src/socketio/index.ts","../src/authMiddleware.ts","../src/services/message.ts","../src/loader.ts"],"sourcesContent":["/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/*!\n * vary\n * Copyright(c) 2014-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n */\n\nmodule.exports = vary\nmodule.exports.append = append\n\n/**\n * RegExp to match field-name in RFC 7230 sec 3.2\n *\n * field-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n */\n\nvar FIELD_NAME_REGEXP = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\n/**\n * Append a field to a vary header.\n *\n * @param {String} header\n * @param {String|Array} field\n * @return {String}\n * @public\n */\n\nfunction append (header, field) {\n if (typeof header !== 'string') {\n throw new TypeError('header argument is required')\n }\n\n if (!field) {\n throw new TypeError('field argument is required')\n }\n\n // get fields array\n var fields = !Array.isArray(field)\n ? parse(String(field))\n : field\n\n // assert on invalid field names\n for (var j = 0; j < fields.length; j++) {\n if (!FIELD_NAME_REGEXP.test(fields[j])) {\n throw new TypeError('field argument contains an invalid header name')\n }\n }\n\n // existing, unspecified vary\n if (header === '*') {\n return header\n }\n\n // enumerate current values\n var val = header\n var vals = parse(header.toLowerCase())\n\n // unspecified vary\n if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {\n return '*'\n }\n\n for (var i = 0; i < fields.length; i++) {\n var fld = fields[i].toLowerCase()\n\n // append value (case-preserving)\n if (vals.indexOf(fld) === -1) {\n vals.push(fld)\n val = val\n ? val + ', ' + fields[i]\n : fields[i]\n }\n }\n\n return val\n}\n\n/**\n * Parse a vary header into an array.\n *\n * @param {String} header\n * @return {Array}\n * @private\n */\n\nfunction parse (header) {\n var end = 0\n var list = []\n var start = 0\n\n // gather tokens\n for (var i = 0, len = header.length; i < len; i++) {\n switch (header.charCodeAt(i)) {\n case 0x20: /* */\n if (start === end) {\n start = end = i + 1\n }\n break\n case 0x2c: /* , */\n list.push(header.substring(start, end))\n start = end = i + 1\n break\n default:\n end = i + 1\n break\n }\n }\n\n // final token\n list.push(header.substring(start, end))\n\n return list\n}\n\n/**\n * Mark that a request is varied on a header field.\n *\n * @param {Object} res\n * @param {String|Array} field\n * @public\n */\n\nfunction vary (res, field) {\n if (!res || !res.getHeader || !res.setHeader) {\n // quack quack\n throw new TypeError('res argument is required')\n }\n\n // get existing header\n var val = res.getHeader('Vary') || ''\n var header = Array.isArray(val)\n ? val.join(', ')\n : String(val)\n\n // set new header\n if ((val = append(header, field))) {\n res.setHeader('Vary', val)\n }\n}\n","(function () {\n\n 'use strict';\n\n var assign = require('object-assign');\n var vary = require('vary');\n\n var defaults = {\n origin: '*',\n methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',\n preflightContinue: false,\n optionsSuccessStatus: 204\n };\n\n function isString(s) {\n return typeof s === 'string' || s instanceof String;\n }\n\n function isOriginAllowed(origin, allowedOrigin) {\n if (Array.isArray(allowedOrigin)) {\n for (var i = 0; i < allowedOrigin.length; ++i) {\n if (isOriginAllowed(origin, allowedOrigin[i])) {\n return true;\n }\n }\n return false;\n } else if (isString(allowedOrigin)) {\n return origin === allowedOrigin;\n } else if (allowedOrigin instanceof RegExp) {\n return allowedOrigin.test(origin);\n } else {\n return !!allowedOrigin;\n }\n }\n\n function configureOrigin(options, req) {\n var requestOrigin = req.headers.origin,\n headers = [],\n isAllowed;\n\n if (!options.origin || options.origin === '*') {\n // allow any origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: '*'\n }]);\n } else if (isString(options.origin)) {\n // fixed origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: options.origin\n }]);\n headers.push([{\n key: 'Vary',\n value: 'Origin'\n }]);\n } else {\n isAllowed = isOriginAllowed(requestOrigin, options.origin);\n // reflect origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: isAllowed ? requestOrigin : false\n }]);\n headers.push([{\n key: 'Vary',\n value: 'Origin'\n }]);\n }\n\n return headers;\n }\n\n function configureMethods(options) {\n var methods = options.methods;\n if (methods.join) {\n methods = options.methods.join(','); // .methods is an array, so turn it into a string\n }\n return {\n key: 'Access-Control-Allow-Methods',\n value: methods\n };\n }\n\n function configureCredentials(options) {\n if (options.credentials === true) {\n return {\n key: 'Access-Control-Allow-Credentials',\n value: 'true'\n };\n }\n return null;\n }\n\n function configureAllowedHeaders(options, req) {\n var allowedHeaders = options.allowedHeaders || options.headers;\n var headers = [];\n\n if (!allowedHeaders) {\n allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers\n headers.push([{\n key: 'Vary',\n value: 'Access-Control-Request-Headers'\n }]);\n } else if (allowedHeaders.join) {\n allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string\n }\n if (allowedHeaders && allowedHeaders.length) {\n headers.push([{\n key: 'Access-Control-Allow-Headers',\n value: allowedHeaders\n }]);\n }\n\n return headers;\n }\n\n function configureExposedHeaders(options) {\n var headers = options.exposedHeaders;\n if (!headers) {\n return null;\n } else if (headers.join) {\n headers = headers.join(','); // .headers is an array, so turn it into a string\n }\n if (headers && headers.length) {\n return {\n key: 'Access-Control-Expose-Headers',\n value: headers\n };\n }\n return null;\n }\n\n function configureMaxAge(options) {\n var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString()\n if (maxAge && maxAge.length) {\n return {\n key: 'Access-Control-Max-Age',\n value: maxAge\n };\n }\n return null;\n }\n\n function applyHeaders(headers, res) {\n for (var i = 0, n = headers.length; i < n; i++) {\n var header = headers[i];\n if (header) {\n if (Array.isArray(header)) {\n applyHeaders(header, res);\n } else if (header.key === 'Vary' && header.value) {\n vary(res, header.value);\n } else if (header.value) {\n res.setHeader(header.key, header.value);\n }\n }\n }\n }\n\n function cors(options, req, res, next) {\n var headers = [],\n method = req.method && req.method.toUpperCase && req.method.toUpperCase();\n\n if (method === 'OPTIONS') {\n // preflight\n headers.push(configureOrigin(options, req));\n headers.push(configureCredentials(options, req));\n headers.push(configureMethods(options, req));\n headers.push(configureAllowedHeaders(options, req));\n headers.push(configureMaxAge(options, req));\n headers.push(configureExposedHeaders(options, req));\n applyHeaders(headers, res);\n\n if (options.preflightContinue) {\n next();\n } else {\n // Safari (and potentially other browsers) need content-length 0,\n // for 204 or they just hang waiting for a body\n res.statusCode = options.optionsSuccessStatus;\n res.setHeader('Content-Length', '0');\n res.end();\n }\n } else {\n // actual response\n headers.push(configureOrigin(options, req));\n headers.push(configureCredentials(options, req));\n headers.push(configureExposedHeaders(options, req));\n applyHeaders(headers, res);\n next();\n }\n }\n\n function middlewareWrapper(o) {\n // if options are static (either via defaults or custom options passed in), wrap in a function\n var optionsCallback = null;\n if (typeof o === 'function') {\n optionsCallback = o;\n } else {\n optionsCallback = function (req, cb) {\n cb(null, o);\n };\n }\n\n return function corsMiddleware(req, res, next) {\n optionsCallback(req, function (err, options) {\n if (err) {\n next(err);\n } else {\n var corsOptions = assign({}, defaults, options);\n var originCallback = null;\n if (corsOptions.origin && typeof corsOptions.origin === 'function') {\n originCallback = corsOptions.origin;\n } else if (corsOptions.origin) {\n originCallback = function (origin, cb) {\n cb(null, corsOptions.origin);\n };\n }\n\n if (originCallback) {\n originCallback(req.headers.origin, function (err2, origin) {\n if (err2 || !origin) {\n next(err2);\n } else {\n corsOptions.origin = origin;\n cors(corsOptions, req, res, next);\n }\n });\n } else {\n next();\n }\n }\n });\n };\n }\n\n // can pass either an options hash, an options delegate, or nothing\n module.exports = middlewareWrapper;\n\n}());\n","import {\n type Character,\n DatabaseAdapter,\n type IAgentRuntime,\n logger,\n type UUID,\n} from '@elizaos/core';\nimport bodyParser from 'body-parser';\nimport cors from 'cors';\nimport express, { Request, Response } from 'express';\nimport fileUpload from 'express-fileupload';\nimport helmet from 'helmet';\nimport * as fs from 'node:fs';\nimport http from 'node:http';\nimport path, { basename, dirname, extname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Server as SocketIOServer } from 'socket.io';\nimport { createApiRouter, createPluginRouteHandler, setupSocketIO } from './api/index.js';\nimport { apiKeyAuthMiddleware } from './authMiddleware.js';\nimport { messageBusConnectorPlugin } from './services/message.js';\nimport { loadCharacterTryPath, jsonToCharacter } from './loader.js';\n\nimport {\n createDatabaseAdapter,\n DatabaseMigrationService,\n plugin as sqlPlugin,\n} from '@elizaos/plugin-sql';\nimport internalMessageBus from './bus.js';\nimport type {\n CentralRootMessage,\n MessageChannel,\n MessageServer,\n MessageServiceStructure,\n} from './types.js';\nimport { existsSync } from 'node:fs';\nimport { resolveEnvFile } from './api/system/environment.js';\nimport dotenv from 'dotenv';\n\n/**\n * Expands a file path starting with `~` to the project directory.\n *\n * @param filepath - The path to expand.\n * @returns The expanded path.\n */\nexport function expandTildePath(filepath: string): string {\n if (!filepath) {\n return filepath;\n }\n\n if (filepath.startsWith('~')) {\n if (filepath === '~') {\n return process.cwd();\n } else if (filepath.startsWith('~/')) {\n return path.join(process.cwd(), filepath.slice(2));\n } else if (filepath.startsWith('~~')) {\n // Don't expand ~~\n return filepath;\n } else {\n // Handle ~user/path by expanding it to cwd/user/path\n return path.join(process.cwd(), filepath.slice(1));\n }\n }\n\n return filepath;\n}\n\nexport function resolvePgliteDir(dir?: string, fallbackDir?: string): string {\n const envPath = resolveEnvFile();\n if (existsSync(envPath)) {\n dotenv.config({ path: envPath });\n }\n\n const base =\n dir ??\n process.env.PGLITE_DATA_DIR ??\n fallbackDir ??\n path.join(process.cwd(), '.eliza', '.elizadb');\n\n // Automatically migrate legacy path (<cwd>/.elizadb) to new location (<cwd>/.eliza/.elizadb)\n const resolved = expandTildePath(base);\n const legacyPath = path.join(process.cwd(), '.elizadb');\n if (resolved === legacyPath) {\n const newPath = path.join(process.cwd(), '.eliza', '.elizadb');\n process.env.PGLITE_DATA_DIR = newPath;\n return newPath;\n }\n\n return resolved;\n}\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID; // Single default server\n\n/**\n * Represents a function that acts as a server middleware.\n * @param {express.Request} req - The request object.\n * @param {express.Response} res - The response object.\n * @param {express.NextFunction} next - The next function to be called in the middleware chain.\n * @returns {void}\n */\nexport type ServerMiddleware = (\n req: express.Request,\n res: express.Response,\n next: express.NextFunction\n) => void;\n\n/**\n * Interface for defining server configuration options.\n * @typedef {Object} ServerOptions\n * @property {ServerMiddleware[]} [middlewares] - Optional array of server middlewares.\n * @property {string} [dataDir] - Optional directory for storing server data.\n * @property {string} [postgresUrl] - Optional URL for connecting to a PostgreSQL database.\n */\nexport interface ServerOptions {\n middlewares?: ServerMiddleware[];\n dataDir?: string;\n postgresUrl?: string;\n}\n\n/**\n * Class representing an agent server.\n */ /**\n * Represents an agent server which handles agents, database, and server functionalities.\n */\nexport class AgentServer {\n public app!: express.Application;\n private agents: Map<UUID, IAgentRuntime>;\n public server!: http.Server;\n public socketIO!: SocketIOServer;\n public isInitialized: boolean = false; // Flag to prevent double initialization\n\n public database!: DatabaseAdapter;\n\n public startAgent!: (character: Character) => Promise<IAgentRuntime>;\n public stopAgent!: (runtime: IAgentRuntime) => void;\n public loadCharacterTryPath!: (characterPath: string) => Promise<Character>;\n public jsonToCharacter!: (character: unknown) => Promise<Character>;\n\n /**\n * Constructor for AgentServer class.\n *\n * @constructor\n */\n constructor() {\n try {\n logger.debug('Initializing AgentServer (constructor)...');\n this.agents = new Map();\n\n // Initialize character loading functions\n this.loadCharacterTryPath = loadCharacterTryPath;\n this.jsonToCharacter = jsonToCharacter;\n } catch (error) {\n logger.error('Failed to initialize AgentServer (constructor):', error);\n throw error;\n }\n }\n\n /**\n * Initializes the database and server.\n *\n * @param {ServerOptions} [options] - Optional server options.\n * @returns {Promise<void>} A promise that resolves when initialization is complete.\n */\n public async initialize(options?: ServerOptions): Promise<void> {\n if (this.isInitialized) {\n logger.warn('AgentServer is already initialized, skipping initialization');\n return;\n }\n\n try {\n logger.debug('Initializing AgentServer (async operations)...');\n\n const agentDataDir = await resolvePgliteDir(options?.dataDir);\n logger.info(`[INIT] Database Dir for SQL plugin: ${agentDataDir}`);\n this.database = createDatabaseAdapter(\n {\n dataDir: agentDataDir,\n postgresUrl: options?.postgresUrl,\n },\n '00000000-0000-0000-0000-000000000002'\n ) as DatabaseAdapter;\n await this.database.init();\n logger.success('Consolidated database initialized successfully');\n\n // Run migrations for the SQL plugin schema\n logger.info('[INIT] Running database migrations for messaging tables...');\n try {\n const migrationService = new DatabaseMigrationService();\n\n // Get the underlying database instance\n const db = (this.database as any).getDatabase();\n await migrationService.initializeWithDatabase(db);\n\n // Register the SQL plugin schema\n migrationService.discoverAndRegisterPluginSchemas([sqlPlugin]);\n\n // Run the migrations\n await migrationService.runAllPluginMigrations();\n\n logger.success('[INIT] Database migrations completed successfully');\n } catch (migrationError) {\n logger.error('[INIT] Failed to run database migrations:', migrationError);\n throw new Error(\n `Database migration failed: ${migrationError instanceof Error ? migrationError.message : String(migrationError)}`\n );\n }\n\n // Add a small delay to ensure database is fully ready\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n // Ensure default server exists\n logger.info('[INIT] Ensuring default server exists...');\n await this.ensureDefaultServer();\n logger.success('[INIT] Default server setup complete');\n\n await this.initializeServer(options);\n await new Promise((resolve) => setTimeout(resolve, 250));\n this.isInitialized = true;\n } catch (error) {\n logger.error('Failed to initialize AgentServer (async operations):', error);\n console.trace(error);\n throw error;\n }\n }\n\n private async ensureDefaultServer(): Promise<void> {\n try {\n // Check if the default server exists\n logger.info('[AgentServer] Checking for default server...');\n const servers = await (this.database as any).getMessageServers();\n logger.debug(`[AgentServer] Found ${servers.length} existing servers`);\n\n // Log all existing servers for debugging\n servers.forEach((s: any) => {\n logger.debug(`[AgentServer] Existing server: ID=${s.id}, Name=${s.name}`);\n });\n\n const defaultServer = servers.find(\n (s: any) => s.id === '00000000-0000-0000-0000-000000000000'\n );\n\n if (!defaultServer) {\n logger.info(\n '[AgentServer] Creating default server with UUID 00000000-0000-0000-0000-000000000000...'\n );\n\n // Use raw SQL to ensure the server is created with the exact ID\n try {\n await (this.database as any).db.execute(`\n INSERT INTO message_servers (id, name, source_type, created_at, updated_at)\n VALUES ('00000000-0000-0000-0000-000000000000', 'Default Server', 'eliza_default', NOW(), NOW())\n ON CONFLICT (id) DO NOTHING\n `);\n logger.success('[AgentServer] Default server created via raw SQL');\n\n // Immediately check if it was created\n const checkResult = await (this.database as any).db.execute(\n \"SELECT id, name FROM message_servers WHERE id = '00000000-0000-0000-0000-000000000000'\"\n );\n logger.debug('[AgentServer] Raw SQL check result:', checkResult);\n } catch (sqlError: any) {\n logger.error('[AgentServer] Raw SQL insert failed:', sqlError);\n\n // Try creating with ORM as fallback\n try {\n const server = await (this.database as any).createMessageServer({\n id: '00000000-0000-0000-0000-000000000000' as UUID,\n name: 'Default Server',\n sourceType: 'eliza_default',\n });\n logger.success('[AgentServer] Default server created via ORM with ID:', server.id);\n } catch (ormError: any) {\n logger.error('[AgentServer] Both SQL and ORM creation failed:', ormError);\n throw new Error(`Failed to create default server: ${ormError.message}`);\n }\n }\n\n // Verify it was created\n const verifyServers = await (this.database as any).getMessageServers();\n logger.debug(`[AgentServer] After creation attempt, found ${verifyServers.length} servers`);\n verifyServers.forEach((s: any) => {\n logger.debug(`[AgentServer] Server after creation: ID=${s.id}, Name=${s.name}`);\n });\n\n const verifyDefault = verifyServers.find(\n (s: any) => s.id === '00000000-0000-0000-0000-000000000000'\n );\n if (!verifyDefault) {\n throw new Error(`Failed to create or verify default server with ID ${DEFAULT_SERVER_ID}`);\n } else {\n logger.success('[AgentServer] Default server creation verified successfully');\n }\n } else {\n logger.info('[AgentServer] Default server already exists with ID:', defaultServer.id);\n }\n } catch (error) {\n logger.error('[AgentServer] Error ensuring default server:', error);\n throw error; // Re-throw to prevent startup if default server can't be created\n }\n }\n\n /**\n * Initializes the server with the provided options.\n *\n * @param {ServerOptions} [options] - Optional server options.\n * @returns {Promise<void>} - A promise that resolves once the server is initialized.\n */\n private async initializeServer(options?: ServerOptions) {\n try {\n // Initialize middleware and database\n this.app = express();\n\n // Security headers first - before any other middleware\n const isProd = process.env.NODE_ENV === 'production';\n logger.debug('Setting up security headers...');\n if (!isProd) {\n logger.debug(`NODE_ENV: ${process.env.NODE_ENV}`);\n logger.debug(`CSP will be: ${isProd ? 'ENABLED' : 'MINIMAL_DEV'}`);\n }\n this.app.use(\n helmet({\n // Content Security Policy - environment-aware configuration\n contentSecurityPolicy: isProd\n ? {\n // Production CSP - includes upgrade-insecure-requests\n directives: {\n defaultSrc: [\"'self'\"],\n styleSrc: [\"'self'\", \"'unsafe-inline'\", 'https:'],\n scriptSrc: [\"'self'\", \"'unsafe-inline'\", \"'unsafe-eval'\"],\n imgSrc: [\"'self'\", 'data:', 'blob:', 'https:', 'http:'],\n fontSrc: [\"'self'\", 'https:', 'data:'],\n connectSrc: [\"'self'\", 'ws:', 'wss:', 'https:', 'http:'],\n mediaSrc: [\"'self'\", 'blob:', 'data:'],\n objectSrc: [\"'none'\"],\n frameSrc: [\"'none'\"],\n baseUri: [\"'self'\"],\n formAction: [\"'self'\"],\n // upgrade-insecure-requests is added by helmet automatically\n },\n useDefaults: true,\n }\n : {\n // Development CSP - minimal policy without upgrade-insecure-requests\n directives: {\n defaultSrc: [\"'self'\"],\n styleSrc: [\"'self'\", \"'unsafe-inline'\", 'https:', 'http:'],\n scriptSrc: [\"'self'\", \"'unsafe-inline'\", \"'unsafe-eval'\"],\n imgSrc: [\"'self'\", 'data:', 'blob:', 'https:', 'http:'],\n fontSrc: [\"'self'\", 'https:', 'http:', 'data:'],\n connectSrc: [\"'self'\", 'ws:', 'wss:', 'https:', 'http:'],\n mediaSrc: [\"'self'\", 'blob:', 'data:'],\n objectSrc: [\"'none'\"],\n frameSrc: [\"'self'\", 'data:'],\n baseUri: [\"'self'\"],\n formAction: [\"'self'\"],\n // Note: upgrade-insecure-requests is intentionally omitted for Safari compatibility\n },\n useDefaults: false,\n },\n // Cross-Origin Embedder Policy - disabled for compatibility\n crossOriginEmbedderPolicy: false,\n // Cross-Origin Resource Policy\n crossOriginResourcePolicy: { policy: 'cross-origin' },\n // Frame Options - allow same-origin iframes to align with frameSrc CSP\n frameguard: { action: 'sameorigin' },\n // Hide Powered-By header\n hidePoweredBy: true,\n // HTTP Strict Transport Security - only in production\n hsts: isProd\n ? {\n maxAge: 31536000, // 1 year\n includeSubDomains: true,\n preload: true,\n }\n : false,\n // No Sniff\n noSniff: true,\n // Referrer Policy\n referrerPolicy: { policy: 'no-referrer-when-downgrade' },\n // X-XSS-Protection\n xssFilter: true,\n })\n );\n\n // Apply custom middlewares if provided\n if (options?.middlewares) {\n logger.debug('Applying custom middlewares...');\n for (const middleware of options.middlewares) {\n this.app.use(middleware);\n }\n }\n\n // Setup middleware for all requests\n logger.debug('Setting up standard middlewares...');\n this.app.use(\n cors({\n origin: process.env.CORS_ORIGIN || true,\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-API-KEY'],\n })\n ); // Enable CORS\n this.app.use(\n bodyParser.json({\n limit: process.env.EXPRESS_MAX_PAYLOAD || '100kb',\n })\n ); // Parse JSON bodies\n\n // Global file upload configuration with security constraints\n // Note: Individual routes use more specific configurations\n this.app.use(\n fileUpload({\n useTempFiles: true,\n tempFileDir: '/tmp/',\n createParentPath: true,\n preserveExtension: true,\n safeFileNames: true,\n limits: {\n fileSize: 50 * 1024 * 1024, // 50MB default limit\n },\n abortOnLimit: true,\n uploadTimeout: 60000, // 60 seconds\n })\n );\n\n // Optional Authentication Middleware\n const serverAuthToken = process.env.ELIZA_SERVER_AUTH_TOKEN;\n if (serverAuthToken) {\n logger.info('Server authentication enabled. Requires X-API-KEY header for /api routes.');\n // Apply middleware only to /api paths\n this.app.use('/api', (req, res, next) => {\n apiKeyAuthMiddleware(req, res, next);\n });\n } else {\n logger.warn(\n 'Server authentication is disabled. Set ELIZA_SERVER_AUTH_TOKEN environment variable to enable.'\n );\n }\n\n const uploadsBasePath = path.join(process.cwd(), '.eliza', 'data', 'uploads', 'agents');\n const generatedBasePath = path.join(process.cwd(), '.eliza', 'data', 'generated');\n fs.mkdirSync(uploadsBasePath, { recursive: true });\n fs.mkdirSync(generatedBasePath, { recursive: true });\n\n // Agent-specific media serving - only serve files from agent-specific directories\n this.app.get(\n '/media/uploads/agents/:agentId/:filename',\n // @ts-expect-error - this is a valid express route\n (req: express.Request, res: express.Response) => {\n const agentId = req.params.agentId as string;\n const filename = req.params.filename as string;\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(agentId)) {\n return res.status(400).json({ error: 'Invalid agent ID format' });\n }\n const sanitizedFilename = basename(filename);\n const agentUploadsPath = join(uploadsBasePath, agentId);\n const filePath = join(agentUploadsPath, sanitizedFilename);\n if (!filePath.startsWith(agentUploadsPath)) {\n return res.status(403).json({ error: 'Access denied' });\n }\n\n if (!fs.existsSync(filePath)) {\n return res.status(404).json({ error: 'File does not exist!!!!!!!' });\n }\n\n res.sendFile(sanitizedFilename, { root: agentUploadsPath }, (err) => {\n if (err) {\n if (err.message === 'Request aborted') {\n logger.warn(`[MEDIA] Download aborted: ${req.originalUrl}`);\n } else if (!res.headersSent) {\n logger.warn(`[MEDIA] File not found: ${agentUploadsPath}/${sanitizedFilename}`);\n res.status(404).json({ error: 'File not found' });\n }\n } else {\n logger.debug(`[MEDIA] Successfully served: ${sanitizedFilename}`);\n }\n });\n }\n );\n\n this.app.get(\n '/media/generated/:agentId/:filename',\n // @ts-expect-error - this is a valid express route\n (req: express.Request<{ agentId: string; filename: string }>, res: express.Response) => {\n const agentId = req.params.agentId;\n const filename = req.params.filename;\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(agentId)) {\n return res.status(400).json({ error: 'Invalid agent ID format' });\n }\n const sanitizedFilename = basename(filename);\n const agentGeneratedPath = join(generatedBasePath, agentId);\n const filePath = join(agentGeneratedPath, sanitizedFilename);\n if (!filePath.startsWith(agentGeneratedPath)) {\n return res.status(403).json({ error: 'Access denied' });\n }\n res.sendFile(filePath, (err) => {\n if (err) {\n res.status(404).json({ error: 'File not found' });\n }\n });\n }\n );\n\n // Channel-specific media serving\n this.app.get(\n '/media/uploads/channels/:channelId/:filename',\n (req: express.Request<{ channelId: string; filename: string }>, res: express.Response) => {\n const channelId = req.params.channelId as string;\n const filename = req.params.filename as string;\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n if (!uuidRegex.test(channelId)) {\n res.status(400).json({ error: 'Invalid channel ID format' });\n return;\n }\n\n const sanitizedFilename = basename(filename);\n const channelUploadsPath = join(uploadsBasePath, 'channels', channelId);\n const filePath = join(channelUploadsPath, sanitizedFilename);\n\n if (!filePath.startsWith(channelUploadsPath)) {\n res.status(403).json({ error: 'Access denied' });\n return;\n }\n\n res.sendFile(filePath, (err) => {\n if (err) {\n logger.warn(`[STATIC] Channel media file not found: ${filePath}`, err);\n if (!res.headersSent) {\n res.status(404).json({ error: 'File not found' });\n }\n } else {\n logger.debug(`[STATIC] Served channel media file: ${filePath}`);\n }\n });\n }\n );\n\n // Add specific middleware to handle portal assets\n this.app.use((req, res, next) => {\n // Automatically detect and handle static assets based on file extension\n const ext = extname(req.path).toLowerCase();\n\n // Set correct content type based on file extension\n if (ext === '.js' || ext === '.mjs') {\n res.setHeader('Content-Type', 'application/javascript');\n } else if (ext === '.css') {\n res.setHeader('Content-Type', 'text/css');\n } else if (ext === '.svg') {\n res.setHeader('Content-Type', 'image/svg+xml');\n } else if (ext === '.png') {\n res.setHeader('Content-Type', 'image/png');\n } else if (ext === '.jpg' || ext === '.jpeg') {\n res.setHeader('Content-Type', 'image/jpeg');\n }\n\n // Continue processing\n next();\n });\n\n // Setup static file serving with proper MIME types\n const staticOptions = {\n etag: true,\n lastModified: true,\n setHeaders: (res: express.Response, filePath: string) => {\n // Set the correct content type for different file extensions\n const ext = extname(filePath).toLowerCase();\n if (ext === '.css') {\n res.setHeader('Content-Type', 'text/css');\n } else if (ext === '.js') {\n res.setHeader('Content-Type', 'application/javascript');\n } else if (ext === '.html') {\n res.setHeader('Content-Type', 'text/html');\n } else if (ext === '.png') {\n res.setHeader('Content-Type', 'image/png');\n } else if (ext === '.jpg' || ext === '.jpeg') {\n res.setHeader('Content-Type', 'image/jpeg');\n } else if (ext === '.svg') {\n res.setHeader('Content-Type', 'image/svg+xml');\n }\n },\n };\n\n // Serve static assets from the client dist path\n // Client files are built into the CLI package's dist directory\n const clientPath = path.resolve(__dirname, '../../cli/dist');\n this.app.use(express.static(clientPath, staticOptions));\n\n // *** NEW: Mount the plugin route handler BEFORE static serving ***\n const pluginRouteHandler = createPluginRouteHandler(this.agents);\n this.app.use(pluginRouteHandler);\n\n // Mount the core API router under /api\n // This router handles all API endpoints including:\n // - /api/agents/* - Agent management and interactions\n // - /api/messaging/* - Message handling and channels\n // - /api/media/* - File uploads and media serving\n // - /api/memory/* - Memory management and retrieval\n // - /api/audio/* - Audio processing and transcription\n // - /api/server/* - Runtime and server management\n // - /api/tee/* - TEE (Trusted Execution Environment) operations\n // - /api/system/* - System configuration and health checks\n const apiRouter = createApiRouter(this.agents, this);\n this.app.use(\n '/api',\n (req: express.Request, _res: express.Response, next: express.NextFunction) => {\n if (req.path !== '/ping') {\n logger.debug(`API request: ${req.method} ${req.path}`);\n }\n next();\n },\n apiRouter,\n (err: any, req: Request, res: Response) => {\n logger.error(`API error: ${req.method} ${req.path}`, err);\n res.status(500).json({\n success: false,\n error: {\n message: err.message || 'Internal Server Error',\n code: err.code || 500,\n },\n });\n }\n );\n\n // Add a catch-all route for API 404s\n this.app.use((req, res, next) => {\n // Check if this is an API route that wasn't handled\n if (req.path.startsWith('/api/')) {\n // worms are going to hitting it all the time, use a reverse proxy if you need this type of logging\n //logger.warn(`API 404: ${req.method} ${req.path}`);\n res.status(404).json({\n success: false,\n error: {\n message: 'API endpoint not found',\n code: 404,\n },\n });\n } else {\n // Not an API route, continue to next middleware\n next();\n }\n });\n\n // Main fallback for the SPA - must be registered after all other routes\n // Use a final middleware that handles all unmatched routes\n (this.app as any).use((req: express.Request, res: express.Response) => {\n // For JavaScript requests that weren't handled by static middleware,\n // return a JavaScript response instead of HTML\n if (\n req.path.endsWith('.js') ||\n req.path.includes('.js?') ||\n req.path.match(/\\/[a-zA-Z0-9_-]+-[A-Za-z0-9]{8}\\.js/)\n ) {\n res.setHeader('Content-Type', 'application/javascript');\n return res.status(404).send(`// JavaScript module not found: ${req.path}`);\n }\n\n // For all other routes, serve the SPA's index.html\n // Client files are built into the CLI package's dist directory\n const cliDistPath = path.resolve(__dirname, '../../cli/dist');\n res.sendFile(path.join(cliDistPath, 'index.html'));\n });\n\n // Create HTTP server for Socket.io\n this.server = http.createServer(this.app);\n\n // Initialize Socket.io, passing the AgentServer instance\n this.socketIO = setupSocketIO(this.server, this.agents, this);\n\n logger.success('AgentServer HTTP server and Socket.IO initialized');\n } catch (error) {\n logger.error('Failed to complete server initialization:', error);\n throw error;\n }\n }\n\n /**\n * Registers an agent with the provided runtime.\n *\n * @param {IAgentRuntime} runtime - The runtime object containing agent information.\n * @throws {Error} if the runtime is null/undefined, if agentId is missing, if character configuration is missing,\n * or if there are any errors during registration.\n */\n public async registerAgent(runtime: IAgentRuntime) {\n try {\n if (!runtime) {\n throw new Error('Attempted to register null/undefined runtime');\n }\n if (!runtime.agentId) {\n throw new Error('Runtime missing agentId');\n }\n if (!runtime.character) {\n throw new Error('Runtime missing character configuration');\n }\n\n this.agents.set(runtime.agentId, runtime);\n logger.debug(`Agent ${runtime.character.name} (${runtime.agentId}) added to agents map`);\n\n // Auto-register the MessageBusConnector plugin\n try {\n if (messageBusConnectorPlugin) {\n await runtime.registerPlugin(messageBusConnectorPlugin);\n logger.info(\n `[AgentServer] Automatically registered MessageBusConnector for agent ${runtime.character.name}`\n );\n } else {\n logger.error(`[AgentServer] CRITICAL: MessageBusConnector plugin definition not found.`);\n }\n } catch (e) {\n logger.error(\n `[AgentServer] CRITICAL: Failed to register MessageBusConnector for agent ${runtime.character.name}`,\n e\n );\n // Decide if this is a fatal error for the agent.\n }\n\n // Register TEE plugin if present\n const teePlugin = runtime.plugins.find((p) => p.name === 'phala-tee-plugin');\n if (teePlugin) {\n logger.debug(`Found TEE plugin for agent ${runtime.agentId}`);\n if (teePlugin.providers) {\n for (const provider of teePlugin.providers) {\n runtime.registerProvider(provider);\n logger.debug(`Registered TEE provider: ${provider.name}`);\n }\n }\n if (teePlugin.actions) {\n for (const action of teePlugin.actions) {\n runtime.registerAction(action);\n logger.debug(`Registered TEE action: ${action.name}`);\n }\n }\n }\n\n logger.success(\n `Successfully registered agent ${runtime.character.name} (${runtime.agentId}) with core services.`\n );\n\n await this.addAgentToServer(DEFAULT_SERVER_ID, runtime.agentId);\n logger.info(\n `[AgentServer] Auto-associated agent ${runtime.character.name} with server ID: ${DEFAULT_SERVER_ID}`\n );\n } catch (error) {\n logger.error('Failed to register agent:', error);\n throw error;\n }\n }\n\n /**\n * Unregisters an agent from the system.\n *\n * @param {UUID} agentId - The unique identifier of the agent to unregister.\n * @returns {void}\n */\n public unregisterAgent(agentId: UUID) {\n if (!agentId) {\n logger.warn('[AGENT UNREGISTER] Attempted to unregister undefined or invalid agent runtime');\n return;\n }\n\n try {\n // Retrieve the agent before deleting it from the map\n const agent = this.agents.get(agentId);\n\n if (agent) {\n // Stop all services of the agent before unregistering it\n try {\n agent.stop().catch((stopError) => {\n logger.error(\n `[AGENT UNREGISTER] Error stopping agent services for ${agentId}:`,\n stopError\n );\n });\n logger.debug(`[AGENT UNREGISTER] Stopping services for agent ${agentId}`);\n } catch (stopError) {\n logger.error(`[AGENT UNREGISTER] Error initiating stop for agent ${agentId}:`, stopError);\n }\n }\n\n // Delete the agent from the map\n this.agents.delete(agentId);\n logger.debug(`Agent ${agentId} removed from agents map`);\n } catch (error) {\n logger.error(`Error removing agent ${agentId}:`, error);\n }\n }\n\n /**\n * Add middleware to the server's request handling pipeline\n * @param {ServerMiddleware} middleware - The middleware function to be registered\n */\n public registerMiddleware(middleware: ServerMiddleware) {\n this.app.use(middleware);\n }\n\n /**\n * Starts the server on the specified port.\n *\n * @param {number} port - The port number on which the server should listen.\n * @throws {Error} If the port is invalid or if there is an error while starting the server.\n */\n public start(port: number) {\n try {\n if (!port || typeof port !== 'number') {\n throw new Error(`Invalid port number: ${port}`);\n }\n\n logger.debug(`Starting server on port ${port}...`);\n logger.debug(`Current agents count: ${this.agents.size}`);\n logger.debug(`Environment: ${process.env.NODE_ENV}`);\n\n // Use http server instead of app.listen with explicit host binding and error handling\n // For tests and macOS compatibility, prefer 127.0.0.1 when specified\n const host = process.env.SERVER_HOST || '0.0.0.0';\n\n this.server\n .listen(port, host, () => {\n // Only show the dashboard URL in production mode\n if (process.env.NODE_ENV !== 'development') {\n // Display the dashboard URL with the correct port after the server is actually listening\n console.log(\n `\\x1b[32mStartup successful!\\nGo to the dashboard at \\x1b[1mhttp://localhost:${port}\\x1b[22m\\x1b[0m`\n );\n }\n\n // Add log for test readiness\n console.log(`AgentServer is listening on port ${port}`);\n\n logger.success(\n `REST API bound to ${host}:${port}. If running locally, access it at http://localhost:${port}.`\n );\n logger.debug(`Active agents: ${this.agents.size}`);\n this.agents.forEach((agent, id) => {\n logger.debug(`- Agent ${id}: ${agent.character.name}`);\n });\n })\n .on('error', (error: any) => {\n logger.error(`Failed to bind server to ${host}:${port}:`, error);\n\n // Provide helpful error messages for common issues\n if (error.code === 'EADDRINUSE') {\n logger.error(\n `Port ${port} is already in use. Please try a different port or stop the process using that port.`\n );\n } else if (error.code === 'EACCES') {\n logger.error(\n `Permission denied to bind to port ${port}. Try using a port above 1024 or running with appropriate permissions.`\n );\n } else if (error.code === 'EADDRNOTAVAIL') {\n logger.error(\n `Cannot bind to ${host}:${port} - address not available. Check if the host address is correct.`\n );\n }\n\n throw error;\n });\n\n // Enhanced graceful shutdown\n const gracefulShutdown = async () => {\n logger.info('Received shutdown signal, initiating graceful shutdown...');\n\n // Stop all agents first\n logger.debug('Stopping all agents...');\n for (const [id, agent] of this.agents.entries()) {\n try {\n await agent.stop();\n logger.debug(`Stopped agent ${id}`);\n } catch (error) {\n logger.error(`Error stopping agent ${id}:`, error);\n }\n }\n\n // Close database\n if (this.database) {\n try {\n await this.database.close();\n logger.info('Database closed.');\n } catch (error) {\n logger.error('Error closing database:', error);\n }\n }\n\n // Close server\n this.server.close(() => {\n logger.success('Server closed successfully');\n process.exit(0);\n });\n\n // Force close after timeout\n setTimeout(() => {\n logger.error('Could not close connections in time, forcing shutdown');\n process.exit(1);\n }, 5000);\n };\n\n process.on('SIGTERM', gracefulShutdown);\n process.on('SIGINT', gracefulShutdown);\n\n logger.debug('Shutdown handlers registered');\n } catch (error) {\n logger.error('Failed to start server:', error);\n throw error;\n }\n }\n\n /**\n * Stops the server if it is running. Closes the server connection,\n * stops the database connection, and logs a success message.\n */\n public async stop(): Promise<void> {\n if (this.server) {\n this.server.close(() => {\n logger.success('Server stopped');\n });\n }\n }\n\n // Central DB Data Access Methods\n async createServer(\n data: Omit<MessageServer, 'id' | 'createdAt' | 'updatedAt'>\n ): Promise<MessageServer> {\n return (this.database as any).createMessageServer(data);\n }\n\n async getServers(): Promise<MessageServer[]> {\n return (this.database as any).getMessageServers();\n }\n\n async getServerById(serverId: UUID): Promise<MessageServer | null> {\n return (this.database as any).getMessageServerById(serverId);\n }\n\n async getServerBySourceType(sourceType: string): Promise<MessageServer | null> {\n const servers = await (this.database as any).getMessageServers();\n const filtered = servers.filter((s: MessageServer) => s.sourceType === sourceType);\n return filtered.length > 0 ? filtered[0] : null;\n }\n\n async createChannel(\n data: Omit<MessageChannel, 'id' | 'createdAt' | 'updatedAt'> & { id?: UUID },\n participantIds?: UUID[]\n ): Promise<MessageChannel> {\n return (this.database as any).createChannel(data, participantIds);\n }\n\n async addParticipantsToChannel(channelId: UUID, userIds: UUID[]): Promise<void> {\n return (this.database as any).addChannelParticipants(channelId, userIds);\n }\n\n async getChannelsForServer(serverId: UUID): Promise<MessageChannel[]> {\n return (this.database as any).getChannelsForServer(serverId);\n }\n\n async getChannelDetails(channelId: UUID): Promise<MessageChannel | null> {\n return (this.database as any).getChannelDetails(channelId);\n }\n\n async getChannelParticipants(channelId: UUID): Promise<UUID[]> {\n return (this.database as any).getChannelParticipants(channelId);\n }\n\n async deleteMessage(messageId: UUID): Promise<void> {\n return (this.database as any).deleteMessage(messageId);\n }\n\n async updateChannel(\n channelId: UUID,\n updates: { name?: string; participantCentralUserIds?: UUID[]; metadata?: any }\n ): Promise<MessageChannel> {\n return (this.database as any).updateChannel(channelId, updates);\n }\n\n async deleteChannel(channelId: UUID): Promise<void> {\n return (this.database as any).deleteChannel(channelId);\n }\n\n async clearChannelMessages(channelId: UUID): Promise<void> {\n // Get all messages for the channel and delete them one by one\n const messages = await (this.database as any).getMessagesForChannel(channelId, 1000);\n for (const message of messages) {\n await (this.database as any).deleteMessage(message.id);\n }\n logger.info(`[AgentServer] Cleared all messages for central channel: ${channelId}`);\n }\n\n async findOrCreateCentralDmChannel(\n user1Id: UUID,\n user2Id: UUID,\n messageServerId: UUID\n ): Promise<MessageChannel> {\n return (this.database as any).findOrCreateDmChannel(user1Id, user2Id, messageServerId);\n }\n\n async createMessage(\n data: Omit<CentralRootMessage, 'id' | 'createdAt' | 'updatedAt'>\n ): Promise<CentralRootMessage> {\n const createdMessage = await (this.database as any).createMessage(data);\n\n // Get the channel details to find the server ID\n const channel = await this.getChannelDetails(createdMessage.channelId);\n if (channel) {\n // Emit to internal message bus for agent consumption\n const messageForBus: MessageServiceStructure = {\n id: createdMessage.id,\n channel_id: createdMessage.channelId,\n server_id: channel.messageServerId,\n author_id: createdMessage.authorId,\n content: createdMessage.content,\n raw_message: createdMessage.rawMessage,\n source_id: createdMessage.sourceId,\n source_type: createdMessage.sourceType,\n in_reply_to_message_id: createdMessage.inReplyToRootMessageId,\n created_at: createdMessage.createdAt.getTime(),\n metadata: createdMessage.metadata,\n };\n\n internalMessageBus.emit('new_message', messageForBus);\n logger.info(`[AgentServer] Published message ${createdMessage.id} to internal message bus`);\n }\n\n return createdMessage;\n }\n\n async getMessagesForChannel(\n channelId: UUID,\n limit: number = 50,\n beforeTimestamp?: Date\n ): Promise<CentralRootMessage[]> {\n return (this.database as any).getMessagesForChannel(channelId, limit, beforeTimestamp);\n }\n\n // Optional: Method to remove a participant\n async removeParticipantFromChannel(): Promise<void> {\n // Since we don't have a direct method for this, we'll need to handle it at the channel level\n logger.warn(\n `[AgentServer] Remove participant operation not directly supported in database adapter`\n );\n }\n\n // ===============================\n // Server-Agent Association Methods\n // ===============================\n\n /**\n * Add an agent to a server\n * @param {UUID} serverId - The server ID\n * @param {UUID} agentId - The agent ID to add\n */\n async addAgentToServer(serverId: UUID, agentId: UUID): Promise<void> {\n // First, verify the server exists\n const server = await this.getServerById(serverId);\n if (!server) {\n throw new Error(`Server ${serverId} not found`);\n }\n\n return (this.database as any).addAgentToServer(serverId, agentId);\n }\n\n /**\n * Remove an agent from a server\n * @param {UUID} serverId - The server ID\n * @param {UUID} agentId - The agent ID to remove\n */\n async removeAgentFromServer(serverId: UUID, agentId: UUID): Promise<void> {\n return (this.database as any).removeAgentFromServer(serverId, agentId);\n }\n\n /**\n * Get all agents associated with a server\n * @param {UUID} serverId - The server ID\n * @returns {Promise<UUID[]>} Array of agent IDs\n */\n async getAgentsForServer(serverId: UUID): Promise<UUID[]> {\n return (this.database as any).getAgentsForServer(serverId);\n }\n\n /**\n * Get all servers an agent belongs to\n * @param {UUID} agentId - The agent ID\n * @returns {Promise<UUID[]>} Array of server IDs\n */\n async getServersForAgent(agentId: UUID): Promise<UUID[]> {\n // This method isn't directly supported in the adapter, so we need to implement it differently\n const servers = await (this.database as any).getMessageServers();\n const serverIds = [];\n for (const server of servers) {\n const agents = await (this.database as any).getAgentsForServer(server.id);\n if (agents.includes(agentId)) {\n serverIds.push(server.id as never);\n }\n }\n return serverIds;\n }\n}\n\n// Export loader utilities\nexport {\n tryLoadFile,\n loadCharactersFromUrl,\n jsonToCharacter,\n loadCharacter,\n loadCharacterTryPath,\n hasValidRemoteUrls,\n loadCharacters,\n} from './loader';\n\n// Export types\nexport * from './types';\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { logger, validateUuid } from '@elizaos/core';\nimport bodyParser from 'body-parser';\nimport cors from 'cors';\nimport express from 'express';\nimport helmet from 'helmet';\nimport http from 'node:http';\nimport { match, MatchFunction } from 'path-to-regexp';\nimport { Server as SocketIOServer } from 'socket.io';\nimport type { AgentServer } from '../index';\n// Import new domain routers\nimport { agentsRouter } from './agents';\nimport { messagingRouter } from './messaging';\nimport { mediaRouter } from './media';\nimport { memoryRouter } from './memory';\nimport { audioRouter } from './audio';\nimport { runtimeRouter } from './runtime';\nimport { teeRouter } from './tee';\nimport { systemRouter } from './system';\n// NOTE: world router has been removed - functionality moved to messaging/spaces\nimport { SocketIORouter } from '../socketio';\nimport {\n securityMiddleware,\n validateContentTypeMiddleware,\n createApiRateLimit,\n} from './shared/middleware';\n\n/**\n * Sets up Socket.io server for real-time messaging\n * @param server HTTP Server instance\n * @param agents Map of agent runtimes\n */\n// Global reference to SocketIO router for log streaming\n// let socketIORouter: SocketIORouter | null = null; // This can be removed if router is managed within setupSocketIO scope correctly\n\nexport function setupSocketIO(\n server: http.Server,\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): SocketIOServer {\n const io = new SocketIOServer(server, {\n cors: {\n origin: '*',\n methods: ['GET', 'POST'],\n },\n });\n\n const centralSocketRouter = new SocketIORouter(agents, serverInstance);\n centralSocketRouter.setupListeners(io);\n\n setupLogStreaming(io, centralSocketRouter);\n\n // Old direct-to-agent processing path via sockets is now fully handled by SocketIORouter\n // which routes messages through the message store and internal bus.\n // The old code block is removed.\n\n return io;\n}\n\n// Setup log streaming integration with the logger\nfunction setupLogStreaming(io: SocketIOServer, router: SocketIORouter) {\n // Access the logger's destination to hook into log events\n const loggerInstance = logger as any;\n const destination = loggerInstance[Symbol.for('pino-destination')];\n\n if (destination && typeof destination.write === 'function') {\n // Store original write method\n const originalWrite = destination.write.bind(destination);\n\n // Override write method to broadcast logs via WebSocket\n destination.write = function (data: string | any) {\n // Call original write first\n originalWrite(data);\n\n // Parse and broadcast log entry\n try {\n let logEntry;\n if (typeof data === 'string') {\n logEntry = JSON.parse(data);\n } else {\n logEntry = data;\n }\n\n // Add timestamp if not present\n if (!logEntry.time) {\n logEntry.time = Date.now();\n }\n\n // Broadcast to WebSocket clients\n router.broadcastLog(io, logEntry);\n } catch (error) {\n // Ignore JSON parse errors for non-log data\n }\n };\n }\n}\n\n// Extracted function to handle plugin routes\nexport function createPluginRouteHandler(agents: Map<UUID, IAgentRuntime>): express.RequestHandler {\n return (req, res, next) => {\n logger.debug('Handling plugin request in the plugin route handler', {\n path: req.path,\n method: req.method,\n query: req.query,\n });\n\n // Skip standard agent API routes - these should be handled by agentRouter\n // Pattern: /agents/{uuid}/...\n const agentApiRoutePattern = /^\\/agents\\/[a-f0-9-]{36}\\/(?!plugins\\/)/i;\n if (agentApiRoutePattern.test(req.path)) {\n logger.debug(`Skipping agent API route in plugin handler: ${req.path}`);\n return next();\n }\n\n // Skip messages API routes - these should be handled by MessagesRouter\n if (req.path.startsWith('/api/messages/')) {\n return next();\n }\n\n // Debug output for JavaScript requests\n if (\n req.path.endsWith('.js') ||\n req.path.includes('.js?') ||\n req.path.match(/index-[A-Za-z0-9]{8}\\.js/) // Escaped dot for regex\n ) {\n logger.debug(`JavaScript request in plugin handler: ${req.method} ${req.path}`);\n res.setHeader('Content-Type', 'application/javascript');\n }\n\n if (agents.size === 0) {\n logger.debug('No agents available, skipping plugin route handling.');\n return next();\n }\n\n let handled = false;\n const agentIdFromQuery = req.query.agentId as UUID | undefined;\n const reqPath = req.path; // Path to match against plugin routes (e.g., /hello2)\n\n if (agentIdFromQuery && validateUuid(agentIdFromQuery)) {\n const runtime = agents.get(agentIdFromQuery);\n if (runtime) {\n logger.debug(\n `Agent-scoped request for Agent ID: ${agentIdFromQuery} from query. Path: ${reqPath}`\n );\n for (const route of runtime.routes) {\n if (handled) break;\n\n const methodMatches = req.method.toLowerCase() === route.type.toLowerCase();\n if (!methodMatches) continue;\n\n const routePath = route.path.startsWith('/') ? route.path : `/${route.path}`;\n\n if (routePath.endsWith('/*')) {\n const baseRoute = routePath.slice(0, -1);\n if (reqPath.startsWith(baseRoute)) {\n logger.debug(\n `Agent ${agentIdFromQuery} plugin wildcard route: [${route.type.toUpperCase()}] ${routePath} for request: ${reqPath}`\n );\n try {\n if (route.handler) {\n route.handler(req, res, runtime);\n handled = true;\n }\n } catch (error) {\n logger.error(\n `Error handling plugin wildcard route for agent ${agentIdFromQuery}: ${routePath}`,\n {\n error,\n path: reqPath,\n agent: agentIdFromQuery,\n }\n );\n if (!res.headersSent) {\n const status =\n (error instanceof Error && 'code' in error && error.code === 'ENOENT') ||\n (error instanceof Error && error.message?.includes('not found'))\n ? 404\n : 500;\n res.status(status).json({\n error:\n error instanceof Error ? error.message : 'Error processing wildcard route',\n });\n }\n handled = true;\n }\n }\n } else {\n logger.debug(\n `Agent ${agentIdFromQuery} attempting plugin route match: [${route.type.toUpperCase()}] ${routePath} vs request path: ${reqPath}`\n );\n let matcher: MatchFunction<object>;\n try {\n matcher = match(routePath, { decode: decodeURIComponent });\n } catch (err) {\n logger.error(\n `Invalid plugin route path syntax for agent ${agentIdFromQuery}: \"${routePath}\"`,\n err\n );\n continue;\n }\n\n const matched = matcher(reqPath);\n\n if (matched) {\n logger.debug(\n `Agent ${agentIdFromQuery} plugin route matched: [${route.type.toUpperCase()}] ${routePath} vs request path: ${reqPath}`\n );\n req.params = { ...(matched.params || {}) };\n try {\n if (route.handler) {\n route.handler(req, res, runtime);\n handled = true;\n }\n } catch (error) {\n logger.error(\n `Error handling plugin route for agent ${agentIdFromQuery}: ${routePath}`,\n {\n error,\n path: reqPath,\n agent: agentIdFromQuery,\n params: req.params,\n }\n );\n if (!res.headersSent) {\n const status =\n (error instanceof Error && 'code' in error && error.code === 'ENOENT') ||\n (error instanceof Error && error.message?.includes('not found'))\n ? 404\n : 500;\n res.status(status).json({\n error: error instanceof Error ? error.message : 'Error processing route',\n });\n }\n handled = true;\n }\n }\n }\n } // End route loop\n } else {\n logger.warn(\n `Agent ID ${agentIdFromQuery} provided in query, but agent runtime not found. Path: ${reqPath}.`\n );\n // Return a specific error instead of passing to next middleware\n res.status(404).json({\n success: false,\n error: {\n message: 'Agent not found',\n code: 'AGENT_NOT_FOUND',\n },\n });\n return;\n }\n } else if (agentIdFromQuery && !validateUuid(agentIdFromQuery)) {\n logger.warn(`Invalid Agent ID format in query: ${agentIdFromQuery}. Path: ${reqPath}.`);\n // Return a specific error for invalid UUID format\n res.status(400).json({\n success: false,\n error: {\n message: 'Invalid agent ID format',\n code: 'INVALID_AGENT_ID',\n },\n });\n return;\n } else {\n // No agentId in query, or it was invalid. Try matching globally for any agent that might have this route.\n // This allows for non-agent-specific plugin routes if any plugin defines them.\n logger.debug(`No valid agentId in query. Trying global match for path: ${reqPath}`);\n for (const [_, runtime] of agents) {\n // Iterate over all agents\n if (handled) break; // If handled by a previous agent's route (e.g. specific match)\n\n for (const route of runtime.routes) {\n if (handled) break;\n\n const methodMatches = req.method.toLowerCase() === route.type.toLowerCase();\n if (!methodMatches) continue;\n\n const routePath = route.path.startsWith('/') ? route.path : `/${route.path}`;\n\n // Do not allow agent-specific routes (containing placeholders like :id) to be matched globally\n if (routePath.includes(':')) {\n continue;\n }\n\n if (routePath.endsWith('/*')) {\n const baseRoute = routePath.slice(0, -1);\n if (reqPath.startsWith(baseRoute)) {\n logger.debug(\n `Global plugin wildcard route: [${route.type.toUpperCase()}] ${routePath} (Agent: ${runtime.agentId}) for request: ${reqPath}`\n );\n try {\n route?.handler?.(req, res, runtime);\n handled = true;\n } catch (error) {\n logger.error(\n `Error handling global plugin wildcard route ${routePath} (Agent: ${runtime.agentId})`,\n { error, path: reqPath }\n );\n if (!res.headersSent) {\n const status =\n (error instanceof Error && 'code' in error && error.code === 'ENOENT') ||\n (error instanceof Error && error.message?.includes('not found'))\n ? 404\n : 500;\n res.status(status).json({\n error:\n error instanceof Error ? error.message : 'Error processing wildcard route',\n });\n }\n handled = true;\n }\n }\n } else if (reqPath === routePath) {\n // Exact match for global routes\n logger.debug(\n `Global plugin route matched: [${route.type.toUpperCase()}] ${routePath} (Agent: ${runtime.agentId}) for request: ${reqPath}`\n );\n try {\n route?.handler?.(req, res, runtime);\n handled = true;\n } catch (error) {\n logger.error(\n `Error handling global plugin route ${routePath} (Agent: ${runtime.agentId})`,\n { error, path: reqPath }\n );\n if (!res.headersSent) {\n const status =\n (error instanceof Error && 'code' in error && error.code === 'ENOENT') ||\n (error instanceof Error && error.message?.includes('not found'))\n ? 404\n : 500;\n res.status(status).json({\n error: error instanceof Error ? error.message : 'Error processing route',\n });\n }\n handled = true;\n }\n }\n } // End route loop for global matching\n } // End agent loop for global matching\n }\n\n if (handled) {\n return;\n }\n\n logger.debug(`No plugin route handled ${req.method} ${req.path}, passing to next middleware.`);\n next();\n };\n}\n\n/**\n * Creates an API router with various endpoints and middleware.\n * @param {Map<UUID, IAgentRuntime>} agents - Map of agents with UUID as key and IAgentRuntime as value.\n * @param {AgentServer} [server] - Optional AgentServer instance.\n * @returns {express.Router} The configured API router.\n */\nexport function createApiRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer // AgentServer is already serverInstance here\n): express.Router {\n const router = express.Router();\n\n // API-specific security headers (supplementing main app helmet)\n // Let the main app's environment-aware CSP handle all routes\n // Only add non-CSP security headers for API routes\n router.use(\n helmet({\n // Disable CSP here - let main app handle it with environment awareness\n contentSecurityPolicy: false,\n // API-specific headers only\n crossOriginResourcePolicy: { policy: 'cross-origin' },\n referrerPolicy: { policy: 'no-referrer' },\n })\n );\n\n // API-specific CORS configuration\n router.use(\n cors({\n origin: process.env.API_CORS_ORIGIN || process.env.CORS_ORIGIN || false, // More restrictive for API\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-API-KEY'],\n exposedHeaders: ['X-Total-Count'],\n maxAge: 86400, // Cache preflight for 24 hours\n })\n );\n\n // Rate limiting - should be early in middleware chain\n router.use(createApiRateLimit());\n\n // Additional security middleware\n router.use(securityMiddleware());\n\n // Content type validation for write operations\n router.use(validateContentTypeMiddleware());\n\n // Body parsing middleware\n router.use(\n bodyParser.json({\n limit: process.env.EXPRESS_MAX_PAYLOAD || '100kb',\n })\n );\n router.use(\n bodyParser.urlencoded({\n extended: true,\n limit: process.env.EXPRESS_MAX_PAYLOAD || '100kb',\n })\n );\n router.use(\n express.json({\n limit: process.env.EXPRESS_MAX_PAYLOAD || '100kb',\n })\n );\n\n // Setup new domain-based routes\n // Mount agents router at /agents - handles agent creation, management, and interactions\n router.use('/agents', agentsRouter(agents, serverInstance));\n\n // Mount messaging router at /messaging - handles messages, channels, and chat functionality\n router.use('/messaging', messagingRouter(agents, serverInstance));\n\n // Mount media router at /media - handles file uploads, downloads, and media management\n router.use('/media', mediaRouter());\n\n // Mount memory router at /memory - handles agent memory storage and retrieval\n router.use('/memory', memoryRouter(agents, serverInstance));\n\n // Mount audio router at /audio - handles audio processing, transcription, and voice operations\n router.use('/audio', audioRouter(agents));\n\n // Mount runtime router at /server - handles server runtime operations and management\n router.use('/server', runtimeRouter(agents, serverInstance));\n\n // Mount TEE router at /tee - handles Trusted Execution Environment operations\n router.use('/tee', teeRouter());\n\n // Mount system router at /system - handles system configuration, health checks, and environment\n router.use('/system', systemRouter());\n\n // NOTE: /world routes have been removed - functionality moved to messaging/spaces\n\n // NOTE: Legacy route aliases removed to prevent duplicates\n // Use proper domain routes: /messaging, /system, /tee\n\n // Add the plugin routes middleware AFTER specific routers\n router.use(createPluginRouteHandler(agents));\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { createAgentCrudRouter } from './crud';\nimport { createAgentLifecycleRouter } from './lifecycle';\nimport { createAgentWorldsRouter } from './worlds';\nimport { createAgentPanelsRouter } from './panels';\nimport { createAgentLogsRouter } from './logs';\nimport { createAgentMemoryRouter } from '../memory/agents';\n\n/**\n * Creates the agents router for agent lifecycle and management operations\n */\nexport function agentsRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n // Mount CRUD operations at root level\n router.use('/', createAgentCrudRouter(agents, serverInstance));\n\n // Mount lifecycle operations\n router.use('/', createAgentLifecycleRouter(agents, serverInstance));\n\n // Mount world management operations\n router.use('/', createAgentWorldsRouter(agents));\n\n // Mount panels operations\n router.use('/', createAgentPanelsRouter(agents));\n\n // Mount logs operations\n router.use('/', createAgentLogsRouter(agents));\n\n // Mount memory operations\n router.use('/', createAgentMemoryRouter(agents, serverInstance));\n\n return router;\n}\n","import type { Agent, Character, IAgentRuntime, UUID } from '@elizaos/core';\nimport {\n validateUuid,\n logger,\n stringToUuid,\n getSalt,\n encryptObjectValues,\n encryptStringValue,\n} from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent CRUD operations\n */\nexport function createAgentCrudRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n const db = serverInstance?.database;\n\n // List all agents with minimal details\n router.get('/', async (_, res) => {\n try {\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n const allAgents = await db.getAgents();\n const runtimes = Array.from(agents.keys());\n\n // Return only minimal agent data\n const response = allAgents\n .map((agent: Partial<Agent>) => ({\n id: agent.id,\n name: agent.name || '',\n characterName: agent.name || '', // Since Agent extends Character, agent.name is the character name\n bio: agent.bio?.[0] ?? '',\n status: agent.id && runtimes.includes(agent.id) ? 'active' : 'inactive',\n }))\n .filter((agent) => agent.id) // Filter out agents without IDs\n .sort((a: any, b: any) => {\n if (a.status === b.status) {\n return a.name.localeCompare(b.name);\n }\n return a.status === 'active' ? -1 : 1;\n });\n\n sendSuccess(res, { agents: response });\n } catch (error) {\n logger.error('[AGENTS LIST] Error retrieving agents:', error);\n sendError(\n res,\n 500,\n '500',\n 'Error retrieving agents',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Get specific agent details\n router.get('/:agentId', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n try {\n const agent = await db.getAgent(agentId);\n if (!agent) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n const runtime = agents.get(agentId);\n const response = {\n ...agent,\n status: runtime ? 'active' : 'inactive',\n };\n\n sendSuccess(res, response);\n } catch (error) {\n logger.error('[AGENT GET] Error retrieving agent:', error);\n sendError(\n res,\n 500,\n '500',\n 'Error retrieving agent',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Create new agent\n router.post('/', async (req, res) => {\n logger.debug('[AGENT CREATE] Creating new agent');\n const { characterPath, characterJson } = req.body;\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n try {\n let character: Character;\n\n if (characterJson) {\n logger.debug('[AGENT CREATE] Parsing character from JSON');\n character = await serverInstance?.jsonToCharacter(characterJson);\n } else if (characterPath) {\n logger.debug(`[AGENT CREATE] Loading character from path: ${characterPath}`);\n character = await serverInstance?.loadCharacterTryPath(characterPath);\n } else {\n throw new Error('No character configuration provided');\n }\n\n if (!character) {\n throw new Error('Failed to create character configuration');\n }\n\n if (character.settings?.secrets) {\n logger.debug('[AGENT CREATE] Encrypting secrets');\n const salt = getSalt();\n character.settings.secrets = encryptObjectValues(character.settings.secrets, salt);\n }\n\n const ensureAgentExists = async (character: Character) => {\n const agentId = stringToUuid(character.name);\n let agent = await db.getAgent(agentId);\n if (!agent) {\n await db.createAgent({ ...character, id: agentId });\n agent = await db.getAgent(agentId);\n }\n return agent;\n };\n\n const newAgent = await ensureAgentExists(character);\n\n if (!newAgent) {\n throw new Error(`Failed to create agent ${character.name}`);\n }\n\n res.status(201).json({\n success: true,\n data: {\n id: newAgent.id,\n character: character,\n },\n });\n logger.success(`[AGENT CREATE] Successfully created agent: ${character.name}`);\n } catch (error) {\n logger.error('[AGENT CREATE] Error creating agent:', error);\n res.status(400).json({\n success: false,\n error: {\n code: 'CREATE_ERROR',\n message: error instanceof Error ? error.message : 'Error creating agent',\n details: error instanceof Error ? error.message : String(error),\n },\n });\n }\n });\n\n // Update agent\n router.patch('/:agentId', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n const updates = req.body;\n\n try {\n if (updates.settings?.secrets) {\n const salt = getSalt();\n const encryptedSecrets: Record<string, string | null> = {};\n Object.entries(updates.settings.secrets).forEach(([key, value]) => {\n if (value === null) {\n encryptedSecrets[key] = null;\n } else if (typeof value === 'string') {\n encryptedSecrets[key] = encryptStringValue(value, salt);\n } else {\n encryptedSecrets[key] = value as string;\n }\n });\n updates.settings.secrets = encryptedSecrets;\n }\n\n if (Object.keys(updates).length > 0) {\n await db.updateAgent(agentId, updates);\n }\n\n const updatedAgent = await db.getAgent(agentId);\n\n const isActive = !!agents.get(agentId);\n if (isActive && updatedAgent) {\n serverInstance?.unregisterAgent(agentId);\n await serverInstance?.startAgent(updatedAgent);\n }\n\n const runtime = agents.get(agentId);\n const status = runtime ? 'active' : 'inactive';\n\n sendSuccess(res, { ...updatedAgent, status });\n } catch (error) {\n logger.error('[AGENT UPDATE] Error updating agent:', error);\n sendError(\n res,\n 500,\n 'UPDATE_ERROR',\n 'Error updating agent',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Delete agent\n router.delete('/:agentId', async (req, res) => {\n logger.debug(`[AGENT DELETE] Received request to delete agent with ID: ${req.params.agentId}`);\n\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n logger.error(`[AGENT DELETE] Invalid agent ID format: ${req.params.agentId}`);\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n logger.debug(`[AGENT DELETE] Validated agent ID: ${agentId}, proceeding with deletion`);\n\n try {\n const agent = await db.getAgent(agentId);\n if (!agent) {\n logger.warn(`[AGENT DELETE] Agent not found: ${agentId}`);\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n logger.debug(`[AGENT DELETE] Agent found: ${agent.name} (${agentId})`);\n } catch (checkError) {\n logger.error(`[AGENT DELETE] Error checking if agent exists: ${agentId}`, checkError);\n }\n\n const timeoutId = setTimeout(() => {\n logger.warn(`[AGENT DELETE] Operation taking longer than expected for agent: ${agentId}`);\n if (!res.headersSent) {\n res.status(202).json({\n success: true,\n partial: true,\n message:\n 'Agent deletion initiated but taking longer than expected. The operation will continue in the background.',\n });\n }\n }, 10000);\n\n const MAX_RETRIES = 2;\n let retryCount = 0;\n let lastError: unknown = null;\n\n while (retryCount <= MAX_RETRIES) {\n try {\n const runtime = agents.get(agentId);\n if (runtime) {\n logger.debug(`[AGENT DELETE] Agent ${agentId} is running, unregistering from server`);\n try {\n serverInstance?.unregisterAgent(agentId);\n logger.debug(`[AGENT DELETE] Agent ${agentId} unregistered successfully`);\n } catch (stopError) {\n logger.error(`[AGENT DELETE] Error stopping agent ${agentId}:`, stopError);\n }\n } else {\n logger.debug(`[AGENT DELETE] Agent ${agentId} was not running, no need to unregister`);\n }\n\n logger.debug(`[AGENT DELETE] Calling database deleteAgent method for agent: ${agentId}`);\n\n const deleteResult = await db.deleteAgent(agentId);\n logger.debug(`[AGENT DELETE] Database deleteAgent result: ${JSON.stringify(deleteResult)}`);\n\n clearTimeout(timeoutId);\n\n logger.success(`[AGENT DELETE] Successfully deleted agent: ${agentId}`);\n\n if (!res.headersSent) {\n res.status(204).send();\n }\n\n return;\n } catch (error) {\n lastError = error;\n retryCount++;\n\n logger.error(\n `[AGENT DELETE] Error deleting agent ${agentId} (attempt ${retryCount}/${MAX_RETRIES + 1}):`,\n error\n );\n\n if (retryCount > MAX_RETRIES) {\n break;\n }\n\n const delay = 1000 * Math.pow(2, retryCount - 1);\n logger.debug(`[AGENT DELETE] Waiting ${delay}ms before retry ${retryCount}`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n clearTimeout(timeoutId);\n\n if (!res.headersSent) {\n let statusCode = 500;\n let errorMessage = 'Error deleting agent';\n\n if (lastError instanceof Error) {\n const message = lastError.message;\n\n if (message.includes('foreign key constraint')) {\n errorMessage = 'Cannot delete agent because it has active references in the system';\n statusCode = 409;\n } else if (message.includes('timed out')) {\n errorMessage = 'Agent deletion operation timed out';\n statusCode = 408;\n }\n }\n\n res.status(statusCode).json({\n success: false,\n error: {\n code: 'DELETE_ERROR',\n message: errorMessage,\n details: lastError instanceof Error ? lastError.message : String(lastError),\n },\n });\n }\n });\n\n return router;\n}\n","import express from 'express';\n\n/**\n * Sends a standardized error response\n */\nexport const sendError = (\n res: express.Response,\n status: number,\n code: string,\n message: string,\n details?: string\n) => {\n res.status(status).json({\n success: false,\n error: {\n code,\n message,\n ...(details && { details }),\n },\n });\n};\n\n/**\n * Sends a standardized success response\n */\nexport const sendSuccess = (res: express.Response, data: any, status = 200) => {\n res.status(status).json({\n success: true,\n data,\n });\n};\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { validateUuid, logger } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent lifecycle operations (start, stop, status)\n */\nexport function createAgentLifecycleRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n const db = serverInstance?.database;\n\n // Start an existing agent\n router.post('/:agentId/start', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n try {\n const agent = await db.getAgent(agentId);\n\n if (!agent) {\n logger.debug('[AGENT START] Agent not found');\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n const isActive = !!agents.get(agentId);\n\n if (isActive) {\n logger.debug(`[AGENT START] Agent ${agentId} is already running`);\n return sendSuccess(res, {\n id: agentId,\n name: agent.name,\n status: 'active',\n });\n }\n\n await serverInstance?.startAgent(agent);\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n throw new Error('Failed to start agent');\n }\n\n logger.debug(`[AGENT START] Successfully started agent: ${agent.name}`);\n sendSuccess(res, {\n id: agentId,\n name: agent.name,\n status: 'active',\n });\n } catch (error) {\n logger.error('[AGENT START] Error starting agent:', error);\n sendError(\n res,\n 500,\n 'START_ERROR',\n 'Error starting agent',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Stop an existing agent\n router.post('/:agentId/stop', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n logger.debug('[AGENT STOP] Invalid agent ID format');\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n serverInstance?.unregisterAgent(agentId);\n\n logger.debug(`[AGENT STOP] Successfully stopped agent: ${runtime.character.name} (${agentId})`);\n\n sendSuccess(res, {\n message: 'Agent stopped',\n });\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { validateUuid, logger, createUniqueUuid } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent world management operations\n */\nexport function createAgentWorldsRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Get all worlds\n router.get('/worlds', async (_req, res) => {\n try {\n const runtime = Array.from(agents.values())[0];\n\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'No active agents found to get worlds');\n }\n const worlds = await runtime.getAllWorlds();\n sendSuccess(res, { worlds });\n } catch (error) {\n logger.error('[WORLDS LIST] Error retrieving worlds:', error);\n sendError(\n res,\n 500,\n '500',\n 'Error retrieving worlds',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Helper function to create a world\n const createWorldHelper = async (\n runtime: IAgentRuntime,\n req: express.Request,\n res: express.Response\n ) => {\n try {\n const { name, serverId, metadata } = req.body;\n\n if (!name) {\n return sendError(res, 400, 'BAD_REQUEST', 'World name is required');\n }\n\n const worldId = createUniqueUuid(runtime, `world-${Date.now()}`);\n\n await runtime.createWorld({\n id: worldId,\n name,\n agentId: runtime.agentId,\n serverId: serverId || `server-${Date.now()}`,\n metadata,\n });\n\n const world = (await runtime.getAllWorlds()).find((w) => w.id === worldId);\n\n sendSuccess(res, { world }, 201);\n } catch (error) {\n logger.error('[WORLD CREATE] Error creating world:', error);\n sendError(\n res,\n 500,\n '500',\n 'Error creating world',\n error instanceof Error ? error.message : String(error)\n );\n }\n };\n\n // Create new world for specific agent\n router.post('/:agentId/worlds', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n await createWorldHelper(runtime, req, res);\n });\n\n // Update world properties\n router.patch('/:agentId/worlds/:worldId', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n const worldId = validateUuid(req.params.worldId);\n\n if (!agentId || !worldId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID or world ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const world = (await runtime.getAllWorlds()).find((w) => w.id === worldId);\n\n if (!world) {\n return sendError(res, 404, 'NOT_FOUND', 'World not found');\n }\n\n const { name, metadata } = req.body;\n\n const updatedWorld = {\n ...world,\n name: name !== undefined ? name : world.name,\n metadata:\n metadata !== undefined\n ? world.metadata\n ? { ...world.metadata, ...metadata }\n : metadata\n : world.metadata,\n };\n\n await runtime.updateWorld(updatedWorld);\n const refreshedWorld = (await runtime.getAllWorlds()).find((w) => w.id === worldId);\n sendSuccess(res, { world: refreshedWorld });\n } catch (error) {\n logger.error('[WORLD UPDATE] Error updating world:', error);\n sendError(\n res,\n 500,\n '500',\n 'Error updating world',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { validateUuid, logger } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent panels and plugin routes management\n */\nexport function createAgentPanelsRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Get Agent Panels (public GET routes)\n router.get('/:agentId/panels', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const publicPanels = runtime.plugins\n .flatMap((plugin) => plugin.routes || [])\n .filter((route) => route.public === true && route.type === 'GET' && route.name)\n .map((route) => ({\n name: route.name,\n path: `/api${route.path.startsWith('/') ? route.path : `/${route.path}`}?agentId=${agentId}`,\n }));\n\n sendSuccess(res, publicPanels);\n } catch (error) {\n logger.error(`[AGENT PANELS] Error retrieving panels for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'PANEL_ERROR',\n 'Error retrieving agent panels',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID, Log } from '@elizaos/core';\nimport { validateUuid, logger } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent logs management\n */\nexport function createAgentLogsRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Get Agent Logs\n router.get('/:agentId/logs', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n const { roomId, type, count, offset, excludeTypes } = req.query;\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n if (roomId) {\n const roomIdValidated = validateUuid(roomId as string);\n if (!roomIdValidated) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid room ID format');\n }\n }\n\n try {\n const logs: Log[] = await runtime.getLogs({\n entityId: agentId,\n roomId: roomId ? (roomId as UUID) : undefined,\n type: type ? (type as string) : undefined,\n count: count ? Number(count) : undefined,\n offset: offset ? Number(offset) : undefined,\n });\n\n // Filter out excluded types if specified\n let filteredLogs = logs;\n if (excludeTypes) {\n const excludeTypesArray = Array.isArray(excludeTypes)\n ? (excludeTypes as string[])\n : [excludeTypes as string];\n\n filteredLogs = logs.filter((log) => {\n // Check the log type\n if (log.type && excludeTypesArray.includes(log.type)) {\n return false;\n }\n\n // Check the modelType in the log body for model-related operations\n if (log.body && typeof log.body === 'object') {\n const body = log.body as any;\n if (\n body.modelType &&\n excludeTypesArray.some((excludeType) =>\n body.modelType.toLowerCase().includes(excludeType.toLowerCase())\n )\n ) {\n return false;\n }\n }\n\n return true;\n });\n }\n\n sendSuccess(res, filteredLogs);\n } catch (error) {\n logger.error(`[AGENT LOGS] Error retrieving logs for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'LOG_ERROR',\n 'Error retrieving agent logs',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Delete specific log\n router.delete('/:agentId/logs/:logId', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n const logId = validateUuid(req.params.logId);\n if (!agentId || !logId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent or log ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n await runtime.deleteLog(logId);\n res.status(204).send();\n } catch (error) {\n logger.error(`[LOG DELETE] Error deleting log ${logId} for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'DELETE_ERROR',\n 'Failed to delete log',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID, Memory, MemoryMetadata } from '@elizaos/core';\nimport { MemoryType, createUniqueUuid } from '@elizaos/core';\nimport { validateUuid, logger } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\n/**\n * Agent memory management functionality\n */\nexport function createAgentMemoryRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Get memories for a specific room\n router.get('/:agentId/rooms/:roomId/memories', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n const roomId = validateUuid(req.params.roomId);\n\n if (!agentId || !roomId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID or room ID format');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const limit = req.query.limit ? Number.parseInt(req.query.limit as string, 10) : 20;\n const before = req.query.before\n ? Number.parseInt(req.query.before as string, 10)\n : Date.now();\n const includeEmbedding = req.query.includeEmbedding === 'true';\n const tableName = (req.query.tableName as string) || 'messages';\n\n const memories = await runtime.getMemories({\n tableName,\n roomId,\n count: limit,\n end: before,\n });\n\n const cleanMemories = includeEmbedding\n ? memories\n : memories.map((memory) => ({\n ...memory,\n embedding: undefined,\n }));\n\n sendSuccess(res, { memories: cleanMemories });\n } catch (error) {\n logger.error('[MEMORIES GET] Error retrieving memories for room:', error);\n sendError(\n res,\n 500,\n '500',\n 'Failed to retrieve memories',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Get all memories for an agent\n router.get('/:agentId/memories', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const tableName = (req.query.tableName as string) || 'messages';\n const includeEmbedding = req.query.includeEmbedding === 'true';\n\n // Handle both roomId and channelId parameters\n let roomIdToUse: UUID | undefined;\n\n if (req.query.channelId) {\n // Convert channelId to the agent's unique roomId\n const channelId = validateUuid(req.query.channelId as string);\n if (!channelId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid channel ID format');\n }\n // Use createUniqueUuid to generate the same roomId the agent uses\n roomIdToUse = createUniqueUuid(runtime, channelId);\n logger.info(\n `[AGENT MEMORIES] Converting channelId ${channelId} to roomId ${roomIdToUse} for agent ${agentId}`\n );\n } else if (req.query.roomId) {\n // Backward compatibility: still accept roomId directly\n const roomId = validateUuid(req.query.roomId as string);\n if (!roomId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid room ID format');\n }\n roomIdToUse = roomId;\n }\n\n const memories = await runtime.getMemories({\n agentId,\n tableName,\n roomId: roomIdToUse,\n });\n\n const cleanMemories = includeEmbedding\n ? memories\n : memories.map((memory) => ({\n ...memory,\n embedding: undefined,\n }));\n sendSuccess(res, { memories: cleanMemories });\n } catch (error) {\n logger.error(`[AGENT MEMORIES] Error retrieving memories for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'MEMORY_ERROR',\n 'Error retrieving agent memories',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Update a specific memory for an agent\n router.patch('/:agentId/memories/:memoryId', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n const memoryId = validateUuid(req.params.memoryId);\n\n const { id: _idFromData, ...restOfMemoryData } = req.body;\n\n if (!agentId || !memoryId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID or memory ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n // Construct memoryToUpdate ensuring it satisfies Partial<Memory> & { id: UUID }\n const memoryToUpdate: Partial<Memory> & { id: UUID; metadata?: MemoryMetadata } = {\n // Explicitly set the required id using the validated path parameter\n id: memoryId,\n // Spread other properties from the request body.\n // Cast to Partial<Memory> to align with the base type.\n ...(restOfMemoryData as Partial<Memory>),\n // If specific fields from restOfMemoryData need type assertion (e.g., to UUID),\n // they should be handled here or ensured by upstream validation.\n // For example, if agentId from body is always expected as UUID:\n agentId: restOfMemoryData.agentId\n ? validateUuid(restOfMemoryData.agentId as string) || undefined\n : agentId,\n roomId: restOfMemoryData.roomId\n ? validateUuid(restOfMemoryData.roomId as string) || undefined\n : undefined,\n entityId: restOfMemoryData.entityId\n ? validateUuid(restOfMemoryData.entityId as string) || undefined\n : undefined,\n worldId: restOfMemoryData.worldId\n ? validateUuid(restOfMemoryData.worldId as string) || undefined\n : undefined,\n // Ensure metadata, if provided, conforms to MemoryMetadata\n metadata: restOfMemoryData.metadata as MemoryMetadata | undefined,\n };\n\n // Remove undefined fields that might have been explicitly set to undefined by casting above,\n // if the updateMemory implementation doesn't handle them gracefully.\n Object.keys(memoryToUpdate).forEach((key) => {\n if ((memoryToUpdate as any)[key] === undefined) {\n delete (memoryToUpdate as any)[key];\n }\n });\n\n await runtime.updateMemory(memoryToUpdate);\n\n logger.success(`[MEMORY UPDATE] Successfully updated memory ${memoryId}`);\n sendSuccess(res, { id: memoryId, message: 'Memory updated successfully' });\n } catch (error) {\n logger.error(`[MEMORY UPDATE] Error updating memory ${memoryId}:`, error);\n sendError(\n res,\n 500,\n 'UPDATE_ERROR',\n 'Failed to update memory',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Delete all memories for an agent\n router.delete('/:agentId/memories', async (req, res) => {\n try {\n const agentId = validateUuid(req.params.agentId);\n\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n const deletedCount = (await runtime.getAllMemories()).length;\n await runtime.clearAllAgentMemories();\n\n sendSuccess(res, { deletedCount, message: 'All agent memories cleared successfully' });\n } catch (error) {\n logger.error('[DELETE ALL AGENT MEMORIES] Error deleting all agent memories:', error);\n sendError(\n res,\n 500,\n 'DELETE_ERROR',\n 'Error deleting all agent memories',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Delete all memories for a room\n router.delete('/:agentId/memories/all/:roomId', async (req, res) => {\n try {\n const agentId = validateUuid(req.params.agentId);\n const roomId = validateUuid(req.params.roomId);\n\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID');\n }\n\n if (!roomId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid room ID');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n await runtime.deleteAllMemories(roomId, MemoryType.MESSAGE);\n await runtime.deleteAllMemories(roomId, MemoryType.DOCUMENT);\n\n res.status(204).send();\n } catch (error) {\n logger.error('[DELETE ALL MEMORIES] Error deleting all memories:', error);\n sendError(\n res,\n 500,\n 'DELETE_ERROR',\n 'Error deleting all memories',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { createMessagingCoreRouter } from './core';\nimport { createServersRouter } from './servers';\nimport { createChannelsRouter } from './channels';\n\n/**\n * Creates the messaging router for all communication functionality\n */\nexport function messagingRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n if (!serverInstance) {\n throw new Error('ServerInstance is required for messaging router');\n }\n\n // Mount core messaging functionality at root level\n router.use('/', createMessagingCoreRouter(serverInstance));\n\n // Mount server management functionality\n router.use('/', createServersRouter(serverInstance));\n\n // Mount channel management functionality\n router.use('/', createChannelsRouter(agents, serverInstance));\n\n return router;\n}\n","import { logger, validateUuid, type UUID } from '@elizaos/core';\nimport express from 'express';\nimport internalMessageBus from '../../bus'; // Import the bus\nimport type { AgentServer } from '../../index';\nimport type { MessageServiceStructure as MessageService } from '../../types';\n\nconst DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID; // Single default server\n\n/**\n * Core messaging functionality - message submission and ingestion\n */\nexport function createMessagingCoreRouter(serverInstance: AgentServer): express.Router {\n const router = express.Router();\n\n // Endpoint for AGENT REPLIES or direct submissions to the central bus FROM AGENTS/SYSTEM\n (router as any).post('/submit', async (req: express.Request, res: express.Response) => {\n const {\n channel_id,\n server_id, // This is the server_id\n author_id, // This should be the agent's runtime.agentId or a dedicated central ID for the agent\n content,\n in_reply_to_message_id, // This is a root_message.id\n source_type,\n raw_message,\n metadata, // Should include agent_name if author_id is agent's runtime.agentId\n } = req.body;\n\n // Special handling for default server ID \"0\"\n const isValidServerId = server_id === DEFAULT_SERVER_ID || validateUuid(server_id);\n\n if (\n !validateUuid(channel_id) ||\n !validateUuid(author_id) ||\n !content ||\n !isValidServerId ||\n !source_type ||\n !raw_message\n ) {\n return res.status(400).json({\n success: false,\n error:\n 'Missing required fields: channel_id, server_id, author_id, content, source_type, raw_message',\n });\n }\n\n // Validate in_reply_to_message_id only if it's provided\n if (in_reply_to_message_id && !validateUuid(in_reply_to_message_id)) {\n return res.status(400).json({\n success: false,\n error: 'Invalid in_reply_to_message_id format',\n });\n }\n\n try {\n const newRootMessageData = {\n channelId: validateUuid(channel_id)!,\n authorId: validateUuid(author_id)!,\n content: content as string,\n rawMessage: raw_message,\n sourceType: source_type || 'agent_response',\n inReplyToRootMessageId: in_reply_to_message_id\n ? validateUuid(in_reply_to_message_id) || undefined\n : undefined,\n metadata,\n };\n // Use AgentServer's method to create the message in the DB\n const createdMessage = await serverInstance.createMessage(newRootMessageData);\n\n // Emit to SocketIO for real-time GUI updates\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channel_id).emit('messageBroadcast', {\n senderId: author_id, // This is the agent's ID\n senderName: metadata?.agentName || 'Agent',\n text: content,\n roomId: channel_id, // For SocketIO, room is the central channel_id\n serverId: server_id, // Client layer uses serverId\n createdAt: new Date(createdMessage.createdAt).getTime(),\n source: createdMessage.sourceType,\n id: createdMessage.id, // Central message ID\n thought: raw_message?.thought,\n actions: raw_message?.actions,\n attachments: metadata?.attachments,\n });\n }\n // NO broadcast to internalMessageBus here, this endpoint is for messages ALREADY PROCESSED by an agent\n // or system messages that don't need further agent processing via the bus.\n\n res.status(201).json({ success: true, data: createdMessage });\n } catch (error) {\n logger.error('[Messages Router /submit] Error submitting agent message:', error);\n res.status(500).json({ success: false, error: 'Failed to submit agent message' });\n }\n });\n\n // Endpoint to notify that a message is complete (e.g., agent finished responding)\n (router as any).post('/complete', async (req: express.Request, res: express.Response) => {\n const { channel_id, server_id } = req.body;\n\n if (!validateUuid(channel_id) || !validateUuid(server_id)) {\n return res.status(400).json({\n success: false,\n error: 'Missing or invalid fields: channel_id, server_id',\n });\n }\n\n try {\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channel_id).emit('messageComplete', {\n channelId: channel_id,\n serverId: server_id,\n });\n }\n\n res.status(200).json({ success: true, message: 'Completion event emitted' });\n } catch (error) {\n logger.error('[Messages Router /notify-complete] Error notifying message complete:', error);\n res.status(500).json({ success: false, error: 'Failed to notify message completion' });\n }\n });\n\n // Endpoint for INGESTING messages from EXTERNAL platforms (e.g., Discord plugin)\n (router as any).post('/ingest-external', async (req: express.Request, res: express.Response) => {\n const messagePayload = req.body as Partial<MessageService>; // Partial because ID, created_at will be generated\n\n if (\n !messagePayload.channel_id ||\n !messagePayload.server_id ||\n !messagePayload.author_id ||\n !messagePayload.content\n ) {\n return res.status(400).json({ success: false, error: 'Invalid external message payload' });\n }\n\n try {\n const messageToCreate = {\n channelId: messagePayload.channel_id as UUID,\n authorId: messagePayload.author_id as UUID, // This is the original author's ID from the platform (needs mapping to central user ID later)\n content: messagePayload.content as string,\n rawMessage: messagePayload.raw_message,\n sourceId: messagePayload.source_id, // Original platform message ID\n sourceType: messagePayload.source_type,\n inReplyToRootMessageId: messagePayload.in_reply_to_message_id\n ? validateUuid(messagePayload.in_reply_to_message_id) || undefined\n : undefined,\n metadata: messagePayload.metadata,\n };\n const createdRootMessage = await serverInstance.createMessage(messageToCreate);\n\n // Prepare message for the internal bus (for agents to consume)\n const messageForBus: MessageService = {\n id: createdRootMessage.id!,\n channel_id: createdRootMessage.channelId,\n server_id: messagePayload.server_id as UUID, // Pass through the original server_id\n author_id: createdRootMessage.authorId, // This is the central ID used for storage\n author_display_name: messagePayload.author_display_name, // Pass through display name\n content: createdRootMessage.content,\n raw_message: createdRootMessage.rawMessage,\n source_id: createdRootMessage.sourceId,\n source_type: createdRootMessage.sourceType,\n in_reply_to_message_id: createdRootMessage.inReplyToRootMessageId,\n created_at: new Date(createdRootMessage.createdAt).getTime(),\n metadata: createdRootMessage.metadata,\n };\n\n internalMessageBus.emit('new_message', messageForBus);\n logger.info(\n '[Messages Router /ingest-external] Published to internal message bus:',\n createdRootMessage.id\n );\n\n // Also emit to SocketIO for real-time GUI updates if anyone is watching this channel\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(messageForBus.channel_id).emit('messageBroadcast', {\n senderId: messageForBus.author_id,\n senderName: messageForBus.author_display_name || 'User',\n text: messageForBus.content,\n roomId: messageForBus.channel_id,\n serverId: messageForBus.server_id, // Client layer uses serverId\n createdAt: messageForBus.created_at,\n source: messageForBus.source_type,\n id: messageForBus.id,\n });\n }\n\n res.status(202).json({\n success: true,\n message: 'Message ingested and published to bus',\n data: { messageId: createdRootMessage.id },\n });\n } catch (error) {\n logger.error('[Messages Router /ingest-external] Error ingesting external message:', error);\n res.status(500).json({ success: false, error: 'Failed to ingest message' });\n }\n });\n\n return router;\n}\n","import EventEmitter from 'events';\n\n/**\n * A simple in-memory message bus for distributing messages from the server\n * to subscribed MessageBusService instances within the same process.\n *\n * For multi-process or multi-server deployments, this would need to be replaced\n * with a more robust solution like Redis Pub/Sub, Kafka, RabbitMQ, etc.\n */\nclass InternalMessageBus extends EventEmitter {}\n\nconst internalMessageBus = new InternalMessageBus();\n\n// Increase the default max listeners if many agents might be running in one process\ninternalMessageBus.setMaxListeners(50);\n\nexport default internalMessageBus;\n","import { logger, validateUuid, type UUID } from '@elizaos/core';\nimport express from 'express';\nimport internalMessageBus from '../../bus';\nimport type { AgentServer } from '../../index';\n\nconst DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n\n/**\n * Server management functionality\n */\nexport function createServersRouter(serverInstance: AgentServer): express.Router {\n const router = express.Router();\n\n // GET /central-servers\n (router as any).get('/central-servers', async (_req: express.Request, res: express.Response) => {\n try {\n const servers = await serverInstance.getServers();\n res.json({ success: true, data: { servers } });\n } catch (error) {\n logger.error('[Messages Router /central-servers] Error fetching servers:', error);\n res.status(500).json({ success: false, error: 'Failed to fetch servers' });\n }\n });\n\n // POST /servers - Create a new server\n (router as any).post('/servers', async (req: express.Request, res: express.Response) => {\n const { name, sourceType, sourceId, metadata } = req.body;\n\n if (!name || !sourceType) {\n return res.status(400).json({\n success: false,\n error: 'Missing required fields: name, sourceType',\n });\n }\n\n try {\n const server = await serverInstance.createServer({\n name,\n sourceType,\n sourceId,\n metadata,\n });\n res.status(201).json({ success: true, data: { server } });\n } catch (error) {\n logger.error('[Messages Router /servers] Error creating server:', error);\n res.status(500).json({ success: false, error: 'Failed to create server' });\n }\n });\n\n // ===============================\n // Server-Agent Association Endpoints\n // ===============================\n\n // POST /servers/:serverId/agents - Add agent to server\n (router as any).post(\n '/servers/:serverId/agents',\n async (req: express.Request, res: express.Response) => {\n const serverId =\n req.params.serverId === DEFAULT_SERVER_ID\n ? DEFAULT_SERVER_ID\n : validateUuid(req.params.serverId);\n const { agentId } = req.body;\n\n if (!serverId || !validateUuid(agentId)) {\n return res.status(400).json({\n success: false,\n error: 'Invalid serverId or agentId format',\n });\n }\n\n try {\n // Add agent to server association\n await serverInstance.addAgentToServer(serverId, agentId as UUID);\n\n // Notify the agent's message bus service to start listening for this server\n const messageForBus = {\n type: 'agent_added_to_server',\n serverId,\n agentId,\n };\n internalMessageBus.emit('server_agent_update', messageForBus);\n\n res.status(201).json({\n success: true,\n data: {\n serverId,\n agentId,\n message: 'Agent added to server successfully',\n },\n });\n } catch (error) {\n logger.error(\n `[MessagesRouter] Error adding agent ${agentId} to server ${serverId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to add agent to server' });\n }\n }\n );\n\n // DELETE /servers/:serverId/agents/:agentId - Remove agent from server\n (router as any).delete(\n '/servers/:serverId/agents/:agentId',\n async (req: express.Request, res: express.Response) => {\n const serverId =\n req.params.serverId === DEFAULT_SERVER_ID\n ? DEFAULT_SERVER_ID\n : validateUuid(req.params.serverId);\n const agentId = validateUuid(req.params.agentId);\n\n if (!serverId || !agentId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid serverId or agentId format',\n });\n }\n\n try {\n // Remove agent from server association\n await serverInstance.removeAgentFromServer(serverId, agentId);\n\n // Notify the agent's message bus service to stop listening for this server\n const messageForBus = {\n type: 'agent_removed_from_server',\n serverId,\n agentId,\n };\n internalMessageBus.emit('server_agent_update', messageForBus);\n\n res.status(200).json({\n success: true,\n data: {\n serverId,\n agentId,\n message: 'Agent removed from server successfully',\n },\n });\n } catch (error) {\n logger.error(\n `[MessagesRouter] Error removing agent ${agentId} from server ${serverId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to remove agent from server' });\n }\n }\n );\n\n // GET /servers/:serverId/agents - List agents in server\n (router as any).get(\n '/servers/:serverId/agents',\n async (req: express.Request, res: express.Response) => {\n const serverId =\n req.params.serverId === DEFAULT_SERVER_ID\n ? DEFAULT_SERVER_ID\n : validateUuid(req.params.serverId);\n\n if (!serverId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid serverId format',\n });\n }\n\n try {\n const agents = await serverInstance.getAgentsForServer(serverId);\n res.json({\n success: true,\n data: {\n serverId,\n agents, // Array of agent IDs\n },\n });\n } catch (error) {\n logger.error(`[MessagesRouter] Error fetching agents for server ${serverId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to fetch server agents' });\n }\n }\n );\n\n // GET /agents/:agentId/servers - List servers agent belongs to\n (router as any).get(\n '/agents/:agentId/servers',\n async (req: express.Request, res: express.Response) => {\n const agentId = validateUuid(req.params.agentId);\n\n if (!agentId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid agentId format',\n });\n }\n\n try {\n const servers = await serverInstance.getServersForAgent(agentId);\n res.json({\n success: true,\n data: {\n agentId,\n servers, // Array of server IDs\n },\n });\n } catch (error) {\n logger.error(`[MessagesRouter] Error fetching servers for agent ${agentId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to fetch agent servers' });\n }\n }\n );\n\n return router;\n}\n","import {\n composePromptFromState,\n IAgentRuntime,\n ModelType,\n ChannelType,\n logger,\n validateUuid,\n type UUID,\n} from '@elizaos/core';\nimport express from 'express';\nimport internalMessageBus from '../../bus';\nimport type { AgentServer } from '../../index';\nimport type { MessageServiceStructure as MessageService } from '../../types';\nimport { channelUpload, validateMediaFile, processUploadedFile } from '../../upload';\nimport { createUploadRateLimit, createFileSystemRateLimit } from '../shared/middleware';\nimport { MAX_FILE_SIZE } from '../shared/constants';\nimport { cleanupUploadedFile } from '../shared/file-utils';\nimport type fileUpload from 'express-fileupload';\n\nconst DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n\n// Using express-fileupload file type\ntype UploadedFile = fileUpload.UploadedFile;\n\ninterface ChannelUploadRequest extends Omit<express.Request<{ channelId: string }>, 'files'> {\n files?: { [fieldname: string]: UploadedFile | UploadedFile[] } | UploadedFile[];\n params: {\n channelId: string;\n };\n}\n\n/**\n * Channel management functionality\n */\nexport function createChannelsRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n // GUI posts NEW messages from a user here\n (router as any).post(\n '/central-channels/:channelId/messages',\n async (req: express.Request, res: express.Response) => {\n const channelIdParam = validateUuid(req.params.channelId);\n const {\n author_id, // This is the GUI user's central ID\n content,\n in_reply_to_message_id, // Central root_message.id\n server_id, // Central server_id this channel belongs to\n raw_message,\n metadata, // Should include user_display_name\n source_type, // Should be something like 'eliza_gui'\n } = req.body;\n\n // Special handling for default server ID \"0\"\n const isValidServerId = server_id === DEFAULT_SERVER_ID || validateUuid(server_id);\n\n if (!channelIdParam || !validateUuid(author_id) || !content || !isValidServerId) {\n return res.status(400).json({\n success: false,\n error: 'Missing required fields: channelId, server_id, author_id, content',\n });\n }\n\n try {\n // Ensure the channel exists before creating the message\n logger.info(\n `[Messages Router] Checking if channel ${channelIdParam} exists before creating message`\n );\n let channelExists = false;\n try {\n const existingChannel = await serverInstance.getChannelDetails(channelIdParam);\n channelExists = !!existingChannel;\n logger.info(`[Messages Router] Channel ${channelIdParam} exists: ${channelExists}`);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.info(\n `[Messages Router] Channel ${channelIdParam} does not exist, will create it. Error: ${errorMessage}`\n );\n }\n\n if (!channelExists) {\n // Auto-create the channel if it doesn't exist\n logger.info(\n `[Messages Router] Auto-creating channel ${channelIdParam} with serverId ${server_id}`\n );\n try {\n // First verify the server exists\n const servers = await serverInstance.getServers();\n const serverExists = servers.some((s) => s.id === server_id);\n logger.info(\n `[Messages Router] Server ${server_id} exists: ${serverExists}. Available servers: ${servers.map((s) => s.id).join(', ')}`\n );\n\n if (!serverExists) {\n logger.error(\n `[Messages Router] Server ${server_id} does not exist, cannot create channel`\n );\n return res\n .status(500)\n .json({ success: false, error: `Server ${server_id} does not exist` });\n }\n\n // Determine if this is likely a DM based on the context\n const isDmChannel =\n metadata?.isDm ||\n metadata?.channelType === ChannelType.DM ||\n metadata?.channel_type === ChannelType.DM;\n\n const channelData = {\n id: channelIdParam as UUID, // Use the specific channel ID from the URL\n messageServerId: server_id as UUID,\n name: isDmChannel\n ? `DM ${channelIdParam.substring(0, 8)}`\n : `Chat ${channelIdParam.substring(0, 8)}`,\n type: isDmChannel ? ChannelType.DM : ChannelType.GROUP,\n sourceType: 'auto_created',\n metadata: {\n created_by: 'gui_auto_creation',\n created_for_user: author_id,\n created_at: new Date().toISOString(),\n channel_type: isDmChannel ? ChannelType.DM : ChannelType.GROUP,\n ...metadata,\n },\n };\n\n logger.info(\n '[Messages Router] Creating channel with data:',\n JSON.stringify(channelData, null, 2)\n );\n\n // For DM channels, we need to determine the participants\n const participants = [author_id as UUID];\n if (isDmChannel) {\n // Try to extract the other participant from metadata\n const otherParticipant = metadata?.targetUserId || metadata?.recipientId;\n if (otherParticipant && validateUuid(otherParticipant)) {\n participants.push(otherParticipant as UUID);\n logger.info(\n `[Messages Router] DM channel will include participants: ${participants.join(', ')}`\n );\n } else {\n logger.warn(\n `[Messages Router] DM channel missing second participant, only adding author: ${author_id}`\n );\n }\n }\n\n await serverInstance.createChannel(channelData, participants);\n logger.info(\n `[Messages Router] Auto-created ${isDmChannel ? ChannelType.DM : ChannelType.GROUP} channel ${channelIdParam} for message submission with ${participants.length} participants`\n );\n } catch (createError: unknown) {\n const errorMessage =\n createError instanceof Error ? createError.message : String(createError);\n logger.error(\n `[Messages Router] Failed to auto-create channel ${channelIdParam}:`,\n createError\n );\n return res\n .status(500)\n .json({ success: false, error: `Failed to create channel: ${errorMessage}` });\n }\n } else {\n logger.info(\n `[Messages Router] Channel ${channelIdParam} already exists, proceeding with message creation`\n );\n }\n\n const newRootMessageData = {\n channelId: channelIdParam,\n authorId: author_id as UUID,\n content: content as string,\n inReplyToRootMessageId: in_reply_to_message_id\n ? validateUuid(in_reply_to_message_id) || undefined\n : undefined,\n rawMessage: raw_message,\n metadata,\n sourceType: source_type || 'eliza_gui',\n };\n\n const createdRootMessage = await serverInstance.createMessage(newRootMessageData);\n\n if (!createdRootMessage.id) {\n throw new Error('Created message does not have an ID');\n }\n\n const messageForBus: MessageService = {\n id: createdRootMessage.id,\n channel_id: createdRootMessage.channelId,\n server_id: server_id as UUID,\n author_id: createdRootMessage.authorId,\n content: createdRootMessage.content,\n created_at: new Date(createdRootMessage.createdAt).getTime(),\n source_type: createdRootMessage.sourceType,\n raw_message: createdRootMessage.rawMessage,\n metadata: createdRootMessage.metadata,\n author_display_name: metadata?.user_display_name, // Get from GUI payload\n in_reply_to_message_id: createdRootMessage.inReplyToRootMessageId,\n source_id: createdRootMessage.sourceId, // Will be undefined here, which is fine\n };\n\n internalMessageBus.emit('new_message', messageForBus);\n logger.info(\n '[Messages Router /central-channels/:channelId/messages] GUI Message published to internal bus:',\n messageForBus.id\n );\n\n // Emit to SocketIO for real-time display in all connected GUIs\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channelIdParam).emit('messageBroadcast', {\n senderId: author_id,\n senderName: metadata?.user_display_name || 'User',\n text: content,\n roomId: channelIdParam, // GUI uses central channelId as roomId for socket\n serverId: server_id, // Client layer uses serverId\n createdAt: messageForBus.created_at,\n source: messageForBus.source_type,\n id: messageForBus.id,\n });\n }\n\n res.status(201).json({ success: true, data: messageForBus });\n } catch (error) {\n logger.error(\n '[Messages Router /central-channels/:channelId/messages] Error processing GUI message:',\n error\n );\n res.status(500).json({ success: false, error: 'Failed to process message' });\n }\n }\n );\n\n // GET messages for a central channel\n (router as any).get(\n '/central-channels/:channelId/messages',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n const limit = req.query.limit ? Number.parseInt(req.query.limit as string, 10) : 50;\n const before = req.query.before ? Number.parseInt(req.query.before as string, 10) : undefined;\n const beforeDate = before ? new Date(before) : undefined;\n\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n\n try {\n const messages = await serverInstance.getMessagesForChannel(channelId, limit, beforeDate);\n // Transform to MessageService structure if GUI expects timestamps as numbers, or align types\n const messagesForGui = messages.map((msg) => {\n // Extract thought and actions from rawMessage for historical messages\n const rawMessage =\n typeof msg.rawMessage === 'string' ? JSON.parse(msg.rawMessage) : msg.rawMessage;\n\n return {\n ...msg,\n created_at: new Date(msg.createdAt).getTime(), // Ensure timestamp number\n updated_at: new Date(msg.updatedAt).getTime(),\n // Include thought and actions from rawMessage in metadata for client compatibility\n metadata: {\n ...msg.metadata,\n thought: rawMessage?.thought,\n actions: rawMessage?.actions,\n },\n // Ensure other fields align with client's MessageServiceStructure / ServerMessage\n };\n });\n res.json({ success: true, data: { messages: messagesForGui } });\n } catch (error) {\n logger.error(\n `[Messages Router /central-channels/:channelId/messages] Error fetching messages for channel ${channelId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to fetch messages' });\n }\n }\n );\n\n // GET /central-servers/:serverId/channels\n (router as any).get(\n '/central-servers/:serverId/channels',\n async (req: express.Request, res: express.Response) => {\n const serverId =\n req.params.serverId === DEFAULT_SERVER_ID\n ? DEFAULT_SERVER_ID\n : validateUuid(req.params.serverId);\n if (!serverId) {\n return res.status(400).json({ success: false, error: 'Invalid serverId' });\n }\n try {\n const channels = await serverInstance.getChannelsForServer(serverId);\n res.json({ success: true, data: { channels } });\n } catch (error) {\n logger.error(\n `[Messages Router /central-servers/:serverId/channels] Error fetching channels for server ${serverId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to fetch channels' });\n }\n }\n );\n\n // POST /channels - Create a new central channel\n (router as any).post('/channels', async (req: express.Request, res: express.Response) => {\n const { messageServerId, name, type, sourceType, sourceId, topic, metadata } = req.body;\n\n if (!messageServerId || !name || !type) {\n return res.status(400).json({\n success: false,\n error: 'Missing required fields: messageServerId, name, type',\n });\n }\n\n if (!validateUuid(messageServerId)) {\n return res.status(400).json({\n success: false,\n error: 'Invalid messageServerId format',\n });\n }\n\n try {\n const channel = await serverInstance.createChannel({\n messageServerId: messageServerId as UUID,\n name,\n type,\n sourceType,\n sourceId,\n topic,\n metadata,\n });\n res.status(201).json({ success: true, data: { channel } });\n } catch (error) {\n logger.error('[Messages Router /channels] Error creating channel:', error);\n res.status(500).json({ success: false, error: 'Failed to create channel' });\n }\n });\n\n // GET /dm-channel?targetUserId=<target_user_id>\n (router as any).get('/dm-channel', async (req: express.Request, res: express.Response) => {\n const targetUserId = validateUuid(req.query.targetUserId as string);\n const currentUserId = validateUuid(req.query.currentUserId as string);\n const providedDmServerId =\n req.query.dmServerId === DEFAULT_SERVER_ID\n ? DEFAULT_SERVER_ID\n : validateUuid(req.query.dmServerId as string);\n\n if (!targetUserId || !currentUserId) {\n res.status(400).json({ success: false, error: 'Missing targetUserId or currentUserId' });\n return;\n }\n if (targetUserId === currentUserId) {\n res.status(400).json({ success: false, error: 'Cannot create DM channel with oneself' });\n return;\n }\n\n let dmServerIdToUse: UUID = DEFAULT_SERVER_ID;\n\n try {\n if (providedDmServerId) {\n // Check if the provided server ID exists\n const existingServer = await serverInstance.getServerById(providedDmServerId); // Assumes AgentServer has getServerById\n if (existingServer) {\n dmServerIdToUse = providedDmServerId;\n } else {\n logger.warn(\n `Provided dmServerId ${providedDmServerId} not found, using default DM server logic.`\n );\n // Use default server if provided ID is invalid\n dmServerIdToUse = DEFAULT_SERVER_ID;\n }\n }\n\n const channel = await serverInstance.findOrCreateCentralDmChannel(\n currentUserId,\n targetUserId,\n dmServerIdToUse\n );\n res.json({ success: true, data: channel });\n } catch (error: unknown) {\n const errorDetails =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n originalError: error,\n }\n : { message: String(error) };\n\n logger.error('Error finding/creating DM channel:', errorDetails);\n res.status(500).json({ success: false, error: 'Failed to find or create DM channel' });\n }\n });\n\n // POST /central-channels (for creating group channels)\n (router as any).post('/central-channels', async (req: express.Request, res: express.Response) => {\n const {\n name,\n participantCentralUserIds,\n type = ChannelType.GROUP,\n server_id,\n metadata,\n } = req.body;\n\n // Special handling for default server ID \"0\"\n const isValidServerId = server_id === DEFAULT_SERVER_ID || validateUuid(server_id);\n\n if (\n !name ||\n !isValidServerId ||\n !Array.isArray(participantCentralUserIds) ||\n participantCentralUserIds.some((id) => !validateUuid(id))\n ) {\n return res.status(400).json({\n success: false,\n error:\n 'Invalid payload. Required: name, server_id (UUID or \"0\"), participantCentralUserIds (array of UUIDs). Optional: type, metadata.',\n });\n }\n\n try {\n const channelData = {\n messageServerId: server_id as UUID,\n name,\n type: type as ChannelType,\n metadata: {\n ...(metadata || {}),\n // participantIds are now handled by the separate table via createChannel's second argument\n },\n };\n // Pass participant IDs to createChannel\n const newChannel = await serverInstance.createChannel(\n channelData,\n participantCentralUserIds as UUID[]\n );\n\n res.status(201).json({ success: true, data: newChannel });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(\n '[Messages Router /central-channels] Error creating group channel:',\n errorMessage\n );\n res\n .status(500)\n .json({ success: false, error: 'Failed to create group channel', details: errorMessage });\n }\n });\n\n // Get channel details\n (router as any).get(\n '/central-channels/:channelId/details',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n try {\n const channelDetails = await serverInstance.getChannelDetails(channelId);\n if (!channelDetails) {\n return res.status(404).json({ success: false, error: 'Channel not found' });\n }\n res.json({ success: true, data: channelDetails });\n } catch (error) {\n logger.error(`[Messages Router] Error fetching details for channel ${channelId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to fetch channel details' });\n }\n }\n );\n\n // Get channel participants\n (router as any).get(\n '/central-channels/:channelId/participants',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n try {\n const participants = await serverInstance.getChannelParticipants(channelId);\n res.json({ success: true, data: participants });\n } catch (error) {\n logger.error(\n `[Messages Router] Error fetching participants for channel ${channelId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to fetch channel participants' });\n }\n }\n );\n\n // POST /central-channels/:channelId/agents - Add agent to channel\n (router as any).post(\n '/central-channels/:channelId/agents',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n const { agentId } = req.body;\n\n if (!channelId || !validateUuid(agentId)) {\n return res.status(400).json({\n success: false,\n error: 'Invalid channelId or agentId format',\n });\n }\n\n try {\n // Verify the channel exists\n const channel = await serverInstance.getChannelDetails(channelId);\n if (!channel) {\n return res.status(404).json({\n success: false,\n error: 'Channel not found',\n });\n }\n\n // Verify the agent exists (optional - depends on your agent registry)\n // You might want to add a method to check if agent exists in your system\n\n // Add agent to channel participants\n await serverInstance.addParticipantsToChannel(channelId, [agentId as UUID]);\n\n logger.info(`[Messages Router] Added agent ${agentId} to channel ${channelId}`);\n\n res.status(201).json({\n success: true,\n data: {\n channelId,\n agentId,\n message: 'Agent added to channel successfully',\n },\n });\n } catch (error) {\n logger.error(\n `[Messages Router] Error adding agent ${agentId} to channel ${channelId}:`,\n error\n );\n res.status(500).json({\n success: false,\n error: 'Failed to add agent to channel',\n details: error instanceof Error ? error.message : String(error),\n });\n }\n }\n );\n\n // DELETE /central-channels/:channelId/agents/:agentId - Remove agent from channel\n (router as any).delete(\n '/central-channels/:channelId/agents/:agentId',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n const agentId = validateUuid(req.params.agentId);\n\n if (!channelId || !agentId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid channelId or agentId format',\n });\n }\n\n try {\n // Verify the channel exists\n const channel = await serverInstance.getChannelDetails(channelId);\n if (!channel) {\n return res.status(404).json({\n success: false,\n error: 'Channel not found',\n });\n }\n\n // Get current participants to verify agent is in channel\n const currentParticipants = await serverInstance.getChannelParticipants(channelId);\n if (!currentParticipants.includes(agentId)) {\n return res.status(404).json({\n success: false,\n error: 'Agent is not a participant in this channel',\n });\n }\n\n // Remove agent from channel participants\n // Note: We need to update the channel with the new participant list\n const updatedParticipants = currentParticipants.filter((id) => id !== agentId);\n await serverInstance.updateChannel(channelId, {\n participantCentralUserIds: updatedParticipants,\n });\n\n logger.info(`[Messages Router] Removed agent ${agentId} from channel ${channelId}`);\n\n res.status(200).json({\n success: true,\n data: {\n channelId,\n agentId,\n message: 'Agent removed from channel successfully',\n },\n });\n } catch (error) {\n logger.error(\n `[Messages Router] Error removing agent ${agentId} from channel ${channelId}:`,\n error\n );\n res.status(500).json({\n success: false,\n error: 'Failed to remove agent from channel',\n details: error instanceof Error ? error.message : String(error),\n });\n }\n }\n );\n\n // GET /central-channels/:channelId/agents - List agents in channel\n (router as any).get(\n '/central-channels/:channelId/agents',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n\n if (!channelId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid channelId format',\n });\n }\n\n try {\n // Get all participants\n const allParticipants = await serverInstance.getChannelParticipants(channelId);\n\n // Filter for agents (this is a simplified approach - you might want to\n // implement a more sophisticated way to distinguish agents from users)\n // For now, we'll return all participants and let the client filter\n // In a production system, you'd want to cross-reference with an agent registry\n\n res.json({\n success: true,\n data: {\n channelId,\n participants: allParticipants, // All participants (agents and users)\n // TODO: Add agent-specific filtering when agent registry is available\n },\n });\n } catch (error) {\n logger.error(`[Messages Router] Error fetching agents for channel ${channelId}:`, error);\n res.status(500).json({\n success: false,\n error: 'Failed to fetch channel agents',\n });\n }\n }\n );\n\n // Delete single message\n (router as any).delete(\n '/central-channels/:channelId/messages/:messageId',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n const messageId = validateUuid(req.params.messageId);\n if (!channelId || !messageId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId or messageId' });\n }\n try {\n // First, delete the message from central database\n await serverInstance.deleteMessage(messageId);\n logger.info(`[Messages Router] Deleted message ${messageId} from central database`);\n\n // Then emit message_deleted event to internal bus for agent memory cleanup\n const deletedMessagePayload = {\n messageId: messageId,\n channelId: channelId,\n };\n\n internalMessageBus.emit('message_deleted', deletedMessagePayload);\n logger.info(\n `[Messages Router] Emitted message_deleted event to internal bus for message ${messageId}`\n );\n\n // Also, emit an event via SocketIO to inform clients about the deletion\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channelId).emit('messageDeleted', {\n messageId: messageId,\n channelId: channelId,\n });\n }\n res.status(204).send();\n } catch (error) {\n logger.error(\n `[Messages Router] Error deleting message ${messageId} from channel ${channelId}:`,\n error\n );\n res.status(500).json({ success: false, error: 'Failed to delete message' });\n }\n }\n );\n\n // Clear all messages in channel\n (router as any).delete(\n '/central-channels/:channelId/messages',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n try {\n // Clear all messages from central database\n await serverInstance.clearChannelMessages(channelId);\n\n // Emit to internal bus for agent memory cleanup\n const channelClearedPayload = {\n channelId: channelId,\n };\n internalMessageBus.emit('channel_cleared', channelClearedPayload);\n logger.info(\n `[Messages Router] Emitted channel_cleared event to internal bus for channel ${channelId}`\n );\n\n // Also, emit an event via SocketIO to inform clients about the channel clear\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channelId).emit('channelCleared', {\n channelId: channelId,\n });\n }\n res.status(204).send();\n } catch (error) {\n logger.error(`[Messages Router] Error clearing messages for channel ${channelId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to clear messages' });\n }\n }\n );\n\n // Update channel\n (router as any).patch(\n '/central-channels/:channelId',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n const { name, participantCentralUserIds, metadata } = req.body;\n try {\n const updatedChannel = await serverInstance.updateChannel(channelId, {\n name,\n participantCentralUserIds,\n metadata,\n });\n // Emit an event via SocketIO to inform clients about the channel update\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channelId).emit('channelUpdated', {\n channelId: channelId,\n updates: updatedChannel,\n });\n }\n res.json({ success: true, data: updatedChannel });\n } catch (error) {\n logger.error(`[Messages Router] Error updating channel ${channelId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to update channel' });\n }\n }\n );\n\n // Delete entire channel\n (router as any).delete(\n '/central-channels/:channelId',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n return res.status(400).json({ success: false, error: 'Invalid channelId' });\n }\n try {\n // Get messages count before deletion for logging\n const messages = await serverInstance.getMessagesForChannel(channelId);\n const messageCount = messages.length;\n\n // Delete the entire channel\n await serverInstance.deleteChannel(channelId);\n logger.info(\n `[Messages Router] Deleted channel ${channelId} with ${messageCount} messages from central database`\n );\n\n // Emit to internal bus for agent memory cleanup (same as clear messages)\n const channelClearedPayload = {\n channelId: channelId,\n };\n internalMessageBus.emit('channel_cleared', channelClearedPayload);\n logger.info(\n `[Messages Router] Emitted channel_cleared event to internal bus for deleted channel ${channelId}`\n );\n\n // Emit an event via SocketIO to inform clients about the channel deletion\n if (serverInstance.socketIO) {\n serverInstance.socketIO.to(channelId).emit('channelDeleted', {\n channelId: channelId,\n });\n }\n res.status(204).send();\n } catch (error) {\n logger.error(`[Messages Router] Error deleting channel ${channelId}:`, error);\n res.status(500).json({ success: false, error: 'Failed to delete channel' });\n }\n }\n );\n\n // Upload media to channel\n (router as any).post(\n '/channels/:channelId/upload-media',\n createUploadRateLimit(),\n createFileSystemRateLimit(),\n channelUpload(),\n async (req: ChannelUploadRequest, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n if (!channelId) {\n res.status(400).json({ success: false, error: 'Invalid channelId format' });\n return;\n }\n\n // Get the uploaded file from express-fileupload\n let mediaFile: UploadedFile;\n if (req.files && !Array.isArray(req.files)) {\n // files is an object with field names\n mediaFile = req.files.file as UploadedFile;\n } else if (Array.isArray(req.files) && req.files.length > 0) {\n // files is an array\n mediaFile = req.files[0];\n } else {\n res.status(400).json({ success: false, error: 'No media file provided' });\n return;\n }\n\n if (!mediaFile) {\n res.status(400).json({ success: false, error: 'No media file provided' });\n return;\n }\n\n try {\n // Enhanced security validation\n // Validate MIME type\n if (!validateMediaFile(mediaFile)) {\n cleanupUploadedFile(mediaFile);\n res\n .status(400)\n .json({ success: false, error: `Invalid file type: ${mediaFile.mimetype}` });\n return;\n }\n\n // Additional filename security validation\n if (!mediaFile.name || mediaFile.name.includes('..') || mediaFile.name.includes('/')) {\n cleanupUploadedFile(mediaFile);\n res.status(400).json({ success: false, error: 'Invalid filename detected' });\n return;\n }\n\n // Validate file size (additional check beyond middleware limits)\n if (mediaFile.size > MAX_FILE_SIZE) {\n cleanupUploadedFile(mediaFile);\n res.status(400).json({ success: false, error: 'File too large' });\n return;\n }\n\n // Process and move the uploaded file\n const result = await processUploadedFile(mediaFile, channelId, 'channels');\n\n logger.info(\n `[MessagesRouter /upload-media] Secure file uploaded for channel ${channelId}: ${result.filename}. URL: ${result.url}`\n );\n\n res.json({\n success: true,\n data: {\n url: result.url, // Relative URL, client prepends server origin\n type: mediaFile.mimetype,\n filename: result.filename,\n originalName: mediaFile.name,\n size: mediaFile.size,\n },\n });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(\n `[MessagesRouter /upload-media] Error processing upload for channel ${channelId}: ${errorMessage}`,\n error\n );\n if (mediaFile) {\n cleanupUploadedFile(mediaFile);\n }\n res.status(500).json({ success: false, error: 'Failed to process media upload' });\n }\n }\n );\n\n (router as any).post(\n '/central-channels/:channelId/generate-title',\n async (req: express.Request, res: express.Response) => {\n const channelId = validateUuid(req.params.channelId);\n const { agentId } = req.body;\n\n if (!channelId) {\n return res.status(400).json({\n success: false,\n error: 'Invalid channel ID format',\n });\n }\n\n if (!agentId || !validateUuid(agentId)) {\n return res.status(400).json({\n success: false,\n error: 'Valid agent ID is required',\n });\n }\n\n try {\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n return res.status(404).json({\n success: false,\n error: 'Agent not found or not active',\n });\n }\n\n logger.info(`[CHANNEL SUMMARIZE] Summarizing channel ${channelId}`);\n const limit = req.query.limit ? Number.parseInt(req.query.limit as string, 10) : 50;\n const before = req.query.before\n ? Number.parseInt(req.query.before as string, 10)\n : undefined;\n const beforeDate = before ? new Date(before) : undefined;\n\n const messages = await serverInstance.getMessagesForChannel(channelId, limit, beforeDate);\n\n if (!messages || messages.length < 4) {\n return res.status(200).json({\n success: true,\n data: {\n title: null,\n channelId,\n reason: 'Not enough messages to generate a title',\n },\n });\n }\n\n const recentMessages = messages\n .reverse() // Show in chronological order\n .map((msg) => {\n const isUser = msg.authorId !== runtime.agentId;\n const role = isUser ? 'User' : 'Agent';\n return `${role}: ${msg.content}`;\n })\n .join('\\n');\n\n const prompt = composePromptFromState({\n state: {\n recentMessages,\n values: {},\n data: {},\n text: recentMessages,\n },\n template: `\nBased on the conversation below, generate a short, descriptive title for this chat. The title should capture the main topic or theme of the discussion.\nRules:\n- Keep it concise (3-6 words)\n- Make it descriptive and specific\n- Avoid generic terms like \"Chat\" or \"Conversation\"\n- Focus on the main topic, activity, or subject matter\n- Use natural language, not hashtags or symbols\nExamples:\n- \"React Component Help\"\n- \"Weekend Trip Planning\"\n- \"Database Design Discussion\"\n- \"Recipe Exchange\"\n- \"Career Advice Session\"\nRecent conversation:\n{{recentMessages}}\nRespond with just the title, nothing else.\n `,\n });\n\n const newTitle = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n temperature: 0.3, // Use low temperature for consistent titles\n maxTokens: 50, // Keep titles short\n });\n\n if (!newTitle || newTitle.trim().length === 0) {\n logger.warn(`[ChatTitleEvaluator] Failed to generate title for room ${channelId}`);\n return;\n }\n\n const cleanTitle = newTitle.trim().replace(/^[\"']|[\"']$/g, ''); // Remove quotes if present\n\n logger.info(`[ChatTitleEvaluator] Generated title: \"${cleanTitle}\" for room ${channelId}`);\n\n const result = {\n title: cleanTitle,\n channelId,\n };\n\n logger.success(`[CHANNEL SUMMARIZE] Successfully summarized channel ${channelId}`);\n\n res.json({\n success: true,\n data: result,\n });\n } catch (error) {\n logger.error('[CHANNEL SUMMARIZE] Error summarizing channel:', error);\n res.status(500).json({\n success: false,\n error: 'Failed to summarize channel',\n details: error instanceof Error ? error.message : String(error),\n });\n }\n }\n );\n\n return router;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport fileUpload from 'express-fileupload';\nimport { validateUuid, logger } from '@elizaos/core';\nimport { createSecureUploadDir, sanitizeFilename } from './api/shared/file-utils';\nimport {\n MAX_FILE_SIZE,\n ALLOWED_AUDIO_MIME_TYPES,\n ALLOWED_MEDIA_MIME_TYPES,\n} from './api/shared/constants';\n\n// Helper function to generate secure filename\nfunction generateSecureFilename(originalName: string): string {\n const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n const sanitizedName = sanitizeFilename(originalName);\n return `${uniqueSuffix}-${sanitizedName}`;\n}\n\n// Helper function to create upload directory\nfunction ensureUploadDir(id: string, type: 'agents' | 'channels'): string {\n if (!validateUuid(id)) {\n throw new Error(`Invalid ${type.slice(0, -1)} ID format`);\n }\n\n const uploadDir = createSecureUploadDir(id, type);\n\n if (!fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n logger.debug(`[UPLOAD] Secure ${type.slice(0, -1)} upload directory created: ${uploadDir}`);\n return uploadDir;\n}\n\n// --- Agent-Specific Upload Configuration ---\nexport const agentAudioUpload = () =>\n fileUpload({\n limits: {\n fileSize: MAX_FILE_SIZE, // 50MB max file size\n files: 1, // Only allow 1 file per request\n },\n useTempFiles: true,\n tempFileDir: '/tmp/',\n parseNested: true,\n abortOnLimit: true,\n createParentPath: true,\n preserveExtension: true,\n safeFileNames: true,\n uploadTimeout: 60000, // 60 seconds timeout\n });\n\nexport const agentMediaUpload = () =>\n fileUpload({\n limits: {\n fileSize: MAX_FILE_SIZE, // 50MB max file size\n files: 1, // Only allow 1 file per request\n },\n useTempFiles: true,\n tempFileDir: '/tmp/',\n parseNested: true,\n abortOnLimit: true,\n createParentPath: true,\n preserveExtension: true,\n safeFileNames: true,\n uploadTimeout: 60000, // 60 seconds timeout\n });\n\n// --- Channel-Specific Upload Configuration ---\nexport const channelUpload = () =>\n fileUpload({\n limits: {\n fileSize: MAX_FILE_SIZE, // 50MB max file size\n files: 1, // Only allow 1 file per request\n },\n useTempFiles: true,\n tempFileDir: '/tmp/',\n parseNested: true,\n abortOnLimit: true,\n createParentPath: true,\n preserveExtension: true,\n safeFileNames: true,\n uploadTimeout: 60000, // 60 seconds timeout\n });\n\n// --- Generic Upload Configuration (if ever needed, less specific) ---\nexport const genericUpload = () =>\n fileUpload({\n limits: {\n fileSize: MAX_FILE_SIZE, // 50MB max file size\n files: 1, // Only allow 1 file per request\n },\n useTempFiles: true,\n tempFileDir: '/tmp/',\n parseNested: true,\n abortOnLimit: true,\n createParentPath: true,\n preserveExtension: true,\n safeFileNames: true,\n uploadTimeout: 60000, // 60 seconds timeout\n });\n\n// Original generic upload (kept for compatibility if used elsewhere, but prefer specific ones)\nexport const upload = genericUpload; // Defaulting to generic if 'upload' is directly used\n\n// Export helper functions for use in route handlers\nexport { generateSecureFilename, ensureUploadDir };\n\n// File validation functions\nexport function validateAudioFile(file: fileUpload.UploadedFile): boolean {\n return ALLOWED_AUDIO_MIME_TYPES.includes(file.mimetype as any);\n}\n\nexport function validateMediaFile(file: fileUpload.UploadedFile): boolean {\n return ALLOWED_MEDIA_MIME_TYPES.includes(file.mimetype as any);\n}\n\n// Process and move uploaded file to final destination\nexport async function processUploadedFile(\n file: fileUpload.UploadedFile,\n targetId: string,\n type: 'agents' | 'channels'\n): Promise<{ filename: string; path: string; url: string }> {\n try {\n // Ensure upload directory exists\n const uploadDir = ensureUploadDir(targetId, type);\n\n // Generate secure filename\n const filename = generateSecureFilename(file.name);\n const finalPath = path.join(uploadDir, filename);\n\n // Move file from temp location to final destination\n await file.mv(finalPath);\n\n // Construct URL\n const url = `/media/uploads/${type}/${targetId}/${filename}`;\n\n logger.debug(`[UPLOAD] File processed successfully: ${filename}`);\n\n return { filename, path: finalPath, url };\n } catch (error) {\n logger.error('[UPLOAD] Error processing uploaded file:', error);\n throw error;\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '@elizaos/core';\nimport type fileUpload from 'express-fileupload';\n\n// Using express-fileupload file type\ntype UploadedFile = fileUpload.UploadedFile;\n\n/**\n * Safely constructs and validates upload directory paths to prevent path traversal attacks\n */\nexport function createSecureUploadDir(id: string, type: 'agents' | 'channels'): string {\n // Additional validation beyond UUID to ensure no path traversal\n if (id.includes('..') || id.includes('/') || id.includes('\\\\') || id.includes('\\0')) {\n throw new Error(`Invalid ${type.slice(0, -1)} ID: contains illegal characters`);\n }\n\n const basePath = path.resolve(process.cwd(), '.eliza', 'data', 'uploads', type);\n const targetPath = path.join(basePath, id);\n\n // Ensure the resolved path is still within the expected base directory\n if (!targetPath.startsWith(basePath)) {\n throw new Error(`Invalid ${type.slice(0, -1)} ID: path traversal detected`);\n }\n\n return targetPath;\n}\n\n/**\n * Safely sanitizes filenames to prevent security issues\n */\nexport function sanitizeFilename(filename: string): string {\n // Remove null bytes and path separators\n let sanitized = filename.replace(/[\\0\\/\\\\:*?\"<>|]/g, '_');\n\n // Remove leading dots and spaces\n sanitized = sanitized.replace(/^[.\\s]+/, '');\n\n // Limit length to prevent filesystem issues\n if (sanitized.length > 255) {\n const ext = path.extname(sanitized);\n const name = path.basename(sanitized, ext);\n sanitized = name.substring(0, 255 - ext.length) + ext;\n }\n\n // Ensure filename is not empty after sanitization\n if (!sanitized || sanitized.trim() === '') {\n sanitized = 'file';\n }\n\n return sanitized;\n}\n\n/**\n * Safely cleans up a single file by path with path validation\n */\nexport const cleanupFile = (filePath: string) => {\n if (!filePath) return;\n\n try {\n // Validate and resolve the path to prevent directory traversal\n const resolvedPath = path.resolve(filePath);\n const normalizedPath = path.normalize(resolvedPath);\n\n // Ensure the path doesn't contain directory traversal attempts\n if (normalizedPath.includes('..') || !normalizedPath.startsWith(process.cwd())) {\n logger.warn(`[SECURITY] Potentially unsafe file path blocked: ${filePath}`);\n return;\n }\n\n if (fs.existsSync(normalizedPath)) {\n fs.unlinkSync(normalizedPath);\n logger.debug(`[FILE] Successfully cleaned up file: ${normalizedPath}`);\n }\n } catch (error) {\n logger.error(`Error cleaning up file ${filePath}:`, error);\n }\n};\n\n/**\n * Cleans up multiple files from express-fileupload\n */\nexport const cleanupFiles = (files: UploadedFile[]) => {\n if (files) {\n files.forEach((file) => cleanupFile(file.tempFilePath || ''));\n }\n};\n\n/**\n * Cleans up an uploaded file by removing it from temp location\n */\nexport const cleanupUploadedFile = (file: UploadedFile) => {\n if (file.tempFilePath) {\n cleanupFile(file.tempFilePath);\n }\n};\n","/**\n * Shared constants for the API server\n */\n\n/**\n * Maximum file size allowed for uploads (50MB)\n * Used across various endpoints including audio processing,\n * media uploads, and multer configurations\n */\nexport const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB\n\n/**\n * Maximum file size in human-readable format\n */\nexport const MAX_FILE_SIZE_DISPLAY = '50MB';\n\n/**\n * Valid MIME types for audio files\n */\nexport const ALLOWED_AUDIO_MIME_TYPES = [\n 'audio/mpeg',\n 'audio/mp3',\n 'audio/wav',\n 'audio/ogg',\n 'audio/webm',\n 'audio/mp4',\n 'audio/aac',\n 'audio/flac',\n 'audio/x-wav',\n 'audio/wave',\n] as const;\n\n/**\n * Valid MIME types for media files (includes audio, images, documents)\n */\nexport const ALLOWED_MEDIA_MIME_TYPES = [\n ...ALLOWED_AUDIO_MIME_TYPES,\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'video/mp4',\n 'video/webm',\n 'application/pdf',\n 'text/plain',\n] as const;\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport { validateUuid, logger } from '@elizaos/core';\nimport { sendError } from './response-utils';\nimport { validateChannelId } from './validation';\nimport rateLimit from 'express-rate-limit';\n\n/**\n * Middleware to validate that an agent exists\n */\nexport const agentExistsMiddleware = (agents: Map<UUID, IAgentRuntime>) => {\n return (req: express.Request, res: express.Response, next: express.NextFunction) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n // Add runtime to request object for use in route handlers\n (req as any).runtime = runtime;\n (req as any).agentId = agentId;\n next();\n };\n};\n\n/**\n * Middleware to validate UUID parameters\n */\nexport const validateUuidMiddleware = (paramName: string) => {\n return (req: express.Request, res: express.Response, next: express.NextFunction) => {\n const paramValue = req.params[paramName];\n let validatedUuid: UUID | null;\n\n // Use enhanced validation for channel IDs\n if (paramName === 'channelId') {\n const clientIp = req.ip || 'unknown';\n validatedUuid = validateChannelId(paramValue, clientIp);\n } else {\n validatedUuid = validateUuid(paramValue);\n }\n\n if (!validatedUuid) {\n // Log security event for invalid IDs\n const clientIp = req.ip || 'unknown';\n logger.warn(`[SECURITY] Invalid ${paramName} from ${clientIp}: ${paramValue}`);\n return sendError(res, 400, 'INVALID_ID', `Invalid ${paramName} format`);\n }\n\n // Add validated UUID to request params\n req.params[paramName] = validatedUuid;\n next();\n };\n};\n\n/**\n * Enhanced channel ID validation middleware with additional security\n */\nexport const validateChannelIdMiddleware = () => {\n return (req: express.Request, res: express.Response, next: express.NextFunction) => {\n const channelId = req.params.channelId;\n const clientIp = req.ip || 'unknown';\n\n if (!channelId) {\n return sendError(res, 400, 'MISSING_CHANNEL_ID', 'Channel ID is required');\n }\n\n const validatedChannelId = validateChannelId(channelId, clientIp);\n\n if (!validatedChannelId) {\n // Rate limit failed attempts to prevent brute force\n logger.warn(`[SECURITY] Failed channel ID validation from ${clientIp}: ${channelId}`);\n return sendError(res, 400, 'INVALID_CHANNEL_ID', 'Invalid channel ID format');\n }\n\n // Store validated channel ID\n req.params.channelId = validatedChannelId;\n next();\n };\n};\n\n/**\n * Security middleware to add additional API protection\n */\nexport const securityMiddleware = () => {\n return (req: express.Request, res: express.Response, next: express.NextFunction) => {\n // Add security headers specific to API responses\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'SAMEORIGIN'); // Changed from DENY to allow same-origin iframes, otherwise we can load panels from plugins\n res.setHeader('X-XSS-Protection', '1; mode=block');\n res.setHeader('Referrer-Policy', 'no-referrer');\n\n // Remove potentially sensitive headers\n res.removeHeader('X-Powered-By');\n res.removeHeader('Server');\n\n // Log security-relevant information\n const userAgent = req.get('User-Agent');\n const forwarded = req.get('X-Forwarded-For');\n const realIp = req.get('X-Real-IP');\n const clientIp = forwarded || realIp || req.ip;\n\n // Log suspicious patterns\n if (userAgent && (userAgent.includes('..') || userAgent.includes('<script'))) {\n logger.warn(`[SECURITY] Suspicious User-Agent from ${clientIp}: ${userAgent}`);\n }\n\n // Check for suspicious request patterns with safe, non-backtracking regexes\n const url = req.originalUrl || req.url;\n const queryString = JSON.stringify(req.query);\n\n // Use safer string matching instead of potentially dangerous regexes\n const suspiciousIndicators = [\n { pattern: '..', name: 'Path traversal' },\n { pattern: '<script', name: 'XSS attempt' },\n { pattern: 'javascript:', name: 'JavaScript injection' },\n ];\n\n // Safe SQL injection detection without backtracking regex\n const sqlKeywords = ['union', 'select', 'drop', 'delete', 'insert', 'update'];\n let hasSqlPattern = false;\n const lowerUrl = url.toLowerCase();\n const lowerQuery = queryString.toLowerCase();\n\n // Check for SQL injection patterns more safely\n for (let i = 0; i < sqlKeywords.length - 1; i++) {\n const keyword1 = sqlKeywords[i];\n for (let j = i + 1; j < sqlKeywords.length; j++) {\n const keyword2 = sqlKeywords[j];\n if (\n (lowerUrl.includes(keyword1) && lowerUrl.includes(keyword2)) ||\n (lowerQuery.includes(keyword1) && lowerQuery.includes(keyword2))\n ) {\n hasSqlPattern = true;\n break;\n }\n }\n if (hasSqlPattern) break;\n }\n\n // Check for other suspicious patterns\n for (const indicator of suspiciousIndicators) {\n if (url.includes(indicator.pattern) || queryString.includes(indicator.pattern)) {\n logger.warn(`[SECURITY] ${indicator.name} detected from ${clientIp}: ${url}`);\n break;\n }\n }\n\n if (hasSqlPattern) {\n logger.warn(`[SECURITY] SQL injection pattern detected from ${clientIp}: ${url}`);\n }\n\n next();\n };\n};\n\n/**\n * Middleware to validate request content type for POST/PUT/PATCH requests\n */\nexport const validateContentTypeMiddleware = () => {\n return (req: express.Request, res: express.Response, next: express.NextFunction) => {\n // Only validate Content-Type for methods that typically have request bodies\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n const contentType = req.get('Content-Type');\n const contentLength = req.get('Content-Length');\n\n // Skip validation if request has no body (Content-Length is 0 or undefined)\n if (!contentLength || contentLength === '0') {\n return next();\n }\n\n // Allow multipart for file uploads, JSON for regular API requests\n const validTypes = [\n 'application/json',\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ];\n\n if (!contentType || !validTypes.some((type) => contentType.includes(type))) {\n return sendError(\n res,\n 400,\n 'INVALID_CONTENT_TYPE',\n 'Invalid or missing Content-Type header'\n );\n }\n }\n\n next();\n };\n};\n\n/**\n * General API rate limiting middleware\n */\nexport const createApiRateLimit = () => {\n return rateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 1000, // Limit each IP to 1000 requests per windowMs\n message: {\n success: false,\n error: {\n code: 'RATE_LIMIT_EXCEEDED',\n message: 'Too many requests. Please try again later.',\n },\n },\n standardHeaders: true, // Return rate limit info in the `RateLimitInfo` headers\n legacyHeaders: false, // Disable the `X-RateLimit-*` headers\n handler: (req, res) => {\n const clientIp = req.ip || 'unknown';\n logger.warn(`[SECURITY] Rate limit exceeded for IP: ${clientIp}`);\n res.status(429).json({\n success: false,\n error: {\n code: 'RATE_LIMIT_EXCEEDED',\n message: 'Too many requests. Please try again later.',\n },\n });\n },\n });\n};\n\n/**\n * Strict rate limiting for file system operations\n */\nexport const createFileSystemRateLimit = () => {\n return rateLimit({\n windowMs: 5 * 60 * 1000, // 5 minutes\n max: 100, // Limit each IP to 100 file operations per 5 minutes\n message: {\n success: false,\n error: {\n code: 'FILE_RATE_LIMIT_EXCEEDED',\n message: 'Too many file operations. Please try again later.',\n },\n },\n standardHeaders: true,\n legacyHeaders: false,\n handler: (req, res) => {\n const clientIp = req.ip || 'unknown';\n logger.warn(\n `[SECURITY] File system rate limit exceeded for IP: ${clientIp}, endpoint: ${req.path}`\n );\n res.status(429).json({\n success: false,\n error: {\n code: 'FILE_RATE_LIMIT_EXCEEDED',\n message: 'Too many file operations. Please try again later.',\n },\n });\n },\n });\n};\n\n/**\n * Very strict rate limiting for upload operations\n */\nexport const createUploadRateLimit = () => {\n return rateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 50, // Limit each IP to 50 uploads per 15 minutes\n message: {\n success: false,\n error: {\n code: 'UPLOAD_RATE_LIMIT_EXCEEDED',\n message: 'Too many upload attempts. Please try again later.',\n },\n },\n standardHeaders: true,\n legacyHeaders: false,\n handler: (req, res) => {\n const clientIp = req.ip || 'unknown';\n logger.warn(\n `[SECURITY] Upload rate limit exceeded for IP: ${clientIp}, endpoint: ${req.path}`\n );\n res.status(429).json({\n success: false,\n error: {\n code: 'UPLOAD_RATE_LIMIT_EXCEEDED',\n message: 'Too many upload attempts. Please try again later.',\n },\n });\n },\n });\n};\n\n/**\n * Rate limiting specifically for channel validation attempts\n * Prevents brute force attacks on channel IDs\n */\nexport const createChannelValidationRateLimit = () => {\n return rateLimit({\n windowMs: 10 * 60 * 1000, // 10 minutes\n max: 200, // Limit each IP to 200 channel validation attempts per 10 minutes\n message: {\n success: false,\n error: {\n code: 'CHANNEL_VALIDATION_RATE_LIMIT_EXCEEDED',\n message: 'Too many channel validation attempts. Please try again later.',\n },\n },\n standardHeaders: true,\n legacyHeaders: false,\n skip: (req) => {\n // Skip rate limiting if channel ID is valid (successful validations)\n const channelId = req.params.channelId;\n if (channelId) {\n const validatedChannelId = validateChannelId(channelId);\n return !!validatedChannelId; // Skip if valid\n }\n return false; // Apply rate limiting for invalid attempts\n },\n handler: (req, res) => {\n const clientIp = req.ip || 'unknown';\n const channelId = req.params.channelId || 'unknown';\n logger.warn(\n `[SECURITY] Channel validation rate limit exceeded for IP: ${clientIp}, attempted channel: ${channelId}`\n );\n res.status(429).json({\n success: false,\n error: {\n code: 'CHANNEL_VALIDATION_RATE_LIMIT_EXCEEDED',\n message: 'Too many channel validation attempts. Please try again later.',\n },\n });\n },\n });\n};\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { validateUuid, logger } from '@elizaos/core';\n\n/**\n * Validates and retrieves an agent runtime from the agents map\n */\nexport const getRuntime = (agents: Map<UUID, IAgentRuntime>, agentId: UUID) => {\n const runtime = agents.get(agentId);\n if (!runtime) {\n throw new Error(`Agent not found: ${agentId}`);\n }\n return runtime;\n};\n\n/**\n * Validates a UUID parameter and returns it as UUID type or null if invalid\n */\nexport const validateAgentId = (agentId: string): UUID | null => {\n return validateUuid(agentId);\n};\n\n/**\n * Validates a room ID parameter\n */\nexport const validateRoomId = (roomId: string): UUID | null => {\n return validateUuid(roomId);\n};\n\n/**\n * Enhanced channel ID validation with security logging\n * Validates a channel ID parameter with additional security checks\n */\nexport const validateChannelId = (channelId: string, clientIp?: string): UUID | null => {\n // Basic UUID validation\n const validatedUuid = validateUuid(channelId);\n\n if (!validatedUuid) {\n // Log invalid channel ID attempts for security monitoring\n if (clientIp) {\n logger.warn(`[SECURITY] Invalid channel ID attempted from ${clientIp}: ${channelId}`);\n }\n return null;\n }\n\n // Additional security check: ensure channel ID doesn't contain suspicious patterns\n const suspiciousPatterns = ['..', '<', '>', '\"', \"'\", '\\\\', '/'];\n const hasSuspiciousPattern = suspiciousPatterns.some((pattern) => channelId.includes(pattern));\n\n if (hasSuspiciousPattern) {\n if (clientIp) {\n logger.warn(`[SECURITY] Suspicious channel ID pattern from ${clientIp}: ${channelId}`);\n }\n return null;\n }\n\n return validatedUuid;\n};\n\n/**\n * Validates a memory ID parameter\n */\nexport const validateMemoryId = (memoryId: string): UUID | null => {\n return validateUuid(memoryId);\n};\n\n/**\n * Validates a world ID parameter\n */\nexport const validateWorldId = (worldId: string): UUID | null => {\n return validateUuid(worldId);\n};\n","import express from 'express';\nimport { createAgentMediaRouter } from './agents';\nimport { createChannelMediaRouter } from './channels';\n\n/**\n * Creates the media router for file uploads and media handling\n */\nexport function mediaRouter(): express.Router {\n const router = express.Router();\n\n // Mount agent media uploads under /agents\n router.use('/agents', createAgentMediaRouter());\n\n // Mount channel media uploads under /channels\n router.use('/channels', createChannelMediaRouter());\n\n return router;\n}\n","import { validateUuid, logger, getContentTypeFromMimeType } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\nimport { cleanupUploadedFile } from '../shared/file-utils';\nimport { agentMediaUpload, validateMediaFile, processUploadedFile } from '../shared/uploads';\nimport type fileUpload from 'express-fileupload';\n\n// Using express-fileupload file type\ntype UploadedFile = fileUpload.UploadedFile;\n\ninterface AgentMediaRequest extends Omit<express.Request, 'files'> {\n files?: { [fieldname: string]: UploadedFile | UploadedFile[] } | UploadedFile[];\n params: {\n agentId: string;\n };\n}\n\n/**\n * Agent media upload functionality\n */\nexport function createAgentMediaRouter(): express.Router {\n const router = express.Router();\n\n // Media upload endpoint for images and videos\n router.post('/:agentId/upload-media', agentMediaUpload(), async (req, res) => {\n const agentMediaReq = req as AgentMediaRequest;\n\n logger.debug('[MEDIA UPLOAD] Processing media upload');\n const agentId = validateUuid(agentMediaReq.params.agentId);\n\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n // Get the uploaded file from express-fileupload\n let mediaFile: UploadedFile;\n if (agentMediaReq.files && !Array.isArray(agentMediaReq.files)) {\n // files is an object with field names\n mediaFile = agentMediaReq.files.file as UploadedFile;\n } else if (Array.isArray(agentMediaReq.files) && agentMediaReq.files.length > 0) {\n // files is an array\n mediaFile = agentMediaReq.files[0];\n } else {\n return sendError(res, 400, 'INVALID_REQUEST', 'No media file provided');\n }\n\n if (!mediaFile) {\n return sendError(res, 400, 'INVALID_REQUEST', 'No media file provided');\n }\n\n const mimetype = mediaFile.mimetype;\n\n if (!validateMediaFile(mediaFile)) {\n cleanupUploadedFile(mediaFile);\n return sendError(res, 400, 'INVALID_FILE_TYPE', 'Unsupported media file type');\n }\n\n const mediaType = getContentTypeFromMimeType(mimetype);\n\n if (!mediaType) {\n cleanupUploadedFile(mediaFile);\n return sendError(\n res,\n 400,\n 'UNSUPPORTED_MEDIA_TYPE',\n `Unsupported media MIME type: ${mimetype}`\n );\n }\n\n try {\n // Process and move the uploaded file\n const result = await processUploadedFile(mediaFile, agentId, 'agents');\n\n logger.info(\n `[MEDIA UPLOAD] Successfully uploaded ${mediaType}: ${result.filename}. URL: ${result.url}`\n );\n\n sendSuccess(res, {\n url: result.url,\n type: mediaType,\n filename: result.filename,\n originalName: mediaFile.name,\n size: mediaFile.size,\n });\n } catch (error) {\n logger.error(`[MEDIA UPLOAD] Error processing upload: ${error}`);\n cleanupUploadedFile(mediaFile);\n sendError(\n res,\n 500,\n 'UPLOAD_ERROR',\n 'Failed to process media upload',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import { validateUuid, logger } from '@elizaos/core';\nimport express from 'express';\nimport rateLimit from 'express-rate-limit';\nimport { channelUpload, validateMediaFile, processUploadedFile } from '../shared/uploads';\nimport { cleanupUploadedFile } from '../shared/file-utils';\nimport type fileUpload from 'express-fileupload';\n\n// Using express-fileupload file type\ntype UploadedFile = fileUpload.UploadedFile;\n\ninterface ChannelMediaRequest extends Omit<express.Request, 'files'> {\n files?: { [fieldname: string]: UploadedFile | UploadedFile[] } | UploadedFile[];\n params: {\n channelId: string;\n };\n}\n\n/**\n * Channel media upload functionality\n */\nexport function createChannelMediaRouter(): express.Router {\n const router = express.Router();\n\n // Define rate limiter: maximum 100 requests per 15 minutes\n const uploadMediaRateLimiter = rateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 100, // Limit each IP to 100 requests per windowMs\n message: { success: false, error: 'Too many requests, please try again later.' },\n });\n\n // Upload media to channel\n router.post(\n '/:channelId/upload-media',\n uploadMediaRateLimiter, // Apply rate limiter\n channelUpload(),\n async (req, res) => {\n const channelMediaReq = req as ChannelMediaRequest;\n const channelId = validateUuid(channelMediaReq.params.channelId);\n if (!channelId) {\n res.status(400).json({ success: false, error: 'Invalid channelId format' });\n return;\n }\n\n // Get the uploaded file from express-fileupload\n let mediaFile: UploadedFile;\n if (channelMediaReq.files && !Array.isArray(channelMediaReq.files)) {\n // files is an object with field names\n mediaFile = channelMediaReq.files.file as UploadedFile;\n } else if (Array.isArray(channelMediaReq.files) && channelMediaReq.files.length > 0) {\n // files is an array\n mediaFile = channelMediaReq.files[0];\n } else {\n res.status(400).json({ success: false, error: 'No media file provided' });\n return;\n }\n\n if (!mediaFile) {\n res.status(400).json({ success: false, error: 'No media file provided' });\n return;\n }\n\n // Validate file type using the helper function\n if (!validateMediaFile(mediaFile)) {\n cleanupUploadedFile(mediaFile);\n res.status(400).json({ success: false, error: `Invalid file type: ${mediaFile.mimetype}` });\n return;\n }\n\n try {\n // Process and move the uploaded file\n const result = await processUploadedFile(mediaFile, channelId, 'channels');\n\n logger.info(\n `[Channel Media Upload] File uploaded for channel ${channelId}: ${result.filename}. URL: ${result.url}`\n );\n\n res.json({\n success: true,\n data: {\n url: result.url, // Relative URL, client prepends server origin\n type: mediaFile.mimetype,\n filename: result.filename,\n originalName: mediaFile.name,\n size: mediaFile.size,\n },\n });\n } catch (error: any) {\n logger.error(\n `[Channel Media Upload] Error processing upload for channel ${channelId}: ${error.message}`,\n error\n );\n cleanupUploadedFile(mediaFile);\n res.status(500).json({ success: false, error: 'Failed to process media upload' });\n }\n }\n );\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { createAgentMemoryRouter } from './agents';\nimport { createGroupMemoryRouter } from './groups';\nimport { createRoomManagementRouter } from './rooms';\n\n/**\n * Creates the memory router for memory and knowledge management\n */\nexport function memoryRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n // Mount agent memory management at root level\n router.use('/', createAgentMemoryRouter(agents));\n\n // Mount group memory management\n router.use('/', createGroupMemoryRouter(agents, serverInstance));\n\n // Mount room management\n router.use('/', createRoomManagementRouter(agents));\n\n return router;\n}\n","import type { IAgentRuntime, Room, UUID } from '@elizaos/core';\nimport { validateUuid, logger, createUniqueUuid, ChannelType } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { sendError, getRuntime } from '../shared';\n\n/**\n * Group and world memory management functionality\n */\nexport function createGroupMemoryRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n const db = serverInstance?.database;\n\n // Create group memory spaces for multiple agents\n router.post('/groups/:serverId', async (req, res) => {\n const serverId = validateUuid(req.params.serverId);\n const { name, worldId, source, metadata, agentIds = [] } = req.body;\n\n if (!Array.isArray(agentIds) || agentIds.length === 0) {\n return sendError(res, 400, 'BAD_REQUEST', 'agentIds must be a non-empty array');\n }\n\n let results: Room[] = [];\n let errors: {\n agentId: UUID;\n code: string;\n message: string;\n details: string;\n }[] = [];\n\n for (const agentId of agentIds) {\n try {\n const runtime = getRuntime(agents, agentId as UUID);\n const roomId = createUniqueUuid(runtime, serverId as string);\n const roomName = name || `Chat ${new Date().toLocaleString()}`;\n\n await runtime.ensureWorldExists({\n id: worldId,\n name: source,\n agentId: runtime.agentId,\n serverId: serverId as UUID,\n });\n\n await runtime.ensureRoomExists({\n id: roomId,\n name: roomName,\n source,\n type: ChannelType.API,\n worldId,\n serverId: serverId as UUID,\n metadata,\n channelId: roomId,\n });\n\n await runtime.addParticipant(runtime.agentId, roomId);\n await runtime.ensureParticipantInRoom(runtime.agentId, roomId);\n await runtime.setParticipantUserState(roomId, runtime.agentId, 'FOLLOWED');\n\n results.push({\n id: roomId,\n name: roomName,\n source: 'client',\n worldId,\n type: ChannelType.API,\n });\n } catch (error) {\n logger.error(`[ROOM CREATE] Error creating room for agent ${agentId}:`, error);\n errors.push({\n agentId,\n code:\n error instanceof Error && error.message === 'Agent not found'\n ? 'NOT_FOUND'\n : 'CREATE_ERROR',\n message:\n error instanceof Error && error.message === 'Agent not found'\n ? error.message\n : 'Failed to Create group',\n details: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (results.length === 0 && errors.length > 0) {\n res.status(500).json({\n success: false,\n error: errors.length\n ? errors\n : [{ code: 'UNKNOWN_ERROR', message: 'No rooms were created' }],\n });\n return;\n }\n\n res.status(errors.length ? 207 : 201).json({\n success: errors.length === 0,\n data: results,\n errors: errors.length ? errors : undefined,\n });\n });\n\n // Delete group\n router.delete('/groups/:serverId', async (req, res) => {\n const worldId = validateUuid(req.params.serverId);\n if (!worldId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid serverId (worldId) format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n try {\n await db.deleteRoomsByWorldId(worldId);\n res.status(204).send();\n } catch (error) {\n logger.error('[GROUP DELETE] Error deleting group:', error);\n sendError(\n res,\n 500,\n 'DELETE_ERROR',\n 'Error deleting group',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Clear group memories\n router.delete('/groups/:serverId/memories', async (req, res) => {\n const worldId = validateUuid(req.params.serverId);\n if (!worldId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid serverId (worldId) format');\n }\n if (!db) {\n return sendError(res, 500, 'DB_ERROR', 'Database not available');\n }\n\n try {\n const memories = await db.getMemoriesByWorldId({ worldId, tableName: 'messages' });\n const memoryIds = memories.map((memory) => memory.id as UUID);\n\n if (memoryIds.length > 0) {\n await (db as any).deleteManyMemories(memoryIds);\n }\n\n res.status(204).send();\n } catch (error) {\n logger.error('[GROUP MEMORIES DELETE] Error clearing memories:', error);\n sendError(\n res,\n 500,\n 'DELETE_ERROR',\n 'Error deleting group memories',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, Room, UUID } from '@elizaos/core';\nimport { validateUuid, logger, createUniqueUuid, ChannelType } from '@elizaos/core';\nimport express from 'express';\nimport { sendError, sendSuccess } from '../shared/response-utils';\n\ninterface CustomRequest extends express.Request {\n params: {\n agentId: string;\n roomId?: string;\n };\n}\n\n/**\n * Room management functionality for agents\n */\nexport function createRoomManagementRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Create a new room for an agent\n router.post('/:agentId/rooms', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const { name, type = ChannelType.DM, source = 'client', worldId, metadata } = req.body;\n\n if (!name) {\n return sendError(res, 400, 'MISSING_PARAM', 'Room name is required');\n }\n\n const roomId = createUniqueUuid(runtime, `room-${Date.now()}`);\n const serverId = req.body.serverId || `server-${Date.now()}`;\n\n let resolvedWorldId = worldId;\n if (!resolvedWorldId) {\n const worldName = `World for ${name}`;\n resolvedWorldId = createUniqueUuid(runtime, `world-${Date.now()}`);\n\n await runtime.ensureWorldExists({\n id: resolvedWorldId,\n name: worldName,\n agentId: runtime.agentId,\n serverId: serverId,\n metadata: metadata,\n });\n }\n\n await runtime.ensureRoomExists({\n id: roomId,\n name: name,\n source: source,\n type: type,\n channelId: roomId,\n serverId: serverId,\n worldId: resolvedWorldId,\n metadata: metadata,\n });\n\n await runtime.addParticipant(runtime.agentId, roomId);\n await runtime.ensureParticipantInRoom(runtime.agentId, roomId);\n await runtime.setParticipantUserState(roomId, runtime.agentId, 'FOLLOWED');\n\n sendSuccess(\n res,\n {\n id: roomId,\n name: name,\n agentId: agentId,\n createdAt: Date.now(),\n source: source,\n type: type,\n worldId: resolvedWorldId,\n serverId: serverId,\n metadata: metadata,\n },\n 201\n );\n } catch (error) {\n logger.error(`[ROOM CREATE] Error creating room for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'CREATE_ERROR',\n 'Failed to create room',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Get all rooms where an agent is a participant\n router.get('/:agentId/rooms', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const worlds = await runtime.getAllWorlds();\n const participantRoomIds = await runtime.getRoomsForParticipant(agentId);\n const agentRooms: Room[] = [];\n\n for (const world of worlds) {\n const worldRooms = await runtime.getRooms(world.id);\n for (const room of worldRooms) {\n if (participantRoomIds.includes(room.id)) {\n agentRooms.push({\n ...room,\n });\n }\n }\n }\n\n sendSuccess(res, { rooms: agentRooms });\n } catch (error) {\n logger.error(`[ROOMS LIST] Error retrieving rooms for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'RETRIEVAL_ERROR',\n 'Failed to retrieve agent rooms',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Get room details\n router.get('/:agentId/rooms/:roomId', async (req: CustomRequest, res: express.Response) => {\n const agentId = validateUuid(req.params.agentId);\n const roomId = validateUuid(req.params.roomId);\n\n if (!agentId || !roomId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID or room ID format');\n }\n\n // Get runtime\n const runtime = agents.get(agentId);\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const room = await runtime.getRoom(roomId);\n if (!room) {\n return sendError(res, 404, 'NOT_FOUND', 'Room not found');\n }\n\n // Enrich room data with world name\n let worldName: string | undefined;\n if (room.worldId) {\n const world = await runtime.getWorld(room.worldId);\n worldName = world?.name;\n }\n\n sendSuccess(res, {\n ...room,\n ...(worldName && { worldName }),\n });\n } catch (error) {\n logger.error(`[ROOM DETAILS] Error retrieving room ${roomId} for agent ${agentId}:`, error);\n sendError(\n res,\n 500,\n 'RETRIEVAL_ERROR',\n 'Failed to retrieve room details',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport { createAudioProcessingRouter } from './processing';\nimport { createSynthesisRouter } from './synthesis';\nimport { createConversationRouter } from './conversation';\n\n/**\n * Creates the audio router for speech and audio processing\n */\nexport function audioRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Mount audio processing (upload, transcription)\n router.use('/', createAudioProcessingRouter(agents));\n\n // Mount text-to-speech synthesis\n router.use('/', createSynthesisRouter(agents));\n\n // Mount speech conversation functionality\n router.use('/', createConversationRouter(agents));\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { logger, ModelType, validateUuid } from '@elizaos/core';\nimport express from 'express';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { cleanupUploadedFile } from '../shared/file-utils';\nimport { sendError, sendSuccess } from '../shared/response-utils';\nimport { agentAudioUpload, validateAudioFile } from '../shared/uploads';\nimport { createFileSystemRateLimit, createUploadRateLimit } from '../shared/middleware';\nimport { MAX_FILE_SIZE, MAX_FILE_SIZE_DISPLAY } from '../shared/constants';\nimport type fileUpload from 'express-fileupload';\n\n// Using express-fileupload file type\ntype UploadedFile = fileUpload.UploadedFile;\n\ninterface AudioRequest extends Omit<express.Request, 'files'> {\n files?: { [fieldname: string]: UploadedFile | UploadedFile[] } | UploadedFile[];\n params: {\n agentId: string;\n };\n}\n\n/**\n * Securely validates a file path to prevent path traversal attacks\n */\nfunction validateSecureFilePath(filePath: string): string {\n if (!filePath) {\n throw new Error('File path is required');\n }\n\n // Resolve and normalize the path\n const resolvedPath = path.resolve(filePath);\n const normalizedPath = path.normalize(resolvedPath);\n\n // Ensure the path doesn't contain directory traversal attempts\n if (normalizedPath.includes('..') || normalizedPath !== resolvedPath) {\n throw new Error('Invalid file path: path traversal detected');\n }\n\n // Ensure the path is within the current working directory or system temp\n const allowedBasePaths = [process.cwd(), os.tmpdir(), os.homedir()];\n\n const isPathAllowed = allowedBasePaths.some((basePath) =>\n normalizedPath.startsWith(path.resolve(basePath))\n );\n\n if (!isPathAllowed) {\n throw new Error('Invalid file path: path outside allowed directories');\n }\n\n // Additional security: ensure file exists and is a regular file\n try {\n const stats = fs.statSync(normalizedPath);\n if (!stats.isFile()) {\n throw new Error('Path does not point to a regular file');\n }\n } catch (error) {\n throw new Error(`File access error: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return normalizedPath;\n}\n\n/**\n * Helper function to get uploaded file from express-fileupload request\n */\nfunction getUploadedFile(req: AudioRequest): UploadedFile | null {\n if (req.files && !Array.isArray(req.files)) {\n // files is an object with field names\n return req.files.file as UploadedFile;\n } else if (Array.isArray(req.files) && req.files.length > 0) {\n // files is an array\n return req.files[0];\n }\n return null;\n}\n\n/**\n * Audio processing functionality - upload and transcription\n */\nexport function createAudioProcessingRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Apply rate limiting to all audio processing routes\n router.use(createUploadRateLimit());\n router.use(createFileSystemRateLimit());\n\n // Audio messages endpoints\n router.post(\n '/:agentId/audio-messages',\n agentAudioUpload(), // Use agentAudioUpload\n async (req, res) => {\n const audioReq = req as AudioRequest;\n logger.debug('[AUDIO MESSAGE] Processing audio message');\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const audioFile = getUploadedFile(audioReq);\n if (!audioFile) {\n return sendError(res, 400, 'INVALID_REQUEST', 'No audio file provided');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n cleanupUploadedFile(audioFile);\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n // Validate file type\n if (!validateAudioFile(audioFile)) {\n cleanupUploadedFile(audioFile);\n return sendError(res, 400, 'INVALID_FILE_TYPE', 'Invalid audio file type');\n }\n\n // Validate file path security before any file operations\n let securePath: string;\n try {\n const filePath = audioFile.tempFilePath || '';\n securePath = validateSecureFilePath(filePath);\n } catch (pathError) {\n cleanupUploadedFile(audioFile);\n return sendError(\n res,\n 403,\n 'INVALID_PATH',\n `Invalid file path: ${pathError instanceof Error ? pathError.message : String(pathError)}`\n );\n }\n\n // Additional file validation using secure path\n const stats = await fs.promises.stat(securePath);\n if (stats.size > MAX_FILE_SIZE) {\n cleanupUploadedFile(audioFile);\n return sendError(\n res,\n 413,\n 'FILE_TOO_LARGE',\n `Audio file too large (max ${MAX_FILE_SIZE_DISPLAY})`\n );\n }\n\n const audioBuffer = await fs.promises.readFile(securePath);\n const transcription = await runtime.useModel(ModelType.TRANSCRIPTION, audioBuffer);\n\n // Placeholder: This part needs to be updated to align with message creation.\n logger.info(`[AUDIO MESSAGE] Transcription for agent ${agentId}: ${transcription}`);\n cleanupUploadedFile(audioFile);\n sendSuccess(res, { transcription, message: 'Audio transcribed, further processing TBD.' });\n } catch (error) {\n logger.error('[AUDIO MESSAGE] Error processing audio:', error);\n cleanupUploadedFile(audioFile);\n sendError(\n res,\n 500,\n 'PROCESSING_ERROR',\n 'Error processing audio message',\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n );\n\n // Transcription endpoint\n router.post(\n '/:agentId/transcriptions',\n agentAudioUpload(), // Use agentAudioUpload\n async (req, res) => {\n const audioReq = req as AudioRequest;\n logger.debug('[TRANSCRIPTION] Request to transcribe audio');\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const audioFile = getUploadedFile(audioReq);\n if (!audioFile) {\n return sendError(res, 400, 'INVALID_REQUEST', 'No audio file provided');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n cleanupUploadedFile(audioFile);\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n logger.debug('[TRANSCRIPTION] Reading audio file');\n\n // Validate file type\n if (!validateAudioFile(audioFile)) {\n cleanupUploadedFile(audioFile);\n return sendError(res, 400, 'INVALID_FILE_TYPE', 'Invalid audio file type');\n }\n\n // Validate file path security before any file operations\n let securePath: string;\n try {\n const filePath = audioFile.tempFilePath || '';\n securePath = validateSecureFilePath(filePath);\n } catch (pathError) {\n cleanupUploadedFile(audioFile);\n return sendError(\n res,\n 403,\n 'INVALID_PATH',\n `Invalid file path: ${pathError instanceof Error ? pathError.message : String(pathError)}`\n );\n }\n\n const stats = await fs.promises.stat(securePath);\n if (stats.size > MAX_FILE_SIZE) {\n cleanupUploadedFile(audioFile);\n return sendError(\n res,\n 413,\n 'FILE_TOO_LARGE',\n `Audio file too large (max ${MAX_FILE_SIZE_DISPLAY})`\n );\n }\n\n const audioBuffer = await fs.promises.readFile(securePath);\n\n logger.debug('[TRANSCRIPTION] Transcribing audio');\n const transcription = await runtime.useModel(ModelType.TRANSCRIPTION, audioBuffer);\n\n cleanupUploadedFile(audioFile);\n\n if (!transcription) {\n return sendError(res, 500, 'PROCESSING_ERROR', 'Failed to transcribe audio');\n }\n\n logger.success('[TRANSCRIPTION] Successfully transcribed audio');\n sendSuccess(res, { text: transcription });\n } catch (error) {\n logger.error('[TRANSCRIPTION] Error transcribing audio:', error);\n cleanupUploadedFile(audioFile);\n sendError(\n res,\n 500,\n 'PROCESSING_ERROR',\n 'Error transcribing audio',\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n );\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { validateUuid, logger, ModelType } from '@elizaos/core';\nimport express from 'express';\nimport { sendError } from '../shared/response-utils';\nimport { convertToAudioBuffer } from './audioBuffer';\n\n/**\n * Text-to-speech synthesis functionality\n */\nexport function createSynthesisRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Text-to-Speech endpoint\n router.post('/:agentId/audio-messages/synthesize', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const { text } = req.body;\n if (!text) {\n return sendError(res, 400, 'INVALID_REQUEST', 'Text is required for speech synthesis');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const speechResponse = await runtime.useModel(ModelType.TEXT_TO_SPEECH, text);\n const audioResult = await convertToAudioBuffer(speechResponse, true);\n\n logger.debug('[TTS] Setting response headers');\n res.set({\n 'Content-Type': audioResult.mimeType,\n 'Content-Length': audioResult.buffer.length.toString(),\n });\n\n res.send(audioResult.buffer);\n } catch (error) {\n logger.error('[TTS] Error generating speech:', error);\n sendError(\n res,\n 500,\n 'PROCESSING_ERROR',\n 'Error generating speech',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n // Speech generation endpoint\n router.post('/:agentId/speech/generate', async (req, res) => {\n logger.debug('[SPEECH GENERATE] Request to generate speech from text');\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const { text } = req.body;\n if (!text) {\n return sendError(res, 400, 'INVALID_REQUEST', 'Text is required for speech synthesis');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n logger.debug('[SPEECH GENERATE] Using text-to-speech model');\n const speechResponse = await runtime.useModel(ModelType.TEXT_TO_SPEECH, text);\n const audioResult = await convertToAudioBuffer(speechResponse, true);\n logger.debug('[SPEECH GENERATE] Detected audio MIME type:', audioResult.mimeType);\n\n logger.debug('[SPEECH GENERATE] Setting response headers');\n res.set({\n 'Content-Type': audioResult.mimeType,\n 'Content-Length': audioResult.buffer.length.toString(),\n });\n\n res.send(audioResult.buffer);\n logger.success(\n `[SPEECH GENERATE] Successfully generated speech for: ${runtime.character.name}`\n );\n } catch (error) {\n logger.error('[SPEECH GENERATE] Error generating speech:', error);\n sendError(\n res,\n 500,\n 'PROCESSING_ERROR',\n 'Error generating speech',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import { Readable } from 'node:stream';\n\n/**\n * Determines the appropriate MIME type for audio data based on its format.\n * Detects WAV files by checking for the RIFF header signature.\n *\n * @param audioBuffer - The audio data buffer to check\n * @returns The appropriate MIME type string\n */\nexport function getAudioMimeType(audioBuffer: Buffer): string {\n // Check if this is a WAV file by looking for the RIFF header\n // WAV files start with the signature \"RIFF\" followed by file size,\n // then \"WAVE\" identifier\n if (\n audioBuffer.length >= 12 &&\n audioBuffer.toString('ascii', 0, 4) === 'RIFF' &&\n audioBuffer.toString('ascii', 8, 12) === 'WAVE'\n ) {\n return 'audio/wav';\n }\n\n // MP3 files typically start with ID3 tag or directly with an MP3 frame\n // Check for ID3 tag (ID3v2)\n if (audioBuffer.length >= 3 && audioBuffer.toString('ascii', 0, 3) === 'ID3') {\n return 'audio/mpeg';\n }\n\n // Check for MP3 frame header (begins with 0xFF followed by 0xE or 0xF)\n if (audioBuffer.length >= 2 && audioBuffer[0] === 0xff && (audioBuffer[1] & 0xe0) === 0xe0) {\n return 'audio/mpeg';\n }\n\n // Default to MP3 if we can't determine (maintaining backward compatibility)\n return 'audio/mpeg';\n}\n\n/**\n * Result of audio processing containing the buffer and MIME type\n */\nexport interface AudioProcessingResult {\n buffer: Buffer;\n mimeType: string;\n}\n\nexport async function convertToAudioBuffer(speechResponse: any): Promise<Buffer>;\nexport async function convertToAudioBuffer(\n speechResponse: any,\n detectMimeType: true\n): Promise<AudioProcessingResult>;\nexport async function convertToAudioBuffer(\n speechResponse: any,\n detectMimeType?: boolean\n): Promise<Buffer | AudioProcessingResult> {\n let resultBuffer: Buffer;\n\n if (Buffer.isBuffer(speechResponse)) {\n resultBuffer = speechResponse;\n } else if (typeof speechResponse?.getReader === 'function') {\n // Handle Web ReadableStream\n const reader = (speechResponse as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n resultBuffer = Buffer.concat(chunks);\n } finally {\n reader.releaseLock();\n }\n } else if (\n speechResponse instanceof Readable ||\n (speechResponse &&\n speechResponse.readable === true &&\n typeof speechResponse.pipe === 'function' &&\n typeof speechResponse.on === 'function')\n ) {\n // Handle Node Readable Stream\n resultBuffer = await new Promise<Buffer>((resolve, reject) => {\n const chunks: Buffer[] = [];\n speechResponse.on('data', (chunk: any) =>\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n );\n speechResponse.on('end', () => resolve(Buffer.concat(chunks)));\n speechResponse.on('error', (err: Error) => reject(err));\n });\n } else {\n throw new Error('Unexpected response type from TEXT_TO_SPEECH model');\n }\n\n // Return both buffer and MIME type if requested\n if (detectMimeType) {\n return {\n buffer: resultBuffer,\n mimeType: getAudioMimeType(resultBuffer),\n };\n }\n\n // Otherwise just return the buffer for backward compatibility\n return resultBuffer;\n}\n","import type { IAgentRuntime, UUID, Content, Memory } from '@elizaos/core';\nimport {\n validateUuid,\n logger,\n ModelType,\n ChannelType,\n createUniqueUuid,\n composePrompt,\n messageHandlerTemplate,\n} from '@elizaos/core';\nimport express from 'express';\nimport { sendError } from '../shared/response-utils';\nimport { convertToAudioBuffer } from './audioBuffer';\n\n/**\n * Speech conversation functionality\n */\nexport function createConversationRouter(agents: Map<UUID, IAgentRuntime>): express.Router {\n const router = express.Router();\n\n // Speech conversation endpoint\n router.post('/:agentId/speech/conversation', async (req, res) => {\n const agentId = validateUuid(req.params.agentId);\n if (!agentId) {\n return sendError(res, 400, 'INVALID_ID', 'Invalid agent ID format');\n }\n\n const { text, roomId: rawRoomId, entityId: rawUserId, worldId: rawWorldId } = req.body;\n if (!text) {\n return sendError(res, 400, 'INVALID_REQUEST', 'Text is required for conversation');\n }\n\n const runtime = agents.get(agentId);\n\n if (!runtime) {\n return sendError(res, 404, 'NOT_FOUND', 'Agent not found');\n }\n\n try {\n const roomId = createUniqueUuid(runtime, rawRoomId ?? `default-room-${agentId}`);\n const entityId = createUniqueUuid(runtime, rawUserId ?? 'Anon');\n const worldId = rawWorldId ?? createUniqueUuid(runtime, 'direct');\n\n logger.debug('[SPEECH CONVERSATION] Ensuring connection');\n await runtime.ensureConnection({\n entityId,\n roomId,\n userName: req.body.userName,\n name: req.body.name,\n source: 'direct',\n type: ChannelType.API,\n worldId,\n worldName: 'Direct',\n });\n\n const messageId = createUniqueUuid(runtime, Date.now().toString());\n const content: Content = {\n text,\n attachments: [],\n source: 'direct',\n inReplyTo: undefined,\n channelType: ChannelType.API,\n };\n\n const userMessageMemory: Memory = {\n id: messageId,\n entityId,\n roomId,\n worldId,\n agentId: runtime.agentId,\n content,\n createdAt: Date.now(),\n };\n\n logger.debug('[SPEECH CONVERSATION] Creating memory');\n await runtime.createMemory(userMessageMemory, 'messages');\n\n logger.debug('[SPEECH CONVERSATION] Composing state');\n const state = await runtime.composeState(userMessageMemory);\n\n logger.debug('[SPEECH CONVERSATION] Creating context');\n const prompt = composePrompt({\n state,\n template: messageHandlerTemplate,\n });\n\n logger.debug('[SPEECH CONVERSATION] Using LLM for response');\n const llmResponse = await runtime.useModel(ModelType.TEXT_LARGE, {\n // Renamed to llmResponse\n messages: [\n {\n role: 'system',\n content: messageHandlerTemplate,\n },\n {\n role: 'user',\n content: prompt,\n },\n ],\n });\n\n if (!llmResponse) {\n return sendError(res, 500, 'MODEL_ERROR', 'No response from model');\n }\n\n logger.debug('[SPEECH CONVERSATION] Creating response memory');\n\n const responseMessage: Memory = {\n // Explicitly type as Memory\n id: createUniqueUuid(runtime, `resp-${messageId}`), // Ensure new ID for response\n entityId: runtime.agentId, // Agent is sender\n agentId: runtime.agentId,\n roomId: roomId as UUID,\n worldId,\n content: { text: llmResponse, inReplyTo: messageId }, // Use llmResponse\n createdAt: Date.now(),\n };\n\n await runtime.createMemory(responseMessage, 'messages');\n await runtime.evaluate(userMessageMemory, state);\n\n await runtime.processActions(\n userMessageMemory,\n [responseMessage],\n state,\n async () => [userMessageMemory] // Callback should return relevant memories\n );\n\n logger.debug('[SPEECH CONVERSATION] Generating speech response from LLM output');\n\n const speechAudioResponse = await runtime.useModel(ModelType.TEXT_TO_SPEECH, llmResponse); // Use llmResponse for TTS\n const audioResult = await convertToAudioBuffer(speechAudioResponse, true);\n\n logger.debug('[SPEECH CONVERSATION] Setting response headers');\n\n res.set({\n 'Content-Type': audioResult.mimeType,\n 'Content-Length': audioResult.buffer.length.toString(),\n });\n\n res.send(audioResult.buffer);\n\n logger.success(\n `[SPEECH CONVERSATION] Successfully processed conversation for: ${runtime.character.name}`\n );\n } catch (error) {\n logger.error('[SPEECH CONVERSATION] Error processing conversation:', error);\n sendError(\n res,\n 500,\n 'PROCESSING_ERROR',\n 'Error processing conversation',\n error instanceof Error ? error.message : String(error)\n );\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\nimport { createHealthRouter } from './health';\nimport { createLoggingRouter } from './logging';\nimport { createDebugRouter } from './debug';\n\n/**\n * Creates the runtime router for system operations and health monitoring\n */\nexport function runtimeRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n // Mount health endpoints at root level\n router.use('/', createHealthRouter(agents, serverInstance));\n\n // Mount logging endpoints\n router.use('/', createLoggingRouter(agents, serverInstance));\n\n // Mount debug endpoints under /debug\n router.use('/debug', createDebugRouter(serverInstance));\n\n return router;\n}\n","import type { IAgentRuntime, UUID } from '@elizaos/core';\nimport { logger } from '@elizaos/core';\nimport express from 'express';\nimport type { AgentServer } from '../../index';\n\n/**\n * Health monitoring and status endpoints\n */\nexport function createHealthRouter(\n agents: Map<UUID, IAgentRuntime>,\n serverInstance: AgentServer\n): express.Router {\n const router = express.Router();\n\n // Health check\n router.get('/ping', (_req, res) => {\n res.json({ pong: true, timestamp: Date.now() });\n });\n\n // Hello world endpoint\n router.get('/hello', (_req, res) => {\n logger.info('Hello endpoint hit');\n res.setHeader('Content-Type', 'application/json');\n res.send(JSON.stringify({ message: 'Hello World!' }));\n });\n\n // System status endpoint\n router.get('/status', (_req, res) => {\n logger.info('Status endpoint hit');\n res.setHeader('Content-Type', 'application/json');\n res.send(\n JSON.stringify({\n status: 'ok',\n agentCount: agents.size,\n timestamp: new Date().toISOString(),\n })\n );\n });\n\n // Comprehensive health check\n router.get('/health', (_req, res) => {\n logger.log({ apiRoute: '/health' }, 'Health check route hit');\n const healthcheck = {\n status: 'OK',\n version: process.env.APP_VERSION || 'unknown',\n timestamp: new Date().toISOString(),\n dependencies: {\n agents: agents.size > 0 ? 'healthy' : 'no_agents',\n },\n };\n\n const statusCode = healthcheck.dependencies.agents === 'healthy' ? 200 : 503;\n res.status(statusCode).json(healthcheck);\n });\n\n // Server stop endpoint\n router.post('/stop', (_req, res) => {\n logger.log({ apiRoute: '/stop' }, 'Server stopping...');\n serverInstance?.stop(); // Use optional chaining in case server is undefined\n res.json({ message: 'Server stopping...' });\n });\n\n return router;\n}\n","import { logger } from '@elizaos/core';\nimport express from 'express';\n\n// Custom levels from @elizaos/core logger\nconst LOG_LEVELS = {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n log: 29,\n progress: 28,\n success: 27,\n debug: 20,\n trace: 10,\n} as const;\n\n/**\n * Defines a type `LogLevel` as the keys of the `LOG_LEVELS` object.\n */\ntype LogLevel = keyof typeof LOG_LEVELS | 'all';\n\n/**\n * Represents a log entry with specific properties.\n */\ninterface LogEntry {\n level: number;\n time: number;\n msg: string;\n [key: string]: string | number | boolean | null | undefined;\n}\n\n/**\n * Logging management endpoints\n */\nexport function createLoggingRouter(): express.Router {\n const router = express.Router();\n\n // Logs endpoint handler\n const logsHandler = async (req: express.Request, res: express.Response) => {\n const since = req.query.since ? Number(req.query.since) : Date.now() - 3600000; // Default 1 hour\n const requestedLevel = (req.query.level?.toString().toLowerCase() || 'all') as LogLevel;\n const requestedAgentName = req.query.agentName?.toString() || 'all';\n const requestedAgentId = req.query.agentId?.toString() || 'all'; // Add support for agentId parameter\n const limit = Math.min(Number(req.query.limit) || 100, 1000); // Max 1000 entries\n\n // Access the underlying logger instance\n const destination = (logger as any)[Symbol.for('pino-destination')];\n\n if (!destination?.recentLogs) {\n return res.status(500).json({\n error: 'Logger destination not available',\n message: 'The logger is not configured to maintain recent logs',\n });\n }\n\n try {\n // Get logs from the destination's buffer\n const recentLogs: LogEntry[] = destination.recentLogs();\n const requestedLevelValue =\n requestedLevel === 'all'\n ? 0 // Show all levels when 'all' is requested\n : LOG_LEVELS[requestedLevel as keyof typeof LOG_LEVELS] || LOG_LEVELS.info;\n\n // Calculate population rates once for efficiency\n const logsWithAgentNames = recentLogs.filter((l) => l.agentName).length;\n const logsWithAgentIds = recentLogs.filter((l) => l.agentId).length;\n const totalLogs = recentLogs.length;\n const agentNamePopulationRate = totalLogs > 0 ? logsWithAgentNames / totalLogs : 0;\n const agentIdPopulationRate = totalLogs > 0 ? logsWithAgentIds / totalLogs : 0;\n\n // If less than 10% of logs have agent metadata, be lenient with filtering\n const isAgentNameDataSparse = agentNamePopulationRate < 0.1;\n const isAgentIdDataSparse = agentIdPopulationRate < 0.1;\n\n const filtered = recentLogs\n .filter((log) => {\n // Filter by time always\n const timeMatch = log.time >= since;\n\n // Filter by level - return all logs if requestedLevel is 'all'\n let levelMatch = true;\n if (requestedLevel && requestedLevel !== 'all') {\n levelMatch = log.level === requestedLevelValue;\n }\n\n // Filter by agentName if provided - return all if 'all'\n let agentNameMatch = true;\n if (requestedAgentName && requestedAgentName !== 'all') {\n if (log.agentName) {\n // If the log has an agentName, match it exactly\n agentNameMatch = log.agentName === requestedAgentName;\n } else {\n // If log has no agentName but most logs lack agentNames, show all logs\n // This handles the case where logs aren't properly tagged with agent names\n agentNameMatch = isAgentNameDataSparse;\n }\n }\n\n // Filter by agentId if provided - return all if 'all'\n let agentIdMatch = true;\n if (requestedAgentId && requestedAgentId !== 'all') {\n if (log.agentId) {\n // If the log has an agentId, match it exactly\n agentIdMatch = log.agentId === requestedAgentId;\n } else {\n // If log has no agentId but most logs lack agentIds, show all logs\n agentIdMatch = isAgentIdDataSparse;\n }\n }\n\n return timeMatch && levelMatch && agentNameMatch && agentIdMatch;\n })\n .slice(-limit);\n\n // Add debug log to help troubleshoot\n logger.debug('Logs request processed', {\n requestedLevel,\n requestedLevelValue,\n requestedAgentName,\n requestedAgentId,\n filteredCount: filtered.length,\n totalLogs: recentLogs.length,\n logsWithAgentNames,\n logsWithAgentIds,\n agentNamePopulationRate: Math.round(agentNamePopulationRate * 100) + '%',\n agentIdPopulationRate: Math.round(agentIdPopulationRate * 100) + '%',\n isAgentNameDataSparse,\n isAgentIdDataSparse,\n sampleLogAgentNames: recentLogs.slice(0, 5).map((log) => log.agentName),\n uniqueAgentNamesInLogs: [...new Set(recentLogs.map((log) => log.agentName))].filter(\n Boolean\n ),\n exactAgentNameMatches: recentLogs.filter((log) => log.agentName === requestedAgentName)\n .length,\n });\n\n res.json({\n logs: filtered,\n count: filtered.length,\n total: recentLogs.length,\n requestedLevel: requestedLevel,\n agentName: requestedAgentName,\n agentId: requestedAgentId,\n levels: Object.keys(LOG_LEVELS),\n });\n } catch (error) {\n res.status(500).json({\n error: 'Failed to retrieve logs',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n };\n\n // GET and POST endpoints for logs\n (router as any).get('/logs', logsHandler);\n (router as any).post('/logs', logsHandler);\n\n // Handler for clearing logs\n const logsClearHandler = (_req: express.Request, res: express.Response) => {\n try {\n // Access the underlying logger instance\n const destination = (logger as any)[Symbol.for('pino-destination')];\n\n if (!destination?.clear) {\n return res.status(500).json({\n error: 'Logger clear method not available',\n message: 'The logger is not configured to clear logs',\n });\n }\n\n // Clear the logs\n destination.clear();\n\n logger.debug('Logs cleared via API endpoint');\n res.json({ status: 'success', message: 'Logs cleared successfully' });\n } catch (error) {\n res.status(500).json({\n error: 'Failed to clear logs',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n };\n\n // DELETE endpoint for clearing logs\n (router as any).delete('/logs', logsClearHandler);\n\n return router;\n}\n","import express from 'express';\nimport type { AgentServer } from '../../index';\n\n/**\n * Debug and diagnostic endpoints\n */\nexport function createDebugRouter(serverInstance: AgentServer): express.Router {\n const router = express.Router();\n\n // Debug endpoint to check message servers\n router.get('/servers', async (_req, res) => {\n try {\n const servers = await serverInstance?.getServers();\n res.json({\n success: true,\n servers: servers || [],\n count: servers?.length || 0,\n });\n } catch (error) {\n res.status(500).json({\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n return router;\n}\n","import express from 'express';\n// import { createTeeRouter } from './tee';\n\n/**\n * Creates the security router for TEE and security operations\n */\nexport function teeRouter(): express.Router {\n const router = express.Router();\n\n // Mount TEE functionality at root level\n // router.use('/', createTeeRouter(agents));\n\n return router;\n}\n","import express from 'express';\nimport { createEnvironmentRouter } from './environment';\n\n/**\n * Creates the system router for configuration and environment management\n */\nexport function systemRouter(): express.Router {\n const router = express.Router();\n\n // Mount environment management under /env\n router.use('/env', createEnvironmentRouter());\n\n return router;\n}\n","import { logger } from '@elizaos/core';\nimport express from 'express';\nimport { existsSync, writeFileSync } from 'fs';\nimport path from 'path';\nimport dotenv from 'dotenv';\nimport fs from 'fs/promises';\n\nexport type EnvVars = Record<string, string>;\n\n/**\n * Parse an .env file and return the key-value pairs\n * @param filePath Path to the .env file\n * @returns Object containing the key-value pairs\n */\nexport async function parseEnvFile(filePath: string): Promise<EnvVars> {\n try {\n if (!existsSync(filePath)) {\n return {};\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n // Handle empty file case gracefully\n if (content.trim() === '') {\n return {};\n }\n return dotenv.parse(content);\n } catch (error: any) {\n console.error(`Error parsing .env file: ${error.message}`);\n return {};\n }\n}\n\nfunction serializeEnvObject(envObj: Record<string, string>): string {\n return Object.entries(envObj)\n .map(([key, val]) => `${key}=${val ?? ''}`)\n .join('\\n\\n');\n}\n\nfunction getLocalEnvPath(): string | null {\n const envPath = resolveEnvFile();\n return existsSync(envPath) ? envPath : null;\n}\n\n/**\n * Resolves the path to the nearest `.env` file.\n *\n * If no `.env` file is found when traversing up from the starting directory,\n * a path to `.env` in the starting directory is returned.\n *\n * @param startDir - The directory to start searching from. Defaults to the\n * current working directory.\n * @returns The resolved path to the `.env` file.\n */\nexport function resolveEnvFile(startDir: string = process.cwd()): string {\n let currentDir = startDir;\n\n while (true) {\n const candidate = path.join(currentDir, '.env');\n if (existsSync(candidate)) {\n return candidate;\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n return path.join(startDir, '.env');\n}\n\n/**\n * Environment configuration management\n */\nexport function createEnvironmentRouter(): express.Router {\n const router = express.Router();\n\n // Get local environment variables\n (router as any).get('/local', async (_req: express.Request, res: express.Response) => {\n try {\n const localEnvPath = getLocalEnvPath();\n if (!localEnvPath) {\n return res.json({\n success: true,\n data: {},\n });\n }\n const localEnvs = await parseEnvFile(localEnvPath);\n\n res.json({\n success: true,\n data: localEnvs,\n });\n } catch (error) {\n logger.error(`[ENVS GET] Error retrieving local envs`, error);\n res.status(500).json({\n success: false,\n error: {\n code: 'FETCH_ERROR',\n message: 'Failed to retrieve local envs',\n details: error instanceof Error ? error.message : String(error),\n },\n });\n }\n });\n\n // Update local environment variables\n (router as any).post('/local', async (req: express.Request, res: express.Response) => {\n try {\n const { content } = req.body;\n\n if (!content || typeof content !== 'object') {\n res.status(400).json({\n success: false,\n error: {\n code: 'INVALID_INPUT',\n message: 'Missing or invalid \"content\" in request body',\n },\n });\n }\n\n const localEnvPath = getLocalEnvPath();\n if (!localEnvPath) throw new Error('Local .env file not found');\n\n const envString = serializeEnvObject(content);\n writeFileSync(localEnvPath, envString, 'utf-8');\n\n res.json({\n success: true,\n message: 'Local env updated',\n });\n } catch (error) {\n logger.error(`[ENVS POST] Error updating local envs`, error);\n res.status(500).json({\n success: false,\n error: {\n code: 'UPDATE_ERROR',\n message: 'Failed to update local envs',\n details: error instanceof Error ? error.message : String(error),\n },\n });\n }\n });\n\n return router;\n}\n","import type { IAgentRuntime } from '@elizaos/core';\nimport {\n logger,\n SOCKET_MESSAGE_TYPE,\n validateUuid,\n ChannelType,\n type UUID,\n EventType,\n} from '@elizaos/core';\nimport type { Socket, Server as SocketIOServer } from 'socket.io';\nimport type { AgentServer } from '../index';\n\nconst DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID; // Single default server\nexport class SocketIORouter {\n private agents: Map<UUID, IAgentRuntime>;\n private connections: Map<string, UUID>; // socket.id -> agentId (for agent-specific interactions like log streaming, if any)\n private logStreamConnections: Map<string, { agentName?: string; level?: string }>;\n private serverInstance: AgentServer;\n\n constructor(agents: Map<UUID, IAgentRuntime>, serverInstance: AgentServer) {\n this.agents = agents;\n this.connections = new Map();\n this.logStreamConnections = new Map();\n this.serverInstance = serverInstance;\n logger.info(`[SocketIO] Router initialized with ${this.agents.size} agents`);\n }\n\n setupListeners(io: SocketIOServer) {\n logger.info(`[SocketIO] Setting up Socket.IO event listeners`);\n const messageTypes = Object.keys(SOCKET_MESSAGE_TYPE).map(\n (key) => `${key}: ${SOCKET_MESSAGE_TYPE[key as keyof typeof SOCKET_MESSAGE_TYPE]}`\n );\n logger.info(`[SocketIO] Registered message types: ${messageTypes.join(', ')}`);\n io.on('connection', (socket: Socket) => {\n this.handleNewConnection(socket, io);\n });\n }\n\n private handleNewConnection(socket: Socket, _io: SocketIOServer) {\n logger.info(`[SocketIO] New connection: ${socket.id}`);\n\n socket.on(String(SOCKET_MESSAGE_TYPE.ROOM_JOINING), (payload) => {\n logger.debug(\n `[SocketIO] Channel joining event received directly: ${JSON.stringify(payload)}`\n );\n this.handleChannelJoining(socket, payload);\n });\n\n socket.on(String(SOCKET_MESSAGE_TYPE.SEND_MESSAGE), (payload) => {\n const messagePreview =\n payload.message?.substring(0, 50) + (payload.message?.length > 50 ? '...' : '');\n const channelId = payload.channelId || payload.roomId;\n logger.info(\n `[SocketIO] SEND_MESSAGE event received directly: ${JSON.stringify({\n senderId: payload.senderId,\n channelId: channelId,\n messagePreview,\n })}`\n );\n this.handleMessageSubmission(socket, payload);\n });\n\n socket.on('message', (data) => {\n logger.info(\n `[SocketIO] Generic 'message' event received: ${JSON.stringify(data)} (SocketID: ${socket.id})`\n );\n this.handleGenericMessage(socket, data);\n });\n\n socket.on('subscribe_logs', () => this.handleLogSubscription(socket));\n socket.on('unsubscribe_logs', () => this.handleLogUnsubscription(socket));\n socket.on('update_log_filters', (filters) => this.handleLogFilterUpdate(socket, filters));\n socket.on('disconnect', () => this.handleDisconnect(socket));\n socket.on('error', (error) => {\n logger.error(`[SocketIO] Socket error for ${socket.id}: ${error.message}`, error);\n });\n\n if (process.env.NODE_ENV === 'development') {\n socket.onAny((event, ...args) => {\n logger.info(`[SocketIO DEBUG ${socket.id}] Event '${event}': ${JSON.stringify(args)}`);\n });\n }\n\n socket.emit('connection_established', {\n message: 'Connected to Eliza Socket.IO server',\n socketId: socket.id,\n });\n }\n\n private handleGenericMessage(socket: Socket, data: any) {\n try {\n if (!(data && typeof data === 'object' && 'type' in data && 'payload' in data)) {\n logger.warn(\n `[SocketIO ${socket.id}] Malformed 'message' event data: ${JSON.stringify(data)}`\n );\n return;\n }\n const { type, payload } = data;\n\n switch (type) {\n case SOCKET_MESSAGE_TYPE.ROOM_JOINING:\n logger.info(`[SocketIO ${socket.id}] Handling channel joining via 'message' event`);\n this.handleChannelJoining(socket, payload);\n break;\n case SOCKET_MESSAGE_TYPE.SEND_MESSAGE:\n logger.info(`[SocketIO ${socket.id}] Handling message sending via 'message' event`);\n this.handleMessageSubmission(socket, payload);\n break;\n default:\n logger.warn(\n `[SocketIO ${socket.id}] Unknown message type received in 'message' event: ${type}`\n );\n break;\n }\n } catch (error: any) {\n logger.error(\n `[SocketIO ${socket.id}] Error processing 'message' event: ${error.message}`,\n error\n );\n }\n }\n\n private handleChannelJoining(socket: Socket, payload: any) {\n const channelId = payload.channelId || payload.roomId; // Support both for backward compatibility\n const { agentId, entityId, serverId, metadata } = payload;\n\n logger.debug(\n `[SocketIO] handleChannelJoining called with payload:`,\n JSON.stringify(payload, null, 2)\n );\n\n if (!channelId) {\n this.sendErrorResponse(socket, `channelId is required for joining.`);\n return;\n }\n\n if (agentId) {\n const agentUuid = validateUuid(agentId);\n if (agentUuid) {\n this.connections.set(socket.id, agentUuid);\n logger.info(`[SocketIO] Socket ${socket.id} associated with agent ${agentUuid}`);\n }\n }\n\n socket.join(channelId);\n logger.info(`[SocketIO] Socket ${socket.id} joined Socket.IO channel: ${channelId}`);\n\n // Emit ENTITY_JOINED event for bootstrap plugin to handle world/entity creation\n if (entityId && (serverId || DEFAULT_SERVER_ID)) {\n const finalServerId = serverId || DEFAULT_SERVER_ID;\n const isDm = metadata?.isDm || metadata?.channelType === ChannelType.DM;\n\n logger.info(\n `[SocketIO] Emitting ENTITY_JOINED event for entityId: ${entityId}, serverId: ${finalServerId}, isDm: ${isDm}`\n );\n\n // Get the first available runtime (there should typically be one)\n const runtime = Array.from(this.agents.values())[0];\n if (runtime) {\n runtime.emitEvent(EventType.ENTITY_JOINED as any, {\n entityId: entityId as UUID,\n runtime,\n worldId: finalServerId, // Use serverId as worldId identifier\n roomId: channelId as UUID,\n metadata: {\n type: isDm ? ChannelType.DM : ChannelType.GROUP,\n isDm,\n ...metadata,\n },\n source: 'socketio',\n });\n\n logger.info(`[SocketIO] ENTITY_JOINED event emitted successfully for ${entityId}`);\n } else {\n logger.warn(`[SocketIO] No runtime available to emit ENTITY_JOINED event`);\n }\n } else {\n logger.debug(\n `[SocketIO] Missing entityId (${entityId}) or serverId (${serverId || DEFAULT_SERVER_ID}) - not emitting ENTITY_JOINED event`\n );\n }\n\n const successMessage = `Socket ${socket.id} successfully joined channel ${channelId}.`;\n const responsePayload = {\n message: successMessage,\n channelId,\n roomId: channelId, // Keep for backward compatibility\n ...(agentId && { agentId: validateUuid(agentId) || agentId }),\n };\n socket.emit('channel_joined', responsePayload);\n socket.emit('room_joined', responsePayload); // Keep for backward compatibility\n logger.info(`[SocketIO] ${successMessage}`);\n }\n\n private async handleMessageSubmission(socket: Socket, payload: any) {\n const channelId = payload.channelId || payload.roomId; // Support both for backward compatibility\n const { senderId, senderName, message, serverId, source, metadata, attachments } = payload;\n\n logger.info(\n `[SocketIO ${socket.id}] Received SEND_MESSAGE for central submission: channel ${channelId} from ${senderName || senderId}`\n );\n logger.info(\n `[SocketIO ${socket.id}] Full payload for debugging:`,\n JSON.stringify(payload, null, 2)\n );\n\n // Special handling for default server ID \"0\"\n const isValidServerId = serverId === DEFAULT_SERVER_ID || validateUuid(serverId);\n\n if (!validateUuid(channelId) || !isValidServerId || !validateUuid(senderId) || !message) {\n this.sendErrorResponse(\n socket,\n `For SEND_MESSAGE: channelId, serverId (server_id), senderId (author_id), and message are required.`\n );\n return;\n }\n\n try {\n // Check if this is a DM channel and emit ENTITY_JOINED for proper world setup\n const isDmForWorldSetup = metadata?.isDm || metadata?.channelType === ChannelType.DM;\n if (isDmForWorldSetup && senderId) {\n logger.info(\n `[SocketIO] Detected DM channel during message submission, emitting ENTITY_JOINED for proper world setup`\n );\n\n const runtime = Array.from(this.agents.values())[0];\n if (runtime) {\n runtime.emitEvent(EventType.ENTITY_JOINED as any, {\n entityId: senderId as UUID,\n runtime,\n worldId: serverId, // Use serverId as worldId identifier\n roomId: channelId as UUID,\n metadata: {\n type: ChannelType.DM,\n isDm: true,\n ...metadata,\n },\n source: 'socketio_message',\n });\n\n logger.info(`[SocketIO] ENTITY_JOINED event emitted for DM channel setup: ${senderId}`);\n }\n }\n\n // Ensure the channel exists before creating the message\n logger.info(\n `[SocketIO ${socket.id}] Checking if channel ${channelId} exists before creating message`\n );\n let channelExists = false;\n try {\n const existingChannel = await this.serverInstance.getChannelDetails(channelId as UUID);\n channelExists = !!existingChannel;\n logger.info(`[SocketIO ${socket.id}] Channel ${channelId} exists: ${channelExists}`);\n } catch (error: any) {\n logger.info(\n `[SocketIO ${socket.id}] Channel ${channelId} does not exist, will create it. Error: ${error.message}`\n );\n }\n\n if (!channelExists) {\n // Auto-create the channel if it doesn't exist\n logger.info(\n `[SocketIO ${socket.id}] Auto-creating channel ${channelId} with serverId ${serverId}`\n );\n try {\n // First verify the server exists\n const servers = await this.serverInstance.getServers();\n const serverExists = servers.some((s) => s.id === serverId);\n logger.info(\n `[SocketIO ${socket.id}] Server ${serverId} exists: ${serverExists}. Available servers: ${servers.map((s) => s.id).join(', ')}`\n );\n\n if (!serverExists) {\n logger.error(\n `[SocketIO ${socket.id}] Server ${serverId} does not exist, cannot create channel`\n );\n this.sendErrorResponse(socket, `Server ${serverId} does not exist`);\n return;\n }\n\n // Determine if this is likely a DM based on the context\n const isDmChannel =\n metadata?.isDm ||\n metadata?.channelType === ChannelType.DM ||\n senderName?.includes('DM');\n\n const channelData = {\n id: channelId as UUID, // Use the specific channel ID from the client\n messageServerId: serverId as UUID,\n name: isDmChannel\n ? `DM ${channelId.substring(0, 8)}`\n : `Chat ${channelId.substring(0, 8)}`,\n type: isDmChannel ? ChannelType.DM : ChannelType.GROUP,\n sourceType: 'auto_created',\n metadata: {\n created_by: 'socketio_auto_creation',\n created_for_user: senderId,\n created_at: new Date().toISOString(),\n channel_type: isDmChannel ? ChannelType.DM : ChannelType.GROUP,\n ...metadata,\n },\n };\n\n logger.info(\n `[SocketIO ${socket.id}] Creating channel with data:`,\n JSON.stringify(channelData, null, 2)\n );\n\n // For DM channels, we need to determine the participants\n let participants = [senderId as UUID];\n if (isDmChannel) {\n // Try to extract the other participant from metadata or payload\n const otherParticipant =\n metadata?.targetUserId || metadata?.recipientId || payload.targetUserId;\n if (otherParticipant && validateUuid(otherParticipant)) {\n participants.push(otherParticipant as UUID);\n logger.info(\n `[SocketIO ${socket.id}] DM channel will include participants: ${participants.join(', ')}`\n );\n } else {\n logger.warn(\n `[SocketIO ${socket.id}] DM channel missing second participant, only adding sender: ${senderId}`\n );\n }\n }\n\n await this.serverInstance.createChannel(channelData, participants);\n logger.info(\n `[SocketIO ${socket.id}] Auto-created ${isDmChannel ? ChannelType.DM : ChannelType.GROUP} channel ${channelId} for message submission with ${participants.length} participants`\n );\n } catch (createError: any) {\n logger.error(\n `[SocketIO ${socket.id}] Failed to auto-create channel ${channelId}:`,\n createError\n );\n this.sendErrorResponse(socket, `Failed to create channel: ${createError.message}`);\n return;\n }\n } else {\n logger.info(\n `[SocketIO ${socket.id}] Channel ${channelId} already exists, proceeding with message creation`\n );\n }\n\n const newRootMessageData = {\n channelId: channelId as UUID,\n authorId: senderId as UUID,\n content: message as string,\n rawMessage: payload,\n metadata: {\n ...(metadata || {}),\n user_display_name: senderName,\n socket_id: socket.id,\n serverId: serverId as UUID,\n attachments,\n },\n sourceType: source || 'socketio_client',\n };\n\n const createdRootMessage = await this.serverInstance.createMessage(newRootMessageData);\n\n logger.info(\n `[SocketIO ${socket.id}] Message from ${senderId} (msgId: ${payload.messageId || 'N/A'}) submitted to central store (central ID: ${createdRootMessage.id}). It will be processed by agents and broadcasted upon their reply.`\n );\n\n // Immediately broadcast the message to all clients in the channel\n const messageBroadcast = {\n id: createdRootMessage.id,\n senderId: senderId,\n senderName: senderName || 'User',\n text: message,\n channelId: channelId,\n roomId: channelId, // Keep for backward compatibility\n serverId: serverId, // Use serverId at message server layer\n createdAt: new Date(createdRootMessage.createdAt).getTime(),\n source: source || 'socketio_client',\n attachments: attachments,\n };\n\n // Broadcast to everyone in the channel except the sender\n socket.to(channelId).emit('messageBroadcast', messageBroadcast);\n\n // Also send back to the sender with the server-assigned ID\n socket.emit('messageBroadcast', {\n ...messageBroadcast,\n clientMessageId: payload.messageId,\n });\n\n socket.emit('messageAck', {\n clientMessageId: payload.messageId,\n messageId: createdRootMessage.id,\n status: 'received_by_server_and_processing',\n channelId,\n roomId: channelId, // Keep for backward compatibility\n });\n } catch (error: any) {\n logger.error(\n `[SocketIO ${socket.id}] Error during central submission for message: ${error.message}`,\n error\n );\n this.sendErrorResponse(socket, `[SocketIO] Error processing your message: ${error.message}`);\n }\n }\n\n private sendErrorResponse(socket: Socket, errorMessage: string) {\n logger.error(`[SocketIO ${socket.id}] Sending error to client: ${errorMessage}`);\n socket.emit('messageError', {\n error: errorMessage,\n });\n }\n\n private handleLogSubscription(socket: Socket) {\n this.logStreamConnections.set(socket.id, {});\n logger.info(`[SocketIO ${socket.id}] Client subscribed to log stream`);\n socket.emit('log_subscription_confirmed', {\n subscribed: true,\n message: 'Successfully subscribed to log stream',\n });\n }\n\n private handleLogUnsubscription(socket: Socket) {\n this.logStreamConnections.delete(socket.id);\n logger.info(`[SocketIO ${socket.id}] Client unsubscribed from log stream`);\n socket.emit('log_subscription_confirmed', {\n subscribed: false,\n message: 'Successfully unsubscribed from log stream',\n });\n }\n\n private handleLogFilterUpdate(socket: Socket, filters: { agentName?: string; level?: string }) {\n const existingFilters = this.logStreamConnections.get(socket.id);\n if (existingFilters !== undefined) {\n this.logStreamConnections.set(socket.id, { ...existingFilters, ...filters });\n logger.info(`[SocketIO ${socket.id}] Updated log filters:`, filters);\n socket.emit('log_filters_updated', {\n success: true,\n filters: this.logStreamConnections.get(socket.id),\n });\n } else {\n logger.warn(`[SocketIO ${socket.id}] Cannot update filters: not subscribed to log stream`);\n socket.emit('log_filters_updated', {\n success: false,\n error: 'Not subscribed to log stream',\n });\n }\n }\n\n public broadcastLog(io: SocketIOServer, logEntry: any) {\n if (this.logStreamConnections.size === 0) return;\n const logData = { type: 'log_entry', payload: logEntry };\n this.logStreamConnections.forEach((filters, socketId) => {\n const socket = io.sockets.sockets.get(socketId);\n if (socket) {\n let shouldBroadcast = true;\n if (filters.agentName && filters.agentName !== 'all') {\n shouldBroadcast = shouldBroadcast && logEntry.agentName === filters.agentName;\n }\n if (filters.level && filters.level !== 'all') {\n const numericLevel =\n typeof filters.level === 'string'\n ? logger.levels.values[filters.level.toLowerCase()] || 70\n : filters.level;\n shouldBroadcast = shouldBroadcast && logEntry.level >= numericLevel;\n }\n if (shouldBroadcast) {\n socket.emit('log_stream', logData);\n }\n }\n });\n }\n\n private handleDisconnect(socket: Socket) {\n const agentIdAssociated = this.connections.get(socket.id);\n this.connections.delete(socket.id);\n this.logStreamConnections.delete(socket.id);\n if (agentIdAssociated) {\n logger.info(\n `[SocketIO] Client ${socket.id} (associated with agent ${agentIdAssociated}) disconnected.`\n );\n } else {\n logger.info(`[SocketIO] Client ${socket.id} disconnected.`);\n }\n }\n}\n","import { type Request, type Response, type NextFunction } from 'express';\nimport { logger } from '@elizaos/core';\n\n/**\n * Express middleware for validating API Key authentication based on an environment variable.\n *\n * If the ELIZA_SERVER_AUTH_TOKEN environment variable is set, this middleware\n * checks for a matching 'X-API-KEY' header in incoming requests.\n *\n * If the environment variable is *not* set, the middleware allows all requests\n * to pass through without authentication checks.\n *\n * @param req - Express request object.\n * @param res - Express response object.\n * @param next - Express next function.\n */\nexport function apiKeyAuthMiddleware(req: Request, res: Response, next: NextFunction) {\n const serverAuthToken = process.env.ELIZA_SERVER_AUTH_TOKEN;\n\n // If no token is configured in ENV, skip auth check\n if (!serverAuthToken) {\n return next();\n }\n\n // Allow OPTIONS requests for CORS preflight\n if (req.method === 'OPTIONS') {\n return next();\n }\n\n const apiKey = req.headers?.['x-api-key'];\n\n if (!apiKey || apiKey !== serverAuthToken) {\n logger.warn(`Unauthorized access attempt: Missing or invalid X-API-KEY from ${req.ip}`);\n return res.status(401).send('Unauthorized: Invalid or missing X-API-KEY');\n }\n\n // If key is valid, proceed\n next();\n}\n","import {\n ChannelType,\n EventType,\n Service,\n createUniqueUuid,\n logger,\n validateUuid,\n type Content,\n type IAgentRuntime,\n type Memory,\n type Plugin,\n type UUID,\n} from '@elizaos/core';\nimport internalMessageBus from '../bus'; // Import the bus\n\n// This interface defines the structure of messages coming from the server\nexport interface MessageServiceMessage {\n id: UUID; // root_message.id\n channel_id: UUID;\n server_id: UUID;\n author_id: UUID; // UUID of a central user identity\n author_display_name?: string; // Display name from central user identity\n content: string;\n raw_message?: any;\n source_id?: string; // original platform message ID\n source_type?: string;\n in_reply_to_message_id?: UUID;\n created_at: number;\n metadata?: any;\n}\n\nexport class MessageBusService extends Service {\n static serviceType = 'message-bus-service';\n capabilityDescription = 'Manages connection and message synchronization with the message server.';\n\n private boundHandleIncomingMessage: (message: MessageServiceMessage) => Promise<void>;\n private boundHandleServerAgentUpdate: (data: any) => Promise<void>;\n private boundHandleMessageDeleted: (data: any) => Promise<void>;\n private boundHandleChannelCleared: (data: any) => Promise<void>;\n private subscribedServers: Set<UUID> = new Set();\n\n constructor(runtime: IAgentRuntime) {\n super(runtime);\n this.boundHandleIncomingMessage = this.handleIncomingMessage.bind(this);\n this.boundHandleServerAgentUpdate = this.handleServerAgentUpdate.bind(this);\n this.boundHandleMessageDeleted = this.handleMessageDeleted.bind(this);\n this.boundHandleChannelCleared = this.handleChannelCleared.bind(this);\n // Don't connect here - let start() handle it\n }\n\n static async start(runtime: IAgentRuntime): Promise<Service> {\n const service = new MessageBusService(runtime);\n await service.connectToMessageBus();\n return service;\n }\n\n static async stop(runtime: IAgentRuntime): Promise<void> {\n const service = new MessageBusService(runtime);\n await service.stop();\n }\n\n private async connectToMessageBus() {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Subscribing to internal message bus for 'new_message', 'message_deleted', and 'channel_cleared' events.`\n );\n internalMessageBus.on('new_message', this.boundHandleIncomingMessage);\n internalMessageBus.on('server_agent_update', this.boundHandleServerAgentUpdate);\n internalMessageBus.on('message_deleted', this.boundHandleMessageDeleted);\n internalMessageBus.on('channel_cleared', this.boundHandleChannelCleared);\n\n // Initialize by fetching servers this agent belongs to\n await this.fetchAgentServers();\n // Then fetch valid channels for those servers\n await this.fetchValidChannelIds();\n }\n\n private validChannelIds: Set<UUID> = new Set();\n\n private async fetchValidChannelIds(): Promise<void> {\n try {\n const serverApiUrl = this.getCentralMessageServerUrl();\n\n // Clear existing channel IDs before fetching new ones\n this.validChannelIds.clear();\n\n // Include the default server ID if not already in subscribed servers\n const DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n const serversToCheck = new Set(this.subscribedServers);\n serversToCheck.add(DEFAULT_SERVER_ID);\n\n // Fetch channels for each subscribed server\n for (const serverId of serversToCheck) {\n try {\n // Use URL constructor for safe URL building\n const channelsUrl = new URL(\n `/api/messaging/central-servers/${encodeURIComponent(serverId)}/channels`,\n serverApiUrl\n );\n const response = await fetch(channelsUrl.toString(), {\n headers: this.getAuthHeaders(),\n });\n if (response.ok) {\n const data = await response.json();\n if (data.success && data.data?.channels && Array.isArray(data.data.channels)) {\n // Add channel IDs to the set\n data.data.channels.forEach((channel: any) => {\n if (channel.id && validateUuid(channel.id)) {\n this.validChannelIds.add(channel.id as UUID);\n }\n });\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Fetched ${data.data.channels.length} channels from server ${serverId}`\n );\n }\n } else {\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: Failed to fetch channels for server ${serverId}: ${response.status} ${response.statusText}`\n );\n }\n } catch (serverError) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error fetching channels for server ${serverId}:`,\n serverError\n );\n }\n }\n\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Loaded ${this.validChannelIds.size} valid channel IDs from ${serversToCheck.size} servers (including default server)`\n );\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error in fetchValidChannelIds:`,\n error\n );\n }\n }\n\n private async getChannelParticipants(channelId: UUID): Promise<string[]> {\n try {\n const serverApiUrl = this.getCentralMessageServerUrl();\n\n if (!validateUuid(channelId)) {\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: Invalid channel ID format: ${channelId}`\n );\n return [];\n }\n\n // First check if channel is in our cached set\n if (!this.validChannelIds.has(channelId)) {\n // Try to verify the channel exists by fetching its details\n // Use URL constructor for safe URL building\n const detailsUrl = new URL(\n `/api/messaging/central-channels/${encodeURIComponent(channelId)}/details`,\n serverApiUrl\n );\n const detailsResponse = await fetch(detailsUrl.toString(), {\n headers: this.getAuthHeaders(),\n });\n\n if (detailsResponse.ok) {\n // Channel exists, add it to our valid set for future use\n this.validChannelIds.add(channelId);\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Discovered new channel ${channelId}, added to valid channels`\n );\n } else {\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: Channel ${channelId} does not exist or is not accessible`\n );\n return [];\n }\n }\n\n // Now fetch the participants\n // Use URL constructor for safe URL building\n const participantsUrl = new URL(\n `/api/messaging/central-channels/${encodeURIComponent(channelId)}/participants`,\n serverApiUrl\n );\n const response = await fetch(participantsUrl.toString(), {\n headers: this.getAuthHeaders(),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success && data.data) {\n return data.data;\n }\n }\n return [];\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error fetching participants for channel ${channelId}:`,\n error\n );\n return [];\n }\n }\n\n private async fetchAgentServers() {\n try {\n const serverApiUrl = this.getCentralMessageServerUrl();\n // Use URL constructor for safe URL building\n const agentServersUrl = new URL(\n `/api/messaging/agents/${encodeURIComponent(this.runtime.agentId)}/servers`,\n serverApiUrl\n );\n const response = await fetch(agentServersUrl.toString(), {\n headers: this.getAuthHeaders(),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success && data.data?.servers) {\n this.subscribedServers = new Set(data.data.servers);\n // Always include the default server\n const DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n this.subscribedServers.add(DEFAULT_SERVER_ID);\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Agent is subscribed to ${this.subscribedServers.size} servers (including default server)`\n );\n }\n } else {\n // Even if the request fails, ensure we're subscribed to the default server\n const DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n this.subscribedServers.add(DEFAULT_SERVER_ID);\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: Failed to fetch agent servers, but added default server`\n );\n }\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error fetching agent servers:`,\n error\n );\n // Even on error, ensure we're subscribed to the default server\n const DEFAULT_SERVER_ID = '00000000-0000-0000-0000-000000000000' as UUID;\n this.subscribedServers.add(DEFAULT_SERVER_ID);\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Added default server after error`\n );\n }\n }\n\n private async handleServerAgentUpdate(data: any) {\n if (data.agentId !== this.runtime.agentId) {\n return; // Not for this agent\n }\n\n if (data.type === 'agent_added_to_server') {\n this.subscribedServers.add(data.serverId);\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Agent added to server ${data.serverId}`\n );\n // Refresh channel IDs to include channels from the new server\n await this.fetchValidChannelIds();\n } else if (data.type === 'agent_removed_from_server') {\n this.subscribedServers.delete(data.serverId);\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Agent removed from server ${data.serverId}`\n );\n // Refresh channel IDs to remove channels from the removed server\n await this.fetchValidChannelIds();\n }\n }\n\n private async validateServerSubscription(message: MessageServiceMessage): Promise<boolean> {\n if (!this.subscribedServers.has(message.server_id)) {\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: Agent not subscribed to server ${message.server_id}, ignoring message`\n );\n return false;\n }\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Passed server subscription check for ${message.server_id}`\n );\n return true;\n }\n\n private async validateNotSelfMessage(message: MessageServiceMessage): Promise<boolean> {\n if (message.author_id === this.runtime.agentId) {\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: Agent is the author of the message, ignoring message`\n );\n return false;\n }\n return true;\n }\n\n private async ensureWorldAndRoomExist(\n message: MessageServiceMessage\n ): Promise<{ agentWorldId: UUID; agentRoomId: UUID }> {\n const agentWorldId = createUniqueUuid(this.runtime, message.server_id);\n const agentRoomId = createUniqueUuid(this.runtime, message.channel_id);\n\n try {\n await this.runtime.ensureWorldExists({\n id: agentWorldId,\n name: message.metadata?.serverName || `Server ${message.server_id.substring(0, 8)}`,\n agentId: this.runtime.agentId,\n serverId: message.server_id,\n metadata: {\n ...(message.metadata?.serverMetadata || {}),\n },\n });\n } catch (error: any) {\n if (error.message && error.message.includes('worlds_pkey')) {\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: World ${agentWorldId} already exists, continuing with message processing`\n );\n } else {\n throw error;\n }\n }\n\n try {\n await this.runtime.ensureRoomExists({\n id: agentRoomId,\n name: message.metadata?.channelName || `Channel ${message.channel_id.substring(0, 8)}`,\n agentId: this.runtime.agentId,\n worldId: agentWorldId,\n channelId: message.channel_id,\n serverId: message.server_id,\n source: message.source_type || 'central-bus',\n type: message.metadata?.channelType || ChannelType.GROUP,\n metadata: {\n ...(message.metadata?.channelMetadata || {}),\n },\n });\n } catch (error: any) {\n if (error.message && error.message.includes('rooms_pkey')) {\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: Room ${agentRoomId} already exists, continuing with message processing`\n );\n } else {\n throw error;\n }\n }\n\n return { agentWorldId, agentRoomId };\n }\n\n private async ensureAuthorEntityExists(message: MessageServiceMessage): Promise<UUID> {\n const agentAuthorEntityId = createUniqueUuid(this.runtime, message.author_id);\n\n const authorEntity = await this.runtime.getEntityById(agentAuthorEntityId);\n if (!authorEntity) {\n await this.runtime.createEntity({\n id: agentAuthorEntityId,\n names: [message.author_display_name || `User-${message.author_id.substring(0, 8)}`],\n agentId: this.runtime.agentId,\n metadata: {\n author_id: message.author_id,\n source: message.source_type,\n },\n });\n }\n\n return agentAuthorEntityId;\n }\n\n private createAgentMemory(\n message: MessageServiceMessage,\n agentAuthorEntityId: UUID,\n agentRoomId: UUID,\n agentWorldId: UUID\n ): Memory {\n const messageContent: Content = {\n text: message.content,\n source: message.source_type || 'central-bus',\n attachments: message.metadata?.attachments,\n inReplyTo: message.in_reply_to_message_id\n ? createUniqueUuid(this.runtime, message.in_reply_to_message_id)\n : undefined,\n };\n\n return {\n id: createUniqueUuid(this.runtime, message.id),\n entityId: agentAuthorEntityId,\n agentId: this.runtime.agentId,\n roomId: agentRoomId,\n worldId: agentWorldId,\n content: messageContent,\n createdAt: message.created_at,\n metadata: {\n type: 'message',\n source: message.source_type || 'central-bus',\n sourceId: message.id,\n raw: {\n ...message.raw_message,\n senderName: message.author_display_name || `User-${message.author_id.substring(0, 8)}`,\n senderId: message.author_id,\n },\n },\n };\n }\n\n public async handleIncomingMessage(message: MessageServiceMessage) {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Received message from central bus`,\n { messageId: message.id }\n );\n\n const participants = await this.getChannelParticipants(message.channel_id);\n\n if (!participants.includes(this.runtime.agentId)) {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Agent not a participant in channel ${message.channel_id}, ignoring message`\n );\n return;\n }\n\n logger.info(\n `[${this.runtime.character.name} - ${this.runtime.agentId}] MessageBusService: Agent is a participant in channel ${message.channel_id}, proceeding with message processing`\n );\n\n try {\n if (!(await this.validateServerSubscription(message))) return;\n if (!(await this.validateNotSelfMessage(message))) return;\n\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: All checks passed, proceeding to create agent memory and emit MESSAGE_RECEIVED event`\n );\n\n const { agentWorldId, agentRoomId } = await this.ensureWorldAndRoomExist(message);\n const agentAuthorEntityId = await this.ensureAuthorEntityExists(message);\n const agentMemory = this.createAgentMemory(\n message,\n agentAuthorEntityId,\n agentRoomId,\n agentWorldId\n );\n\n // Check if this memory already exists (in case of duplicate processing)\n const existingMemory = await this.runtime.getMemoryById(agentMemory.id as UUID);\n if (existingMemory) {\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: Memory ${agentMemory.id} already exists, skipping duplicate processing`\n );\n return;\n }\n\n const callbackForCentralBus = async (responseContent: Content): Promise<Memory[]> => {\n logger.info(\n `[${this.runtime.character.name}] Agent generated response for message. Preparing to send back to bus.`\n );\n\n await this.runtime.createMemory(\n {\n entityId: this.runtime.agentId,\n content: responseContent,\n roomId: agentRoomId,\n worldId: agentWorldId,\n agentId: this.runtime.agentId,\n },\n 'messages'\n );\n\n // Send response to central bus\n await this.sendAgentResponseToBus(\n agentRoomId,\n agentWorldId,\n responseContent,\n agentMemory.id,\n message\n );\n\n // The core runtime/bootstrap plugin will handle creating the agent's own memory of its response.\n // So, we return an empty array here as this callback's primary job is to ferry the response externally.\n return [];\n };\n\n await this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message: agentMemory,\n callback: callbackForCentralBus,\n });\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error processing incoming message:`,\n error\n );\n }\n }\n\n private async handleMessageDeleted(data: any) {\n try {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Received message_deleted event for message ${data.messageId}`\n );\n\n // Convert the central message ID to the agent's unique memory ID\n const agentMemoryId = createUniqueUuid(this.runtime, data.messageId);\n\n // Try to find and delete the existing memory\n const existingMemory = await this.runtime.getMemoryById(agentMemoryId);\n\n if (existingMemory) {\n // Emit MESSAGE_DELETED event with the existing memory\n await this.runtime.emitEvent(EventType.MESSAGE_DELETED, {\n runtime: this.runtime,\n message: existingMemory,\n source: 'message-bus-service',\n });\n\n logger.debug(\n `[${this.runtime.character.name}] MessageBusService: Successfully processed message deletion for ${data.messageId}`\n );\n } else {\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: No memory found for deleted message ${data.messageId}`\n );\n }\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error handling message deletion:`,\n error\n );\n }\n }\n\n private async handleChannelCleared(data: any) {\n try {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Received channel_cleared event for channel ${data.channelId}`\n );\n\n // Convert the central channel ID to the agent's unique room ID\n const agentRoomId = createUniqueUuid(this.runtime, data.channelId);\n\n // Get all memories for this room and emit deletion events for each\n const memories = await this.runtime.getMemoriesByRoomIds({\n tableName: 'messages',\n roomIds: [agentRoomId],\n });\n\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Found ${memories.length} memories to delete for channel ${data.channelId}`\n );\n\n // Emit CHANNEL_CLEARED event to bootstrap which will handle bulk deletion\n await this.runtime.emitEvent(EventType.CHANNEL_CLEARED, {\n runtime: this.runtime,\n source: 'message-bus-service',\n roomId: agentRoomId,\n channelId: data.channelId,\n memoryCount: memories.length,\n });\n\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Successfully processed channel clear for ${data.channelId} -> room ${agentRoomId}`\n );\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error handling channel clear:`,\n error\n );\n }\n }\n\n private async sendAgentResponseToBus(\n agentRoomId: UUID,\n agentWorldId: UUID,\n content: Content,\n inReplyToAgentMemoryId?: UUID,\n originalMessage?: MessageServiceMessage\n ) {\n try {\n const room = await this.runtime.getRoom(agentRoomId);\n const world = await this.runtime.getWorld(agentWorldId);\n\n const channelId = room?.channelId as UUID;\n const serverId = world?.serverId as UUID;\n\n if (!channelId || !serverId) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Cannot map agent room/world to central IDs for response. AgentRoomID: ${agentRoomId}, AgentWorldID: ${agentWorldId}. Room or World object missing, or channelId/serverId not found on them.`\n );\n await this.notifyMessageComplete(channelId, serverId);\n return;\n }\n\n // If agent decides to IGNORE or has no valid text, notify completion and skip sending response\n const shouldSkip =\n content.actions?.includes('IGNORE') || !content.text || content.text.trim() === '';\n\n if (shouldSkip) {\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Skipping response (reason: ${content.actions?.includes('IGNORE') ? 'IGNORE action' : 'No text'})`\n );\n await this.notifyMessageComplete(channelId, serverId);\n return;\n }\n\n // Resolve reply-to message ID from agent memory metadata\n let centralInReplyToRootMessageId: UUID | undefined = undefined;\n if (inReplyToAgentMemoryId) {\n const originalAgentMemory = await this.runtime.getMemoryById(inReplyToAgentMemoryId);\n if (originalAgentMemory?.metadata?.sourceId) {\n centralInReplyToRootMessageId = originalAgentMemory.metadata.sourceId as UUID;\n }\n }\n\n const payloadToServer = {\n channel_id: channelId,\n server_id: serverId,\n author_id: this.runtime.agentId, // This needs careful consideration: is it the agent's core ID or a specific central identity for the agent?\n content: content.text,\n in_reply_to_message_id: centralInReplyToRootMessageId,\n source_type: 'agent_response',\n raw_message: {\n text: content.text,\n thought: content.thought,\n actions: content.actions,\n },\n metadata: {\n agent_id: this.runtime.agentId,\n agentName: this.runtime.character.name,\n attachments: content.attachments,\n channelType: originalMessage?.metadata?.channelType || room?.type,\n isDm:\n originalMessage?.metadata?.isDm ||\n (originalMessage?.metadata?.channelType || room?.type) === ChannelType.DM,\n },\n };\n\n logger.info(\n `[${this.runtime.character.name}] MessageBusService: Sending payload to central server API endpoint (/api/messaging/submit):`,\n payloadToServer\n );\n\n // Actual fetch to the central server API\n const baseUrl = this.getCentralMessageServerUrl();\n // Use URL constructor for safe URL building\n const submitUrl = new URL('/api/messaging/submit', baseUrl);\n const serverApiUrl = submitUrl.toString();\n const response = await fetch(serverApiUrl, {\n method: 'POST',\n headers: this.getAuthHeaders(),\n body: JSON.stringify(payloadToServer),\n });\n\n if (!response.ok) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error sending response to central server: ${response.status} ${await response.text()}`\n );\n }\n } catch (error) {\n logger.error(\n `[${this.runtime.character.name}] MessageBusService: Error sending agent response to bus:`,\n error\n );\n }\n }\n\n private async notifyMessageComplete(channelId?: UUID, serverId?: UUID) {\n if (!channelId || !serverId) return;\n\n try {\n const completeUrl = new URL('/api/messaging/complete', this.getCentralMessageServerUrl());\n await fetch(completeUrl.toString(), {\n method: 'POST',\n headers: this.getAuthHeaders(),\n body: JSON.stringify({ channel_id: channelId, server_id: serverId }),\n });\n } catch (error) {\n logger.warn(\n `[${this.runtime.character.name}] MessageBusService: Failed to notify completion`,\n error\n );\n }\n }\n\n private getAuthHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Add authentication header if ELIZA_SERVER_AUTH_TOKEN is configured\n const serverAuthToken = process.env.ELIZA_SERVER_AUTH_TOKEN;\n if (serverAuthToken) {\n headers['X-API-KEY'] = serverAuthToken;\n }\n\n return headers;\n }\n\n getCentralMessageServerUrl(): string {\n const serverPort = process.env.SERVER_PORT;\n const envUrl = process.env.CENTRAL_MESSAGE_SERVER_URL;\n\n // Validate and sanitize server port\n let validatedPort: number | null = null;\n if (serverPort) {\n const portNum = parseInt(serverPort, 10);\n if (!isNaN(portNum) && portNum > 0 && portNum <= 65535) {\n validatedPort = portNum;\n } else {\n logger.warn(`[MessageBusService] Invalid SERVER_PORT value: ${serverPort}`);\n }\n }\n\n const defaultUrl = validatedPort\n ? `http://localhost:${validatedPort}`\n : 'http://localhost:3000';\n const baseUrl = envUrl ?? defaultUrl;\n\n // Strict validation to prevent SSRF attacks\n try {\n const url = new URL(baseUrl);\n\n // Only allow HTTP/HTTPS protocols\n if (!['http:', 'https:'].includes(url.protocol)) {\n logger.warn(\n `[MessageBusService] Unsafe protocol in CENTRAL_MESSAGE_SERVER_URL: ${url.protocol}`\n );\n return defaultUrl;\n }\n\n // Only allow safe localhost variants and block private/internal IPs\n const allowedHosts = ['localhost', '127.0.0.1', '::1'];\n if (!allowedHosts.includes(url.hostname)) {\n logger.warn(\n `[MessageBusService] Unsafe hostname in CENTRAL_MESSAGE_SERVER_URL: ${url.hostname}`\n );\n return defaultUrl;\n }\n\n // Validate port range\n if (url.port) {\n const portNum = parseInt(url.port, 10);\n if (isNaN(portNum) || portNum <= 0 || portNum > 65535) {\n logger.warn(\n `[MessageBusService] Invalid port in CENTRAL_MESSAGE_SERVER_URL: ${url.port}`\n );\n return defaultUrl;\n }\n }\n\n // Remove any potentially dangerous URL components\n url.username = '';\n url.password = '';\n url.hash = '';\n\n return url.toString().replace(/\\/$/, ''); // Remove trailing slash\n } catch (error) {\n logger.error(\n `[MessageBusService] Invalid URL format in CENTRAL_MESSAGE_SERVER_URL: ${baseUrl}`\n );\n return defaultUrl;\n }\n }\n\n async stop(): Promise<void> {\n logger.info(`[${this.runtime.character.name}] MessageBusService stopping...`);\n internalMessageBus.off('new_message', this.boundHandleIncomingMessage);\n internalMessageBus.off('server_agent_update', this.boundHandleServerAgentUpdate);\n internalMessageBus.off('message_deleted', this.boundHandleMessageDeleted);\n internalMessageBus.off('channel_cleared', this.boundHandleChannelCleared);\n }\n}\n\n// Minimal plugin definition to register the service\nexport const messageBusConnectorPlugin: Plugin = {\n name: 'internal-message-bus-connector',\n description: 'Internal service to connect agent to the message bus.',\n services: [MessageBusService],\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n type Character,\n logger,\n parseAndValidateCharacter,\n validateCharacter,\n} from '@elizaos/core';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/**\n * Attempts to load a file from the given file path.\n *\n * @param {string} filePath - The path to the file to load.\n * @returns {string | null} The contents of the file as a string, or null if an error occurred.\n * @throws {Error} If an error occurs while loading the file.\n */\nexport function tryLoadFile(filePath: string): string | null {\n try {\n return fs.readFileSync(filePath, 'utf8');\n } catch (e) {\n throw new Error(`Error loading file ${filePath}: ${e}`);\n }\n}\n\n/**\n * Load characters from a specified URL and return them as an array of Character objects.\n * @param {string} url - The URL from which to load character data.\n * @returns {Promise<Character[]>} - A promise that resolves with an array of Character objects.\n */\nexport async function loadCharactersFromUrl(url: string): Promise<Character[]> {\n try {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`HTTP error ${response.status}: ${response.statusText}`);\n }\n\n const responseJson = await response.json();\n\n let characters: Character[] = [];\n if (Array.isArray(responseJson)) {\n characters = await Promise.all(responseJson.map((character) => jsonToCharacter(character)));\n } else {\n const character = await jsonToCharacter(responseJson);\n characters.push(character);\n }\n return characters;\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n logger.error(`Error loading character(s) from ${url}: ${errorMsg}`);\n\n // Enhanced error handling for validation errors\n if (errorMsg.includes('Character validation failed') || errorMsg.includes('validation')) {\n throw new Error(\n `Invalid character data from URL '${url}'. The character data does not match the required schema: ${errorMsg}`\n );\n } else if (errorMsg.includes('JSON')) {\n throw new Error(\n `Invalid JSON response from URL '${url}'. The resource may not contain valid character data.`\n );\n } else if (e instanceof TypeError) {\n throw new Error(\n `Failed to fetch character from URL '${url}'. The URL may be incorrect or unavailable.`\n );\n } else {\n throw new Error(`Failed to load character from URL '${url}': ${errorMsg}`);\n }\n }\n}\n\n/**\n * Converts a JSON object representing a character into a validated Character object with additional settings and secrets.\n *\n * @param {unknown} character - The input data representing a character.\n * @returns {Promise<Character>} - A Promise that resolves to a validated Character object.\n * @throws {Error} If character validation fails.\n */\nexport async function jsonToCharacter(character: unknown): Promise<Character> {\n // First validate the base character data\n const validationResult = validateCharacter(character);\n\n if (!validationResult.success) {\n const errorDetails = validationResult.error?.issues\n ? validationResult.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')\n : validationResult.error?.message || 'Unknown validation error';\n\n throw new Error(`Character validation failed: ${errorDetails}`);\n }\n\n // Type guard to ensure we have valid data\n if (!validationResult.data) {\n throw new Error('Validation succeeded but no data was returned');\n }\n\n const validatedCharacter = validationResult.data;\n\n // Add environment-based settings and secrets (preserve existing functionality)\n const characterId = validatedCharacter.id || validatedCharacter.name;\n const characterPrefix = `CHARACTER.${characterId.toUpperCase().replace(/ /g, '_')}.`;\n\n const characterSettings = Object.entries(process.env)\n .filter(([key]) => key.startsWith(characterPrefix))\n .reduce((settings, [key, value]) => {\n const settingKey = key.slice(characterPrefix.length);\n return { ...settings, [settingKey]: value };\n }, {});\n\n if (Object.keys(characterSettings).length > 0) {\n // Collect all secrets from various sources\n const combinedSecrets = {\n ...characterSettings,\n ...(validatedCharacter.secrets || {}),\n ...(typeof validatedCharacter.settings?.secrets === 'object' &&\n validatedCharacter.settings?.secrets !== null\n ? validatedCharacter.settings.secrets\n : {}),\n };\n\n const updatedCharacter: Character = {\n ...validatedCharacter,\n };\n\n if (validatedCharacter.settings || Object.keys(combinedSecrets).length > 0) {\n updatedCharacter.settings = validatedCharacter.settings || {};\n }\n\n if (Object.keys(combinedSecrets).length > 0) {\n updatedCharacter.secrets = combinedSecrets;\n }\n\n // Re-validate the updated character to ensure it's still valid\n const revalidationResult = validateCharacter(updatedCharacter);\n if (!revalidationResult.success) {\n logger.warn(\n 'Character became invalid after adding environment settings, using original validated character'\n );\n return validatedCharacter;\n }\n\n if (!revalidationResult.data) {\n logger.warn('Revalidation succeeded but no data returned, using original character');\n return validatedCharacter;\n }\n\n return revalidationResult.data;\n }\n\n return validatedCharacter;\n}\n\n/**\n * Loads a character from the specified file path with safe JSON parsing and validation.\n *\n * @param {string} filePath - The path to the character file.\n * @returns {Promise<Character>} A Promise that resolves to the validated Character object.\n * @throws {Error} If the character file is not found, has invalid JSON, or fails validation.\n */\nexport async function loadCharacter(filePath: string): Promise<Character> {\n const content = tryLoadFile(filePath);\n if (!content) {\n throw new Error(`Character file not found: ${filePath}`);\n }\n\n // Use safe JSON parsing and validation\n const parseResult = parseAndValidateCharacter(content);\n\n if (!parseResult.success) {\n throw new Error(`Failed to load character from ${filePath}: ${parseResult.error?.message}`);\n }\n\n // Apply environment settings (this will also re-validate)\n return jsonToCharacter(parseResult.data!);\n}\n\n/**\n * Handles errors when loading a character from a specific path.\n *\n * @param {string} path - The path from which the character is being loaded.\n * @param {unknown} error - The error that occurred during the loading process.\n * @returns {never}\n */\nfunction handleCharacterLoadError(path: string, error: unknown): never {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n // Check for different types of errors and provide appropriate messages\n if (errorMsg.includes('ENOENT') || errorMsg.includes('no such file')) {\n logger.error(`Character file not found: ${path}`);\n throw new Error(\n `Character '${path}' not found. Please check if the file exists and the path is correct.`\n );\n } else if (errorMsg.includes('Character validation failed')) {\n logger.error(`Character validation failed for: ${path}`);\n throw new Error(`Character file '${path}' contains invalid character data. ${errorMsg}`);\n } else if (errorMsg.includes('JSON')) {\n logger.error(`JSON parsing error in character file: ${path}`);\n throw new Error(`Character file '${path}' has malformed JSON. Please check the file content.`);\n } else if (errorMsg.includes('Invalid JSON')) {\n logger.error(`Invalid JSON in character file: ${path}`);\n throw new Error(\n `Character file '${path}' has invalid JSON format. Please check the file content.`\n );\n } else {\n logger.error(`Error loading character from ${path}: ${errorMsg}`);\n throw new Error(`Failed to load character '${path}': ${errorMsg}`);\n }\n}\n\n/**\n * Asynchronously loads a character from the specified path while handling any potential errors.\n *\n * @param {string} path - The path to load the character from.\n * @returns {Promise<Character>} A promise that resolves to the loaded character.\n */\nasync function safeLoadCharacter(path: string): Promise<Character> {\n try {\n const character = await loadCharacter(path);\n logger.info(`Successfully loaded character from: ${path}`);\n return character;\n } catch (e) {\n return handleCharacterLoadError(path, e);\n }\n}\n\n/**\n * Asynchronously loads a character from the specified path.\n * If the path is a URL, it loads the character from the URL.\n * If the path is a local file path, it tries multiple possible locations and\n * loads the character from the first valid location found.\n *\n * @param {string} characterPath - The path to load the character from.\n * @returns {Promise<Character>} A Promise that resolves to the loaded character.\n */\nexport async function loadCharacterTryPath(characterPath: string): Promise<Character> {\n if (characterPath.startsWith('http')) {\n try {\n const characters = await loadCharactersFromUrl(characterPath);\n if (!characters || characters.length === 0) {\n throw new Error('No characters found in the URL response');\n }\n return characters[0];\n } catch (error) {\n // The error is already formatted by loadCharactersFromUrl, so just re-throw it\n throw error;\n }\n }\n\n // Create path variants with and without .json extension\n const hasJsonExtension = characterPath.toLowerCase().endsWith('.json');\n const basePath = hasJsonExtension ? characterPath : characterPath;\n const jsonPath = hasJsonExtension ? characterPath : `${characterPath}.json`;\n\n const basePathsToTry = [\n basePath,\n path.resolve(process.cwd(), basePath),\n path.resolve(process.cwd(), '..', '..', basePath),\n path.resolve(process.cwd(), '..', '..', '..', basePath),\n path.resolve(process.cwd(), 'agent', basePath),\n path.resolve(__dirname, basePath),\n path.resolve(__dirname, 'characters', path.basename(basePath)),\n path.resolve(__dirname, '../characters', path.basename(basePath)),\n path.resolve(__dirname, '../../characters', path.basename(basePath)),\n path.resolve(__dirname, '../../../characters', path.basename(basePath)),\n ];\n\n const jsonPathsToTry = hasJsonExtension\n ? []\n : [\n jsonPath,\n path.resolve(process.cwd(), jsonPath),\n path.resolve(process.cwd(), '..', '..', jsonPath),\n path.resolve(process.cwd(), '..', '..', '..', jsonPath),\n path.resolve(process.cwd(), 'agent', jsonPath),\n path.resolve(__dirname, jsonPath),\n path.resolve(__dirname, 'characters', path.basename(jsonPath)),\n path.resolve(__dirname, '../characters', path.basename(jsonPath)),\n path.resolve(__dirname, '../../characters', path.basename(jsonPath)),\n path.resolve(__dirname, '../../../characters', path.basename(jsonPath)),\n ];\n\n // Combine the paths to try both variants\n const pathsToTry = Array.from(new Set([...basePathsToTry, ...jsonPathsToTry]));\n\n let lastError: unknown = null;\n\n for (const tryPath of pathsToTry) {\n try {\n const content = tryLoadFile(tryPath);\n if (content !== null) {\n return safeLoadCharacter(tryPath);\n }\n } catch (e) {\n lastError = e;\n // Continue trying other paths\n }\n }\n\n // If we get here, all paths failed\n const errorMessage = lastError\n ? `${lastError}`\n : 'File not found in any of the expected locations';\n return handleCharacterLoadError(\n characterPath,\n `Character not found. Tried ${pathsToTry.length} locations. ${errorMessage}`\n );\n}\n\n/**\n * Converts a comma-separated string to an array of strings.\n *\n * @param {string} commaSeparated - The input comma-separated string.\n * @returns {string[]} An array of strings after splitting the input string by commas and trimming each value.\n */\nfunction commaSeparatedStringToArray(commaSeparated: string): string[] {\n return commaSeparated?.split(',').map((value) => value.trim());\n}\n\n/**\n * Asynchronously reads character files from the storage directory and pushes their paths to the characterPaths array.\n * @param {string[]} characterPaths - An array of paths where the character files will be stored.\n * @returns {Promise<string[]>} - A promise that resolves with an updated array of characterPaths.\n */\nasync function readCharactersFromStorage(characterPaths: string[]): Promise<string[]> {\n try {\n const uploadDir = path.join(process.cwd(), '.eliza', 'data', 'characters');\n await fs.promises.mkdir(uploadDir, { recursive: true });\n const fileNames = await fs.promises.readdir(uploadDir);\n for (const fileName of fileNames) {\n characterPaths.push(path.join(uploadDir, fileName));\n }\n } catch (err) {\n logger.error(`Error reading directory: ${(err as Error).message}`);\n }\n\n return characterPaths;\n}\n\nexport const hasValidRemoteUrls = () =>\n process.env.REMOTE_CHARACTER_URLS &&\n process.env.REMOTE_CHARACTER_URLS !== '' &&\n process.env.REMOTE_CHARACTER_URLS.startsWith('http');\n\n/**\n * Load characters from local paths or remote URLs based on configuration.\n * @param charactersArg - A comma-separated list of local file paths or remote URLs to load characters from.\n * @returns A promise that resolves to an array of loaded characters.\n */\nexport async function loadCharacters(charactersArg: string): Promise<Character[]> {\n let characterPaths = commaSeparatedStringToArray(charactersArg);\n const loadedCharacters: Character[] = [];\n\n if (process.env.USE_CHARACTER_STORAGE === 'true') {\n characterPaths = await readCharactersFromStorage(characterPaths);\n }\n\n if (characterPaths?.length > 0) {\n for (const characterPath of characterPaths) {\n try {\n const character = await loadCharacterTryPath(characterPath);\n loadedCharacters.push(character);\n } catch (error) {\n // Log error but continue loading other characters\n const errorMsg = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to load character from '${characterPath}': ${errorMsg}`);\n // Continue to next character\n }\n }\n }\n\n if (hasValidRemoteUrls()) {\n logger.info('Loading characters from remote URLs');\n const characterUrls = commaSeparatedStringToArray(process.env.REMOTE_CHARACTER_URLS! || '');\n for (const characterUrl of characterUrls) {\n const characters = await loadCharactersFromUrl(characterUrl);\n loadedCharacters.push(...characters);\n }\n }\n\n if (loadedCharacters.length === 0) {\n logger.info('No characters found, using default character');\n // Note: The server package doesn't have a default character like the CLI does\n // This should be provided by the consumer of the server package\n logger.warn('Server package does not include a default character. Please provide one.');\n }\n\n return loadedCharacters;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAQA,QAAI,wBAAwB,OAAO;AACnC,QAAI,iBAAiB,OAAO,UAAU;AACtC,QAAI,mBAAmB,OAAO,UAAU;AAExC,aAAS,SAAS,KAAK;AACtB,UAAI,QAAQ,QAAQ,QAAQ,QAAW;AACtC,cAAM,IAAI,UAAU,uDAAuD;AAAA,MAC5E;AAEA,aAAO,OAAO,GAAG;AAAA,IAClB;AAEA,aAAS,kBAAkB;AAC1B,UAAI;AACH,YAAI,CAAC,OAAO,QAAQ;AACnB,iBAAO;AAAA,QACR;AAKA,YAAI,QAAQ,IAAI,OAAO,KAAK;AAC5B,cAAM,CAAC,IAAI;AACX,YAAI,OAAO,oBAAoB,KAAK,EAAE,CAAC,MAAM,KAAK;AACjD,iBAAO;AAAA,QACR;AAGA,YAAI,QAAQ,CAAC;AACb,iBAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC5B,gBAAM,MAAM,OAAO,aAAa,CAAC,CAAC,IAAI;AAAA,QACvC;AACA,YAAI,SAAS,OAAO,oBAAoB,KAAK,EAAE,IAAI,SAAU,GAAG;AAC/D,iBAAO,MAAM,CAAC;AAAA,QACf,CAAC;AACD,YAAI,OAAO,KAAK,EAAE,MAAM,cAAc;AACrC,iBAAO;AAAA,QACR;AAGA,YAAI,QAAQ,CAAC;AACb,+BAAuB,MAAM,EAAE,EAAE,QAAQ,SAAU,QAAQ;AAC1D,gBAAM,MAAM,IAAI;AAAA,QACjB,CAAC;AACD,YAAI,OAAO,KAAK,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,EAAE,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ACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,iBAAiB,UAAgB,SAA8B;AAEnE,UAAM,SAAS,MAAM,KAAK,cAAc,QAAQ;AAChD,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,UAAU,QAAQ,YAAY;AAAA,IAChD;AAEA,WAAQ,KAAK,SAAiB,iBAAiB,UAAU,OAAO;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,sBAAsB,UAAgB,SAA8B;AACxE,WAAQ,KAAK,SAAiB,sBAAsB,UAAU,OAAO;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,mBAAmB,UAAiC;AACxD,WAAQ,KAAK,SAAiB,mBAAmB,QAAQ;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,mBAAmB,SAAgC;AAEvD,UAAM,UAAU,MAAO,KAAK,SAAiB,kBAAkB;AAC/D,UAAM,YAAY,CAAC;AACnB,eAAW,UAAU,SAAS;AAC5B,YAAM,SAAS,MAAO,KAAK,SAAiB,mBAAmB,OAAO,EAAE;AACxE,UAAI,OAAO,SAAS,OAAO,GAAG;AAC5B,kBAAU,KAAK,OAAO,EAAW;AAAA,MACnC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;","names":["cors","import_cors","logger","bodyParser","express","fileUpload","helmet","fs","path","fileURLToPath","logger","validateUuid","express","express","character","validateUuid","logger","express","express","validateUuid","logger","validateUuid","logger","express","express","logger","validateUuid","validateUuid","logger","express","express","validateUuid","logger","validateUuid","logger","express","express","validateUuid","logger","createUniqueUuid","validateUuid","logger","express","express","validateUuid","logger","createUniqueUuid","express","express","logger","validateUuid","express","express","validateUuid","logger","logger","validateUuid","express","DEFAULT_SERVER_ID","express","logger","validateUuid","logger","validateUuid","express","fs","path","validateUuid","logger","logger","validateUuid","fs","logger","path","logger","validateUuid","logger","validateUuid","logger","logger","DEFAULT_SERVER_ID","express","validateUuid","logger","express","express","validateUuid","logger","express","express","logger","validateUuid","validateUuid","logger","express","rateLimit","express","rateLimit","validateUuid","logger","express","express","validateUuid","logger","createUniqueUuid","ChannelType","express","express","validateUuid","createUniqueUuid","ChannelType","logger","validateUuid","logger","createUniqueUuid","ChannelType","express","express","validateUuid","ChannelType","createUniqueUuid","logger","express","express","logger","ModelType","validateUuid","express","fs","path","path","fs","express","logger","validateUuid","ModelType","validateUuid","logger","ModelType","express","express","validateUuid","ModelType","logger","validateUuid","logger","ModelType","ChannelType","createUniqueUuid","express","express","validateUuid","createUniqueUuid","logger","ChannelType","ModelType","express","express","logger","express","logger","express","express","express","express","express","logger","express","path","fs","express","logger","validateUuid","ChannelType","DEFAULT_SERVER_ID","logger","validateUuid","express","cors","logger","ChannelType","EventType","createUniqueUuid","logger","validateUuid","logger","DEFAULT_SERVER_ID","validateUuid","createUniqueUuid","ChannelType","EventType","fs","path","logger","existsSync","dotenv","path","existsSync","__dirname","fileURLToPath","DEFAULT_SERVER_ID","logger","express","helmet","cors","bodyParser","fileUpload"]}
|