@elizaos/core 1.6.5 → 1.7.0-beta.0

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 (81) hide show
  1. package/dist/browser/index.browser.js +121 -121
  2. package/dist/browser/index.browser.js.map +32 -29
  3. package/dist/database.d.ts +4 -7
  4. package/dist/database.d.ts.map +1 -1
  5. package/dist/elizaos.d.ts +13 -54
  6. package/dist/elizaos.d.ts.map +1 -1
  7. package/dist/entities.d.ts +0 -8
  8. package/dist/entities.d.ts.map +1 -1
  9. package/dist/index.browser.d.ts +1 -0
  10. package/dist/index.browser.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.node.d.ts +2 -0
  14. package/dist/index.node.d.ts.map +1 -1
  15. package/dist/logger.d.ts +26 -0
  16. package/dist/logger.d.ts.map +1 -1
  17. package/dist/node/index.node.js +1377 -1116
  18. package/dist/node/index.node.js.map +34 -31
  19. package/dist/plugin.d.ts.map +1 -1
  20. package/dist/roles.d.ts +0 -6
  21. package/dist/roles.d.ts.map +1 -1
  22. package/dist/runtime.d.ts +22 -19
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/schemas/character.d.ts +2 -2
  25. package/dist/schemas/character.d.ts.map +1 -1
  26. package/dist/search.d.ts +8 -8
  27. package/dist/search.d.ts.map +1 -1
  28. package/dist/services/default-message-service.d.ts.map +1 -1
  29. package/dist/services/message-service.d.ts +11 -2
  30. package/dist/services/message-service.d.ts.map +1 -1
  31. package/dist/services.d.ts +10 -2
  32. package/dist/services.d.ts.map +1 -1
  33. package/dist/settings.d.ts +9 -9
  34. package/dist/settings.d.ts.map +1 -1
  35. package/dist/streaming-context.browser.d.ts +27 -0
  36. package/dist/streaming-context.browser.d.ts.map +1 -0
  37. package/dist/streaming-context.d.ts +79 -0
  38. package/dist/streaming-context.d.ts.map +1 -0
  39. package/dist/streaming-context.node.d.ts +16 -0
  40. package/dist/streaming-context.node.d.ts.map +1 -0
  41. package/dist/types/agent.d.ts +1 -1
  42. package/dist/types/agent.d.ts.map +1 -1
  43. package/dist/types/components.d.ts +2 -2
  44. package/dist/types/components.d.ts.map +1 -1
  45. package/dist/types/database.d.ts +93 -8
  46. package/dist/types/database.d.ts.map +1 -1
  47. package/dist/types/elizaos.d.ts +53 -25
  48. package/dist/types/elizaos.d.ts.map +1 -1
  49. package/dist/types/events.d.ts +15 -4
  50. package/dist/types/events.d.ts.map +1 -1
  51. package/dist/types/index.d.ts +2 -1
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/dist/types/messaging.d.ts +51 -0
  54. package/dist/types/messaging.d.ts.map +1 -1
  55. package/dist/types/model.d.ts +119 -12
  56. package/dist/types/model.d.ts.map +1 -1
  57. package/dist/types/plugin.d.ts +35 -7
  58. package/dist/types/plugin.d.ts.map +1 -1
  59. package/dist/types/primitives.d.ts +6 -0
  60. package/dist/types/primitives.d.ts.map +1 -1
  61. package/dist/types/runtime.d.ts +35 -14
  62. package/dist/types/runtime.d.ts.map +1 -1
  63. package/dist/types/service.d.ts +7 -5
  64. package/dist/types/service.d.ts.map +1 -1
  65. package/dist/types/settings.d.ts +2 -2
  66. package/dist/types/settings.d.ts.map +1 -1
  67. package/dist/types/state.d.ts +42 -7
  68. package/dist/types/state.d.ts.map +1 -1
  69. package/dist/types/streaming.d.ts +46 -0
  70. package/dist/types/streaming.d.ts.map +1 -0
  71. package/dist/utils/buffer.d.ts +1 -1
  72. package/dist/utils/buffer.d.ts.map +1 -1
  73. package/dist/utils/crypto-compat.d.ts.map +1 -1
  74. package/dist/utils/environment.d.ts.map +1 -1
  75. package/dist/utils/paths.d.ts.map +1 -1
  76. package/dist/utils/server-health.d.ts.map +1 -1
  77. package/dist/utils/streaming.d.ts +116 -0
  78. package/dist/utils/streaming.d.ts.map +1 -0
  79. package/dist/utils.d.ts +10 -4
  80. package/dist/utils.d.ts.map +1 -1
  81. package/package.json +3 -3
@@ -25135,6 +25135,45 @@ https://github.com/browserify/crypto-browserify`);
25135
25135
  };
25136
25136
  });
25137
25137
 
25138
+ // src/streaming-context.ts
25139
+ class NoopContextManager {
25140
+ run(_context, fn) {
25141
+ return fn();
25142
+ }
25143
+ active() {
25144
+ return;
25145
+ }
25146
+ }
25147
+ var globalContextManager = new NoopContextManager;
25148
+ function setStreamingContextManager(manager) {
25149
+ globalContextManager = manager;
25150
+ }
25151
+ function getStreamingContextManager() {
25152
+ return globalContextManager;
25153
+ }
25154
+ function runWithStreamingContext(context, fn) {
25155
+ return globalContextManager.run(context, fn);
25156
+ }
25157
+ function getStreamingContext() {
25158
+ return globalContextManager.active();
25159
+ }
25160
+
25161
+ // src/streaming-context.node.ts
25162
+ import { AsyncLocalStorage } from "async_hooks";
25163
+
25164
+ class AsyncLocalStorageContextManager {
25165
+ storage = new AsyncLocalStorage;
25166
+ run(context, fn) {
25167
+ return this.storage.run(context, fn);
25168
+ }
25169
+ active() {
25170
+ return this.storage.getStore();
25171
+ }
25172
+ }
25173
+ function createNodeStreamingContextManager() {
25174
+ return new AsyncLocalStorageContextManager;
25175
+ }
25176
+
25138
25177
  // src/types/primitives.ts
25139
25178
  function asUUID(id) {
25140
25179
  if (!id || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
@@ -25151,16 +25190,6 @@ var ContentType;
25151
25190
  ContentType2["LINK"] = "link";
25152
25191
  })(ContentType ||= {});
25153
25192
 
25154
- // src/types/memory.ts
25155
- var MemoryType;
25156
- ((MemoryType2) => {
25157
- MemoryType2["DOCUMENT"] = "document";
25158
- MemoryType2["FRAGMENT"] = "fragment";
25159
- MemoryType2["MESSAGE"] = "message";
25160
- MemoryType2["DESCRIPTION"] = "description";
25161
- MemoryType2["CUSTOM"] = "custom";
25162
- })(MemoryType ||= {});
25163
-
25164
25193
  // src/types/environment.ts
25165
25194
  var Role;
25166
25195
  ((Role2) => {
@@ -25182,6 +25211,16 @@ var ChannelType;
25182
25211
  ChannelType2["API"] = "API";
25183
25212
  })(ChannelType ||= {});
25184
25213
 
25214
+ // src/types/memory.ts
25215
+ var MemoryType;
25216
+ ((MemoryType2) => {
25217
+ MemoryType2["DOCUMENT"] = "document";
25218
+ MemoryType2["FRAGMENT"] = "fragment";
25219
+ MemoryType2["MESSAGE"] = "message";
25220
+ MemoryType2["DESCRIPTION"] = "description";
25221
+ MemoryType2["CUSTOM"] = "custom";
25222
+ })(MemoryType ||= {});
25223
+
25185
25224
  // src/types/agent.ts
25186
25225
  var AgentStatus;
