@elizaos/core 1.6.2-alpha.9 → 1.6.2

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.
@@ -25,6 +25,7 @@ var __export = (target, all) => {
25
25
  set: (newValue) => all[name] = () => newValue
26
26
  });
27
27
  };
28
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
28
29
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
29
30
 
30
31
  // ../../node_modules/retry/lib/retry_operation.js
@@ -2291,6 +2292,9 @@ var require_parse_options = __commonJS((exports, module) => {
2291
2292
  var require_identifiers = __commonJS((exports, module) => {
2292
2293
  var numeric = /^[0-9]+$/;
2293
2294
  var compareIdentifiers = (a, b) => {
2295
+ if (typeof a === "number" && typeof b === "number") {
2296
+ return a === b ? 0 : a < b ? -1 : 1;
2297
+ }
2294
2298
  const anum = numeric.test(a);
2295
2299
  const bnum = numeric.test(b);
2296
2300
  if (anum && bnum) {
@@ -2393,7 +2397,25 @@ var require_semver = __commonJS((exports, module) => {
2393
2397
  if (!(other instanceof SemVer)) {
2394
2398
  other = new SemVer(other, this.options);
2395
2399
  }
2396
- return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
2400
+ if (this.major < other.major) {
2401
+ return -1;
2402
+ }
2403
+ if (this.major > other.major) {
2404
+ return 1;
2405
+ }
2406
+ if (this.minor < other.minor) {
2407
+ return -1;
2408
+ }
2409
+ if (this.minor > other.minor) {
2410
+ return 1;
2411
+ }
2412
+ if (this.patch < other.patch) {
2413
+ return -1;
2414
+ }
2415
+ if (this.patch > other.patch) {
2416
+ return 1;
2417
+ }
2418
+ return 0;
2397
2419
  }
2398
2420
  comparePre(other) {
2399
2421
  if (!(other instanceof SemVer)) {
@@ -3070,6 +3092,7 @@ var require_range = __commonJS((exports, module) => {
3070
3092
  return result;
3071
3093
  };
3072
3094
  var parseComparator = (comp, options) => {
3095
+ comp = comp.replace(re[t.BUILD], "");
3073
3096
  debug("comp", comp, options);
3074
3097
  comp = replaceCarets(comp, options);
3075
3098
  debug("caret", comp);
@@ -9811,6 +9834,217 @@ Length provided: ${this.length}. Number of dictionaries provided: ${this.diction
9811
9834
  };
9812
9835
  });
9813
9836
 
9837
+ // src/utils/environment.ts
9838
+ var exports_environment = {};
9839
+ __export(exports_environment, {
9840
+ setEnv: () => setEnv,
9841
+ loadEnvConfig: () => loadEnvConfig,
9842
+ initBrowserEnvironment: () => initBrowserEnvironment,
9843
+ hasEnv: () => hasEnv,
9844
+ getNumberEnv: () => getNumberEnv,
9845
+ getEnvironment: () => getEnvironment,
9846
+ getEnv: () => getEnv3,
9847
+ getBooleanEnv: () => getBooleanEnv,
9848
+ findEnvFile: () => findEnvFile,
9849
+ detectEnvironment: () => detectEnvironment,
9850
+ currentRuntime: () => currentRuntime,
9851
+ Environment: () => Environment
9852
+ });
9853
+ function detectEnvironment() {
9854
+ if (typeof process !== "undefined" && process.versions && process.versions.node) {
9855
+ return "node";
9856
+ }
9857
+ if (typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.window.document !== "undefined") {
9858
+ return "browser";
9859
+ }
9860
+ return "unknown";
9861
+ }
9862
+
9863
+ class BrowserEnvironmentStore {
9864
+ store = {};
9865
+ constructor() {
9866
+ if (typeof globalThis !== "undefined" && globalThis.window && globalThis.window.ENV) {
9867
+ this.store = { ...globalThis.window.ENV };
9868
+ }
9869
+ if (typeof globalThis !== "undefined" && globalThis.__ENV__) {
9870
+ this.store = { ...this.store, ...globalThis.__ENV__ };
9871
+ }
9872
+ }
9873
+ get(key) {
9874
+ const value = this.store[key];
9875
+ return value !== undefined ? String(value) : undefined;
9876
+ }
9877
+ set(key, value) {
9878
+ this.store[key] = value;
9879
+ }
9880
+ has(key) {
9881
+ return key in this.store;
9882
+ }
9883
+ getAll() {
9884
+ return { ...this.store };
9885
+ }
9886
+ }
9887
+
9888
+ class Environment {
9889
+ runtime;
9890
+ browserStore;
9891
+ cache = new Map;
9892
+ constructor() {
9893
+ this.runtime = detectEnvironment();
9894
+ if (this.runtime === "browser") {
9895
+ this.browserStore = new BrowserEnvironmentStore;
9896
+ }
9897
+ }
9898
+ getRuntime() {
9899
+ return this.runtime;
9900
+ }
9901
+ isNode() {
9902
+ return this.runtime === "node";
9903
+ }
9904
+ isBrowser() {
9905
+ return this.runtime === "browser";
9906
+ }
9907
+ get(key, defaultValue) {
9908
+ if (this.cache.has(key)) {
9909
+ const cached = this.cache.get(key);
9910
+ return cached === undefined && defaultValue !== undefined ? defaultValue : cached;
9911
+ }
9912
+ let value;
9913
+ switch (this.runtime) {
9914
+ case "node":
9915
+ if (typeof process !== "undefined" && process.env) {
9916
+ value = process.env[key];
9917
+ }
9918
+ break;
9919
+ case "browser":
9920
+ if (this.browserStore) {
9921
+ value = this.browserStore.get(key);
9922
+ }
9923
+ break;
9924
+ default:
9925
+ value = undefined;
9926
+ }
9927
+ this.cache.set(key, value);
9928
+ return value === undefined && defaultValue !== undefined ? defaultValue : value;
9929
+ }
9930
+ set(key, value) {
9931
+ const stringValue = String(value);
9932
+ this.cache.delete(key);
9933
+ switch (this.runtime) {
9934
+ case "node":
9935
+ if (typeof process !== "undefined" && process.env) {
9936
+ process.env[key] = stringValue;
9937
+ }
9938
+ break;
9939
+ case "browser":
9940
+ if (this.browserStore) {
9941
+ this.browserStore.set(key, value);
9942
+ }
9943
+ break;
9944
+ }
9945
+ }
9946
+ has(key) {
9947
+ const value = this.get(key);
9948
+ return value !== undefined;
9949
+ }
9950
+ getAll() {
9951
+ switch (this.runtime) {
9952
+ case "node":
9953
+ if (typeof process !== "undefined" && process.env) {
9954
+ return { ...process.env };
9955
+ }
9956
+ break;
9957
+ case "browser":
9958
+ if (this.browserStore) {
9959
+ return this.browserStore.getAll();
9960
+ }
9961
+ break;
9962
+ }
9963
+ return {};
9964
+ }
9965
+ getBoolean(key, defaultValue = false) {
9966
+ const value = this.get(key);
9967
+ if (value === undefined) {
9968
+ return defaultValue;
9969
+ }
9970
+ return ["true", "1", "yes", "on"].includes(value.toLowerCase());
9971
+ }
9972
+ getNumber(key, defaultValue) {
9973
+ const value = this.get(key);
9974
+ if (value === undefined) {
9975
+ return defaultValue;
9976
+ }
9977
+ const parsed = Number(value);
9978
+ return isNaN(parsed) ? defaultValue : parsed;
9979
+ }
9980
+ clearCache() {
9981
+ this.cache.clear();
9982
+ }
9983
+ }
9984
+ function getEnvironment() {
9985
+ if (!environmentInstance) {
9986
+ environmentInstance = new Environment;
9987
+ }
9988
+ return environmentInstance;
9989
+ }
9990
+ function getEnv3(key, defaultValue) {
9991
+ return getEnvironment().get(key, defaultValue);
9992
+ }
9993
+ function setEnv(key, value) {
9994
+ getEnvironment().set(key, value);
9995
+ }
9996
+ function hasEnv(key) {
9997
+ return getEnvironment().has(key);
9998
+ }
9999
+ function getBooleanEnv(key, defaultValue = false) {
10000
+ return getEnvironment().getBoolean(key, defaultValue);
10001
+ }
10002
+ function getNumberEnv(key, defaultValue) {
10003
+ return getEnvironment().getNumber(key, defaultValue);
10004
+ }
10005
+ function initBrowserEnvironment(config) {
10006
+ const env = getEnvironment();
10007
+ if (env.isBrowser()) {
10008
+ Object.entries(config).forEach(([key, value]) => {
10009
+ if (value !== undefined) {
10010
+ env.set(key, value);
10011
+ }
10012
+ });
10013
+ }
10014
+ }
10015
+ function findEnvFile() {
10016
+ if (typeof process === "undefined" || !process.cwd) {
10017
+ return null;
10018
+ }
10019
+ const fs = __require("node:fs");
10020
+ const path = __require("node:path");
10021
+ const possiblePaths = [path.join(process.cwd(), ".env"), path.join(process.cwd(), ".env.local")];
10022
+ for (const envPath of possiblePaths) {
10023
+ if (fs.existsSync(envPath)) {
10024
+ return envPath;
10025
+ }
10026
+ }
10027
+ return null;
10028
+ }
10029
+ async function loadEnvConfig(envPath) {
10030
+ if (typeof process === "undefined" || !process.cwd) {
10031
+ return {};
10032
+ }
10033
+ const dotenv = __require("dotenv");
10034
+ const resolvedPath = envPath || findEnvFile();
10035
+ if (resolvedPath) {
10036
+ const result = dotenv.config({ path: resolvedPath });
10037
+ if (result.error) {
10038
+ throw result.error;
10039
+ }
10040
+ }
10041
+ return process.env;
10042
+ }
10043
+ var environmentInstance = null, currentRuntime;
10044
+ var init_environment = __esm(() => {
10045
+ currentRuntime = detectEnvironment();
10046
+ });
10047
+
9814
10048
  // ../../node_modules/picocolors/picocolors.js
9815
10049
  var require_picocolors = __commonJS((exports, module) => {
9816
10050
  var p = process || {};
@@ -10499,24 +10733,6 @@ var require_get_proto = __commonJS((exports, module) => {
10499
10733
  } : null;
10500
10734
  });
10501
10735
 
10502
- // ../../node_modules/async-function/index.js
10503
- var require_async_function = __commonJS((exports, module) => {
10504
- var cached = async function() {}.constructor;
10505
- module.exports = () => cached;
10506
- });
10507
-
10508
- // ../../node_modules/generator-function/index.js
10509
- var require_generator_function = __commonJS((exports, module) => {
10510
- var cached = function* () {}.constructor;
10511
- module.exports = () => cached;
10512
- });
10513
-
10514
- // ../../node_modules/async-generator-function/index.js
10515
- var require_async_generator_function = __commonJS((exports, module) => {
10516
- var cached = async function* () {}.constructor;
10517
- module.exports = () => cached;
10518
- });
10519
-
10520
10736
  // ../../node_modules/hasown/index.js
10521
10737
  var require_hasown = __commonJS((exports, module) => {
10522
10738
  var call = Function.prototype.call;
@@ -10543,6 +10759,12 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10543
10759
  var pow = require_pow();
10544
10760
  var round = require_round();
10545
10761
  var sign = require_sign();
10762
+ var $Function = Function;
10763
+ var getEvalledConstructor = function(expressionSyntax) {
10764
+ try {
10765
+ return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
10766
+ } catch (e) {}
10767
+ };
10546
10768
  var $gOPD = require_gopd();
10547
10769
  var $defineProperty = require_es_define_property();
10548
10770
  var throwTypeError = function() {
@@ -10597,7 +10819,7 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10597
10819
  "%Float32Array%": typeof Float32Array === "undefined" ? undefined3 : Float32Array,
10598
10820
  "%Float64Array%": typeof Float64Array === "undefined" ? undefined3 : Float64Array,
10599
10821
  "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined3 : FinalizationRegistry,
10600
- "%Function%": Function,
10822
+ "%Function%": $Function,
10601
10823
  "%GeneratorFunction%": needsEval,
10602
10824
  "%Int8Array%": typeof Int8Array === "undefined" ? undefined3 : Int8Array,
10603
10825
  "%Int16Array%": typeof Int16Array === "undefined" ? undefined3 : Int16Array,
@@ -10660,17 +10882,14 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10660
10882
  }
10661
10883
  }
10662
10884
  var errorProto;
10663
- var getAsyncFunction = require_async_function();
10664
- var getGeneratorFunction = require_generator_function();
10665
- var getAsyncGeneratorFunction = require_async_generator_function();
10666
10885
  var doEval = function doEval(name) {
10667
10886
  var value;
10668
10887
  if (name === "%AsyncFunction%") {
10669
- value = getAsyncFunction() || undefined;
10888
+ value = getEvalledConstructor("async function () {}");
10670
10889
  } else if (name === "%GeneratorFunction%") {
10671
- value = getGeneratorFunction() || undefined;
10890
+ value = getEvalledConstructor("function* () {}");
10672
10891
  } else if (name === "%AsyncGeneratorFunction%") {
10673
- value = getAsyncGeneratorFunction() || undefined;
10892
+ value = getEvalledConstructor("async function* () {}");
10674
10893
  } else if (name === "%AsyncGenerator%") {
10675
10894
  var fn = doEval("%AsyncGeneratorFunction%");
10676
10895
  if (fn) {
@@ -24970,6 +25189,7 @@ var ServiceType = {
24970
25189
  WALLET: "wallet",
24971
25190
  LP_POOL: "lp_pool",
24972
25191
  TOKEN_DATA: "token_data",
25192
+ MESSAGE_SERVICE: "message_service",
24973
25193
  MESSAGE: "message",
24974
25194
  POST: "post",
24975
25195
  UNKNOWN: "unknown"
@@ -25770,7 +25990,7 @@ var getDefaultProjectName = () => {
25770
25990
  };
25771
25991
 
25772
25992
  // ../../node_modules/langsmith/dist/index.js
25773
- var __version__ = "0.3.71";
25993
+ var __version__ = "0.3.74";
25774
25994
 
25775
25995
  // ../../node_modules/langsmith/dist/utils/env.js
25776
25996
  var globalEnv;
@@ -25815,8 +26035,8 @@ function getRuntimeEnvironment() {
25815
26035
  }
25816
26036
  return runtimeEnvironment;
25817
26037
  }
25818
- function getLangChainEnvVarsMetadata() {
25819
- const allEnvVars = getEnvironmentVariables() || {};
26038
+ function getLangSmithEnvVarsMetadata() {
26039
+ const allEnvVars = getLangSmithEnvironmentVariables();
25820
26040
  const envVars = {};
25821
26041
  const excluded = [
25822
26042
  "LANGCHAIN_API_KEY",
@@ -25831,7 +26051,7 @@ function getLangChainEnvVarsMetadata() {
25831
26051
  "LANGSMITH_SESSION"
25832
26052
  ];
25833
26053
  for (const [key, value] of Object.entries(allEnvVars)) {
25834
- if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
26054
+ if (typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
25835
26055
  if (key === "LANGCHAIN_REVISION_ID") {
25836
26056
  envVars["revision_id"] = value;
25837
26057
  } else {
@@ -25841,18 +26061,22 @@ function getLangChainEnvVarsMetadata() {
25841
26061
  }
25842
26062
  return envVars;
25843
26063
  }
25844
- function getEnvironmentVariables() {
26064
+ function getLangSmithEnvironmentVariables() {
26065
+ const envVars = {};
25845
26066
  try {
25846
26067
  if (typeof process !== "undefined" && process.env) {
25847
- return Object.entries(process.env).reduce((acc, [key, value]) => {
25848
- acc[key] = String(value);
25849
- return acc;
25850
- }, {});
26068
+ for (const [key, value] of Object.entries(process.env)) {
26069
+ if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && value != null) {
26070
+ if ((key.toLowerCase().includes("key") || key.toLowerCase().includes("secret") || key.toLowerCase().includes("token")) && typeof value === "string") {
26071
+ envVars[key] = value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2);
26072
+ } else {
26073
+ envVars[key] = value;
26074
+ }
26075
+ }
26076
+ }
25851
26077
  }
25852
- return;
25853
- } catch (e) {
25854
- return;
25855
- }
26078
+ } catch (e) {}
26079
+ return envVars;
25856
26080
  }
25857
26081
  function getEnvironmentVariable(name) {
25858
26082
  try {
@@ -26727,9 +26951,9 @@ function replaceGetterValues(replacer) {
26727
26951
  }
26728
26952
 
26729
26953
  // ../../node_modules/langsmith/dist/client.js
26730
- function mergeRuntimeEnvIntoRun(run) {
26954
+ function mergeRuntimeEnvIntoRun(run, cachedEnvVars) {
26731
26955
  const runtimeEnv = getRuntimeEnvironment();
26732
- const envVars = getLangChainEnvVarsMetadata();
26956
+ const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();
26733
26957
  const extra = run.extra ?? {};
26734
26958
  const metadata = extra.metadata;
26735
26959
  run.extra = {
@@ -27035,6 +27259,12 @@ class Client {
27035
27259
  writable: true,
27036
27260
  value: undefined
27037
27261
  });
27262
+ Object.defineProperty(this, "cachedLSEnvVarsForMetadata", {
27263
+ enumerable: true,
27264
+ configurable: true,
27265
+ writable: true,
27266
+ value: undefined
27267
+ });
27038
27268
  Object.defineProperty(this, "multipartStreamingDisabled", {
27039
27269
  enumerable: true,
27040
27270
  configurable: true,
@@ -27089,6 +27319,7 @@ class Client {
27089
27319
  if (getOtelEnabled()) {
27090
27320
  this.langSmithToOTELTranslator = new LangSmithToOTELTranslator;
27091
27321
  }
27322
+ this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata();
27092
27323
  }
27093
27324
  static getDefaultClientConfig() {
27094
27325
  const apiKey = getLangSmithEnvironmentVariable("API_KEY");
@@ -27400,7 +27631,7 @@ class Client {
27400
27631
  async processRunOperation(item) {
27401
27632
  clearTimeout(this.autoBatchTimeout);
27402
27633
  this.autoBatchTimeout = undefined;
27403
- item.item = mergeRuntimeEnvIntoRun(item.item);
27634
+ item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata);
27404
27635
  const itemPromise = this.autoBatchQueue.push(item);
27405
27636
  if (this.manualFlushMode) {
27406
27637
  return itemPromise;
@@ -27515,7 +27746,7 @@ class Client {
27515
27746
  }).catch(console.error);
27516
27747
  return;
27517
27748
  }
27518
- const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate);
27749
+ const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata);
27519
27750
  if (options?.apiKey !== undefined) {
27520
27751
  headers["x-api-key"] = options.apiKey;
27521
27752
  }
@@ -28017,6 +28248,9 @@ Context: ${context}`);
28017
28248
  is_root: isRoot,
28018
28249
  order
28019
28250
  };
28251
+ if (body.select.includes("child_run_ids")) {
28252
+ warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");
28253
+ }
28020
28254
  let runsYielded = 0;
28021
28255
  for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
28022
28256
  if (limit) {
@@ -39079,171 +39313,8 @@ var import_handlebars = __toESM(require_lib(), 1);
39079
39313
  var import_unique_names_generator = __toESM(require_dist4(), 1);
39080
39314
  import { z as z2 } from "zod";
39081
39315
 
39082
- // src/utils/environment.ts
39083
- function detectEnvironment() {
39084
- if (typeof process !== "undefined" && process.versions && process.versions.node) {
39085
- return "node";
39086
- }
39087
- if (typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.window.document !== "undefined") {
39088
- return "browser";
39089
- }
39090
- return "unknown";
39091
- }
39092
-
39093
- class BrowserEnvironmentStore {
39094
- store = {};
39095
- constructor() {
39096
- if (typeof globalThis !== "undefined" && globalThis.window && globalThis.window.ENV) {
39097
- this.store = { ...globalThis.window.ENV };
39098
- }
39099
- if (typeof globalThis !== "undefined" && globalThis.__ENV__) {
39100
- this.store = { ...this.store, ...globalThis.__ENV__ };
39101
- }
39102
- }
39103
- get(key) {
39104
- const value = this.store[key];
39105
- return value !== undefined ? String(value) : undefined;
39106
- }
39107
- set(key, value) {
39108
- this.store[key] = value;
39109
- }
39110
- has(key) {
39111
- return key in this.store;
39112
- }
39113
- getAll() {
39114
- return { ...this.store };
39115
- }
39116
- }
39117
-
39118
- class Environment {
39119
- runtime;
39120
- browserStore;
39121
- cache = new Map;
39122
- constructor() {
39123
- this.runtime = detectEnvironment();
39124
- if (this.runtime === "browser") {
39125
- this.browserStore = new BrowserEnvironmentStore;
39126
- }
39127
- }
39128
- getRuntime() {
39129
- return this.runtime;
39130
- }
39131
- isNode() {
39132
- return this.runtime === "node";
39133
- }
39134
- isBrowser() {
39135
- return this.runtime === "browser";
39136
- }
39137
- get(key, defaultValue) {
39138
- if (this.cache.has(key)) {
39139
- const cached = this.cache.get(key);
39140
- return cached === undefined && defaultValue !== undefined ? defaultValue : cached;
39141
- }
39142
- let value;
39143
- switch (this.runtime) {
39144
- case "node":
39145
- if (typeof process !== "undefined" && process.env) {
39146
- value = process.env[key];
39147
- }
39148
- break;
39149
- case "browser":
39150
- if (this.browserStore) {
39151
- value = this.browserStore.get(key);
39152
- }
39153
- break;
39154
- default:
39155
- value = undefined;
39156
- }
39157
- this.cache.set(key, value);
39158
- return value === undefined && defaultValue !== undefined ? defaultValue : value;
39159
- }
39160
- set(key, value) {
39161
- const stringValue = String(value);
39162
- this.cache.delete(key);
39163
- switch (this.runtime) {
39164
- case "node":
39165
- if (typeof process !== "undefined" && process.env) {
39166
- process.env[key] = stringValue;
39167
- }
39168
- break;
39169
- case "browser":
39170
- if (this.browserStore) {
39171
- this.browserStore.set(key, value);
39172
- }
39173
- break;
39174
- }
39175
- }
39176
- has(key) {
39177
- const value = this.get(key);
39178
- return value !== undefined;
39179
- }
39180
- getAll() {
39181
- switch (this.runtime) {
39182
- case "node":
39183
- if (typeof process !== "undefined" && process.env) {
39184
- return { ...process.env };
39185
- }
39186
- break;
39187
- case "browser":
39188
- if (this.browserStore) {
39189
- return this.browserStore.getAll();
39190
- }
39191
- break;
39192
- }
39193
- return {};
39194
- }
39195
- getBoolean(key, defaultValue = false) {
39196
- const value = this.get(key);
39197
- if (value === undefined) {
39198
- return defaultValue;
39199
- }
39200
- return ["true", "1", "yes", "on"].includes(value.toLowerCase());
39201
- }
39202
- getNumber(key, defaultValue) {
39203
- const value = this.get(key);
39204
- if (value === undefined) {
39205
- return defaultValue;
39206
- }
39207
- const parsed = Number(value);
39208
- return isNaN(parsed) ? defaultValue : parsed;
39209
- }
39210
- clearCache() {
39211
- this.cache.clear();
39212
- }
39213
- }
39214
- var environmentInstance = null;
39215
- function getEnvironment() {
39216
- if (!environmentInstance) {
39217
- environmentInstance = new Environment;
39218
- }
39219
- return environmentInstance;
39220
- }
39221
- function getEnv3(key, defaultValue) {
39222
- return getEnvironment().get(key, defaultValue);
39223
- }
39224
- function setEnv(key, value) {
39225
- getEnvironment().set(key, value);
39226
- }
39227
- function hasEnv(key) {
39228
- return getEnvironment().has(key);
39229
- }
39230
- function getBooleanEnv(key, defaultValue = false) {
39231
- return getEnvironment().getBoolean(key, defaultValue);
39232
- }
39233
- function getNumberEnv(key, defaultValue) {
39234
- return getEnvironment().getNumber(key, defaultValue);
39235
- }
39236
- function initBrowserEnvironment(config) {
39237
- const env = getEnvironment();
39238
- if (env.isBrowser()) {
39239
- Object.entries(config).forEach(([key, value]) => {
39240
- if (value !== undefined) {
39241
- env.set(key, value);
39242
- }
39243
- });
39244
- }
39245
- }
39246
- var currentRuntime = detectEnvironment();
39316
+ // src/logger.ts
39317
+ init_environment();
39247
39318
  // ../../node_modules/adze/dist/tools.js
39248
39319
  class Tools {
39249
39320
  globalStore;
@@ -41379,6 +41450,7 @@ var recentLogs = () => globalInMemoryDestination.recentLogs();
41379
41450
  var logger_default = logger;
41380
41451
 
41381
41452
  // src/utils.ts
41453
+ init_environment();
41382
41454
  function upgradeDoubleToTriple(tpl) {
41383
41455
  return tpl.replace(/(?<!{){{(?![{#\/!>])([\s\S]*?)}}/g, (_match, inner) => {
41384
41456
  if (inner.trim() === "else")
@@ -42090,6 +42162,10 @@ function parseAndValidateCharacter(jsonString) {
42090
42162
  function isValidCharacter(data2) {
42091
42163
  return validateCharacter(data2).success;
42092
42164
  }
42165
+
42166
+ // src/index.node.ts
42167
+ init_environment();
42168
+
42093
42169
  // src/utils/buffer.ts
42094
42170
  function hasNativeBuffer() {
42095
42171
  return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
@@ -42490,6 +42566,67 @@ function formatActions(actions) {
42490
42566
  class DatabaseAdapter {
42491
42567
  db;
42492
42568
  }
42569
+ // src/character.ts
42570
+ function parseCharacter(input) {
42571
+ if (typeof input === "string") {
42572
+ throw new Error(`Character path provided but must be loaded first: ${input}`);
42573
+ }
42574
+ if (typeof input === "object") {
42575
+ const validationResult = validateCharacter(input);
42576
+ if (!validationResult.success) {
42577
+ const errorDetails = validationResult.error?.issues ? validationResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ") : validationResult.error?.message || "Unknown validation error";
42578
+ throw new Error(`Character validation failed: ${errorDetails}`);
42579
+ }
42580
+ return validationResult.data;
42581
+ }
42582
+ throw new Error("Invalid character input format");
42583
+ }
42584
+ function validateCharacterConfig(character) {
42585
+ const validationResult = validateCharacter(character);
42586
+ if (validationResult.success) {
42587
+ return {
42588
+ isValid: true,
42589
+ errors: []
42590
+ };
42591
+ }
42592
+ const errors = validationResult.error?.issues ? validationResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`) : [validationResult.error?.message || "Unknown validation error"];
42593
+ return {
42594
+ isValid: false,
42595
+ errors
42596
+ };
42597
+ }
42598
+ function mergeCharacterDefaults(char) {
42599
+ const defaults = {
42600
+ settings: {},
42601
+ plugins: [],
42602
+ bio: []
42603
+ };
42604
+ return {
42605
+ ...defaults,
42606
+ ...char,
42607
+ name: char.name || "Unnamed Character"
42608
+ };
42609
+ }
42610
+ function buildCharacterPlugins(env2 = process.env) {
42611
+ const plugins = [
42612
+ "@elizaos/plugin-sql",
42613
+ ...env2.ANTHROPIC_API_KEY?.trim() ? ["@elizaos/plugin-anthropic"] : [],
42614
+ ...env2.OPENROUTER_API_KEY?.trim() ? ["@elizaos/plugin-openrouter"] : [],
42615
+ ...env2.OPENAI_API_KEY?.trim() ? ["@elizaos/plugin-openai"] : [],
42616
+ ...env2.GOOGLE_GENERATIVE_AI_API_KEY?.trim() ? ["@elizaos/plugin-google-genai"] : [],
42617
+ ...env2.DISCORD_API_TOKEN?.trim() ? ["@elizaos/plugin-discord"] : [],
42618
+ ...env2.TWITTER_API_KEY?.trim() && env2.TWITTER_API_SECRET_KEY?.trim() && env2.TWITTER_ACCESS_TOKEN?.trim() && env2.TWITTER_ACCESS_TOKEN_SECRET?.trim() ? ["@elizaos/plugin-twitter"] : [],
42619
+ ...env2.TELEGRAM_BOT_TOKEN?.trim() ? ["@elizaos/plugin-telegram"] : [],
42620
+ ...(() => {
42621
+ const ignore = env2.IGNORE_BOOTSTRAP?.trim().toLowerCase();
42622
+ const shouldIgnore = ignore === "true" || ignore === "1" || ignore === "yes";
42623
+ return shouldIgnore ? [] : ["@elizaos/plugin-bootstrap"];
42624
+ })(),
42625
+ ...!env2.ANTHROPIC_API_KEY?.trim() && !env2.OPENROUTER_API_KEY?.trim() && !env2.OPENAI_API_KEY?.trim() && !env2.GOOGLE_GENERATIVE_AI_API_KEY?.trim() ? ["@elizaos/plugin-ollama"] : []
42626
+ ];
42627
+ return plugins;
42628
+ }
42629
+
42493
42630
  // src/memory.ts
42494
42631
  function createMessageMemory(params) {
42495
42632
  return {
@@ -42862,6 +42999,754 @@ function v43(options, buf, offset) {
42862
42999
  return _v4(options, buf, offset);
42863
43000
  }
42864
43001
  var v4_default = v43;
43002
+ // src/runtime.ts
43003
+ init_environment();
43004
+
43005
+ // src/services/default-message-service.ts
43006
+ var latestResponseIds = new Map;
43007
+
43008
+ class DefaultMessageService {
43009
+ async handleMessage(runtime, message, callback, options) {
43010
+ const opts = {
43011
+ maxRetries: options?.maxRetries ?? 3,
43012
+ timeoutDuration: options?.timeoutDuration ?? 60 * 60 * 1000,
43013
+ useMultiStep: options?.useMultiStep ?? parseBooleanFromText2(runtime.getSetting("USE_MULTI_STEP")),
43014
+ maxMultiStepIterations: options?.maxMultiStepIterations ?? parseInt(runtime.getSetting("MAX_MULTISTEP_ITERATIONS") || "6")
43015
+ };
43016
+ let timeoutId = undefined;
43017
+ const responseId = v4_default();
43018
+ try {
43019
+ runtime.logger.info(`[MessageService] Message received from ${message.entityId} in room ${message.roomId}`);
43020
+ if (!latestResponseIds.has(runtime.agentId)) {
43021
+ latestResponseIds.set(runtime.agentId, new Map);
43022
+ }
43023
+ const agentResponses = latestResponseIds.get(runtime.agentId);
43024
+ if (!agentResponses)
43025
+ throw new Error("Agent responses map not found");
43026
+ const previousResponseId = agentResponses.get(message.roomId);
43027
+ if (previousResponseId) {
43028
+ logger.warn(`[MessageService] Updating response ID for room ${message.roomId} from ${previousResponseId} to ${responseId}`);
43029
+ }
43030
+ agentResponses.set(message.roomId, responseId);
43031
+ const runId = runtime.startRun();
43032
+ const startTime = Date.now();
43033
+ await runtime.emitEvent("RUN_STARTED" /* RUN_STARTED */, {
43034
+ runtime,
43035
+ runId,
43036
+ messageId: message.id,
43037
+ roomId: message.roomId,
43038
+ entityId: message.entityId,
43039
+ startTime,
43040
+ status: "started",
43041
+ source: "messageHandler",
43042
+ metadata: message.content
43043
+ });
43044
+ const timeoutPromise = new Promise((_, reject) => {
43045
+ timeoutId = setTimeout(async () => {
43046
+ await runtime.emitEvent("RUN_TIMEOUT" /* RUN_TIMEOUT */, {
43047
+ runtime,
43048
+ runId,
43049
+ messageId: message.id,
43050
+ roomId: message.roomId,
43051
+ entityId: message.entityId,
43052
+ startTime,
43053
+ status: "timeout",
43054
+ endTime: Date.now(),
43055
+ duration: Date.now() - startTime,
43056
+ error: "Run exceeded timeout",
43057
+ source: "messageHandler"
43058
+ });
43059
+ reject(new Error("Run exceeded timeout"));
43060
+ }, opts.timeoutDuration);
43061
+ });
43062
+ const processingPromise = this.processMessage(runtime, message, callback, responseId, runId, startTime, opts);
43063
+ const result = await Promise.race([processingPromise, timeoutPromise]);
43064
+ clearTimeout(timeoutId);
43065
+ return result;
43066
+ } catch (error) {
43067
+ clearTimeout(timeoutId);
43068
+ runtime.logger.error({ error }, "[MessageService] Error in handleMessage:");
43069
+ throw error;
43070
+ }
43071
+ }
43072
+ async processMessage(runtime, message, callback, responseId, runId, startTime, opts) {
43073
+ try {
43074
+ const agentResponses = latestResponseIds.get(runtime.agentId);
43075
+ if (!agentResponses)
43076
+ throw new Error("Agent responses map not found");
43077
+ if (message.entityId === runtime.agentId) {
43078
+ runtime.logger.debug(`[MessageService] Skipping message from self (${runtime.agentId})`);
43079
+ await this.emitRunEnded(runtime, runId, message, startTime, "self");
43080
+ return {
43081
+ didRespond: false,
43082
+ responseContent: null,
43083
+ responseMessages: [],
43084
+ state: {},
43085
+ mode: "none"
43086
+ };
43087
+ }
43088
+ runtime.logger.debug(`[MessageService] Processing message: ${truncateToCompleteSentence(message.content.text || "", 50)}...`);
43089
+ runtime.logger.debug("[MessageService] Saving message to memory and queueing embeddings");
43090
+ let memoryToQueue;
43091
+ if (message.id) {
43092
+ const existingMemory = await runtime.getMemoryById(message.id);
43093
+ if (existingMemory) {
43094
+ runtime.logger.debug("[MessageService] Memory already exists, skipping creation");
43095
+ memoryToQueue = existingMemory;
43096
+ } else {
43097
+ const createdMemoryId = await runtime.createMemory(message, "messages");
43098
+ memoryToQueue = { ...message, id: createdMemoryId };
43099
+ }
43100
+ await runtime.queueEmbeddingGeneration(memoryToQueue, "high");
43101
+ } else {
43102
+ const memoryId = await runtime.createMemory(message, "messages");
43103
+ message.id = memoryId;
43104
+ memoryToQueue = { ...message, id: memoryId };
43105
+ await runtime.queueEmbeddingGeneration(memoryToQueue, "normal");
43106
+ }
43107
+ const agentUserState = await runtime.getParticipantUserState(message.roomId, runtime.agentId);
43108
+ const defLllmOff = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_DEFLLMOFF"));
43109
+ if (defLllmOff && agentUserState === null) {
43110
+ runtime.logger.debug("[MessageService] LLM is off by default");
43111
+ await this.emitRunEnded(runtime, runId, message, startTime, "off");
43112
+ return {
43113
+ didRespond: false,
43114
+ responseContent: null,
43115
+ responseMessages: [],
43116
+ state: {},
43117
+ mode: "none"
43118
+ };
43119
+ }
43120
+ if (agentUserState === "MUTED" && !message.content.text?.toLowerCase().includes(runtime.character.name.toLowerCase())) {
43121
+ runtime.logger.debug(`[MessageService] Ignoring muted room ${message.roomId}`);
43122
+ await this.emitRunEnded(runtime, runId, message, startTime, "muted");
43123
+ return {
43124
+ didRespond: false,
43125
+ responseContent: null,
43126
+ responseMessages: [],
43127
+ state: {},
43128
+ mode: "none"
43129
+ };
43130
+ }
43131
+ let state = await runtime.composeState(message, ["ANXIETY", "ENTITIES", "CHARACTER", "RECENT_MESSAGES", "ACTIONS"], true);
43132
+ const mentionContext = message.content.mentionContext;
43133
+ const room = await runtime.getRoom(message.roomId);
43134
+ if (message.content.attachments && message.content.attachments.length > 0) {
43135
+ message.content.attachments = await this.processAttachments(runtime, message.content.attachments);
43136
+ if (message.id) {
43137
+ await runtime.updateMemory({ id: message.id, content: message.content });
43138
+ }
43139
+ }
43140
+ const responseDecision = this.shouldRespond(runtime, message, room ?? undefined, mentionContext);
43141
+ runtime.logger.debug(`[MessageService] Response decision: ${JSON.stringify(responseDecision)}`);
43142
+ let shouldRespondToMessage = true;
43143
+ if (responseDecision.skipEvaluation) {
43144
+ runtime.logger.debug(`[MessageService] Skipping evaluation for ${runtime.character.name} (${responseDecision.reason})`);
43145
+ shouldRespondToMessage = responseDecision.shouldRespond;
43146
+ } else {
43147
+ const shouldRespondPrompt = composePromptFromState({
43148
+ state,
43149
+ template: runtime.character.templates?.shouldRespondTemplate || shouldRespondTemplate
43150
+ });
43151
+ runtime.logger.debug(`[MessageService] Using LLM evaluation for ${runtime.character.name} (${responseDecision.reason})`);
43152
+ const response = await runtime.useModel(ModelType.TEXT_SMALL, {
43153
+ prompt: shouldRespondPrompt
43154
+ });
43155
+ runtime.logger.debug(`[MessageService] LLM evaluation result:
43156
+ ${response}`);
43157
+ const responseObject = parseKeyValueXml(response);
43158
+ runtime.logger.debug({ responseObject }, "[MessageService] Parsed evaluation result:");
43159
+ const nonResponseActions = ["IGNORE", "NONE"];
43160
+ shouldRespondToMessage = responseObject?.action && !nonResponseActions.includes(responseObject.action.toUpperCase());
43161
+ }
43162
+ let responseContent = null;
43163
+ let responseMessages = [];
43164
+ let mode = "none";
43165
+ if (shouldRespondToMessage) {
43166
+ const result = opts.useMultiStep ? await this.runMultiStepCore(runtime, message, state, callback, opts) : await this.runSingleShotCore(runtime, message, state, opts);
43167
+ responseContent = result.responseContent;
43168
+ responseMessages = result.responseMessages;
43169
+ state = result.state;
43170
+ mode = result.mode;
43171
+ const currentResponseId = agentResponses.get(message.roomId);
43172
+ if (currentResponseId !== responseId) {
43173
+ runtime.logger.info(`Response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`);
43174
+ return {
43175
+ didRespond: false,
43176
+ responseContent: null,
43177
+ responseMessages: [],
43178
+ state,
43179
+ mode: "none"
43180
+ };
43181
+ }
43182
+ if (responseContent && message.id) {
43183
+ responseContent.inReplyTo = createUniqueUuid(runtime, message.id);
43184
+ }
43185
+ if (responseContent?.providers?.length && responseContent.providers.length > 0) {
43186
+ state = await runtime.composeState(message, responseContent.providers || []);
43187
+ }
43188
+ if (responseContent) {
43189
+ if (mode === "simple") {
43190
+ if (responseContent.providers && responseContent.providers.length > 0) {
43191
+ runtime.logger.debug({ providers: responseContent.providers }, "[MessageService] Simple response used providers");
43192
+ }
43193
+ if (callback) {
43194
+ await callback(responseContent);
43195
+ }
43196
+ } else if (mode === "actions") {
43197
+ await runtime.processActions(message, responseMessages, state, async (content) => {
43198
+ runtime.logger.debug({ content }, "action callback");
43199
+ responseContent.actionCallbacks = content;
43200
+ if (callback) {
43201
+ return callback(content);
43202
+ }
43203
+ return [];
43204
+ });
43205
+ }
43206
+ }
43207
+ } else {
43208
+ runtime.logger.debug("[MessageService] Agent decided not to respond (shouldRespond is false).");
43209
+ const currentResponseId = agentResponses.get(message.roomId);
43210
+ const keepResp = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_KEEP_RESP"));
43211
+ if (currentResponseId !== responseId && !keepResp) {
43212
+ runtime.logger.info(`Ignore response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`);
43213
+ await this.emitRunEnded(runtime, runId, message, startTime, "replaced");
43214
+ return {
43215
+ didRespond: false,
43216
+ responseContent: null,
43217
+ responseMessages: [],
43218
+ state,
43219
+ mode: "none"
43220
+ };
43221
+ }
43222
+ if (!message.id) {
43223
+ runtime.logger.error("[MessageService] Message ID is missing, cannot create ignore response.");
43224
+ await this.emitRunEnded(runtime, runId, message, startTime, "noMessageId");
43225
+ return {
43226
+ didRespond: false,
43227
+ responseContent: null,
43228
+ responseMessages: [],
43229
+ state,
43230
+ mode: "none"
43231
+ };
43232
+ }
43233
+ const ignoreContent = {
43234
+ thought: "Agent decided not to respond to this message.",
43235
+ actions: ["IGNORE"],
43236
+ simple: true,
43237
+ inReplyTo: createUniqueUuid(runtime, message.id)
43238
+ };
43239
+ if (callback) {
43240
+ await callback(ignoreContent);
43241
+ }
43242
+ const ignoreMemory = {
43243
+ id: asUUID(v4_default()),
43244
+ entityId: runtime.agentId,
43245
+ agentId: runtime.agentId,
43246
+ content: ignoreContent,
43247
+ roomId: message.roomId,
43248
+ createdAt: Date.now()
43249
+ };
43250
+ await runtime.createMemory(ignoreMemory, "messages");
43251
+ runtime.logger.debug("[MessageService] Saved ignore response to memory", `memoryId: ${ignoreMemory.id}`);
43252
+ }
43253
+ agentResponses.delete(message.roomId);
43254
+ if (agentResponses.size === 0) {
43255
+ latestResponseIds.delete(runtime.agentId);
43256
+ }
43257
+ await runtime.evaluate(message, state, shouldRespondToMessage, async (content) => {
43258
+ runtime.logger.debug({ content }, "evaluate callback");
43259
+ if (responseContent) {
43260
+ responseContent.evalCallbacks = content;
43261
+ }
43262
+ if (callback) {
43263
+ return callback(content);
43264
+ }
43265
+ return [];
43266
+ }, responseMessages);
43267
+ let entityName = "noname";
43268
+ if (message.metadata && "entityName" in message.metadata) {
43269
+ entityName = message.metadata.entityName;
43270
+ }
43271
+ const isDM = message.content?.channelType === "DM" /* DM */;
43272
+ let roomName = entityName;
43273
+ if (!isDM) {
43274
+ const roomDatas = await runtime.getRoomsByIds([message.roomId]);
43275
+ if (roomDatas?.length) {
43276
+ const roomData = roomDatas[0];
43277
+ if (roomData.name) {
43278
+ roomName = roomData.name;
43279
+ }
43280
+ if (roomData.worldId) {
43281
+ const worldData = await runtime.getWorld(roomData.worldId);
43282
+ if (worldData) {
43283
+ roomName = worldData.name + "-" + roomName;
43284
+ }
43285
+ }
43286
+ }
43287
+ }
43288
+ const date2 = new Date;
43289
+ const availableActions = state.data?.providers?.ACTIONS?.data?.actionsData?.map((a) => a.name) || [-1];
43290
+ const logData = {
43291
+ at: date2.toString(),
43292
+ timestamp: parseInt("" + date2.getTime() / 1000),
43293
+ messageId: message.id,
43294
+ userEntityId: message.entityId,
43295
+ input: message.content.text,
43296
+ thought: responseContent?.thought,
43297
+ simple: responseContent?.simple,
43298
+ availableActions,
43299
+ actions: responseContent?.actions,
43300
+ providers: responseContent?.providers,
43301
+ irt: responseContent?.inReplyTo,
43302
+ output: responseContent?.text,
43303
+ entityName,
43304
+ source: message.content.source,
43305
+ channelType: message.content.channelType,
43306
+ roomName
43307
+ };
43308
+ await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
43309
+ runtime,
43310
+ runId,
43311
+ messageId: message.id,
43312
+ roomId: message.roomId,
43313
+ entityId: message.entityId,
43314
+ startTime,
43315
+ status: "completed",
43316
+ endTime: Date.now(),
43317
+ duration: Date.now() - startTime,
43318
+ source: "messageHandler",
43319
+ entityName,
43320
+ responseContent,
43321
+ metadata: logData
43322
+ });
43323
+ return {
43324
+ didRespond: shouldRespondToMessage,
43325
+ responseContent,
43326
+ responseMessages,
43327
+ state,
43328
+ mode
43329
+ };
43330
+ } catch (error) {
43331
+ console.error("error is", error);
43332
+ await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
43333
+ runtime,
43334
+ runId,
43335
+ messageId: message.id,
43336
+ roomId: message.roomId,
43337
+ entityId: message.entityId,
43338
+ startTime,
43339
+ status: "error",
43340
+ endTime: Date.now(),
43341
+ duration: Date.now() - startTime,
43342
+ error: error.message,
43343
+ source: "messageHandler"
43344
+ });
43345
+ throw error;
43346
+ }
43347
+ }
43348
+ shouldRespond(runtime, message, room, mentionContext) {
43349
+ if (!room) {
43350
+ return { shouldRespond: false, skipEvaluation: true, reason: "no room context" };
43351
+ }
43352
+ function normalizeEnvList(value) {
43353
+ if (!value || typeof value !== "string")
43354
+ return [];
43355
+ const cleaned = value.trim().replace(/^\[|\]$/g, "");
43356
+ return cleaned.split(",").map((v) => v.trim()).filter(Boolean);
43357
+ }
43358
+ const alwaysRespondChannels = [
43359
+ "DM" /* DM */,
43360
+ "VOICE_DM" /* VOICE_DM */,
43361
+ "SELF" /* SELF */,
43362
+ "API" /* API */
43363
+ ];
43364
+ const alwaysRespondSources = ["client_chat"];
43365
+ const customChannels = normalizeEnvList(runtime.getSetting("ALWAYS_RESPOND_CHANNELS") || runtime.getSetting("SHOULD_RESPOND_BYPASS_TYPES"));
43366
+ const customSources = normalizeEnvList(runtime.getSetting("ALWAYS_RESPOND_SOURCES") || runtime.getSetting("SHOULD_RESPOND_BYPASS_SOURCES"));
43367
+ const respondChannels = new Set([...alwaysRespondChannels.map((t) => t.toString()), ...customChannels].map((s) => s.trim().toLowerCase()));
43368
+ const respondSources = [...alwaysRespondSources, ...customSources].map((s) => s.trim().toLowerCase());
43369
+ const roomType = room.type?.toString().toLowerCase();
43370
+ const sourceStr = message.content.source?.toLowerCase() || "";
43371
+ if (respondChannels.has(roomType)) {
43372
+ return { shouldRespond: true, skipEvaluation: true, reason: `private channel: ${roomType}` };
43373
+ }
43374
+ if (respondSources.some((pattern) => sourceStr.includes(pattern))) {
43375
+ return {
43376
+ shouldRespond: true,
43377
+ skipEvaluation: true,
43378
+ reason: `whitelisted source: ${sourceStr}`
43379
+ };
43380
+ }
43381
+ const hasPlatformMention = !!(mentionContext?.isMention || mentionContext?.isReply);
43382
+ if (hasPlatformMention) {
43383
+ const mentionType = mentionContext?.isMention ? "mention" : "reply";
43384
+ return { shouldRespond: true, skipEvaluation: true, reason: `platform ${mentionType}` };
43385
+ }
43386
+ return { shouldRespond: false, skipEvaluation: false, reason: "needs LLM evaluation" };
43387
+ }
43388
+ async processAttachments(runtime, attachments) {
43389
+ if (!attachments || attachments.length === 0) {
43390
+ return [];
43391
+ }
43392
+ runtime.logger.debug(`[MessageService] Processing ${attachments.length} attachment(s)`);
43393
+ const processedAttachments = [];
43394
+ for (const attachment of attachments) {
43395
+ try {
43396
+ const processedAttachment = { ...attachment };
43397
+ const isRemote = /^(http|https):\/\//.test(attachment.url);
43398
+ const url = isRemote ? attachment.url : getLocalServerUrl(attachment.url);
43399
+ if (attachment.contentType === "image" /* IMAGE */ && !attachment.description) {
43400
+ runtime.logger.debug(`[MessageService] Generating description for image: ${attachment.url}`);
43401
+ let imageUrl = url;
43402
+ if (!isRemote) {
43403
+ const res = await fetch(url);
43404
+ if (!res.ok)
43405
+ throw new Error(`Failed to fetch image: ${res.statusText}`);
43406
+ const arrayBuffer = await res.arrayBuffer();
43407
+ const buffer = Buffer.from(arrayBuffer);
43408
+ const contentType = res.headers.get("content-type") || "application/octet-stream";
43409
+ imageUrl = `data:${contentType};base64,${buffer.toString("base64")}`;
43410
+ }
43411
+ try {
43412
+ const response = await runtime.useModel(ModelType.IMAGE_DESCRIPTION, {
43413
+ prompt: imageDescriptionTemplate,
43414
+ imageUrl
43415
+ });
43416
+ if (typeof response === "string") {
43417
+ const parsedXml = parseKeyValueXml(response);
43418
+ if (parsedXml && (parsedXml.description || parsedXml.text)) {
43419
+ processedAttachment.description = parsedXml.description || "";
43420
+ processedAttachment.title = parsedXml.title || "Image";
43421
+ processedAttachment.text = parsedXml.text || parsedXml.description || "";
43422
+ runtime.logger.debug(`[MessageService] Generated description: ${processedAttachment.description?.substring(0, 100)}...`);
43423
+ } else {
43424
+ const responseStr = response;
43425
+ const titleMatch = responseStr.match(/<title>([^<]+)<\/title>/);
43426
+ const descMatch = responseStr.match(/<description>([^<]+)<\/description>/);
43427
+ const textMatch = responseStr.match(/<text>([^<]+)<\/text>/);
43428
+ if (titleMatch || descMatch || textMatch) {
43429
+ processedAttachment.title = titleMatch?.[1] || "Image";
43430
+ processedAttachment.description = descMatch?.[1] || "";
43431
+ processedAttachment.text = textMatch?.[1] || descMatch?.[1] || "";
43432
+ runtime.logger.debug(`[MessageService] Used fallback XML parsing - description: ${processedAttachment.description?.substring(0, 100)}...`);
43433
+ } else {
43434
+ runtime.logger.warn(`[MessageService] Failed to parse XML response for image description`);
43435
+ }
43436
+ }
43437
+ } else if (response && typeof response === "object" && "description" in response) {
43438
+ processedAttachment.description = response.description;
43439
+ processedAttachment.title = response.title || "Image";
43440
+ processedAttachment.text = response.description;
43441
+ runtime.logger.debug(`[MessageService] Generated description: ${processedAttachment.description?.substring(0, 100)}...`);
43442
+ } else {
43443
+ runtime.logger.warn(`[MessageService] Unexpected response format for image description`);
43444
+ }
43445
+ } catch (error) {
43446
+ runtime.logger.error({ error }, `[MessageService] Error generating image description:`);
43447
+ }
43448
+ } else if (attachment.contentType === "document" /* DOCUMENT */ && !attachment.text) {
43449
+ const res = await fetch(url);
43450
+ if (!res.ok)
43451
+ throw new Error(`Failed to fetch document: ${res.statusText}`);
43452
+ const contentType = res.headers.get("content-type") || "";
43453
+ const isPlainText = contentType.startsWith("text/plain");
43454
+ if (isPlainText) {
43455
+ runtime.logger.debug(`[MessageService] Processing plain text document: ${attachment.url}`);
43456
+ const textContent = await res.text();
43457
+ processedAttachment.text = textContent;
43458
+ processedAttachment.title = processedAttachment.title || "Text File";
43459
+ runtime.logger.debug(`[MessageService] Extracted text content (first 100 chars): ${processedAttachment.text?.substring(0, 100)}...`);
43460
+ } else {
43461
+ runtime.logger.warn(`[MessageService] Skipping non-plain-text document: ${contentType}`);
43462
+ }
43463
+ }
43464
+ processedAttachments.push(processedAttachment);
43465
+ } catch (error) {
43466
+ runtime.logger.error({ error, attachmentUrl: attachment.url }, `[MessageService] Failed to process attachment ${attachment.url}:`);
43467
+ processedAttachments.push(attachment);
43468
+ }
43469
+ }
43470
+ return processedAttachments;
43471
+ }
43472
+ async runSingleShotCore(runtime, message, state, opts) {
43473
+ state = await runtime.composeState(message, ["ACTIONS"]);
43474
+ if (!state.values?.actionNames) {
43475
+ runtime.logger.warn("actionNames data missing from state, even though it was requested");
43476
+ }
43477
+ const prompt = composePromptFromState({
43478
+ state,
43479
+ template: runtime.character.templates?.messageHandlerTemplate || messageHandlerTemplate
43480
+ });
43481
+ let responseContent = null;
43482
+ let retries = 0;
43483
+ while (retries < opts.maxRetries && (!responseContent?.thought || !responseContent?.actions)) {
43484
+ const response = await runtime.useModel(ModelType.TEXT_LARGE, { prompt });
43485
+ runtime.logger.debug({ response }, "[MessageService] *** Raw LLM Response ***");
43486
+ const parsedXml = parseKeyValueXml(response);
43487
+ runtime.logger.debug({ parsedXml }, "[MessageService] *** Parsed XML Content ***");
43488
+ if (parsedXml) {
43489
+ responseContent = {
43490
+ ...parsedXml,
43491
+ thought: parsedXml.thought || "",
43492
+ actions: parsedXml.actions || ["IGNORE"],
43493
+ providers: parsedXml.providers || [],
43494
+ text: parsedXml.text || "",
43495
+ simple: parsedXml.simple || false
43496
+ };
43497
+ } else {
43498
+ responseContent = null;
43499
+ }
43500
+ retries++;
43501
+ if (!responseContent?.thought || !responseContent?.actions) {
43502
+ runtime.logger.warn({ response, parsedXml, responseContent }, "[MessageService] *** Missing required fields (thought or actions), retrying... ***");
43503
+ }
43504
+ }
43505
+ if (!responseContent) {
43506
+ return { responseContent: null, responseMessages: [], state, mode: "none" };
43507
+ }
43508
+ if (responseContent.actions && responseContent.actions.length > 1) {
43509
+ const isIgnore = (a) => typeof a === "string" && a.toUpperCase() === "IGNORE";
43510
+ const hasIgnore = responseContent.actions.some(isIgnore);
43511
+ if (hasIgnore) {
43512
+ if (!responseContent.text || responseContent.text.trim() === "") {
43513
+ responseContent.actions = ["IGNORE"];
43514
+ } else {
43515
+ const filtered = responseContent.actions.filter((a) => !isIgnore(a));
43516
+ responseContent.actions = filtered.length ? filtered : ["REPLY"];
43517
+ }
43518
+ }
43519
+ }
43520
+ const isSimple = responseContent.actions?.length === 1 && typeof responseContent.actions[0] === "string" && responseContent.actions[0].toUpperCase() === "REPLY" && (!responseContent.providers || responseContent.providers.length === 0);
43521
+ responseContent.simple = isSimple;
43522
+ const responseMessages = [
43523
+ {
43524
+ id: asUUID(v4_default()),
43525
+ entityId: runtime.agentId,
43526
+ agentId: runtime.agentId,
43527
+ content: responseContent,
43528
+ roomId: message.roomId,
43529
+ createdAt: Date.now()
43530
+ }
43531
+ ];
43532
+ return {
43533
+ responseContent,
43534
+ responseMessages,
43535
+ state,
43536
+ mode: isSimple && responseContent.text ? "simple" : "actions"
43537
+ };
43538
+ }
43539
+ async runMultiStepCore(runtime, message, state, callback, opts) {
43540
+ const traceActionResult = [];
43541
+ let accumulatedState = state;
43542
+ let iterationCount = 0;
43543
+ while (iterationCount < opts.maxMultiStepIterations) {
43544
+ iterationCount++;
43545
+ runtime.logger.debug(`[MultiStep] Starting iteration ${iterationCount}/${opts.maxMultiStepIterations}`);
43546
+ accumulatedState = await runtime.composeState(message, [
43547
+ "RECENT_MESSAGES",
43548
+ "ACTION_STATE"
43549
+ ]);
43550
+ accumulatedState.data.actionResults = traceActionResult;
43551
+ const prompt = composePromptFromState({
43552
+ state: accumulatedState,
43553
+ template: runtime.character.templates?.multiStepDecisionTemplate || multiStepDecisionTemplate
43554
+ });
43555
+ const stepResultRaw = await runtime.useModel(ModelType.TEXT_LARGE, { prompt });
43556
+ const parsedStep = parseKeyValueXml(stepResultRaw);
43557
+ if (!parsedStep) {
43558
+ runtime.logger.warn(`[MultiStep] Failed to parse step result at iteration ${iterationCount}`);
43559
+ traceActionResult.push({
43560
+ data: { actionName: "parse_error" },
43561
+ success: false,
43562
+ error: "Failed to parse step result"
43563
+ });
43564
+ break;
43565
+ }
43566
+ const { thought, providers = [], action, isFinish } = parsedStep;
43567
+ if (isFinish === "true" || isFinish === true) {
43568
+ runtime.logger.info(`[MultiStep] Task marked as complete at iteration ${iterationCount}`);
43569
+ if (callback) {
43570
+ await callback({
43571
+ text: "",
43572
+ thought: thought ?? ""
43573
+ });
43574
+ }
43575
+ break;
43576
+ }
43577
+ if ((!providers || providers.length === 0) && !action) {
43578
+ runtime.logger.warn(`[MultiStep] No providers or action specified at iteration ${iterationCount}, forcing completion`);
43579
+ break;
43580
+ }
43581
+ try {
43582
+ for (const providerName of providers) {
43583
+ const provider = runtime.providers.find((p) => p.name === providerName);
43584
+ if (!provider) {
43585
+ runtime.logger.warn(`[MultiStep] Provider not found: ${providerName}`);
43586
+ traceActionResult.push({
43587
+ data: { actionName: providerName },
43588
+ success: false,
43589
+ error: `Provider not found: ${providerName}`
43590
+ });
43591
+ continue;
43592
+ }
43593
+ const providerResult = await provider.get(runtime, message, state);
43594
+ if (!providerResult) {
43595
+ runtime.logger.warn(`[MultiStep] Provider returned no result: ${providerName}`);
43596
+ traceActionResult.push({
43597
+ data: { actionName: providerName },
43598
+ success: false,
43599
+ error: `Provider returned no result`
43600
+ });
43601
+ continue;
43602
+ }
43603
+ const success = !!providerResult.text;
43604
+ traceActionResult.push({
43605
+ data: { actionName: providerName },
43606
+ success,
43607
+ text: success ? providerResult.text : undefined,
43608
+ error: success ? undefined : "Provider returned no result"
43609
+ });
43610
+ if (callback) {
43611
+ await callback({
43612
+ text: `\uD83D\uDD0E Provider executed: ${providerName}`,
43613
+ actions: [providerName],
43614
+ thought: thought ?? ""
43615
+ });
43616
+ }
43617
+ }
43618
+ if (action) {
43619
+ const actionContent = {
43620
+ text: `\uD83D\uDD0E Executing action: ${action}`,
43621
+ actions: [action],
43622
+ thought: thought ?? ""
43623
+ };
43624
+ await runtime.processActions(message, [
43625
+ {
43626
+ id: v4_default(),
43627
+ entityId: runtime.agentId,
43628
+ roomId: message.roomId,
43629
+ createdAt: Date.now(),
43630
+ content: actionContent
43631
+ }
43632
+ ], state, async () => {
43633
+ return [];
43634
+ });
43635
+ const cachedState = runtime.stateCache?.get(`${message.id}_action_results`);
43636
+ const actionResults = cachedState?.values?.actionResults || [];
43637
+ const result = actionResults.length > 0 ? actionResults[0] : null;
43638
+ const success = result?.success ?? false;
43639
+ traceActionResult.push({
43640
+ data: { actionName: action },
43641
+ success,
43642
+ text: result?.text,
43643
+ values: result?.values,
43644
+ error: success ? undefined : result?.text
43645
+ });
43646
+ }
43647
+ } catch (err) {
43648
+ runtime.logger.error({ err }, "[MultiStep] Error executing step");
43649
+ traceActionResult.push({
43650
+ data: { actionName: action || "unknown" },
43651
+ success: false,
43652
+ error: err instanceof Error ? err.message : String(err)
43653
+ });
43654
+ }
43655
+ }
43656
+ if (iterationCount >= opts.maxMultiStepIterations) {
43657
+ runtime.logger.warn(`[MultiStep] Reached maximum iterations (${opts.maxMultiStepIterations}), forcing completion`);
43658
+ }
43659
+ accumulatedState = await runtime.composeState(message, [
43660
+ "RECENT_MESSAGES",
43661
+ "ACTION_STATE"
43662
+ ]);
43663
+ const summaryPrompt = composePromptFromState({
43664
+ state: accumulatedState,
43665
+ template: runtime.character.templates?.multiStepSummaryTemplate || multiStepSummaryTemplate
43666
+ });
43667
+ const finalOutput = await runtime.useModel(ModelType.TEXT_LARGE, { prompt: summaryPrompt });
43668
+ const summary = parseKeyValueXml(finalOutput);
43669
+ let responseContent = null;
43670
+ if (summary?.text) {
43671
+ responseContent = {
43672
+ actions: ["MULTI_STEP_SUMMARY"],
43673
+ text: summary.text,
43674
+ thought: summary.thought || "Final user-facing message after task completion.",
43675
+ simple: true
43676
+ };
43677
+ }
43678
+ const responseMessages = responseContent ? [
43679
+ {
43680
+ id: asUUID(v4_default()),
43681
+ entityId: runtime.agentId,
43682
+ agentId: runtime.agentId,
43683
+ content: responseContent,
43684
+ roomId: message.roomId,
43685
+ createdAt: Date.now()
43686
+ }
43687
+ ] : [];
43688
+ return {
43689
+ responseContent,
43690
+ responseMessages,
43691
+ state: accumulatedState,
43692
+ mode: responseContent ? "simple" : "none"
43693
+ };
43694
+ }
43695
+ async emitRunEnded(runtime, runId, message, startTime, status) {
43696
+ await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
43697
+ runtime,
43698
+ runId,
43699
+ messageId: message.id,
43700
+ roomId: message.roomId,
43701
+ entityId: message.entityId,
43702
+ startTime,
43703
+ status,
43704
+ endTime: Date.now(),
43705
+ duration: Date.now() - startTime,
43706
+ source: "messageHandler"
43707
+ });
43708
+ }
43709
+ async deleteMessage(runtime, message) {
43710
+ try {
43711
+ if (!message.id) {
43712
+ runtime.logger.error("[MessageService] Cannot delete memory: message ID is missing");
43713
+ return;
43714
+ }
43715
+ runtime.logger.info("[MessageService] Deleting memory for message", message.id, "from room", message.roomId);
43716
+ await runtime.deleteMemory(message.id);
43717
+ runtime.logger.debug({ messageId: message.id }, "[MessageService] Successfully deleted memory for message");
43718
+ } catch (error) {
43719
+ runtime.logger.error({ error }, "[MessageService] Error in deleteMessage:");
43720
+ throw error;
43721
+ }
43722
+ }
43723
+ async clearChannel(runtime, roomId, channelId) {
43724
+ try {
43725
+ runtime.logger.info(`[MessageService] Clearing message memories from channel ${channelId} -> room ${roomId}`);
43726
+ const memories = await runtime.getMemoriesByRoomIds({
43727
+ tableName: "messages",
43728
+ roomIds: [roomId]
43729
+ });
43730
+ runtime.logger.info(`[MessageService] Found ${memories.length} message memories to delete from channel ${channelId}`);
43731
+ let deletedCount = 0;
43732
+ for (const memory of memories) {
43733
+ if (memory.id) {
43734
+ try {
43735
+ await runtime.deleteMemory(memory.id);
43736
+ deletedCount++;
43737
+ } catch (error) {
43738
+ runtime.logger.warn({ error, memoryId: memory.id }, `[MessageService] Failed to delete message memory ${memory.id}:`);
43739
+ }
43740
+ }
43741
+ }
43742
+ runtime.logger.info(`[MessageService] Successfully cleared ${deletedCount}/${memories.length} message memories from channel ${channelId}`);
43743
+ } catch (error) {
43744
+ runtime.logger.error({ error }, "[MessageService] Error in clearChannel:");
43745
+ throw error;
43746
+ }
43747
+ }
43748
+ }
43749
+
42865
43750
  // src/search.ts
42866
43751
  var isV = (char) => {
42867
43752
  switch (char) {
@@ -43738,8 +44623,9 @@ class AgentRuntime {
43738
44623
  currentRunId;
43739
44624
  currentActionContext;
43740
44625
  maxWorkingMemoryEntries = 50;
44626
+ messageService = null;
43741
44627
  constructor(opts) {
43742
- this.agentId = opts.character?.id ?? opts?.agentId ?? stringToUuid(opts.character?.name ?? v4_default() + opts.character?.username);
44628
+ this.agentId = opts.character?.id ?? opts?.agentId ?? stringToUuid(opts.character?.name ?? v4_default());
43743
44629
  this.character = opts.character;
43744
44630
  this.initPromise = new Promise((resolve, reject) => {
43745
44631
  this.initResolver = resolve;
@@ -43902,12 +44788,16 @@ class AgentRuntime {
43902
44788
  if (!await this.adapter.isReady()) {
43903
44789
  await this.adapter.init();
43904
44790
  }
44791
+ this.messageService = new DefaultMessageService;
43905
44792
  this.logger.info("Running plugin migrations...");
43906
44793
  await this.runPluginMigrations();
43907
44794
  this.logger.info("Plugin migrations completed.");
43908
- const existingAgent = await this.ensureAgentExists(this.character);
44795
+ const existingAgent = await this.ensureAgentExists({
44796
+ ...this.character,
44797
+ id: this.agentId
44798
+ });
43909
44799
  if (!existingAgent) {
43910
- const errorMsg = `Agent ${this.character.name} does not exist in database after ensureAgentExists call`;
44800
+ const errorMsg = `Agent ${this.agentId} does not exist in database after ensureAgentExists call`;
43911
44801
  throw new Error(errorMsg);
43912
44802
  }
43913
44803
  let agentEntity = await this.getEntityById(this.agentId);
@@ -44455,42 +45345,56 @@ class AgentRuntime {
44455
45345
  }
44456
45346
  }
44457
45347
  async evaluate(message, state, didRespond, callback, responses) {
44458
- const evaluatorPromises = this.evaluators.map(async (evaluator) => {
44459
- if (!evaluator.handler) {
44460
- return null;
44461
- }
44462
- if (!didRespond && !evaluator.alwaysRun) {
44463
- return null;
44464
- }
44465
- const result = await evaluator.validate(this, message, state);
44466
- if (result) {
44467
- return evaluator;
45348
+ try {
45349
+ const evaluatorPromises = this.evaluators.map(async (evaluator) => {
45350
+ try {
45351
+ if (!evaluator.handler) {
45352
+ return null;
45353
+ }
45354
+ if (!didRespond && !evaluator.alwaysRun) {
45355
+ return null;
45356
+ }
45357
+ const result = await evaluator.validate(this, message, state);
45358
+ if (result) {
45359
+ return evaluator;
45360
+ }
45361
+ return null;
45362
+ } catch (error) {
45363
+ this.logger.error({ error, evaluatorName: evaluator.name }, `Error validating evaluator ${evaluator.name}`);
45364
+ return null;
45365
+ }
45366
+ });
45367
+ const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
45368
+ if (evaluators.length === 0) {
45369
+ return [];
44468
45370
  }
44469
- return null;
44470
- });
44471
- const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
44472
- if (evaluators.length === 0) {
45371
+ state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
45372
+ await Promise.all(evaluators.map(async (evaluator) => {
45373
+ try {
45374
+ if (evaluator.handler) {
45375
+ await evaluator.handler(this, message, state, {}, callback, responses);
45376
+ this.adapter.log({
45377
+ entityId: message.entityId,
45378
+ roomId: message.roomId,
45379
+ type: "evaluator",
45380
+ body: {
45381
+ evaluator: evaluator.name,
45382
+ messageId: message.id,
45383
+ message: message.content.text,
45384
+ state,
45385
+ runId: this.getCurrentRunId()
45386
+ }
45387
+ });
45388
+ }
45389
+ } catch (error) {
45390
+ this.logger.error({ error, evaluatorName: evaluator.name }, `Error executing evaluator ${evaluator.name}`);
45391
+ }
45392
+ }));
45393
+ return evaluators;
45394
+ } catch (error) {
45395
+ this.logger.error({ error, messageId: message.id, roomId: message.roomId }, "Error in evaluate method");
44473
45396
  return [];
44474
45397
  }
44475
- state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
44476
- await Promise.all(evaluators.map(async (evaluator) => {
44477
- if (evaluator.handler) {
44478
- await evaluator.handler(this, message, state, {}, callback, responses);
44479
- this.adapter.log({
44480
- entityId: message.entityId,
44481
- roomId: message.roomId,
44482
- type: "evaluator",
44483
- body: {
44484
- evaluator: evaluator.name,
44485
- messageId: message.id,
44486
- message: message.content.text,
44487
- state,
44488
- runId: this.getCurrentRunId()
44489
- }
44490
- });
44491
- }
44492
- }));
44493
- return evaluators;
44494
45398
  }
44495
45399
  async ensureConnections(entities, rooms, source, world) {
44496
45400
  if (!entities) {
@@ -45095,6 +45999,51 @@ class AgentRuntime {
45095
45999
  throw error;
45096
46000
  }
45097
46001
  }
46002
+ async generateText(input, options) {
46003
+ if (!input?.trim()) {
46004
+ throw new Error("Input cannot be empty");
46005
+ }
46006
+ const includeCharacter = options?.includeCharacter ?? true;
46007
+ const modelType = options?.modelType ?? ModelType.TEXT_LARGE;
46008
+ let prompt = input;
46009
+ if (includeCharacter && this.character) {
46010
+ const c = this.character;
46011
+ const parts = [];
46012
+ const bioText = Array.isArray(c.bio) ? c.bio.join(" ") : c.bio;
46013
+ if (bioText) {
46014
+ parts.push(`# About ${c.name}
46015
+ ${bioText}`);
46016
+ }
46017
+ if (c.system) {
46018
+ parts.push(c.system);
46019
+ }
46020
+ const styles2 = [...c.style?.all || [], ...c.style?.chat || []];
46021
+ if (styles2.length > 0) {
46022
+ parts.push(`Style:
46023
+ ${styles2.map((s) => `- ${s}`).join(`
46024
+ `)}`);
46025
+ }
46026
+ if (parts.length > 0) {
46027
+ prompt = `${parts.join(`
46028
+
46029
+ `)}
46030
+
46031
+ ${input}`;
46032
+ }
46033
+ }
46034
+ const params = {
46035
+ prompt,
46036
+ maxTokens: options?.maxTokens,
46037
+ temperature: options?.temperature,
46038
+ frequencyPenalty: options?.frequencyPenalty,
46039
+ presencePenalty: options?.presencePenalty,
46040
+ stopSequences: options?.stopSequences
46041
+ };
46042
+ const response = await this.useModel(modelType, params);
46043
+ return {
46044
+ text: response
46045
+ };
46046
+ }
45098
46047
  registerEvent(event, handler) {
45099
46048
  if (!this.events[event]) {
45100
46049
  this.events[event] = [];
@@ -45181,34 +46130,33 @@ class AgentRuntime {
45181
46130
  return await this.adapter.deleteAgent(agentId);
45182
46131
  }
45183
46132
  async ensureAgentExists(agent) {
45184
- if (!agent.name) {
45185
- throw new Error("Agent name is required");
46133
+ if (!agent.id) {
46134
+ throw new Error("Agent id is required");
45186
46135
  }
45187
- const agents = await this.adapter.getAgents();
45188
- const existingAgentId = agents.find((a) => a.name === agent.name)?.id;
45189
- if (existingAgentId) {
46136
+ const existingAgent = await this.adapter.getAgent(agent.id);
46137
+ if (existingAgent) {
45190
46138
  const updatedAgent = {
45191
46139
  ...agent,
45192
- id: existingAgentId,
46140
+ id: agent.id,
45193
46141
  updatedAt: Date.now()
45194
46142
  };
45195
- await this.adapter.updateAgent(existingAgentId, updatedAgent);
45196
- const existingAgent = await this.adapter.getAgent(existingAgentId);
45197
- if (!existingAgent) {
45198
- throw new Error(`Failed to retrieve agent after update: ${existingAgentId}`);
46143
+ await this.adapter.updateAgent(agent.id, updatedAgent);
46144
+ const refreshedAgent = await this.adapter.getAgent(agent.id);
46145
+ if (!refreshedAgent) {
46146
+ throw new Error(`Failed to retrieve agent after update: ${agent.id}`);
45199
46147
  }
45200
- this.logger.debug(`Updated existing agent ${agent.name} on restart`);
45201
- return existingAgent;
46148
+ this.logger.debug(`Updated existing agent ${agent.id} on restart`);
46149
+ return refreshedAgent;
45202
46150
  }
45203
46151
  const newAgent = {
45204
46152
  ...agent,
45205
- id: stringToUuid(agent.name)
46153
+ id: agent.id
45206
46154
  };
45207
46155
  const created = await this.adapter.createAgent(newAgent);
45208
46156
  if (!created) {
45209
- throw new Error(`Failed to create agent: ${agent.name}`);
46157
+ throw new Error(`Failed to create agent: ${agent.id}`);
45210
46158
  }
45211
- this.logger.debug(`Created new agent ${agent.name}`);
46159
+ this.logger.debug(`Created new agent ${agent.id}`);
45212
46160
  return newAgent;
45213
46161
  }
45214
46162
  async getEntityById(entityId) {
@@ -45578,8 +46526,44 @@ class AgentRuntime {
45578
46526
  }
45579
46527
  }
45580
46528
 
46529
+ // src/secrets.ts
46530
+ init_environment();
46531
+ function hasCharacterSecrets(character) {
46532
+ return Boolean(character?.settings?.secrets && Object.keys(character.settings.secrets).length > 0);
46533
+ }
46534
+ async function loadSecretsNodeImpl(character) {
46535
+ const fs = await import("node:fs");
46536
+ const dotenv = await import("dotenv");
46537
+ const { findEnvFile: findEnvFile2 } = await Promise.resolve().then(() => (init_environment(), exports_environment));
46538
+ if (hasCharacterSecrets(character)) {
46539
+ return false;
46540
+ }
46541
+ const envPath = findEnvFile2();
46542
+ if (!envPath)
46543
+ return false;
46544
+ try {
46545
+ const buf = fs.readFileSync(envPath);
46546
+ const envSecrets = dotenv.parse(buf);
46547
+ if (!character.settings) {
46548
+ character.settings = {};
46549
+ }
46550
+ character.settings.secrets = envSecrets;
46551
+ return true;
46552
+ } catch {
46553
+ return false;
46554
+ }
46555
+ }
46556
+ async function setDefaultSecretsFromEnv(character) {
46557
+ const env2 = detectEnvironment();
46558
+ if (env2 !== "node") {
46559
+ return false;
46560
+ }
46561
+ return loadSecretsNodeImpl(character);
46562
+ }
46563
+
45581
46564
  // src/settings.ts
45582
46565
  var import_crypto_browserify = __toESM(require_crypto_browserify(), 1);
46566
+ init_environment();
45583
46567
  function createSettingFromConfig(configSetting) {
45584
46568
  return {
45585
46569
  name: configSetting.name,
@@ -45856,20 +46840,293 @@ function defineService(definition) {
45856
46840
  return createService(definition.serviceType).withDescription(definition.description).withStart(definition.start).withStop(definition.stop || (() => Promise.resolve())).build();
45857
46841
  }
45858
46842
 
46843
+ // src/plugin.ts
46844
+ init_environment();
46845
+ var attemptedInstalls = new Set;
46846
+ function isAutoInstallAllowed() {
46847
+ if (process.env.ELIZA_NO_AUTO_INSTALL === "true")
46848
+ return false;
46849
+ if (process.env.ELIZA_NO_PLUGIN_AUTO_INSTALL === "true")
46850
+ return false;
46851
+ if (process.env.CI === "true")
46852
+ return false;
46853
+ if (process.env.ELIZA_TEST_MODE === "true")
46854
+ return false;
46855
+ if (false)
46856
+ ;
46857
+ return true;
46858
+ }
46859
+ async function tryInstallPlugin(pluginName) {
46860
+ try {
46861
+ if (!isAutoInstallAllowed()) {
46862
+ logger.debug(`Auto-install disabled or not allowed in this environment. Skipping install for ${pluginName}.`);
46863
+ return false;
46864
+ }
46865
+ if (attemptedInstalls.has(pluginName)) {
46866
+ logger.debug(`Auto-install already attempted for ${pluginName}. Skipping.`);
46867
+ return false;
46868
+ }
46869
+ attemptedInstalls.add(pluginName);
46870
+ if (typeof Bun === "undefined" || typeof Bun.spawn !== "function") {
46871
+ logger.warn(`Bun runtime not available. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46872
+ return false;
46873
+ }
46874
+ try {
46875
+ const check = Bun.spawn(["bun", "--version"], { stdout: "pipe", stderr: "pipe" });
46876
+ const code = await check.exited;
46877
+ if (code !== 0) {
46878
+ logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46879
+ return false;
46880
+ }
46881
+ } catch {
46882
+ logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46883
+ return false;
46884
+ }
46885
+ logger.info(`Attempting to auto-install missing plugin: ${pluginName}`);
46886
+ const install = Bun.spawn(["bun", "add", pluginName], {
46887
+ cwd: process.cwd(),
46888
+ env: process.env,
46889
+ stdout: "inherit",
46890
+ stderr: "inherit"
46891
+ });
46892
+ const exit = await install.exited;
46893
+ if (exit === 0) {
46894
+ logger.info(`Successfully installed ${pluginName}. Retrying import...`);
46895
+ return true;
46896
+ }
46897
+ logger.error(`bun add ${pluginName} failed with exit code ${exit}. Please install manually.`);
46898
+ return false;
46899
+ } catch (e) {
46900
+ const message = e instanceof Error ? e.message : String(e);
46901
+ logger.error(`Unexpected error during auto-install of ${pluginName}: ${message}`);
46902
+ return false;
46903
+ }
46904
+ }
46905
+ function isValidPluginShape(obj) {
46906
+ if (!obj || typeof obj !== "object") {
46907
+ return false;
46908
+ }
46909
+ const plugin = obj;
46910
+ if (!plugin.name) {
46911
+ return false;
46912
+ }
46913
+ return !!(plugin.init || plugin.services || plugin.providers || plugin.actions || plugin.evaluators || plugin.description);
46914
+ }
46915
+ function validatePlugin(plugin) {
46916
+ const errors = [];
46917
+ if (!plugin) {
46918
+ errors.push("Plugin is null or undefined");
46919
+ return { isValid: false, errors };
46920
+ }
46921
+ const pluginObj = plugin;
46922
+ if (!pluginObj.name) {
46923
+ errors.push("Plugin must have a name");
46924
+ }
46925
+ if (pluginObj.actions) {
46926
+ if (!Array.isArray(pluginObj.actions)) {
46927
+ errors.push("Plugin actions must be an array");
46928
+ } else {
46929
+ const invalidActions = pluginObj.actions.filter((a) => typeof a !== "object" || !a);
46930
+ if (invalidActions.length > 0) {
46931
+ errors.push("Plugin actions must be an array of action objects");
46932
+ }
46933
+ }
46934
+ }
46935
+ if (pluginObj.services) {
46936
+ if (!Array.isArray(pluginObj.services)) {
46937
+ errors.push("Plugin services must be an array");
46938
+ } else {
46939
+ const invalidServices = pluginObj.services.filter((s) => typeof s !== "function" && (typeof s !== "object" || !s));
46940
+ if (invalidServices.length > 0) {
46941
+ errors.push("Plugin services must be an array of service classes or objects");
46942
+ }
46943
+ }
46944
+ }
46945
+ if (pluginObj.providers && !Array.isArray(pluginObj.providers)) {
46946
+ errors.push("Plugin providers must be an array");
46947
+ }
46948
+ if (pluginObj.evaluators && !Array.isArray(pluginObj.evaluators)) {
46949
+ errors.push("Plugin evaluators must be an array");
46950
+ }
46951
+ return {
46952
+ isValid: errors.length === 0,
46953
+ errors
46954
+ };
46955
+ }
46956
+ async function loadAndPreparePlugin(pluginName) {
46957
+ try {
46958
+ let pluginModule;
46959
+ try {
46960
+ pluginModule = await import(pluginName);
46961
+ } catch (error) {
46962
+ logger.warn(`Failed to load plugin ${pluginName}: ${error}`);
46963
+ const attempted = await tryInstallPlugin(pluginName);
46964
+ if (!attempted) {
46965
+ return null;
46966
+ }
46967
+ try {
46968
+ pluginModule = await import(pluginName);
46969
+ } catch (secondError) {
46970
+ logger.error(`Auto-install attempted for ${pluginName} but import still failed: ${secondError}`);
46971
+ return null;
46972
+ }
46973
+ }
46974
+ if (!pluginModule) {
46975
+ logger.error(`Failed to load module for plugin ${pluginName}.`);
46976
+ return null;
46977
+ }
46978
+ const expectedFunctionName = `${pluginName.replace(/^@elizaos\/plugin-/, "").replace(/^@elizaos\//, "").replace(/-./g, (match) => match[1].toUpperCase())}Plugin`;
46979
+ const moduleObj = pluginModule;
46980
+ const exportsToCheck = [
46981
+ moduleObj[expectedFunctionName],
46982
+ moduleObj.default,
46983
+ ...Object.values(moduleObj)
46984
+ ];
46985
+ for (const potentialPlugin of exportsToCheck) {
46986
+ if (isValidPluginShape(potentialPlugin)) {
46987
+ return potentialPlugin;
46988
+ }
46989
+ if (typeof potentialPlugin === "function" && potentialPlugin.length === 0) {
46990
+ try {
46991
+ const produced = potentialPlugin();
46992
+ if (isValidPluginShape(produced)) {
46993
+ return produced;
46994
+ }
46995
+ } catch (err) {
46996
+ logger.debug(`Factory export threw for ${pluginName}: ${err}`);
46997
+ }
46998
+ }
46999
+ }
47000
+ logger.warn(`Could not find a valid plugin export in ${pluginName}.`);
47001
+ return null;
47002
+ } catch (error) {
47003
+ logger.error(`Error loading plugin ${pluginName}: ${error}`);
47004
+ return null;
47005
+ }
47006
+ }
47007
+ function resolvePluginDependencies(availablePlugins, isTestMode = false) {
47008
+ const resolutionOrder = [];
47009
+ const visited = new Set;
47010
+ const visiting = new Set;
47011
+ function visit(pluginName) {
47012
+ if (!availablePlugins.has(pluginName)) {
47013
+ logger.warn(`Plugin dependency "${pluginName}" not found and will be skipped.`);
47014
+ return;
47015
+ }
47016
+ if (visited.has(pluginName))
47017
+ return;
47018
+ if (visiting.has(pluginName)) {
47019
+ logger.error(`Circular dependency detected involving plugin: ${pluginName}`);
47020
+ return;
47021
+ }
47022
+ visiting.add(pluginName);
47023
+ const plugin = availablePlugins.get(pluginName);
47024
+ if (plugin) {
47025
+ const deps = [...plugin.dependencies || []];
47026
+ if (isTestMode) {
47027
+ deps.push(...plugin.testDependencies || []);
47028
+ }
47029
+ for (const dep of deps) {
47030
+ visit(dep);
47031
+ }
47032
+ }
47033
+ visiting.delete(pluginName);
47034
+ visited.add(pluginName);
47035
+ resolutionOrder.push(pluginName);
47036
+ }
47037
+ for (const name of availablePlugins.keys()) {
47038
+ if (!visited.has(name)) {
47039
+ visit(name);
47040
+ }
47041
+ }
47042
+ const finalPlugins = resolutionOrder.map((name) => availablePlugins.get(name)).filter((p) => Boolean(p));
47043
+ logger.info({ plugins: finalPlugins.map((p) => p.name) }, `Final plugins being loaded:`);
47044
+ return finalPlugins;
47045
+ }
47046
+ async function loadPlugin(nameOrPlugin) {
47047
+ if (typeof nameOrPlugin === "string") {
47048
+ return loadAndPreparePlugin(nameOrPlugin);
47049
+ }
47050
+ const validation = validatePlugin(nameOrPlugin);
47051
+ if (!validation.isValid) {
47052
+ logger.error(`Invalid plugin provided: ${validation.errors.join(", ")}`);
47053
+ return null;
47054
+ }
47055
+ return nameOrPlugin;
47056
+ }
47057
+ async function resolvePluginsImpl(plugins, isTestMode = false) {
47058
+ const pluginMap = new Map;
47059
+ const queue2 = [...plugins];
47060
+ while (queue2.length > 0) {
47061
+ const next = queue2.shift();
47062
+ const loaded = await loadPlugin(next);
47063
+ if (!loaded)
47064
+ continue;
47065
+ if (!pluginMap.has(loaded.name)) {
47066
+ pluginMap.set(loaded.name, loaded);
47067
+ for (const depName of loaded.dependencies ?? []) {
47068
+ if (!pluginMap.has(depName)) {
47069
+ queue2.push(depName);
47070
+ }
47071
+ }
47072
+ if (isTestMode) {
47073
+ for (const depName of loaded.testDependencies ?? []) {
47074
+ if (!pluginMap.has(depName)) {
47075
+ queue2.push(depName);
47076
+ }
47077
+ }
47078
+ }
47079
+ }
47080
+ }
47081
+ return resolvePluginDependencies(pluginMap, isTestMode);
47082
+ }
47083
+ async function resolvePlugins(plugins, isTestMode = false) {
47084
+ const env2 = detectEnvironment();
47085
+ if (env2 === "node") {
47086
+ return resolvePluginsImpl(plugins, isTestMode);
47087
+ }
47088
+ const pluginObjects = plugins.filter((p) => typeof p !== "string");
47089
+ if (plugins.some((p) => typeof p === "string")) {
47090
+ logger.warn("Browser environment: String plugin references are not supported. Only Plugin objects will be used. Skipped plugins: " + plugins.filter((p) => typeof p === "string").join(", "));
47091
+ }
47092
+ const pluginMap = new Map;
47093
+ for (const plugin of pluginObjects) {
47094
+ pluginMap.set(plugin.name, plugin);
47095
+ }
47096
+ return resolvePluginDependencies(pluginMap, isTestMode);
47097
+ }
47098
+
45859
47099
  // src/elizaos.ts
45860
47100
  class ElizaOS extends EventTarget {
45861
47101
  runtimes = new Map;
47102
+ initFunctions = new Map;
45862
47103
  editableMode = false;
45863
- async addAgents(agents) {
47104
+ async addAgents(agents, options) {
45864
47105
  const promises = agents.map(async (agent) => {
47106
+ const character = agent.character;
47107
+ if (!hasCharacterSecrets(character)) {
47108
+ await setDefaultSecretsFromEnv(character);
47109
+ }
47110
+ const resolvedPlugins = agent.plugins ? await resolvePlugins(agent.plugins, options?.isTestMode || false) : [];
45865
47111
  const runtime = new AgentRuntime({
45866
- character: agent.character,
45867
- plugins: agent.plugins || [],
47112
+ character,
47113
+ plugins: resolvedPlugins,
45868
47114
  settings: agent.settings || {}
45869
47115
  });
45870
47116
  this.runtimes.set(runtime.agentId, runtime);
47117
+ if (typeof agent.init === "function") {
47118
+ this.initFunctions.set(runtime.agentId, agent.init);
47119
+ }
47120
+ const { settings, ...characterWithoutSecrets } = character;
47121
+ const { secrets, ...settingsWithoutSecrets } = settings || {};
45871
47122
  this.dispatchEvent(new CustomEvent("agent:added", {
45872
- detail: { agentId: runtime.agentId, character: agent.character }
47123
+ detail: {
47124
+ agentId: runtime.agentId,
47125
+ character: {
47126
+ ...characterWithoutSecrets,
47127
+ settings: settingsWithoutSecrets
47128
+ }
47129
+ }
45873
47130
  }));
45874
47131
  return runtime.agentId;
45875
47132
  });
@@ -45905,6 +47162,7 @@ class ElizaOS extends EventTarget {
45905
47162
  await this.stopAgents(agentIds);
45906
47163
  for (const id of agentIds) {
45907
47164
  this.runtimes.delete(id);
47165
+ this.initFunctions.delete(id);
45908
47166
  }
45909
47167
  this.dispatchEvent(new CustomEvent("agents:deleted", {
45910
47168
  detail: { agentIds, count: agentIds.length }
@@ -45922,6 +47180,16 @@ class ElizaOS extends EventTarget {
45922
47180
  detail: { agentId: id }
45923
47181
  }));
45924
47182
  }));
47183
+ for (const id of ids) {
47184
+ const initFn = this.initFunctions.get(id);
47185
+ if (initFn) {
47186
+ const runtime = this.runtimes.get(id);
47187
+ if (runtime) {
47188
+ await initFn(runtime);
47189
+ this.initFunctions.delete(id);
47190
+ }
47191
+ }
47192
+ }
45925
47193
  this.dispatchEvent(new CustomEvent("agents:started", {
45926
47194
  detail: { agentIds: ids, count: ids.length }
45927
47195
  }));
@@ -46284,11 +47552,14 @@ var isNode3 = true;
46284
47552
  export {
46285
47553
  waitForServerReady,
46286
47554
  validateUuid,
47555
+ validatePlugin,
47556
+ validateCharacterConfig,
46287
47557
  validateCharacter,
46288
47558
  uuidSchema2 as uuidSchema,
46289
47559
  updateWorldSettings,
46290
47560
  unsaltWorldSettings,
46291
47561
  unsaltSettingValue,
47562
+ tryInstallPlugin,
46292
47563
  truncateToCompleteSentence,
46293
47564
  trimTokens,
46294
47565
  toString2 as toString,
@@ -46301,10 +47572,13 @@ export {
46301
47572
  shouldRespondTemplate,
46302
47573
  settingsSchema,
46303
47574
  setEnv,
47575
+ setDefaultSecretsFromEnv,
46304
47576
  secretsSchema,
46305
47577
  saltWorldSettings,
46306
47578
  saltSettingValue,
46307
47579
  safeReplacer,
47580
+ resolvePlugins,
47581
+ resolvePluginDependencies,
46308
47582
  resetPaths,
46309
47583
  recentLogs,
46310
47584
  randomBytes,
@@ -46313,6 +47587,7 @@ export {
46313
47587
  pingServer,
46314
47588
  parseKeyValueXml,
46315
47589
  parseJSONObjectFromText,
47590
+ parseCharacter,
46316
47591
  parseBooleanFromText2 as parseBooleanFromText,
46317
47592
  parseAndValidateCharacter,
46318
47593
  normalizeJsonString,
@@ -46320,9 +47595,14 @@ export {
46320
47595
  multiStepDecisionTemplate,
46321
47596
  messageHandlerTemplate,
46322
47597
  messageExampleSchema,
47598
+ mergeCharacterDefaults,
46323
47599
  mediaSchema,
46324
47600
  logger,
47601
+ loadPlugin,
47602
+ loadEnvConfig,
47603
+ loadAndPreparePlugin,
46325
47604
  knowledgeItemSchema,
47605
+ isValidPluginShape,
46326
47606
  isValidCharacter,
46327
47607
  isNode3 as isNode,
46328
47608
  isMessageMetadata,
@@ -46338,6 +47618,7 @@ export {
46338
47618
  initBrowserEnvironment,
46339
47619
  imageDescriptionTemplate,
46340
47620
  hasEnv,
47621
+ hasCharacterSecrets,
46341
47622
  getWorldSettings,
46342
47623
  getUserServerRole,
46343
47624
  getUploadsChannelsDir,
@@ -46368,6 +47649,7 @@ export {
46368
47649
  formatActions,
46369
47650
  formatActionNames,
46370
47651
  findWorldsForOwner,
47652
+ findEnvFile,
46371
47653
  findEntityByName,
46372
47654
  equals,
46373
47655
  encryptedCharacter,
@@ -46397,6 +47679,7 @@ export {
46397
47679
  clearSaltCache,
46398
47680
  characterSchema,
46399
47681
  byteLength,
47682
+ buildCharacterPlugins,
46400
47683
  booleanFooter,
46401
47684
  asUUID,
46402
47685
  alloc,
@@ -46418,6 +47701,7 @@ export {
46418
47701
  EventType,
46419
47702
  Environment,
46420
47703
  ElizaOS,
47704
+ DefaultMessageService,
46421
47705
  DatabaseAdapter,
46422
47706
  ContentType,
46423
47707
  ChannelType,
@@ -46427,5 +47711,5 @@ export {
46427
47711
  AgentRuntime
46428
47712
  };
46429
47713
 
46430
- //# debugId=EC34687CD2FBE32664756E2164756E21
47714
+ //# debugId=738C38AE1C103AEB64756E2164756E21
46431
47715
  //# sourceMappingURL=index.node.js.map