@elizaos/core 1.6.2-alpha.2 → 1.6.2-alpha.21

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,220 @@ 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 = [
10022
+ path.join(process.cwd(), ".env"),
10023
+ path.join(process.cwd(), ".env.local")
10024
+ ];
10025
+ for (const envPath of possiblePaths) {
10026
+ if (fs.existsSync(envPath)) {
10027
+ return envPath;
10028
+ }
10029
+ }
10030
+ return null;
10031
+ }
10032
+ async function loadEnvConfig(envPath) {
10033
+ if (typeof process === "undefined" || !process.cwd) {
10034
+ return {};
10035
+ }
10036
+ const dotenv = __require("dotenv");
10037
+ const resolvedPath = envPath || findEnvFile();
10038
+ if (resolvedPath) {
10039
+ const result = dotenv.config({ path: resolvedPath });
10040
+ if (result.error) {
10041
+ throw result.error;
10042
+ }
10043
+ }
10044
+ return process.env;
10045
+ }
10046
+ var environmentInstance = null, currentRuntime;
10047
+ var init_environment = __esm(() => {
10048
+ currentRuntime = detectEnvironment();
10049
+ });
10050
+
9814
10051
  // ../../node_modules/picocolors/picocolors.js
9815
10052
  var require_picocolors = __commonJS((exports, module) => {
9816
10053
  var p = process || {};
@@ -10499,24 +10736,6 @@ var require_get_proto = __commonJS((exports, module) => {
10499
10736
  } : null;
10500
10737
  });
10501
10738
 
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
10739
  // ../../node_modules/hasown/index.js
10521
10740
  var require_hasown = __commonJS((exports, module) => {
10522
10741
  var call = Function.prototype.call;
@@ -10543,6 +10762,12 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10543
10762
  var pow = require_pow();
10544
10763
  var round = require_round();
10545
10764
  var sign = require_sign();
10765
+ var $Function = Function;
10766
+ var getEvalledConstructor = function(expressionSyntax) {
10767
+ try {
10768
+ return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
10769
+ } catch (e) {}
10770
+ };
10546
10771
  var $gOPD = require_gopd();
10547
10772
  var $defineProperty = require_es_define_property();
10548
10773
  var throwTypeError = function() {
@@ -10597,7 +10822,7 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10597
10822
  "%Float32Array%": typeof Float32Array === "undefined" ? undefined3 : Float32Array,
10598
10823
  "%Float64Array%": typeof Float64Array === "undefined" ? undefined3 : Float64Array,
10599
10824
  "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined3 : FinalizationRegistry,
10600
- "%Function%": Function,
10825
+ "%Function%": $Function,
10601
10826
  "%GeneratorFunction%": needsEval,
10602
10827
  "%Int8Array%": typeof Int8Array === "undefined" ? undefined3 : Int8Array,
10603
10828
  "%Int16Array%": typeof Int16Array === "undefined" ? undefined3 : Int16Array,
@@ -10660,17 +10885,14 @@ var require_get_intrinsic = __commonJS((exports, module) => {
10660
10885
  }
10661
10886
  }
10662
10887
  var errorProto;
10663
- var getAsyncFunction = require_async_function();
10664
- var getGeneratorFunction = require_generator_function();
10665
- var getAsyncGeneratorFunction = require_async_generator_function();
10666
10888
  var doEval = function doEval(name) {
10667
10889
  var value;
10668
10890
  if (name === "%AsyncFunction%") {
10669
- value = getAsyncFunction() || undefined;
10891
+ value = getEvalledConstructor("async function () {}");
10670
10892
  } else if (name === "%GeneratorFunction%") {
10671
- value = getGeneratorFunction() || undefined;
10893
+ value = getEvalledConstructor("function* () {}");
10672
10894
  } else if (name === "%AsyncGeneratorFunction%") {
10673
- value = getAsyncGeneratorFunction() || undefined;
10895
+ value = getEvalledConstructor("async function* () {}");
10674
10896
  } else if (name === "%AsyncGenerator%") {
10675
10897
  var fn = doEval("%AsyncGeneratorFunction%");
10676
10898
  if (fn) {
@@ -25770,7 +25992,7 @@ var getDefaultProjectName = () => {
25770
25992
  };
25771
25993
 
25772
25994
  // ../../node_modules/langsmith/dist/index.js
25773
- var __version__ = "0.3.71";
25995
+ var __version__ = "0.3.74";
25774
25996
 
25775
25997
  // ../../node_modules/langsmith/dist/utils/env.js
25776
25998
  var globalEnv;
@@ -25815,8 +26037,8 @@ function getRuntimeEnvironment() {
25815
26037
  }
25816
26038
  return runtimeEnvironment;
25817
26039
  }
25818
- function getLangChainEnvVarsMetadata() {
25819
- const allEnvVars = getEnvironmentVariables() || {};
26040
+ function getLangSmithEnvVarsMetadata() {
26041
+ const allEnvVars = getLangSmithEnvironmentVariables();
25820
26042
  const envVars = {};
25821
26043
  const excluded = [
25822
26044
  "LANGCHAIN_API_KEY",
@@ -25831,7 +26053,7 @@ function getLangChainEnvVarsMetadata() {
25831
26053
  "LANGSMITH_SESSION"
25832
26054
  ];
25833
26055
  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")) {
26056
+ if (typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
25835
26057
  if (key === "LANGCHAIN_REVISION_ID") {
25836
26058
  envVars["revision_id"] = value;
25837
26059
  } else {
@@ -25841,18 +26063,22 @@ function getLangChainEnvVarsMetadata() {
25841
26063
  }
25842
26064
  return envVars;
25843
26065
  }
25844
- function getEnvironmentVariables() {
26066
+ function getLangSmithEnvironmentVariables() {
26067
+ const envVars = {};
25845
26068
  try {
25846
26069
  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
- }, {});
26070
+ for (const [key, value] of Object.entries(process.env)) {
26071
+ if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && value != null) {
26072
+ if ((key.toLowerCase().includes("key") || key.toLowerCase().includes("secret") || key.toLowerCase().includes("token")) && typeof value === "string") {
26073
+ envVars[key] = value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2);
26074
+ } else {
26075
+ envVars[key] = value;
26076
+ }
26077
+ }
26078
+ }
25851
26079
  }
25852
- return;
25853
- } catch (e) {
25854
- return;
25855
- }
26080
+ } catch (e) {}
26081
+ return envVars;
25856
26082
  }
25857
26083
  function getEnvironmentVariable(name) {
25858
26084
  try {
@@ -26727,9 +26953,9 @@ function replaceGetterValues(replacer) {
26727
26953
  }
26728
26954
 
26729
26955
  // ../../node_modules/langsmith/dist/client.js
26730
- function mergeRuntimeEnvIntoRun(run) {
26956
+ function mergeRuntimeEnvIntoRun(run, cachedEnvVars) {
26731
26957
  const runtimeEnv = getRuntimeEnvironment();
26732
- const envVars = getLangChainEnvVarsMetadata();
26958
+ const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();
26733
26959
  const extra = run.extra ?? {};
26734
26960
  const metadata = extra.metadata;
26735
26961
  run.extra = {
@@ -27035,6 +27261,12 @@ class Client {
27035
27261
  writable: true,
27036
27262
  value: undefined
27037
27263
  });
27264
+ Object.defineProperty(this, "cachedLSEnvVarsForMetadata", {
27265
+ enumerable: true,
27266
+ configurable: true,
27267
+ writable: true,
27268
+ value: undefined
27269
+ });
27038
27270
  Object.defineProperty(this, "multipartStreamingDisabled", {
27039
27271
  enumerable: true,
27040
27272
  configurable: true,
@@ -27089,6 +27321,7 @@ class Client {
27089
27321
  if (getOtelEnabled()) {
27090
27322
  this.langSmithToOTELTranslator = new LangSmithToOTELTranslator;
27091
27323
  }
27324
+ this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata();
27092
27325
  }
27093
27326
  static getDefaultClientConfig() {
27094
27327
  const apiKey = getLangSmithEnvironmentVariable("API_KEY");
@@ -27400,7 +27633,7 @@ class Client {
27400
27633
  async processRunOperation(item) {
27401
27634
  clearTimeout(this.autoBatchTimeout);
27402
27635
  this.autoBatchTimeout = undefined;
27403
- item.item = mergeRuntimeEnvIntoRun(item.item);
27636
+ item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata);
27404
27637
  const itemPromise = this.autoBatchQueue.push(item);
27405
27638
  if (this.manualFlushMode) {
27406
27639
  return itemPromise;
@@ -27515,7 +27748,7 @@ class Client {
27515
27748
  }).catch(console.error);
27516
27749
  return;
27517
27750
  }
27518
- const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate);
27751
+ const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata);
27519
27752
  if (options?.apiKey !== undefined) {
27520
27753
  headers["x-api-key"] = options.apiKey;
27521
27754
  }
@@ -28017,6 +28250,9 @@ Context: ${context}`);
28017
28250
  is_root: isRoot,
28018
28251
  order
28019
28252
  };
28253
+ if (body.select.includes("child_run_ids")) {
28254
+ warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");
28255
+ }
28020
28256
  let runsYielded = 0;
28021
28257
  for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
28022
28258
  if (limit) {
@@ -39079,171 +39315,8 @@ var import_handlebars = __toESM(require_lib(), 1);
39079
39315
  var import_unique_names_generator = __toESM(require_dist4(), 1);
39080
39316
  import { z as z2 } from "zod";
39081
39317
 
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();
39318
+ // src/logger.ts
39319
+ init_environment();
39247
39320
  // ../../node_modules/adze/dist/tools.js
39248
39321
  class Tools {
39249
39322
  globalStore;
@@ -41379,6 +41452,7 @@ var recentLogs = () => globalInMemoryDestination.recentLogs();
41379
41452
  var logger_default = logger;
41380
41453
 
41381
41454
  // src/utils.ts
41455
+ init_environment();
41382
41456
  function upgradeDoubleToTriple(tpl) {
41383
41457
  return tpl.replace(/(?<!{){{(?![{#\/!>])([\s\S]*?)}}/g, (_match, inner) => {
41384
41458
  if (inner.trim() === "else")
@@ -41791,6 +41865,8 @@ function safeReplacer() {
41791
41865
  function parseBooleanFromText2(value) {
41792
41866
  if (!value)
41793
41867
  return false;
41868
+ if (typeof value === "boolean")
41869
+ return value;
41794
41870
  const affirmative = ["YES", "Y", "TRUE", "T", "1", "ON", "ENABLE"];
41795
41871
  const negative = ["NO", "N", "FALSE", "F", "0", "OFF", "DISABLE"];
41796
41872
  const normalizedText = value.trim().toUpperCase();
@@ -41990,63 +42066,72 @@ function getLocalServerUrl(path) {
41990
42066
  }
41991
42067
  // src/schemas/character.ts
41992
42068
  import { z as z3 } from "zod";
41993
- var uuidSchema2 = z3.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Invalid UUID format");
42069
+ var uuidSchema2 = z3.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Invalid UUID format").describe("Unique identifier for the character in UUID format");
42070
+ var mediaSchema = z3.object({
42071
+ id: z3.string().describe("Unique identifier for the media"),
42072
+ url: z3.string().describe("URL of the media file"),
42073
+ title: z3.string().optional().describe("Media title"),
42074
+ source: z3.string().optional().describe("Media source"),
42075
+ description: z3.string().optional().describe("Media description"),
42076
+ text: z3.string().optional().describe("Text content associated with the media"),
42077
+ contentType: z3.nativeEnum(ContentType).optional().describe("Type of media content")
42078
+ }).loose().describe("Media attachment with URL and metadata");
41994
42079
  var contentSchema = z3.object({
41995
- text: z3.string().optional(),
41996
- thought: z3.string().optional(),
41997
- actions: z3.array(z3.string()).optional(),
41998
- providers: z3.array(z3.string()).optional(),
41999
- source: z3.string().optional(),
42000
- target: z3.string().optional(),
42001
- url: z3.string().optional(),
42002
- inReplyTo: uuidSchema2.optional(),
42003
- attachments: z3.array(z3.any()).optional(),
42004
- channelType: z3.nativeEnum(ChannelType).optional()
42005
- }).passthrough();
42080
+ text: z3.string().optional().describe("The main text content of the message"),
42081
+ thought: z3.string().optional().describe("Internal thought process or reasoning"),
42082
+ actions: z3.array(z3.string()).optional().describe("Actions to be taken in response"),
42083
+ providers: z3.array(z3.string()).optional().describe("Data providers to use (e.g., KNOWLEDGE)"),
42084
+ source: z3.string().optional().describe("Source of the content"),
42085
+ target: z3.string().optional().describe("Target of the content"),
42086
+ url: z3.string().optional().describe("Related URL"),
42087
+ inReplyTo: uuidSchema2.optional().describe("UUID of message this is replying to"),
42088
+ attachments: z3.array(mediaSchema).optional().describe("Array of media attachments (images, videos, documents, etc.)"),
42089
+ channelType: z3.enum(ChannelType).optional().describe("Type of channel this content is for")
42090
+ }).catchall(z3.unknown()).describe("Content structure for messages in conversation examples");
42006
42091
  var messageExampleSchema = z3.object({
42007
- name: z3.string(),
42092
+ name: z3.string().describe("Name of the speaker (can use {{name1}} placeholder for dynamic names)"),
42008
42093
  content: contentSchema
42009
- });
42094
+ }).describe("A single message in a conversation example");
42010
42095
  var directoryItemSchema = z3.object({
42011
- directory: z3.string(),
42012
- shared: z3.boolean().optional()
42013
- });
42096
+ directory: z3.string().describe("Path to a directory containing knowledge files"),
42097
+ shared: z3.boolean().optional().describe("Whether this knowledge is shared across characters")
42098
+ }).describe("Directory-based knowledge source");
42014
42099
  var knowledgeItemSchema = z3.union([
42015
- z3.string(),
42100
+ z3.string().describe("File path to a knowledge document"),
42016
42101
  z3.object({
42017
- path: z3.string(),
42018
- shared: z3.boolean().optional()
42102
+ path: z3.string().describe("Path to a knowledge file"),
42103
+ shared: z3.boolean().optional().describe("Whether this knowledge is shared across characters")
42019
42104
  }),
42020
42105
  directoryItemSchema
42021
- ]);
42106
+ ]).describe("Knowledge source - can be a file path, file object, or directory");
42022
42107
  var templateTypeSchema = z3.union([
42023
- z3.string(),
42108
+ z3.string().describe("Template string with placeholders"),
42024
42109
  z3.function().optional()
42025
- ]);
42110
+ ]).describe("Template for generating text - can be a string template or function");
42026
42111
  var styleSchema = z3.object({
42027
- all: z3.array(z3.string()).optional(),
42028
- chat: z3.array(z3.string()).optional(),
42029
- post: z3.array(z3.string()).optional()
42030
- }).optional();
42031
- var settingsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.boolean(), z3.number(), z3.any()])).optional();
42032
- var secretsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.boolean(), z3.number()])).optional();
42112
+ all: z3.array(z3.string()).optional().describe("Style guidelines applied to all types of responses"),
42113
+ chat: z3.array(z3.string()).optional().describe("Style guidelines specific to chat/conversation responses"),
42114
+ post: z3.array(z3.string()).optional().describe("Style guidelines specific to social media posts")
42115
+ }).optional().describe("Style configuration defining how the character communicates across different contexts");
42116
+ 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");
42117
+ 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)");
42033
42118
  var characterSchema = z3.object({
42034
- id: uuidSchema2.optional(),
42035
- name: z3.string().min(1, "Character name is required"),
42036
- username: z3.string().optional(),
42037
- system: z3.string().optional(),
42038
- templates: z3.record(z3.string(), templateTypeSchema).optional(),
42039
- bio: z3.union([z3.string(), z3.array(z3.string())]),
42040
- messageExamples: z3.array(z3.array(messageExampleSchema)).optional(),
42041
- postExamples: z3.array(z3.string()).optional(),
42042
- topics: z3.array(z3.string()).optional(),
42043
- adjectives: z3.array(z3.string()).optional(),
42044
- knowledge: z3.array(knowledgeItemSchema).optional(),
42045
- plugins: z3.array(z3.string()).optional(),
42119
+ id: uuidSchema2.optional().describe("Unique identifier for the character"),
42120
+ name: z3.string().min(1, "Character name is required").describe('The name of the character (e.g., "Eliza")'),
42121
+ username: z3.string().optional().describe("Username for the character on various platforms"),
42122
+ system: z3.string().optional().describe("System prompt that defines the character's core behavior and response style"),
42123
+ templates: z3.record(z3.string(), templateTypeSchema).optional().describe("Custom templates for generating different types of content"),
42124
+ bio: z3.union([z3.string(), z3.array(z3.string())]).describe("Character biography - can be a single string or array of biographical points"),
42125
+ messageExamples: z3.array(z3.array(messageExampleSchema)).optional().describe("Example conversations showing how the character responds in different scenarios"),
42126
+ postExamples: z3.array(z3.string()).optional().describe("Example social media posts demonstrating the character's voice and topics"),
42127
+ topics: z3.array(z3.string()).optional().describe("Topics the character is knowledgeable about and engages with"),
42128
+ adjectives: z3.array(z3.string()).optional().describe("Adjectives that describe the character's personality and traits"),
42129
+ knowledge: z3.array(knowledgeItemSchema).optional().describe("Knowledge sources (files, directories) the character can reference"),
42130
+ plugins: z3.array(z3.string()).optional().describe('List of plugin package names to load (e.g., ["@elizaos/plugin-sql", "@elizaos/plugin-bootstrap"] - these are commonly required)'),
42046
42131
  settings: settingsSchema,
42047
42132
  secrets: secretsSchema,
42048
42133
  style: styleSchema
42049
- }).strict();
42134
+ }).strict().describe("Complete character definition including personality, behavior, and capabilities");
42050
42135
  function validateCharacter(data2) {
42051
42136
  const result = characterSchema.safeParse(data2);
42052
42137
  if (result.success) {
@@ -42079,6 +42164,10 @@ function parseAndValidateCharacter(jsonString) {
42079
42164
  function isValidCharacter(data2) {
42080
42165
  return validateCharacter(data2).success;
42081
42166
  }
42167
+
42168
+ // src/index.node.ts
42169
+ init_environment();
42170
+
42082
42171
  // src/utils/buffer.ts
42083
42172
  function hasNativeBuffer() {
42084
42173
  return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
@@ -42710,12 +42799,12 @@ These are the actions or data provider calls that have already been used in this
42710
42799
 
42711
42800
  <keys>
42712
42801
  "thought" Clearly explain your reasoning for the selected providers and/or action, and how this step contributes to resolving the user's request.
42713
- "action" Name of the action to execute after providers return (can be null if no action is needed).
42802
+ "action" Name of the action to execute after providers return (can be empty if no action is needed).
42714
42803
  "providers" List of provider names to call in this step (can be empty if none are needed).
42715
42804
  "isFinish" Set to true only if the task is fully complete.
42716
42805
  </keys>
42717
42806
 
42718
- ⚠️ IMPORTANT: Do **not** mark the task as \`isFinish: true\` immediately after calling an action like. Wait for the action to complete before deciding the task is finished.
42807
+ ⚠️ IMPORTANT: Do **not** mark the task as \`isFinish: true\` immediately after calling an action. Wait for the action to complete before deciding the task is finished.
42719
42808
 
42720
42809
  <output>
42721
42810
  <response>
@@ -42851,6 +42940,9 @@ function v43(options, buf, offset) {
42851
42940
  return _v4(options, buf, offset);
42852
42941
  }
42853
42942
  var v4_default = v43;
42943
+ // src/runtime.ts
42944
+ init_environment();
42945
+
42854
42946
  // src/search.ts
42855
42947
  var isV = (char) => {
42856
42948
  switch (char) {
@@ -43728,7 +43820,7 @@ class AgentRuntime {
43728
43820
  currentActionContext;
43729
43821
  maxWorkingMemoryEntries = 50;
43730
43822
  constructor(opts) {
43731
- this.agentId = opts.character?.id ?? opts?.agentId ?? stringToUuid(opts.character?.name ?? v4_default() + opts.character?.username);
43823
+ this.agentId = opts.character?.id ?? opts?.agentId ?? stringToUuid(opts.character?.name ?? v4_default());
43732
43824
  this.character = opts.character;
43733
43825
  this.initPromise = new Promise((resolve, reject) => {
43734
43826
  this.initResolver = resolve;
@@ -43894,9 +43986,12 @@ class AgentRuntime {
43894
43986
  this.logger.info("Running plugin migrations...");
43895
43987
  await this.runPluginMigrations();
43896
43988
  this.logger.info("Plugin migrations completed.");
43897
- const existingAgent = await this.ensureAgentExists(this.character);
43989
+ const existingAgent = await this.ensureAgentExists({
43990
+ ...this.character,
43991
+ id: this.agentId
43992
+ });
43898
43993
  if (!existingAgent) {
43899
- const errorMsg = `Agent ${this.character.name} does not exist in database after ensureAgentExists call`;
43994
+ const errorMsg = `Agent ${this.agentId} does not exist in database after ensureAgentExists call`;
43900
43995
  throw new Error(errorMsg);
43901
43996
  }
43902
43997
  let agentEntity = await this.getEntityById(this.agentId);
@@ -44444,42 +44539,56 @@ class AgentRuntime {
44444
44539
  }
44445
44540
  }
44446
44541
  async evaluate(message, state, didRespond, callback, responses) {
44447
- const evaluatorPromises = this.evaluators.map(async (evaluator) => {
44448
- if (!evaluator.handler) {
44449
- return null;
44450
- }
44451
- if (!didRespond && !evaluator.alwaysRun) {
44452
- return null;
44453
- }
44454
- const result = await evaluator.validate(this, message, state);
44455
- if (result) {
44456
- return evaluator;
44542
+ try {
44543
+ const evaluatorPromises = this.evaluators.map(async (evaluator) => {
44544
+ try {
44545
+ if (!evaluator.handler) {
44546
+ return null;
44547
+ }
44548
+ if (!didRespond && !evaluator.alwaysRun) {
44549
+ return null;
44550
+ }
44551
+ const result = await evaluator.validate(this, message, state);
44552
+ if (result) {
44553
+ return evaluator;
44554
+ }
44555
+ return null;
44556
+ } catch (error) {
44557
+ this.logger.error({ error, evaluatorName: evaluator.name }, `Error validating evaluator ${evaluator.name}`);
44558
+ return null;
44559
+ }
44560
+ });
44561
+ const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
44562
+ if (evaluators.length === 0) {
44563
+ return [];
44457
44564
  }
44458
- return null;
44459
- });
44460
- const evaluators = (await Promise.all(evaluatorPromises)).filter(Boolean);
44461
- if (evaluators.length === 0) {
44565
+ state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
44566
+ await Promise.all(evaluators.map(async (evaluator) => {
44567
+ try {
44568
+ if (evaluator.handler) {
44569
+ await evaluator.handler(this, message, state, {}, callback, responses);
44570
+ this.adapter.log({
44571
+ entityId: message.entityId,
44572
+ roomId: message.roomId,
44573
+ type: "evaluator",
44574
+ body: {
44575
+ evaluator: evaluator.name,
44576
+ messageId: message.id,
44577
+ message: message.content.text,
44578
+ state,
44579
+ runId: this.getCurrentRunId()
44580
+ }
44581
+ });
44582
+ }
44583
+ } catch (error) {
44584
+ this.logger.error({ error, evaluatorName: evaluator.name }, `Error executing evaluator ${evaluator.name}`);
44585
+ }
44586
+ }));
44587
+ return evaluators;
44588
+ } catch (error) {
44589
+ this.logger.error({ error, messageId: message.id, roomId: message.roomId }, "Error in evaluate method");
44462
44590
  return [];
44463
44591
  }
44464
- state = await this.composeState(message, ["RECENT_MESSAGES", "EVALUATORS"]);
44465
- await Promise.all(evaluators.map(async (evaluator) => {
44466
- if (evaluator.handler) {
44467
- await evaluator.handler(this, message, state, {}, callback, responses);
44468
- this.adapter.log({
44469
- entityId: message.entityId,
44470
- roomId: message.roomId,
44471
- type: "evaluator",
44472
- body: {
44473
- evaluator: evaluator.name,
44474
- messageId: message.id,
44475
- message: message.content.text,
44476
- state,
44477
- runId: this.getCurrentRunId()
44478
- }
44479
- });
44480
- }
44481
- }));
44482
- return evaluators;
44483
44592
  }
44484
44593
  async ensureConnections(entities, rooms, source, world) {
44485
44594
  if (!entities) {
@@ -45084,6 +45193,51 @@ class AgentRuntime {
45084
45193
  throw error;
45085
45194
  }
45086
45195
  }
45196
+ async generateText(input, options) {
45197
+ if (!input?.trim()) {
45198
+ throw new Error("Input cannot be empty");
45199
+ }
45200
+ const includeCharacter = options?.includeCharacter ?? true;
45201
+ const modelType = options?.modelType ?? ModelType.TEXT_LARGE;
45202
+ let prompt = input;
45203
+ if (includeCharacter && this.character) {
45204
+ const c = this.character;
45205
+ const parts = [];
45206
+ const bioText = Array.isArray(c.bio) ? c.bio.join(" ") : c.bio;
45207
+ if (bioText) {
45208
+ parts.push(`# About ${c.name}
45209
+ ${bioText}`);
45210
+ }
45211
+ if (c.system) {
45212
+ parts.push(c.system);
45213
+ }
45214
+ const styles2 = [...c.style?.all || [], ...c.style?.chat || []];
45215
+ if (styles2.length > 0) {
45216
+ parts.push(`Style:
45217
+ ${styles2.map((s) => `- ${s}`).join(`
45218
+ `)}`);
45219
+ }
45220
+ if (parts.length > 0) {
45221
+ prompt = `${parts.join(`
45222
+
45223
+ `)}
45224
+
45225
+ ${input}`;
45226
+ }
45227
+ }
45228
+ const params = {
45229
+ prompt,
45230
+ maxTokens: options?.maxTokens,
45231
+ temperature: options?.temperature,
45232
+ frequencyPenalty: options?.frequencyPenalty,
45233
+ presencePenalty: options?.presencePenalty,
45234
+ stopSequences: options?.stopSequences
45235
+ };
45236
+ const response = await this.useModel(modelType, params);
45237
+ return {
45238
+ text: response
45239
+ };
45240
+ }
45087
45241
  registerEvent(event, handler) {
45088
45242
  if (!this.events[event]) {
45089
45243
  this.events[event] = [];
@@ -45170,34 +45324,33 @@ class AgentRuntime {
45170
45324
  return await this.adapter.deleteAgent(agentId);
45171
45325
  }
45172
45326
  async ensureAgentExists(agent) {
45173
- if (!agent.name) {
45174
- throw new Error("Agent name is required");
45327
+ if (!agent.id) {
45328
+ throw new Error("Agent id is required");
45175
45329
  }
45176
- const agents = await this.adapter.getAgents();
45177
- const existingAgentId = agents.find((a) => a.name === agent.name)?.id;
45178
- if (existingAgentId) {
45330
+ const existingAgent = await this.adapter.getAgent(agent.id);
45331
+ if (existingAgent) {
45179
45332
  const updatedAgent = {
45180
45333
  ...agent,
45181
- id: existingAgentId,
45334
+ id: agent.id,
45182
45335
  updatedAt: Date.now()
45183
45336
  };
45184
- await this.adapter.updateAgent(existingAgentId, updatedAgent);
45185
- const existingAgent = await this.adapter.getAgent(existingAgentId);
45186
- if (!existingAgent) {
45187
- throw new Error(`Failed to retrieve agent after update: ${existingAgentId}`);
45337
+ await this.adapter.updateAgent(agent.id, updatedAgent);
45338
+ const refreshedAgent = await this.adapter.getAgent(agent.id);
45339
+ if (!refreshedAgent) {
45340
+ throw new Error(`Failed to retrieve agent after update: ${agent.id}`);
45188
45341
  }
45189
- this.logger.debug(`Updated existing agent ${agent.name} on restart`);
45190
- return existingAgent;
45342
+ this.logger.debug(`Updated existing agent ${agent.id} on restart`);
45343
+ return refreshedAgent;
45191
45344
  }
45192
45345
  const newAgent = {
45193
45346
  ...agent,
45194
- id: stringToUuid(agent.name)
45347
+ id: agent.id
45195
45348
  };
45196
45349
  const created = await this.adapter.createAgent(newAgent);
45197
45350
  if (!created) {
45198
- throw new Error(`Failed to create agent: ${agent.name}`);
45351
+ throw new Error(`Failed to create agent: ${agent.id}`);
45199
45352
  }
45200
- this.logger.debug(`Created new agent ${agent.name}`);
45353
+ this.logger.debug(`Created new agent ${agent.id}`);
45201
45354
  return newAgent;
45202
45355
  }
45203
45356
  async getEntityById(entityId) {
@@ -45567,8 +45720,44 @@ class AgentRuntime {
45567
45720
  }
45568
45721
  }
45569
45722
 
45723
+ // src/secrets.ts
45724
+ init_environment();
45725
+ function hasCharacterSecrets(character) {
45726
+ return Boolean(character?.settings?.secrets && Object.keys(character.settings.secrets).length > 0);
45727
+ }
45728
+ async function loadSecretsNodeImpl(character) {
45729
+ const fs = await import("node:fs");
45730
+ const dotenv = await import("dotenv");
45731
+ const { findEnvFile: findEnvFile2 } = await Promise.resolve().then(() => (init_environment(), exports_environment));
45732
+ if (hasCharacterSecrets(character)) {
45733
+ return false;
45734
+ }
45735
+ const envPath = findEnvFile2();
45736
+ if (!envPath)
45737
+ return false;
45738
+ try {
45739
+ const buf = fs.readFileSync(envPath);
45740
+ const envSecrets = dotenv.parse(buf);
45741
+ if (!character.settings) {
45742
+ character.settings = {};
45743
+ }
45744
+ character.settings.secrets = envSecrets;
45745
+ return true;
45746
+ } catch {
45747
+ return false;
45748
+ }
45749
+ }
45750
+ async function setDefaultSecretsFromEnv(character) {
45751
+ const env2 = detectEnvironment();
45752
+ if (env2 !== "node") {
45753
+ return false;
45754
+ }
45755
+ return loadSecretsNodeImpl(character);
45756
+ }
45757
+
45570
45758
  // src/settings.ts
45571
45759
  var import_crypto_browserify = __toESM(require_crypto_browserify(), 1);
45760
+ init_environment();
45572
45761
  function createSettingFromConfig(configSetting) {
45573
45762
  return {
45574
45763
  name: configSetting.name,
@@ -45845,20 +46034,293 @@ function defineService(definition) {
45845
46034
  return createService(definition.serviceType).withDescription(definition.description).withStart(definition.start).withStop(definition.stop || (() => Promise.resolve())).build();
45846
46035
  }
45847
46036
 
46037
+ // src/plugin.ts
46038
+ init_environment();
46039
+ var attemptedInstalls = new Set;
46040
+ function isAutoInstallAllowed() {
46041
+ if (process.env.ELIZA_NO_AUTO_INSTALL === "true")
46042
+ return false;
46043
+ if (process.env.ELIZA_NO_PLUGIN_AUTO_INSTALL === "true")
46044
+ return false;
46045
+ if (process.env.CI === "true")
46046
+ return false;
46047
+ if (process.env.ELIZA_TEST_MODE === "true")
46048
+ return false;
46049
+ if (false)
46050
+ ;
46051
+ return true;
46052
+ }
46053
+ async function tryInstallPlugin(pluginName) {
46054
+ try {
46055
+ if (!isAutoInstallAllowed()) {
46056
+ logger.debug(`Auto-install disabled or not allowed in this environment. Skipping install for ${pluginName}.`);
46057
+ return false;
46058
+ }
46059
+ if (attemptedInstalls.has(pluginName)) {
46060
+ logger.debug(`Auto-install already attempted for ${pluginName}. Skipping.`);
46061
+ return false;
46062
+ }
46063
+ attemptedInstalls.add(pluginName);
46064
+ if (typeof Bun === "undefined" || typeof Bun.spawn !== "function") {
46065
+ logger.warn(`Bun runtime not available. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46066
+ return false;
46067
+ }
46068
+ try {
46069
+ const check = Bun.spawn(["bun", "--version"], { stdout: "pipe", stderr: "pipe" });
46070
+ const code = await check.exited;
46071
+ if (code !== 0) {
46072
+ logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46073
+ return false;
46074
+ }
46075
+ } catch {
46076
+ logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
46077
+ return false;
46078
+ }
46079
+ logger.info(`Attempting to auto-install missing plugin: ${pluginName}`);
46080
+ const install = Bun.spawn(["bun", "add", pluginName], {
46081
+ cwd: process.cwd(),
46082
+ env: process.env,
46083
+ stdout: "inherit",
46084
+ stderr: "inherit"
46085
+ });
46086
+ const exit = await install.exited;
46087
+ if (exit === 0) {
46088
+ logger.info(`Successfully installed ${pluginName}. Retrying import...`);
46089
+ return true;
46090
+ }
46091
+ logger.error(`bun add ${pluginName} failed with exit code ${exit}. Please install manually.`);
46092
+ return false;
46093
+ } catch (e) {
46094
+ const message = e instanceof Error ? e.message : String(e);
46095
+ logger.error(`Unexpected error during auto-install of ${pluginName}: ${message}`);
46096
+ return false;
46097
+ }
46098
+ }
46099
+ function isValidPluginShape(obj) {
46100
+ if (!obj || typeof obj !== "object") {
46101
+ return false;
46102
+ }
46103
+ const plugin = obj;
46104
+ if (!plugin.name) {
46105
+ return false;
46106
+ }
46107
+ return !!(plugin.init || plugin.services || plugin.providers || plugin.actions || plugin.evaluators || plugin.description);
46108
+ }
46109
+ function validatePlugin(plugin) {
46110
+ const errors = [];
46111
+ if (!plugin) {
46112
+ errors.push("Plugin is null or undefined");
46113
+ return { isValid: false, errors };
46114
+ }
46115
+ const pluginObj = plugin;
46116
+ if (!pluginObj.name) {
46117
+ errors.push("Plugin must have a name");
46118
+ }
46119
+ if (pluginObj.actions) {
46120
+ if (!Array.isArray(pluginObj.actions)) {
46121
+ errors.push("Plugin actions must be an array");
46122
+ } else {
46123
+ const invalidActions = pluginObj.actions.filter((a) => typeof a !== "object" || !a);
46124
+ if (invalidActions.length > 0) {
46125
+ errors.push("Plugin actions must be an array of action objects");
46126
+ }
46127
+ }
46128
+ }
46129
+ if (pluginObj.services) {
46130
+ if (!Array.isArray(pluginObj.services)) {
46131
+ errors.push("Plugin services must be an array");
46132
+ } else {
46133
+ const invalidServices = pluginObj.services.filter((s) => typeof s !== "function" && (typeof s !== "object" || !s));
46134
+ if (invalidServices.length > 0) {
46135
+ errors.push("Plugin services must be an array of service classes or objects");
46136
+ }
46137
+ }
46138
+ }
46139
+ if (pluginObj.providers && !Array.isArray(pluginObj.providers)) {
46140
+ errors.push("Plugin providers must be an array");
46141
+ }
46142
+ if (pluginObj.evaluators && !Array.isArray(pluginObj.evaluators)) {
46143
+ errors.push("Plugin evaluators must be an array");
46144
+ }
46145
+ return {
46146
+ isValid: errors.length === 0,
46147
+ errors
46148
+ };
46149
+ }
46150
+ async function loadAndPreparePlugin(pluginName) {
46151
+ try {
46152
+ let pluginModule;
46153
+ try {
46154
+ pluginModule = await import(pluginName);
46155
+ } catch (error) {
46156
+ logger.warn(`Failed to load plugin ${pluginName}: ${error}`);
46157
+ const attempted = await tryInstallPlugin(pluginName);
46158
+ if (!attempted) {
46159
+ return null;
46160
+ }
46161
+ try {
46162
+ pluginModule = await import(pluginName);
46163
+ } catch (secondError) {
46164
+ logger.error(`Auto-install attempted for ${pluginName} but import still failed: ${secondError}`);
46165
+ return null;
46166
+ }
46167
+ }
46168
+ if (!pluginModule) {
46169
+ logger.error(`Failed to load module for plugin ${pluginName}.`);
46170
+ return null;
46171
+ }
46172
+ const expectedFunctionName = `${pluginName.replace(/^@elizaos\/plugin-/, "").replace(/^@elizaos\//, "").replace(/-./g, (match) => match[1].toUpperCase())}Plugin`;
46173
+ const moduleObj = pluginModule;
46174
+ const exportsToCheck = [
46175
+ moduleObj[expectedFunctionName],
46176
+ moduleObj.default,
46177
+ ...Object.values(moduleObj)
46178
+ ];
46179
+ for (const potentialPlugin of exportsToCheck) {
46180
+ if (isValidPluginShape(potentialPlugin)) {
46181
+ return potentialPlugin;
46182
+ }
46183
+ if (typeof potentialPlugin === "function" && potentialPlugin.length === 0) {
46184
+ try {
46185
+ const produced = potentialPlugin();
46186
+ if (isValidPluginShape(produced)) {
46187
+ return produced;
46188
+ }
46189
+ } catch (err) {
46190
+ logger.debug(`Factory export threw for ${pluginName}: ${err}`);
46191
+ }
46192
+ }
46193
+ }
46194
+ logger.warn(`Could not find a valid plugin export in ${pluginName}.`);
46195
+ return null;
46196
+ } catch (error) {
46197
+ logger.error(`Error loading plugin ${pluginName}: ${error}`);
46198
+ return null;
46199
+ }
46200
+ }
46201
+ function resolvePluginDependencies(availablePlugins, isTestMode = false) {
46202
+ const resolutionOrder = [];
46203
+ const visited = new Set;
46204
+ const visiting = new Set;
46205
+ function visit(pluginName) {
46206
+ if (!availablePlugins.has(pluginName)) {
46207
+ logger.warn(`Plugin dependency "${pluginName}" not found and will be skipped.`);
46208
+ return;
46209
+ }
46210
+ if (visited.has(pluginName))
46211
+ return;
46212
+ if (visiting.has(pluginName)) {
46213
+ logger.error(`Circular dependency detected involving plugin: ${pluginName}`);
46214
+ return;
46215
+ }
46216
+ visiting.add(pluginName);
46217
+ const plugin = availablePlugins.get(pluginName);
46218
+ if (plugin) {
46219
+ const deps = [...plugin.dependencies || []];
46220
+ if (isTestMode) {
46221
+ deps.push(...plugin.testDependencies || []);
46222
+ }
46223
+ for (const dep of deps) {
46224
+ visit(dep);
46225
+ }
46226
+ }
46227
+ visiting.delete(pluginName);
46228
+ visited.add(pluginName);
46229
+ resolutionOrder.push(pluginName);
46230
+ }
46231
+ for (const name of availablePlugins.keys()) {
46232
+ if (!visited.has(name)) {
46233
+ visit(name);
46234
+ }
46235
+ }
46236
+ const finalPlugins = resolutionOrder.map((name) => availablePlugins.get(name)).filter((p) => Boolean(p));
46237
+ logger.info({ plugins: finalPlugins.map((p) => p.name) }, `Final plugins being loaded:`);
46238
+ return finalPlugins;
46239
+ }
46240
+ async function loadPlugin(nameOrPlugin) {
46241
+ if (typeof nameOrPlugin === "string") {
46242
+ return loadAndPreparePlugin(nameOrPlugin);
46243
+ }
46244
+ const validation = validatePlugin(nameOrPlugin);
46245
+ if (!validation.isValid) {
46246
+ logger.error(`Invalid plugin provided: ${validation.errors.join(", ")}`);
46247
+ return null;
46248
+ }
46249
+ return nameOrPlugin;
46250
+ }
46251
+ async function resolvePluginsImpl(plugins, isTestMode = false) {
46252
+ const pluginMap = new Map;
46253
+ const queue2 = [...plugins];
46254
+ while (queue2.length > 0) {
46255
+ const next = queue2.shift();
46256
+ const loaded = await loadPlugin(next);
46257
+ if (!loaded)
46258
+ continue;
46259
+ if (!pluginMap.has(loaded.name)) {
46260
+ pluginMap.set(loaded.name, loaded);
46261
+ for (const depName of loaded.dependencies ?? []) {
46262
+ if (!pluginMap.has(depName)) {
46263
+ queue2.push(depName);
46264
+ }
46265
+ }
46266
+ if (isTestMode) {
46267
+ for (const depName of loaded.testDependencies ?? []) {
46268
+ if (!pluginMap.has(depName)) {
46269
+ queue2.push(depName);
46270
+ }
46271
+ }
46272
+ }
46273
+ }
46274
+ }
46275
+ return resolvePluginDependencies(pluginMap, isTestMode);
46276
+ }
46277
+ async function resolvePlugins(plugins, isTestMode = false) {
46278
+ const env2 = detectEnvironment();
46279
+ if (env2 === "node") {
46280
+ return resolvePluginsImpl(plugins, isTestMode);
46281
+ }
46282
+ const pluginObjects = plugins.filter((p) => typeof p !== "string");
46283
+ if (plugins.some((p) => typeof p === "string")) {
46284
+ 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(", "));
46285
+ }
46286
+ const pluginMap = new Map;
46287
+ for (const plugin of pluginObjects) {
46288
+ pluginMap.set(plugin.name, plugin);
46289
+ }
46290
+ return resolvePluginDependencies(pluginMap, isTestMode);
46291
+ }
46292
+
45848
46293
  // src/elizaos.ts
45849
46294
  class ElizaOS extends EventTarget {
45850
46295
  runtimes = new Map;
46296
+ initFunctions = new Map;
45851
46297
  editableMode = false;
45852
- async addAgents(agents) {
46298
+ async addAgents(agents, options) {
45853
46299
  const promises = agents.map(async (agent) => {
46300
+ const character = agent.character;
46301
+ if (!hasCharacterSecrets(character)) {
46302
+ await setDefaultSecretsFromEnv(character);
46303
+ }
46304
+ const resolvedPlugins = agent.plugins ? await resolvePlugins(agent.plugins, options?.isTestMode || false) : [];
45854
46305
  const runtime = new AgentRuntime({
45855
- character: agent.character,
45856
- plugins: agent.plugins || [],
46306
+ character,
46307
+ plugins: resolvedPlugins,
45857
46308
  settings: agent.settings || {}
45858
46309
  });
45859
46310
  this.runtimes.set(runtime.agentId, runtime);
46311
+ if (typeof agent.init === "function") {
46312
+ this.initFunctions.set(runtime.agentId, agent.init);
46313
+ }
46314
+ const { settings, ...characterWithoutSecrets } = character;
46315
+ const { secrets, ...settingsWithoutSecrets } = settings || {};
45860
46316
  this.dispatchEvent(new CustomEvent("agent:added", {
45861
- detail: { agentId: runtime.agentId, character: agent.character }
46317
+ detail: {
46318
+ agentId: runtime.agentId,
46319
+ character: {
46320
+ ...characterWithoutSecrets,
46321
+ settings: settingsWithoutSecrets
46322
+ }
46323
+ }
45862
46324
  }));
45863
46325
  return runtime.agentId;
45864
46326
  });
@@ -45894,6 +46356,7 @@ class ElizaOS extends EventTarget {
45894
46356
  await this.stopAgents(agentIds);
45895
46357
  for (const id of agentIds) {
45896
46358
  this.runtimes.delete(id);
46359
+ this.initFunctions.delete(id);
45897
46360
  }
45898
46361
  this.dispatchEvent(new CustomEvent("agents:deleted", {
45899
46362
  detail: { agentIds, count: agentIds.length }
@@ -45911,6 +46374,16 @@ class ElizaOS extends EventTarget {
45911
46374
  detail: { agentId: id }
45912
46375
  }));
45913
46376
  }));
46377
+ for (const id of ids) {
46378
+ const initFn = this.initFunctions.get(id);
46379
+ if (initFn) {
46380
+ const runtime = this.runtimes.get(id);
46381
+ if (runtime) {
46382
+ await initFn(runtime);
46383
+ this.initFunctions.delete(id);
46384
+ }
46385
+ }
46386
+ }
45914
46387
  this.dispatchEvent(new CustomEvent("agents:started", {
45915
46388
  detail: { agentIds: ids, count: ids.length }
45916
46389
  }));
@@ -46266,6 +46739,47 @@ Data: ${JSON.stringify(entity.metadata)}
46266
46739
  return entityStrings.join(`
46267
46740
  `);
46268
46741
  }
46742
+ // src/character.ts
46743
+ function parseCharacter(input) {
46744
+ if (typeof input === "string") {
46745
+ throw new Error(`Character path provided but must be loaded first: ${input}`);
46746
+ }
46747
+ if (typeof input === "object") {
46748
+ const validationResult = validateCharacter(input);
46749
+ if (!validationResult.success) {
46750
+ const errorDetails = validationResult.error?.issues ? validationResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ") : validationResult.error?.message || "Unknown validation error";
46751
+ throw new Error(`Character validation failed: ${errorDetails}`);
46752
+ }
46753
+ return validationResult.data;
46754
+ }
46755
+ throw new Error("Invalid character input format");
46756
+ }
46757
+ function validateCharacterConfig(character) {
46758
+ const validationResult = validateCharacter(character);
46759
+ if (validationResult.success) {
46760
+ return {
46761
+ isValid: true,
46762
+ errors: []
46763
+ };
46764
+ }
46765
+ const errors = validationResult.error?.issues ? validationResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`) : [validationResult.error?.message || "Unknown validation error"];
46766
+ return {
46767
+ isValid: false,
46768
+ errors
46769
+ };
46770
+ }
46771
+ function mergeCharacterDefaults(char) {
46772
+ const defaults = {
46773
+ settings: {},
46774
+ plugins: [],
46775
+ bio: []
46776
+ };
46777
+ return {
46778
+ ...defaults,
46779
+ ...char,
46780
+ name: char.name || "Unnamed Character"
46781
+ };
46782
+ }
46269
46783
 
46270
46784
  // src/index.node.ts
46271
46785
  var isBrowser4 = false;
@@ -46273,22 +46787,33 @@ var isNode3 = true;
46273
46787
  export {
46274
46788
  waitForServerReady,
46275
46789
  validateUuid,
46790
+ validatePlugin,
46791
+ validateCharacterConfig,
46276
46792
  validateCharacter,
46793
+ uuidSchema2 as uuidSchema,
46277
46794
  updateWorldSettings,
46278
46795
  unsaltWorldSettings,
46279
46796
  unsaltSettingValue,
46797
+ tryInstallPlugin,
46280
46798
  truncateToCompleteSentence,
46281
46799
  trimTokens,
46282
46800
  toString2 as toString,
46283
46801
  toHex,
46802
+ templateTypeSchema,
46803
+ styleSchema,
46284
46804
  stringToUuid,
46285
46805
  splitChunks,
46286
46806
  slice,
46287
46807
  shouldRespondTemplate,
46808
+ settingsSchema,
46288
46809
  setEnv,
46810
+ setDefaultSecretsFromEnv,
46811
+ secretsSchema,
46289
46812
  saltWorldSettings,
46290
46813
  saltSettingValue,
46291
46814
  safeReplacer,
46815
+ resolvePlugins,
46816
+ resolvePluginDependencies,
46292
46817
  resetPaths,
46293
46818
  recentLogs,
46294
46819
  randomBytes,
@@ -46297,13 +46822,22 @@ export {
46297
46822
  pingServer,
46298
46823
  parseKeyValueXml,
46299
46824
  parseJSONObjectFromText,
46825
+ parseCharacter,
46300
46826
  parseBooleanFromText2 as parseBooleanFromText,
46301
46827
  parseAndValidateCharacter,
46302
46828
  normalizeJsonString,
46303
46829
  multiStepSummaryTemplate,
46304
46830
  multiStepDecisionTemplate,
46305
46831
  messageHandlerTemplate,
46832
+ messageExampleSchema,
46833
+ mergeCharacterDefaults,
46834
+ mediaSchema,
46306
46835
  logger,
46836
+ loadPlugin,
46837
+ loadEnvConfig,
46838
+ loadAndPreparePlugin,
46839
+ knowledgeItemSchema,
46840
+ isValidPluginShape,
46307
46841
  isValidCharacter,
46308
46842
  isNode3 as isNode,
46309
46843
  isMessageMetadata,
@@ -46319,6 +46853,7 @@ export {
46319
46853
  initBrowserEnvironment,
46320
46854
  imageDescriptionTemplate,
46321
46855
  hasEnv,
46856
+ hasCharacterSecrets,
46322
46857
  getWorldSettings,
46323
46858
  getUserServerRole,
46324
46859
  getUploadsChannelsDir,
@@ -46349,12 +46884,14 @@ export {
46349
46884
  formatActions,
46350
46885
  formatActionNames,
46351
46886
  findWorldsForOwner,
46887
+ findEnvFile,
46352
46888
  findEntityByName,
46353
46889
  equals,
46354
46890
  encryptedCharacter,
46355
46891
  encryptStringValue,
46356
46892
  encryptObjectValues,
46357
46893
  elizaLogger,
46894
+ directoryItemSchema,
46358
46895
  detectEnvironment,
46359
46896
  defineService,
46360
46897
  decryptedCharacter,
@@ -46369,6 +46906,7 @@ export {
46369
46906
  createService,
46370
46907
  createMessageMemory,
46371
46908
  createLogger,
46909
+ contentSchema,
46372
46910
  concat2 as concat,
46373
46911
  composePromptFromState,
46374
46912
  composePrompt,
@@ -46406,5 +46944,5 @@ export {
46406
46944
  AgentRuntime
46407
46945
  };
46408
46946
 
46409
- //# debugId=35E0E0299134B2DE64756E2164756E21
46947
+ //# debugId=4E1D16D9C214CAAC64756E2164756E21
46410
46948
  //# sourceMappingURL=index.node.js.map