@elizaos/core 2.0.0-alpha.53 → 2.0.0-alpha.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/advanced-capabilities/actions/addContact.d.ts.map +1 -1
  2. package/dist/advanced-capabilities/actions/removeContact.d.ts.map +1 -1
  3. package/dist/advanced-capabilities/actions/scheduleFollowUp.d.ts.map +1 -1
  4. package/dist/advanced-capabilities/actions/searchContacts.d.ts.map +1 -1
  5. package/dist/advanced-capabilities/actions/updateContact.d.ts.map +1 -1
  6. package/dist/advanced-capabilities/evaluators/relationshipExtraction.d.ts.map +1 -1
  7. package/dist/advanced-capabilities/providers/contacts.d.ts.map +1 -1
  8. package/dist/advanced-capabilities/providers/followUps.d.ts.map +1 -1
  9. package/dist/advanced-memory/evaluators/long-term-extraction.d.ts.map +1 -1
  10. package/dist/advanced-memory/evaluators/summarization.d.ts.map +1 -1
  11. package/dist/autonomy/routes.d.ts.map +1 -1
  12. package/dist/basic-capabilities/index.d.ts.map +1 -1
  13. package/dist/browser/index.browser.js +372 -406
  14. package/dist/browser/index.browser.js.map +27 -30
  15. package/dist/connection.d.ts +44 -0
  16. package/dist/connection.d.ts.map +1 -0
  17. package/dist/edge/index.d.ts +2 -0
  18. package/dist/edge/index.edge.js +118444 -0
  19. package/dist/edge/index.edge.js.map +791 -0
  20. package/dist/index.node.d.ts +3 -0
  21. package/dist/index.node.d.ts.map +1 -1
  22. package/dist/logger.d.ts.map +1 -1
  23. package/dist/node/index.node.js +945 -1876
  24. package/dist/node/index.node.js.map +34 -35
  25. package/dist/packages/typescript/tsconfig.tsbuildinfo +1 -1
  26. package/dist/provisioning.d.ts +54 -0
  27. package/dist/provisioning.d.ts.map +1 -0
  28. package/dist/runtime-composition.d.ts +117 -0
  29. package/dist/runtime-composition.d.ts.map +1 -0
  30. package/dist/runtime.d.ts +94 -93
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/services/pairing-integration.d.ts +1 -1
  33. package/dist/services/pairing-integration.d.ts.map +1 -1
  34. package/dist/services/pairing-migration.d.ts.map +1 -1
  35. package/dist/services/task.d.ts +6 -3
  36. package/dist/services/task.d.ts.map +1 -1
  37. package/dist/settings.d.ts.map +1 -1
  38. package/dist/types/plugin.d.ts +14 -1
  39. package/dist/types/plugin.d.ts.map +1 -1
  40. package/dist/types/runtime.d.ts +12 -6
  41. package/dist/types/runtime.d.ts.map +1 -1
  42. package/dist/types/service.d.ts +4 -3
  43. package/dist/types/service.d.ts.map +1 -1
  44. package/package.json +4 -4
@@ -32304,11 +32304,15 @@ function sealAdze(base) {
32304
32304
  }
32305
32305
  if (raw && !metaBase.hostname) {
32306
32306
  let hostname = "unknown";
32307
- if (typeof process !== "undefined" && process.platform) {
32308
- const os = __require("node:os");
32309
- hostname = os.hostname();
32310
- } else if (typeof window !== "undefined" && window.location) {
32311
- hostname = window.location.hostname || "browser";
32307
+ try {
32308
+ if (typeof process !== "undefined" && process.platform) {
32309
+ const os = __require("node:os");
32310
+ hostname = os.hostname();
32311
+ } else if (typeof window !== "undefined" && window.location) {
32312
+ hostname = window.location.hostname || "browser";
32313
+ }
32314
+ } catch {
32315
+ hostname = "unknown";
32312
32316
  }
32313
32317
  metaBase.hostname = hostname;
32314
32318
  }
@@ -37331,7 +37335,7 @@ class Service {
37331
37335
  throw new Error("Service.start() must be implemented by subclass");
37332
37336
  }
37333
37337
  }
