@elizaos/server 1.6.4-alpha.15 → 1.6.4-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -57,6 +57,8 @@ export declare class AgentServer {
57
57
  private clientPath?;
58
58
  elizaOS?: ElizaOS;
59
59
  database: DatabaseAdapter;
60
+ private rlsOwnerId?;
61
+ serverId: UUID;
60
62
  loadCharacterTryPath: (characterPath: string) => Promise<Character>;
61
63
  jsonToCharacter: (character: unknown) => Promise<Character>;
62
64
  /**
package/dist/index.js CHANGED
@@ -26420,7 +26420,6 @@ function transformMessageAttachments(message) {
26420
26420
  }
26421
26421
 
26422
26422
  // src/api/messaging/core.ts
26423
- var DEFAULT_SERVER_ID = "00000000-0000-0000-0000-000000000000";
26424
26423
  function createMessagingCoreRouter(serverInstance) {
26425
26424
  const router = express10.Router();
26426
26425
  router.post("/submit", async (req, res) => {
@@ -26434,7 +26433,7 @@ function createMessagingCoreRouter(serverInstance) {
26434
26433
  raw_message,
26435
26434
  metadata
26436
26435
  } = req.body;
26437
- const isValidServerId = server_id === DEFAULT_SERVER_ID || validateUuid9(server_id);
26436
+ const isValidServerId = server_id === serverInstance.serverId;
26438
26437
  if (!validateUuid9(channel_id) || !validateUuid9(author_id) || !content || !isValidServerId || !source_type || !raw_message) {
26439
26438
  return res.status(400).json({
26440
26439
  success: false,
@@ -26492,7 +26491,7 @@ function createMessagingCoreRouter(serverInstance) {
26492
26491
  raw_message,
26493
26492
  metadata
26494
26493
  } = req.body;
26495
- const isValidServerId = server_id === DEFAULT_SERVER_ID || validateUuid9(server_id);
26494
+ const isValidServerId = server_id === serverInstance.serverId;
26496
26495
  if (!validateUuid9(channel_id) || !validateUuid9(author_id) || !content || !isValidServerId || !source_type || !raw_message) {
26497
26496
  return res.status(400).json({
26498
26497
  success: false,
@@ -26561,8 +26560,8 @@ function createMessagingCoreRouter(serverInstance) {
26561
26560
  if (author_id && !validateUuid9(author_id)) {
26562
26561
  return res.status(400).json({ success: false, error: "Invalid author_id format" });
26563
26562
  }
26564
- if (server_id && !(server_id === DEFAULT_SERVER_ID || validateUuid9(server_id))) {
26565
- return res.status(400).json({ success: false, error: "Invalid server_id format" });
26563
+ if (server_id && server_id !== serverInstance.serverId) {
26564
+ return res.status(403).json({ success: false, error: "Forbidden: server_id does not match current server" });
26566
26565
  }
26567
26566
  try {
26568
26567
  const updated = await serverInstance.updateMessage(id, {
@@ -26660,7 +26659,6 @@ function createMessagingCoreRouter(serverInstance) {
26660
26659
  // src/api/messaging/servers.ts
26661
26660
  import { logger as logger9, validateUuid as validateUuid10 } from "@elizaos/core";
26662
26661
  import express11 from "express";
26663
- var DEFAULT_SERVER_ID2 = "00000000-0000-0000-0000-000000000000";
26664
26662
  function createServersRouter(serverInstance) {
26665
26663
  const router = express11.Router();
26666
26664
  router.get("/central-servers", async (_req, res) => {
@@ -26694,7 +26692,7 @@ function createServersRouter(serverInstance) {
26694
26692
  }
26695
26693
  });
26696
26694
  router.post("/servers/:serverId/agents", async (req, res) => {
26697
- const serverId = req.params.serverId === DEFAULT_SERVER_ID2 ? DEFAULT_SERVER_ID2 : validateUuid10(req.params.serverId);
26695
+ const serverId = validateUuid10(req.params.serverId);
26698
26696
  const { agentId } = req.body;
26699
26697
  if (!serverId || !validateUuid10(agentId)) {
26700
26698
  return res.status(400).json({
@@ -26702,6 +26700,12 @@ function createServersRouter(serverInstance) {
26702
26700
  error: "Invalid serverId or agentId format"
26703
26701
  });
26704
26702
  }
26703
+ if (serverId !== serverInstance.serverId) {
26704
+ return res.status(403).json({
26705
+ success: false,
26706
+ error: "Cannot modify agents for a different server"
26707
+ });
26708
+ }
26705
26709
  try {
26706
26710
  await serverInstance.addAgentToServer(serverId, agentId);
26707
26711
  const messageForBus = {
@@ -26724,7 +26728,7 @@ function createServersRouter(serverInstance) {
26724
26728
  }
26725
26729
  });
26726
26730
  router.delete("/servers/:serverId/agents/:agentId", async (req, res) => {
26727
- const serverId = req.params.serverId === DEFAULT_SERVER_ID2 ? DEFAULT_SERVER_ID2 : validateUuid10(req.params.serverId);
26731
+ const serverId = validateUuid10(req.params.serverId);
26728
26732
  const agentId = validateUuid10(req.params.agentId);
26729
26733
  if (!serverId || !agentId) {
26730
26734
  return res.status(400).json({
@@ -26732,6 +26736,12 @@ function createServersRouter(serverInstance) {
26732
26736
  error: "Invalid serverId or agentId format"
26733
26737
  });
26734
26738
  }
26739
+ if (serverId !== serverInstance.serverId) {
26740
+ return res.status(403).json({
26741
+ success: false,
26742
+ error: "Cannot modify agents for a different server"
26743
+ });
26744
+ }
26735
26745
  try {
26736
26746
  await serverInstance.removeAgentFromServer(serverId, agentId);
26737
26747
  const messageForBus = {
@@ -26754,13 +26764,19 @@ function createServersRouter(serverInstance) {
26754
26764
  }
26755
26765
  });
26756
26766
  router.get("/servers/:serverId/agents", async (req, res) => {
26757
- const serverId = req.params.serverId === DEFAULT_SERVER_ID2 ? DEFAULT_SERVER_ID2 : validateUuid10(req.params.serverId);
26767
+ const serverId = validateUuid10(req.params.serverId);
26758
26768
  if (!serverId) {
26759
26769
  return res.status(400).json({
26760
26770
  success: false,
26761
26771
  error: "Invalid serverId format"
26762
26772
  });
26763
26773
  }
26774
+ if (serverId !== serverInstance.serverId) {
26775
+ return res.status(403).json({
26776
+ success: false,
26777
+ error: "Cannot access agents for a different server"
26778
+ });
26779
+ }
26764
26780
  try {
26765
26781
  const agents = await serverInstance.getAgentsForServer(serverId);
26766
26782
  res.json({
@@ -27603,7 +27619,6 @@ var ALLOWED_MEDIA_MIME_TYPES = [
27603
27619
  import multer from "multer";
27604
27620
  import fs from "fs";
27605
27621
  import path2 from "path";
27606
- var DEFAULT_SERVER_ID3 = "00000000-0000-0000-0000-000000000000";
27607
27622
  var channelStorage = multer.memoryStorage();
27608
27623
  var channelUploadMiddleware = multer({
27609
27624
  storage: channelStorage,
@@ -27647,13 +27662,19 @@ function createChannelsRouter(elizaOS, serverInstance) {
27647
27662
  metadata,
27648
27663
  source_type
27649
27664
  } = req.body;
27650
- const isValidServerId = server_id === DEFAULT_SERVER_ID3 || validateUuid13(server_id);
27651
- if (!channelIdParam || !validateUuid13(author_id) || !content || !isValidServerId) {
27665
+ const isValidServerId = server_id === serverInstance.serverId;
27666
+ if (!channelIdParam || !validateUuid13(author_id) || !content || !validateUuid13(server_id)) {
27652
27667
  return res.status(400).json({
27653
27668
  success: false,
27654
27669
  error: "Missing required fields: channelId, server_id, author_id, content"
27655
27670
  });
27656
27671
  }
27672
+ if (!isValidServerId) {
27673
+ return res.status(403).json({
27674
+ success: false,
27675
+ error: "Forbidden: server_id does not match current server"
27676
+ });
27677
+ }
27657
27678
  try {
27658
27679
  logger15.info(`[Messages Router] Checking if channel ${channelIdParam} exists before creating message`);
27659
27680
  let channelExists = false;
@@ -27799,7 +27820,7 @@ function createChannelsRouter(elizaOS, serverInstance) {
27799
27820
  }
27800
27821
  });
27801
27822
  router.get("/central-servers/:serverId/channels", async (req, res) => {
27802
- const serverId = req.params.serverId === DEFAULT_SERVER_ID3 ? DEFAULT_SERVER_ID3 : validateUuid13(req.params.serverId);
27823
+ const serverId = validateUuid13(req.params.serverId);
27803
27824
  if (!serverId) {
27804
27825
  return res.status(400).json({ success: false, error: "Invalid serverId" });
27805
27826
  }
@@ -27858,7 +27879,7 @@ function createChannelsRouter(elizaOS, serverInstance) {
27858
27879
  router.get("/dm-channel", async (req, res) => {
27859
27880
  const targetUserId = validateUuid13(req.query.targetUserId);
27860
27881
  const currentUserId = validateUuid13(req.query.currentUserId);
27861
- const providedDmServerId = req.query.dmServerId === DEFAULT_SERVER_ID3 ? DEFAULT_SERVER_ID3 : validateUuid13(req.query.dmServerId);
27882
+ const providedDmServerId = validateUuid13(req.query.dmServerId);
27862
27883
  if (!targetUserId || !currentUserId) {
27863
27884
  res.status(400).json({ success: false, error: "Missing targetUserId or currentUserId" });
27864
27885
  return;
@@ -27867,15 +27888,15 @@ function createChannelsRouter(elizaOS, serverInstance) {
27867
27888
  res.status(400).json({ success: false, error: "Cannot create DM channel with oneself" });
27868
27889
  return;
27869
27890
  }
27870
- let dmServerIdToUse = DEFAULT_SERVER_ID3;
27891
+ let dmServerIdToUse = serverInstance.serverId;
27871
27892
  try {
27872
27893
  if (providedDmServerId) {
27873
27894
  const existingServer = await serverInstance.getServerById(providedDmServerId);
27874
27895
  if (existingServer) {
27875
27896
  dmServerIdToUse = providedDmServerId;
27876
27897
  } else {
27877
- logger15.warn(`Provided dmServerId ${providedDmServerId} not found, using default DM server logic.`);
27878
- dmServerIdToUse = DEFAULT_SERVER_ID3;
27898
+ logger15.warn(`Provided dmServerId ${providedDmServerId} not found, using current server ID.`);
27899
+ dmServerIdToUse = serverInstance.serverId;
27879
27900
  }
27880
27901
  }
27881
27902
  const channel = await serverInstance.findOrCreateCentralDmChannel(currentUserId, targetUserId, dmServerIdToUse);
@@ -27898,13 +27919,25 @@ function createChannelsRouter(elizaOS, serverInstance) {
27898
27919
  server_id,
27899
27920
  metadata
27900
27921
  } = req.body;
27901
- const isValidServerId = server_id === DEFAULT_SERVER_ID3 || validateUuid13(server_id);
27902
- if (!name || !isValidServerId || !Array.isArray(participantCentralUserIds) || participantCentralUserIds.some((id) => !validateUuid13(id))) {
27922
+ if (!validateUuid13(server_id)) {
27923
+ return res.status(400).json({
27924
+ success: false,
27925
+ error: "Invalid server_id format"
27926
+ });
27927
+ }
27928
+ const isValidServerId = server_id === serverInstance.serverId;
27929
+ if (!name || !Array.isArray(participantCentralUserIds) || participantCentralUserIds.some((id) => !validateUuid13(id))) {
27903
27930
  return res.status(400).json({
27904
27931
  success: false,
27905
27932
  error: 'Invalid payload. Required: name, server_id (UUID or "0"), participantCentralUserIds (array of UUIDs). Optional: type, metadata.'
27906
27933
  });
27907
27934
  }
27935
+ if (!isValidServerId) {
27936
+ return res.status(403).json({
27937
+ success: false,
27938
+ error: "Forbidden: server_id does not match current server"
27939
+ });
27940
+ }
27908
27941
  try {
27909
27942
  const channelData = {
27910
27943
  messageServerId: server_id,
@@ -28542,7 +28575,6 @@ var DEFAULT_MAX_DURATION_MINUTES = safeParseInt(process.env.SESSION_MAX_DURATION
28542
28575
  var DEFAULT_WARNING_THRESHOLD_MINUTES = safeParseInt(process.env.SESSION_WARNING_THRESHOLD_MINUTES, 5, 1, 60);
28543
28576
  var CLEANUP_INTERVAL_MS = safeParseInt(process.env.SESSION_CLEANUP_INTERVAL_MINUTES, 5, 1, 60) * 60 * 1000;
28544
28577
  var sessions = new Map;
28545
- var DEFAULT_SERVER_ID4 = "00000000-0000-0000-0000-000000000000";
28546
28578
  var agentTimeoutConfigs = new Map;
28547
28579
  var activeCleanupIntervals = new Set;
28548
28580
  var processHandlersRegistered = false;
@@ -28778,7 +28810,7 @@ function createSessionsRouter(elizaOS, serverInstance) {
28778
28810
  id: channelId,
28779
28811
  name: `session-${sessionId}`,
28780
28812
  type: ChannelType3.DM,
28781
- messageServerId: DEFAULT_SERVER_ID4,
28813
+ messageServerId: serverInstance.serverId,
28782
28814
  metadata: {
28783
28815
  sessionId,
28784
28816
  agentId: body.agentId,
@@ -29208,7 +29240,7 @@ var JobValidation = {
29208
29240
  };
29209
29241
 
29210
29242
  // src/api/messaging/jobs.ts
29211
- var DEFAULT_SERVER_ID5 = "00000000-0000-0000-0000-000000000000";
29243
+ var DEFAULT_SERVER_ID = "00000000-0000-0000-0000-000000000000";
29212
29244
  var JOB_CLEANUP_INTERVAL_MS = 60000;
29213
29245
  var ABSOLUTE_MAX_LISTENER_TIMEOUT_MS = 5 * 60 * 1000;
29214
29246
  var MAX_JOBS_IN_MEMORY = 1e4;
@@ -29411,7 +29443,7 @@ function createJobsRouter(elizaOS, serverInstance) {
29411
29443
  id: channelId,
29412
29444
  name: `job-${jobId}`,
29413
29445
  type: ChannelType4.DM,
29414
- messageServerId: DEFAULT_SERVER_ID5,
29446
+ messageServerId: DEFAULT_SERVER_ID,
29415
29447
  metadata: {
29416
29448
  jobId,
29417
29449
  agentId,
@@ -29448,7 +29480,7 @@ function createJobsRouter(elizaOS, serverInstance) {
29448
29480
  bus_default.emit("new_message", {
29449
29481
  id: userMessage.id,
29450
29482
  channel_id: channelId,
29451
- server_id: DEFAULT_SERVER_ID5,
29483
+ server_id: DEFAULT_SERVER_ID,
29452
29484
  author_id: userId,
29453
29485
  content: body.content,
29454
29486
  created_at: new Date(userMessage.createdAt).getTime(),
@@ -30624,7 +30656,7 @@ import express31 from "express";
30624
30656
  // package.json
30625
30657
  var package_default = {
30626
30658
  name: "@elizaos/server",
30627
- version: "1.6.4-alpha.15",
30659
+ version: "1.6.4-alpha.16",
30628
30660
  description: "ElizaOS Server - Core server infrastructure for ElizaOS agents",
30629
30661
  publishConfig: {
30630
30662
  access: "public",
@@ -30744,8 +30776,6 @@ import {
30744
30776
  ChannelType as ChannelType7,
30745
30777
  EventType
30746
30778
  } from "@elizaos/core";
30747
- var DEFAULT_SERVER_ID6 = "00000000-0000-0000-0000-000000000000";
30748
-
30749
30779
  class SocketIORouter {
30750
30780
  elizaOS;
30751
30781
  connections;
@@ -30844,8 +30874,8 @@ class SocketIORouter {
30844
30874
  }
30845
30875
  socket.join(channelId);
30846
30876
  logger29.info(`[SocketIO] Socket ${socket.id} joined Socket.IO channel: ${channelId}`);
30847
- if (entityId && (serverId || DEFAULT_SERVER_ID6)) {
30848
- const finalServerId = serverId || DEFAULT_SERVER_ID6;
30877
+ if (entityId && (serverId || this.serverInstance.serverId)) {
30878
+ const finalServerId = serverId || this.serverInstance.serverId;
30849
30879
  const isDm = metadata?.isDm || metadata?.channelType === ChannelType7.DM;
30850
30880
  logger29.info(`[SocketIO] Emitting ENTITY_JOINED event for entityId: ${entityId}, serverId: ${finalServerId}, isDm: ${isDm}`);
30851
30881
  const runtime = this.elizaOS.getAgents()[0];
@@ -30867,7 +30897,7 @@ class SocketIORouter {
30867
30897
  logger29.warn(`[SocketIO] No runtime available to emit ENTITY_JOINED event`);
30868
30898
  }
30869
30899
  } else {
30870
- logger29.debug(`[SocketIO] Missing entityId (${entityId}) or serverId (${serverId || DEFAULT_SERVER_ID6}) - not emitting ENTITY_JOINED event`);
30900
+ logger29.debug(`[SocketIO] Missing entityId (${entityId}) or serverId (${serverId || this.serverInstance.serverId}) - not emitting ENTITY_JOINED event`);
30871
30901
  }
30872
30902
  const successMessage = `Socket ${socket.id} successfully joined channel ${channelId}.`;
30873
30903
  const responsePayload = {
@@ -30885,7 +30915,7 @@ class SocketIORouter {
30885
30915
  const { senderId, senderName, message, serverId, source, metadata, attachments } = payload;
30886
30916
  logger29.info(`[SocketIO ${socket.id}] Received SEND_MESSAGE for central submission: channel ${channelId} from ${senderName || senderId}`);
30887
30917
  logger29.info(`[SocketIO ${socket.id}] Full payload for debugging:`, JSON.stringify(payload, null, 2));
30888
- const isValidServerId = serverId === DEFAULT_SERVER_ID6 || validateUuid23(serverId);
30918
+ const isValidServerId = serverId === this.serverInstance.serverId || validateUuid23(serverId);
30889
30919
  if (!validateUuid23(channelId) || !isValidServerId || !validateUuid23(senderId) || !message) {
30890
30920
  this.sendErrorResponse(socket, `For SEND_MESSAGE: channelId, serverId (server_id), senderId (author_id), and message are required.`);
30891
30921
  return;
@@ -31313,16 +31343,27 @@ import {
31313
31343
  validateUuid as validateUuid25
31314
31344
  } from "@elizaos/core";
31315
31345
  var globalElizaOS = null;
31346
+ var globalAgentServer = null;
31316
31347
  function setGlobalElizaOS(elizaOS) {
31317
31348
  globalElizaOS = elizaOS;
31318
31349
  logger31.info("[MessageBusService] Global ElizaOS instance set");
31319
31350
  }
31351
+ function setGlobalAgentServer(agentServer) {
31352
+ globalAgentServer = agentServer;
31353
+ logger31.info("[MessageBusService] Global AgentServer instance set");
31354
+ }
31320
31355
  function getGlobalElizaOS() {
31321
31356
  if (!globalElizaOS) {
31322
31357
  throw new Error("ElizaOS not initialized. Call setGlobalElizaOS() before using MessageBusService.");
31323
31358
  }
31324
31359
  return globalElizaOS;
31325
31360
  }
31361
+ function getGlobalAgentServer() {
31362
+ if (!globalAgentServer) {
31363
+ throw new Error("AgentServer not initialized. Call setGlobalAgentServer() before using MessageBusService.");
31364
+ }
31365
+ return globalAgentServer;
31366
+ }
31326
31367
 
31327
31368
  class MessageBusService extends Service {
31328
31369
  static serviceType = "message-bus-service";
@@ -31332,8 +31373,10 @@ class MessageBusService extends Service {
31332
31373
  boundHandleMessageDeleted;
31333
31374
  boundHandleChannelCleared;
31334
31375
  subscribedServers = new Set;
31376
+ serverInstance;
31335
31377
  constructor(runtime) {
31336
31378
  super(runtime);
31379
+ this.serverInstance = getGlobalAgentServer();
31337
31380
  this.boundHandleIncomingMessage = (data) => {
31338
31381
  this.handleIncomingMessage(data).catch((error) => {
31339
31382
  logger31.error(`[${this.runtime.character.name}] Error handling incoming message:`, error instanceof Error ? error.message : String(error));
@@ -31366,9 +31409,8 @@ class MessageBusService extends Service {
31366
31409
  try {
31367
31410
  const serverApiUrl = this.getCentralMessageServerUrl();
31368
31411
  this.validChannelIds.clear();
31369
- const DEFAULT_SERVER_ID7 = "00000000-0000-0000-0000-000000000000";
31370
31412
  const serversToCheck = new Set(this.subscribedServers);
31371
- serversToCheck.add(DEFAULT_SERVER_ID7);
31413
+ serversToCheck.add(this.serverInstance.serverId);
31372
31414
  for (const serverId of serversToCheck) {
31373
31415
  try {
31374
31416
  const channelsUrl = new URL(`/api/messaging/central-servers/${encodeURIComponent(serverId)}/channels`, serverApiUrl);
@@ -31444,20 +31486,17 @@ class MessageBusService extends Service {
31444
31486
  const data = await response.json();
31445
31487
  if (data.success && data.data?.servers) {
31446
31488
  this.subscribedServers = new Set(data.data.servers);
31447
- const DEFAULT_SERVER_ID7 = "00000000-0000-0000-0000-000000000000";
31448
- this.subscribedServers.add(DEFAULT_SERVER_ID7);
31449
- logger31.info(`[${this.runtime.character.name}] MessageBusService: Agent is subscribed to ${this.subscribedServers.size} servers (including default server)`);
31489
+ this.subscribedServers.add(this.serverInstance.serverId);
31490
+ logger31.info(`[${this.runtime.character.name}] MessageBusService: Agent is subscribed to ${this.subscribedServers.size} servers (including server ${this.serverInstance.serverId})`);
31450
31491
  }
31451
31492
  } else {
31452
- const DEFAULT_SERVER_ID7 = "00000000-0000-0000-0000-000000000000";
31453
- this.subscribedServers.add(DEFAULT_SERVER_ID7);
31454
- logger31.warn(`[${this.runtime.character.name}] MessageBusService: Failed to fetch agent servers, but added default server`);
31493
+ this.subscribedServers.add(this.serverInstance.serverId);
31494
+ logger31.warn(`[${this.runtime.character.name}] MessageBusService: Failed to fetch agent servers, but added server ${this.serverInstance.serverId}`);
31455
31495
  }
31456
31496
  } catch (error) {
31457
31497
  logger31.error(`[${this.runtime.character.name}] MessageBusService: Error fetching agent servers:`, error instanceof Error ? error.message : String(error));
31458
- const DEFAULT_SERVER_ID7 = "00000000-0000-0000-0000-000000000000";
31459
- this.subscribedServers.add(DEFAULT_SERVER_ID7);
31460
- logger31.info(`[${this.runtime.character.name}] MessageBusService: Added default server after error`);
31498
+ this.subscribedServers.add(this.serverInstance.serverId);
31499
+ logger31.info(`[${this.runtime.character.name}] MessageBusService: Added server ${this.serverInstance.serverId} after error`);
31461
31500
  }
31462
31501
  }
31463
31502
  async handleServerAgentUpdate(data) {
@@ -48493,8 +48532,632 @@ function _init2(options = {}, getDefaultIntegrationsImpl) {
48493
48532
  return client;
48494
48533
  }
48495
48534
  // src/index.ts
48496
- import sqlPlugin, { createDatabaseAdapter, DatabaseMigrationService } from "@elizaos/plugin-sql";
48535
+ import sqlPlugin, {
48536
+ createDatabaseAdapter,
48537
+ DatabaseMigrationService,
48538
+ installRLSFunctions,
48539
+ getOrCreateRlsOwner,
48540
+ setOwnerContext,
48541
+ assignAgentToOwner,
48542
+ applyRLSToNewTables,
48543
+ uninstallRLS
48544
+ } from "@elizaos/plugin-sql";
48497
48545
  import { encryptedCharacter, stringToUuid as stringToUuid2 } from "@elizaos/core";
48546
+
48547
+ // ../../node_modules/drizzle-orm/entity.js
48548
+ var entityKind = Symbol.for("drizzle:entityKind");
48549
+ var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
48550
+ function is(value, type) {
48551
+ if (!value || typeof value !== "object") {
48552
+ return false;
48553
+ }
48554
+ if (value instanceof type) {
48555
+ return true;
48556
+ }
48557
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
48558
+ throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
48559
+ }
48560
+ let cls = Object.getPrototypeOf(value).constructor;
48561
+ if (cls) {
48562
+ while (cls) {
48563
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
48564
+ return true;
48565
+ }
48566
+ cls = Object.getPrototypeOf(cls);
48567
+ }
48568
+ }
48569
+ return false;
48570
+ }
48571
+
48572
+ // ../../node_modules/drizzle-orm/column.js
48573
+ class Column {
48574
+ constructor(table, config3) {
48575
+ this.table = table;
48576
+ this.config = config3;
48577
+ this.name = config3.name;
48578
+ this.keyAsName = config3.keyAsName;
48579
+ this.notNull = config3.notNull;
48580
+ this.default = config3.default;
48581
+ this.defaultFn = config3.defaultFn;
48582
+ this.onUpdateFn = config3.onUpdateFn;
48583
+ this.hasDefault = config3.hasDefault;
48584
+ this.primary = config3.primaryKey;
48585
+ this.isUnique = config3.isUnique;
48586
+ this.uniqueName = config3.uniqueName;
48587
+ this.uniqueType = config3.uniqueType;
48588
+ this.dataType = config3.dataType;
48589
+ this.columnType = config3.columnType;
48590
+ this.generated = config3.generated;
48591
+ this.generatedIdentity = config3.generatedIdentity;
48592
+ }
48593
+ static [entityKind] = "Column";
48594
+ name;
48595
+ keyAsName;
48596
+ primary;
48597
+ notNull;
48598
+ default;
48599
+ defaultFn;
48600
+ onUpdateFn;
48601
+ hasDefault;
48602
+ isUnique;
48603
+ uniqueName;
48604
+ uniqueType;
48605
+ dataType;
48606
+ columnType;
48607
+ enumValues = undefined;
48608
+ generated = undefined;
48609
+ generatedIdentity = undefined;
48610
+ config;
48611
+ mapFromDriverValue(value) {
48612
+ return value;
48613
+ }
48614
+ mapToDriverValue(value) {
48615
+ return value;
48616
+ }
48617
+ shouldDisableInsert() {
48618
+ return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
48619
+ }
48620
+ }
48621
+
48622
+ // ../../node_modules/drizzle-orm/table.utils.js
48623
+ var TableName = Symbol.for("drizzle:Name");
48624
+
48625
+ // ../../node_modules/drizzle-orm/tracing-utils.js
48626
+ function iife(fn, ...args) {
48627
+ return fn(...args);
48628
+ }
48629
+
48630
+ // ../../node_modules/drizzle-orm/pg-core/unique-constraint.js
48631
+ function uniqueKeyName(table, columns) {
48632
+ return `${table[TableName]}_${columns.join("_")}_unique`;
48633
+ }
48634
+
48635
+ // ../../node_modules/drizzle-orm/pg-core/columns/common.js
48636
+ class PgColumn extends Column {
48637
+ constructor(table, config3) {
48638
+ if (!config3.uniqueName) {
48639
+ config3.uniqueName = uniqueKeyName(table, [config3.name]);
48640
+ }
48641
+ super(table, config3);
48642
+ this.table = table;
48643
+ }
48644
+ static [entityKind] = "PgColumn";
48645
+ }
48646
+
48647
+ class ExtraConfigColumn extends PgColumn {
48648
+ static [entityKind] = "ExtraConfigColumn";
48649
+ getSQLType() {
48650
+ return this.getSQLType();
48651
+ }
48652
+ indexConfig = {
48653
+ order: this.config.order ?? "asc",
48654
+ nulls: this.config.nulls ?? "last",
48655
+ opClass: this.config.opClass
48656
+ };
48657
+ defaultConfig = {
48658
+ order: "asc",
48659
+ nulls: "last",
48660
+ opClass: undefined
48661
+ };
48662
+ asc() {
48663
+ this.indexConfig.order = "asc";
48664
+ return this;
48665
+ }
48666
+ desc() {
48667
+ this.indexConfig.order = "desc";
48668
+ return this;
48669
+ }
48670
+ nullsFirst() {
48671
+ this.indexConfig.nulls = "first";
48672
+ return this;
48673
+ }
48674
+ nullsLast() {
48675
+ this.indexConfig.nulls = "last";
48676
+ return this;
48677
+ }
48678
+ op(opClass) {
48679
+ this.indexConfig.opClass = opClass;
48680
+ return this;
48681
+ }
48682
+ }
48683
+
48684
+ // ../../node_modules/drizzle-orm/pg-core/columns/enum.js
48685
+ class PgEnumObjectColumn extends PgColumn {
48686
+ static [entityKind] = "PgEnumObjectColumn";
48687
+ enum;
48688
+ enumValues = this.config.enum.enumValues;
48689
+ constructor(table, config3) {
48690
+ super(table, config3);
48691
+ this.enum = config3.enum;
48692
+ }
48693
+ getSQLType() {
48694
+ return this.enum.enumName;
48695
+ }
48696
+ }
48697
+ var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
48698
+ function isPgEnum(obj) {
48699
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
48700
+ }
48701
+ class PgEnumColumn extends PgColumn {
48702
+ static [entityKind] = "PgEnumColumn";
48703
+ enum = this.config.enum;
48704
+ enumValues = this.config.enum.enumValues;
48705
+ constructor(table, config3) {
48706
+ super(table, config3);
48707
+ this.enum = config3.enum;
48708
+ }
48709
+ getSQLType() {
48710
+ return this.enum.enumName;
48711
+ }
48712
+ }
48713
+
48714
+ // ../../node_modules/drizzle-orm/subquery.js
48715
+ class Subquery {
48716
+ static [entityKind] = "Subquery";
48717
+ constructor(sql, fields, alias, isWith = false, usedTables = []) {
48718
+ this._ = {
48719
+ brand: "Subquery",
48720
+ sql,
48721
+ selectedFields: fields,
48722
+ alias,
48723
+ isWith,
48724
+ usedTables
48725
+ };
48726
+ }
48727
+ }
48728
+
48729
+ // ../../node_modules/drizzle-orm/version.js
48730
+ var version = "0.44.7";
48731
+
48732
+ // ../../node_modules/drizzle-orm/tracing.js
48733
+ var otel;
48734
+ var rawTracer;
48735
+ var tracer = {
48736
+ startActiveSpan(name, fn) {
48737
+ if (!otel) {
48738
+ return fn();
48739
+ }
48740
+ if (!rawTracer) {
48741
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
48742
+ }
48743
+ return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
48744
+ try {
48745
+ return fn(span);
48746
+ } catch (e) {
48747
+ span.setStatus({
48748
+ code: otel2.SpanStatusCode.ERROR,
48749
+ message: e instanceof Error ? e.message : "Unknown error"
48750
+ });
48751
+ throw e;
48752
+ } finally {
48753
+ span.end();
48754
+ }
48755
+ }), otel, rawTracer);
48756
+ }
48757
+ };
48758
+
48759
+ // ../../node_modules/drizzle-orm/view-common.js
48760
+ var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
48761
+
48762
+ // ../../node_modules/drizzle-orm/table.js
48763
+ var Schema = Symbol.for("drizzle:Schema");
48764
+ var Columns = Symbol.for("drizzle:Columns");
48765
+ var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
48766
+ var OriginalName = Symbol.for("drizzle:OriginalName");
48767
+ var BaseName = Symbol.for("drizzle:BaseName");
48768
+ var IsAlias = Symbol.for("drizzle:IsAlias");
48769
+ var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
48770
+ var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
48771
+
48772
+ class Table {
48773
+ static [entityKind] = "Table";
48774
+ static Symbol = {
48775
+ Name: TableName,
48776
+ Schema,
48777
+ OriginalName,
48778
+ Columns,
48779
+ ExtraConfigColumns,
48780
+ BaseName,
48781
+ IsAlias,
48782
+ ExtraConfigBuilder
48783
+ };
48784
+ [TableName];
48785
+ [OriginalName];
48786
+ [Schema];
48787
+ [Columns];
48788
+ [ExtraConfigColumns];
48789
+ [BaseName];
48790
+ [IsAlias] = false;
48791
+ [IsDrizzleTable] = true;
48792
+ [ExtraConfigBuilder] = undefined;
48793
+ constructor(name, schema, baseName) {
48794
+ this[TableName] = this[OriginalName] = name;
48795
+ this[Schema] = schema;
48796
+ this[BaseName] = baseName;
48797
+ }
48798
+ }
48799
+
48800
+ // ../../node_modules/drizzle-orm/sql/sql.js
48801
+ function isSQLWrapper(value) {
48802
+ return value !== null && value !== undefined && typeof value.getSQL === "function";
48803
+ }
48804
+ function mergeQueries(queries) {
48805
+ const result = { sql: "", params: [] };
48806
+ for (const query of queries) {
48807
+ result.sql += query.sql;
48808
+ result.params.push(...query.params);
48809
+ if (query.typings?.length) {
48810
+ if (!result.typings) {
48811
+ result.typings = [];
48812
+ }
48813
+ result.typings.push(...query.typings);
48814
+ }
48815
+ }
48816
+ return result;
48817
+ }
48818
+
48819
+ class StringChunk {
48820
+ static [entityKind] = "StringChunk";
48821
+ value;
48822
+ constructor(value) {
48823
+ this.value = Array.isArray(value) ? value : [value];
48824
+ }
48825
+ getSQL() {
48826
+ return new SQL([this]);
48827
+ }
48828
+ }
48829
+
48830
+ class SQL {
48831
+ constructor(queryChunks) {
48832
+ this.queryChunks = queryChunks;
48833
+ for (const chunk of queryChunks) {
48834
+ if (is(chunk, Table)) {
48835
+ const schemaName = chunk[Table.Symbol.Schema];
48836
+ this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
48837
+ }
48838
+ }
48839
+ }
48840
+ static [entityKind] = "SQL";
48841
+ decoder = noopDecoder;
48842
+ shouldInlineParams = false;
48843
+ usedTables = [];
48844
+ append(query) {
48845
+ this.queryChunks.push(...query.queryChunks);
48846
+ return this;
48847
+ }
48848
+ toQuery(config3) {
48849
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
48850
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config3);
48851
+ span?.setAttributes({
48852
+ "drizzle.query.text": query.sql,
48853
+ "drizzle.query.params": JSON.stringify(query.params)
48854
+ });
48855
+ return query;
48856
+ });
48857
+ }
48858
+ buildQueryFromSourceParams(chunks, _config) {
48859
+ const config3 = Object.assign({}, _config, {
48860
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
48861
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
48862
+ });
48863
+ const {
48864
+ casing,
48865
+ escapeName,
48866
+ escapeParam,
48867
+ prepareTyping,
48868
+ inlineParams,
48869
+ paramStartIndex
48870
+ } = config3;
48871
+ return mergeQueries(chunks.map((chunk) => {
48872
+ if (is(chunk, StringChunk)) {
48873
+ return { sql: chunk.value.join(""), params: [] };
48874
+ }
48875
+ if (is(chunk, Name)) {
48876
+ return { sql: escapeName(chunk.value), params: [] };
48877
+ }
48878
+ if (chunk === undefined) {
48879
+ return { sql: "", params: [] };
48880
+ }
48881
+ if (Array.isArray(chunk)) {
48882
+ const result = [new StringChunk("(")];
48883
+ for (const [i, p] of chunk.entries()) {
48884
+ result.push(p);
48885
+ if (i < chunk.length - 1) {
48886
+ result.push(new StringChunk(", "));
48887
+ }
48888
+ }
48889
+ result.push(new StringChunk(")"));
48890
+ return this.buildQueryFromSourceParams(result, config3);
48891
+ }
48892
+ if (is(chunk, SQL)) {
48893
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
48894
+ ...config3,
48895
+ inlineParams: inlineParams || chunk.shouldInlineParams
48896
+ });
48897
+ }
48898
+ if (is(chunk, Table)) {
48899
+ const schemaName = chunk[Table.Symbol.Schema];
48900
+ const tableName = chunk[Table.Symbol.Name];
48901
+ return {
48902
+ sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
48903
+ params: []
48904
+ };
48905
+ }
48906
+ if (is(chunk, Column)) {
48907
+ const columnName = casing.getColumnCasing(chunk);
48908
+ if (_config.invokeSource === "indexes") {
48909
+ return { sql: escapeName(columnName), params: [] };
48910
+ }
48911
+ const schemaName = chunk.table[Table.Symbol.Schema];
48912
+ return {
48913
+ sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
48914
+ params: []
48915
+ };
48916
+ }
48917
+ if (is(chunk, View)) {
48918
+ const schemaName = chunk[ViewBaseConfig].schema;
48919
+ const viewName = chunk[ViewBaseConfig].name;
48920
+ return {
48921
+ sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
48922
+ params: []
48923
+ };
48924
+ }
48925
+ if (is(chunk, Param)) {
48926
+ if (is(chunk.value, Placeholder)) {
48927
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
48928
+ }
48929
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
48930
+ if (is(mappedValue, SQL)) {
48931
+ return this.buildQueryFromSourceParams([mappedValue], config3);
48932
+ }
48933
+ if (inlineParams) {
48934
+ return { sql: this.mapInlineParam(mappedValue, config3), params: [] };
48935
+ }
48936
+ let typings = ["none"];
48937
+ if (prepareTyping) {
48938
+ typings = [prepareTyping(chunk.encoder)];
48939
+ }
48940
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
48941
+ }
48942
+ if (is(chunk, Placeholder)) {
48943
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
48944
+ }
48945
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
48946
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
48947
+ }
48948
+ if (is(chunk, Subquery)) {
48949
+ if (chunk._.isWith) {
48950
+ return { sql: escapeName(chunk._.alias), params: [] };
48951
+ }
48952
+ return this.buildQueryFromSourceParams([
48953
+ new StringChunk("("),
48954
+ chunk._.sql,
48955
+ new StringChunk(") "),
48956
+ new Name(chunk._.alias)
48957
+ ], config3);
48958
+ }
48959
+ if (isPgEnum(chunk)) {
48960
+ if (chunk.schema) {
48961
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
48962
+ }
48963
+ return { sql: escapeName(chunk.enumName), params: [] };
48964
+ }
48965
+ if (isSQLWrapper(chunk)) {
48966
+ if (chunk.shouldOmitSQLParens?.()) {
48967
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config3);
48968
+ }
48969
+ return this.buildQueryFromSourceParams([
48970
+ new StringChunk("("),
48971
+ chunk.getSQL(),
48972
+ new StringChunk(")")
48973
+ ], config3);
48974
+ }
48975
+ if (inlineParams) {
48976
+ return { sql: this.mapInlineParam(chunk, config3), params: [] };
48977
+ }
48978
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
48979
+ }));
48980
+ }
48981
+ mapInlineParam(chunk, { escapeString }) {
48982
+ if (chunk === null) {
48983
+ return "null";
48984
+ }
48985
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
48986
+ return chunk.toString();
48987
+ }
48988
+ if (typeof chunk === "string") {
48989
+ return escapeString(chunk);
48990
+ }
48991
+ if (typeof chunk === "object") {
48992
+ const mappedValueAsString = chunk.toString();
48993
+ if (mappedValueAsString === "[object Object]") {
48994
+ return escapeString(JSON.stringify(chunk));
48995
+ }
48996
+ return escapeString(mappedValueAsString);
48997
+ }
48998
+ throw new Error("Unexpected param value: " + chunk);
48999
+ }
49000
+ getSQL() {
49001
+ return this;
49002
+ }
49003
+ as(alias) {
49004
+ if (alias === undefined) {
49005
+ return this;
49006
+ }
49007
+ return new SQL.Aliased(this, alias);
49008
+ }
49009
+ mapWith(decoder) {
49010
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
49011
+ return this;
49012
+ }
49013
+ inlineParams() {
49014
+ this.shouldInlineParams = true;
49015
+ return this;
49016
+ }
49017
+ if(condition) {
49018
+ return condition ? this : undefined;
49019
+ }
49020
+ }
49021
+
49022
+ class Name {
49023
+ constructor(value) {
49024
+ this.value = value;
49025
+ }
49026
+ static [entityKind] = "Name";
49027
+ brand;
49028
+ getSQL() {
49029
+ return new SQL([this]);
49030
+ }
49031
+ }
49032
+ var noopDecoder = {
49033
+ mapFromDriverValue: (value) => value
49034
+ };
49035
+ var noopEncoder = {
49036
+ mapToDriverValue: (value) => value
49037
+ };
49038
+ var noopMapper = {
49039
+ ...noopDecoder,
49040
+ ...noopEncoder
49041
+ };
49042
+
49043
+ class Param {
49044
+ constructor(value, encoder = noopEncoder) {
49045
+ this.value = value;
49046
+ this.encoder = encoder;
49047
+ }
49048
+ static [entityKind] = "Param";
49049
+ brand;
49050
+ getSQL() {
49051
+ return new SQL([this]);
49052
+ }
49053
+ }
49054
+ function sql(strings, ...params) {
49055
+ const queryChunks = [];
49056
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
49057
+ queryChunks.push(new StringChunk(strings[0]));
49058
+ }
49059
+ for (const [paramIndex, param2] of params.entries()) {
49060
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
49061
+ }
49062
+ return new SQL(queryChunks);
49063
+ }
49064
+ ((sql2) => {
49065
+ function empty() {
49066
+ return new SQL([]);
49067
+ }
49068
+ sql2.empty = empty;
49069
+ function fromList(list) {
49070
+ return new SQL(list);
49071
+ }
49072
+ sql2.fromList = fromList;
49073
+ function raw(str) {
49074
+ return new SQL([new StringChunk(str)]);
49075
+ }
49076
+ sql2.raw = raw;
49077
+ function join4(chunks, separator) {
49078
+ const result = [];
49079
+ for (const [i, chunk] of chunks.entries()) {
49080
+ if (i > 0 && separator !== undefined) {
49081
+ result.push(separator);
49082
+ }
49083
+ result.push(chunk);
49084
+ }
49085
+ return new SQL(result);
49086
+ }
49087
+ sql2.join = join4;
49088
+ function identifier(value) {
49089
+ return new Name(value);
49090
+ }
49091
+ sql2.identifier = identifier;
49092
+ function placeholder2(name2) {
49093
+ return new Placeholder(name2);
49094
+ }
49095
+ sql2.placeholder = placeholder2;
49096
+ function param2(value, encoder) {
49097
+ return new Param(value, encoder);
49098
+ }
49099
+ sql2.param = param2;
49100
+ })(sql || (sql = {}));
49101
+ ((SQL2) => {
49102
+
49103
+ class Aliased {
49104
+ constructor(sql2, fieldAlias) {
49105
+ this.sql = sql2;
49106
+ this.fieldAlias = fieldAlias;
49107
+ }
49108
+ static [entityKind] = "SQL.Aliased";
49109
+ isSelectionField = false;
49110
+ getSQL() {
49111
+ return this.sql;
49112
+ }
49113
+ clone() {
49114
+ return new Aliased(this.sql, this.fieldAlias);
49115
+ }
49116
+ }
49117
+ SQL2.Aliased = Aliased;
49118
+ })(SQL || (SQL = {}));
49119
+
49120
+ class Placeholder {
49121
+ constructor(name2) {
49122
+ this.name = name2;
49123
+ }
49124
+ static [entityKind] = "Placeholder";
49125
+ getSQL() {
49126
+ return new SQL([this]);
49127
+ }
49128
+ }
49129
+ var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
49130
+
49131
+ class View {
49132
+ static [entityKind] = "View";
49133
+ [ViewBaseConfig];
49134
+ [IsDrizzleView] = true;
49135
+ constructor({ name: name2, schema, selectedFields, query }) {
49136
+ this[ViewBaseConfig] = {
49137
+ name: name2,
49138
+ originalName: name2,
49139
+ schema,
49140
+ selectedFields,
49141
+ query,
49142
+ isExisting: !query,
49143
+ isAlias: false
49144
+ };
49145
+ }
49146
+ getSQL() {
49147
+ return new SQL([this]);
49148
+ }
49149
+ }
49150
+ Column.prototype.getSQL = function() {
49151
+ return new SQL([this]);
49152
+ };
49153
+ Table.prototype.getSQL = function() {
49154
+ return new SQL([this]);
49155
+ };
49156
+ Subquery.prototype.getSQL = function() {
49157
+ return new SQL([this]);
49158
+ };
49159
+
49160
+ // src/index.ts
48498
49161
  import { existsSync as existsSync4 } from "node:fs";
48499
49162
  var import_dotenv2 = __toESM(require_main(), 1);
48500
49163
  import { ElizaOS as ElizaOS4 } from "@elizaos/core";
@@ -48535,7 +49198,7 @@ function resolvePgliteDir(dir, fallbackDir) {
48535
49198
  return resolved;
48536
49199
  }
48537
49200
  var __dirname3 = dirname3(fileURLToPath2(import.meta.url));
48538
- var DEFAULT_SERVER_ID7 = "00000000-0000-0000-0000-000000000000";
49201
+ var DEFAULT_SERVER_ID2 = "00000000-0000-0000-0000-000000000000";
48539
49202
  function isWebUIEnabled() {
48540
49203
  const isProduction = false;
48541
49204
  const uiEnabledEnv = process.env.ELIZA_UI_ENABLE;
@@ -48554,6 +49217,8 @@ class AgentServer {
48554
49217
  clientPath;
48555
49218
  elizaOS;
48556
49219
  database;
49220
+ rlsOwnerId;
49221
+ serverId = DEFAULT_SERVER_ID2;
48557
49222
  loadCharacterTryPath;
48558
49223
  jsonToCharacter;
48559
49224
  async startAgents(agents, options) {
@@ -48585,6 +49250,9 @@ class AgentServer {
48585
49250
  });
48586
49251
  logger33.info(`Persisted agent ${runtime.character.name} (${runtime.agentId}) to database`);
48587
49252
  }
49253
+ if (this.rlsOwnerId) {
49254
+ await assignAgentToOwner(this.database, runtime.agentId, this.rlsOwnerId);
49255
+ }
48588
49256
  } catch (error2) {
48589
49257
  logger33.error({ error: error2 }, `Failed to persist agent ${runtime.agentId} to database`);
48590
49258
  }
@@ -48657,6 +49325,43 @@ class AgentServer {
48657
49325
  logger33.error({ error: migrationError }, "[INIT] Failed to run database migrations:");
48658
49326
  throw new Error(`Database migration failed: ${migrationError instanceof Error ? migrationError.message : String(migrationError)}`);
48659
49327
  }
49328
+ const rlsEnabled = process.env.ENABLE_RLS_ISOLATION === "true";
49329
+ const rlsOwnerIdString = process.env.RLS_OWNER_ID;
49330
+ if (rlsEnabled) {
49331
+ if (!config3?.postgresUrl) {
49332
+ logger33.error("[RLS] ENABLE_RLS_ISOLATION requires PostgreSQL (not compatible with PGLite)");
49333
+ throw new Error("RLS isolation requires PostgreSQL database");
49334
+ }
49335
+ if (!rlsOwnerIdString) {
49336
+ logger33.error("[RLS] ENABLE_RLS_ISOLATION requires RLS_OWNER_ID environment variable");
49337
+ throw new Error("RLS_OWNER_ID environment variable is required when RLS is enabled");
49338
+ }
49339
+ const owner_id = stringToUuid2(rlsOwnerIdString);
49340
+ logger33.info("[INIT] Initializing RLS multi-tenant isolation...");
49341
+ logger33.info(`[RLS] Tenant ID: ${owner_id.slice(0, 8)}… (from RLS_OWNER_ID="${rlsOwnerIdString}")`);
49342
+ logger33.warn("[RLS] Ensure your PostgreSQL user is NOT a superuser!");
49343
+ logger33.warn("[RLS] Superusers bypass ALL RLS policies, defeating isolation.");
49344
+ try {
49345
+ await installRLSFunctions(this.database);
49346
+ await getOrCreateRlsOwner(this.database, owner_id);
49347
+ this.rlsOwnerId = owner_id;
49348
+ await setOwnerContext(this.database, owner_id);
49349
+ await applyRLSToNewTables(this.database);
49350
+ logger33.success("[INIT] RLS multi-tenant isolation initialized successfully");
49351
+ } catch (rlsError) {
49352
+ logger33.error({ error: rlsError }, "[INIT] Failed to initialize RLS:");
49353
+ throw new Error(`RLS initialization failed: ${rlsError instanceof Error ? rlsError.message : String(rlsError)}`);
49354
+ }
49355
+ } else if (config3?.postgresUrl) {
49356
+ logger33.info("[INIT] RLS multi-tenant isolation disabled (legacy mode)");
49357
+ try {
49358
+ logger33.info("[INIT] Cleaning up RLS policies and functions...");
49359
+ await uninstallRLS(this.database);
49360
+ logger33.success("[INIT] RLS cleanup completed");
49361
+ } catch (cleanupError) {
49362
+ logger33.debug("[INIT] RLS cleanup skipped (RLS not installed or already cleaned)");
49363
+ }
49364
+ }
48660
49365
  await new Promise((resolve2) => setTimeout(resolve2, 500));
48661
49366
  logger33.info("[INIT] Ensuring default server exists...");
48662
49367
  await this.ensureDefaultServer();
@@ -48667,6 +49372,7 @@ class AgentServer {
48667
49372
  this.elizaOS = new ElizaOS3;
48668
49373
  this.elizaOS.enableEditableMode();
48669
49374
  setGlobalElizaOS(this.elizaOS);
49375
+ setGlobalAgentServer(this);
48670
49376
  logger33.success("[INIT] ElizaOS initialized");
48671
49377
  await this.initializeServer(config3);
48672
49378
  await new Promise((resolve2) => setTimeout(resolve2, 250));
@@ -48679,36 +49385,42 @@ class AgentServer {
48679
49385
  }
48680
49386
  async ensureDefaultServer() {
48681
49387
  try {
48682
- logger33.info("[AgentServer] Checking for default server...");
49388
+ const rlsEnabled = process.env.ENABLE_RLS_ISOLATION === "true";
49389
+ this.serverId = rlsEnabled && this.rlsOwnerId ? this.rlsOwnerId : "00000000-0000-0000-0000-000000000000";
49390
+ const serverName = rlsEnabled && this.rlsOwnerId ? `Server ${this.rlsOwnerId.substring(0, 8)}` : "Default Server";
49391
+ logger33.info(`[AgentServer] Checking for server ${this.serverId}...`);
48683
49392
  const servers = await this.database.getMessageServers();
48684
49393
  logger33.debug(`[AgentServer] Found ${servers.length} existing servers`);
48685
49394
  servers.forEach((s) => {
48686
49395
  logger33.debug(`[AgentServer] Existing server: ID=${s.id}, Name=${s.name}`);
48687
49396
  });
48688
- const defaultServer = servers.find((s) => s.id === "00000000-0000-0000-0000-000000000000");
49397
+ const defaultServer = servers.find((s) => s.id === this.serverId);
48689
49398
  if (!defaultServer) {
48690
- logger33.info("[AgentServer] Creating default server with UUID 00000000-0000-0000-0000-000000000000...");
49399
+ logger33.info(`[AgentServer] Creating server with UUID ${this.serverId}...`);
48691
49400
  try {
48692
- await this.database.db.execute(`
49401
+ const db = this.database.db;
49402
+ await db.execute(sql`
48693
49403
  INSERT INTO message_servers (id, name, source_type, created_at, updated_at)
48694
- VALUES ('00000000-0000-0000-0000-000000000000', 'Default Server', 'eliza_default', NOW(), NOW())
49404
+ VALUES (${this.serverId}, ${serverName}, ${"eliza_default"}, NOW(), NOW())
48695
49405
  ON CONFLICT (id) DO NOTHING
48696
49406
  `);
48697
- logger33.success("[AgentServer] Default server created via raw SQL");
48698
- const checkResult = await this.database.db.execute("SELECT id, name FROM message_servers WHERE id = '00000000-0000-0000-0000-000000000000'");
48699
- logger33.debug("[AgentServer] Raw SQL check result:", checkResult);
49407
+ logger33.success("[AgentServer] Server created via parameterized query");
49408
+ const checkResult = await db.execute(sql`
49409
+ SELECT id, name FROM message_servers WHERE id = ${this.serverId}
49410
+ `);
49411
+ logger33.debug("[AgentServer] Parameterized query check result:", checkResult);
48700
49412
  } catch (sqlError) {
48701
49413
  logger33.error("[AgentServer] Raw SQL insert failed:", sqlError);
48702
49414
  try {
48703
49415
  const server = await this.database.createMessageServer({
48704
- id: "00000000-0000-0000-0000-000000000000",
48705
- name: "Default Server",
49416
+ id: this.serverId,
49417
+ name: serverName,
48706
49418
  sourceType: "eliza_default"
48707
49419
  });
48708
- logger33.success("[AgentServer] Default server created via ORM with ID:", server.id);
49420
+ logger33.success("[AgentServer] Server created via ORM with ID:", server.id);
48709
49421
  } catch (ormError) {
48710
49422
  logger33.error("[AgentServer] Both SQL and ORM creation failed:", ormError);
48711
- throw new Error(`Failed to create default server: ${ormError.message}`);
49423
+ throw new Error(`Failed to create server: ${ormError.message}`);
48712
49424
  }
48713
49425
  }
48714
49426
  const verifyServers = await this.database.getMessageServers();
@@ -48716,14 +49428,14 @@ class AgentServer {
48716
49428
  verifyServers.forEach((s) => {
48717
49429
  logger33.debug(`[AgentServer] Server after creation: ID=${s.id}, Name=${s.name}`);
48718
49430
  });
48719
- const verifyDefault = verifyServers.find((s) => s.id === "00000000-0000-0000-0000-000000000000");
49431
+ const verifyDefault = verifyServers.find((s) => s.id === this.serverId);
48720
49432
  if (!verifyDefault) {
48721
- throw new Error(`Failed to create or verify default server with ID ${DEFAULT_SERVER_ID7}`);
49433
+ throw new Error(`Failed to create or verify server with ID ${this.serverId}`);
48722
49434
  } else {
48723
- logger33.success("[AgentServer] Default server creation verified successfully");
49435
+ logger33.success("[AgentServer] Server creation verified successfully");
48724
49436
  }
48725
49437
  } else {
48726
- logger33.info("[AgentServer] Default server already exists with ID:", defaultServer.id);
49438
+ logger33.info("[AgentServer] Server already exists with ID:", defaultServer.id);
48727
49439
  }
48728
49440
  } catch (error2) {
48729
49441
  logger33.error({ error: error2 }, "[AgentServer] Error ensuring default server:");
@@ -49030,8 +49742,8 @@ class AgentServer {
49030
49742
  const nvmPath = path8.join(os3.homedir(), ".nvm/versions/node");
49031
49743
  if (existsSync4(nvmPath)) {
49032
49744
  const versions = fs6.readdirSync(nvmPath);
49033
- for (const version of versions) {
49034
- const cliPath = path8.join(nvmPath, version, "lib/node_modules/@elizaos/server/dist/client");
49745
+ for (const version2 of versions) {
49746
+ const cliPath = path8.join(nvmPath, version2, "lib/node_modules/@elizaos/server/dist/client");
49035
49747
  if (existsSync4(path8.join(cliPath, "index.html"))) {
49036
49748
  return cliPath;
49037
49749
  }
@@ -49213,8 +49925,8 @@ class AgentServer {
49213
49925
  }
49214
49926
  }
49215
49927
  logger33.success(`Successfully registered agent ${runtime.character.name} (${runtime.agentId}) with core services.`);
49216
- await this.addAgentToServer(DEFAULT_SERVER_ID7, runtime.agentId);
49217
- logger33.info(`[AgentServer] Auto-associated agent ${runtime.character.name} with server ID: ${DEFAULT_SERVER_ID7}`);
49928
+ await this.addAgentToServer(this.serverId, runtime.agentId);
49929
+ logger33.info(`[AgentServer] Auto-associated agent ${runtime.character.name} with server ID: ${this.serverId}`);
49218
49930
  } catch (error2) {
49219
49931
  logger33.error({ error: error2 }, "Failed to register agent:");
49220
49932
  throw error2;
@@ -1,10 +1,16 @@
1
1
  import { Service, type Content, type IAgentRuntime, type Plugin, type UUID, ElizaOS } from '@elizaos/core';
2
2
  import type { MessageMetadata } from '@elizaos/api-client';
3
+ import type { AgentServer } from '../index.js';
3
4
  /**
4
5
  * Set the global ElizaOS instance
5
6
  * Should be called by AgentServer during initialization
6
7
  */
7
8
  export declare function setGlobalElizaOS(elizaOS: ElizaOS): void;
9
+ /**
10
+ * Set the global AgentServer instance
11
+ * Should be called by AgentServer during initialization
12
+ */
13
+ export declare function setGlobalAgentServer(agentServer: AgentServer): void;
8
14
  export interface MessageServiceMessage {
9
15
  id: UUID;
10
16
  channel_id: UUID;
@@ -27,6 +33,7 @@ export declare class MessageBusService extends Service {
27
33
  private boundHandleMessageDeleted;
28
34
  private boundHandleChannelCleared;
29
35
  private subscribedServers;
36
+ private serverInstance;
30
37
  constructor(runtime: IAgentRuntime);
31
38
  static start(runtime: IAgentRuntime): Promise<Service>;
32
39
  static stop(runtime: IAgentRuntime): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elizaos/server",
3
- "version": "1.6.4-alpha.15",
3
+ "version": "1.6.4-alpha.16",
4
4
  "description": "ElizaOS Server - Core server infrastructure for ElizaOS agents",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -44,7 +44,7 @@
44
44
  "dev": "bun run build.ts --watch"
45
45
  },
46
46
  "devDependencies": {
47
- "@elizaos/client": "1.6.4-alpha.15",
47
+ "@elizaos/client": "1.6.4-alpha.16",
48
48
  "@types/node": "^24.0.1",
49
49
  "prettier": "3.6.2",
50
50
  "tsx": "4.20.6",
@@ -52,10 +52,10 @@
52
52
  "which": "^5.0.0",
53
53
  "ws": "^8.18.0"
54
54
  },
55
- "gitHead": "5a15da1e9f38a2e91240a3d02213daffed6b60c7",
55
+ "gitHead": "23eb854811f3a84b324c0daea12adad45c5ae2b0",
56
56
  "dependencies": {
57
- "@elizaos/core": "1.6.4-alpha.15",
58
- "@elizaos/plugin-sql": "1.6.4-alpha.15",
57
+ "@elizaos/core": "1.6.4-alpha.16",
58
+ "@elizaos/plugin-sql": "1.6.4-alpha.16",
59
59
  "@sentry/node": "^10.16.0",
60
60
  "@types/express": "^5.0.2",
61
61
  "@types/helmet": "^4.0.0",