25187
25226
  ((AgentStatus2) => {
@@ -25342,6 +25381,15 @@ var MODEL_SETTINGS = {
25342
25381
  MODEL_FREQ_PENALTY: "MODEL_FREQ_PENALTY",
25343
25382
  MODEL_PRESENCE_PENALTY: "MODEL_PRESENCE_PENALTY"
25344
25383
  };
25384
+ function isStreamableModelType(modelType) {
25385
+ return [
25386
+ ModelType.TEXT_SMALL,
25387
+ ModelType.TEXT_LARGE,
25388
+ ModelType.TEXT_REASONING_SMALL,
25389
+ ModelType.TEXT_REASONING_LARGE,
25390
+ ModelType.TEXT_COMPLETION
25391
+ ].includes(modelType);
25392
+ }
25345
25393
 
25346
25394
  // src/types/database.ts
25347
25395
  var VECTOR_DIMS = {
@@ -25384,6 +25432,7 @@ var EventType;
25384
25432
  EventType2["EMBEDDING_GENERATION_REQUESTED"] = "EMBEDDING_GENERATION_REQUESTED";
25385
25433
  EventType2["EMBEDDING_GENERATION_COMPLETED"] = "EMBEDDING_GENERATION_COMPLETED";
25386
25434
  EventType2["EMBEDDING_GENERATION_FAILED"] = "EMBEDDING_GENERATION_FAILED";
25435
+ EventType2["CONTROL_MESSAGE"] = "CONTROL_MESSAGE";
25387
25436
  })(EventType ||= {});
25388
25437
  var PlatformPrefix;
25389
25438
  ((PlatformPrefix2) => {
@@ -25415,6 +25464,11 @@ var SOCKET_MESSAGE_TYPE;
25415
25464
  SOCKET_MESSAGE_TYPE2[SOCKET_MESSAGE_TYPE2["THINKING"] = 5] = "THINKING";
25416
25465
  SOCKET_MESSAGE_TYPE2[SOCKET_MESSAGE_TYPE2["CONTROL"] = 6] = "CONTROL";
25417
25466
  })(SOCKET_MESSAGE_TYPE ||= {});
25467
+ var MESSAGE_STREAM_EVENT = {
25468
+ messageStreamChunk: "messageStreamChunk",
25469
+ messageStreamError: "messageStreamError",
25470
+ messageBroadcast: "messageBroadcast"
25471
+ };
25418
25472
  // ../../node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js
25419
25473
  var __defProp2 = Object.defineProperty;
25420
25474
  var __export = (target, all) => {
@@ -41565,7 +41619,7 @@ function detectEnvironment() {
41565
41619
  if (typeof process !== "undefined" && process.versions && process.versions.node) {
41566
41620
  return "node";
41567
41621
  }
41568
- if (typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.window.document !== "undefined") {
41622
+ if (typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.window?.document !== "undefined") {
41569
41623
  return "browser";
41570
41624
  }
41571
41625
  return "unknown";
@@ -41574,11 +41628,13 @@ function detectEnvironment() {
41574
41628
  class BrowserEnvironmentStore {
41575
41629
  store = {};
41576
41630
  constructor() {
41577
- if (typeof globalThis !== "undefined" && globalThis.window && globalThis.window.ENV) {
41578
- this.store = { ...globalThis.window.ENV };
41631
+ const windowWithEnv = globalThis;
41632
+ if (typeof globalThis !== "undefined" && windowWithEnv.window && windowWithEnv.window.ENV) {
41633
+ this.store = { ...windowWithEnv.window.ENV };
41579
41634
  }
41580
- if (typeof globalThis !== "undefined" && globalThis.__ENV__) {
41581
- this.store = { ...this.store, ...globalThis.__ENV__ };
41635
+ const globalWithEnv = globalThis;
41636
+ if (typeof globalThis !== "undefined" && globalWithEnv.__ENV__) {
41637
+ this.store = { ...this.store, ...globalWithEnv.__ENV__ };
41582
41638
  }
41583
41639
  }
41584
41640
  get(key) {
@@ -41751,26 +41807,19 @@ function loadEnvFile(envPath) {
41751
41807
  if (typeof process === "undefined" || !process.cwd) {
41752
41808
  return false;
41753
41809
  }
41754
- try {
41755
- const dotenv = __require("dotenv");
41756
- const resolvedPath = envPath || findEnvFile();
41757
- if (!resolvedPath) {
41758
- return false;
41759
- }
41760
- const result = dotenv.config({ path: resolvedPath });
41761
- if (result.error) {
41762
- if (typeof console !== "undefined" && console.warn) {
41763
- console.warn(`Failed to parse .env file at ${resolvedPath}:`, result.error);
41764
- }
41765
- return false;
41766
- }
41767
- return true;
41768
- } catch (error) {
41810
+ const dotenv = __require("dotenv");
41811
+ const resolvedPath = envPath || findEnvFile();
41812
+ if (!resolvedPath) {
41813
+ return false;
41814
+ }
41815
+ const result = dotenv.config({ path: resolvedPath });
41816
+ if (result.error) {
41769
41817
  if (typeof console !== "undefined" && console.warn) {
41770
- console.warn("Failed to load .env file:", error);
41818
+ console.warn(`Failed to parse .env file at ${resolvedPath}:`, result.error);
41771
41819
  }
41772
41820
  return false;
41773
41821
  }
41822
+ return true;
41774
41823
  }
41775
41824
  // ../../node_modules/adze/dist/tools.js
41776
41825
  class Tools {
@@ -43491,6 +43540,14 @@ var import_fast_redact = __toESM(require_fast_redact(), 1);
43491
43540
  var __loggerTestHooks = {
43492
43541
  __noop: () => {}
43493
43542
  };
43543
+ var logListeners = new Set;
43544
+ function addLogListener(listener) {
43545
+ logListeners.add(listener);
43546
+ return () => logListeners.delete(listener);
43547
+ }
43548
+ function removeLogListener(listener) {
43549
+ logListeners.delete(listener);
43550
+ }
43494
43551
  var LOG_LEVEL_PRIORITY = {
43495
43552
  trace: 10,
43496
43553
  verbose: 10,
@@ -43635,6 +43692,11 @@ function createInMemoryDestination(maxLogs = 100) {
43635
43692
  if (logs.length > maxLogs) {
43636
43693
  logs.shift();
43637
43694
  }
43695
+ for (const listener of logListeners) {
43696
+ try {
43697
+ listener(entry);
43698
+ } catch {}
43699
+ }
43638
43700
  },
43639
43701
  clear() {
43640
43702
  logs.length = 0;
@@ -43790,12 +43852,8 @@ function sealAdze(base) {
43790
43852
  if (raw && !metaBase.hostname) {
43791
43853
  let hostname = "unknown";
43792
43854
  if (typeof process !== "undefined" && process.platform) {
43793
- try {
43794
- const os = __require("os");
43795
- hostname = os.hostname();
43796
- } catch {
43797
- hostname = "localhost";
43798
- }
43855
+ const os = __require("os");
43856
+ hostname = os.hostname();
43799
43857
  } else if (typeof window !== "undefined" && window.location) {
43800
43858
  hostname = window.location.hostname || "browser";
43801
43859
  }
@@ -43849,9 +43907,10 @@ function createLogger(bindings = false) {
43849
43907
  return;
43850
43908
  }
43851
43909
  const message = formatArgs(...args);
43852
- const consoleMethod = method === "fatal" ? "error" : method === "trace" || method === "verbose" ? "debug" : method === "success" || method === "progress" ? "info" : method === "log" ? "log" : console[method] ? method : "log";
43853
- if (typeof console[consoleMethod] === "function") {
43854
- console[consoleMethod](message);
43910
+ const consoleMethod = method === "fatal" ? "error" : method === "trace" || method === "verbose" ? "debug" : method === "success" || method === "progress" ? "info" : method === "log" ? "log" : (method in console) && typeof console[method] === "function" ? method : "log";
43911
+ const consoleFn = console[consoleMethod];
43912
+ if (consoleFn && typeof consoleFn === "function") {
43913
+ consoleFn(message);
43855
43914
  }
43856
43915
  };
43857
43916
  const safeRedact2 = (obj) => {
@@ -43905,27 +43964,25 @@ function createLogger(bindings = false) {
43905
43964
  return;
43906
43965
  }
43907
43966
  captureIfError(method, args);
43908
- try {
43909
- let msg = "";
43910
- if (args.length > 0) {
43911
- msg = args.map((arg) => {
43912
- if (typeof arg === "string")
43913
- return arg;
43914
- if (arg instanceof Error)
43915
- return arg.message;
43916
- return safeStringify(arg);
43917
- }).join(" ");
43918
- }
43919
- if (base.namespace) {
43920
- msg = `#${base.namespace} ${msg}`;
43921
- }
43922
- const entry = {
43923
- time: Date.now(),
43924
- level: LOG_LEVEL_PRIORITY[method.toLowerCase()] || LOG_LEVEL_PRIORITY.info,
43925
- msg
43926
- };
43927
- globalInMemoryDestination.write(entry);
43928
- } catch {}
43967
+ let msg = "";
43968
+ if (args.length > 0) {
43969
+ msg = args.map((arg) => {
43970
+ if (typeof arg === "string")
43971
+ return arg;
43972
+ if (arg instanceof Error)
43973
+ return arg.message;
43974
+ return safeStringify(arg);
43975
+ }).join(" ");
43976
+ }
43977
+ if (base.namespace) {
43978
+ msg = `#${base.namespace} ${msg}`;
43979
+ }
43980
+ const entry = {
43981
+ time: Date.now(),
43982
+ level: LOG_LEVEL_PRIORITY[method.toLowerCase()] || LOG_LEVEL_PRIORITY.info,
43983
+ msg
43984
+ };
43985
+ globalInMemoryDestination.write(entry);
43929
43986
  let adzeMethod = method;
43930
43987
  let adzeArgs = args;
43931
43988
  if (method === "fatal") {
@@ -43940,8 +43997,11 @@ function createLogger(bindings = false) {
43940
43997
  adzeMethod = "verbose";
43941
43998
  }
43942
43999
  try {
43943
- sealed[adzeMethod](...adzeArgs);
43944
- } catch (error2) {
44000
+ const sealedRecord = sealed;
44001
+ if (adzeMethod in sealedRecord && typeof sealedRecord[adzeMethod] === "function") {
44002
+ sealedRecord[adzeMethod](...adzeArgs);
44003
+ }
44004
+ } catch {
43945
44005
  console.log(`[${method.toUpperCase()}]`, ...args);
43946
44006
  }
43947
44007
  };
@@ -43985,11 +44045,9 @@ function createLogger(bindings = false) {
43985
44045
  const progress = (obj, msg, ...args) => invoke("progress", ...adaptArgs(obj, msg, ...args));
43986
44046
  const logFn = (obj, msg, ...args) => invoke("log", ...adaptArgs(obj, msg, ...args));
43987
44047
  const clear = () => {
43988
- try {
43989
- if (typeof console?.clear === "function") {
43990
- console.clear();
43991
- }
43992
- } catch {}
44048
+ if (typeof console?.clear === "function") {
44049
+ console.clear();
44050
+ }
43993
44051
  globalInMemoryDestination.clear();
43994
44052
  };
43995
44053
  const child = (childBindings) => {
@@ -44163,11 +44221,16 @@ var jsonBlockPattern = /```json\n([\s\S]*?)\n```/;
44163
44221
  function parseKeyValueXml(text) {
44164
44222
  if (!text)
44165
44223
  return null;
44166
- let xmlBlockMatch = text.match(/<response>([\s\S]*?)<\/response>/);
44167
- let xmlContent;
44168
- if (xmlBlockMatch) {
44169
- xmlContent = xmlBlockMatch[1];
44170
- } else {
44224
+ let xmlContent = null;
44225
+ const responseStart = text.indexOf("<response>");
44226
+ if (responseStart !== -1) {
44227
+ const contentStart = responseStart + "<response>".length;
44228
+ const responseEnd = text.indexOf("</response>", contentStart);
44229
+ if (responseEnd !== -1) {
44230
+ xmlContent = text.slice(contentStart, responseEnd);
44231
+ }
44232
+ }
44233
+ if (!xmlContent) {
44171
44234
  const findFirstXmlBlock = (input) => {
44172
44235
  let i = 0;
44173
44236
  const length = input.length;
@@ -44333,15 +44396,15 @@ function parseKeyValueXml(text) {
44333
44396
  return result;
44334
44397
  }
44335
44398
  function parseJSONObjectFromText(text) {
44336
- let jsonData = null;
44337
44399
  const jsonBlockMatch = text.match(jsonBlockPattern);
44400
+ let jsonData = null;
44338
44401
  try {
44339
44402
  if (jsonBlockMatch) {
44340
44403
  jsonData = JSON.parse(normalizeJsonString(jsonBlockMatch[1].trim()));
44341
44404
  } else {
44342
44405
  jsonData = JSON.parse(normalizeJsonString(text.trim()));
44343
44406
  }
44344
- } catch (_e) {
44407
+ } catch {
44345
44408
  return null;
44346
44409
  }
44347
44410
  if (jsonData && typeof jsonData === "object" && !Array.isArray(jsonData)) {
@@ -44394,14 +44457,16 @@ async function trimTokens(prompt, maxTokens, runtime) {
44394
44457
  if (maxTokens <= 0)
44395
44458
  throw new Error("maxTokens must be positive");
44396
44459
  const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, {
44397
- prompt
44460
+ prompt,
44461
+ modelType: ModelType.TEXT_TOKENIZER_ENCODE
44398
44462
  });
44399
44463
  if (tokens.length <= maxTokens) {
44400
44464
  return prompt;
44401
44465
  }
44402
44466
  const truncatedTokens = tokens.slice(-maxTokens);
44403
44467
  return await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, {
44404
- tokens: truncatedTokens
44468
+ tokens: truncatedTokens,
44469
+ modelType: ModelType.TEXT_TOKENIZER_DECODE
44405
44470
  });
44406
44471
  }
44407
44472
  function safeReplacer() {
@@ -44469,12 +44534,10 @@ var webCryptoAvailable = null;
44469
44534
  function checkWebCrypto() {
44470
44535
  if (webCryptoAvailable !== null)
44471
44536
  return webCryptoAvailable;
44472
- try {
44473
- if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.digest === "function") {
44474
- webCryptoAvailable = true;
44475
- return true;
44476
- }
44477
- } catch {}
44537
+ if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.digest === "function") {
44538
+ webCryptoAvailable = true;
44539
+ return true;
44540
+ }
44478
44541
  webCryptoAvailable = false;
44479
44542
  return false;
44480
44543
  }
@@ -44497,12 +44560,10 @@ function getCachedSha1(message) {
44497
44560
  }
44498
44561
  async function sha1BytesAsync(message) {
44499
44562
  if (checkWebCrypto()) {
44500
- try {
44501
- const encoder2 = new TextEncoder;
44502
- const data2 = encoder2.encode(message);
44503
- const hashBuffer = await globalThis.crypto.subtle.digest("SHA-1", data2);
44504
- return new Uint8Array(hashBuffer);
44505
- } catch {}
44563
+ const encoder2 = new TextEncoder;
44564
+ const data2 = encoder2.encode(message);
44565
+ const hashBuffer = await globalThis.crypto.subtle.digest("SHA-1", data2);
44566
+ return new Uint8Array(hashBuffer);
44506
44567
  }
44507
44568
  return sha1Bytes(message);
44508
44569
  }
@@ -44667,7 +44728,7 @@ var styleSchema = z3.object({
44667
44728
  chat: z3.array(z3.string()).optional().describe("Style guidelines specific to chat/conversation responses"),
44668
44729
  post: z3.array(z3.string()).optional().describe("Style guidelines specific to social media posts")
44669
44730
  }).optional().describe("Style configuration defining how the character communicates across different contexts");
44670
- var settingsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.boolean(), z3.number(), z3.object({}).loose(), z3.array(z3.any())])).optional().describe("Character-specific settings like avatar URL, preferences, and configuration");
44731
+ var settingsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.boolean(), z3.number(), z3.object({}).loose(), z3.array(z3.unknown())])).optional().describe("Character-specific settings like avatar URL, preferences, and configuration");
44671
44732
  var secretsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.boolean(), z3.number()])).optional().describe("Secret values and API keys (should not be committed to version control)");
44672
44733
  var characterSchema = z3.object({
44673
44734
  id: uuidSchema2.optional().describe("Unique identifier for the character"),
@@ -44787,7 +44848,14 @@ function isBuffer(obj) {
44787
44848
  if (hasNativeBuffer() && Buffer.isBuffer(obj)) {
44788
44849
  return true;
44789
44850
  }
44790
- return obj instanceof Uint8Array || obj instanceof ArrayBuffer || typeof obj === "object" && obj.buffer instanceof ArrayBuffer && typeof obj.byteLength === "number" && !Array.isArray(obj);
44851
+ if (obj instanceof Uint8Array || obj instanceof ArrayBuffer) {
44852
+ return true;
44853
+ }
44854
+ if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
44855
+ const typedObj = obj;
44856
+ return typedObj.buffer instanceof ArrayBuffer && typeof typedObj.byteLength === "number";
44857
+ }
44858
+ return false;
44791
44859
  }
44792
44860
  function alloc(size) {
44793
44861
  if (hasNativeBuffer()) {
@@ -44867,13 +44935,267 @@ var BufferUtils = {
44867
44935
  byteLength,
44868
44936
  randomBytes
44869
44937
  };
44938
+ // src/utils/streaming.ts
44939
+ class StreamError extends Error {
44940
+ code;
44941
+ details;
44942
+ constructor(code, message, details) {
44943
+ super(message);
44944
+ this.name = "StreamError";
44945
+ this.code = code;
44946
+ this.details = details;
44947
+ }
44948
+ static isStreamError(error) {
44949
+ return error instanceof StreamError;
44950
+ }
44951
+ }
44952
+ var SAFE_MARGIN = 10;
44953
+ var MAX_BUFFER = 100 * 1024;
44954
+ var MAX_CHUNK_SIZE = 1024 * 1024;
44955
+ var ACTIONS_REGEX = /<actions>([\s\S]*?)<\/actions>/;
44956
+ function extractTagContent(buffer, openTag, closeTag, insideTag, safeMargin = SAFE_MARGIN) {
44957
+ let currentBuffer = buffer;
44958
+ let currentInsideTag = insideTag;
44959
+ if (!currentInsideTag) {
44960
+ const idx = currentBuffer.indexOf(openTag);
44961
+ if (idx !== -1) {
44962
+ currentInsideTag = true;
44963
+ currentBuffer = currentBuffer.slice(idx + openTag.length);
44964
+ } else {
44965
+ return { content: "", closed: false, buffer: currentBuffer, insideTag: false };
44966
+ }
44967
+ }
44968
+ const closeIdx = currentBuffer.indexOf(closeTag);
44969
+ if (closeIdx !== -1) {
44970
+ const content = currentBuffer.slice(0, closeIdx);
44971
+ const newBuffer = currentBuffer.slice(closeIdx + closeTag.length);
44972
+ return { content, closed: true, buffer: newBuffer, insideTag: false };
44973
+ }
44974
+ if (currentBuffer.length > safeMargin) {
44975
+ const content = currentBuffer.slice(0, -safeMargin);
44976
+ const newBuffer = currentBuffer.slice(-safeMargin);
44977
+ return { content, closed: false, buffer: newBuffer, insideTag: true };
44978
+ }
44979
+ return { content: "", closed: false, buffer: currentBuffer, insideTag: true };
44980
+ }
44981
+ function validateChunkSize(chunk) {
44982
+ if (chunk.length > MAX_CHUNK_SIZE) {
44983
+ throw new StreamError("CHUNK_TOO_LARGE", `Chunk size ${chunk.length} exceeds maximum allowed ${MAX_CHUNK_SIZE}`, {
44984
+ chunkSize: chunk.length,
44985
+ maxAllowed: MAX_CHUNK_SIZE
44986
+ });
44987
+ }
44988
+ }
44989
+ function trimBuffer(buffer, maxSize = MAX_BUFFER, keepSize = 1024) {
44990
+ if (buffer.length > maxSize) {
44991
+ return buffer.slice(-keepSize);
44992
+ }
44993
+ return buffer;
44994
+ }
44995
+
44996
+ class PassthroughExtractor {
44997
+ get done() {
44998
+ return false;
44999
+ }
45000
+ push(chunk) {
45001
+ validateChunkSize(chunk);
45002
+ return chunk;
45003
+ }
45004
+ reset() {}
45005
+ }
45006
+
45007
+ class XmlTagExtractor {
45008
+ openTag;
45009
+ closeTag;
45010
+ buffer = "";
45011
+ insideTag = false;
45012
+ finished = false;
45013
+ constructor(tagName) {
45014
+ this.openTag = `<${tagName}>`;
45015
+ this.closeTag = `</${tagName}>`;
45016
+ }
45017
+ get done() {
45018
+ return this.finished;
45019
+ }
45020
+ push(chunk) {
45021
+ if (this.finished)
45022
+ return "";
45023
+ validateChunkSize(chunk);
45024
+ this.buffer += chunk;
45025
+ if (!this.insideTag) {
45026
+ this.buffer = trimBuffer(this.buffer);
45027
+ }
45028
+ const result = extractTagContent(this.buffer, this.openTag, this.closeTag, this.insideTag, SAFE_MARGIN);
45029
+ this.buffer = result.buffer;
45030
+ this.insideTag = result.insideTag;
45031
+ if (result.closed) {
45032
+ this.finished = true;
45033
+ }
45034
+ return result.content;
45035
+ }
45036
+ reset() {
45037
+ this.buffer = "";
45038
+ this.insideTag = false;
45039
+ this.finished = false;
45040
+ }
45041
+ }
45042
+
45043
+ class ResponseStreamExtractor {
45044
+ static STREAM_TAGS = ["text"];
45045
+ buffer = "";
45046
+ insideTag = false;
45047
+ currentTag = null;
45048
+ finished = false;
45049
+ responseStrategy = "pending";
45050
+ get done() {
45051
+ return this.finished;
45052
+ }
45053
+ reset() {
45054
+ this.buffer = "";
45055
+ this.insideTag = false;
45056
+ this.currentTag = null;
45057
+ this.finished = false;
45058
+ this.responseStrategy = "pending";
45059
+ }
45060
+ push(chunk) {
45061
+ validateChunkSize(chunk);
45062
+ this.buffer += chunk;
45063
+ if (this.responseStrategy === "pending") {
45064
+ this.detectResponseStrategy();
45065
+ }
45066
+ if (!this.insideTag) {
45067
+ for (const tag of ResponseStreamExtractor.STREAM_TAGS) {
45068
+ const openTag = `<${tag}>`;
45069
+ const closeTag2 = `</${tag}>`;
45070
+ const idx = this.buffer.indexOf(openTag);
45071
+ if (idx !== -1) {
45072
+ if (!this.shouldStreamTag(tag)) {
45073
+ const closeIdx2 = this.buffer.indexOf(closeTag2);
45074
+ if (closeIdx2 !== -1) {
45075
+ this.buffer = this.buffer.slice(closeIdx2 + closeTag2.length);
45076
+ continue;
45077
+ }
45078
+ break;
45079
+ }
45080
+ this.insideTag = true;
45081
+ this.currentTag = tag;
45082
+ this.buffer = this.buffer.slice(idx + openTag.length);
45083
+ break;
45084
+ }
45085
+ }
45086
+ }
45087
+ if (!this.insideTag) {
45088
+ this.buffer = trimBuffer(this.buffer);
45089
+ return "";
45090
+ }
45091
+ const closeTag = `</${this.currentTag}>`;
45092
+ const closeIdx = this.buffer.indexOf(closeTag);
45093
+ if (closeIdx !== -1) {
45094
+ const content = this.buffer.slice(0, closeIdx);
45095
+ this.buffer = this.buffer.slice(closeIdx + closeTag.length);
45096
+ this.insideTag = false;
45097
+ this.currentTag = null;
45098
+ this.finished = true;
45099
+ return content;
45100
+ }
45101
+ if (this.buffer.length > SAFE_MARGIN) {
45102
+ const toStream = this.buffer.slice(0, -SAFE_MARGIN);
45103
+ this.buffer = this.buffer.slice(-SAFE_MARGIN);
45104
+ return toStream;
45105
+ }
45106
+ return "";
45107
+ }
45108
+ detectResponseStrategy() {
45109
+ const match = this.buffer.match(ACTIONS_REGEX);
45110
+ if (match) {
45111
+ const actions = this.parseActions(match[1]);
45112
+ this.responseStrategy = this.isDirectReply(actions) ? "direct" : "delegated";
45113
+ }
45114
+ }
45115
+ parseActions(raw2) {
45116
+ return raw2.split(",").map((a) => a.trim().toUpperCase()).filter(Boolean);
45117
+ }
45118
+ isDirectReply(actions) {
45119
+ return actions.length === 1 && actions[0] === "REPLY";
45120
+ }
45121
+ shouldStreamTag(tag) {
45122
+ return tag === "text" && this.responseStrategy === "direct";
45123
+ }
45124
+ }
45125
+
45126
+ class ActionStreamFilter {
45127
+ buffer = "";
45128
+ decided = false;
45129
+ contentType = null;
45130
+ insideTextTag = false;
45131
+ finished = false;
45132
+ get done() {
45133
+ return this.finished;
45134
+ }
45135
+ reset() {
45136
+ this.buffer = "";
45137
+ this.decided = false;
45138
+ this.contentType = null;
45139
+ this.insideTextTag = false;
45140
+ this.finished = false;
45141
+ }
45142
+ push(chunk) {
45143
+ validateChunkSize(chunk);
45144
+ this.buffer += chunk;
45145
+ if (!this.decided) {
45146
+ const contentType = this.detectContentType();
45147
+ if (contentType) {
45148
+ this.contentType = contentType;
45149
+ this.decided = true;
45150
+ } else {
45151
+ return "";
45152
+ }
45153
+ }
45154
+ switch (this.contentType) {
45155
+ case "json":
45156
+ return "";
45157
+ case "text":
45158
+ return this.handlePlainText();
45159
+ case "xml":
45160
+ return this.handleXml();
45161
+ default:
45162
+ return "";
45163
+ }
45164
+ }
45165
+ detectContentType() {
45166
+ const trimmed = this.buffer.trimStart();
45167
+ if (trimmed.length === 0)
45168
+ return null;
45169
+ const firstChar = trimmed[0];
45170
+ if (firstChar === "{" || firstChar === "[")
45171
+ return "json";
45172
+ if (firstChar === "<")
45173
+ return "xml";
45174
+ return "text";
45175
+ }
45176
+ handlePlainText() {
45177
+ const toStream = this.buffer;
45178
+ this.buffer = "";
45179
+ return toStream;
45180
+ }
45181
+ handleXml() {
45182
+ const result = extractTagContent(this.buffer, "<text>", "</text>", this.insideTextTag, SAFE_MARGIN);
45183
+ this.buffer = result.buffer;
45184
+ this.insideTextTag = result.insideTag;
45185
+ if (result.closed) {
45186
+ this.finished = true;
45187
+ }
45188
+ if (!this.insideTextTag && !result.closed) {
45189
+ this.buffer = trimBuffer(this.buffer, 1024, 1024);
45190
+ }
45191
+ return result.content;
45192
+ }
45193
+ }
44870
45194
  // src/utils/paths.ts
44871
45195
  var pathJoin = (...parts) => {
44872
45196
  if (typeof process !== "undefined" && process.platform) {
44873
- try {
44874
- const path = __require("node:path");
44875
- return path.join(...parts);
44876
- } catch {}
45197
+ const path = __require("node:path");
45198
+ return path.join(...parts);
44877
45199
  }
44878
45200
  return parts.filter((part) => part).join("/").replace(/\/+/g, "/").replace(/\/$/, "");
44879
45201
  };
@@ -44993,28 +45315,22 @@ async function waitForServerReady(options) {
44993
45315
  while (Date.now() - startTime < maxWaitTime) {
44994
45316
  let controller;
44995
45317
  let timeoutId;
44996
- try {
44997
- controller = new AbortController;
44998
- timeoutId = setTimeout(() => {
44999
- if (controller) {
45000
- controller.abort();
45001
- }
45002
- }, requestTimeout);
45003
- const response = await fetch(url, {
45004
- signal: controller.signal
45005
- });
45006
- if (timeoutId) {
45007
- clearTimeout(timeoutId);
45008
- timeoutId = undefined;
45009
- }
45010
- if (response.ok) {
45011
- await new Promise((resolve) => setTimeout(resolve, 1000));
45012
- return;
45013
- }
45014
- } catch (error) {} finally {
45015
- if (timeoutId) {
45016
- clearTimeout(timeoutId);
45318
+ controller = new AbortController;
45319
+ timeoutId = setTimeout(() => {
45320
+ if (controller) {
45321
+ controller.abort();
45017
45322
  }
45323
+ }, requestTimeout);
45324
+ const response = await fetch(url, {
45325
+ signal: controller.signal
45326
+ });
45327
+ if (timeoutId) {
45328
+ clearTimeout(timeoutId);
45329
+ timeoutId = undefined;
45330
+ }
45331
+ if (response.ok) {
45332
+ await new Promise((resolve) => setTimeout(resolve, 1000));
45333
+ return;
45018
45334
  }
45019
45335
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
45020
45336
  }
@@ -45031,28 +45347,20 @@ async function pingServer(options) {
45031
45347
  const url = `${protocol}://${host}:${port}${endpoint}`;
45032
45348
  let controller;
45033
45349
  let timeoutId;
45034
- try {
45035
- controller = new AbortController;
45036
- timeoutId = setTimeout(() => {
45037
- if (controller) {
45038
- controller.abort();
45039
- }
45040
- }, requestTimeout);
45041
- const response = await fetch(url, {
45042
- signal: controller.signal
45043
- });
45044
- if (timeoutId) {
45045
- clearTimeout(timeoutId);
45046
- timeoutId = undefined;
45047
- }
45048
- return response.ok;
45049
- } catch (error) {
45050
- return false;
45051
- } finally {
45052
- if (timeoutId) {
45053
- clearTimeout(timeoutId);
45054
- }
45350
+ controller = new AbortController;
45351
+ timeoutId = setTimeout(() => {
45352
+ if (controller) {
45353
+ controller.abort();
45354
+ }
45355
+ }, requestTimeout);
45356
+ const response = await fetch(url, {
45357
+ signal: controller.signal
45358
+ });
45359
+ if (timeoutId) {
45360
+ clearTimeout(timeoutId);
45361
+ timeoutId = undefined;
45055
45362
  }
45363
+ return response.ok;
45056
45364
  }
45057
45365
  // src/actions.ts
45058
45366
  var import_unique_names_generator2 = __toESM(require_dist4(), 1);
@@ -45469,9 +45777,6 @@ async function getUserServerRole(runtime, entityId, serverId2) {
45469
45777
  if (world.metadata.roles[entityId]) {
45470
45778
  return world.metadata.roles[entityId];
45471
45779
  }
45472
- if (world.metadata.roles[entityId]) {
45473
- return world.metadata.roles[entityId];
45474
- }
45475
45780
  return "NONE" /* NONE */;
45476
45781
  }
45477
45782
  async function findWorldsForOwner(runtime, entityId) {
@@ -45592,11 +45897,12 @@ class DefaultMessageService {
45592
45897
  const opts = {
45593
45898
  maxRetries: options?.maxRetries ?? 3,
45594
45899
  timeoutDuration: options?.timeoutDuration ?? 60 * 60 * 1000,
45595
- useMultiStep: options?.useMultiStep ?? parseBooleanFromText2(runtime.getSetting("USE_MULTI_STEP")),
45596
- maxMultiStepIterations: options?.maxMultiStepIterations ?? parseInt(runtime.getSetting("MAX_MULTISTEP_ITERATIONS") || "6")
45900
+ useMultiStep: options?.useMultiStep ?? parseBooleanFromText2(String(runtime.getSetting("USE_MULTI_STEP") || "")),
45901
+ maxMultiStepIterations: options?.maxMultiStepIterations ?? parseInt(String(runtime.getSetting("MAX_MULTISTEP_ITERATIONS") || "6")),
45902
+ onStreamChunk: options?.onStreamChunk
45597
45903
  };
45598
45904
  let timeoutId = undefined;
45599
- const responseId = v4_default();
45905
+ const responseId = asUUID(v4_default());
45600
45906
  try {
45601
45907
  runtime.logger.info({
45602
45908
  src: "service:message",
@@ -45619,19 +45925,19 @@ class DefaultMessageService {
45619
45925
  const startTime = Date.now();
45620
45926
  await runtime.emitEvent("RUN_STARTED" /* RUN_STARTED */, {
45621
45927
  runtime,
45928
+ source: "messageHandler",
45622
45929
  runId,
45623
45930
  messageId: message.id,
45624
45931
  roomId: message.roomId,
45625
45932
  entityId: message.entityId,
45626
45933
  startTime,
45627
- status: "started",
45628
- source: "messageHandler",
45629
- metadata: message.content
45934
+ status: "started"
45630
45935
  });
45631
45936
  const timeoutPromise = new Promise((_, reject) => {
45632
45937
  timeoutId = setTimeout(async () => {
45633
45938
  await runtime.emitEvent("RUN_TIMEOUT" /* RUN_TIMEOUT */, {
45634
45939
  runtime,
45940
+ source: "messageHandler",
45635
45941
  runId,
45636
45942
  messageId: message.id,
45637
45943
  roomId: message.roomId,
@@ -45640,20 +45946,32 @@ class DefaultMessageService {
45640
45946
  status: "timeout",
45641
45947
  endTime: Date.now(),
45642
45948
  duration: Date.now() - startTime,
45643
- error: "Run exceeded timeout",
45644
- source: "messageHandler"
45949
+ error: "Run exceeded timeout"
45645
45950
  });
45646
45951
  reject(new Error("Run exceeded timeout"));
45647
45952
  }, opts.timeoutDuration);
45648
45953
  });
45649
- const processingPromise = this.processMessage(runtime, message, callback, responseId, runId, startTime, opts);
45954
+ let streamingContext;
45955
+ if (opts.onStreamChunk) {
45956
+ const extractor = new ResponseStreamExtractor;
45957
+ streamingContext = {
45958
+ onStreamChunk: async (chunk, msgId) => {
45959
+ if (extractor.done)
45960
+ return;
45961
+ const textToStream = extractor.push(chunk);
45962
+ if (textToStream) {
45963
+ await opts.onStreamChunk(textToStream, msgId);
45964
+ }
45965
+ },
45966
+ messageId: responseId
45967
+ };
45968
+ }
45969
+ const processingPromise = runWithStreamingContext(streamingContext, () => this.processMessage(runtime, message, callback, responseId, runId, startTime, opts));
45650
45970
  const result = await Promise.race([processingPromise, timeoutPromise]);
45651
45971
  clearTimeout(timeoutId);
45652
45972
  return result;
45653
- } catch (error) {
45973
+ } finally {
45654
45974
  clearTimeout(timeoutId);
45655
- runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error in handleMessage");
45656
- throw error;
45657
45975
  }
45658
45976
  }
45659
45977
  async processMessage(runtime, message, callback, responseId, runId, startTime, opts) {
@@ -45668,7 +45986,7 @@ class DefaultMessageService {
45668
45986
  didRespond: false,
45669
45987
  responseContent: null,
45670
45988
  responseMessages: [],
45671
- state: {},
45989
+ state: { values: {}, data: {}, text: "" },
45672
45990
  mode: "none"
45673
45991
  };
45674
45992
  }
@@ -45695,7 +46013,7 @@ class DefaultMessageService {
45695
46013
  await runtime.queueEmbeddingGeneration(memoryToQueue, "normal");
45696
46014
  }
45697
46015
  const agentUserState = await runtime.getParticipantUserState(message.roomId, runtime.agentId);
45698
- const defLllmOff = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_DEFLLMOFF"));
46016
+ const defLllmOff = parseBooleanFromText2(String(runtime.getSetting("BOOTSTRAP_DEFLLMOFF") || ""));
45699
46017
  if (defLllmOff && agentUserState === null) {
45700
46018
  runtime.logger.debug({ src: "service:message" }, "LLM is off by default");
45701
46019
  await this.emitRunEnded(runtime, runId, message, startTime, "off");
@@ -45703,7 +46021,7 @@ class DefaultMessageService {
45703
46021
  didRespond: false,
45704
46022
  responseContent: null,
45705
46023
  responseMessages: [],
45706
- state: {},
46024
+ state: { values: {}, data: {}, text: "" },
45707
46025
  mode: "none"
45708
46026
  };
45709
46027
  }
@@ -45714,7 +46032,7 @@ class DefaultMessageService {
45714
46032
  didRespond: false,
45715
46033
  responseContent: null,
45716
46034
  responseMessages: [],
45717
- state: {},
46035
+ state: { values: {}, data: {}, text: "" },
45718
46036
  mode: "none"
45719
46037
  };
45720
46038
  }
@@ -45754,13 +46072,14 @@ class DefaultMessageService {
45754
46072
  const responseObject = parseKeyValueXml(response);
45755
46073
  runtime.logger.debug({ src: "service:message", responseObject }, "Parsed evaluation result");
45756
46074
  const nonResponseActions = ["IGNORE", "NONE"];
45757
- shouldRespondToMessage = responseObject?.action && !nonResponseActions.includes(responseObject.action.toUpperCase());
46075
+ const actionValue = responseObject?.action;
46076
+ shouldRespondToMessage = typeof actionValue === "string" && !nonResponseActions.includes(actionValue.toUpperCase());
45758
46077
  }
45759
46078
  let responseContent = null;
45760
46079
  let responseMessages = [];
45761
46080
  let mode = "none";
45762
46081
  if (shouldRespondToMessage) {
45763
- const result = opts.useMultiStep ? await this.runMultiStepCore(runtime, message, state, callback, opts) : await this.runSingleShotCore(runtime, message, state, opts);
46082
+ const result = opts.useMultiStep ? await this.runMultiStepCore(runtime, message, state, callback, opts, responseId) : await this.runSingleShotCore(runtime, message, state, opts, responseId);
45764
46083
  responseContent = result.responseContent;
45765
46084
  responseMessages = result.responseMessages;
45766
46085
  state = result.state;
@@ -45798,13 +46117,13 @@ class DefaultMessageService {
45798
46117
  return callback(content);
45799
46118
  }
45800
46119
  return [];
45801
- });
46120
+ }, { onStreamChunk: opts.onStreamChunk });
45802
46121
  }
45803
46122
  }
45804
46123
  } else {
45805
46124
  runtime.logger.debug({ src: "service:message" }, "Agent decided not to respond");
45806
46125
  const currentResponseId = agentResponses.get(message.roomId);
45807
- const keepResp = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_KEEP_RESP"));
46126
+ const keepResp = parseBooleanFromText2(String(runtime.getSetting("BOOTSTRAP_KEEP_RESP") || ""));
45808
46127
  if (currentResponseId !== responseId && !keepResp) {
45809
46128
  runtime.logger.info({ src: "service:message", agentId: runtime.agentId, roomId: message.roomId }, "Ignore response discarded - newer message being processed");
45810
46129
  await this.emitRunEnded(runtime, runId, message, startTime, "replaced");
@@ -45862,7 +46181,7 @@ class DefaultMessageService {
45862
46181
  return [];
45863
46182
  }, responseMessages);
45864
46183
  let entityName = "noname";
45865
- if (message.metadata && "entityName" in message.metadata) {
46184
+ if (message.metadata && "entityName" in message.metadata && typeof message.metadata.entityName === "string") {
45866
46185
  entityName = message.metadata.entityName;
45867
46186
  }
45868
46187
  const isDM = message.content?.channelType === "DM" /* DM */;
@@ -45883,7 +46202,10 @@ class DefaultMessageService {
45883
46202
  }
45884
46203
  }
45885
46204
  const date2 = new Date;
45886
- const availableActions = state.data?.providers?.ACTIONS?.data?.actionsData?.map((a) => a.name) || [-1];
46205
+ const providersData = state.data?.providers;
46206
+ const actionsProvider = typeof providersData === "object" && providersData !== null && "ACTIONS" in providersData ? providersData.ACTIONS : undefined;
46207
+ const actionsData = actionsProvider?.data?.actionsData;
46208
+ const availableActions = Array.isArray(actionsData) ? actionsData.map((a) => a.name) : [-1];
45887
46209
  const logData = {
45888
46210
  at: date2.toString(),
45889
46211
  timestamp: parseInt("" + date2.getTime() / 1000),
@@ -45904,6 +46226,7 @@ class DefaultMessageService {
45904
46226
  };
45905
46227
  await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
45906
46228
  runtime,
46229
+ source: "messageHandler",
45907
46230
  runId,
45908
46231
  messageId: message.id,
45909
46232
  roomId: message.roomId,
@@ -45911,11 +46234,7 @@ class DefaultMessageService {
45911
46234
  startTime,
45912
46235
  status: "completed",
45913
46236
  endTime: Date.now(),
45914
- duration: Date.now() - startTime,
45915
- source: "messageHandler",
45916
- entityName,
45917
- responseContent,
45918
- metadata: logData
46237
+ duration: Date.now() - startTime
45919
46238
  });
45920
46239
  return {
45921
46240
  didRespond: shouldRespondToMessage,
@@ -45925,19 +46244,20 @@ class DefaultMessageService {
45925
46244
  mode
45926
46245
  };
45927
46246
  } catch (error) {
46247
+ const errorMessage = error instanceof Error ? error.message : String(error);
45928
46248
  runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error processing message");
45929
46249
  await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
45930
46250
  runtime,
46251
+ source: "messageHandler",
45931
46252
  runId,
45932
46253
  messageId: message.id,
45933
46254
  roomId: message.roomId,
45934
46255
  entityId: message.entityId,
45935
46256
  startTime,
45936
- status: "error",
46257
+ status: "completed",
45937
46258
  endTime: Date.now(),
45938
46259
  duration: Date.now() - startTime,
45939
- error: error.message,
45940
- source: "messageHandler"
46260
+ error: errorMessage
45941
46261
  });
45942
46262
  throw error;
45943
46263
  }
@@ -45989,93 +46309,85 @@ class DefaultMessageService {
45989
46309
  runtime.logger.debug({ src: "service:message", count: attachments.length }, "Processing attachments");
45990
46310
  const processedAttachments = [];
45991
46311
  for (const attachment of attachments) {
45992
- try {
45993
- const processedAttachment = { ...attachment };
45994
- const isRemote = /^(http|https):\/\//.test(attachment.url);
45995
- const url = isRemote ? attachment.url : getLocalServerUrl(attachment.url);
45996
- if (attachment.contentType === "image" /* IMAGE */ && !attachment.description) {
45997
- runtime.logger.debug({ src: "service:message", imageUrl: attachment.url }, "Generating image description");
45998
- let imageUrl = url;
45999
- if (!isRemote) {
46000
- const res = await fetch(url);
46001
- if (!res.ok)
46002
- throw new Error(`Failed to fetch image: ${res.statusText}`);
46003
- const arrayBuffer = await res.arrayBuffer();
46004
- const buffer = Buffer.from(arrayBuffer);
46005
- const contentType = res.headers.get("content-type") || "application/octet-stream";
46006
- imageUrl = `data:${contentType};base64,${buffer.toString("base64")}`;
46007
- }
46008
- try {
46009
- const response = await runtime.useModel(ModelType.IMAGE_DESCRIPTION, {
46010
- prompt: imageDescriptionTemplate,
46011
- imageUrl
46012
- });
46013
- if (typeof response === "string") {
46014
- const parsedXml = parseKeyValueXml(response);
46015
- if (parsedXml && (parsedXml.description || parsedXml.text)) {
46016
- processedAttachment.description = parsedXml.description || "";
46017
- processedAttachment.title = parsedXml.title || "Image";
46018
- processedAttachment.text = parsedXml.text || parsedXml.description || "";
46019
- runtime.logger.debug({
46020
- src: "service:message",
46021
- descriptionPreview: processedAttachment.description?.substring(0, 100)
46022
- }, "Generated image description");
46023
- } else {
46024
- const responseStr = response;
46025
- const titleMatch = responseStr.match(/<title>([^<]+)<\/title>/);
46026
- const descMatch = responseStr.match(/<description>([^<]+)<\/description>/);
46027
- const textMatch = responseStr.match(/<text>([^<]+)<\/text>/);
46028
- if (titleMatch || descMatch || textMatch) {
46029
- processedAttachment.title = titleMatch?.[1] || "Image";
46030
- processedAttachment.description = descMatch?.[1] || "";
46031
- processedAttachment.text = textMatch?.[1] || descMatch?.[1] || "";
46032
- runtime.logger.debug({
46033
- src: "service:message",
46034
- descriptionPreview: processedAttachment.description?.substring(0, 100)
46035
- }, "Used fallback XML parsing for description");
46036
- } else {
46037
- runtime.logger.warn({ src: "service:message" }, "Failed to parse XML response for image description");
46038
- }
46039
- }
46040
- } else if (response && typeof response === "object" && "description" in response) {
46041
- processedAttachment.description = response.description;
46042
- processedAttachment.title = response.title || "Image";
46043
- processedAttachment.text = response.description;
46312
+ const processedAttachment = { ...attachment };
46313
+ const isRemote = /^(http|https):\/\//.test(attachment.url);
46314
+ const url = isRemote ? attachment.url : getLocalServerUrl(attachment.url);
46315
+ if (attachment.contentType === "image" /* IMAGE */ && !attachment.description) {
46316
+ runtime.logger.debug({ src: "service:message", imageUrl: attachment.url }, "Generating image description");
46317
+ let imageUrl = url;
46318
+ if (!isRemote) {
46319
+ const res = await fetch(url);
46320
+ if (!res.ok)
46321
+ throw new Error(`Failed to fetch image: ${res.statusText}`);
46322
+ const arrayBuffer = await res.arrayBuffer();
46323
+ const buffer = Buffer.from(arrayBuffer);
46324
+ const contentType = res.headers.get("content-type") || "application/octet-stream";
46325
+ imageUrl = `data:${contentType};base64,${buffer.toString("base64")}`;
46326
+ }
46327
+ const response = await runtime.useModel(ModelType.IMAGE_DESCRIPTION, {
46328
+ prompt: imageDescriptionTemplate,
46329
+ imageUrl
46330
+ });
46331
+ if (typeof response === "string") {
46332
+ const parsedXml = parseKeyValueXml(response);
46333
+ if (parsedXml && (parsedXml.description || parsedXml.text)) {
46334
+ processedAttachment.description = (typeof parsedXml.description === "string" ? parsedXml.description : "") || "";
46335
+ processedAttachment.title = (typeof parsedXml.title === "string" ? parsedXml.title : "Image") || "Image";
46336
+ processedAttachment.text = (typeof parsedXml.text === "string" ? parsedXml.text : "") || (typeof parsedXml.description === "string" ? parsedXml.description : "") || "";
46337
+ runtime.logger.debug({
46338
+ src: "service:message",
46339
+ descriptionPreview: processedAttachment.description?.substring(0, 100)
46340
+ }, "Generated image description");
46341
+ } else {
46342
+ const responseStr = response;
46343
+ const titleMatch = responseStr.match(/<title>([^<]+)<\/title>/);
46344
+ const descMatch = responseStr.match(/<description>([^<]+)<\/description>/);
46345
+ const textMatch = responseStr.match(/<text>([^<]+)<\/text>/);
46346
+ if (titleMatch || descMatch || textMatch) {
46347
+ processedAttachment.title = titleMatch?.[1] || "Image";
46348
+ processedAttachment.description = descMatch?.[1] || "";
46349
+ processedAttachment.text = textMatch?.[1] || descMatch?.[1] || "";
46044
46350
  runtime.logger.debug({
46045
46351
  src: "service:message",
46046
46352
  descriptionPreview: processedAttachment.description?.substring(0, 100)
46047
- }, "Generated image description");
46353
+ }, "Used fallback XML parsing for description");
46048
46354
  } else {
46049
- runtime.logger.warn({ src: "service:message" }, "Unexpected response format for image description");
46355
+ runtime.logger.warn({ src: "service:message" }, "Failed to parse XML response for image description");
46050
46356
  }
46051
- } catch (error) {
46052
- runtime.logger.error({ src: "service:message", error }, "Error generating image description");
46053
- }
46054
- } else if (attachment.contentType === "document" /* DOCUMENT */ && !attachment.text) {
46055
- const res = await fetch(url);
46056
- if (!res.ok)
46057
- throw new Error(`Failed to fetch document: ${res.statusText}`);
46058
- const contentType = res.headers.get("content-type") || "";
46059
- const isPlainText = contentType.startsWith("text/plain");
46060
- if (isPlainText) {
46061
- runtime.logger.debug({ src: "service:message", documentUrl: attachment.url }, "Processing plain text document");
46062
- const textContent = await res.text();
46063
- processedAttachment.text = textContent;
46064
- processedAttachment.title = processedAttachment.title || "Text File";
46065
- runtime.logger.debug({ src: "service:message", textPreview: processedAttachment.text?.substring(0, 100) }, "Extracted text content");
46066
- } else {
46067
- runtime.logger.warn({ src: "service:message", contentType }, "Skipping non-plain-text document");
46068
46357
  }
46358
+ } else if (response && typeof response === "object" && "description" in response) {
46359
+ const objResponse = response;
46360
+ processedAttachment.description = objResponse.description;
46361
+ processedAttachment.title = objResponse.title || "Image";
46362
+ processedAttachment.text = objResponse.description;
46363
+ runtime.logger.debug({
46364
+ src: "service:message",
46365
+ descriptionPreview: processedAttachment.description?.substring(0, 100)
46366
+ }, "Generated image description");
46367
+ } else {
46368
+ runtime.logger.warn({ src: "service:message" }, "Unexpected response format for image description");
46369
+ }
46370
+ } else if (attachment.contentType === "document" /* DOCUMENT */ && !attachment.text) {
46371
+ const res = await fetch(url);
46372
+ if (!res.ok)
46373
+ throw new Error(`Failed to fetch document: ${res.statusText}`);
46374
+ const contentType = res.headers.get("content-type") || "";
46375
+ const isPlainText = contentType.startsWith("text/plain");
46376
+ if (isPlainText) {
46377
+ runtime.logger.debug({ src: "service:message", documentUrl: attachment.url }, "Processing plain text document");
46378
+ const textContent = await res.text();
46379
+ processedAttachment.text = textContent;
46380
+ processedAttachment.title = processedAttachment.title || "Text File";
46381
+ runtime.logger.debug({ src: "service:message", textPreview: processedAttachment.text?.substring(0, 100) }, "Extracted text content");
46382
+ } else {
46383
+ runtime.logger.warn({ src: "service:message", contentType }, "Skipping non-plain-text document");
46069
46384
  }
46070
- processedAttachments.push(processedAttachment);
46071
- } catch (error) {
46072
- runtime.logger.error({ src: "service:message", error, attachmentUrl: attachment.url }, "Failed to process attachment");
46073
- processedAttachments.push(attachment);
46074
46385
  }
46386
+ processedAttachments.push(processedAttachment);
46075
46387
  }
46076
46388
  return processedAttachments;
46077
46389
  }
46078
- async runSingleShotCore(runtime, message, state, opts) {
46390
+ async runSingleShotCore(runtime, message, state, opts, responseId) {
46079
46391
  state = await runtime.composeState(message, ["ACTIONS"]);
46080
46392
  if (!state.values?.actionNames) {
46081
46393
  runtime.logger.warn({ src: "service:message" }, "actionNames data missing from state");
@@ -46087,25 +46399,54 @@ class DefaultMessageService {
46087
46399
  let responseContent = null;
46088
46400
  let retries = 0;
46089
46401
  while (retries < opts.maxRetries && (!responseContent?.thought || !responseContent?.actions)) {
46090
- const response = await runtime.useModel(ModelType.TEXT_LARGE, { prompt });
46091
- runtime.logger.debug({ src: "service:message", response }, "Raw LLM response");
46402
+ const response = await runtime.useModel(ModelType.TEXT_LARGE, {
46403
+ prompt
46404
+ });
46405
+ runtime.logger.info({
46406
+ src: "service:message",
46407
+ responseLength: response.length,
46408
+ responsePreview: response.substring(0, 500)
46409
+ }, "Raw LLM response received");
46092
46410
  const parsedXml = parseKeyValueXml(response);
46093
- runtime.logger.debug({ src: "service:message", parsedXml }, "Parsed XML content");
46411
+ runtime.logger.info({
46412
+ src: "service:message",
46413
+ parsedXml: parsedXml ? {
46414
+ hasThought: !!parsedXml.thought,
46415
+ thoughtPreview: typeof parsedXml.thought === "string" ? parsedXml.thought.substring(0, 100) : null,
46416
+ hasActions: !!parsedXml.actions,
46417
+ actions: parsedXml.actions,
46418
+ hasText: !!parsedXml.text,
46419
+ textPreview: typeof parsedXml.text === "string" ? parsedXml.text.substring(0, 100) : null
46420
+ } : null
46421
+ }, "Parsed XML content");
46094
46422
  if (parsedXml) {
46423
+ const thought = typeof parsedXml.thought === "string" ? parsedXml.thought : "";
46424
+ const actions = Array.isArray(parsedXml.actions) ? parsedXml.actions.filter((a) => typeof a === "string") : typeof parsedXml.actions === "string" ? [parsedXml.actions] : ["IGNORE"];
46425
+ const providers = Array.isArray(parsedXml.providers) ? parsedXml.providers.filter((p) => typeof p === "string") : [];
46426
+ const text = typeof parsedXml.text === "string" ? parsedXml.text : "";
46427
+ const simple = typeof parsedXml.simple === "boolean" ? parsedXml.simple : false;
46095
46428
  responseContent = {
46096
46429
  ...parsedXml,
46097
- thought: parsedXml.thought || "",
46098
- actions: parsedXml.actions || ["IGNORE"],
46099
- providers: parsedXml.providers || [],
46100
- text: parsedXml.text || "",
46101
- simple: parsedXml.simple || false
46430
+ thought,
46431
+ actions,
46432
+ providers,
46433
+ text,
46434
+ simple
46102
46435
  };
46103
46436
  } else {
46104
46437
  responseContent = null;
46438
+ runtime.logger.warn({ src: "service:message", responsePreview: response.substring(0, 300) }, "parseKeyValueXml returned null - XML parsing failed");
46105
46439
  }
46106
46440
  retries++;
46107
46441
  if (!responseContent?.thought || !responseContent?.actions) {
46108
- runtime.logger.warn({ src: "service:message", retries, maxRetries: opts.maxRetries }, "Missing required fields (thought or actions), retrying");
46442
+ runtime.logger.warn({
46443
+ src: "service:message",
46444
+ retries,
46445
+ maxRetries: opts.maxRetries,
46446
+ hasThought: !!responseContent?.thought,
46447
+ hasActions: !!responseContent?.actions,
46448
+ actionsValue: responseContent?.actions
46449
+ }, "Missing required fields (thought or actions), retrying");
46109
46450
  }
46110
46451
  }
46111
46452
  if (!responseContent) {
@@ -46125,9 +46466,10 @@ class DefaultMessageService {
46125
46466
  }
46126
46467
  const isSimple = responseContent.actions?.length === 1 && typeof responseContent.actions[0] === "string" && responseContent.actions[0].toUpperCase() === "REPLY" && (!responseContent.providers || responseContent.providers.length === 0);
46127
46468
  responseContent.simple = isSimple;
46469
+ responseContent.responseId = responseId;
46128
46470
  const responseMessages = [
46129
46471
  {
46130
- id: asUUID(v4_default()),
46472
+ id: responseId,
46131
46473
  entityId: runtime.agentId,
46132
46474
  agentId: runtime.agentId,
46133
46475
  content: responseContent,
@@ -46142,7 +46484,7 @@ class DefaultMessageService {
46142
46484
  mode: isSimple && responseContent.text ? "simple" : "actions"
46143
46485
  };
46144
46486
  }
46145
- async runMultiStepCore(runtime, message, state, callback, opts) {
46487
+ async runMultiStepCore(runtime, message, state, callback, opts, responseId) {
46146
46488
  const traceActionResult = [];
46147
46489
  let accumulatedState = state;
46148
46490
  let iterationCount = 0;
@@ -46173,93 +46515,90 @@ class DefaultMessageService {
46173
46515
  });
46174
46516
  break;
46175
46517
  }
46176
- const { thought, providers = [], action, isFinish } = parsedStep;
46518
+ const thought = typeof parsedStep.thought === "string" ? parsedStep.thought : undefined;
46519
+ const providers = Array.isArray(parsedStep.providers) ? parsedStep.providers : [];
46520
+ const action = typeof parsedStep.action === "string" ? parsedStep.action : undefined;
46521
+ const isFinish = parsedStep.isFinish;
46177
46522
  if (isFinish === "true" || isFinish === true) {
46178
46523
  runtime.logger.info({ src: "service:message", agentId: runtime.agentId, iteration: iterationCount }, "Multi-step task completed");
46179
46524
  if (callback) {
46180
46525
  await callback({
46181
46526
  text: "",
46182
- thought: thought ?? ""
46527
+ thought: typeof thought === "string" ? thought : ""
46183
46528
  });
46184
46529
  }
46185
46530
  break;
46186
46531
  }
46187
- if ((!providers || providers.length === 0) && !action) {
46532
+ const providersArray = Array.isArray(providers) ? providers : [];
46533
+ if ((!providersArray || providersArray.length === 0) && !action) {
46188
46534
  runtime.logger.warn({ src: "service:message", iteration: iterationCount }, "No providers or action specified, forcing completion");
46189
46535
  break;
46190
46536
  }
46191
- try {
46192
- for (const providerName of providers) {
46193
- const provider = runtime.providers.find((p) => p.name === providerName);
46194
- if (!provider) {
46195
- runtime.logger.warn({ src: "service:message", providerName }, "Provider not found");
46196
- traceActionResult.push({
46197
- data: { actionName: providerName },
46198
- success: false,
46199
- error: `Provider not found: ${providerName}`
46200
- });
46201
- continue;
46202
- }
46203
- const providerResult = await provider.get(runtime, message, state);
46204
- if (!providerResult) {
46205
- runtime.logger.warn({ src: "service:message", providerName }, "Provider returned no result");
46206
- traceActionResult.push({
46207
- data: { actionName: providerName },
46208
- success: false,
46209
- error: `Provider returned no result`
46210
- });
46211
- continue;
46212
- }
46213
- const success = !!providerResult.text;
46537
+ for (const providerName of providersArray) {
46538
+ if (typeof providerName !== "string")
46539
+ continue;
46540
+ const provider = runtime.providers.find((p) => p.name === providerName);
46541
+ if (!provider) {
46542
+ runtime.logger.warn({ src: "service:message", providerName }, "Provider not found");
46214
46543
  traceActionResult.push({
46215
46544
  data: { actionName: providerName },
46216
- success,
46217
- text: success ? providerResult.text : undefined,
46218
- error: success ? undefined : "Provider returned no result"
46545
+ success: false,
46546
+ error: `Provider not found: ${providerName}`
46219
46547
  });
46220
- if (callback) {
46221
- await callback({
46222
- text: `\uD83D\uDD0E Provider executed: ${providerName}`,
46223
- actions: [providerName],
46224
- thought: thought ?? ""
46225
- });
46226
- }
46548
+ continue;
46227
46549
  }
46228
- if (action) {
46229
- const actionContent = {
46230
- text: `\uD83D\uDD0E Executing action: ${action}`,
46231
- actions: [action],
46232
- thought: thought ?? ""
46233
- };
46234
- await runtime.processActions(message, [
46235
- {
46236
- id: v4_default(),
46237
- entityId: runtime.agentId,
46238
- roomId: message.roomId,
46239
- createdAt: Date.now(),
46240
- content: actionContent
46241
- }
46242
- ], state, async () => {
46243
- return [];
46244
- });
46245
- const cachedState = runtime.stateCache?.get(`${message.id}_action_results`);
46246
- const actionResults = cachedState?.values?.actionResults || [];
46247
- const result = actionResults.length > 0 ? actionResults[0] : null;
46248
- const success = result?.success ?? false;
46550
+ const providerResult = await provider.get(runtime, message, state);
46551
+ if (!providerResult) {
46552
+ runtime.logger.warn({ src: "service:message", providerName }, "Provider returned no result");
46249
46553
  traceActionResult.push({
46250
- data: { actionName: action },
46251
- success,
46252
- text: result?.text,
46253
- values: result?.values,
46254
- error: success ? undefined : result?.text
46554
+ data: { actionName: providerName },
46555
+ success: false,
46556
+ error: `Provider returned no result`
46255
46557
  });
46558
+ continue;
46256
46559
  }
46257
- } catch (err) {
46258
- runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error: err }, "Error executing multi-step action");
46560
+ const success = !!providerResult.text;
46259
46561
  traceActionResult.push({
46260
- data: { actionName: action || "unknown" },
46261
- success: false,
46262
- error: err instanceof Error ? err.message : String(err)
46562
+ data: { actionName: providerName },
46563
+ success,
46564
+ text: success ? providerResult.text : undefined,
46565
+ error: success ? undefined : "Provider returned no result"
46566
+ });
46567
+ if (callback) {
46568
+ await callback({
46569
+ text: `\uD83D\uDD0E Provider executed: ${providerName}`,
46570
+ actions: [providerName],
46571
+ thought: typeof thought === "string" ? thought : ""
46572
+ });
46573
+ }
46574
+ }
46575
+ if (action) {
46576
+ const actionContent = {
46577
+ text: `\uD83D\uDD0E Executing action: ${action}`,
46578
+ actions: [action],
46579
+ thought: thought || ""
46580
+ };
46581
+ await runtime.processActions(message, [
46582
+ {
46583
+ id: v4_default(),
46584
+ entityId: runtime.agentId,
46585
+ roomId: message.roomId,
46586
+ createdAt: Date.now(),
46587
+ content: actionContent
46588
+ }
46589
+ ], state, async () => {
46590
+ return [];
46591
+ });
46592
+ const cachedState = runtime.stateCache?.get(`${message.id}_action_results`);
46593
+ const actionResults = Array.isArray(cachedState?.values?.actionResults) ? cachedState.values.actionResults : [];
46594
+ const result = actionResults.length > 0 && typeof actionResults[0] === "object" && actionResults[0] !== null ? actionResults[0] : null;
46595
+ const success = result && "success" in result && typeof result.success === "boolean" ? result.success : false;
46596
+ traceActionResult.push({
46597
+ data: { actionName: typeof action === "string" ? action : "unknown" },
46598
+ success,
46599
+ text: result && "text" in result && typeof result.text === "string" ? result.text : undefined,
46600
+ values: result && "values" in result && typeof result.values === "object" && result.values !== null ? result.values : undefined,
46601
+ error: success ? undefined : result && ("text" in result) && typeof result.text === "string" ? result.text : undefined
46263
46602
  });
46264
46603
  }
46265
46604
  }
@@ -46274,20 +46613,24 @@ class DefaultMessageService {
46274
46613
  state: accumulatedState,
46275
46614
  template: runtime.character.templates?.multiStepSummaryTemplate || multiStepSummaryTemplate
46276
46615
  });
46277
- const finalOutput = await runtime.useModel(ModelType.TEXT_LARGE, { prompt: summaryPrompt });
46616
+ const finalOutput = await runtime.useModel(ModelType.TEXT_LARGE, {
46617
+ prompt: summaryPrompt
46618
+ });
46278
46619
  const summary = parseKeyValueXml(finalOutput);
46279
46620
  let responseContent = null;
46280
- if (summary?.text) {
46621
+ const summaryText = summary?.text;
46622
+ if (typeof summaryText === "string" && summaryText) {
46281
46623
  responseContent = {
46282
46624
  actions: ["MULTI_STEP_SUMMARY"],
46283
- text: summary.text,
46284
- thought: summary.thought || "Final user-facing message after task completion.",
46285
- simple: true
46625
+ text: summaryText,
46626
+ thought: (typeof summary.thought === "string" ? summary.thought : "Final user-facing message after task completion.") || "Final user-facing message after task completion.",
46627
+ simple: true,
46628
+ responseId
46286
46629
  };
46287
46630
  }
46288
46631
  const responseMessages = responseContent ? [
46289
46632
  {
46290
- id: asUUID(v4_default()),
46633
+ id: responseId,
46291
46634
  entityId: runtime.agentId,
46292
46635
  agentId: runtime.agentId,
46293
46636
  content: responseContent,
@@ -46305,6 +46648,7 @@ class DefaultMessageService {
46305
46648
  async emitRunEnded(runtime, runId, message, startTime, status) {
46306
46649
  await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
46307
46650
  runtime,
46651
+ source: "messageHandler",
46308
46652
  runId,
46309
46653
  messageId: message.id,
46310
46654
  roomId: message.roomId,
@@ -46312,8 +46656,7 @@ class DefaultMessageService {
46312
46656
  startTime,
46313
46657
  status,
46314
46658
  endTime: Date.now(),
46315
- duration: Date.now() - startTime,
46316
- source: "messageHandler"
46659
+ duration: Date.now() - startTime
46317
46660
  });
46318
46661
  }
46319
46662
  async deleteMessage(runtime, message) {
@@ -47139,8 +47482,6 @@ class BM25 {
47139
47482
  this.termFrequencies.get(termIndexVal).set(docIndex, freq);
47140
47483
  if (termIndexVal < this.documentFrequency.length) {
47141
47484
  this.documentFrequency[termIndexVal]++;
47142
- } else {
47143
- console.error(`Error: termIndexVal ${termIndexVal} is out of bounds for documentFrequency (length ${this.documentFrequency.length}). This indicates an issue with array resizing or term indexing.`);
47144
47485
  }
47145
47486
  });
47146
47487
  this.recalculateAverageLength();
@@ -47311,19 +47652,16 @@ class AgentRuntime {
47311
47652
  this.plugins.push(plugin);
47312
47653
  this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin added");
47313
47654
  if (plugin.init) {
47314
- try {
47315
- await plugin.init(plugin.config || {}, this);
47316
- this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin initialized");
47317
- } catch (error) {
47318
- const errorMessage = error instanceof Error ? error.message : String(error);
47319
- if (errorMessage.includes("API key") || errorMessage.includes("environment variables") || errorMessage.includes("Invalid plugin configuration")) {
47320
- console.warn(`Plugin ${plugin.name} requires configuration. ${errorMessage}`);
47321
- console.warn("Please check your environment variables and ensure all required API keys are set.");
47322
- console.warn("You can set these in your .env file.");
47323
- } else {
47324
- throw error;
47655
+ const config = {};
47656
+ if (plugin.config) {
47657
+ for (const [key, value] of Object.entries(plugin.config)) {
47658
+ if (value !== null && value !== undefined) {
47659
+ config[key] = String(value);
47660
+ }
47325
47661
  }
47326
47662
  }
47663
+ await plugin.init(config, this);
47664
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin initialized");
47327
47665
  }
47328
47666
  if (plugin.adapter) {
47329
47667
  this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Registering database adapter");
@@ -47404,122 +47742,110 @@ class AgentRuntime {
47404
47742
  this.elizaOS = undefined;
47405
47743
  }
47406
47744
  async initialize(options) {
47407
- try {
47408
- const pluginRegistrationPromises = [];
47409
- const pluginsToLoad = this.characterPlugins;
47410
- for (const plugin of pluginsToLoad) {
47411
- if (plugin) {
47412
- pluginRegistrationPromises.push(this.registerPlugin(plugin));
47413
- }
47414
- }
47415
- await Promise.all(pluginRegistrationPromises);
47416
- if (!this.adapter) {
47417
- this.logger.error({ src: "agent", agentId: this.agentId }, "Database adapter not initialized");
47418
- throw new Error("Database adapter not initialized. The SQL plugin (@elizaos/plugin-sql) is required for agent initialization. Please ensure it is included in your character configuration.");
47419
- }
47420
- if (!await this.adapter.isReady()) {
47421
- await this.adapter.init();
47745
+ const pluginRegistrationPromises = [];
47746
+ const pluginsToLoad = this.characterPlugins;
47747
+ for (const plugin of pluginsToLoad) {
47748
+ if (plugin) {
47749
+ pluginRegistrationPromises.push(this.registerPlugin(plugin));
47422
47750
  }
47423
- this.messageService = new DefaultMessageService;
47424
- const skipMigrations = options?.skipMigrations ?? false;
47425
- if (skipMigrations) {
47426
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Skipping plugin migrations");
47427
- } else {
47428
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Running plugin migrations");
47429
- await this.runPluginMigrations();
47430
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
47751
+ }
47752
+ await Promise.all(pluginRegistrationPromises);
47753
+ if (!this.adapter) {
47754
+ this.logger.error({ src: "agent", agentId: this.agentId }, "Database adapter not initialized");
47755
+ throw new Error("Database adapter not initialized. The SQL plugin (@elizaos/plugin-sql) is required for agent initialization. Please ensure it is included in your character configuration.");
47756
+ }
47757
+ if (!await this.adapter.isReady()) {
47758
+ await this.adapter.init();
47759
+ }
47760
+ this.messageService = new DefaultMessageService;
47761
+ const skipMigrations = options?.skipMigrations ?? false;
47762
+ if (skipMigrations) {
47763
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Skipping plugin migrations");
47764
+ } else {
47765
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Running plugin migrations");
47766
+ await this.runPluginMigrations();
47767
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
47768
+ }
47769
+ const existingAgent = await this.ensureAgentExists({
47770
+ ...this.character,
47771
+ id: this.agentId
47772
+ });
47773
+ if (!existingAgent) {
47774
+ const errorMsg = `Agent ${this.agentId} does not exist in database after ensureAgentExists call`;
47775
+ throw new Error(errorMsg);
47776
+ }
47777
+ if (existingAgent.settings) {
47778
+ this.character.settings = {
47779
+ ...existingAgent.settings,
47780
+ ...this.character.settings
47781
+ };
47782
+ const dbSecrets = existingAgent.settings.secrets && typeof existingAgent.settings.secrets === "object" ? existingAgent.settings.secrets : {};
47783
+ const settingsSecrets = this.character.settings.secrets && typeof this.character.settings.secrets === "object" ? this.character.settings.secrets : {};
47784
+ const characterSecrets = this.character.secrets && typeof this.character.secrets === "object" ? this.character.secrets : {};
47785
+ const mergedSecrets = {
47786
+ ...dbSecrets,
47787
+ ...characterSecrets,
47788
+ ...settingsSecrets
47789
+ };
47790
+ if (Object.keys(mergedSecrets).length > 0) {
47791
+ const filteredSecrets = {};
47792
+ for (const [key, value] of Object.entries(mergedSecrets)) {
47793
+ if (value !== null && value !== undefined) {
47794
+ filteredSecrets[key] = value;
47795
+ }
47796
+ }
47797
+ if (Object.keys(filteredSecrets).length > 0) {
47798
+ this.character.secrets = filteredSecrets;
47799
+ this.character.settings.secrets = filteredSecrets;
47800
+ }
47431
47801
  }
47432
- const existingAgent = await this.ensureAgentExists({
47433
- ...this.character,
47434
- id: this.agentId
47802
+ }
47803
+ let agentEntity = await this.getEntityById(this.agentId);
47804
+ if (!agentEntity) {
47805
+ const created = await this.createEntity({
47806
+ id: this.agentId,
47807
+ names: [this.character.name],
47808
+ metadata: {},
47809
+ agentId: existingAgent.id
47435
47810
  });
47436
- if (!existingAgent) {
47437
- const errorMsg = `Agent ${this.agentId} does not exist in database after ensureAgentExists call`;
47811
+ if (!created) {
47812
+ const errorMsg = `Failed to create entity for agent ${this.agentId}`;
47438
47813
  throw new Error(errorMsg);
47439
47814
  }
47440
- if (existingAgent.settings) {
47441
- this.character.settings = {
47442
- ...existingAgent.settings,
47443
- ...this.character.settings
47444
- };
47445
- const dbSecrets = existingAgent.settings.secrets && typeof existingAgent.settings.secrets === "object" ? existingAgent.settings.secrets : {};
47446
- const settingsSecrets = this.character.settings.secrets && typeof this.character.settings.secrets === "object" ? this.character.settings.secrets : {};
47447
- const characterSecrets = this.character.secrets && typeof this.character.secrets === "object" ? this.character.secrets : {};
47448
- const mergedSecrets = {
47449
- ...dbSecrets,
47450
- ...characterSecrets,
47451
- ...settingsSecrets
47452
- };
47453
- if (Object.keys(mergedSecrets).length > 0) {
47454
- this.character.secrets = mergedSecrets;
47455
- this.character.settings.secrets = mergedSecrets;
47456
- }
47457
- }
47458
- let agentEntity = await this.getEntityById(this.agentId);
47459
- if (!agentEntity) {
47460
- const created = await this.createEntity({
47461
- id: this.agentId,
47462
- names: [this.character.name],
47463
- metadata: {},
47464
- agentId: existingAgent.id
47465
- });
47466
- if (!created) {
47467
- const errorMsg = `Failed to create entity for agent ${this.agentId}`;
47468
- throw new Error(errorMsg);
47469
- }
47470
- agentEntity = await this.getEntityById(this.agentId);
47471
- if (!agentEntity)
47472
- throw new Error(`Agent entity not found for ${this.agentId}`);
47473
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent entity created");
47474
- }
47475
- const room = await this.getRoom(this.agentId);
47476
- if (!room) {
47477
- await this.createRoom({
47478
- id: this.agentId,
47479
- name: this.character.name,
47480
- source: "elizaos",
47481
- type: "SELF" /* SELF */,
47482
- channelId: this.agentId,
47483
- messageServerId: this.agentId,
47484
- worldId: this.agentId
47485
- });
47486
- }
47487
- const participants = await this.adapter.getParticipantsForRoom(this.agentId);
47488
- if (!participants.includes(this.agentId)) {
47489
- const added = await this.addParticipant(this.agentId, this.agentId);
47490
- if (!added) {
47491
- throw new Error(`Failed to add agent ${this.agentId} as participant to its own room`);
47492
- }
47493
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent linked to room");
47494
- }
47495
- const embeddingModel = this.getModel(ModelType.TEXT_EMBEDDING);
47496
- if (!embeddingModel) {
47497
- this.logger.warn({ src: "agent", agentId: this.agentId }, "No TEXT_EMBEDDING model registered, skipping embedding setup");
47498
- } else {
47499
- await this.ensureEmbeddingDimension();
47500
- }
47501
- if (this.initResolver) {
47502
- this.initResolver();
47503
- this.initResolver = undefined;
47504
- }
47505
- } catch (error) {
47506
- const errorMsg = error instanceof Error ? error.message : String(error);
47507
- this.logger.error({ src: "agent", agentId: this.agentId, error: errorMsg }, "Runtime initialization failed");
47508
- if (this.initRejecter) {
47509
- this.initRejecter(error);
47510
- this.initRejecter = undefined;
47511
- }
47512
- for (const [serviceType, promise] of this.servicePromises) {
47513
- const handler = this.servicePromiseHandlers.get(serviceType);
47514
- if (handler) {
47515
- const serviceError = new Error(`Service ${serviceType} failed to start due to runtime initialization failure: ${errorMsg}`);
47516
- handler.reject(serviceError);
47517
- this.servicePromiseHandlers.delete(serviceType);
47518
- this.servicePromises.delete(serviceType);
47519
- this.serviceRegistrationStatus.set(serviceType, "failed");
47520
- }
47815
+ agentEntity = await this.getEntityById(this.agentId);
47816
+ if (!agentEntity)
47817
+ throw new Error(`Agent entity not found for ${this.agentId}`);
47818
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent entity created");
47819
+ }
47820
+ const room = await this.getRoom(this.agentId);
47821
+ if (!room) {
47822
+ await this.createRoom({
47823
+ id: this.agentId,
47824
+ name: this.character.name,
47825
+ source: "elizaos",
47826
+ type: "SELF" /* SELF */,
47827
+ channelId: this.agentId,
47828
+ messageServerId: this.agentId,
47829
+ worldId: this.agentId
47830
+ });
47831
+ }
47832
+ const participants = await this.adapter.getParticipantsForRoom(this.agentId);
47833
+ if (!participants.includes(this.agentId)) {
47834
+ const added = await this.addParticipant(this.agentId, this.agentId);
47835
+ if (!added) {
47836
+ throw new Error(`Failed to add agent ${this.agentId} as participant to its own room`);
47521
47837
  }
47522
- throw error;
47838
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent linked to room");
47839
+ }
47840
+ const embeddingModel = this.getModel(ModelType.TEXT_EMBEDDING);
47841
+ if (!embeddingModel) {
47842
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "No TEXT_EMBEDDING model registered, skipping embedding setup");
47843
+ } else {
47844
+ await this.ensureEmbeddingDimension();
47845
+ }
47846
+ if (this.initResolver) {
47847
+ this.initResolver();
47848
+ this.initResolver = undefined;
47523
47849
  }
47524
47850
  }
47525
47851
  async runPluginMigrations() {
@@ -47531,29 +47857,29 @@ class AgentRuntime {
47531
47857
  this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter does not support plugin migrations");
47532
47858
  return;
47533
47859
  }
47534
- const pluginsWithSchemas = this.plugins.filter((p) => p.schema).map((p) => ({ name: p.name, schema: p.schema }));
47860
+ const pluginsWithSchemas = this.plugins.filter((p) => p.schema).map((p) => {
47861
+ const schema = p.schema || {};
47862
+ const normalizedSchema = {};
47863
+ for (const [key, value] of Object.entries(schema)) {
47864
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || typeof value === "object" && value !== null && !Array.isArray(value)) {
47865
+ normalizedSchema[key] = value;
47866
+ }
47867
+ }
47868
+ return { name: p.name, schema: normalizedSchema };
47869
+ });
47535
47870
  if (pluginsWithSchemas.length === 0) {
47536
47871
  this.logger.debug({ src: "agent", agentId: this.agentId }, "No plugins with schemas, skipping migrations");
47537
47872
  return;
47538
47873
  }
47539
47874
  this.logger.debug({ src: "agent", agentId: this.agentId, count: pluginsWithSchemas.length }, "Found plugins with schemas");
47540
- try {
47541
- const isProduction = false;
47542
- const forceDestructive = process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS === "true";
47543
- await this.adapter.runPluginMigrations(pluginsWithSchemas, {
47544
- verbose: !isProduction,
47545
- force: forceDestructive,
47546
- dryRun: false
47547
- });
47548
- this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
47549
- } catch (error) {
47550
- this.logger.error({
47551
- src: "agent",
47552
- agentId: this.agentId,
47553
- error: error instanceof Error ? error.message : String(error)
47554
- }, "Plugin migrations failed");
47555
- throw error;
47556
- }
47875
+ const isProduction = false;
47876
+ const forceDestructive = process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS === "true";
47877
+ await this.adapter.runPluginMigrations(pluginsWithSchemas, {
47878
+ verbose: !isProduction,
47879
+ force: forceDestructive,
47880
+ dryRun: false
47881
+ });
47882
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
47557
47883
  }
47558
47884
  async getConnection() {
47559
47885
  if (!this.adapter) {
@@ -47566,22 +47892,41 @@ class AgentRuntime {
47566
47892
  if (!this.character.secrets) {
47567
47893
  this.character.secrets = {};
47568
47894
  }
47569
- this.character.secrets[key] = value;
47895
+ if (value !== null && value !== undefined) {
47896
+ this.character.secrets[key] = value;
47897
+ }
47570
47898
  } else {
47571
47899
  if (!this.character.settings) {
47572
47900
  this.character.settings = {};
47573
47901
  }
47574
- this.character.settings[key] = value;
47902
+ if (value !== null && value !== undefined) {
47903
+ this.character.settings[key] = value;
47904
+ }
47575
47905
  }
47576
47906
  }
47577
47907
  getSetting(key) {
47578
- const value = this.character.secrets?.[key] || this.character.settings?.[key] || typeof this.character.settings === "object" && this.character.settings !== null && "secrets" in this.character.settings && this.character.settings.secrets?.[key] || this.settings[key];
47579
- const decryptedValue = decryptStringValue(value, getSalt());
47580
- if (decryptedValue === "true")
47581
- return true;
47582
- if (decryptedValue === "false")
47583
- return false;
47584
- return decryptedValue || null;
47908
+ const settings = this.character.settings;
47909
+ const secrets = this.character.secrets;
47910
+ const nestedSecrets = typeof settings === "object" && settings !== null && "secrets" in settings && typeof settings.secrets === "object" && settings.secrets !== null ? settings.secrets : undefined;
47911
+ const value = secrets?.[key] || settings?.[key] || nestedSecrets?.[key] || this.settings[key];
47912
+ if (value === undefined || value === null) {
47913
+ return null;
47914
+ }
47915
+ if (typeof value === "number") {
47916
+ return value;
47917
+ }
47918
+ if (typeof value === "boolean") {
47919
+ return value;
47920
+ }
47921
+ if (typeof value === "string") {
47922
+ const decrypted = decryptStringValue(value, getSalt());
47923
+ if (decrypted === "true")
47924
+ return true;
47925
+ if (decrypted === "false")
47926
+ return false;
47927
+ return decrypted;
47928
+ }
47929
+ return null;
47585
47930
  }
47586
47931
  getConversationLength() {
47587
47932
  return this.#conversationLength;
@@ -47622,7 +47967,7 @@ class AgentRuntime {
47622
47967
  steps: plan.steps.map((step, i) => i === index ? { ...step, ...stepUpdates } : step)
47623
47968
  };
47624
47969
  }
47625
- async processActions(message, responses, state, callback) {
47970
+ async processActions(message, responses, state, callback, processOptions) {
47626
47971
  const allActions = [];
47627
47972
  for (const response of responses) {
47628
47973
  if (response.content?.actions && response.content.actions.length > 0) {
@@ -47632,7 +47977,7 @@ class AgentRuntime {
47632
47977
  const hasMultipleActions = allActions.length > 1;
47633
47978
  const parentRunId = this.getCurrentRunId();
47634
47979
  const runId = this.createRunId();
47635
- let actionPlan = null;
47980
+ let actionPlan = undefined;
47636
47981
  const thought = responses[0]?.content?.thought || `Executing ${allActions.length} actions: ${allActions.join(", ")}`;
47637
47982
  if (hasMultipleActions) {
47638
47983
  actionPlan = {
@@ -47707,7 +48052,7 @@ class AgentRuntime {
47707
48052
  error: errorMsg
47708
48053
  });
47709
48054
  }
47710
- const actionMemory = {
48055
+ const actionMemory2 = {
47711
48056
  id: v4_default(),
47712
48057
  entityId: message.entityId,
47713
48058
  roomId: message.roomId,
@@ -47721,7 +48066,7 @@ class AgentRuntime {
47721
48066
  runId
47722
48067
  }
47723
48068
  };
47724
- await this.createMemory(actionMemory, "messages");
48069
+ await this.createMemory(actionMemory2, "messages");
47725
48070
  actionIndex++;
47726
48071
  continue;
47727
48072
  }
@@ -47736,255 +48081,214 @@ class AgentRuntime {
47736
48081
  actionIndex++;
47737
48082
  continue;
47738
48083
  }
47739
- try {
47740
- this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Executing action");
47741
- const actionId = v4_default();
47742
- this.currentActionContext = {
47743
- actionName: action.name,
47744
- actionId,
47745
- prompts: []
47746
- };
47747
- const actionContext = {
47748
- previousResults: actionResults,
47749
- getPreviousResult: (actionName) => {
47750
- return actionResults.find((r) => r.data?.actionName === actionName);
47751
- }
47752
- };
47753
- const options = {
47754
- actionContext
48084
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Executing action");
48085
+ const actionId = v4_default();
48086
+ const responseMessageId = v4_default();
48087
+ this.currentActionContext = {
48088
+ actionName: action.name,
48089
+ actionId,
48090
+ prompts: []
48091
+ };
48092
+ const actionContext = {
48093
+ previousResults: actionResults,
48094
+ getPreviousResult: (actionName) => {
48095
+ return actionResults.find((r) => r.data?.actionName === actionName);
48096
+ }
48097
+ };
48098
+ const options = {
48099
+ actionContext
48100
+ };
48101
+ if (actionPlan) {
48102
+ options.actionPlan = {
48103
+ totalSteps: actionPlan.totalSteps,
48104
+ currentStep: actionPlan.currentStep,
48105
+ steps: actionPlan.steps,
48106
+ thought: actionPlan.thought
47755
48107
  };
47756
- if (actionPlan) {
47757
- options.actionPlan = {
47758
- totalSteps: actionPlan.totalSteps,
47759
- currentStep: actionPlan.currentStep,
47760
- steps: actionPlan.steps,
47761
- thought: actionPlan.thought
47762
- };
48108
+ }
48109
+ if (processOptions?.onStreamChunk) {
48110
+ options.onStreamChunk = processOptions.onStreamChunk;
48111
+ }
48112
+ await this.emitEvent("ACTION_STARTED" /* ACTION_STARTED */, {
48113
+ messageId: actionId,
48114
+ roomId: message.roomId,
48115
+ world: message.worldId,
48116
+ content: {
48117
+ text: `Executing action: ${action.name}`,
48118
+ actions: [action.name],
48119
+ actionStatus: "executing",
48120
+ actionId,
48121
+ runId,
48122
+ type: "agent_action",
48123
+ thought,
48124
+ source: message.content?.source
47763
48125
  }
47764
- try {
47765
- await this.emitEvent("ACTION_STARTED" /* ACTION_STARTED */, {
47766
- messageId: actionId,
47767
- roomId: message.roomId,
47768
- world: message.worldId,
47769
- content: {
47770
- text: `Executing action: ${action.name}`,
47771
- actions: [action.name],
47772
- actionStatus: "executing",
47773
- actionId,
47774
- runId,
47775
- type: "agent_action",
47776
- thought,
47777
- source: message.content?.source
48126
+ });
48127
+ let storedCallbackData = [];
48128
+ const storageCallback = async (response2) => {
48129
+ response2.responseId = responseMessageId;
48130
+ storedCallbackData.push(response2);
48131
+ return [];
48132
+ };
48133
+ let actionStreamingContext;
48134
+ if (processOptions?.onStreamChunk) {
48135
+ let currentFilter = null;
48136
+ actionStreamingContext = {
48137
+ messageId: responseMessageId,
48138
+ onStreamChunk: async (chunk, msgId) => {
48139
+ if (!currentFilter) {
48140
+ currentFilter = new ActionStreamFilter;
47778
48141
  }
47779
- });
47780
- } catch (error) {
47781
- this.logger.error({ src: "agent", agentId: this.agentId, action: action.name, error: String(error) }, "Failed to emit action start event");
47782
- }
47783
- let storedCallbackData = [];
47784
- const storageCallback = async (response2) => {
47785
- storedCallbackData.push(response2);
47786
- return [];
47787
- };
47788
- const result = await action.handler(this, message, accumulatedState, options, storageCallback, responses);
47789
- const isLegacyReturn = result === undefined || result === null || typeof result === "boolean";
47790
- let actionResult = null;
47791
- if (!isLegacyReturn) {
47792
- if (typeof result === "object" && result !== null && (("values" in result) || ("data" in result) || ("text" in result))) {
47793
- actionResult = {
47794
- ...result,
47795
- success: "success" in result ? result.success : true
47796
- };
47797
- } else {
47798
- actionResult = {
47799
- success: true,
47800
- data: {
47801
- actionName: action.name,
47802
- legacyResult: result
47803
- }
47804
- };
47805
- }
47806
- actionResults.push(actionResult);
47807
- if (actionResult.values) {
47808
- accumulatedState = {
47809
- ...accumulatedState,
47810
- values: { ...accumulatedState.values, ...actionResult.values },
47811
- data: {
47812
- ...accumulatedState.data || {},
47813
- actionResults: [...accumulatedState.data?.actionResults || [], actionResult],
47814
- actionPlan
47815
- }
47816
- };
48142
+ const textToStream = currentFilter.push(chunk);
48143
+ if (textToStream) {
48144
+ await processOptions.onStreamChunk(textToStream, msgId);
48145
+ }
48146
+ },
48147
+ onStreamEnd: () => {
48148
+ currentFilter = null;
47817
48149
  }
47818
- if (actionResult && accumulatedState.data) {
47819
- if (!accumulatedState.data.workingMemory)
47820
- accumulatedState.data.workingMemory = {};
47821
- const memoryKey = `action_${responseAction}_${v4_default()}`;
47822
- const memoryEntry = {
48150
+ };
48151
+ }
48152
+ const result = await runWithStreamingContext(actionStreamingContext, () => action.handler(this, message, accumulatedState, options, storageCallback, responses));
48153
+ const isLegacyReturn = result === undefined || result === null || typeof result === "boolean";
48154
+ let actionResult = null;
48155
+ if (!isLegacyReturn) {
48156
+ if (typeof result === "object" && result !== null && (("values" in result) || ("data" in result) || ("text" in result))) {
48157
+ actionResult = {
48158
+ ...result,
48159
+ success: "success" in result ? result.success : true
48160
+ };
48161
+ } else {
48162
+ actionResult = {
48163
+ success: true,
48164
+ data: {
47823
48165
  actionName: action.name,
47824
- result: actionResult,
47825
- timestamp: Date.now()
47826
- };
47827
- accumulatedState.data.workingMemory[memoryKey] = memoryEntry;
47828
- const entries = Object.entries(accumulatedState.data.workingMemory);
47829
- if (entries.length > this.maxWorkingMemoryEntries) {
47830
- const sorted = entries.sort((a, b) => {
47831
- const entryA = a[1];
47832
- const entryB = b[1];
47833
- const timestampA = entryA?.timestamp ?? 0;
47834
- const timestampB = entryB?.timestamp ?? 0;
47835
- return timestampB - timestampA;
47836
- });
47837
- accumulatedState.data.workingMemory = Object.fromEntries(sorted.slice(0, this.maxWorkingMemoryEntries));
48166
+ legacyResult: result
47838
48167
  }
47839
- }
47840
- if (actionPlan && actionPlan.steps[actionIndex]) {
47841
- actionPlan = this.updateActionStep(actionPlan, actionIndex, {
47842
- status: "completed",
47843
- result: actionResult
47844
- });
47845
- }
48168
+ };
47846
48169
  }
47847
- try {
47848
- const isSuccess = actionResult?.success !== false;
47849
- const statusText = isSuccess ? "completed" : "failed";
47850
- await this.emitEvent("ACTION_COMPLETED" /* ACTION_COMPLETED */, {
47851
- messageId: actionId,
47852
- roomId: message.roomId,
47853
- world: message.worldId,
47854
- content: {
47855
- text: `Action ${action.name} ${statusText}`,
47856
- actions: [action.name],
47857
- actionStatus: statusText,
47858
- actionId,
47859
- type: "agent_action",
47860
- thought,
47861
- actionResult,
47862
- source: message.content?.source
48170
+ actionResults.push(actionResult);
48171
+ if (actionResult.values) {
48172
+ const existingActionResults = Array.isArray(accumulatedState.data?.actionResults) ? accumulatedState.data.actionResults : [];
48173
+ accumulatedState = {
48174
+ ...accumulatedState,
48175
+ values: { ...accumulatedState.values, ...actionResult.values },
48176
+ data: {
48177
+ ...accumulatedState.data || {},
48178
+ actionResults: [...existingActionResults, actionResult],
48179
+ actionPlan
47863
48180
  }
47864
- });
47865
- } catch (error) {
47866
- this.logger.error({
47867
- src: "agent",
47868
- agentId: this.agentId,
47869
- action: action.name,
47870
- error: error instanceof Error ? error.message : String(error)
47871
- }, "Failed to emit ACTION_COMPLETED event");
47872
- }
47873
- if (callback) {
47874
- for (const content of storedCallbackData) {
47875
- await callback(content);
47876
- }
48181
+ };
47877
48182
  }
47878
- const actionMemory = {
47879
- id: actionId,
47880
- entityId: this.agentId,
47881
- roomId: message.roomId,
47882
- worldId: message.worldId,
47883
- content: {
47884
- text: actionResult?.text || `Executed action: ${action.name}`,
47885
- source: "action",
47886
- type: "action_result",
47887
- actionName: action.name,
47888
- actionStatus: actionResult?.success ? "completed" : "failed",
47889
- actionResult: isLegacyReturn ? { legacy: result } : actionResult,
47890
- runId,
47891
- ...actionPlan && {
47892
- planStep: `${actionPlan.currentStep}/${actionPlan.totalSteps}`,
47893
- planThought: actionPlan.thought
47894
- }
47895
- },
47896
- metadata: {
47897
- type: "action_result",
48183
+ if (actionResult && accumulatedState.data) {
48184
+ if (!accumulatedState.data.workingMemory)
48185
+ accumulatedState.data.workingMemory = {};
48186
+ const responseAction2 = actionResult.data?.actionName || action.name;
48187
+ const memoryKey = `action_${responseAction2}_${v4_default()}`;
48188
+ const memoryEntry = {
47898
48189
  actionName: action.name,
47899
- runId,
47900
- parentRunId,
47901
- actionId,
47902
- ...actionPlan && {
47903
- totalSteps: actionPlan.totalSteps,
47904
- currentStep: actionPlan.currentStep
47905
- }
47906
- }
47907
- };
47908
- await this.createMemory(actionMemory, "messages");
47909
- this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Action completed");
47910
- await this.adapter.log({
47911
- entityId: message.entityId,
47912
- roomId: message.roomId,
47913
- type: "action",
47914
- body: {
47915
- action: action.name,
47916
- actionId,
47917
- message: message.content.text,
47918
- messageId: message.id,
47919
- state: accumulatedState,
47920
- responses,
47921
- result: isLegacyReturn ? { legacy: result } : actionResult,
47922
- isLegacyReturn,
47923
- prompts: this.currentActionContext?.prompts || [],
47924
- promptCount: this.currentActionContext?.prompts.length || 0,
47925
- runId,
47926
- parentRunId,
47927
- ...actionPlan && {
47928
- planStep: `${actionPlan.currentStep}/${actionPlan.totalSteps}`,
47929
- planThought: actionPlan.thought
47930
- }
48190
+ result: actionResult,
48191
+ timestamp: Date.now()
48192
+ };
48193
+ const workingMemory = accumulatedState.data.workingMemory;
48194
+ workingMemory[memoryKey] = memoryEntry;
48195
+ const entries = Object.entries(workingMemory);
48196
+ if (entries.length > this.maxWorkingMemoryEntries) {
48197
+ const sorted = entries.sort((a, b) => {
48198
+ const entryA = a[1];
48199
+ const entryB = b[1];
48200
+ const timestampA = entryA?.timestamp ?? 0;
48201
+ const timestampB = entryB?.timestamp ?? 0;
48202
+ return timestampB - timestampA;
48203
+ });
48204
+ accumulatedState.data.workingMemory = Object.fromEntries(sorted.slice(0, this.maxWorkingMemoryEntries));
47931
48205
  }
47932
- });
47933
- this.currentActionContext = undefined;
47934
- } catch (error) {
47935
- const errorMessage = error instanceof Error ? error.message : String(error);
47936
- this.logger.error({ src: "agent", agentId: this.agentId, action: action.name, error: errorMessage }, "Action execution failed");
48206
+ }
47937
48207
  if (actionPlan && actionPlan.steps[actionIndex]) {
47938
48208
  actionPlan = this.updateActionStep(actionPlan, actionIndex, {
47939
- status: "failed",
47940
- error: errorMessage
48209
+ status: "completed",
48210
+ result: actionResult
47941
48211
  });
47942
48212
  }
47943
- this.currentActionContext = undefined;
47944
- const errorResult = {
47945
- success: false,
47946
- data: {
47947
- actionName: action.name,
47948
- error: errorMessage,
47949
- errorObject: error
48213
+ }
48214
+ const isSuccess = actionResult?.success !== false;
48215
+ const statusText = isSuccess ? "completed" : "failed";
48216
+ await this.emitEvent("ACTION_COMPLETED" /* ACTION_COMPLETED */, {
48217
+ messageId: actionId,
48218
+ roomId: message.roomId,
48219
+ world: message.worldId,
48220
+ content: {
48221
+ text: actionResult?.text || "",
48222
+ actions: [action.name],
48223
+ actionStatus: statusText,
48224
+ actionId,
48225
+ type: "agent_action",
48226
+ thought,
48227
+ actionResult,
48228
+ source: message.content?.source
48229
+ }
48230
+ });
48231
+ if (callback) {
48232
+ for (const content of storedCallbackData) {
48233
+ await callback(content);
48234
+ }
48235
+ }
48236
+ const actionMemory = {
48237
+ id: actionId,
48238
+ entityId: this.agentId,
48239
+ roomId: message.roomId,
48240
+ worldId: message.worldId,
48241
+ content: {
48242
+ text: actionResult?.text || `Executed action: ${action.name}`,
48243
+ source: "action",
48244
+ type: "action_result",
48245
+ actionName: action.name,
48246
+ actionStatus: actionResult?.success ? "completed" : "failed",
48247
+ actionResult: isLegacyReturn ? { legacy: result } : actionResult,
48248
+ runId,
48249
+ ...actionPlan && {
48250
+ planStep: `${actionPlan.currentStep}/${actionPlan.totalSteps}`,
48251
+ planThought: actionPlan.thought
47950
48252
  }
47951
- };
47952
- actionResults.push(errorResult);
47953
- const actionMemory = {
47954
- id: v4_default(),
47955
- content: {
47956
- thought: errorMessage,
47957
- source: "auto",
47958
- type: "action_result",
47959
- actionName: action.name,
47960
- actionStatus: "failed",
47961
- error: errorMessage,
47962
- runId,
47963
- ...actionPlan && {
47964
- planStep: `${actionPlan.currentStep}/${actionPlan.totalSteps}`,
47965
- planThought: actionPlan.thought
47966
- }
47967
- },
47968
- entityId: this.agentId,
47969
- roomId: message.roomId,
47970
- worldId: message.worldId,
47971
- metadata: {
47972
- type: "action_result",
47973
- actionName: action.name,
47974
- runId,
47975
- parentRunId,
47976
- error: true,
47977
- ...actionPlan && {
47978
- totalSteps: actionPlan.totalSteps,
47979
- currentStep: actionPlan.currentStep
47980
- }
48253
+ },
48254
+ metadata: {
48255
+ type: "action_result",
48256
+ actionName: action.name,
48257
+ runId,
48258
+ parentRunId,
48259
+ actionId,
48260
+ ...actionPlan && {
48261
+ totalSteps: actionPlan.totalSteps,
48262
+ currentStep: actionPlan.currentStep
47981
48263
  }
47982
- };
47983
- await this.createMemory(actionMemory, "messages");
47984
- if (error?.critical || error?.code === "CRITICAL_ERROR") {
47985
- throw error;
47986
48264
  }
47987
- }
48265
+ };
48266
+ await this.createMemory(actionMemory, "messages");
48267
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Action completed");
48268
+ await this.adapter.log({
48269
+ entityId: message.entityId,
48270
+ roomId: message.roomId,
48271
+ type: "action",
48272
+ body: {
48273
+ action: action.name,
48274
+ actionId,
48275
+ message: message.content.text,
48276
+ messageId: message.id,
48277
+ state: accumulatedState,
48278
+ responses,
48279
+ result: isLegacyReturn ? { legacy: result } : actionResult,
48280
+ isLegacyReturn,
48281
+ prompts: this.currentActionContext?.prompts || [],
48282
+ promptCount: this.currentActionContext?.prompts.length || 0,
48283
+ runId,
48284
+ parentRunId,
48285
+ ...actionPlan && {
48286
+ planStep: `${actionPlan.currentStep}/${actionPlan.totalSteps}`,
48287
+ planThought: actionPlan.thought
48288
+ }
48289
+ }
48290
+ });
48291
+ this.currentActionContext = undefined;
47988
48292
  actionIndex++;
47989
48293
  }
47990
48294
  if (message.id) {
@@ -48001,81 +48305,49 @@ class AgentRuntime {
48001
48305
  return cachedState?.data?.actionResults || [];
48002
48306
  }
48003
48307
  async evaluate(message, state, didRespond, callback, responses) {
48004
- try {
48005
- const evaluatorPromises = this.evaluators.map(async (evaluator) => {
48006
- try {
48007
- if (!evaluator.handler) {
48008
- return null;
48009
- }
48010
- if (!didRespond && !evaluator.alwaysRun) {
48011
- return null;
48012
- }
48013
- const result = await evaluator.validate(this, message, state);
48014
- if (result) {
48015
- return evaluator;
48016
- }
48017
- return null;
48018
- } catch (error) {
48019
- this.logger.error({
48020
- src: "agent",
48021
- agentId: this.agentId,
48022
- evaluator: evaluator.name,
48023
- error: error instanceof Error ? error.message : String(error)
48024
- }, "Evaluator validation failed");
48025
- return null;
48026
- }
48027
- });
48028
- const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
48029
- if (evaluators.length === 0) {
48030
- return [];
48308
+ const evaluatorPromises = this.evaluators.map(async (evaluator) => {
48309
+ if (!evaluator.handler) {
48310
+ return null;
48031
48311
  }
48032
- state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
48033
- await Promise.all(evaluators.map(async (evaluator) => {
48034
- try {
48035
- if (evaluator.handler) {
48036
- await evaluator.handler(this, message, state, {}, callback, responses);
48037
- this.adapter.log({
48038
- entityId: message.entityId,
48039
- roomId: message.roomId,
48040
- type: "evaluator",
48041
- body: {
48042
- evaluator: evaluator.name,
48043
- messageId: message.id,
48044
- message: message.content.text,
48045
- state,
48046
- runId: this.getCurrentRunId()
48047
- }
48048
- });
48049
- }
48050
- } catch (error) {
48051
- this.logger.error({
48052
- src: "agent",
48053
- agentId: this.agentId,
48054
- evaluator: evaluator.name,
48055
- error: error instanceof Error ? error.message : String(error)
48056
- }, "Evaluator execution failed");
48057
- }
48058
- }));
48059
- return evaluators;
48060
- } catch (error) {
48061
- this.logger.error({
48062
- src: "agent",
48063
- agentId: this.agentId,
48064
- messageId: message.id,
48065
- channelId: message.roomId,
48066
- error: error instanceof Error ? error.message : String(error)
48067
- }, "Evaluate method failed");
48312
+ if (!didRespond && !evaluator.alwaysRun) {
48313
+ return null;
48314
+ }
48315
+ const result = await evaluator.validate(this, message, state);
48316
+ if (result) {
48317
+ return evaluator;
48318
+ }
48319
+ return null;
48320
+ });
48321
+ const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
48322
+ if (evaluators.length === 0) {
48068
48323
  return [];
48069
48324
  }
48325
+ state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
48326
+ await Promise.all(evaluators.map(async (evaluator) => {
48327
+ if (evaluator.handler) {
48328
+ await evaluator.handler(this, message, state, {}, callback, responses);
48329
+ this.adapter.log({
48330
+ entityId: message.entityId,
48331
+ roomId: message.roomId,
48332
+ type: "evaluator",
48333
+ body: {
48334
+ evaluator: evaluator.name,
48335
+ messageId: message.id,
48336
+ message: message.content.text,
48337
+ state,
48338
+ runId: this.getCurrentRunId()
48339
+ }
48340
+ });
48341
+ }
48342
+ }));
48343
+ return evaluators;
48070
48344
  }
48071
48345
  async ensureConnections(entities, rooms, source, world) {
48072
48346
  if (!entities) {
48073
- console.trace();
48074
48347
  this.logger.error({ src: "agent", agentId: this.agentId }, "ensureConnections called without entities");
48075
48348
  return;
48076
48349
  }
48077
48350
  if (!rooms || rooms.length === 0) {
48078
- console.trace();
48079
48351
  this.logger.error({ src: "agent", agentId: this.agentId }, "ensureConnections called without rooms");
48080
48352
  return;
48081
48353
  }
@@ -48099,13 +48371,13 @@ class AgentRuntime {
48099
48371
  };
48100
48372
  if (roomsToCreate.length) {
48101
48373
  this.logger.debug({ src: "agent", agentId: this.agentId, count: roomsToCreate.length }, "Creating rooms");
48102
- const roomObjsToCreate = rooms.filter((r2) => roomsToCreate.includes(r2.id)).map((r2) => ({ ...r2, ...rf }));
48374
+ const roomObjsToCreate = rooms.filter((r2) => roomsToCreate.includes(r2.id)).map((r2) => ({ ...r2, ...rf, type: r2.type || "GROUP" /* GROUP */ }));
48103
48375
  await this.createRooms(roomObjsToCreate);
48104
48376
  }
48105
- const entityIds = entities.map((e) => e.id);
48377
+ const entityIds = entities.map((e) => e.id).filter((id) => id !== undefined);
48106
48378
  const entityExistsCheck = await this.adapter.getEntitiesByIds(entityIds);
48107
- const entitiesToUpdate = entityExistsCheck?.map((e) => e.id);
48108
- const entitiesToCreate = entities.filter((e) => !entitiesToUpdate?.includes(e.id));
48379
+ const entitiesToUpdate = entityExistsCheck?.map((e) => e.id).filter((id) => id !== undefined) || [];
48380
+ const entitiesToCreate = entities.filter((e) => e.id !== undefined && !entitiesToUpdate.includes(e.id));
48109
48381
  const r = {
48110
48382
  roomId: firstRoom.id,
48111
48383
  channelId: firstRoom.channelId,
@@ -48123,7 +48395,11 @@ class AgentRuntime {
48123
48395
  source,
48124
48396
  agentId: this.agentId
48125
48397
  };
48126
- const entitiesToCreateWFields = entitiesToCreate.map((e) => ({ ...e, ...ef }));
48398
+ const entitiesToCreateWFields = entitiesToCreate.map((e) => ({
48399
+ ...e,
48400
+ ...ef,
48401
+ metadata: e.metadata || {}
48402
+ }));
48127
48403
  const batches = chunkArray(entitiesToCreateWFields, 5000);
48128
48404
  for (const batch of batches) {
48129
48405
  await this.createEntities(batch);
@@ -48131,7 +48407,7 @@ class AgentRuntime {
48131
48407
  }
48132
48408
  await this.ensureParticipantInRoom(this.agentId, firstRoom.id);
48133
48409
  const entityIdsInFirstRoom = await this.getParticipantsForRoom(firstRoom.id);
48134
- const entityIdsInFirstRoomFiltered = entityIdsInFirstRoom.filter(Boolean);
48410
+ const entityIdsInFirstRoomFiltered = entityIdsInFirstRoom.filter((id) => id !== undefined);
48135
48411
  const missingIdsInRoom = entityIds.filter((id) => !entityIdsInFirstRoomFiltered.includes(id));
48136
48412
  if (missingIdsInRoom.length) {
48137
48413
  this.logger.debug({
@@ -48172,85 +48448,54 @@ class AgentRuntime {
48172
48448
  userName
48173
48449
  }
48174
48450
  };
48175
- try {
48176
- const entity = await this.getEntityById(entityId);
48177
- if (!entity) {
48178
- try {
48179
- const success = await this.createEntity({
48180
- id: entityId,
48181
- names: names3,
48182
- metadata: entityMetadata,
48183
- agentId: this.agentId
48184
- });
48185
- if (success) {
48186
- this.logger.debug({ src: "agent", agentId: this.agentId, entityId, userName: name || userName }, "Entity created");
48187
- } else {
48188
- throw new Error(`Failed to create entity ${entityId}`);
48189
- }
48190
- } catch (error) {
48191
- if (error.message?.includes("duplicate key") || error.code === "23505") {
48192
- this.logger.debug({ src: "agent", agentId: this.agentId, entityId }, "Entity exists in database (multi-agent setup)");
48193
- } else {
48194
- throw error;
48195
- }
48196
- }
48451
+ const entity = await this.getEntityById(entityId);
48452
+ if (!entity) {
48453
+ const success = await this.createEntity({
48454
+ id: entityId,
48455
+ names: names3,
48456
+ metadata: entityMetadata,
48457
+ agentId: this.agentId
48458
+ });
48459
+ if (success) {
48460
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, userName: name || userName }, "Entity created");
48197
48461
  } else {
48198
- await this.adapter.updateEntity({
48199
- id: entityId,
48200
- names: [...new Set([...entity.names || [], ...names3])].filter(Boolean),
48201
- metadata: {
48202
- ...entity.metadata,
48203
- [source]: {
48204
- ...entity.metadata?.[source],
48205
- id: userId,
48206
- name,
48207
- userName
48208
- }
48209
- },
48210
- agentId: this.agentId
48211
- });
48462
+ throw new Error(`Failed to create entity ${entityId}`);
48212
48463
  }
48213
- await this.ensureWorldExists({
48214
- id: worldId,
48215
- name: worldName || messageServerId ? `World for server ${messageServerId}` : `World for room ${roomId}`,
48216
- agentId: this.agentId,
48217
- messageServerId,
48218
- metadata
48219
- });
48220
- await this.ensureRoomExists({
48221
- id: roomId,
48222
- name: name || "default",
48223
- source: source || "default",
48224
- type: type || "DM" /* DM */,
48225
- channelId,
48226
- messageServerId,
48227
- worldId
48228
- });
48229
- try {
48230
- await this.ensureParticipantInRoom(entityId, roomId);
48231
- } catch (error) {
48232
- if (error.message?.includes("not found")) {
48233
- const added = await this.addParticipant(entityId, roomId);
48234
- if (!added) {
48235
- throw new Error(`Failed to add participant ${entityId} to room ${roomId}`);
48464
+ } else {
48465
+ await this.adapter.updateEntity({
48466
+ id: entityId,
48467
+ names: [...new Set([...entity.names || [], ...names3])].filter(Boolean),
48468
+ metadata: {
48469
+ ...entity.metadata,
48470
+ [source]: {
48471
+ ...entity.metadata?.[source] && typeof entity.metadata[source] === "object" ? entity.metadata[source] : {},
48472
+ id: userId,
48473
+ name,
48474
+ userName
48236
48475
  }
48237
- this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Participant added");
48238
- } else {
48239
- throw error;
48240
- }
48241
- }
48242
- await this.ensureParticipantInRoom(this.agentId, roomId);
48243
- this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Entity connected");
48244
- } catch (error) {
48245
- this.logger.error({
48246
- src: "agent",
48247
- agentId: this.agentId,
48248
- entityId,
48249
- channelId: roomId,
48250
- error: error instanceof Error ? error.message : String(error)
48251
- }, "Connection setup failed");
48252
- throw error;
48476
+ },
48477
+ agentId: this.agentId
48478
+ });
48253
48479
  }
48480
+ await this.ensureWorldExists({
48481
+ id: worldId,
48482
+ name: worldName || messageServerId ? `World for server ${messageServerId}` : `World for room ${roomId}`,
48483
+ agentId: this.agentId,
48484
+ messageServerId,
48485
+ metadata
48486
+ });
48487
+ await this.ensureRoomExists({
48488
+ id: roomId,
48489
+ name: name || "default",
48490
+ source: source || "default",
48491
+ type: type || "DM" /* DM */,
48492
+ channelId,
48493
+ messageServerId,
48494
+ worldId
48495
+ });
48496
+ await this.ensureParticipantInRoom(entityId, roomId);
48497
+ await this.ensureParticipantInRoom(this.agentId, roomId);
48498
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Entity connected");
48254
48499
  }
48255
48500
  async ensureParticipantInRoom(entityId, roomId) {
48256
48501
  const entity = await this.getEntityById(entityId);
@@ -48354,29 +48599,26 @@ class AgentRuntime {
48354
48599
  const providersToGet = Array.from(new Set(this.providers.filter((p) => providerNames.has(p.name)))).sort((a, b) => (a.position || 0) - (b.position || 0));
48355
48600
  const providerData = await Promise.all(providersToGet.map(async (provider) => {
48356
48601
  const start = Date.now();
48357
- try {
48358
- const result = await provider.get(this, message, cachedState);
48359
- const duration = Date.now() - start;
48360
- if (duration > 100) {
48361
- this.logger.debug({ src: "agent", agentId: this.agentId, provider: provider.name, duration }, "Slow provider");
48362
- }
48363
- return {
48364
- ...result,
48365
- providerName: provider.name
48366
- };
48367
- } catch (error) {
48368
- console.error("provider error", provider.name, error);
48369
- return { values: {}, text: "", data: {}, providerName: provider.name };
48602
+ const result = await provider.get(this, message, cachedState);
48603
+ const duration = Date.now() - start;
48604
+ if (duration > 100) {
48605
+ this.logger.debug({ src: "agent", agentId: this.agentId, provider: provider.name, duration }, "Slow provider");
48370
48606
  }
48607
+ return {
48608
+ ...result,
48609
+ providerName: provider.name
48610
+ };
48371
48611
  }));
48372
- const currentProviderResults = { ...cachedState.data?.providers || {} };
48612
+ const currentProviderResults = {
48613
+ ...cachedState.data?.providers || {}
48614
+ };
48373
48615
  for (const freshResult of providerData) {
48374
48616
  currentProviderResults[freshResult.providerName] = freshResult;
48375
48617
  }
48376
48618
  const orderedTexts = [];
48377
48619
  for (const provider of providersToGet) {
48378
48620
  const result = currentProviderResults[provider.name];
48379
- if (result && result.text && result.text.trim() !== "") {
48621
+ if (result && result.text && typeof result.text === "string" && result.text.trim() !== "") {
48380
48622
  orderedTexts.push(result.text);
48381
48623
  }
48382
48624
  }
@@ -48385,14 +48627,14 @@ class AgentRuntime {
48385
48627
  const aggregatedStateValues = { ...cachedState.values || {} };
48386
48628
  for (const provider of providersToGet) {
48387
48629
  const providerResult = currentProviderResults[provider.name];
48388
- if (providerResult && providerResult.values && typeof providerResult.values === "object") {
48630
+ if (providerResult && providerResult.values && typeof providerResult.values === "object" && providerResult.values !== null) {
48389
48631
  Object.assign(aggregatedStateValues, providerResult.values);
48390
48632
  }
48391
48633
  }
48392
48634
  for (const providerName in currentProviderResults) {
48393
48635
  if (!providersToGet.some((p) => p.name === providerName)) {
48394
48636
  const providerResult = currentProviderResults[providerName];
48395
- if (providerResult && providerResult.values && typeof providerResult.values === "object") {
48637
+ if (providerResult && providerResult.values && typeof providerResult.values === "object" && providerResult.values !== null) {
48396
48638
  Object.assign(aggregatedStateValues, providerResult.values);
48397
48639
  }
48398
48640
  }
@@ -48471,73 +48713,40 @@ class AgentRuntime {
48471
48713
  }
48472
48714
  this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Registering service");
48473
48715
  this.serviceRegistrationStatus.set(serviceType, "registering");
48474
- try {
48475
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service waiting for init");
48476
- const initTimeout = new Promise((_, reject) => {
48477
- setTimeout(() => {
48478
- reject(new Error(`Service ${serviceType} registration timed out waiting for runtime initialization (30s timeout)`));
48479
- }, 30000);
48480
- });
48481
- await Promise.race([this.initPromise, initTimeout]);
48482
- if (typeof serviceDef.start !== "function") {
48483
- throw new Error(`Service ${serviceType} does not have a static start method. All services must implement static async start(runtime: IAgentRuntime): Promise<Service>.`);
48484
- }
48485
- const serviceInstance = await serviceDef.start(this);
48486
- if (!serviceInstance) {
48487
- throw new Error(`Service ${serviceType} start() method returned null or undefined. It must return a Service instance.`);
48488
- }
48489
- if (!this.services.has(serviceType)) {
48490
- this.services.set(serviceType, []);
48491
- }
48492
- if (!this.serviceTypes.has(serviceType)) {
48493
- this.serviceTypes.set(serviceType, []);
48494
- }
48495
- this.services.get(serviceType).push(serviceInstance);
48496
- this.serviceTypes.get(serviceType).push(serviceDef);
48497
- const handler = this.servicePromiseHandlers.get(serviceType);
48498
- if (handler) {
48499
- handler.resolve(serviceInstance);
48500
- this.servicePromiseHandlers.delete(serviceType);
48501
- } else {
48502
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service has no promise handler");
48503
- }
48504
- if (typeof serviceDef.registerSendHandlers === "function") {
48505
- serviceDef.registerSendHandlers(this, serviceInstance);
48506
- }
48507
- this.serviceRegistrationStatus.set(serviceType, "registered");
48508
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service registered");
48509
- } catch (error) {
48510
- const errorMessage = error instanceof Error ? error.message : String(error);
48511
- const errorStack = error instanceof Error ? error.stack : undefined;
48512
- this.logger.error({ src: "agent", agentId: this.agentId, serviceType, error: errorMessage }, "Service registration failed");
48513
- if (errorStack) {
48514
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType, stack: errorStack }, "Service error stack");
48515
- }
48516
- if (error?.message?.includes("timed out waiting for runtime initialization")) {
48517
- this.logger.error(`Service ${serviceType} failed due to runtime initialization timeout. Check if runtime.initialize() is being called and completing successfully.`);
48518
- } else if (error?.message?.includes("Not implemented")) {
48519
- this.logger.error(`Service ${serviceType} failed because it does not implement the static start() method. ` + `All services must override the base Service.start() method. ` + `Add: static async start(runtime: IAgentRuntime): Promise<${serviceName}> { return new ${serviceName}(runtime); }`);
48520
- if (errorStack) {
48521
- this.logger.debug(`Stack trace: ${errorStack}`);
48522
- }
48523
- } else if (error?.message?.includes("Service") && error?.message?.includes("failed to start")) {
48524
- this.logger.error(`Service ${serviceType} (${serviceName}) failed to start. Check service implementation and dependencies.`);
48525
- } else if (error?.message?.includes("does not have a static start method")) {
48526
- this.logger.error({ src: "agent", agentId: this.agentId, serviceType, serviceName, error: error?.message }, "Service missing required static start() method implementation");
48527
- } else {
48528
- if (errorStack) {
48529
- this.logger.debug({ src: "agent", agentId: this.agentId, serviceType, serviceName, stack: errorStack }, "Service error stack");
48530
- }
48531
- }
48532
- this.serviceRegistrationStatus.set(serviceType, "failed");
48533
- const handler = this.servicePromiseHandlers.get(serviceType);
48534
- if (handler) {
48535
- handler.reject(error);
48536
- this.servicePromiseHandlers.delete(serviceType);
48537
- this.servicePromises.delete(serviceType);
48538
- }
48539
- throw error;
48716
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service waiting for init");
48717
+ const initTimeout = new Promise((_, reject) => {
48718
+ setTimeout(() => {
48719
+ reject(new Error(`Service ${serviceType} registration timed out waiting for runtime initialization (30s timeout)`));
48720
+ }, 30000);
48721
+ });
48722
+ await Promise.race([this.initPromise, initTimeout]);
48723
+ if (typeof serviceDef.start !== "function") {
48724
+ throw new Error(`Service ${serviceType} does not have a static start method. All services must implement static async start(runtime: IAgentRuntime): Promise<Service>.`);
48725
+ }
48726
+ const serviceInstance = await serviceDef.start(this);
48727
+ if (!serviceInstance) {
48728
+ throw new Error(`Service ${serviceType} start() method returned null or undefined. It must return a Service instance.`);
48729
+ }
48730
+ if (!this.services.has(serviceType)) {
48731
+ this.services.set(serviceType, []);
48732
+ }
48733
+ if (!this.serviceTypes.has(serviceType)) {
48734
+ this.serviceTypes.set(serviceType, []);
48735
+ }
48736
+ this.services.get(serviceType).push(serviceInstance);
48737
+ this.serviceTypes.get(serviceType).push(serviceDef);
48738
+ const handler = this.servicePromiseHandlers.get(serviceType);
48739
+ if (handler) {
48740
+ handler.resolve(serviceInstance);
48741
+ this.servicePromiseHandlers.delete(serviceType);
48742
+ } else {
48743
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service has no promise handler");
48744
+ }
48745
+ if (serviceDef.registerSendHandlers) {
48746
+ serviceDef.constructor.registerSendHandlers?.(this, serviceInstance);
48540
48747
  }
48748
+ this.serviceRegistrationStatus.set(serviceType, "registered");
48749
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service registered");
48541
48750
  }
48542
48751
  _createServiceResolver(serviceType) {
48543
48752
  let resolver;
@@ -48581,21 +48790,12 @@ class AgentRuntime {
48581
48790
  return (a.registrationOrder || 0) - (b.registrationOrder || 0);
48582
48791
  });
48583
48792
  }
48584
- getModel(modelType, provider) {
48793
+ getModel(modelType) {
48585
48794
  const modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
48586
48795
  const models = this.models.get(modelKey);
48587
48796
  if (!models?.length) {
48588
48797
  return;
48589
48798
  }
48590
- if (provider) {
48591
- const modelWithProvider = models.find((m) => m.provider === provider);
48592
- if (modelWithProvider) {
48593
- this.logger.debug({ src: "agent", agentId: this.agentId, model: modelKey, provider }, "Using model");
48594
- return modelWithProvider.handler;
48595
- } else {
48596
- this.logger.warn({ src: "agent", agentId: this.agentId, model: modelKey, provider }, "Model provider not found");
48597
- }
48598
- }
48599
48799
  this.logger.debug({ src: "agent", agentId: this.agentId, model: modelKey, provider: models[0].provider }, "Using model");
48600
48800
  return models[0].handler;
48601
48801
  }
@@ -48662,9 +48862,12 @@ class AgentRuntime {
48662
48862
  }
48663
48863
  async useModel(modelType, params, provider) {
48664
48864
  const modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
48665
- const promptContent = params?.prompt || params?.input || (Array.isArray(params?.messages) ? JSON.stringify(params.messages) : null);
48666
- const model = this.getModel(modelKey, provider);
48667
- if (!model) {
48865
+ const paramsObj = params;
48866
+ const promptContent = (paramsObj && "prompt" in paramsObj && typeof paramsObj.prompt === "string" ? paramsObj.prompt : null) || (paramsObj && "input" in paramsObj && typeof paramsObj.input === "string" ? paramsObj.input : null) || (paramsObj && "messages" in paramsObj && Array.isArray(paramsObj.messages) ? JSON.stringify(paramsObj.messages) : null);
48867
+ const model = this.getModel(modelKey);
48868
+ const modelWithProvider = provider && this.models.get(modelKey)?.find((m) => m.provider === provider);
48869
+ const handler = modelWithProvider ? modelWithProvider.handler : model;
48870
+ if (!handler) {
48668
48871
  const errorMsg = `No handler found for delegate type: ${modelKey}`;
48669
48872
  throw new Error(errorMsg);
48670
48873
  }
@@ -48706,57 +48909,94 @@ class AgentRuntime {
48706
48909
  }
48707
48910
  if (isPlainObject(modelParams)) {
48708
48911
  if (modelParams.user === undefined && this.character?.name) {
48709
- modelParams.user = this.character.name;
48912
+ if (typeof modelParams === "object" && modelParams !== null && !Array.isArray(modelParams)) {
48913
+ modelParams.user = this.character.name;
48914
+ }
48710
48915
  }
48711
48916
  }
48712
48917
  }
48713
48918
  const startTime = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
48714
- try {
48715
- const response = await model(this, modelParams);
48716
- const elapsedTime = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
48919
+ const streamingCtx = getStreamingContext();
48920
+ const paramsChunk = isPlainObject(modelParams) ? modelParams.onStreamChunk : undefined;
48921
+ const ctxChunk = streamingCtx?.onStreamChunk;
48922
+ const msgId = streamingCtx?.messageId;
48923
+ const abortSignal = streamingCtx?.abortSignal;
48924
+ const explicitStream = isPlainObject(modelParams) ? modelParams.stream : undefined;
48925
+ const shouldStream = explicitStream === false ? false : !!(paramsChunk || ctxChunk || explicitStream);
48926
+ if (isPlainObject(modelParams)) {
48927
+ modelParams.stream = shouldStream;
48928
+ delete modelParams.onStreamChunk;
48929
+ }
48930
+ const response = await handler(this, modelParams);
48931
+ if (shouldStream && (paramsChunk || ctxChunk) && response && typeof response === "object" && "textStream" in response) {
48932
+ let fullText = "";
48933
+ for await (const chunk of response.textStream) {
48934
+ if (abortSignal?.aborted)
48935
+ break;
48936
+ fullText += chunk;
48937
+ try {
48938
+ if (paramsChunk)
48939
+ await paramsChunk(chunk, msgId);
48940
+ } catch {}
48941
+ try {
48942
+ if (ctxChunk)
48943
+ await ctxChunk(chunk, msgId);
48944
+ } catch {}
48945
+ }
48946
+ const ctxEnd = getStreamingContext()?.onStreamEnd;
48947
+ if (ctxEnd)
48948
+ ctxEnd();
48949
+ const elapsedTime2 = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
48717
48950
  this.logger.trace({
48718
48951
  src: "agent",
48719
48952
  agentId: this.agentId,
48720
48953
  model: modelKey,
48721
- duration: Number(elapsedTime.toFixed(2))
48722
- }, "Model output");
48723
- if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
48724
- if (this.currentActionContext) {
48725
- this.currentActionContext.prompts.push({
48726
- modelType: modelKey,
48727
- prompt: promptContent,
48728
- timestamp: Date.now()
48729
- });
48730
- }
48731
- }
48732
- this.adapter.log({
48733
- entityId: this.agentId,
48734
- roomId: this.currentRoomId ?? this.agentId,
48735
- body: {
48736
- modelType,
48737
- modelKey,
48738
- params: {
48739
- ...typeof params === "object" && !Array.isArray(params) && params ? params : {},
48740
- prompt: promptContent
48741
- },
48954
+ duration: Number(elapsedTime2.toFixed(2)),
48955
+ streaming: true
48956
+ }, "Model output (stream with callback complete)");
48957
+ return fullText;
48958
+ }
48959
+ const elapsedTime = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
48960
+ this.logger.trace({
48961
+ src: "agent",
48962
+ agentId: this.agentId,
48963
+ model: modelKey,
48964
+ duration: Number(elapsedTime.toFixed(2))
48965
+ }, "Model output");
48966
+ if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
48967
+ if (this.currentActionContext) {
48968
+ this.currentActionContext.prompts.push({
48969
+ modelType: modelKey,
48742
48970
  prompt: promptContent,
48743
- systemPrompt: this.character?.system || null,
48744
- runId: this.getCurrentRunId(),
48745
- timestamp: Date.now(),
48746
- executionTime: elapsedTime,
48747
- provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
48748
- actionContext: this.currentActionContext ? {
48749
- actionName: this.currentActionContext.actionName,
48750
- actionId: this.currentActionContext.actionId
48751
- } : undefined,
48752
- response: Array.isArray(response) && response.every((x) => typeof x === "number") ? "[array]" : response
48753
- },
48754
- type: `useModel:${modelKey}`
48755
- });
48756
- return response;
48757
- } catch (error) {
48758
- throw error;
48971
+ timestamp: Date.now()
48972
+ });
48973
+ }
48759
48974
  }
48975
+ this.adapter.log({
48976
+ entityId: this.agentId,
48977
+ roomId: this.currentRoomId ?? this.agentId,
48978
+ body: {
48979
+ modelType,
48980
+ modelKey,
48981
+ params: {
48982
+ ...typeof params === "object" && !Array.isArray(params) && params ? params : {},
48983
+ prompt: promptContent
48984
+ },
48985
+ prompt: promptContent,
48986
+ systemPrompt: this.character?.system || null,
48987
+ runId: this.getCurrentRunId(),
48988
+ timestamp: Date.now(),
48989
+ executionTime: elapsedTime,
48990
+ provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
48991
+ actionContext: this.currentActionContext ? {
48992
+ actionName: this.currentActionContext.actionName,
48993
+ actionId: this.currentActionContext.actionId
48994
+ } : undefined,
48995
+ response: Array.isArray(response) && response.every((x) => typeof x === "number") ? "[array]" : response
48996
+ },
48997
+ type: `useModel:${modelKey}`
48998
+ });
48999
+ return response;
48760
49000
  }
48761
49001
  async generateText(input, options) {
48762
49002
  if (!input?.trim()) {
@@ -48827,45 +49067,32 @@ ${input}`;
48827
49067
  if (!eventHandlers) {
48828
49068
  continue;
48829
49069
  }
48830
- try {
48831
- let paramsWithRuntime = { runtime: this };
48832
- if (typeof params === "object" && params) {
48833
- paramsWithRuntime = { ...params, ...paramsWithRuntime };
48834
- }
48835
- await Promise.all(eventHandlers.map((handler) => handler(paramsWithRuntime)));
48836
- } catch (error) {
48837
- this.logger.error({
48838
- src: "agent",
48839
- agentId: this.agentId,
48840
- eventName,
48841
- error: error instanceof Error ? error.message : String(error)
48842
- }, "Event handler failed");
49070
+ let paramsWithRuntime = { runtime: this, source: "runtime" };
49071
+ if (typeof params === "object" && params && params !== null) {
49072
+ const paramsObj = params;
49073
+ paramsWithRuntime = {
49074
+ ...paramsObj,
49075
+ runtime: this,
49076
+ source: paramsObj.source || "runtime"
49077
+ };
48843
49078
  }
49079
+ await Promise.all(eventHandlers.map((handler) => handler(paramsWithRuntime)));
48844
49080
  }
48845
49081
  }
48846
49082
  async ensureEmbeddingDimension() {
48847
49083
  if (!this.adapter) {
48848
49084
  throw new Error("Database adapter not initialized before ensureEmbeddingDimension");
48849
49085
  }
48850
- try {
48851
- const model = this.getModel(ModelType.TEXT_EMBEDDING);
48852
- if (!model) {
48853
- throw new Error("No TEXT_EMBEDDING model registered");
48854
- }
48855
- const embedding = await this.useModel(ModelType.TEXT_EMBEDDING, null);
48856
- if (!embedding || !embedding.length) {
48857
- throw new Error("Invalid embedding received");
48858
- }
48859
- await this.adapter.ensureEmbeddingDimension(embedding.length);
48860
- this.logger.debug({ src: "agent", agentId: this.agentId, dimension: embedding.length }, "Embedding dimension set");
48861
- } catch (error) {
48862
- this.logger.error({
48863
- src: "agent",
48864
- agentId: this.agentId,
48865
- error: error instanceof Error ? error.message : String(error)
48866
- }, "Embedding dimension setup failed");
48867
- throw error;
49086
+ const model = this.getModel(ModelType.TEXT_EMBEDDING);
49087
+ if (!model) {
49088
+ throw new Error("No TEXT_EMBEDDING model registered");
49089
+ }
49090
+ const embedding = await this.useModel(ModelType.TEXT_EMBEDDING, { text: "" });
49091
+ if (!embedding || !embedding.length) {
49092
+ throw new Error("Invalid embedding received");
48868
49093
  }
49094
+ await this.adapter.ensureEmbeddingDimension(embedding.length);
49095
+ this.logger.debug({ src: "agent", agentId: this.agentId, dimension: embedding.length }, "Embedding dimension set");
48869
49096
  }
48870
49097
  registerTaskWorker(taskHandler) {
48871
49098
  if (this.taskWorkers.has(taskHandler.name)) {
@@ -49005,7 +49232,7 @@ ${input}`;
49005
49232
  agentId: this.agentId,
49006
49233
  error: error instanceof Error ? error.message : String(error)
49007
49234
  }, "Embedding generation failed");
49008
- memory.embedding = await this.useModel(ModelType.TEXT_EMBEDDING, null);
49235
+ memory.embedding = await this.useModel(ModelType.TEXT_EMBEDDING, { text: "" });
49009
49236
  }
49010
49237
  return memory;
49011
49238
  }
@@ -49268,16 +49495,16 @@ ${input}`;
49268
49495
  }
49269
49496
  }
49270
49497
  async sendControlMessage(params) {
49498
+ const { roomId, action, target } = params;
49499
+ const controlMessage = {
49500
+ type: "control",
49501
+ payload: {
49502
+ action,
49503
+ target
49504
+ },
49505
+ roomId
49506
+ };
49271
49507
  try {
49272
- const { roomId, action, target } = params;
49273
- const controlMessage = {
49274
- type: "control",
49275
- payload: {
49276
- action,
49277
- target
49278
- },
49279
- roomId
49280
- };
49281
49508
  await this.emitEvent("CONTROL_MESSAGE", {
49282
49509
  runtime: this,
49283
49510
  message: controlMessage,
@@ -49322,7 +49549,7 @@ ${input}`;
49322
49549
  return await this.adapter.getMemoriesByWorldId(params);
49323
49550
  }
49324
49551
  async runMigrations(migrationsPaths) {
49325
- if (this.adapter && "runMigrations" in this.adapter) {
49552
+ if (this.adapter?.runMigrations) {
49326
49553
  await this.adapter.runMigrations(migrationsPaths);
49327
49554
  } else {
49328
49555
  this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter does not support migrations");
@@ -49373,11 +49600,7 @@ async function setDefaultSecretsFromEnv(character, options) {
49373
49600
 
49374
49601
  // src/utils/crypto-compat.ts
49375
49602
  function hasNodeCrypto() {
49376
- try {
49377
- return typeof process !== "undefined" && (process.versions?.node !== undefined || process.versions?.bun !== undefined);
49378
- } catch {
49379
- return false;
49380
- }
49603
+ return typeof process !== "undefined" && (process.versions?.node !== undefined || process.versions?.bun !== undefined);
49381
49604
  }
49382
49605
  function getCryptoModule() {
49383
49606
  if (hasNodeCrypto()) {
@@ -49403,14 +49626,34 @@ function createCipheriv(algorithm, key, iv) {
49403
49626
  throw new Error(`Unsupported algorithm: ${algorithm}. Only 'aes-256-cbc' is currently supported.`);
49404
49627
  }
49405
49628
  const crypto2 = getCryptoModule();
49406
- return crypto2.createCipheriv(algorithm, key, iv);
49629
+ const cipher = crypto2.createCipheriv(algorithm, key, iv);
49630
+ return {
49631
+ update(data2, inputEncoding, outputEncoding) {
49632
+ const result = cipher.update(Buffer.from(data2, inputEncoding), undefined, outputEncoding);
49633
+ return typeof result === "string" ? result : result.toString(outputEncoding);
49634
+ },
49635
+ final(encoding) {
49636
+ const result = cipher.final(encoding);
49637
+ return typeof result === "string" ? result : result.toString(encoding);
49638
+ }
49639
+ };
49407
49640
  }
49408
49641
  function createDecipheriv(algorithm, key, iv) {
49409
49642
  if (algorithm !== "aes-256-cbc") {
49410
49643
  throw new Error(`Unsupported algorithm: ${algorithm}. Only 'aes-256-cbc' is currently supported.`);
49411
49644
  }
49412
49645
  const crypto2 = getCryptoModule();
49413
- return crypto2.createDecipheriv(algorithm, key, iv);
49646
+ const decipher = crypto2.createDecipheriv(algorithm, key, iv);
49647
+ return {
49648
+ update(data2, inputEncoding, outputEncoding) {
49649
+ const result = decipher.update(Buffer.from(data2, inputEncoding), undefined, outputEncoding);
49650
+ return typeof result === "string" ? result : result.toString(outputEncoding);
49651
+ },
49652
+ final(encoding) {
49653
+ const result = decipher.final(encoding);
49654
+ return typeof result === "string" ? result : result.toString(encoding);
49655
+ }
49656
+ };
49414
49657
  }
49415
49658
 
49416
49659
  // src/settings.ts
@@ -49472,7 +49715,7 @@ function encryptStringValue(value, salt) {
49472
49715
  if (possibleIv.length === 16) {
49473
49716
  return value;
49474
49717
  }
49475
- } catch (e) {}
49718
+ } catch {}
49476
49719
  }
49477
49720
  const key = createHash("sha256").update(salt).digest().slice(0, 32);
49478
49721
  const iv = BufferUtils.randomBytes(16);
@@ -49483,15 +49726,6 @@ function encryptStringValue(value, salt) {
49483
49726
  }
49484
49727
  function decryptStringValue(value, salt) {
49485
49728
  try {
49486
- if (value === undefined || value === null) {
49487
- return value;
49488
- }
49489
- if (typeof value === "boolean" || typeof value === "number") {
49490
- return value;
49491
- }
49492
- if (typeof value !== "string") {
49493
- return value;
49494
- }
49495
49729
  const parts = value.split(":");
49496
49730
  if (parts.length !== 2) {
49497
49731
  return value;
@@ -49658,7 +49892,8 @@ class ServiceBuilder {
49658
49892
  const description = this.description;
49659
49893
  const startFn = this.startFn;
49660
49894
  const stopFn = this.stopFn;
49661
- return class extends Service {
49895
+
49896
+ class ServiceClass extends Service {
49662
49897
  static serviceType = serviceType;
49663
49898
  capabilityDescription = description;
49664
49899
  static async start(runtime) {
@@ -49672,14 +49907,16 @@ class ServiceBuilder {
49672
49907
  await stopFn();
49673
49908
  }
49674
49909
  }
49675
- };
49910
+ }
49911
+ return ServiceClass;
49676
49912
  }
49677
49913
  }
49678
49914
  function createService(serviceType) {
49679
49915
  return new ServiceBuilder(serviceType);
49680
49916
  }
49681
49917
  function defineService(definition) {
49682
- return createService(definition.serviceType).withDescription(definition.description).withStart(definition.start).withStop(definition.stop || (() => Promise.resolve())).build();
49918
+ const builtService = createService(definition.serviceType).withDescription(definition.description).withStart(definition.start).withStop(definition.stop || (() => Promise.resolve())).build();
49919
+ return builtService;
49683
49920
  }
49684
49921
 
49685
49922
  // src/plugin.ts
@@ -49795,55 +50032,46 @@ function validatePlugin(plugin) {
49795
50032
  };
49796
50033
  }
49797
50034
  async function loadAndPreparePlugin(pluginName) {
50035
+ let pluginModule;
49798
50036
  try {
49799
- let pluginModule;
50037
+ pluginModule = await import(pluginName);
50038
+ } catch (error) {
50039
+ logger.warn({ src: "core:plugin", pluginName, error }, "Failed to load plugin");
50040
+ const attempted = await tryInstallPlugin(pluginName);
50041
+ if (!attempted) {
50042
+ return null;
50043
+ }
49800
50044
  try {
49801
50045
  pluginModule = await import(pluginName);
49802
- } catch (error) {
49803
- logger.warn({ src: "core:plugin", pluginName, error }, "Failed to load plugin");
49804
- const attempted = await tryInstallPlugin(pluginName);
49805
- if (!attempted) {
49806
- return null;
49807
- }
49808
- try {
49809
- pluginModule = await import(pluginName);
49810
- } catch (secondError) {
49811
- logger.error({ src: "core:plugin", pluginName, error: secondError }, "Import failed after auto-install");
49812
- return null;
49813
- }
49814
- }
49815
- if (!pluginModule) {
49816
- logger.error({ src: "core:plugin", pluginName }, "Failed to load plugin module");
50046
+ } catch (secondError) {
50047
+ logger.error({ src: "core:plugin", pluginName, error: secondError }, "Import failed after auto-install");
49817
50048
  return null;
49818
50049
  }
49819
- const expectedFunctionName = `${pluginName.replace(/^@elizaos\/plugin-/, "").replace(/^@elizaos\//, "").replace(/-./g, (match) => match[1].toUpperCase())}Plugin`;
49820
- const moduleObj = pluginModule;
49821
- const exportsToCheck = [
49822
- moduleObj[expectedFunctionName],
49823
- moduleObj.default,
49824
- ...Object.values(moduleObj)
49825
- ];
49826
- for (const potentialPlugin of exportsToCheck) {
49827
- if (isValidPluginShape(potentialPlugin)) {
49828
- return potentialPlugin;
49829
- }
49830
- if (typeof potentialPlugin === "function" && potentialPlugin.length === 0) {
49831
- try {
49832
- const produced = potentialPlugin();
49833
- if (isValidPluginShape(produced)) {
49834
- return produced;
49835
- }
49836
- } catch (err) {
49837
- logger.debug({ src: "core:plugin", pluginName, error: err }, "Factory export threw");
49838
- }
50050
+ }
50051
+ if (!pluginModule) {
50052
+ logger.error({ src: "core:plugin", pluginName }, "Failed to load plugin module");
50053
+ return null;
50054
+ }
50055
+ const expectedFunctionName = `${pluginName.replace(/^@elizaos\/plugin-/, "").replace(/^@elizaos\//, "").replace(/-./g, (match) => match[1].toUpperCase())}Plugin`;
50056
+ const moduleObj = pluginModule;
50057
+ const exportsToCheck = [
50058
+ moduleObj[expectedFunctionName],
50059
+ moduleObj.default,
50060
+ ...Object.values(moduleObj)
50061
+ ];
50062
+ for (const potentialPlugin of exportsToCheck) {
50063
+ if (isValidPluginShape(potentialPlugin)) {
50064
+ return potentialPlugin;
50065
+ }
50066
+ if (typeof potentialPlugin === "function" && potentialPlugin.length === 0) {
50067
+ const produced = potentialPlugin();
50068
+ if (isValidPluginShape(produced)) {
50069
+ return produced;
49839
50070
  }
49840
50071
  }
49841
- logger.warn({ src: "core:plugin", pluginName }, "No valid plugin export found");
49842
- return null;
49843
- } catch (error) {
49844
- logger.error({ src: "core:plugin", pluginName, error }, "Error loading plugin");
49845
- return null;
49846
50072
  }
50073
+ logger.warn({ src: "core:plugin", pluginName }, "No valid plugin export found");
50074
+ return null;
49847
50075
  }
49848
50076
  function normalizePluginName(pluginName) {
49849
50077
  const scopedMatch = pluginName.match(/^@[^/]+\/plugin-(.+)$/);
@@ -49985,8 +50213,15 @@ class ElizaOS extends EventTarget {
49985
50213
  async addAgents(agents, options) {
49986
50214
  const createdRuntimes = [];
49987
50215
  const promises = agents.map(async (agent) => {
49988
- const character = agent.character;
50216
+ const character = JSON.parse(JSON.stringify(agent.character));
49989
50217
  await setDefaultSecretsFromEnv(character, { skipEnvMerge: options?.isTestMode });
50218
+ const salt = getSalt();
50219
+ if (character.settings?.secrets && typeof character.settings.secrets === "object") {
50220
+ character.settings.secrets = encryptObjectValues(character.settings.secrets, salt);
50221
+ }
50222
+ if (character.secrets && typeof character.secrets === "object") {
50223
+ character.secrets = encryptObjectValues(character.secrets, salt);
50224
+ }
49990
50225
  let resolvedPlugins = agent.plugins ? await resolvePlugins(agent.plugins, options?.isTestMode || false) : [];
49991
50226
  if (agent.databaseAdapter) {
49992
50227
  resolvedPlugins = resolvedPlugins.filter((p) => p.name !== "@elizaos/plugin-sql");
@@ -50140,7 +50375,7 @@ class ElizaOS extends EventTarget {
50140
50375
  getAgentByCharacterId(characterId) {
50141
50376
  return this.getAgents().find((runtime) => runtime.character.id === characterId);
50142
50377
  }
50143
- async sendMessage(target, message, options) {
50378
+ async handleMessage(target, message, options) {
50144
50379
  let runtime;
50145
50380
  let agentId;
50146
50381
  if (typeof target === "string") {
@@ -50177,7 +50412,8 @@ class ElizaOS extends EventTarget {
50177
50412
  maxRetries: options?.maxRetries,
50178
50413
  timeoutDuration: options?.timeoutDuration,
50179
50414
  useMultiStep: options?.useMultiStep,
50180
- maxMultiStepIterations: options?.maxMultiStepIterations
50415
+ maxMultiStepIterations: options?.maxMultiStepIterations,
50416
+ onStreamChunk: options?.onStreamChunk
50181
50417
  };
50182
50418
  const handleMessageWithEntityContext = async (handler) => {
50183
50419
  if (runtime.withEntityContext) {
@@ -50221,10 +50457,10 @@ class ElizaOS extends EventTarget {
50221
50457
  return { messageId, userMessage, processing };
50222
50458
  }
50223
50459
  }
50224
- async sendMessages(messages) {
50460
+ async handleMessages(messages) {
50225
50461
  const results = await Promise.all(messages.map(async ({ agentId, message, options }) => {
50226
50462
  try {
50227
- const result = await this.sendMessage(agentId, message, options);
50463
+ const result = await this.handleMessage(agentId, message, options);
50228
50464
  return { agentId, result };
50229
50465
  } catch (error) {
50230
50466
  return {
@@ -50279,9 +50515,8 @@ class ElizaOS extends EventTarget {
50279
50515
  const agent = this.getAgent(agentId);
50280
50516
  if (!agent)
50281
50517
  return;
50282
- const agentRuntime = agent;
50283
- if (agentRuntime.stateCache && agentRuntime.stateCache.size > 0) {
50284
- const states = Array.from(agentRuntime.stateCache.values());
50518
+ if (agent.stateCache && agent.stateCache.size > 0) {
50519
+ const states = Array.from(agent.stateCache.values());
50285
50520
  return states[states.length - 1];
50286
50521
  }
50287
50522
  return;
@@ -50437,8 +50672,10 @@ async function findEntityByName(runtime, message, state) {
50437
50672
  }
50438
50673
  }
50439
50674
  let matchesArray = [];
50440
- if (resolution.matches?.match) {
50441
- matchesArray = Array.isArray(resolution.matches.match) ? resolution.matches.match : [resolution.matches.match];
50675
+ const parsedResolution = resolution;
50676
+ if (parsedResolution.matches?.match) {
50677
+ const matchValue = parsedResolution.matches.match;
50678
+ matchesArray = Array.isArray(matchValue) ? matchValue : [matchValue];
50442
50679
  }
50443
50680
  if (matchesArray.length > 0 && matchesArray[0]?.name) {
50444
50681
  const matchName = matchesArray[0].name.toLowerCase();
@@ -50495,9 +50732,19 @@ async function getEntityDetails({
50495
50732
  mergedData[key] = { ...mergedData[key], ...value };
50496
50733
  }
50497
50734
  }
50735
+ const getEntityNameFromMetadata = (source) => {
50736
+ const sourceMetadata = entity.metadata[source];
50737
+ if (sourceMetadata && typeof sourceMetadata === "object" && sourceMetadata !== null) {
50738
+ const metadataObj = sourceMetadata;
50739
+ if ("name" in metadataObj && typeof metadataObj.name === "string") {
50740
+ return metadataObj.name;
50741
+ }
50742
+ }
50743
+ return;
50744
+ };
50498
50745
  uniqueEntities.set(entity.id, {
50499
50746
  id: entity.id,
50500
- name: room?.source ? entity.metadata[room.source]?.name || entity.names[0] : entity.names[0],
50747
+ name: room?.source ? getEntityNameFromMetadata(room.source) || entity.names[0] : entity.names[0],
50501
50748
  names: entity.names,
50502
50749
  data: JSON.stringify({ ...mergedData, ...entity.metadata })
50503
50750
  });
@@ -50518,6 +50765,7 @@ Data: ${JSON.stringify(entity.metadata)}
50518
50765
  }
50519
50766
 
50520
50767
  // src/index.node.ts
50768
+ setStreamingContextManager(createNodeStreamingContextManager());
50521
50769
  var isBrowser4 = false;
50522
50770
  var isNode3 = true;
50523
50771
  export {
@@ -50542,15 +50790,18 @@ export {
50542
50790
  slice,
50543
50791
  shouldRespondTemplate,
50544
50792
  settingsSchema,
50793
+ setStreamingContextManager,
50545
50794
  setEnv,
50546
50795
  setDefaultSecretsFromEnv,
50547
50796
  secretsSchema,
50548
50797
  saltWorldSettings,
50549
50798
  saltSettingValue,
50550
50799
  safeReplacer,
50800
+ runWithStreamingContext,
50551
50801
  resolvePlugins,
50552
50802
  resolvePluginDependencies,
50553
50803
  resetPaths,
50804
+ removeLogListener,
50554
50805
  recentLogs,
50555
50806
  randomBytes,
50556
50807
  prewarmUuidCache,
@@ -50576,6 +50827,7 @@ export {
50576
50827
  knowledgeItemSchema,
50577
50828
  isValidPluginShape,
50578
50829
  isValidCharacter,
50830
+ isStreamableModelType,
50579
50831
  isNode3 as isNode,
50580
50832
  isMessageMetadata,
50581
50833
  isFragmentMetadata,
@@ -50596,6 +50848,8 @@ export {
50596
50848
  getUploadsChannelsDir,
50597
50849
  getUploadsAgentsDir,
50598
50850
  getTypedService,
50851
+ getStreamingContextManager,
50852
+ getStreamingContext,
50599
50853
  getSalt,
50600
50854
  getNumberEnv,
50601
50855
  getMemoryText,
@@ -50655,21 +50909,27 @@ export {
50655
50909
  booleanFooter,
50656
50910
  asUUID,
50657
50911
  alloc,
50912
+ addLogListener,
50658
50913
  addHeader,
50659
50914
  __loggerTestHooks,
50915
+ XmlTagExtractor,
50660
50916
  VECTOR_DIMS,
50661
50917
  TeeType,
50662
50918
  TEEMode,
50919
+ StreamError,
50663
50920
  ServiceType,
50664
50921
  ServiceBuilder,
50665
50922
  Service,
50666
50923
  Semaphore,
50667
50924
  SOCKET_MESSAGE_TYPE,
50668
50925
  Role,
50926
+ ResponseStreamExtractor,
50669
50927
  PlatformPrefix,
50928
+ PassthroughExtractor,
50670
50929
  ModelType,
50671
50930
  MemoryType,
50672
50931
  MODEL_SETTINGS,
50932
+ MESSAGE_STREAM_EVENT,
50673
50933
  EventType,
50674
50934
  Environment,
50675
50935
  ElizaOS,
@@ -50680,8 +50940,9 @@ export {
50680
50940
  BufferUtils,
50681
50941
  BM25,
50682
50942
  AgentStatus,
50683
- AgentRuntime
50943
+ AgentRuntime,
50944
+ ActionStreamFilter
50684
50945
  };
50685
50946
 
50686
- //# debugId=C468BC8B5AE0993F64756E2164756E21
50947
+ //# debugId=7435777E3B16550264756E2164756E21
50687
50948
  //# sourceMappingURL=index.node.js.map