37334
- function getTypedService(runtime, serviceType) {
37338
+ async function getTypedService(runtime, serviceType) {
37335
37339
  return runtime.getService(serviceType);
37336
37340
  }
37337
37341
  function createServiceError(error, code = "UNKNOWN_ERROR") {
@@ -68504,7 +68508,7 @@ var init_long_term_extraction = __esm(() => {
68504
68508
  return false;
68505
68509
  if (!message2.content?.text)
68506
68510
  return false;
68507
- const memoryService = runtime2.getService("memory");
68511
+ const memoryService = await runtime2.getService("memory");
68508
68512
  if (!memoryService)
68509
68513
  return false;
68510
68514
  const config2 = memoryService.getConfig();
@@ -68520,7 +68524,7 @@ var init_long_term_extraction = __esm(() => {
68520
68524
  return memoryService.shouldRunExtraction(message2.entityId, message2.roomId, currentMessageCount);
68521
68525
  },
68522
68526
  handler: async (runtime2, message2) => {
68523
- const memoryService = runtime2.getService("memory");
68527
+ const memoryService = await runtime2.getService("memory");
68524
68528
  if (!memoryService) {
68525
68529
  logger.error({ src: "evaluator:memory" }, "MemoryService not found");
68526
68530
  return;
@@ -68644,7 +68648,7 @@ var init_summarization = __esm(() => {
68644
68648
  validate: async (runtime2, message2) => {
68645
68649
  if (!message2.content?.text)
68646
68650
  return false;
68647
- const memoryService = runtime2.getService("memory");
68651
+ const memoryService = await runtime2.getService("memory");
68648
68652
  if (!memoryService)
68649
68653
  return false;
68650
68654
  const config2 = memoryService.getConfig();
@@ -68657,7 +68661,7 @@ var init_summarization = __esm(() => {
68657
68661
  return newDialogueCount >= config2.shortTermSummarizationInterval;
68658
68662
  },
68659
68663
  handler: async (runtime2, message2) => {
68660
- const memoryService = runtime2.getService("memory");
68664
+ const memoryService = await runtime2.getService("memory");
68661
68665
  if (!memoryService) {
68662
68666
  logger.error({ src: "evaluator:memory" }, "MemoryService not found");
68663
68667
  return;
@@ -68785,7 +68789,7 @@ var init_context_summary = __esm(() => {
68785
68789
  position: 96,
68786
68790
  get: async (runtime2, message2, _state2) => {
68787
68791
  try {
68788
- const memoryService = runtime2.getService("memory");
68792
+ const memoryService = await runtime2.getService("memory");
68789
68793
  const { roomId } = message2;
68790
68794
  if (!memoryService) {
68791
68795
  return {
@@ -68847,7 +68851,7 @@ var init_long_term_memory = __esm(() => {
68847
68851
  position: 50,
68848
68852
  get: async (runtime2, message2, _state2) => {
68849
68853
  try {
68850
- const memoryService = runtime2.getService("memory");
68854
+ const memoryService = await runtime2.getService("memory");
68851
68855
  if (!memoryService) {
68852
68856
  return {
68853
68857
  data: { memoryCount: 0 },
@@ -68965,7 +68969,7 @@ var init_memory_service = __esm(() => {
68965
68969
  }
68966
68970
  async initialize(runtime2) {
68967
68971
  this.runtime = runtime2;
68968
- const provider = runtime2.getService("memoryStorage");
68972
+ const provider = await runtime2.getService("memoryStorage");
68969
68973
  if (!provider) {
68970
68974
  logger.warn({ src: "service:memory", agentId: runtime2.agentId }, "No MemoryStorageProvider found — long-term memory and session summaries disabled. " + "Register a memoryStorage service from your database plugin to enable them.");
68971
68975
  }
@@ -71622,7 +71626,7 @@ var sendToAdminAction = {
71622
71626
  ]
71623
71627
  ],
71624
71628
  validate: async (runtime2, message2) => {
71625
- const autonomyService = runtime2.getService(AUTONOMY_SERVICE_TYPE);
71629
+ const autonomyService = await runtime2.getService(AUTONOMY_SERVICE_TYPE);
71626
71630
  if (!autonomyService) {
71627
71631
  return false;
71628
71632
  }
@@ -71641,7 +71645,7 @@ var sendToAdminAction = {
71641
71645
  return ADMIN_KEYWORDS.some((keyword) => text.includes(keyword));
71642
71646
  },
71643
71647
  handler: async (runtime2, message2, _state2, _options, callback) => {
71644
- const autonomyService = runtime2.getService(AUTONOMY_SERVICE_TYPE);
71648
+ const autonomyService = await runtime2.getService(AUTONOMY_SERVICE_TYPE);
71645
71649
  if (!autonomyService) {
71646
71650
  return {
71647
71651
  success: false,
@@ -71734,7 +71738,7 @@ var adminChatProvider = {
71734
71738
  name: "ADMIN_CHAT_HISTORY",
71735
71739
  description: "Provides recent conversation history with the admin user for autonomous context",
71736
71740
  get: async (runtime2, message2, _state2) => {
71737
- const autonomyService = runtime2.getService(AUTONOMY_SERVICE_TYPE);
71741
+ const autonomyService = await runtime2.getService(AUTONOMY_SERVICE_TYPE);
71738
71742
  if (!autonomyService) {
71739
71743
  return { text: "", data: {} };
71740
71744
  }
@@ -71817,7 +71821,7 @@ var autonomyStatusProvider = {
71817
71821
  name: "AUTONOMY_STATUS",
71818
71822
  description: "Provides current autonomy status for agent awareness in conversations",
71819
71823
  get: async (runtime2, message2, _state2) => {
71820
- const autonomyService = runtime2.getService(AUTONOMY_SERVICE_TYPE);
71824
+ const autonomyService = await runtime2.getService(AUTONOMY_SERVICE_TYPE);
71821
71825
  if (!autonomyService) {
71822
71826
  return { text: "", data: {} };
71823
71827
  }
@@ -71858,15 +71862,15 @@ Thinking interval: ${intervalUnit}
71858
71862
  }
71859
71863
  };
71860
71864
  // src/autonomy/routes.ts
71861
- function getAutonomyService(runtime2) {
71862
- return runtime2.getService(AUTONOMY_SERVICE_TYPE) || runtime2.getService("autonomy");
71865
+ async function getAutonomyService(runtime2) {
71866
+ return await runtime2.getService(AUTONOMY_SERVICE_TYPE) || await runtime2.getService("autonomy");
71863
71867
  }
71864
71868
  var autonomyRoutes = [
71865
71869
  {
71866
71870
  path: "/autonomy/status",
71867
71871
  type: "GET",
71868
71872
  handler: async (_req, res, runtime2) => {
71869
- const autonomyService = getAutonomyService(runtime2);
71873
+ const autonomyService = await getAutonomyService(runtime2);
71870
71874
  if (!autonomyService) {
71871
71875
  res.status(503).json({
71872
71876
  error: "Autonomy service not available"
@@ -71892,7 +71896,7 @@ var autonomyRoutes = [
71892
71896
  path: "/autonomy/enable",
71893
71897
  type: "POST",
71894
71898
  handler: async (_req, res, runtime2) => {
71895
- const autonomyService = getAutonomyService(runtime2);
71899
+ const autonomyService = await getAutonomyService(runtime2);
71896
71900
  if (!autonomyService) {
71897
71901
  res.status(503).json({
71898
71902
  success: false,
@@ -71917,7 +71921,7 @@ var autonomyRoutes = [
71917
71921
  path: "/autonomy/disable",
71918
71922
  type: "POST",
71919
71923
  handler: async (_req, res, runtime2) => {
71920
- const autonomyService = getAutonomyService(runtime2);
71924
+ const autonomyService = await getAutonomyService(runtime2);
71921
71925
  if (!autonomyService) {
71922
71926
  res.status(503).json({
71923
71927
  success: false,
@@ -71942,7 +71946,7 @@ var autonomyRoutes = [
71942
71946
  path: "/autonomy/toggle",
71943
71947
  type: "POST",
71944
71948
  handler: async (_req, res, runtime2) => {
71945
- const autonomyService = getAutonomyService(runtime2);
71949
+ const autonomyService = await getAutonomyService(runtime2);
71946
71950
  if (!autonomyService) {
71947
71951
  res.status(503).json({
71948
71952
  success: false,
@@ -71972,7 +71976,7 @@ var autonomyRoutes = [
71972
71976
  path: "/autonomy/interval",
71973
71977
  type: "POST",
71974
71978
  handler: async (req, res, runtime2) => {
71975
- const autonomyService = getAutonomyService(runtime2);
71979
+ const autonomyService = await getAutonomyService(runtime2);
71976
71980
  if (!autonomyService) {
71977
71981
  res.status(503).json({
71978
71982
  success: false,
@@ -72823,7 +72827,7 @@ class TaskService extends Service {
72823
72827
  };
72824
72828
  }
72825
72829
  static async stop(runtime2) {
72826
- const service3 = runtime2.getService(ServiceType2.TASK);
72830
+ const service3 = await runtime2.getService(ServiceType2.TASK);
72827
72831
  if (service3) {
72828
72832
  await service3.stop();
72829
72833
  }
@@ -75384,7 +75388,7 @@ var addContactAction = {
75384
75388
  similes: spec18.similes ? [...spec18.similes] : [],
75385
75389
  examples: spec18.examples ?? [],
75386
75390
  validate: async (runtime2, message2, _state2) => {
75387
- const rolodexService = runtime2.getService("rolodex");
75391
+ const rolodexService = await runtime2.getService("rolodex");
75388
75392
  if (!rolodexService) {
75389
75393
  logger.warn("[AddContact] RolodexService not available");
75390
75394
  return false;
@@ -75395,7 +75399,7 @@ var addContactAction = {
75395
75399
  return ADD_KEYWORDS.some((keyword) => messageText.includes(keyword));
75396
75400
  },
75397
75401
  handler: async (runtime2, message2, state2, _options, callback) => {
75398
- const rolodexService = runtime2.getService("rolodex");
75402
+ const rolodexService = await runtime2.getService("rolodex");
75399
75403
  if (!rolodexService) {
75400
75404
  throw new Error("RolodexService not available");
75401
75405
  }
@@ -75943,7 +75947,7 @@ var removeContactAction = {
75943
75947
  description: spec22.description,
75944
75948
  examples: spec22.examples ?? [],
75945
75949
  validate: async (runtime2, message2, _state2) => {
75946
- const hasService = !!runtime2.getService("rolodex");
75950
+ const hasService = !!await runtime2.getService("rolodex");
75947
75951
  const text = message2.content.text;
75948
75952
  if (!text)
75949
75953
  return false;
@@ -75952,7 +75956,7 @@ var removeContactAction = {
75952
75956
  },
75953
75957
  handler: async (runtime2, message2, state2, _options, callback) => {
75954
75958
  try {
75955
- const rolodexService = runtime2.getService("rolodex");
75959
+ const rolodexService = await runtime2.getService("rolodex");
75956
75960
  if (!rolodexService) {
75957
75961
  throw new Error("RolodexService not available");
75958
75962
  }
@@ -76304,8 +76308,8 @@ var scheduleFollowUpAction = {
76304
76308
  similes: spec24.similes ? [...spec24.similes] : [],
76305
76309
  examples: spec24.examples ?? [],
76306
76310
  validate: async (runtime2, message2, _state2) => {
76307
- const rolodexService = runtime2.getService("rolodex");
76308
- const followUpService = runtime2.getService("follow_up");
76311
+ const rolodexService = await runtime2.getService("rolodex");
76312
+ const followUpService = await runtime2.getService("follow_up");
76309
76313
  if (!rolodexService || !followUpService) {
76310
76314
  logger.warn("[ScheduleFollowUp] Required services not available");
76311
76315
  return false;
@@ -76316,8 +76320,8 @@ var scheduleFollowUpAction = {
76316
76320
  return FOLLOW_UP_KEYWORDS.some((keyword) => messageText.includes(keyword));
76317
76321
  },
76318
76322
  handler: async (runtime2, message2, state2, _options, callback) => {
76319
- const rolodexService = runtime2.getService("rolodex");
76320
- const followUpService = runtime2.getService("follow_up");
76323
+ const rolodexService = await runtime2.getService("rolodex");
76324
+ const followUpService = await runtime2.getService("follow_up");
76321
76325
  if (!rolodexService || !followUpService) {
76322
76326
  throw new Error("Required services not available");
76323
76327
  }
@@ -76427,7 +76431,7 @@ var searchContactsAction = {
76427
76431
  similes: spec25.similes ? [...spec25.similes] : [],
76428
76432
  examples: spec25.examples ?? [],
76429
76433
  validate: async (runtime2, message2, _state2) => {
76430
- const rolodexService = runtime2.getService("rolodex");
76434
+ const rolodexService = await runtime2.getService("rolodex");
76431
76435
  if (!rolodexService) {
76432
76436
  logger.warn("[SearchContacts] RolodexService not available");
76433
76437
  return false;
@@ -76438,7 +76442,7 @@ var searchContactsAction = {
76438
76442
  return SEARCH_KEYWORDS.some((keyword) => messageText.includes(keyword));
76439
76443
  },
76440
76444
  handler: async (runtime2, message2, state2, _options, callback) => {
76441
- const rolodexService = runtime2.getService("rolodex");
76445
+ const rolodexService = await runtime2.getService("rolodex");
76442
76446
  if (!rolodexService) {
76443
76447
  throw new Error("RolodexService not available");
76444
76448
  }
@@ -76812,7 +76816,7 @@ var sendMessageAction = {
76812
76816
  success: false
76813
76817
  };
76814
76818
  }
76815
- const service3 = runtime2.getService(source);
76819
+ const service3 = await runtime2.getService(source);
76816
76820
  const sendDirectMessage = service3?.sendDirectMessage;
76817
76821
  if (!sendDirectMessage) {
76818
76822
  await callback({
@@ -76908,7 +76912,7 @@ var sendMessageAction = {
76908
76912
  success: false
76909
76913
  };
76910
76914
  }
76911
- const service3 = runtime2.getService(source);
76915
+ const service3 = await runtime2.getService(source);
76912
76916
  const sendRoomMessage = service3?.sendRoomMessage;
76913
76917
  if (!sendRoomMessage) {
76914
76918
  await callback({
@@ -77441,10 +77445,11 @@ function isEncryptedV2(value) {
77441
77445
  }
77442
77446
  }
77443
77447
  function getSalt() {
77444
- const currentEnvSalt = typeof process !== "undefined" && process.env ? process.env.SECRET_SALT ?? "secretsalt" : getEnv3("SECRET_SALT", "secretsalt") || "secretsalt";
77445
- const nodeEnv = typeof process !== "undefined" && process.env ? "development".toLowerCase() : (getEnv3("NODE_ENV", "") || "").toLowerCase();
77448
+ getEnvironment().clearCache();
77449
+ const currentEnvSalt = getEnv3("SECRET_SALT", "secretsalt") || "secretsalt";
77450
+ const nodeEnv = (getEnv3("NODE_ENV", "") || "").toLowerCase();
77446
77451
  const isProduction = nodeEnv === "production";
77447
- const allowDefaultSaltRaw = typeof process !== "undefined" && process.env ? process.env.ELIZA_ALLOW_DEFAULT_SECRET_SALT ?? "" : getEnv3("ELIZA_ALLOW_DEFAULT_SECRET_SALT", "") || "";
77452
+ const allowDefaultSaltRaw = getEnv3("ELIZA_ALLOW_DEFAULT_SECRET_SALT", "") || "";
77448
77453
  const allowDefaultSalt = allowDefaultSaltRaw.toLowerCase() === "true";
77449
77454
  const now = Date.now();
77450
77455
  if (saltCache !== null) {
@@ -78653,7 +78658,7 @@ var updateContactAction = {
78653
78658
  description: spec30.description,
78654
78659
  examples: spec30.examples ?? [],
78655
78660
  validate: async (runtime2, message2, _state2) => {
78656
- const hasService = !!runtime2.getService("rolodex");
78661
+ const hasService = !!await runtime2.getService("rolodex");
78657
78662
  const text = message2.content.text;
78658
78663
  if (!text)
78659
78664
  return false;
@@ -78662,7 +78667,7 @@ var updateContactAction = {
78662
78667
  },
78663
78668
  handler: async (runtime2, message2, state2, _options, callback) => {
78664
78669
  try {
78665
- const rolodexService = runtime2.getService("rolodex");
78670
+ const rolodexService = await runtime2.getService("rolodex");
78666
78671
  if (!rolodexService) {
78667
78672
  throw new Error("RolodexService not available");
78668
78673
  }
@@ -79320,7 +79325,7 @@ var relationshipExtractionEvaluator = {
79320
79325
  return !!(message2.content?.text && message2.content.text.length > 0);
79321
79326
  },
79322
79327
  handler: async (runtime2, message2, _state2) => {
79323
- const rolodexService = runtime2.getService("rolodex");
79328
+ const rolodexService = await runtime2.getService("rolodex");
79324
79329
  if (!rolodexService) {
79325
79330
  logger.warn("[RelationshipExtraction] RolodexService not available");
79326
79331
  return;
@@ -79881,7 +79886,7 @@ var contactsProvider = {
79881
79886
  name: spec34.name,
79882
79887
  description: spec34.description,
79883
79888
  get: async (runtime2, _message, _state2) => {
79884
- const rolodexService = runtime2.getService("rolodex");
79889
+ const rolodexService = await runtime2.getService("rolodex");
79885
79890
  if (!rolodexService) {
79886
79891
  runtime2.logger.warn("[ContactsProvider] RolodexService not available");
79887
79892
  return { text: "", values: {}, data: {} };
@@ -80038,7 +80043,7 @@ var followUpsProvider = {
80038
80043
  name: spec36.name,
80039
80044
  description: spec36.description,
80040
80045
  get: async (runtime2, _message, _state2) => {
80041
- const followUpService = runtime2.getService("follow_up");
80046
+ const followUpService = await runtime2.getService("follow_up");
80042
80047
  if (!followUpService) {
80043
80048
  runtime2.logger.warn("[FollowUpsProvider] FollowUpService not available");
80044
80049
  return { text: "", values: {}, data: {} };
@@ -81236,7 +81241,7 @@ var controlMessageHandler = async ({
81236
81241
  const serviceNames = Array.from(runtime2.getAllServices().keys());
81237
81242
  const websocketServiceName = serviceNames.find((name) => name.toLowerCase().includes("websocket") || name.toLowerCase().includes("socket"));
81238
81243
  if (websocketServiceName) {
81239
- const websocketService = runtime2.getService(websocketServiceName);
81244
+ const websocketService = await runtime2.getService(websocketServiceName);
81240
81245
  if (websocketService && "sendMessage" in websocketService) {
81241
81246
  await websocketService.sendMessage({
81242
81247
  type: "controlMessage",
@@ -81344,7 +81349,7 @@ var events2 = {
81344
81349
  async (payload) => {
81345
81350
  const payloadContent = payload.content;
81346
81351
  if (payloadContent && payloadContent.source === "client_chat") {
81347
- const messageBusService = payload.runtime.getService("message-bus-service");
81352
+ const messageBusService = await payload.runtime.getService("message-bus-service");
81348
81353
  if (messageBusService?.notifyActionStart) {
81349
81354
  await messageBusService.notifyActionStart(payload.roomId, payload.world, payload.content, payload.messageId);
81350
81355
  }
@@ -81382,7 +81387,7 @@ var events2 = {
81382
81387
  async (payload) => {
81383
81388
  const payloadContent = payload.content;
81384
81389
  if (payloadContent && payloadContent.source === "client_chat") {
81385
- const messageBusService = payload.runtime.getService("message-bus-service");
81390
+ const messageBusService = await payload.runtime.getService("message-bus-service");
81386
81391
  if (messageBusService?.notifyActionUpdate) {
81387
81392
  await messageBusService.notifyActionUpdate(payload.roomId, payload.world, payload.content, payload.messageId);
81388
81393
  }
@@ -82263,6 +82268,126 @@ async function saveCharacter(character, filePath) {
82263
82268
  });
82264
82269
  logger.info(`Character saved to ${characterPath}`);
82265
82270
  }
82271
+ // src/connection.ts
82272
+ init_types5();
82273
+ init_utils5();
82274
+ function resolveWorldId(worldId, messageServerId, agentId) {
82275
+ if (worldId)
82276
+ return worldId;
82277
+ if (messageServerId)
82278
+ return stringToUuid(`${messageServerId}:${agentId}`);
82279
+ throw new Error("worldId or messageServerId is required");
82280
+ }
82281
+ async function ensureConnections(adapter2, params) {
82282
+ const { agentId, connections } = params;
82283
+ if (!connections.length)
82284
+ return;
82285
+ const entityMap = new Map;
82286
+ const worldMap = new Map;
82287
+ const roomMap = new Map;
82288
+ const roomParticipants = new Map;
82289
+ for (const c of connections) {
82290
+ const worldId = resolveWorldId(c.worldId, c.messageServerId, agentId);
82291
+ const names4 = [c.name, c.userName].filter(Boolean);
82292
+ const source = c.source || "default";
82293
+ const entityKey = c.entityId;
82294
+ if (!entityMap.has(entityKey)) {
82295
+ entityMap.set(entityKey, {
82296
+ entityId: c.entityId,
82297
+ names: [],
82298
+ metadata: {},
82299
+ agentId
82300
+ });
82301
+ }
82302
+ const ent = entityMap.get(entityKey);
82303
+ if (!ent) {
82304
+ continue;
82305
+ }
82306
+ ent.names = [...new Set([...ent.names, ...names4])].filter(Boolean);
82307
+ ent.metadata[source] = {
82308
+ id: c.userId,
82309
+ name: c.name,
82310
+ userName: c.userName
82311
+ };
82312
+ const world = {
82313
+ id: worldId,
82314
+ name: c.worldName ? c.worldName : c.messageServerId ? `World for server ${c.messageServerId}` : `World for room ${c.roomId}`,
82315
+ agentId,
82316
+ messageServerId: c.messageServerId,
82317
+ metadata: c.metadata
82318
+ };
82319
+ worldMap.set(worldId, world);
82320
+ const roomType = typeof c.type === "string" && Object.values(ChannelType).includes(c.type) ? c.type : ChannelType.DM;
82321
+ const room = {
82322
+ id: c.roomId,
82323
+ name: c.name || "default",
82324
+ source,
82325
+ type: roomType,
82326
+ channelId: c.channelId ?? c.roomId,
82327
+ messageServerId: c.messageServerId,
82328
+ worldId
82329
+ };
82330
+ roomMap.set(c.roomId, room);
82331
+ if (!roomParticipants.has(c.roomId)) {
82332
+ roomParticipants.set(c.roomId, new Set);
82333
+ }
82334
+ const participants = roomParticipants.get(c.roomId);
82335
+ if (!participants) {
82336
+ continue;
82337
+ }
82338
+ participants.add(c.entityId);
82339
+ participants.add(agentId);
82340
+ }
82341
+ const entityIds = [...entityMap.keys()];
82342
+ const existingEntities = entityIds.length > 0 ? await adapter2.getEntitiesByIds(entityIds) : [];
82343
+ const existingByKey = new Map(existingEntities.map((e) => [e.id, e]));
82344
+ const entities = [];
82345
+ for (const [, v] of entityMap) {
82346
+ const existing = existingByKey.get(v.entityId) ?? null;
82347
+ const names4 = existing ? [...new Set([...existing.names || [], ...v.names])].filter(Boolean) : v.names;
82348
+ const metadata = existing ? { ...existing.metadata, ...v.metadata } : v.metadata;
82349
+ entities.push({
82350
+ id: v.entityId,
82351
+ names: names4,
82352
+ metadata,
82353
+ agentId: v.agentId
82354
+ });
82355
+ }
82356
+ if (entities.length)
82357
+ await adapter2.upsertEntities(entities);
82358
+ const worlds = [...worldMap.values()].map((w) => ({
82359
+ ...w,
82360
+ agentId
82361
+ }));
82362
+ if (worlds.length)
82363
+ await adapter2.upsertWorlds(worlds);
82364
+ const rooms = [...roomMap.values()].map((r) => ({
82365
+ ...r,
82366
+ agentId
82367
+ }));
82368
+ if (rooms.length)
82369
+ await adapter2.upsertRooms(rooms);
82370
+ for (const [roomId, entityIdsSet] of roomParticipants) {
82371
+ const currentResult = await adapter2.getParticipantsForRooms([
82372
+ roomId
82373
+ ]);
82374
+ const current = currentResult[0]?.entityIds ?? [];
82375
+ const missing = [...entityIdsSet].filter((id) => !current.includes(id));
82376
+ if (missing.length) {
82377
+ await adapter2.createRoomParticipants(missing, roomId);
82378
+ }
82379
+ }
82380
+ }
82381
+ async function ensureConnection(adapter2, params) {
82382
+ if (!params.source) {
82383
+ throw new Error("Source is required for ensureConnection");
82384
+ }
82385
+ const worldId = resolveWorldId(params.worldId, params.messageServerId, params.agentId);
82386
+ await ensureConnections(adapter2, {
82387
+ agentId: params.agentId,
82388
+ connections: [{ ...params, worldId }]
82389
+ });
82390
+ }
82266
82391
  // src/database.ts
82267
82392
  class DatabaseAdapter {
82268
82393
  db;
@@ -91595,7 +91720,7 @@ var skillEligibilityProvider = {
91595
91720
  position: -5,
91596
91721
  dynamic: true,
91597
91722
  get: async (runtime2, _message, _state2) => {
91598
- const service3 = runtime2.getService("AGENT_SKILLS_SERVICE");
91723
+ const service3 = await runtime2.getService("AGENT_SKILLS_SERVICE");
91599
91724
  if (!service3) {
91600
91725
  return { text: "" };
91601
91726
  }
@@ -91697,7 +91822,7 @@ var skillEligibilityCompactProvider = {
91697
91822
  position: -5,
91698
91823
  dynamic: true,
91699
91824
  get: async (runtime2, _message, _state2) => {
91700
- const service3 = runtime2.getService("AGENT_SKILLS_SERVICE");
91825
+ const service3 = await runtime2.getService("AGENT_SKILLS_SERVICE");
91701
91826
  if (!service3) {
91702
91827
  return { text: "" };
91703
91828
  }
@@ -91729,6 +91854,152 @@ var skillEligibilityCompactProvider = {
91729
91854
  }
91730
91855
  }
91731
91856
  };
91857
+ // src/provisioning.ts
91858
+ init_logger();
91859
+ init_types5();
91860
+ var logger2 = createLogger({ namespace: "provisioning", level: "info" });
91861
+ async function runPluginMigrations(runtime2) {
91862
+ const adapter2 = runtime2.adapter;
91863
+ if (!adapter2) {
91864
+ logger2.warn({ src: "provisioning", agentId: runtime2.agentId }, "Database adapter not found, skipping plugin migrations");
91865
+ return;
91866
+ }
91867
+ if (typeof adapter2.runPluginMigrations !== "function") {
91868
+ logger2.warn({ src: "provisioning", agentId: runtime2.agentId }, "Database adapter does not support plugin migrations");
91869
+ return;
91870
+ }
91871
+ const pluginsWithSchemas = runtime2.plugins.filter((p) => p.schema).map((p) => {
91872
+ const schema2 = p.schema || {};
91873
+ const normalizedSchema = {};
91874
+ for (const [key, value] of Object.entries(schema2)) {
91875
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || typeof value === "object" && value !== null) {
91876
+ normalizedSchema[key] = value;
91877
+ }
91878
+ }
91879
+ return { name: p.name, schema: normalizedSchema };
91880
+ });
91881
+ if (pluginsWithSchemas.length === 0) {
91882
+ logger2.debug({ src: "provisioning", agentId: runtime2.agentId }, "No plugins with schemas, skipping migrations");
91883
+ return;
91884
+ }
91885
+ const isProduction = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
91886
+ const forceDestructive = typeof process !== "undefined" && process.env?.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS === "true";
91887
+ await adapter2.runPluginMigrations(pluginsWithSchemas, {
91888
+ verbose: !isProduction,
91889
+ force: forceDestructive,
91890
+ dryRun: false
91891
+ });
91892
+ logger2.debug({ src: "provisioning", agentId: runtime2.agentId }, "Plugin migrations completed");
91893
+ }
91894
+ async function ensureAgentInfrastructure(runtime2) {
91895
+ const adapter2 = runtime2.adapter;
91896
+ const agentId = runtime2.agentId;
91897
+ const character = runtime2.character;
91898
+ const existingAgent = await runtime2.ensureAgentExists({
91899
+ ...character,
91900
+ id: agentId
91901
+ });
91902
+ if (!existingAgent) {
91903
+ throw new Error(`Agent ${agentId} does not exist in database after ensureAgentExists call`);
91904
+ }
91905
+ const entities = await adapter2.getEntitiesByIds([agentId]);
91906
+ let agentEntity = entities[0] ?? null;
91907
+ if (!agentEntity) {
91908
+ await adapter2.createEntities([
91909
+ {
91910
+ id: agentId,
91911
+ names: [character.name ?? "Agent"],
91912
+ metadata: {},
91913
+ agentId: existingAgent.id ?? agentId
91914
+ }
91915
+ ]);
91916
+ const refetched = await adapter2.getEntitiesByIds([agentId]);
91917
+ agentEntity = refetched[0] ?? null;
91918
+ if (!agentEntity) {
91919
+ throw new Error(`Agent entity not found for ${agentId}`);
91920
+ }
91921
+ }
91922
+ const rooms = await adapter2.getRoomsByIds([agentId]);
91923
+ if (rooms.length === 0) {
91924
+ await adapter2.createRooms([
91925
+ {
91926
+ id: agentId,
91927
+ name: character.name ?? "Agent",
91928
+ source: "elizaos",
91929
+ type: ChannelType.SELF,
91930
+ channelId: agentId,
91931
+ messageServerId: agentId,
91932
+ worldId: agentId
91933
+ }
91934
+ ]);
91935
+ }
91936
+ const participantResults = await adapter2.getParticipantsForRooms([agentId]);
91937
+ const participants = participantResults[0]?.entityIds ?? [];
91938
+ if (!participants.includes(agentId)) {
91939
+ await adapter2.createRoomParticipants([agentId], agentId);
91940
+ }
91941
+ }
91942
+ async function ensureEmbeddingDimension(runtime2) {
91943
+ const adapter2 = runtime2.adapter;
91944
+ const model2 = runtime2.getModel("TEXT_EMBEDDING");
91945
+ if (!model2) {
91946
+ logger2.debug({ src: "provisioning", agentId: runtime2.agentId }, "No TEXT_EMBEDDING model registered, skipping embedding dimension");
91947
+ return;
91948
+ }
91949
+ const raw2 = runtime2.getSetting("EMBEDDING_DIMENSION");
91950
+ const dimension = typeof raw2 === "number" ? raw2 : typeof raw2 === "string" ? parseInt(raw2, 10) : NaN;
91951
+ if (!Number.isFinite(dimension) || dimension <= 0) {
91952
+ logger2.debug({ src: "provisioning", agentId: runtime2.agentId }, "EMBEDDING_DIMENSION not set or invalid, skipping (set it in character settings to avoid LLM detection)");
91953
+ return;
91954
+ }
91955
+ await adapter2.ensureEmbeddingDimension(dimension);
91956
+ logger2.debug({ src: "provisioning", agentId: runtime2.agentId, dimension }, "Embedding dimension set");
91957
+ }
91958
+ async function provisionAgent(runtime2, options = {}) {
91959
+ const { runMigrations = true } = options;
91960
+ if (runMigrations) {
91961
+ await runPluginMigrations(runtime2);
91962
+ }
91963
+ await ensureAgentInfrastructure(runtime2);
91964
+ await ensureEmbeddingDimension(runtime2);
91965
+ }
91966
+ async function mergeDbSettings(character, adapter2, agentId) {
91967
+ const agents = await adapter2.getAgentsByIds([agentId]);
91968
+ const existingAgent = agents[0] ?? null;
91969
+ if (!existingAgent || !existingAgent.settings) {
91970
+ return character;
91971
+ }
91972
+ const mergedSettings = {
91973
+ ...existingAgent.settings,
91974
+ ...character.settings
91975
+ };
91976
+ const dbSecrets = existingAgent.secrets && typeof existingAgent.secrets === "object" ? existingAgent.secrets : {};
91977
+ const dbSettingsSecrets = existingAgent.settings.secrets && typeof existingAgent.settings.secrets === "object" ? existingAgent.settings.secrets : {};
91978
+ const characterSecrets = character.secrets && typeof character.secrets === "object" ? character.secrets : {};
91979
+ const characterSettingsSecrets = character.settings?.secrets && typeof character.settings.secrets === "object" ? character.settings.secrets : {};
91980
+ const mergedSecrets = {
91981
+ ...dbSecrets,
91982
+ ...dbSettingsSecrets,
91983
+ ...characterSecrets,
91984
+ ...characterSettingsSecrets
91985
+ };
91986
+ if (Object.keys(mergedSecrets).length > 0) {
91987
+ const filtered = {};
91988
+ for (const [key, value] of Object.entries(mergedSecrets)) {
91989
+ if (value !== null && value !== undefined) {
91990
+ filtered[key] = String(value);
91991
+ }
91992
+ }
91993
+ if (Object.keys(filtered).length > 0) {
91994
+ mergedSettings.secrets = filtered;
91995
+ }
91996
+ }
91997
+ return {
91998
+ ...character,
91999
+ settings: mergedSettings,
92000
+ secrets: Object.keys(mergedSecrets).length > 0 ? mergedSettings.secrets : character.secrets
92001
+ };
92002
+ }
91732
92003
 
91733
92004
  // src/index.node.ts
91734
92005
  init_roles();
@@ -91736,7 +92007,6 @@ init_roles();
91736
92007
  // src/runtime.ts
91737
92008
  init_dist_node();
91738
92009
  var import_handlebars2 = __toESM(require_lib(), 1);
91739
- init_entities();
91740
92010
  init_logger();
91741
92011
 
91742
92012
  // src/search.ts
@@ -94912,1228 +95182,7 @@ Output ONLY the continuation, starting immediately after the last character abov
94912
95182
  init_types5();
94913
95183
  init_utils5();
94914
95184
  init_environment();
94915
- // src/utils/prompt-batcher/batcher.ts
94916
- init_prompt_batcher();
94917
-
94918
- // src/utils/text-normalize.ts
94919
- function flattenTextValues(value) {
94920
- if (Array.isArray(value)) {
94921
- return value.flatMap((item) => flattenTextValues(item));
94922
- }
94923
- if (value == null) {
94924
- return [];
94925
- }
94926
- if (typeof value === "string") {
94927
- const trimmed = value.trim();
94928
- return trimmed ? [trimmed] : [];
94929
- }
94930
- if (typeof value === "object") {
94931
- return Object.entries(value).flatMap(([key, inner]) => {
94932
- const innerText = flattenTextValues(inner).join(", ");
94933
- return innerText ? [`${key}: ${innerText}`] : [];
94934
- });
94935
- }
94936
- return [String(value)];
94937
- }
94938
- function toMultilineText(value) {
94939
- return flattenTextValues(value).join(`
94940
- `);
94941
- }
94942
-
94943
- // src/utils/prompt-batcher/shared.ts
94944
- class Semaphore {
94945
- permits;
94946
- queue = [];
94947
- constructor(count) {
94948
- this.permits = Math.max(1, count);
94949
- }
94950
- async acquire() {
94951
- if (this.permits > 0) {
94952
- this.permits -= 1;
94953
- return;
94954
- }
94955
- await new Promise((resolve) => {
94956
- this.queue.push(resolve);
94957
- });
94958
- }
94959
- release() {
94960
- this.permits += 1;
94961
- const next = this.queue.shift();
94962
- if (next && this.permits > 0) {
94963
- this.permits -= 1;
94964
- next();
94965
- }
94966
- }
94967
- }
94968
- function sanitizeIdentifier(value) {
94969
- const normalized = value.replace(/[^a-zA-Z0-9_]/g, "_");
94970
- if (/^[a-zA-Z_]/.test(normalized)) {
94971
- return normalized;
94972
- }
94973
- return `section_${normalized}`;
94974
- }
94975
- function clampRetryCount(value) {
94976
- if (typeof value !== "number" || Number.isNaN(value)) {
94977
- return 0;
94978
- }
94979
- return Math.max(0, Math.min(2, Math.floor(value)));
94980
- }
94981
- function createMinimalState(context) {
94982
- return {
94983
- text: context,
94984
- values: {
94985
- batcherContext: context
94986
- },
94987
- data: {}
94988
- };
94989
- }
94990
- function buildCharacterContext(runtime2) {
94991
- const topics = toMultilineText(runtime2.character.topics);
94992
- const bio = toMultilineText(runtime2.character.bio);
94993
- const style = toMultilineText(runtime2.character.style);
94994
- const knowledge2 = toMultilineText(runtime2.character.knowledge);
94995
- return [
94996
- `Agent Name: ${runtime2.character.name ?? "Unknown"}`,
94997
- bio ? `Bio:
94998
- ${bio}` : "",
94999
- style ? `Style:
95000
- ${style}` : "",
95001
- topics ? `Topics:
95002
- ${topics}` : "",
95003
- knowledge2 ? `Knowledge:
95004
- ${knowledge2}` : ""
95005
- ].filter(Boolean).join(`
95006
-
95007
- `);
95008
- }
95009
- function getSourceMessageId(message2) {
95010
- const metadata = message2.metadata ?? {};
95011
- const content = message2.content ?? {};
95012
- const discordId = metadata.discordMessageId;
95013
- if (typeof discordId === "string" && discordId) {
95014
- return `discord:${discordId}`;
95015
- }
95016
- const telegramId = content.messageId;
95017
- if (telegramId != null) {
95018
- return `telegram:${String(telegramId)}`;
95019
- }
95020
- const slack = metadata.slack;
95021
- if (slack && typeof slack === "object" && "messageTs" in slack) {
95022
- return `slack:${String(slack.messageTs)}`;
95023
- }
95024
- return `internal:${message2.id}`;
95025
- }
95026
- function pickFields(fields, schema2) {
95027
- const picked = {};
95028
- if (!fields) {
95029
- return picked;
95030
- }
95031
- for (const row of schema2) {
95032
- if (row.field in fields) {
95033
- picked[row.field] = fields[row.field];
95034
- }
95035
- }
95036
- return picked;
95037
- }
95038
- function hasMeaningfulSectionDrift(existing, incoming) {
95039
- const comparableExisting = {
95040
- frequency: existing.frequency,
95041
- providers: existing.providers,
95042
- preamble: existing.preamble,
95043
- schema: existing.schema,
95044
- priority: existing.priority,
95045
- model: existing.model,
95046
- affinityKey: existing.affinityKey
95047
- };
95048
- const comparableIncoming = {
95049
- frequency: incoming.frequency,
95050
- providers: incoming.providers,
95051
- preamble: incoming.preamble,
95052
- schema: incoming.schema,
95053
- priority: incoming.priority,
95054
- model: incoming.model,
95055
- affinityKey: incoming.affinityKey
95056
- };
95057
- return JSON.stringify(comparableExisting) !== JSON.stringify(comparableIncoming);
95058
- }
95059
- function rollingAverage(current, count, nextValue) {
95060
- if (count <= 1) {
95061
- return nextValue;
95062
- }
95063
- return current + (nextValue - current) / count;
95064
- }
95065
-
95066
- // src/utils/prompt-batcher/batcher.ts
95067
- class PromptBatcher {
95068
- runtime;
95069
- dispatcher;
95070
- settings;
95071
- sections = new Map;
95072
- pendingResults = new Map;
95073
- contextResolvers = new Map;
95074
- preCallbackHandlers = new Map;
95075
- messageBuffers = new Map;
95076
- processedMessageIds = new Set;
95077
- processedMessageOrder = [];
95078
- affinityLocks = new Map;
95079
- lastRunAt = new Map;
95080
- inMemoryCache = new Map;
95081
- stats = {
95082
- totalDrains: 0,
95083
- totalCalls: 0,
95084
- totalCacheHits: 0,
95085
- totalFallbacks: 0,
95086
- avgSectionsPerCall: 0,
95087
- avgDrainDurationMs: 0
95088
- };
95089
- enabled = false;
95090
- disposed = false;
95091
- affinityTaskIds = new Map;
95092
- constructor(runtime2, dispatcher, settings2) {
95093
- this.runtime = runtime2;
95094
- this.dispatcher = dispatcher;
95095
- this.settings = settings2;
95096
- this.runtime.initPromise.then(() => {
95097
- if (!this.disposed) {
95098
- this.enabled = true;
95099
- this.drain();
95100
- }
95101
- });
95102
- }
95103
- addSection(section) {
95104
- if (this.disposed) {
95105
- return Promise.reject(new BatcherDisposedError);
95106
- }
95107
- this._validateProviders(section.providers);
95108
- const existing = this.sections.get(section.id);
95109
- if (existing) {
95110
- if (hasMeaningfulSectionDrift(existing, section)) {
95111
- this.runtime.logger.warn({
95112
- src: "prompt-batcher",
95113
- agentId: this.runtime.agentId,
95114
- sectionId: section.id
95115
- }, "Duplicate prompt section ID registered with different configuration");
95116
- }
95117
- return Promise.resolve(null);
95118
- }
95119
- const normalized = {
95120
- ...section,
95121
- priority: section.priority ?? "normal",
95122
- model: section.model ?? "small",
95123
- isolated: section.isolated ?? false,
95124
- affinityKey: section.affinityKey ?? "default",
95125
- maxRetries: clampRetryCount(section.maxRetries)
95126
- };
95127
- this.sections.set(normalized.id, normalized);
95128
- const deferred = {};
95129
- const promise = new Promise((resolve, reject) => {
95130
- deferred.resolve = resolve;
95131
- deferred.reject = reject;
95132
- });
95133
- this.pendingResults.set(normalized.id, {
95134
- deferred,
95135
- resolved: false
95136
- });
95137
- this._ensureAffinityTask(normalized.affinityKey ?? "default");
95138
- if (this.enabled && (normalized.priority === "immediate" || normalized.frequency === "once" || normalized.frequency === "per-drain")) {
95139
- this.drainAffinityGroup(normalized.affinityKey ?? "default");
95140
- }
95141
- return promise;
95142
- }
95143
- removeSection(id) {
95144
- const section = this.sections.get(id);
95145
- const affinityKey = section?.affinityKey ?? "default";
95146
- this.sections.delete(id);
95147
- this.pendingResults.delete(id);
95148
- this.lastRunAt.delete(id);
95149
- if (this.getSectionCountForAffinity(affinityKey) === 0) {
95150
- this._removeAffinityTask(affinityKey);
95151
- } else {
95152
- this._syncAffinityTask(affinityKey);
95153
- }
95154
- }
95155
- registerContextResolver(slug, resolver) {
95156
- if (this.contextResolvers.has(slug)) {
95157
- this.runtime.logger.warn({
95158
- src: "prompt-batcher",
95159
- agentId: this.runtime.agentId,
95160
- slug
95161
- }, "Prompt batcher context resolver already registered; keeping first value");
95162
- return;
95163
- }
95164
- this.contextResolvers.set(slug, resolver);
95165
- }
95166
- registerPreCallbackHandler(handler2) {
95167
- if (this.preCallbackHandlers.has(handler2.id)) {
95168
- this.runtime.logger.warn({
95169
- src: "prompt-batcher",
95170
- agentId: this.runtime.agentId,
95171
- handlerId: handler2.id
95172
- }, "Prompt batcher pre-callback handler already registered");
95173
- return;
95174
- }
95175
- this.preCallbackHandlers.set(handler2.id, handler2);
95176
- }
95177
- getPreCallbackHandlers(actionName) {
95178
- return Array.from(this.preCallbackHandlers.values()).filter((handler2) => handler2.actionFilter.includes(actionName));
95179
- }
95180
- tick(message2) {
95181
- if (this.disposed)
95182
- return;
95183
- if (!message2)
95184
- return;
95185
- const sourceMessageId = getSourceMessageId(message2);
95186
- if (this.processedMessageIds.has(sourceMessageId))
95187
- return;
95188
- this.processedMessageIds.add(sourceMessageId);
95189
- this.processedMessageOrder.push(sourceMessageId);
95190
- if (this.processedMessageOrder.length > 1000) {
95191
- const oldest = this.processedMessageOrder.shift();
95192
- if (oldest)
95193
- this.processedMessageIds.delete(oldest);
95194
- }
95195
- this._pushMessage("default", message2);
95196
- this._pushMessage(`room:${String(message2.roomId)}`, message2);
95197
- this._pushMessage(`audit:${String(message2.roomId)}`, message2);
95198
- this._pushMessage("autonomy", message2);
95199
- const messageAffinities = [
95200
- "default",
95201
- `room:${String(message2.roomId)}`,
95202
- `audit:${String(message2.roomId)}`
95203
- ];
95204
- for (const affinityKey of messageAffinities) {
95205
- if (this._shouldDrainAffinity(affinityKey)) {
95206
- this.drainAffinityGroup(affinityKey);
95207
- }
95208
- }
95209
- }
95210
- _shouldDrainAffinity(affinityKey) {
95211
- if (!this.enabled)
95212
- return false;
95213
- const sections = Array.from(this.sections.values()).filter((s) => (s.affinityKey ?? "default") === affinityKey);
95214
- if (sections.some((s) => s.priority === "immediate"))
95215
- return true;
95216
- const buffer = this.messageBuffers.get(affinityKey) ?? [];
95217
- return buffer.length >= this.settings.batchSize;
95218
- }
95219
- async drain() {
95220
- if (this.disposed || !this.enabled) {
95221
- return;
95222
- }
95223
- const affinityKeys = this._getActiveAffinityKeys();
95224
- await Promise.allSettled(affinityKeys.map((affinityKey) => this.drainAffinityGroup(affinityKey)));
95225
- }
95226
- dispose() {
95227
- this.disposed = true;
95228
- if (typeof this.runtime.deleteTask === "function") {
95229
- for (const [, taskId] of this.affinityTaskIds) {
95230
- this.runtime.deleteTask(taskId).catch(() => {});
95231
- }
95232
- }
95233
- this.affinityTaskIds.clear();
95234
- for (const pending of this.pendingResults.values()) {
95235
- if (!pending.resolved) {
95236
- pending.resolved = true;
95237
- pending.deferred.reject(new BatcherDisposedError);
95238
- }
95239
- }
95240
- this.pendingResults.clear();
95241
- this.sections.clear();
95242
- this.messageBuffers.clear();
95243
- this.affinityLocks.clear();
95244
- }
95245
- invalidateCache(sectionId) {
95246
- const cacheKey = this._cacheKey(sectionId);
95247
- this.inMemoryCache.delete(cacheKey);
95248
- this.runtime.deleteCache(cacheKey);
95249
- }
95250
- invalidateAllCaches() {
95251
- for (const section of this.sections.values()) {
95252
- this.invalidateCache(section.id);
95253
- }
95254
- }
95255
- getStats() {
95256
- return { ...this.stats };
95257
- }
95258
- askOnce(id, opts) {
95259
- return this.addSection({
95260
- id,
95261
- frequency: "once",
95262
- priority: "background",
95263
- affinityKey: "init",
95264
- preamble: opts.preamble,
95265
- schema: opts.schema,
95266
- fallback: this._normalizeFallback(opts.fallback),
95267
- providers: opts.providers,
95268
- model: opts.model,
95269
- cacheTtlMs: opts.cacheTtlMs,
95270
- staleWhileRevalidate: opts.staleWhileRevalidate,
95271
- forceRegenerate: opts.forceRegenerate,
95272
- shouldRun: opts.shouldRun,
95273
- validate: opts.validate,
95274
- maxRetries: opts.maxRetries,
95275
- execOptions: opts.execOptions
95276
- }).then((result) => result?.fields ?? {});
95277
- }
95278
- onDrain(id, opts) {
95279
- return this.addSection({
95280
- id,
95281
- frequency: "per-drain",
95282
- priority: "normal",
95283
- affinityKey: opts.room ? `room:${opts.room}` : "default",
95284
- preamble: opts.preamble,
95285
- schema: opts.schema,
95286
- onResult: opts.onResult,
95287
- fallback: this._normalizeFallback(opts.fallback),
95288
- providers: opts.providers,
95289
- model: opts.model,
95290
- shouldRun: opts.shouldRun,
95291
- validate: opts.validate,
95292
- maxRetries: opts.maxRetries,
95293
- execOptions: opts.execOptions
95294
- });
95295
- }
95296
- think(id, opts) {
95297
- this.addSection({
95298
- id,
95299
- frequency: "recurring",
95300
- priority: "normal",
95301
- affinityKey: "autonomy",
95302
- contextBuilder: opts.contextBuilder,
95303
- preamble: opts.preamble,
95304
- schema: opts.schema,
95305
- onResult: opts.onResult,
95306
- fallback: this._normalizeFallback(opts.fallback),
95307
- minCycleMs: opts.minCycleMs,
95308
- model: opts.model,
95309
- shouldRun: opts.shouldRun,
95310
- validate: opts.validate,
95311
- maxRetries: opts.maxRetries,
95312
- execOptions: opts.execOptions
95313
- });
95314
- }
95315
- askNow(id, opts) {
95316
- return this.addSection({
95317
- id,
95318
- frequency: "once",
95319
- priority: "immediate",
95320
- affinityKey: opts.room ? `room:${opts.room}` : "default",
95321
- preamble: opts.preamble,
95322
- schema: opts.schema,
95323
- fallback: this._normalizeFallback(opts.fallback),
95324
- providers: opts.providers,
95325
- model: opts.model,
95326
- validate: opts.validate,
95327
- maxRetries: opts.maxRetries,
95328
- execOptions: opts.execOptions
95329
- }).then((result) => result?.fields ?? opts.fallback);
95330
- }
95331
- _pushMessage(key, message2) {
95332
- const buffer = this.messageBuffers.get(key) ?? [];
95333
- buffer.push(message2);
95334
- const maxBufferedMessages = Math.max(this.settings.batchSize * 4, 50);
95335
- if (buffer.length > maxBufferedMessages) {
95336
- buffer.splice(0, buffer.length - maxBufferedMessages);
95337
- }
95338
- this.messageBuffers.set(key, buffer);
95339
- }
95340
- _getActiveAffinityKeys() {
95341
- const keys2 = new Set;
95342
- for (const section of this.sections.values()) {
95343
- keys2.add(section.affinityKey ?? "default");
95344
- }
95345
- return Array.from(keys2);
95346
- }
95347
- getIdealTickInterval(affinityKey) {
95348
- const sections = Array.from(this.sections.values()).filter((s) => (s.affinityKey ?? "default") === affinityKey);
95349
- let minInterval = this.settings.maxDrainIntervalMs;
95350
- for (const section of sections) {
95351
- if (section.frequency === "recurring" && typeof section.minCycleMs === "number" && section.minCycleMs > 0) {
95352
- minInterval = Math.min(minInterval, section.minCycleMs);
95353
- }
95354
- }
95355
- return Math.min(minInterval, this.settings.maxDrainIntervalMs);
95356
- }
95357
- getSectionCountForAffinity(affinityKey) {
95358
- return Array.from(this.sections.values()).filter((s) => (s.affinityKey ?? "default") === affinityKey).length;
95359
- }
95360
- async _ensureAffinityTask(affinityKey) {
95361
- if (this.affinityTaskIds.has(affinityKey)) {
95362
- return;
95363
- }
95364
- if (typeof this.runtime.getTasksByName !== "function" || typeof this.runtime.createTask !== "function") {
95365
- return;
95366
- }
95367
- const existing = await this.runtime.getTasksByName("BATCHER_DRAIN");
95368
- const match2 = existing.find((t) => t.metadata?.affinityKey === affinityKey);
95369
- if (match2?.id) {
95370
- this.affinityTaskIds.set(affinityKey, match2.id);
95371
- return;
95372
- }
95373
- const interval = this.getIdealTickInterval(affinityKey);
95374
- const task2 = {
95375
- name: "BATCHER_DRAIN",
95376
- description: `Drain affinity group: ${affinityKey}`,
95377
- tags: ["queue", "repeat"],
95378
- metadata: {
95379
- affinityKey,
95380
- updateInterval: interval,
95381
- baseInterval: interval,
95382
- updatedAt: Date.now(),
95383
- maxFailures: -1
95384
- }
95385
- };
95386
- const id = await this.runtime.createTask(task2);
95387
- this.affinityTaskIds.set(affinityKey, id);
95388
- }
95389
- async _syncAffinityTask(affinityKey) {
95390
- const taskId = this.affinityTaskIds.get(affinityKey);
95391
- if (!taskId)
95392
- return;
95393
- if (typeof this.runtime.getTask !== "function" || typeof this.runtime.updateTask !== "function")
95394
- return;
95395
- const count = this.getSectionCountForAffinity(affinityKey);
95396
- if (count === 0) {
95397
- await this._removeAffinityTask(affinityKey);
95398
- return;
95399
- }
95400
- const task2 = await this.runtime.getTask(taskId);
95401
- if (!task2) {
95402
- this.affinityTaskIds.delete(affinityKey);
95403
- return;
95404
- }
95405
- const newInterval = this.getIdealTickInterval(affinityKey);
95406
- const current = task2.metadata?.updateInterval;
95407
- if (current !== newInterval) {
95408
- await this.runtime.updateTask(taskId, {
95409
- metadata: { ...task2.metadata, updateInterval: newInterval }
95410
- });
95411
- }
95412
- }
95413
- async _removeAffinityTask(affinityKey) {
95414
- const taskId = this.affinityTaskIds.get(affinityKey);
95415
- if (!taskId)
95416
- return;
95417
- if (typeof this.runtime.deleteTask !== "function") {
95418
- this.affinityTaskIds.delete(affinityKey);
95419
- return;
95420
- }
95421
- try {
95422
- await this.runtime.deleteTask(taskId);
95423
- } finally {
95424
- this.affinityTaskIds.delete(affinityKey);
95425
- }
95426
- }
95427
- async drainAffinityGroup(affinityKey) {
95428
- const existingLock = this.affinityLocks.get(affinityKey);
95429
- if (existingLock) {
95430
- await existingLock;
95431
- }
95432
- let release;
95433
- const lock = new Promise((resolve) => {
95434
- release = resolve;
95435
- });
95436
- this.affinityLocks.set(affinityKey, lock);
95437
- try {
95438
- await this._drainAffinityGroupUnlocked(affinityKey);
95439
- } finally {
95440
- release();
95441
- this.affinityLocks.delete(affinityKey);
95442
- }
95443
- }
95444
- async _drainAffinityGroupUnlocked(affinityKey) {
95445
- if (this.disposed || !this.enabled) {
95446
- return;
95447
- }
95448
- const drainStartedAt = Date.now();
95449
- const sections = Array.from(this.sections.values()).filter((section) => (section.affinityKey ?? "default") === affinityKey);
95450
- if (sections.length === 0) {
95451
- return;
95452
- }
95453
- const messages = this._getMessagesForAffinity(affinityKey);
95454
- const drainId = `${sanitizeIdentifier(affinityKey)}-${drainStartedAt}`;
95455
- const sectionsIncluded = [];
95456
- const sectionsSkipped = [];
95457
- const cacheHits = [];
95458
- const allCalls = [];
95459
- const firstPass = sections.filter((section) => !section.dependsOnEvaluators);
95460
- const secondPass = sections.filter((section) => section.dependsOnEvaluators);
95461
- allCalls.push(...await this._runDrainPass({
95462
- drainId,
95463
- affinityKey,
95464
- messages,
95465
- sections: firstPass,
95466
- sectionsIncluded,
95467
- sectionsSkipped,
95468
- cacheHits
95469
- }));
95470
- if (secondPass.length > 0) {
95471
- const secondPassMessages = this._getMessagesForAffinity(affinityKey);
95472
- allCalls.push(...await this._runDrainPass({
95473
- drainId,
95474
- affinityKey,
95475
- messages: secondPassMessages,
95476
- sections: secondPass,
95477
- sectionsIncluded,
95478
- sectionsSkipped,
95479
- cacheHits
95480
- }));
95481
- }
95482
- this.stats.totalDrains += 1;
95483
- this.stats.avgDrainDurationMs = rollingAverage(this.stats.avgDrainDurationMs, this.stats.totalDrains, Date.now() - drainStartedAt);
95484
- if (messages.length > 0) {
95485
- this.messageBuffers.set(affinityKey, []);
95486
- }
95487
- this._emitDrainLog({
95488
- drainId,
95489
- agentId: String(this.runtime.agentId),
95490
- affinityKey,
95491
- timestamp: drainStartedAt,
95492
- durationMs: Date.now() - drainStartedAt,
95493
- sectionsIncluded,
95494
- sectionsSkipped,
95495
- cacheHits,
95496
- callCount: allCalls.length,
95497
- calls: allCalls
95498
- });
95499
- }
95500
- async _runDrainPass(args) {
95501
- const resolverCache = new Map;
95502
- const active = [];
95503
- const now = Date.now();
95504
- for (const section of args.sections) {
95505
- if (section.frequency === "per-drain" && args.messages.length === 0) {
95506
- args.sectionsSkipped.push(section.id);
95507
- continue;
95508
- }
95509
- if (section.shouldRun) {
95510
- try {
95511
- const shouldRun = await section.shouldRun(this.runtime);
95512
- if (!shouldRun) {
95513
- args.sectionsSkipped.push(section.id);
95514
- continue;
95515
- }
95516
- } catch (error) {
95517
- this.runtime.logger.warn({
95518
- src: "prompt-batcher",
95519
- agentId: this.runtime.agentId,
95520
- sectionId: section.id,
95521
- error
95522
- }, "Prompt batcher shouldRun threw; skipping section");
95523
- args.sectionsSkipped.push(section.id);
95524
- continue;
95525
- }
95526
- }
95527
- const cacheState = await this._checkCache(section);
95528
- if (cacheState.hit && cacheState.fields) {
95529
- const validatedCached = this._runValidate(section, cacheState.fields);
95530
- if (validatedCached) {
95531
- this.stats.totalCacheHits += 1;
95532
- args.cacheHits.push(section.id);
95533
- await this._deliverSectionResult({
95534
- section,
95535
- fields: validatedCached,
95536
- meta: {
95537
- drainId: args.drainId,
95538
- timestamp: now,
95539
- messages: args.messages,
95540
- sectionId: section.id,
95541
- actualModel: section.model ?? "small",
95542
- durationMs: 0,
95543
- cacheHit: true,
95544
- staleRevalidation: cacheState.stale,
95545
- packedWith: [],
95546
- retryAttempt: 0,
95547
- fallbackUsed: false
95548
- },
95549
- removeOnceSection: !cacheState.stale
95550
- });
95551
- if (!cacheState.stale) {
95552
- continue;
95553
- }
95554
- } else {
95555
- this.invalidateCache(section.id);
95556
- }
95557
- }
95558
- const resolved = await this._resolveContext(section, args.messages, resolverCache);
95559
- if (!resolved) {
95560
- args.sectionsSkipped.push(section.id);
95561
- continue;
95562
- }
95563
- args.sectionsIncluded.push(section.id);
95564
- active.push(resolved);
95565
- }
95566
- if (active.length === 0) {
95567
- return [];
95568
- }
95569
- const outcome = await this.dispatcher.dispatch(active, this.runtime);
95570
- this.stats.totalCalls += outcome.calls.length;
95571
- this.stats.avgSectionsPerCall = rollingAverage(this.stats.avgSectionsPerCall, this.stats.totalCalls, outcome.calls.reduce((sum, call) => sum + call.sectionIds.length, 0) / Math.max(1, outcome.calls.length));
95572
- const retriedCallIds = new Set;
95573
- await Promise.allSettled(active.map(async (resolvedSection) => {
95574
- const baseMeta = this._metaForSection(resolvedSection, args.drainId, args.messages, outcome.calls);
95575
- const rawFields = outcome.results.get(resolvedSection.section.id);
95576
- if (!rawFields) {
95577
- const fallback2 = this._fallbackForSection(resolvedSection.section);
95578
- await this._deliverSectionResult({
95579
- section: resolvedSection.section,
95580
- fields: fallback2,
95581
- meta: { ...baseMeta, fallbackUsed: true },
95582
- removeOnceSection: true
95583
- });
95584
- return;
95585
- }
95586
- const validated = this._runValidate(resolvedSection.section, rawFields);
95587
- if (validated) {
95588
- await this._writeCache(resolvedSection.section, validated);
95589
- await this._deliverSectionResult({
95590
- section: resolvedSection.section,
95591
- fields: validated,
95592
- meta: baseMeta,
95593
- removeOnceSection: true
95594
- });
95595
- this.lastRunAt.set(resolvedSection.section.id, Date.now());
95596
- return;
95597
- }
95598
- const retryFields = await this._retrySection(resolvedSection, args.messages, 1, retriedCallIds);
95599
- if (retryFields) {
95600
- await this._writeCache(resolvedSection.section, retryFields);
95601
- await this._deliverSectionResult({
95602
- section: resolvedSection.section,
95603
- fields: retryFields,
95604
- meta: { ...baseMeta, retryAttempt: 1 },
95605
- removeOnceSection: true
95606
- });
95607
- this.lastRunAt.set(resolvedSection.section.id, Date.now());
95608
- return;
95609
- }
95610
- const fallback = this._fallbackForSection(resolvedSection.section);
95611
- await this._deliverSectionResult({
95612
- section: resolvedSection.section,
95613
- fields: fallback,
95614
- meta: { ...baseMeta, fallbackUsed: true },
95615
- removeOnceSection: true
95616
- });
95617
- }));
95618
- if (retriedCallIds.size > 0) {
95619
- outcome.calls.push({
95620
- model: "small",
95621
- sectionIds: Array.from(retriedCallIds),
95622
- estimatedTokens: 0,
95623
- durationMs: 0,
95624
- success: true,
95625
- retried: true,
95626
- fallbackUsed: []
95627
- });
95628
- }
95629
- return outcome.calls;
95630
- }
95631
- _metaForSection(section, drainId, messages, calls) {
95632
- const call = calls.find((item) => item.sectionIds.includes(section.section.id));
95633
- return {
95634
- drainId,
95635
- timestamp: Date.now(),
95636
- messages,
95637
- sectionId: section.section.id,
95638
- actualModel: call?.model ?? section.preferredModel,
95639
- durationMs: call?.durationMs ?? 0,
95640
- cacheHit: false,
95641
- staleRevalidation: false,
95642
- packedWith: (call?.sectionIds ?? []).filter((id) => id !== section.section.id),
95643
- retryAttempt: 0,
95644
- fallbackUsed: false
95645
- };
95646
- }
95647
- async _resolveContext(section, messages, resolverCache) {
95648
- const pieces = [];
95649
- const providers4 = section.providers ?? [];
95650
- const anchorMessage = messages[messages.length - 1];
95651
- if (providers4.length === 0) {
95652
- pieces.push(buildCharacterContext(this.runtime));
95653
- } else if (providers4.length === 1 && providers4[0] === "*") {
95654
- if (!anchorMessage) {
95655
- this.runtime.logger.warn({
95656
- src: "prompt-batcher",
95657
- agentId: this.runtime.agentId,
95658
- sectionId: section.id
95659
- }, "Prompt batcher section requires providers but no anchor message exists");
95660
- return null;
95661
- }
95662
- const state2 = await this.runtime.composeState(anchorMessage);
95663
- pieces.push(state2.text ?? "");
95664
- } else if (providers4.length > 0) {
95665
- if (!anchorMessage) {
95666
- this.runtime.logger.warn({
95667
- src: "prompt-batcher",
95668
- agentId: this.runtime.agentId,
95669
- sectionId: section.id
95670
- }, "Prompt batcher section requires selective providers but no anchor message exists");
95671
- return null;
95672
- }
95673
- const state2 = await this.runtime.composeState(anchorMessage, providers4, true);
95674
- pieces.push(state2.text ?? "");
95675
- }
95676
- if (section.contextBuilder) {
95677
- try {
95678
- const built = await section.contextBuilder(this.runtime, messages);
95679
- if (built) {
95680
- pieces.push(String(built));
95681
- }
95682
- } catch (error) {
95683
- this.runtime.logger.warn({
95684
- src: "prompt-batcher",
95685
- agentId: this.runtime.agentId,
95686
- sectionId: section.id,
95687
- error
95688
- }, "Prompt batcher contextBuilder failed; using placeholder context");
95689
- pieces.push("[context unavailable]");
95690
- }
95691
- }
95692
- for (const slug of section.contextResolvers ?? []) {
95693
- let resolvedText = resolverCache.get(slug);
95694
- if (!resolvedText) {
95695
- const resolver = this.contextResolvers.get(slug);
95696
- if (!resolver) {
95697
- this.runtime.logger.warn({
95698
- src: "prompt-batcher",
95699
- agentId: this.runtime.agentId,
95700
- sectionId: section.id,
95701
- slug
95702
- }, "Prompt batcher context resolver not found");
95703
- continue;
95704
- }
95705
- try {
95706
- resolvedText = String(await resolver(this.runtime, messages));
95707
- } catch (error) {
95708
- this.runtime.logger.warn({
95709
- src: "prompt-batcher",
95710
- agentId: this.runtime.agentId,
95711
- sectionId: section.id,
95712
- slug,
95713
- error
95714
- }, "Prompt batcher context resolver failed; using placeholder context");
95715
- resolvedText = "[context unavailable]";
95716
- }
95717
- resolverCache.set(slug, resolvedText);
95718
- }
95719
- if (resolvedText) {
95720
- pieces.push(resolvedText);
95721
- }
95722
- }
95723
- if ((section.providers == null || section.providers.length === 0) && Array.from(this.sections.values()).some((other) => other.id !== section.id && (other.affinityKey ?? "default") === (section.affinityKey ?? "default") && other.providers?.includes("*"))) {
95724
- this.runtime.logger.warn({
95725
- src: "prompt-batcher",
95726
- agentId: this.runtime.agentId,
95727
- sectionId: section.id,
95728
- affinityKey: section.affinityKey ?? "default"
95729
- }, "Prompt batcher affinity group mixes cheap and full-provider sections; consider separate affinity keys");
95730
- }
95731
- const resolvedContext = pieces.filter(Boolean).join(`
95732
-
95733
- `);
95734
- const schemaFieldCount = section.schema.length;
95735
- const estimatedTokens = Math.ceil((resolvedContext.length + JSON.stringify(section.schema).length) / 4);
95736
- return {
95737
- section,
95738
- resolvedContext,
95739
- contextCharCount: resolvedContext.length,
95740
- schemaFieldCount,
95741
- estimatedTokens,
95742
- priority: section.priority ?? "normal",
95743
- preferredModel: section.model ?? "small",
95744
- isolated: section.isolated ?? false,
95745
- affinityKey: section.affinityKey ?? "default",
95746
- execOptions: section.execOptions
95747
- };
95748
- }
95749
- _getMessagesForAffinity(affinityKey) {
95750
- return [...this.messageBuffers.get(affinityKey) ?? []];
95751
- }
95752
- async _deliverSectionResult(args) {
95753
- if (args.meta.fallbackUsed) {
95754
- this.stats.totalFallbacks += 1;
95755
- }
95756
- const pending = this.pendingResults.get(args.section.id);
95757
- if (!this.disposed && args.section.onResult) {
95758
- try {
95759
- await args.section.onResult(args.fields, args.meta);
95760
- } catch (error) {
95761
- this.runtime.logger.warn({
95762
- src: "prompt-batcher",
95763
- agentId: this.runtime.agentId,
95764
- sectionId: args.section.id,
95765
- error
95766
- }, "Prompt batcher onResult failed");
95767
- if (pending && !pending.resolved) {
95768
- pending.resolved = true;
95769
- pending.deferred.reject(error);
95770
- }
95771
- if (args.removeOnceSection && args.section.frequency === "once") {
95772
- this.sections.delete(args.section.id);
95773
- this.pendingResults.delete(args.section.id);
95774
- }
95775
- return;
95776
- }
95777
- }
95778
- if (pending && !pending.resolved) {
95779
- pending.resolved = true;
95780
- pending.deferred.resolve({ fields: args.fields, meta: args.meta });
95781
- }
95782
- if (args.removeOnceSection && args.section.frequency === "once") {
95783
- this.sections.delete(args.section.id);
95784
- this.pendingResults.delete(args.section.id);
95785
- }
95786
- }
95787
- _fallbackForSection(section) {
95788
- return section.fallback?.() ?? {};
95789
- }
95790
- _normalizeFallback(fallback) {
95791
- if (!fallback) {
95792
- return;
95793
- }
95794
- return () => ({ ...fallback });
95795
- }
95796
- async _checkCache(section) {
95797
- if (!section.cacheTtlMs || section.forceRegenerate) {
95798
- return { hit: false, stale: false };
95799
- }
95800
- const key = this._cacheKey(section.id);
95801
- let entry = this.inMemoryCache.get(key);
95802
- if (!entry) {
95803
- const persisted = await this.runtime.getCache(key);
95804
- if (persisted?.fields && typeof persisted.expiresAt === "number") {
95805
- entry = persisted;
95806
- this.inMemoryCache.set(key, persisted);
95807
- }
95808
- }
95809
- if (!entry) {
95810
- return { hit: false, stale: false };
95811
- }
95812
- if (entry.expiresAt > Date.now()) {
95813
- return { hit: true, stale: false, fields: entry.fields };
95814
- }
95815
- if (section.staleWhileRevalidate) {
95816
- return { hit: true, stale: true, fields: entry.fields };
95817
- }
95818
- return { hit: false, stale: false };
95819
- }
95820
- async _writeCache(section, fields) {
95821
- if (!section.cacheTtlMs) {
95822
- return;
95823
- }
95824
- const entry = {
95825
- fields,
95826
- expiresAt: Date.now() + section.cacheTtlMs
95827
- };
95828
- const key = this._cacheKey(section.id);
95829
- this.inMemoryCache.set(key, entry);
95830
- await this.runtime.setCache(key, entry);
95831
- }
95832
- _runValidate(section, fields) {
95833
- if (!section.validate) {
95834
- return fields;
95835
- }
95836
- try {
95837
- return section.validate(fields);
95838
- } catch (error) {
95839
- this.runtime.logger.warn({
95840
- src: "prompt-batcher",
95841
- agentId: this.runtime.agentId,
95842
- sectionId: section.id,
95843
- error
95844
- }, "Prompt batcher validate threw");
95845
- return null;
95846
- }
95847
- }
95848
- async _retrySection(resolvedSection, messages, attempt, retriedCallIds) {
95849
- const maxRetries = clampRetryCount(resolvedSection.section.maxRetries);
95850
- if (attempt > maxRetries) {
95851
- return null;
95852
- }
95853
- retriedCallIds.add(resolvedSection.section.id);
95854
- const prompt2 = [
95855
- "Previous attempt was invalid. Try again.",
95856
- resolvedSection.section.preamble ?? "",
95857
- `Context:
95858
- ${resolvedSection.resolvedContext || "[context unavailable]"}`,
95859
- "Return only the requested structured fields."
95860
- ].filter(Boolean).join(`
95861
-
95862
- `);
95863
- const response = await this.runtime.dynamicPromptExecFromState({
95864
- state: createMinimalState(resolvedSection.resolvedContext),
95865
- params: {
95866
- prompt: prompt2,
95867
- ...resolvedSection.execOptions ?? {}
95868
- },
95869
- schema: resolvedSection.section.schema,
95870
- options: {
95871
- modelSize: resolvedSection.preferredModel
95872
- }
95873
- });
95874
- if (!response) {
95875
- return null;
95876
- }
95877
- const validated = this._runValidate(resolvedSection.section, response);
95878
- if (validated) {
95879
- return validated;
95880
- }
95881
- return this._retrySection(resolvedSection, messages, attempt + 1, retriedCallIds);
95882
- }
95883
- _emitDrainLog(log) {
95884
- this.runtime.logger.debug({
95885
- src: "prompt-batcher",
95886
- agentId: this.runtime.agentId,
95887
- drain: log
95888
- }, "Prompt batcher drain completed");
95889
- }
95890
- _cacheKey(sectionId) {
95891
- return `prompt-batcher:${String(this.runtime.agentId)}:${sectionId}`;
95892
- }
95893
- _validateProviders(providers4) {
95894
- if (!providers4 || providers4.length === 0 || providers4.length === 1 && providers4[0] === "*") {
95895
- return;
95896
- }
95897
- const knownProviders = new Set(this.runtime.providers.map((provider) => provider.name));
95898
- for (const provider of providers4) {
95899
- if (!knownProviders.has(provider)) {
95900
- this.runtime.logger.warn({
95901
- src: "prompt-batcher",
95902
- agentId: this.runtime.agentId,
95903
- provider
95904
- }, "Prompt batcher section references unknown provider");
95905
- }
95906
- }
95907
- }
95908
- }
95909
- // src/utils/prompt-batcher/dispatcher.ts
95910
- class PromptDispatcher {
95911
- settings;
95912
- constructor(settings2) {
95913
- this.settings = settings2;
95914
- }
95915
- async dispatch(resolved, runtime2) {
95916
- const results = new Map;
95917
- const calls = [];
95918
- const semaphore = new Semaphore(this.settings.maxParallelCalls);
95919
- const callPlans = this._buildCallPlans(resolved);
95920
- await Promise.all(callPlans.map(async (callPlan) => {
95921
- await semaphore.acquire();
95922
- const startedAt = Date.now();
95923
- try {
95924
- const prompt2 = this._buildPrompt(callPlan);
95925
- const schema2 = callPlan.sections.flatMap((resolvedSection) => {
95926
- const prefix = sanitizeIdentifier(resolvedSection.section.id);
95927
- return resolvedSection.section.schema.map((row) => ({
95928
- ...row,
95929
- field: `${prefix}__${row.field}`
95930
- }));
95931
- });
95932
- const mergedExecOptions = this._mergeExecOptions(callPlan.sections.map((item) => item.execOptions));
95933
- const state2 = createMinimalState(callPlan.sections.map((item) => `[${item.section.id}]
95934
- ${item.resolvedContext || "[context unavailable]"}`).join(`
95935
95185
 
95936
- `));
95937
- const modelSize = callPlan.model;
95938
- const response = await runtime2.dynamicPromptExecFromState({
95939
- state: state2,
95940
- params: {
95941
- prompt: prompt2,
95942
- ...mergedExecOptions
95943
- },
95944
- schema: schema2,
95945
- options: {
95946
- modelSize,
95947
- key: `prompt-batcher:${callPlan.sections.map((item) => item.section.id).join(",")}`
95948
- }
95949
- });
95950
- const durationMs = Date.now() - startedAt;
95951
- if (!response) {
95952
- calls.push({
95953
- model: modelSize,
95954
- sectionIds: callPlan.sections.map((item) => item.section.id),
95955
- estimatedTokens: callPlan.totalEstimatedTokens,
95956
- durationMs,
95957
- success: false,
95958
- retried: false,
95959
- fallbackUsed: callPlan.sections.map((item) => item.section.id)
95960
- });
95961
- return;
95962
- }
95963
- for (const section of callPlan.sections) {
95964
- const prefix = `${sanitizeIdentifier(section.section.id)}__`;
95965
- const stripped = {};
95966
- for (const [key, value] of Object.entries(response)) {
95967
- if (key.startsWith(prefix)) {
95968
- stripped[key.slice(prefix.length)] = value;
95969
- }
95970
- }
95971
- results.set(section.section.id, stripped);
95972
- }
95973
- calls.push({
95974
- model: modelSize,
95975
- sectionIds: callPlan.sections.map((item) => item.section.id),
95976
- estimatedTokens: callPlan.totalEstimatedTokens,
95977
- durationMs,
95978
- success: true,
95979
- retried: false,
95980
- fallbackUsed: []
95981
- });
95982
- } finally {
95983
- semaphore.release();
95984
- }
95985
- }));
95986
- return { results, calls };
95987
- }
95988
- _buildCallPlans(resolved) {
95989
- const affinityGroups = new Map;
95990
- for (const section of resolved) {
95991
- const group = affinityGroups.get(section.affinityKey) ?? [];
95992
- group.push(section);
95993
- affinityGroups.set(section.affinityKey, group);
95994
- }
95995
- const callPlans = [];
95996
- for (const sections of affinityGroups.values()) {
95997
- for (const priority of ["immediate", "normal", "background"]) {
95998
- const prioritized = sections.filter((section) => section.priority === priority);
95999
- if (prioritized.length === 0) {
96000
- continue;
96001
- }
96002
- for (const modelGroup of this._splitByModelPreference(prioritized)) {
96003
- const isolated = modelGroup.sections.filter((item) => item.isolated);
96004
- const packable = modelGroup.sections.filter((item) => !item.isolated).sort((a, b) => b.estimatedTokens - a.estimatedTokens);
96005
- for (const item of isolated) {
96006
- callPlans.push({
96007
- sections: [item],
96008
- model: modelGroup.model,
96009
- totalEstimatedTokens: item.estimatedTokens,
96010
- priority
96011
- });
96012
- }
96013
- const tokenLimit = this._packingTokenLimit(priority);
96014
- let current = [];
96015
- let tokenCount = 0;
96016
- let fieldCount = 0;
96017
- for (const item of packable) {
96018
- const nextTokens = tokenCount + item.estimatedTokens;
96019
- const nextFieldCount = fieldCount + item.schemaFieldCount;
96020
- const exceedsTokens = nextTokens > tokenLimit;
96021
- const exceedsFields = nextFieldCount > this.settings.maxSectionsPerCall;
96022
- const exceedsPromptSafety = nextTokens > 8192;
96023
- if (current.length > 0 && (exceedsTokens || exceedsFields || exceedsPromptSafety)) {
96024
- callPlans.push({
96025
- sections: current,
96026
- model: modelGroup.model,
96027
- totalEstimatedTokens: tokenCount,
96028
- priority
96029
- });
96030
- current = [];
96031
- tokenCount = 0;
96032
- fieldCount = 0;
96033
- }
96034
- current.push(item);
96035
- tokenCount += item.estimatedTokens;
96036
- fieldCount += item.schemaFieldCount;
96037
- }
96038
- if (current.length > 0) {
96039
- callPlans.push({
96040
- sections: current,
96041
- model: modelGroup.model,
96042
- totalEstimatedTokens: tokenCount,
96043
- priority
96044
- });
96045
- }
96046
- }
96047
- }
96048
- }
96049
- return callPlans.sort((a, b) => this._priorityRank(a.priority) - this._priorityRank(b.priority));
96050
- }
96051
- _splitByModelPreference(sections) {
96052
- const small = sections.filter((section) => section.preferredModel === "small");
96053
- const large = sections.filter((section) => section.preferredModel === "large");
96054
- if (small.length === 0) {
96055
- return [{ model: "large", sections: large }];
96056
- }
96057
- if (large.length === 0) {
96058
- return [{ model: "small", sections: small }];
96059
- }
96060
- const normalizedSeparation = Math.max(0, Math.min(1, this.settings.modelSeparation));
96061
- const total = small.length + large.length;
96062
- const smallRatio = small.length / total;
96063
- const promoteSmallIntoLarge = smallRatio < 1 - normalizedSeparation;
96064
- if (promoteSmallIntoLarge) {
96065
- return [
96066
- {
96067
- model: "large",
96068
- sections: [...large, ...small]
96069
- }
96070
- ];
96071
- }
96072
- return [
96073
- { model: "large", sections: large },
96074
- { model: "small", sections: small }
96075
- ];
96076
- }
96077
- _packingTokenLimit(priority) {
96078
- const density = Math.max(0, Math.min(1, this.settings.packingDensity));
96079
- const densityFloor = 0.35 + density * 0.65;
96080
- const priorityMultiplier = priority === "immediate" ? 0.65 : priority === "normal" ? 0.85 : 1;
96081
- return Math.max(512, Math.floor(this.settings.maxTokensPerCall * densityFloor * priorityMultiplier));
96082
- }
96083
- _priorityRank(priority) {
96084
- return priority === "immediate" ? 0 : priority === "normal" ? 1 : 2;
96085
- }
96086
- _buildPrompt(callPlan) {
96087
- const sectionBlocks = callPlan.sections.map((resolvedSection, index) => {
96088
- const fieldList = resolvedSection.section.schema.map((row) => {
96089
- const prefix = sanitizeIdentifier(resolvedSection.section.id);
96090
- const namespacedField = `${prefix}__${row.field}`;
96091
- return `- ${namespacedField}: ${row.description}${row.required ? " (required)" : ""}`;
96092
- }).join(`
96093
- `);
96094
- return [
96095
- `SECTION ${index + 1}: ${resolvedSection.section.id}`,
96096
- resolvedSection.section.preamble ? `Instructions:
96097
- ${resolvedSection.section.preamble}` : "",
96098
- `Context:
96099
- ${resolvedSection.resolvedContext || "[context unavailable]"}`,
96100
- `Output fields for this section:
96101
- ${fieldList}`
96102
- ].filter(Boolean).join(`
96103
-
96104
- `);
96105
- });
96106
- return [
96107
- "You are answering multiple independent structured sections in one response.",
96108
- "Read each section carefully.",
96109
- "Use only the context provided for that section.",
96110
- "Fill every requested field exactly once.",
96111
- "Do not mix facts between sections.",
96112
- "",
96113
- sectionBlocks.join(`
96114
-
96115
- ====================
96116
-
96117
- `)
96118
- ].join(`
96119
- `);
96120
- }
96121
- _mergeExecOptions(options) {
96122
- const temperatures = options.map((item) => item?.temperature).filter((item) => typeof item === "number");
96123
- const maxTokens = options.map((item) => item?.maxTokens).filter((item) => typeof item === "number");
96124
- const stopSequences = new Set;
96125
- for (const option of options) {
96126
- for (const stop of option?.stopSequences ?? []) {
96127
- stopSequences.add(stop);
96128
- }
96129
- }
96130
- return {
96131
- temperature: temperatures.length > 0 ? Math.min(...temperatures) : undefined,
96132
- maxTokens: maxTokens.length > 0 ? Math.max(...maxTokens) : undefined,
96133
- stopSequences: stopSequences.size > 0 ? Array.from(stopSequences) : undefined
96134
- };
96135
- }
96136
- }
96137
95186
  // src/utils/type-guards.ts
96138
95187
  var NON_PLAIN_CONSTRUCTORS = new Set([
96139
95188
  Array,
@@ -96182,7 +95231,7 @@ function isPlainObject(value) {
96182
95231
  // src/runtime.ts
96183
95232
  var environmentSettings = {};
96184
95233
 
96185
- class Semaphore2 {
95234
+ class Semaphore {
96186
95235
  permits;
96187
95236
  waiting = [];
96188
95237
  constructor(count) {
@@ -96209,18 +95258,6 @@ class Semaphore2 {
96209
95258
  function isTextStreamResult(value) {
96210
95259
  return typeof value === "object" && value !== null && "textStream" in value && "text" in value && "usage" in value && "finishReason" in value;
96211
95260
  }
96212
- function parseNumberSetting(value, fallback) {
96213
- if (typeof value === "number" && Number.isFinite(value)) {
96214
- return value;
96215
- }
96216
- if (typeof value === "string") {
96217
- const parsed = Number(value);
96218
- if (Number.isFinite(parsed)) {
96219
- return parsed;
96220
- }
96221
- }
96222
- return fallback;
96223
- }
96224
95261
 
96225
95262
  class AgentRuntime {
96226
95263
  #conversationLength = 100;
@@ -96246,16 +95283,15 @@ class AgentRuntime {
96246
95283
  characterPlugins = [];
96247
95284
  capabilityOptions = {};
96248
95285
  actionPlanningOption;
96249
- cachedEmbeddingDimension;
96250
95286
  llmModeOption;
96251
95287
  checkShouldRespondOption;
96252
95288
  isAnonymousCharacter = false;
96253
95289
  logger;
96254
95290
  enableAutonomy;
96255
- serverless;
96256
95291
  settings;
96257
95292
  servicePromiseHandlers = new Map;
96258
95293
  servicePromises = new Map;
95294
+ startingServices = new Map;
96259
95295
  serviceRegistrationStatus = new Map;
96260
95296
  initPromise;
96261
95297
  initResolver;
@@ -96264,8 +95300,9 @@ class AgentRuntime {
96264
95300
  currentActionContext;
96265
95301
  maxWorkingMemoryEntries = 50;
96266
95302
  messageService = null;
96267
- promptBatcher;
96268
- constructor(opts = {}) {
95303
+ companionUrl;
95304
+ stopped = false;
95305
+ constructor(opts) {
96269
95306
  let character;
96270
95307
  if (opts.character) {
96271
95308
  character = opts.character;
@@ -96312,26 +95349,11 @@ class AgentRuntime {
96312
95349
  if (opts.adapter) {
96313
95350
  this.registerDatabaseAdapter(opts.adapter);
96314
95351
  }
95352
+ this.companionUrl = opts.companionUrl;
96315
95353
  this.fetch = opts.fetch ?? this.fetch;
96316
95354
  this.settings = opts.settings ?? environmentSettings;
96317
- this.promptBatcher = new PromptBatcher(this, new PromptDispatcher({
96318
- packingDensity: parseNumberSetting(this.getSetting("PROMPT_PACKING_DENSITY"), 0.5),
96319
- maxTokensPerCall: parseNumberSetting(this.getSetting("PROMPT_MAX_TOKENS_PER_CALL"), 4096),
96320
- maxParallelCalls: parseNumberSetting(this.getSetting("PROMPT_MAX_PARALLEL_CALLS"), 3),
96321
- modelSeparation: parseNumberSetting(this.getSetting("PROMPT_MODEL_SEPARATION"), 0.7),
96322
- maxSectionsPerCall: parseNumberSetting(this.getSetting("PROMPT_MAX_SECTIONS_PER_CALL"), 30)
96323
- }), {
96324
- batchSize: parseNumberSetting(this.getSetting("PROMPT_BATCH_SIZE"), 10),
96325
- maxDrainIntervalMs: parseNumberSetting(this.getSetting("PROMPT_MAX_DRAIN_INTERVAL_MS"), 300000),
96326
- maxSectionsPerCall: parseNumberSetting(this.getSetting("PROMPT_MAX_SECTIONS_PER_CALL"), 30),
96327
- packingDensity: parseNumberSetting(this.getSetting("PROMPT_PACKING_DENSITY"), 0.5),
96328
- maxTokensPerCall: parseNumberSetting(this.getSetting("PROMPT_MAX_TOKENS_PER_CALL"), 4096),
96329
- maxParallelCalls: parseNumberSetting(this.getSetting("PROMPT_MAX_PARALLEL_CALLS"), 3),
96330
- modelSeparation: parseNumberSetting(this.getSetting("PROMPT_MODEL_SEPARATION"), 0.7)
96331
- });
96332
95355
  const enableAutonomyFromSettings = this.character.settings?.ENABLE_AUTONOMY === true || this.character.settings?.ENABLE_AUTONOMY === "true";
96333
95356
  this.enableAutonomy = opts.enableAutonomy ?? enableAutonomyFromSettings;
96334
- this.serverless = opts.serverless ?? false;
96335
95357
  this.plugins = [];
96336
95358
  this.characterPlugins = opts.plugins ?? [];
96337
95359
  this.actionPlanningOption = opts.actionPlanning;
@@ -96417,8 +95439,7 @@ class AgentRuntime {
96417
95439
  this.logger.debug({ src: "agent", agentId: this.agentId, plugin: pluginToRegister.name }, "Plugin initialized");
96418
95440
  }
96419
95441
  if (pluginToRegister.adapter) {
96420
- this.logger.debug({ src: "agent", agentId: this.agentId, plugin: pluginToRegister.name }, "Registering database adapter");
96421
- this.registerDatabaseAdapter(pluginToRegister.adapter);
95442
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: pluginToRegister.name }, "Plugin declares adapter factory (handled pre-construction)");
96422
95443
  }
96423
95444
  if (pluginToRegister.actions) {
96424
95445
  for (const action of pluginToRegister.actions) {
@@ -96458,14 +95479,6 @@ class AgentRuntime {
96458
95479
  }
96459
95480
  if (pluginToRegister.services) {
96460
95481
  for (const service3 of pluginToRegister.services) {
96461
- if (service3 == null) {
96462
- this.logger.warn({
96463
- src: "agent",
96464
- agentId: this.agentId,
96465
- plugin: pluginToRegister.name
96466
- }, "Plugin has null/undefined entry in services array, skipping");
96467
- continue;
96468
- }
96469
95482
  const serviceType = service3.serviceType;
96470
95483
  this.logger.debug({
96471
95484
  src: "agent",
@@ -96477,32 +95490,41 @@ class AgentRuntime {
96477
95490
  this._createServiceResolver(serviceType);
96478
95491
  }
96479
95492
  this.serviceRegistrationStatus.set(serviceType, "pending");
96480
- this.registerService(service3).catch((error) => {
96481
- this.logger.error({
96482
- src: "agent",
96483
- agentId: this.agentId,
96484
- plugin: pluginToRegister.name,
96485
- serviceType,
96486
- error: error instanceof Error ? error.message : String(error)
96487
- }, "Service registration failed");
96488
- const handler2 = this.servicePromiseHandlers.get(serviceType);
96489
- if (handler2) {
96490
- const serviceError = new Error(`Service ${serviceType} from plugin ${pluginToRegister.name} failed to register: ${error instanceof Error ? error.message : String(error)}`);
96491
- handler2.reject(serviceError);
96492
- this.servicePromiseHandlers.delete(serviceType);
96493
- this.servicePromises.delete(serviceType);
96494
- }
96495
- this.serviceRegistrationStatus.set(serviceType, "failed");
96496
- });
95493
+ if (!this.serviceTypes.has(serviceType)) {
95494
+ this.serviceTypes.set(serviceType, []);
95495
+ }
95496
+ const services = this.serviceTypes.get(serviceType);
95497
+ if (services) {
95498
+ services.push(service3);
95499
+ }
96497
95500
  }
96498
95501
  }
95502
+ if (pluginToRegister.adapter) {
95503
+ this.logger.debug({
95504
+ src: "agent",
95505
+ agentId: this.agentId,
95506
+ plugin: pluginToRegister.name
95507
+ }, "Registering database adapter");
95508
+ const bootstrapSettings = this.getBootstrapSettings();
95509
+ const adapter2 = await Promise.resolve(pluginToRegister.adapter(this.agentId, bootstrapSettings));
95510
+ this.registerDatabaseAdapter(adapter2);
95511
+ }
96499
95512
  }
96500
95513
  getAllServices() {
96501
95514
  return this.services;
96502
95515
  }
96503
95516
  async stop() {
95517
+ if (this.stopped) {
95518
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Runtime already stopped");
95519
+ return;
95520
+ }
95521
+ this.stopped = true;
96504
95522
  this.logger.debug({ src: "agent", agentId: this.agentId }, "Stopping runtime");
96505
- this.promptBatcher.dispose();
95523
+ const inFlight = Array.from(this.startingServices.values());
95524
+ if (inFlight.length > 0) {
95525
+ this.logger.debug({ src: "agent", agentId: this.agentId, count: inFlight.length }, "Waiting for in-flight service starts before stopping");
95526
+ await Promise.all(inFlight);
95527
+ }
96506
95528
  for (const [serviceType, services] of this.services) {
96507
95529
  this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Stopping service");
96508
95530
  for (const service3 of services) {
@@ -96514,6 +95536,20 @@ class AgentRuntime {
96514
95536
  }
96515
95537
  }
96516
95538
  }
95539
+ const stopError = new Error("Runtime stopped");
95540
+ for (const [serviceType, handler2] of this.servicePromiseHandlers) {
95541
+ handler2.reject(stopError);
95542
+ const promise = this.servicePromises.get(serviceType);
95543
+ if (promise) {
95544
+ promise.catch(() => {});
95545
+ }
95546
+ }
95547
+ this.eventHandlers.clear();
95548
+ this.events = {};
95549
+ this.stateCache.clear();
95550
+ this.servicePromises.clear();
95551
+ this.servicePromiseHandlers.clear();
95552
+ this.startingServices.clear();
96517
95553
  }
96518
95554
  async initialize(options) {
96519
95555
  const pluginRegistrationPromises = [];
@@ -96647,6 +95683,45 @@ class AgentRuntime {
96647
95683
  this.initResolver = undefined;
96648
95684
  }
96649
95685
  }
95686
+ getBootstrapSettings() {
95687
+ const out = {};
95688
+ for (const [key, value] of Object.entries(process.env)) {
95689
+ if (value !== undefined && value !== null && key) {
95690
+ out[key] = String(value);
95691
+ }
95692
+ }
95693
+ const settings2 = this.character.settings && typeof this.character.settings === "object" ? this.character.settings : {};
95694
+ for (const [key, value] of Object.entries(settings2)) {
95695
+ if (value === undefined || value === null) {
95696
+ continue;
95697
+ }
95698
+ if (key === "secrets" && typeof value === "object") {
95699
+ continue;
95700
+ }
95701
+ out[key] = typeof value === "string" ? value : String(value);
95702
+ }
95703
+ const secrets = this.character.settings?.secrets && typeof this.character.settings.secrets === "object" ? this.character.settings.secrets : {};
95704
+ for (const [key, value] of Object.entries(secrets)) {
95705
+ if (value !== undefined && value !== null) {
95706
+ out[key] = String(value);
95707
+ }
95708
+ }
95709
+ const topSecrets = this.character.secrets && typeof this.character.secrets === "object" ? this.character.secrets : {};
95710
+ for (const [key, value] of Object.entries(topSecrets)) {
95711
+ if (value !== undefined && value !== null) {
95712
+ out[key] = String(value);
95713
+ }
95714
+ }
95715
+ return out;
95716
+ }
95717
+ registerDatabaseAdapter(adapter2) {
95718
+ if (this.adapter) {
95719
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter already registered, ignoring");
95720
+ } else {
95721
+ this.adapter = adapter2;
95722
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Database adapter registered");
95723
+ }
95724
+ }
96650
95725
  async runPluginMigrations() {
96651
95726
  if (!this.adapter) {
96652
95727
  this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter not found, skipping plugin migrations");
@@ -96774,17 +95849,8 @@ class AgentRuntime {
96774
95849
  }
96775
95850
  return true;
96776
95851
  }
96777
- registerDatabaseAdapter(adapter2) {
96778
- if (this.adapter) {
96779
- this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter already registered, ignoring");
96780
- } else {
96781
- this.adapter = adapter2;
96782
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Database adapter registered");
96783
- }
96784
- }
96785
95852
  getMessagingAdapter() {
96786
- const adapter2 = this.adapter;
96787
- if (adapter2 && typeof adapter2.createMessageServer === "function" && typeof adapter2.createChannel === "function" && typeof adapter2.createMessage === "function") {
95853
+ if (this.adapter && typeof this.adapter.createMessageServer === "function" && typeof this.adapter.createChannel === "function" && typeof this.adapter.createMessage === "function") {
96788
95854
  return this.adapter;
96789
95855
  }
96790
95856
  return null;
@@ -96805,15 +95871,15 @@ class AgentRuntime {
96805
95871
  getAllActions() {
96806
95872
  return [...this.actions];
96807
95873
  }
96808
- getFilteredActions(context) {
96809
- const policyService = this.getService("tool_policy");
95874
+ async getFilteredActions(context) {
95875
+ const policyService = await this.getService("tool_policy");
96810
95876
  if (!policyService || !context) {
96811
95877
  return [...this.actions];
96812
95878
  }
96813
95879
  return policyService.filterActions(this.actions, context);
96814
95880
  }
96815
- isActionAllowed(actionName, context) {
96816
- const policyService = this.getService("tool_policy");
95881
+ async isActionAllowed(actionName, context) {
95882
+ const policyService = await this.getService("tool_policy");
96817
95883
  if (!policyService) {
96818
95884
  return { allowed: true, reason: "No policy service available" };
96819
95885
  }
@@ -96933,16 +95999,10 @@ class AgentRuntime {
96933
95999
  currentStep: actionIndex + 1
96934
96000
  });
96935
96001
  }
96936
- if (message2.id && accumulatedState) {
96937
- this.stateCache.set(message2.id, accumulatedState);
96938
- }
96939
- const freshProviderState = await this.composeState(message2, ["RECENT_MESSAGES", "ACTION_STATE"], true);
96940
- accumulatedState = {
96941
- ...accumulatedState,
96942
- ...freshProviderState,
96943
- values: { ...accumulatedState?.values, ...freshProviderState.values },
96944
- data: { ...accumulatedState?.data, ...freshProviderState.data }
96945
- };
96002
+ accumulatedState = await this.composeState(message2, [
96003
+ "RECENT_MESSAGES",
96004
+ "ACTION_STATE"
96005
+ ]);
96946
96006
  if (actionPlan && accumulatedState.data) {
96947
96007
  accumulatedState.data.actionPlan = actionPlan;
96948
96008
  accumulatedState.data.actionResults = actionResults;
@@ -97198,81 +96258,10 @@ class AgentRuntime {
97198
96258
  }
97199
96259
  });
97200
96260
  if (callback) {
97201
- for (let content of storedCallbackData) {
96261
+ for (const content of storedCallbackData) {
97202
96262
  if (content.text) {
97203
96263
  content.text = this.redactSecrets(content.text);
97204
96264
  }
97205
- const auditHandlers = this.promptBatcher.getPreCallbackHandlers(action.name);
97206
- if (auditHandlers.length > 0) {
97207
- let auditedContent = content;
97208
- const mergedSchema = auditHandlers.flatMap((handler2) => handler2.schema);
97209
- const mergedProviders = [
97210
- ...new Set(auditHandlers.flatMap((handler2) => handler2.providers ?? []))
97211
- ];
97212
- const mergedPreamble = auditHandlers.map((handler2) => `${handler2.preamble}
97213
-
97214
- Output to audit:
97215
- ${content.text ?? ""}`).join(`
97216
-
97217
- ---
97218
-
97219
- `);
97220
- const mergedStopSequences = new Set;
97221
- const mergedMaxTokens = [];
97222
- const mergedTemperatures = [];
97223
- for (const handler2 of auditHandlers) {
97224
- if (typeof handler2.execOptions?.maxTokens === "number") {
97225
- mergedMaxTokens.push(handler2.execOptions.maxTokens);
97226
- }
97227
- if (typeof handler2.execOptions?.temperature === "number") {
97228
- mergedTemperatures.push(handler2.execOptions.temperature);
97229
- }
97230
- for (const stopSequence of handler2.execOptions?.stopSequences ?? []) {
97231
- mergedStopSequences.add(stopSequence);
97232
- }
97233
- }
97234
- const addSectionResult = await this.promptBatcher.addSection({
97235
- id: `audit-${action.name}-${Date.now()}`,
97236
- frequency: "once",
97237
- priority: "immediate",
97238
- providers: mergedProviders.length > 0 ? mergedProviders : undefined,
97239
- preamble: mergedPreamble,
97240
- affinityKey: `audit:${message2.roomId}`,
97241
- schema: mergedSchema,
97242
- model: auditHandlers.some((handler2) => handler2.model === "large") ? "large" : "small",
97243
- execOptions: {
97244
- temperature: mergedTemperatures.length > 0 ? Math.min(...mergedTemperatures) : 0,
97245
- maxTokens: mergedMaxTokens.length > 0 ? Math.max(...mergedMaxTokens) : undefined,
97246
- stopSequences: mergedStopSequences.size > 0 ? Array.from(mergedStopSequences) : undefined
97247
- },
97248
- fallback: () => Object.assign({}, ...auditHandlers.map((handler2) => handler2.fallback?.() ?? {}))
97249
- });
97250
- const auditedFields = addSectionResult?.fields;
97251
- for (const handler2 of auditHandlers) {
97252
- const handlerFields = pickFields(auditedFields, handler2.schema);
97253
- const validatedFields = handler2.validate ? handler2.validate(handlerFields) ?? handler2.fallback?.() ?? handlerFields : handlerFields;
97254
- try {
97255
- const nextContent = auditedContent ? handler2.apply(validatedFields, auditedContent) : null;
97256
- if (!nextContent) {
97257
- auditedContent = null;
97258
- break;
97259
- }
97260
- auditedContent = nextContent;
97261
- } catch (error) {
97262
- this.logger.warn({
97263
- src: "agent",
97264
- agentId: this.agentId,
97265
- actionName: action.name,
97266
- handlerId: handler2.id,
97267
- error
97268
- }, "Pre-callback audit apply failed; falling through to original content");
97269
- }
97270
- }
97271
- if (!auditedContent) {
97272
- continue;
97273
- }
97274
- content = auditedContent;
97275
- }
97276
96265
  await callback(content);
97277
96266
  }
97278
96267
  }
@@ -97323,7 +96312,7 @@ ${content.text ?? ""}`).join(`
97323
96312
  this.stateCache.set(`${message2.id}_action_results`, {
97324
96313
  values: { actionResults },
97325
96314
  data: { actionResults, actionPlan },
97326
- text: JSON.stringify(actionResults, safeReplacer())
96315
+ text: JSON.stringify(actionResults)
97327
96316
  });
97328
96317
  }
97329
96318
  }
@@ -97333,12 +96322,6 @@ ${content.text ?? ""}`).join(`
97333
96322
  return cachedState?.data && cachedState.data.actionResults || [];
97334
96323
  }
97335
96324
  async evaluate(message2, state2, didRespond, callback, responses) {
97336
- const disableMemorySetting = this.getSetting("DISABLE_MEMORY_CREATION");
97337
- const disableMemoryCreation = disableMemorySetting === true || (typeof disableMemorySetting === "string" ? parseBooleanFromText(disableMemorySetting) : disableMemorySetting != null ? parseBooleanFromText(String(disableMemorySetting)) : false);
97338
- if (disableMemoryCreation) {
97339
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Skipping evaluators because DISABLE_MEMORY_CREATION is enabled");
97340
- return [];
97341
- }
97342
96325
  const evaluatorPromises = this.evaluators.map(async (evaluator) => {
97343
96326
  if (!evaluator.handler) {
97344
96327
  return null;
@@ -97458,78 +96441,20 @@ ${content.text ?? ""}`).join(`
97458
96441
  }
97459
96442
  this.logger.success({ src: "agent", agentId: this.agentId, worldId: world.id }, "World connected");
97460
96443
  }
97461
- async ensureConnection({
97462
- entityId,
97463
- roomId,
97464
- worldId,
97465
- worldName,
97466
- userName,
97467
- name,
97468
- source,
97469
- type,
97470
- channelId,
97471
- messageServerId,
97472
- userId,
97473
- metadata
97474
- }) {
97475
- if (!worldId && messageServerId) {
97476
- worldId = createUniqueUuid(this, messageServerId);
97477
- }
97478
- if (!worldId) {
97479
- worldId = this.agentId;
97480
- }
97481
- const names4 = [name, userName].filter(Boolean);
97482
- if (!source) {
97483
- throw new Error("Source is required for ensureEntityExists");
97484
- }
97485
- const entityMetadata = {
97486
- [source]: {
97487
- id: userId,
97488
- name,
97489
- userName
97490
- }
97491
- };
97492
- const entity2 = (await this.adapter.getEntitiesByIds([entityId]))[0] ?? null;
97493
- const entityToUpsert = {
97494
- id: entityId,
97495
- names: entity2 ? [...new Set([...entity2.names || [], ...names4])].filter(Boolean) : names4,
97496
- metadata: entity2 ? {
97497
- ...entity2.metadata,
97498
- [source]: {
97499
- ...entity2.metadata?.[source] && typeof entity2.metadata[source] === "object" ? entity2.metadata[source] : {},
97500
- id: userId,
97501
- name,
97502
- userName
97503
- }
97504
- } : entityMetadata,
97505
- agentId: this.agentId
97506
- };
97507
- await this.adapter.upsertEntities([entityToUpsert]);
96444
+ async ensureConnection(params) {
96445
+ await ensureConnection(this.adapter, {
96446
+ agentId: this.agentId,
96447
+ worldId: params.worldId,
96448
+ messageServerId: params.messageServerId,
96449
+ ...params,
96450
+ source: params.source ?? "default"
96451
+ });
97508
96452
  this.logger.debug({
97509
96453
  src: "agent",
97510
96454
  agentId: this.agentId,
97511
- entityId,
97512
- userName: name || userName
97513
- }, entity2 ? "Entity updated" : "Entity created");
97514
- await this.ensureWorldExists({
97515
- id: worldId,
97516
- name: worldName || messageServerId ? `World for server ${messageServerId}` : `World for room ${roomId}`,
97517
- agentId: this.agentId,
97518
- messageServerId,
97519
- metadata
97520
- });
97521
- await this.ensureRoomExists({
97522
- id: roomId,
97523
- name: name || "default",
97524
- source: source || "default",
97525
- type: typeof type === "string" && Object.values(ChannelType).includes(type) ? type : ChannelType.DM,
97526
- channelId,
97527
- messageServerId,
97528
- worldId
97529
- });
97530
- await this.ensureParticipantInRoom(entityId, roomId);
97531
- await this.ensureParticipantInRoom(this.agentId, roomId);
97532
- this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Entity connected");
96455
+ entityId: params.entityId,
96456
+ channelId: params.roomId
96457
+ }, "Entity connected");
97533
96458
  }
97534
96459
  async ensureParticipantInRoom(entityId, roomId) {
97535
96460
  const entity2 = (await this.adapter.getEntitiesByIds([entityId]))[0] ?? null;
@@ -97540,13 +96465,13 @@ ${content.text ?? ""}`).join(`
97540
96465
  } else if (!entity2) {
97541
96466
  throw new Error(`User entity ${entityId} not found, cannot add as participant.`);
97542
96467
  }
97543
- const [participantsResult] = await this.adapter.getParticipantsForRooms([
96468
+ const participantsResult = await this.adapter.getParticipantsForRooms([
97544
96469
  roomId
97545
96470
  ]);
97546
- const participantIds = participantsResult?.entityIds ?? [];
97547
- if (!participantIds.includes(entityId)) {
96471
+ const participants = participantsResult[0]?.entityIds ?? [];
96472
+ if (!participants.includes(entityId)) {
97548
96473
  const added = await this.adapter.createRoomParticipants([entityId], roomId);
97549
- if (!added.length) {
96474
+ if (!added) {
97550
96475
  throw new Error(`Failed to add participant ${entityId} to room ${roomId}`);
97551
96476
  }
97552
96477
  if (entityId === this.agentId) {
@@ -97556,25 +96481,27 @@ ${content.text ?? ""}`).join(`
97556
96481
  }
97557
96482
  }
97558
96483
  }
97559
- async getParticipantsForEntities(entityIds) {
97560
- return await this.adapter.getParticipantsForEntities(entityIds);
97561
- }
97562
- async getParticipantsForRooms(roomIds) {
97563
- return await this.adapter.getParticipantsForRooms(roomIds);
97564
- }
97565
96484
  async getParticipantsForEntity(entityId) {
97566
96485
  return await this.adapter.getParticipantsForEntities([entityId]);
97567
96486
  }
96487
+ async getParticipantsForEntities(entityIds) {
96488
+ return await this.adapter.getParticipantsForEntities(entityIds);
96489
+ }
97568
96490
  async getParticipantsForRoom(roomId) {
97569
96491
  const result = await this.adapter.getParticipantsForRooms([roomId]);
97570
96492
  return result[0]?.entityIds ?? [];
97571
96493
  }
97572
- async areRoomParticipants(pairs) {
97573
- return await this.adapter.areRoomParticipants(pairs);
96494
+ async getParticipantsForRooms(roomIds) {
96495
+ return await this.adapter.getParticipantsForRooms(roomIds);
97574
96496
  }
97575
96497
  async isRoomParticipant(roomId, entityId) {
97576
- const [ok] = await this.adapter.areRoomParticipants([{ roomId, entityId }]);
97577
- return ok ?? false;
96498
+ const results = await this.adapter.areRoomParticipants([
96499
+ { roomId, entityId }
96500
+ ]);
96501
+ return results[0] ?? false;
96502
+ }
96503
+ async areRoomParticipants(pairs) {
96504
+ return await this.adapter.areRoomParticipants(pairs);
97578
96505
  }
97579
96506
  async addParticipant(entityId, roomId) {
97580
96507
  const ids = await this.adapter.createRoomParticipants([entityId], roomId);
@@ -97606,7 +96533,8 @@ ${content.text ?? ""}`).join(`
97606
96533
  worldId,
97607
96534
  metadata
97608
96535
  }) {
97609
- const resolvedWorldId = worldId ?? this.agentId;
96536
+ if (!worldId)
96537
+ throw new Error("worldId is required");
97610
96538
  const room = await this.getRoom(id);
97611
96539
  await this.adapter.upsertRooms([
97612
96540
  {
@@ -97617,7 +96545,7 @@ ${content.text ?? ""}`).join(`
97617
96545
  type,
97618
96546
  channelId,
97619
96547
  messageServerId,
97620
- worldId: resolvedWorldId,
96548
+ worldId,
97621
96549
  metadata
97622
96550
  }
97623
96551
  ]);
@@ -97658,67 +96586,24 @@ ${content.text ?? ""}`).join(`
97658
96586
  }
97659
96587
  }
97660
96588
  providersToGet.sort((a, b) => (a.position || 0) - (b.position || 0));
97661
- const trajLogger = this.getService("trajectory_logger");
97662
- const composeStateStart = Date.now();
97663
- const providerTimings = [];
97664
- const PROVIDER_TIMEOUT = 30000;
96589
+ const trajLogger = await this.getService("trajectory_logger");
97665
96590
  const providerData = await Promise.all(providersToGet.map(async (provider) => {
97666
96591
  const start = Date.now();
97667
- let timerId;
97668
- try {
97669
- const timeoutPromise = new Promise((_, reject) => {
97670
- timerId = setTimeout(() => reject(new Error(`Provider ${provider.name} timed out after ${PROVIDER_TIMEOUT}ms`)), PROVIDER_TIMEOUT);
97671
- });
97672
- const result = await Promise.race([
97673
- provider.get(this, message2, cachedState),
97674
- timeoutPromise
97675
- ]);
97676
- clearTimeout(timerId);
97677
- const duration2 = Date.now() - start;
97678
- providerTimings.push({ name: provider.name, durationMs: duration2 });
97679
- if (duration2 > 100) {
97680
- this.logger.debug({
97681
- src: "agent",
97682
- agentId: this.agentId,
97683
- provider: provider.name,
97684
- duration: duration2
97685
- }, "Slow provider");
97686
- }
97687
- return {
97688
- ...result,
97689
- providerName: provider.name
97690
- };
97691
- } catch (error) {
97692
- clearTimeout(timerId);
97693
- const duration2 = Date.now() - start;
97694
- this.logger.error({
96592
+ const result = await provider.get(this, message2, cachedState);
96593
+ const duration2 = Date.now() - start;
96594
+ if (duration2 > 100) {
96595
+ this.logger.debug({
97695
96596
  src: "agent",
97696
96597
  agentId: this.agentId,
97697
96598
  provider: provider.name,
97698
- duration: duration2,
97699
- error: error instanceof Error ? error.message : String(error)
97700
- }, "Provider error or timeout");
97701
- return {
97702
- values: {},
97703
- text: "",
97704
- data: {},
97705
- providerName: provider.name
97706
- };
96599
+ duration: duration2
96600
+ }, "Slow provider");
97707
96601
  }
96602
+ return {
96603
+ ...result,
96604
+ providerName: provider.name
96605
+ };
97708
96606
  }));
97709
- const composeStateEnd = Date.now();
97710
- const totalProviderTime = composeStateEnd - composeStateStart;
97711
- if (totalProviderTime > 500 || providerTimings.length > 5) {
97712
- const sortedTimings = [...providerTimings].sort((a, b) => b.durationMs - a.durationMs);
97713
- const topTimings = sortedTimings.slice(0, 5).map((t) => `${t.name}=${t.durationMs.toLocaleString()}ms`).join(", ");
97714
- this.logger.info({
97715
- src: "agent:composeState:profile",
97716
- agentId: this.agentId,
97717
- totalMs: totalProviderTime,
97718
- providerCount: providersToGet.length,
97719
- timings: sortedTimings
97720
- }, `[PROFILE:composeState] ${totalProviderTime.toLocaleString()}ms for ${providersToGet.length} providers. Top: ${topTimings}`);
97721
- }
97722
96607
  if (trajectoryStepId && trajLogger) {
97723
96608
  const userText = typeof message2.content?.text === "string" ? message2.content.text : "";
97724
96609
  for (const r of providerData) {
@@ -97788,18 +96673,94 @@ ${content.text ?? ""}`).join(`
97788
96673
  }
97789
96674
  return newState;
97790
96675
  }
97791
- getService(serviceName) {
97792
- const serviceInstances = this.services.get(serviceName);
97793
- if (!serviceInstances || serviceInstances.length === 0) {
97794
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceName }, "Service not found");
96676
+ async _ensureServiceStarted(serviceType) {
96677
+ if (this.stopped)
96678
+ return null;
96679
+ const key = serviceType;
96680
+ const instances = this.services.get(key);
96681
+ if (instances && instances.length > 0) {
96682
+ return instances[0];
96683
+ }
96684
+ const classes = this.serviceTypes.get(key);
96685
+ if (!classes || classes.length === 0) {
97795
96686
  return null;
97796
96687
  }
97797
- return serviceInstances[0];
96688
+ let inFlight = this.startingServices.get(key);
96689
+ if (!inFlight) {
96690
+ inFlight = (async () => {
96691
+ let first = null;
96692
+ for (const cls of classes) {
96693
+ const result = await this._runServiceStart(key, serviceType, cls);
96694
+ if (result && !first)
96695
+ first = result;
96696
+ }
96697
+ return first;
96698
+ })();
96699
+ this.startingServices.set(key, inFlight);
96700
+ }
96701
+ try {
96702
+ return await inFlight;
96703
+ } finally {
96704
+ this.startingServices.delete(key);
96705
+ }
97798
96706
  }
97799
- getTypedService(serviceName) {
96707
+ async _runServiceStart(key, serviceType, serviceDef) {
96708
+ this.serviceRegistrationStatus.set(key, "registering");
96709
+ await this.initPromise;
96710
+ if (typeof serviceDef.start !== "function") {
96711
+ this.logger.error({ src: "agent", agentId: this.agentId, serviceType }, "Service class has no static start method");
96712
+ this.serviceRegistrationStatus.set(key, "failed");
96713
+ return null;
96714
+ }
96715
+ try {
96716
+ const serviceInstance = await serviceDef.start(this);
96717
+ if (!serviceInstance) {
96718
+ this.serviceRegistrationStatus.set(key, "failed");
96719
+ return null;
96720
+ }
96721
+ if (!this.services.has(key)) {
96722
+ this.services.set(key, []);
96723
+ }
96724
+ const serviceList = this.services.get(key);
96725
+ if (serviceList) {
96726
+ serviceList.push(serviceInstance);
96727
+ }
96728
+ const handler2 = this.servicePromiseHandlers.get(serviceType);
96729
+ if (handler2) {
96730
+ handler2.resolve(serviceInstance);
96731
+ this.servicePromiseHandlers.delete(serviceType);
96732
+ }
96733
+ if (serviceDef.registerSendHandlers) {
96734
+ serviceDef.registerSendHandlers(this, serviceInstance);
96735
+ }
96736
+ this.serviceRegistrationStatus.set(key, "registered");
96737
+ return serviceInstance;
96738
+ } catch (error) {
96739
+ this.logger.error({
96740
+ src: "agent",
96741
+ agentId: this.agentId,
96742
+ serviceType,
96743
+ error: error instanceof Error ? error.message : String(error)
96744
+ }, "Service start failed");
96745
+ const handler2 = this.servicePromiseHandlers.get(serviceType);
96746
+ if (handler2) {
96747
+ handler2.reject(error instanceof Error ? error : new Error(String(error)));
96748
+ this.servicePromiseHandlers.delete(serviceType);
96749
+ this.servicePromises.delete(serviceType);
96750
+ }
96751
+ this.serviceRegistrationStatus.set(key, "failed");
96752
+ return null;
96753
+ }
96754
+ }
96755
+ async getService(serviceName) {
96756
+ const instance = await this._ensureServiceStarted(serviceName);
96757
+ return instance;
96758
+ }
96759
+ async getTypedService(serviceName) {
97800
96760
  return this.getService(serviceName);
97801
96761
  }
97802
- getServicesByType(serviceName) {
96762
+ async getServicesByType(serviceName) {
96763
+ await this._ensureServiceStarted(serviceName);
97803
96764
  const serviceInstances = this.services.get(serviceName);
97804
96765
  if (!serviceInstances || serviceInstances.length === 0) {
97805
96766
  this.logger.debug({ src: "agent", agentId: this.agentId, serviceName }, "No services found for type");
@@ -97808,11 +96769,11 @@ ${content.text ?? ""}`).join(`
97808
96769
  return serviceInstances;
97809
96770
  }
97810
96771
  getRegisteredServiceTypes() {
97811
- return Array.from(this.services.keys());
96772
+ return Array.from(this.serviceTypes.keys());
97812
96773
  }
97813
96774
  hasService(serviceType) {
97814
- const serviceInstances = this.services.get(serviceType);
97815
- return serviceInstances !== undefined && serviceInstances.length > 0;
96775
+ const classes = this.serviceTypes.get(serviceType);
96776
+ return classes !== undefined && classes.length > 0;
97816
96777
  }
97817
96778
  getServiceRegistrationStatus(serviceType) {
97818
96779
  return this.serviceRegistrationStatus.get(serviceType) || "unknown";
@@ -97844,48 +96805,19 @@ ${content.text ?? ""}`).join(`
97844
96805
  this.logger.warn({ src: "agent", agentId: this.agentId, serviceName }, "Service missing serviceType property");
97845
96806
  return;
97846
96807
  }
97847
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Registering service");
97848
- this.serviceRegistrationStatus.set(serviceType, "registering");
97849
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service waiting for init");
97850
- const initTimeout = new Promise((_, reject) => {
97851
- setTimeout(() => {
97852
- reject(new Error(`Service ${serviceType} registration timed out waiting for runtime initialization (30s timeout)`));
97853
- }, 30000);
97854
- });
97855
- await Promise.race([this.initPromise, initTimeout]);
97856
- if (typeof serviceDef.start !== "function") {
97857
- throw new Error(`Service ${serviceType} does not have a static start method. All services must implement static async start(runtime: IAgentRuntime): Promise<Service>.`);
97858
- }
97859
- const serviceInstance = await serviceDef.start(this);
97860
- if (!serviceInstance) {
97861
- throw new Error(`Service ${serviceType} start() method returned null or undefined. It must return a Service instance.`);
97862
- }
97863
- if (!this.services.has(serviceType)) {
97864
- this.services.set(serviceType, []);
96808
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Registering service (lazy; start() on first getService)");
96809
+ this.serviceRegistrationStatus.set(serviceType, "pending");
96810
+ if (!this.servicePromises.has(serviceType)) {
96811
+ this._createServiceResolver(serviceType);
97865
96812
  }
97866
96813
  if (!this.serviceTypes.has(serviceType)) {
97867
96814
  this.serviceTypes.set(serviceType, []);
97868
96815
  }
97869
- const servicesArray = this.services.get(serviceType);
97870
- if (servicesArray) {
97871
- servicesArray.push(serviceInstance);
97872
- }
97873
- const serviceTypesArray = this.serviceTypes.get(serviceType);
97874
- if (serviceTypesArray) {
97875
- serviceTypesArray.push(serviceDef);
97876
- }
97877
- const handler2 = this.servicePromiseHandlers.get(serviceType);
97878
- if (handler2) {
97879
- handler2.resolve(serviceInstance);
97880
- this.servicePromiseHandlers.delete(serviceType);
97881
- } else {
97882
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service has no promise handler");
97883
- }
97884
- if (serviceDef.registerSendHandlers) {
97885
- serviceDef.registerSendHandlers(this, serviceInstance);
96816
+ const serviceClassList = this.serviceTypes.get(serviceType);
96817
+ if (!serviceClassList) {
96818
+ return;
97886
96819
  }
97887
- this.serviceRegistrationStatus.set(serviceType, "registered");
97888
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service registered");
96820
+ serviceClassList.push(serviceDef);
97889
96821
  }
97890
96822
  _createServiceResolver(serviceType) {
97891
96823
  let resolver;
@@ -97911,11 +96843,11 @@ ${content.text ?? ""}`).join(`
97911
96843
  return promise;
97912
96844
  }
97913
96845
  getServiceLoadPromise(serviceType) {
97914
- let p = this.servicePromises.get(serviceType);
97915
- if (!p) {
97916
- p = this._createServiceResolver(serviceType);
97917
- }
97918
- return p;
96846
+ return this.getService(serviceType).then((s) => {
96847
+ if (!s)
96848
+ throw new Error(`Service ${serviceType} not found or failed to start`);
96849
+ return s;
96850
+ });
97919
96851
  }
97920
96852
  registerModel(modelType, handler2, provider, priority) {
97921
96853
  const modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
@@ -98015,55 +96947,6 @@ ${content.text ?? ""}`).join(`
98015
96947
  });
98016
96948
  }
98017
96949
  }
98018
- const providerStr = provider || this.models.get(modelKey)?.[0]?.provider || "unknown";
98019
- const meta = {
98020
- agentName: this.character?.name,
98021
- agentId: this.agentId,
98022
- runId: this.getCurrentRunId(),
98023
- provider: providerStr,
98024
- actionContext: this.currentActionContext?.actionName
98025
- };
98026
- if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
98027
- const redactedPrompt = this.redactSecrets(promptContent);
98028
- const pSlug = logPrompt(modelKey, redactedPrompt, meta);
98029
- if (pSlug) {
98030
- this.logger.debug({
98031
- src: "agent",
98032
- agentId: this.agentId,
98033
- model: modelKey,
98034
- slug: pSlug,
98035
- chars: promptContent.length
98036
- }, `PROMPT ${pSlug}`);
98037
- }
98038
- let responseText;
98039
- if (typeof response === "string") {
98040
- responseText = this.redactSecrets(response);
98041
- } else if (Array.isArray(response) && response.every((x) => typeof x === "number")) {
98042
- responseText = "[embedding-array]";
98043
- } else {
98044
- try {
98045
- const raw2 = this.redactSecrets(JSON.stringify(response));
98046
- responseText = raw2.length > 1e5 ? raw2.substring(0, 1e5) + `... [truncated, ${raw2.length} total chars]` : raw2;
98047
- } catch {
98048
- responseText = "[non-serializable response]";
98049
- }
98050
- }
98051
- const rSlug = logResponse(modelKey, responseText, {
98052
- ...meta,
98053
- promptSlug: pSlug,
98054
- duration: Number(elapsedTime.toFixed(2))
98055
- });
98056
- if (rSlug) {
98057
- this.logger.debug({
98058
- src: "agent",
98059
- agentId: this.agentId,
98060
- model: modelKey,
98061
- slug: rSlug,
98062
- duration: Number(elapsedTime.toFixed(2)),
98063
- chars: responseText.length
98064
- }, `RESPONSE ${rSlug}`);
98065
- }
98066
- }
98067
96950
  const responseValue = Array.isArray(response) && response.every((x) => typeof x === "number") ? "[array]" : typeof response === "string" ? response : undefined;
98068
96951
  this.adapter.createLogs([
98069
96952
  {
@@ -98090,28 +96973,6 @@ ${content.text ?? ""}`).join(`
98090
96973
  }
98091
96974
  async useModel(modelType, params, provider) {
98092
96975
  let modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
98093
- let callerInfo = "unknown";
98094
- if (this.logger.level === "debug" || this.logger.level === "trace") {
98095
- try {
98096
- const stackLimit = Error.stackTraceLimit;
98097
- Error.stackTraceLimit = 5;
98098
- const stack = new Error().stack;
98099
- Error.stackTraceLimit = stackLimit;
98100
- callerInfo = stack?.split(`
98101
- `).slice(2, 5).map((line) => line.trim().replace(/^at\s+/, "")).join(" <- ") || "unknown";
98102
- } catch {
98103
- callerInfo = "unknown (stack error)";
98104
- }
98105
- }
98106
- this.logger.debug({
98107
- src: "agent",
98108
- agentId: this.agentId,
98109
- model: modelKey,
98110
- caller: callerInfo,
98111
- provider: provider || "default",
98112
- actionContext: this.currentActionContext?.actionName,
98113
- runId: this.getCurrentRunId()
98114
- }, "useModel called");
98115
96976
  const llmMode = this.getLLMMode();
98116
96977
  if (llmMode !== "DEFAULT") {
98117
96978
  const textGenerationModels = [
@@ -98225,20 +97086,17 @@ ${content.text ?? ""}`).join(`
98225
97086
  if (ctxEnd)
98226
97087
  ctxEnd();
98227
97088
  const elapsedTime2 = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
98228
- this.logger.debug({
97089
+ this.logger.trace({
98229
97090
  src: "agent",
98230
97091
  agentId: this.agentId,
98231
97092
  model: modelKey,
98232
97093
  duration: Number(elapsedTime2.toFixed(2)),
98233
- streaming: true,
98234
- caller: callerInfo,
98235
- provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
98236
- actionContext: this.currentActionContext?.actionName
98237
- }, "useModel completed (stream with callback complete)");
97094
+ streaming: true
97095
+ }, "Model output (stream with callback complete)");
98238
97096
  this.logModelCall(modelType, modelKey, params, promptContent, elapsedTime2, provider, fullText);
98239
97097
  try {
98240
97098
  const stepId = getTrajectoryContext()?.trajectoryStepId;
98241
- const trajLogger = this.getService("trajectory_logger");
97099
+ const trajLogger = await this.getService("trajectory_logger");
98242
97100
  if (stepId && trajLogger) {
98243
97101
  const tempRaw = isPlainObject(modelParams) ? modelParams.temperature : undefined;
98244
97102
  const maxTokensRaw = isPlainObject(modelParams) ? modelParams.maxTokens : undefined;
@@ -98259,19 +97117,16 @@ ${content.text ?? ""}`).join(`
98259
97117
  return fullText;
98260
97118
  }
98261
97119
  const elapsedTime = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
98262
- this.logger.debug({
97120
+ this.logger.trace({
98263
97121
  src: "agent",
98264
97122
  agentId: this.agentId,
98265
97123
  model: modelKey,
98266
- duration: Number(elapsedTime.toFixed(2)),
98267
- caller: callerInfo,
98268
- provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
98269
- actionContext: this.currentActionContext?.actionName
98270
- }, "useModel completed");
97124
+ duration: Number(elapsedTime.toFixed(2))
97125
+ }, "Model output");
98271
97126
  this.logModelCall(modelType, modelKey, params, promptContent, elapsedTime, provider, response);
98272
97127
  try {
98273
97128
  const stepId = getTrajectoryContext()?.trajectoryStepId;
98274
- const trajLogger = this.getService("trajectory_logger");
97129
+ const trajLogger = await this.getService("trajectory_logger");
98275
97130
  if (stepId && trajLogger) {
98276
97131
  const tempRaw = isPlainObject(modelParams) ? modelParams.temperature : undefined;
98277
97132
  const maxTokensRaw = isPlainObject(modelParams) ? modelParams.maxTokens : undefined;
@@ -98801,47 +97656,6 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
98801
97656
  delete state2._smartRetryContext;
98802
97657
  return null;
98803
97658
  }
98804
- calculateBackoffDelay(config2, retryCount) {
98805
- if (typeof config2 === "number") {
98806
- return config2;
98807
- }
98808
- const { initialMs = 1000, multiplier = 2, maxMs = 30000 } = config2;
98809
- const delay = initialMs * multiplier ** (retryCount - 1);
98810
- return Math.min(delay, maxMs);
98811
- }
98812
- abortableSleep(ms, signal) {
98813
- if (signal?.aborted)
98814
- return Promise.resolve(true);
98815
- return new Promise((resolve) => {
98816
- const timeout = setTimeout(() => {
98817
- signal?.removeEventListener("abort", onAbort);
98818
- resolve(false);
98819
- }, ms);
98820
- const onAbort = () => {
98821
- clearTimeout(timeout);
98822
- resolve(true);
98823
- };
98824
- signal?.addEventListener("abort", onAbort, { once: true });
98825
- });
98826
- }
98827
- upgradeDoubleToTriple(tpl) {
98828
- const DOUBLE_BRACE_VAR = /(?<!\{)\{\{(?!#|\/|!|>|\{|else\b)(\s*)(\S+?)(\s*)\}\}(?!\})/g;
98829
- return tpl.replace(DOUBLE_BRACE_VAR, "{{{$1$2$3}}}");
98830
- }
98831
- normalizeStructuredResponse(responseContent, depth = 0) {
98832
- if (!responseContent)
98833
- return null;
98834
- const MAX_UNWRAP_DEPTH = 3;
98835
- if (depth >= MAX_UNWRAP_DEPTH)
98836
- return responseContent;
98837
- if ("response" in responseContent && typeof responseContent.response === "object" && responseContent.response !== null) {
98838
- const nested = responseContent.response;
98839
- if (Object.keys(nested).length > 0) {
98840
- return this.normalizeStructuredResponse(nested, depth + 1);
98841
- }
98842
- }
98843
- return responseContent;
98844
- }
98845
97659
  flattenSchemaRows(rows) {
98846
97660
  const flattened = [];
98847
97661
  for (const row of rows) {
@@ -99067,6 +97881,47 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99067
97881
  return effectiveType;
99068
97882
  }
99069
97883
  }
97884
+ calculateBackoffDelay(config2, retryCount) {
97885
+ if (typeof config2 === "number") {
97886
+ return config2;
97887
+ }
97888
+ const { initialMs = 1000, multiplier = 2, maxMs = 30000 } = config2;
97889
+ const delay = initialMs * multiplier ** (retryCount - 1);
97890
+ return Math.min(delay, maxMs);
97891
+ }
97892
+ abortableSleep(ms, signal) {
97893
+ if (signal?.aborted)
97894
+ return Promise.resolve(true);
97895
+ return new Promise((resolve) => {
97896
+ const timeout = setTimeout(() => {
97897
+ signal?.removeEventListener("abort", onAbort);
97898
+ resolve(false);
97899
+ }, ms);
97900
+ const onAbort = () => {
97901
+ clearTimeout(timeout);
97902
+ resolve(true);
97903
+ };
97904
+ signal?.addEventListener("abort", onAbort, { once: true });
97905
+ });
97906
+ }
97907
+ upgradeDoubleToTriple(tpl) {
97908
+ const DOUBLE_BRACE_VAR = /(?<!\{)\{\{(?!#|\/|!|>|\{|else\b)(\s*)(\S+?)(\s*)\}\}(?!\})/g;
97909
+ return tpl.replace(DOUBLE_BRACE_VAR, "{{{$1$2$3}}}");
97910
+ }
97911
+ normalizeStructuredResponse(responseContent, depth = 0) {
97912
+ if (!responseContent)
97913
+ return null;
97914
+ const MAX_UNWRAP_DEPTH = 3;
97915
+ if (depth >= MAX_UNWRAP_DEPTH)
97916
+ return responseContent;
97917
+ if ("response" in responseContent && typeof responseContent.response === "object" && responseContent.response !== null) {
97918
+ const nested = responseContent.response;
97919
+ if (Object.keys(nested).length > 0) {
97920
+ return this.normalizeStructuredResponse(nested, depth + 1);
97921
+ }
97922
+ }
97923
+ return responseContent;
97924
+ }
99070
97925
  registerEvent(event, handler2) {
99071
97926
  if (!this.events[event]) {
99072
97927
  this.events[event] = [];
@@ -99109,13 +97964,10 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99109
97964
  if (!model2) {
99110
97965
  throw new Error("No TEXT_EMBEDDING model registered");
99111
97966
  }
99112
- const embedding = await this.useModel(ModelType.TEXT_EMBEDDING, {
99113
- text: "test"
99114
- });
97967
+ const embedding = await this.useModel(ModelType.TEXT_EMBEDDING, null);
99115
97968
  if (!embedding || !embedding.length) {
99116
97969
  throw new Error("Invalid embedding received");
99117
97970
  }
99118
- this.cachedEmbeddingDimension = embedding.length;
99119
97971
  await this.adapter.ensureEmbeddingDimension(embedding.length);
99120
97972
  this.logger.debug({ src: "agent", agentId: this.agentId, dimension: embedding.length }, "Embedding dimension set");
99121
97973
  }
@@ -99262,12 +98114,15 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99262
98114
  });
99263
98115
  return await this.adapter.upsertEntities(entities);
99264
98116
  }
99265
- async getComponentsForEntities(entityIds, worldId, sourceEntityId) {
99266
- return await this.adapter.getComponentsForEntities(entityIds, worldId, sourceEntityId);
99267
- }
99268
98117
  async getComponents(entityId, worldId, sourceEntityId) {
99269
98118
  return await this.adapter.getComponentsForEntities([entityId], worldId, sourceEntityId);
99270
98119
  }
98120
+ async getComponentsByNaturalKeys(keys2) {
98121
+ return await this.adapter.getComponentsByNaturalKeys(keys2);
98122
+ }
98123
+ async getComponentsForEntities(entityIds, worldId, sourceEntityId) {
98124
+ return await this.adapter.getComponentsForEntities(entityIds, worldId, sourceEntityId);
98125
+ }
99271
98126
  async addEmbeddingToMemory(memory2) {
99272
98127
  if (memory2.embedding) {
99273
98128
  return memory2;
@@ -99276,31 +98131,28 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99276
98131
  if (!memoryText) {
99277
98132
  throw new Error("Cannot generate embedding: Memory content is empty");
99278
98133
  }
99279
- try {
99280
- memory2.embedding = await this.useModel(ModelType.TEXT_EMBEDDING, {
99281
- text: memoryText
99282
- });
99283
- } catch (error) {
99284
- this.logger.error({
99285
- src: "agent",
99286
- agentId: this.agentId,
99287
- error: error instanceof Error ? error.message : String(error)
99288
- }, "Embedding generation failed");
99289
- const dimension = this.cachedEmbeddingDimension || 1536;
99290
- memory2.embedding = new Array(dimension).fill(0);
99291
- this.logger.warn({ src: "agent", agentId: this.agentId, dimension }, "Using zero vector for failed embedding");
99292
- }
98134
+ memory2.embedding = await this.useModel(ModelType.TEXT_EMBEDDING, {
98135
+ text: memoryText
98136
+ });
99293
98137
  return memory2;
99294
98138
  }
99295
98139
  async queueEmbeddingGeneration(memory2, priority) {
99296
98140
  priority = priority || "normal";
99297
- if (!memory2) {
98141
+ if (!memory2 || memory2.embedding || !memory2.content?.text) {
99298
98142
  return;
99299
98143
  }
99300
- if (memory2.embedding) {
99301
- return;
99302
- }
99303
- if (!memory2.content || !memory2.content.text) {
98144
+ if (this.companionUrl) {
98145
+ const url = `${this.companionUrl.replace(/\/$/, "")}/embedding-generation`;
98146
+ this.fetch(url, {
98147
+ method: "POST",
98148
+ headers: { "Content-Type": "application/json" },
98149
+ body: JSON.stringify({
98150
+ agentId: this.agentId,
98151
+ memory: memory2,
98152
+ priority,
98153
+ runId: this.getCurrentRunId()
98154
+ })
98155
+ }).catch(() => {});
99304
98156
  return;
99305
98157
  }
99306
98158
  await this.emitEvent("EMBEDDING_GENERATION_REQUESTED" /* EMBEDDING_GENERATION_REQUESTED */, {
@@ -99392,8 +98244,22 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99392
98244
  async deleteAllMemories(roomIds, tableName) {
99393
98245
  await this.adapter.deleteAllMemories(roomIds, tableName);
99394
98246
  }
99395
- async countMemories(params) {
99396
- return await this.adapter.countMemories(params);
98247
+ async countMemories(roomIdOrParams, unique, tableName) {
98248
+ if (typeof roomIdOrParams === "string") {
98249
+ return await this.adapter.countMemories({
98250
+ roomIds: [roomIdOrParams],
98251
+ unique,
98252
+ tableName
98253
+ });
98254
+ }
98255
+ return await this.adapter.countMemories({
98256
+ roomIds: roomIdOrParams.roomId ? [roomIdOrParams.roomId] : undefined,
98257
+ unique: roomIdOrParams.unique,
98258
+ tableName: roomIdOrParams.tableName,
98259
+ entityId: roomIdOrParams.entityId,
98260
+ agentId: roomIdOrParams.agentId,
98261
+ metadata: roomIdOrParams.metadata
98262
+ });
99397
98263
  }
99398
98264
  async getLogs(params) {
99399
98265
  return await this.adapter.getLogs(params);
@@ -99463,7 +98329,8 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99463
98329
  messageServerId,
99464
98330
  worldId
99465
98331
  }) {
99466
- const resolvedWorldId = worldId ?? this.agentId;
98332
+ if (!worldId)
98333
+ throw new Error("worldId is required");
99467
98334
  const res = await this.adapter.createRooms([
99468
98335
  {
99469
98336
  id,
@@ -99472,7 +98339,7 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99472
98339
  type,
99473
98340
  channelId,
99474
98341
  messageServerId,
99475
- worldId: resolvedWorldId
98342
+ worldId
99476
98343
  }
99477
98344
  ]);
99478
98345
  if (!res.length)
@@ -99485,49 +98352,43 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99485
98352
  async upsertRooms(rooms) {
99486
98353
  return await this.adapter.upsertRooms(rooms);
99487
98354
  }
99488
- async deleteRoomsByWorldIds(worldIds) {
99489
- await this.adapter.deleteRoomsByWorldIds(worldIds);
99490
- }
99491
- async getRoomsByWorlds(worldIds, limit, offset) {
99492
- return await this.adapter.getRoomsByWorlds(worldIds, limit, offset);
99493
- }
99494
- async getRoomsForParticipants(entityIds) {
99495
- return await this.adapter.getRoomsForParticipants(entityIds);
99496
- }
99497
98355
  async deleteRoomsByWorldId(worldId) {
99498
98356
  await this.adapter.deleteRoomsByWorldIds([worldId]);
99499
98357
  }
99500
98358
  async getRoomsForParticipant(entityId) {
99501
98359
  return await this.adapter.getRoomsForParticipants([entityId]);
99502
98360
  }
98361
+ async getRoomsForParticipants(entityIds) {
98362
+ return await this.adapter.getRoomsForParticipants(entityIds);
98363
+ }
99503
98364
  async getRooms(worldId) {
99504
98365
  return await this.adapter.getRoomsByWorlds([worldId]);
99505
98366
  }
99506
98367
  async getRoomsByWorld(worldId) {
99507
98368
  return await this.adapter.getRoomsByWorlds([worldId]);
99508
98369
  }
99509
- async getParticipantUserStates(pairs) {
99510
- return await this.adapter.getParticipantUserStates(pairs);
99511
- }
99512
98370
  async getParticipantUserState(roomId, entityId) {
99513
- const [state2] = await this.adapter.getParticipantUserStates([
98371
+ const results = await this.adapter.getParticipantUserStates([
99514
98372
  { roomId, entityId }
99515
98373
  ]);
99516
- return state2 ?? null;
99517
- }
99518
- async updateParticipantUserStates(updates) {
99519
- await this.adapter.updateParticipantUserStates(updates);
98374
+ return results[0] ?? null;
99520
98375
  }
99521
98376
  async updateParticipantUserState(roomId, entityId, state2) {
99522
98377
  await this.adapter.updateParticipantUserStates([
99523
98378
  { roomId, entityId, state: state2 }
99524
98379
  ]);
99525
98380
  }
99526
- async getRelationshipsByPairs(pairs) {
99527
- return await this.adapter.getRelationshipsByPairs(pairs);
98381
+ async getParticipantUserStates(pairs) {
98382
+ return await this.adapter.getParticipantUserStates(pairs);
98383
+ }
98384
+ async updateParticipantUserStates(updates) {
98385
+ await this.adapter.updateParticipantUserStates(updates);
99528
98386
  }
99529
98387
  async getRelationships(params) {
99530
- return await this.adapter.getRelationships(params);
98388
+ return await this.adapter.getRelationships({
98389
+ entityIds: [params.entityId],
98390
+ tags: params.tags
98391
+ });
99531
98392
  }
99532
98393
  async getCaches(keys2) {
99533
98394
  return await this.adapter.getCaches(keys2);
@@ -99539,18 +98400,24 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99539
98400
  return await this.adapter.deleteCaches(keys2);
99540
98401
  }
99541
98402
  async getTasks(params) {
99542
- return await this.adapter.getTasks(params);
98403
+ return await this.adapter.getTasks({ ...params, agentIds: [this.agentId] });
99543
98404
  }
99544
98405
  async getTasksByName(name) {
99545
98406
  return await this.adapter.getTasksByName(name);
99546
98407
  }
98408
+ _notifyCompanionTasksDirty() {
98409
+ if (!this.companionUrl)
98410
+ return;
98411
+ const url = `${this.companionUrl.replace(/\/$/, "")}/task-dirty`;
98412
+ this.fetch(url, {
98413
+ method: "POST",
98414
+ headers: { "Content-Type": "application/json" },
98415
+ body: JSON.stringify({ agentId: this.agentId })
98416
+ }).catch(() => {});
98417
+ }
99547
98418
  async createTask(task2) {
99548
- const taskWithAgent = { ...task2, agentId: task2.agentId ?? this.agentId };
99549
- const ids = await this.adapter.createTasks([taskWithAgent]);
99550
- const taskService = this.getService(ServiceType2.TASK);
99551
- if (taskService && "markDirty" in taskService) {
99552
- taskService.markDirty();
99553
- }
98419
+ const ids = await this.adapter.createTasks([task2]);
98420
+ this._notifyCompanionTasksDirty();
99554
98421
  return ids[0];
99555
98422
  }
99556
98423
  async getTask(id) {
@@ -99559,17 +98426,10 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99559
98426
  }
99560
98427
  async updateTask(id, task2) {
99561
98428
  await this.adapter.updateTasks([{ id, task: task2 }]);
99562
- const taskService = this.getService(ServiceType2.TASK);
99563
- if (taskService && "markDirty" in taskService) {
99564
- taskService.markDirty();
99565
- }
98429
+ this._notifyCompanionTasksDirty();
99566
98430
  }
99567
98431
  async deleteTask(id) {
99568
- await this.adapter.deleteTasks([id]);
99569
- const taskService = this.getService(ServiceType2.TASK);
99570
- if (taskService && "markDirty" in taskService) {
99571
- taskService.markDirty();
99572
- }
98432
+ return await this.adapter.deleteTasks([id]);
99573
98433
  }
99574
98434
  async log(params) {
99575
98435
  return await this.adapter.createLogs([params]);
@@ -99588,15 +98448,8 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99588
98448
  return await this.adapter.deleteCaches([key]);
99589
98449
  }
99590
98450
  async createTasks(tasks) {
99591
- const tasksWithAgent = tasks.map((t) => ({
99592
- ...t,
99593
- agentId: t.agentId ?? this.agentId
99594
- }));
99595
- const ids = await this.adapter.createTasks(tasksWithAgent);
99596
- const taskService = this.getService(ServiceType2.TASK);
99597
- if (taskService && "markDirty" in taskService) {
99598
- taskService.markDirty();
99599
- }
98451
+ const ids = await this.adapter.createTasks(tasks);
98452
+ this._notifyCompanionTasksDirty();
99600
98453
  return ids;
99601
98454
  }
99602
98455
  async getTasksByIds(taskIds) {
@@ -99604,17 +98457,10 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99604
98457
  }
99605
98458
  async updateTasks(updates) {
99606
98459
  await this.adapter.updateTasks(updates);
99607
- const taskService = this.getService(ServiceType2.TASK);
99608
- if (taskService && "markDirty" in taskService) {
99609
- taskService.markDirty();
99610
- }
98460
+ this._notifyCompanionTasksDirty();
99611
98461
  }
99612
98462
  async deleteTasks(taskIds) {
99613
- await this.adapter.deleteTasks(taskIds);
99614
- const taskService = this.getService(ServiceType2.TASK);
99615
- if (taskService && "markDirty" in taskService) {
99616
- taskService.markDirty();
99617
- }
98463
+ return await this.adapter.deleteTasks(taskIds);
99618
98464
  }
99619
98465
  async transaction(callback, options) {
99620
98466
  return await this.adapter.transaction(callback, options);
@@ -99666,14 +98512,11 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99666
98512
  const ids = await this.adapter.createComponents([component]);
99667
98513
  return ids.length > 0;
99668
98514
  }
99669
- async getComponentsByNaturalKeys(keys2) {
99670
- return await this.adapter.getComponentsByNaturalKeys(keys2);
99671
- }
99672
98515
  async getComponent(entityId, type, worldId, sourceEntityId) {
99673
- const [component] = await this.adapter.getComponentsByNaturalKeys([
98516
+ const results = await this.adapter.getComponentsByNaturalKeys([
99674
98517
  { entityId, type, worldId, sourceEntityId }
99675
98518
  ]);
99676
- return component ?? null;
98519
+ return results[0] ?? null;
99677
98520
  }
99678
98521
  async updateComponent(component) {
99679
98522
  return await this.adapter.updateComponents([component]);
@@ -99687,14 +98530,14 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99687
98530
  async upsertComponents(components2, options) {
99688
98531
  return await this.adapter.upsertComponents(components2, options);
99689
98532
  }
98533
+ async patchComponent(componentId, ops, options) {
98534
+ return await this.adapter.patchComponents([{ componentId, ops }], options);
98535
+ }
99690
98536
  async patchComponents(updates, options) {
99691
98537
  return await this.adapter.patchComponents(updates, options);
99692
98538
  }
99693
- async patchComponent(componentId, ops, options) {
99694
- await this.adapter.patchComponents([{ componentId, ops }], options);
99695
- }
99696
98539
  async patchComponentField(componentId, op, options) {
99697
- await this.adapter.patchComponents([{ componentId, ops: [op] }], options);
98540
+ return await this.adapter.patchComponents([{ componentId, ops: [op] }], options);
99698
98541
  }
99699
98542
  async getComponentsByType(type, agentId, options) {
99700
98543
  const entities = await this.adapter.queryEntities({
@@ -99738,6 +98581,9 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99738
98581
  async getRelationshipsByIds(relationshipIds) {
99739
98582
  return await this.adapter.getRelationshipsByIds(relationshipIds);
99740
98583
  }
98584
+ async getRelationshipsByPairs(pairs) {
98585
+ return await this.adapter.getRelationshipsByPairs(pairs);
98586
+ }
99741
98587
  async updateRelationships(relationships) {
99742
98588
  return await this.adapter.updateRelationships(relationships);
99743
98589
  }
@@ -99749,8 +98595,8 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99749
98595
  return ids.length > 0;
99750
98596
  }
99751
98597
  async getRelationship(params) {
99752
- const [rel] = await this.adapter.getRelationshipsByPairs([params]);
99753
- return rel ?? null;
98598
+ const results = await this.adapter.getRelationshipsByPairs([params]);
98599
+ return results[0] ?? null;
99754
98600
  }
99755
98601
  async updateRelationship(relationship) {
99756
98602
  return await this.adapter.updateRelationships([relationship]);
@@ -99894,26 +98740,23 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99894
98740
  }
99895
98741
  return await this.adapter.isReady();
99896
98742
  }
99897
- async getPairingRequests(queriesOrChannel, agentId) {
99898
- if (Array.isArray(queriesOrChannel)) {
99899
- return await this.adapter.getPairingRequests(queriesOrChannel);
99900
- }
99901
- if (agentId === undefined || agentId === null) {
99902
- return [];
99903
- }
99904
- const result = await this.adapter.getPairingRequests([
99905
- { channel: queriesOrChannel, agentId }
98743
+ async getPairingRequestsForChannel(channel, agentId) {
98744
+ const results = await this.adapter.getPairingRequests([
98745
+ { channel, agentId }
99906
98746
  ]);
99907
- return result[0]?.requests ?? [];
98747
+ return results[0]?.requests ?? [];
99908
98748
  }
99909
- async getPairingAllowlists(queries) {
99910
- return await this.adapter.getPairingAllowlists(queries);
98749
+ async getPairingRequests(queries) {
98750
+ return await this.adapter.getPairingRequests(queries);
99911
98751
  }
99912
- async getPairingAllowlist(channel, agentId) {
99913
- const result = await this.adapter.getPairingAllowlists([
98752
+ async getPairingAllowlistForChannel(channel, agentId) {
98753
+ const results = await this.adapter.getPairingAllowlists([
99914
98754
  { channel, agentId }
99915
98755
  ]);
99916
- return result[0]?.entries ?? [];
98756
+ return results[0]?.entries ?? [];
98757
+ }
98758
+ async getPairingAllowlists(queries) {
98759
+ return await this.adapter.getPairingAllowlists(queries);
99917
98760
  }
99918
98761
  async createPairingRequests(requests) {
99919
98762
  return await this.adapter.createPairingRequests(requests);
@@ -99950,6 +98793,221 @@ Please complete: ${diagnosis.missingFields.concat(diagnosis.invalidFields, diagn
99950
98793
  async deletePairingAllowlistEntry(id) {
99951
98794
  return await this.adapter.deletePairingAllowlistEntries([id]);
99952
98795
  }
98796
+ async deleteRoomsByWorldIds(worldIds) {
98797
+ return this.adapter.deleteRoomsByWorldIds(worldIds);
98798
+ }
98799
+ async getRoomsByWorlds(worldIds, limit, offset) {
98800
+ return this.adapter.getRoomsByWorlds(worldIds, limit, offset);
98801
+ }
98802
+ }
98803
+ // src/runtime-composition.ts
98804
+ init_utils5();
98805
+ function getBootstrapSettings(character, env2 = process.env) {
98806
+ const out = {};
98807
+ for (const [key, value] of Object.entries(env2)) {
98808
+ if (value !== undefined && value !== null && key) {
98809
+ out[key] = String(value);
98810
+ }
98811
+ }
98812
+ const settings2 = character.settings && typeof character.settings === "object" ? character.settings : {};
98813
+ for (const [key, value] of Object.entries(settings2)) {
98814
+ if (value === undefined || value === null)
98815
+ continue;
98816
+ if (key === "secrets" && typeof value === "object")
98817
+ continue;
98818
+ out[key] = typeof value === "string" ? value : String(value);
98819
+ }
98820
+ const secrets = character.settings?.secrets && typeof character.settings.secrets === "object" ? character.settings.secrets : {};
98821
+ for (const [key, value] of Object.entries(secrets)) {
98822
+ if (value !== undefined && value !== null) {
98823
+ out[key] = String(value);
98824
+ }
98825
+ }
98826
+ const topSecrets = character.secrets && typeof character.secrets === "object" ? character.secrets : {};
98827
+ for (const [key, value] of Object.entries(topSecrets)) {
98828
+ if (value !== undefined && value !== null) {
98829
+ out[key] = String(value);
98830
+ }
98831
+ }
98832
+ return out;
98833
+ }
98834
+ function mergeSettingsInto(character, agentRecord) {
98835
+ if (!agentRecord?.settings) {
98836
+ return character;
98837
+ }
98838
+ const mergedSettings = {
98839
+ ...agentRecord.settings,
98840
+ ...character.settings
98841
+ };
98842
+ const dbSecrets = agentRecord.secrets && typeof agentRecord.secrets === "object" ? agentRecord.secrets : {};
98843
+ const dbSettingsSecrets = agentRecord.settings.secrets && typeof agentRecord.settings.secrets === "object" ? agentRecord.settings.secrets : {};
98844
+ const characterSecrets = character.secrets && typeof character.secrets === "object" ? character.secrets : {};
98845
+ const characterSettingsSecrets = character.settings?.secrets && typeof character.settings.secrets === "object" ? character.settings.secrets : {};
98846
+ const mergedSecrets = {
98847
+ ...dbSecrets,
98848
+ ...dbSettingsSecrets,
98849
+ ...characterSecrets,
98850
+ ...characterSettingsSecrets
98851
+ };
98852
+ if (Object.keys(mergedSecrets).length > 0) {
98853
+ const filtered = {};
98854
+ for (const [key, value] of Object.entries(mergedSecrets)) {
98855
+ if (value !== null && value !== undefined) {
98856
+ filtered[key] = String(value);
98857
+ }
98858
+ }
98859
+ if (Object.keys(filtered).length > 0) {
98860
+ mergedSettings.secrets = filtered;
98861
+ }
98862
+ }
98863
+ return {
98864
+ ...character,
98865
+ settings: mergedSettings,
98866
+ secrets: Object.keys(mergedSecrets).length > 0 ? mergedSettings.secrets : character.secrets
98867
+ };
98868
+ }
98869
+ async function loadOneCharacterFromFile(filePath) {
98870
+ const loaded = await loadCharacterFile(filePath);
98871
+ if (loaded == null) {
98872
+ throw new Error(`Failed to load character file: ${filePath}`);
98873
+ }
98874
+ let character = importSecretsFromEnv(loaded, COMMON_SECRET_KEYS);
98875
+ character = ensureEncryptionSalt(character);
98876
+ if (!character.id) {
98877
+ character = {
98878
+ ...character,
98879
+ id: stringToUuid(character.name ?? "eliza")
98880
+ };
98881
+ }
98882
+ return character;
98883
+ }
98884
+ function loadOneCharacterFromObject(input) {
98885
+ const character = parseCharacter(input);
98886
+ let out = importSecretsFromEnv(character, COMMON_SECRET_KEYS);
98887
+ out = ensureEncryptionSalt(out);
98888
+ if (!out.id) {
98889
+ out = { ...out, id: stringToUuid(out.name ?? "eliza") };
98890
+ }
98891
+ return out;
98892
+ }
98893
+ async function loadCharacters(sources) {
98894
+ if (sources.length === 0) {
98895
+ return [];
98896
+ }
98897
+ const results = [];
98898
+ for (const source of sources) {
98899
+ if (typeof source === "string") {
98900
+ const character = await loadOneCharacterFromFile(source);
98901
+ results.push(character);
98902
+ } else {
98903
+ const character = loadOneCharacterFromObject(source);
98904
+ results.push(character);
98905
+ }
98906
+ }
98907
+ return results;
98908
+ }
98909
+ async function createRuntimes(characters, options) {
98910
+ if (characters.length === 0) {
98911
+ return [];
98912
+ }
98913
+ const pluginNames = new Set;
98914
+ for (const c of characters) {
98915
+ for (const p of c.plugins ?? []) {
98916
+ if (typeof p === "string")
98917
+ pluginNames.add(p);
98918
+ }
98919
+ }
98920
+ const pluginInput = [...pluginNames];
98921
+ if (options?.sharedPlugins?.length) {
98922
+ pluginInput.push(...options.sharedPlugins);
98923
+ }
98924
+ const resolvedPlugins = await resolvePlugins(pluginInput);
98925
+ const agentIds = [];
98926
+ for (const c of characters) {
98927
+ agentIds.push(c.id ?? stringToUuid(c.name ?? "eliza"));
98928
+ }
98929
+ let adapters;
98930
+ if (options?.adapter) {
98931
+ const defaultAdapter = options.adapter;
98932
+ adapters = characters.map(() => defaultAdapter);
98933
+ } else {
98934
+ const adapterPlugin = resolvedPlugins.find((p) => typeof p.adapter === "function");
98935
+ if (!adapterPlugin) {
98936
+ const first = characters[0];
98937
+ const nameOrId = first?.name ?? first?.id ?? "unknown";
98938
+ throw new Error(`No plugin provides a database adapter for character ${String(nameOrId)}`);
98939
+ }
98940
+ adapters = await Promise.all(characters.map((c) => {
98941
+ const agentId = c.id ?? stringToUuid(c.name ?? "eliza");
98942
+ const settings2 = getBootstrapSettings(c);
98943
+ return Promise.resolve(adapterPlugin.adapter(agentId, settings2));
98944
+ }));
98945
+ }
98946
+ const seenAdapters = new Set;
98947
+ for (const adapter2 of adapters) {
98948
+ if (seenAdapters.has(adapter2))
98949
+ continue;
98950
+ seenAdapters.add(adapter2);
98951
+ if (!await adapter2.isReady()) {
98952
+ await adapter2.initialize();
98953
+ }
98954
+ }
98955
+ const adapterToAgentIds = new Map;
98956
+ for (let i = 0;i < characters.length; i++) {
98957
+ const adapter2 = adapters[i];
98958
+ const agentId = agentIds[i];
98959
+ if (!adapter2 || !agentId) {
98960
+ throw new Error(`Missing adapter or agentId for character index ${i}`);
98961
+ }
98962
+ const list2 = adapterToAgentIds.get(adapter2) ?? [];
98963
+ list2.push(agentId);
98964
+ adapterToAgentIds.set(adapter2, list2);
98965
+ }
98966
+ const agentIdToRecord = new Map;
98967
+ for (const [adapter2, ids] of adapterToAgentIds) {
98968
+ const agents = await adapter2.getAgentsByIds(ids);
98969
+ for (const agent2 of agents) {
98970
+ if (agent2?.id)
98971
+ agentIdToRecord.set(agent2.id, agent2);
98972
+ }
98973
+ }
98974
+ const mergedCharacters = characters.map((c, i) => {
98975
+ const agentId = agentIds[i];
98976
+ if (!agentId) {
98977
+ throw new Error(`Missing agentId for character index ${i}`);
98978
+ }
98979
+ const record = agentIdToRecord.get(agentId) ?? null;
98980
+ return mergeSettingsInto(c, record);
98981
+ });
98982
+ const runtimes = mergedCharacters.map((char, i) => {
98983
+ const adapter2 = adapters[i];
98984
+ if (!adapter2) {
98985
+ throw new Error(`Missing adapter for character index ${i}`);
98986
+ }
98987
+ return new AgentRuntime({
98988
+ character: char,
98989
+ adapter: adapter2,
98990
+ plugins: resolvedPlugins,
98991
+ logLevel: options?.logLevel,
98992
+ settings: options?.settings
98993
+ });
98994
+ });
98995
+ await Promise.all(runtimes.map((r) => r.initialize()));
98996
+ if (options?.provision) {
98997
+ const seenAdaptersForMigrations = new Set;
98998
+ for (const r of runtimes) {
98999
+ const adapter2 = r.adapter;
99000
+ if (adapter2 && !seenAdaptersForMigrations.has(adapter2)) {
99001
+ seenAdaptersForMigrations.add(adapter2);
99002
+ await runPluginMigrations(r);
99003
+ }
99004
+ }
99005
+ for (const r of runtimes) {
99006
+ await ensureAgentInfrastructure(r);
99007
+ await ensureEmbeddingDimension(r);
99008
+ }
99009
+ }
99010
+ return runtimes;
99953
99011
  }
99954
99012
  // src/schemas/index.ts
99955
99013
  init_schemas();
@@ -102437,7 +101495,7 @@ class ApprovalService extends Service {
102437
101495
  }
102438
101496
  }
102439
101497
  async function requestConfirmation(runtime2, params) {
102440
- const service3 = runtime2.getService(ServiceType2.APPROVAL);
101498
+ const service3 = await runtime2.getService(ServiceType2.APPROVAL);
102441
101499
  if (!service3) {
102442
101500
  logger.warn("ApprovalService not available, auto-denying");
102443
101501
  return false;
@@ -104457,16 +103515,16 @@ class PairingService extends Service {
104457
103515
  // src/services/pairing-integration.ts
104458
103516
  init_pairing();
104459
103517
  init_service();
104460
- function getPairingService(runtime2) {
103518
+ async function getPairingService(runtime2) {
104461
103519
  try {
104462
- return runtime2.getService(ServiceType2.PAIRING);
103520
+ return await runtime2.getService(ServiceType2.PAIRING);
104463
103521
  } catch {
104464
103522
  return null;
104465
103523
  }
104466
103524
  }
104467
103525
  async function checkPairingAllowed(runtime2, params) {
104468
103526
  const { channel, senderId, metadata, suppressReply } = params;
104469
- const pairingService = getPairingService(runtime2);
103527
+ const pairingService = await getPairingService(runtime2);
104470
103528
  if (!pairingService) {
104471
103529
  runtime2.logger.warn({ src: "pairing-integration", channel }, "PairingService not available, allowing message by default");
104472
103530
  return { allowed: true };
@@ -104514,7 +103572,7 @@ function buildPairingReplyMessage(params) {
104514
103572
  `);
104515
103573
  }
104516
103574
  async function addToAllowlist(runtime2, channel, senderId, metadata) {
104517
- const pairingService = getPairingService(runtime2);
103575
+ const pairingService = await getPairingService(runtime2);
104518
103576
  if (!pairingService) {
104519
103577
  runtime2.logger.warn({ src: "pairing-integration", channel }, "PairingService not available");
104520
103578
  return false;
@@ -104523,21 +103581,21 @@ async function addToAllowlist(runtime2, channel, senderId, metadata) {
104523
103581
  return true;
104524
103582
  }
104525
103583
  async function removeFromAllowlist(runtime2, channel, senderId) {
104526
- const pairingService = getPairingService(runtime2);
103584
+ const pairingService = await getPairingService(runtime2);
104527
103585
  if (!pairingService) {
104528
103586
  return false;
104529
103587
  }
104530
103588
  return pairingService.removeFromAllowlist(channel, senderId);
104531
103589
  }
104532
103590
  async function isInAllowlist(runtime2, channel, senderId) {
104533
- const pairingService = getPairingService(runtime2);
103591
+ const pairingService = await getPairingService(runtime2);
104534
103592
  if (!pairingService) {
104535
103593
  return false;
104536
103594
  }
104537
103595
  return pairingService.isAllowed(channel, senderId);
104538
103596
  }
104539
103597
  async function approvePairingCode(runtime2, channel, code2) {
104540
- const pairingService = getPairingService(runtime2);
103598
+ const pairingService = await getPairingService(runtime2);
104541
103599
  if (!pairingService) {
104542
103600
  return null;
104543
103601
  }
@@ -104561,9 +103619,9 @@ function isExpired(request, now, ttlMs) {
104561
103619
  return true;
104562
103620
  return now.getTime() - createdAt.getTime() > ttlMs;
104563
103621
  }
104564
- function getPairingService2(runtime2) {
103622
+ async function getPairingService2(runtime2) {
104565
103623
  try {
104566
- return runtime2.getService(ServiceType2.PAIRING);
103624
+ return await runtime2.getService(ServiceType2.PAIRING);
104567
103625
  } catch {
104568
103626
  return null;
104569
103627
  }
@@ -104575,7 +103633,7 @@ async function migrateChannelPairingData(runtime2, channel, pairingData, allowli
104575
103633
  allowlistEntriesMigrated: 0,
104576
103634
  errors: []
104577
103635
  };
104578
- const pairingService = getPairingService2(runtime2);
103636
+ const pairingService = await getPairingService2(runtime2);
104579
103637
  if (!pairingService) {
104580
103638
  result.errors.push("PairingService not available");
104581
103639
  return result;
@@ -106527,6 +105585,7 @@ export {
106527
105585
  runWithStreamingContext,
106528
105586
  runPreRegisterHooks,
106529
105587
  runPostRegisterHooks,
105588
+ runPluginMigrations,
106530
105589
  runNonInteractiveOnboarding,
106531
105590
  roomSchema,
106532
105591
  roleProvider,
@@ -106588,6 +105647,7 @@ export {
106588
105647
  readSessionUpdatedAt,
106589
105648
  readPackageManifest,
106590
105649
  randomBytes,
105650
+ provisionAgent,
106591
105651
  providersProvider,
106592
105652
  exports_proto as proto,
106593
105653
  processAttachments,
@@ -106637,8 +105697,10 @@ export {
106637
105697
  messageExampleGroupSchema,
106638
105698
  messageClassifierTemplate,
106639
105699
  mergeToolPolicies,
105700
+ mergeSettingsInto,
106640
105701
  mergeSessionEntry,
106641
105702
  mergeHybridResults,
105703
+ mergeDbSettings,
106642
105704
  mergeCharacterSecrets,
106643
105705
  mergeCharacterDefaults,
106644
105706
  memorySchema,
@@ -106666,6 +105728,7 @@ export {
106666
105728
  loadPluginManifest,
106667
105729
  loadPlugin,
106668
105730
  loadEnvFile,
105731
+ loadCharacters,
106669
105732
  loadCharacterTs,
106670
105733
  loadCharacterJson,
106671
105734
  loadCharacterFile,
@@ -106776,6 +105839,7 @@ export {
106776
105839
  getCharactersDir,
106777
105840
  getCharacterSecret,
106778
105841
  getCharacterPaths,
105842
+ getBootstrapSettings,
106779
105843
  getBooleanEnv,
106780
105844
  getAllSecretsForChannel,
106781
105845
  getAllElizaPaths,
@@ -106818,6 +105882,10 @@ export {
106818
105882
  entitiesProvider,
106819
105883
  ensureSafeSessionPath,
106820
105884
  ensureEncryptionSalt,
105885
+ ensureEmbeddingDimension,
105886
+ ensureConnections,
105887
+ ensureConnection,
105888
+ ensureAgentInfrastructure,
106821
105889
  encryptedCharacter,
106822
105890
  encryptStringValue,
106823
105891
  encryptObjectValues,
@@ -106852,6 +105920,7 @@ export {
106852
105920
  createService,
106853
105921
  createSendPolicyProvider,
106854
105922
  createSecretsRedactor,
105923
+ createRuntimes,
106855
105924
  createPluginFilterHook,
106856
105925
  createPinnedLookup,
106857
105926
  createOnboardingStateMachine,
@@ -106987,7 +106056,7 @@ export {
106987
106056
  ServiceBuilder,
106988
106057
  Service,
106989
106058
  ServerHealthError,
106990
- Semaphore2 as Semaphore,
106059
+ Semaphore,
106991
106060
  STANDARD_OPTIONS,
106992
106061
  SOCKET_MESSAGE_TYPE,
106993
106062
  SHOULD_UNMUTE_ROOM_TEMPLATE,
@@ -107103,5 +106172,5 @@ export {
107103
106172
  ADD_CONTACT_TEMPLATE
107104
106173
  };
107105
106174
 
107106
- //# debugId=365C1C6680C0DFED64756E2164756E21
106175
+ //# debugId=505860FDDB63A26A64756E2164756E21
107107
106176
  //# sourceMappingURL=index.node.js.map