@elizaos/core 1.0.0-alpha.1 → 1.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
1
4
  // src/types.ts
2
5
  var GoalStatus = /* @__PURE__ */ ((GoalStatus2) => {
3
6
  GoalStatus2["DONE"] = "DONE";
@@ -59,6 +62,9 @@ var ChannelType = /* @__PURE__ */ ((ChannelType2) => {
59
62
  return ChannelType2;
60
63
  })(ChannelType || {});
61
64
  var Service = class {
65
+ static {
66
+ __name(this, "Service");
67
+ }
62
68
  /** Runtime instance */
63
69
  runtime;
64
70
  constructor(runtime) {
@@ -89,6 +95,9 @@ var CacheKeyPrefix = /* @__PURE__ */ ((CacheKeyPrefix2) => {
89
95
  return CacheKeyPrefix2;
90
96
  })(CacheKeyPrefix || {});
91
97
  var TeeLogDAO = class {
98
+ static {
99
+ __name(this, "TeeLogDAO");
100
+ }
92
101
  db;
93
102
  };
94
103
  var TEEMode = /* @__PURE__ */ ((TEEMode2) => {
@@ -112,7 +121,7 @@ var Role = /* @__PURE__ */ ((Role2) => {
112
121
 
113
122
  // src/actions.ts
114
123
  import { names, uniqueNamesGenerator } from "unique-names-generator";
115
- var composeActionExamples = (actionsData, count) => {
124
+ var composeActionExamples = /* @__PURE__ */ __name((actionsData, count) => {
116
125
  const data = actionsData.map((action) => [
117
126
  ...action.examples
118
127
  ]);
@@ -150,16 +159,21 @@ ${example.map((message) => {
150
159
  }).join("\n")}`;
151
160
  });
152
161
  return formattedExamples.join("\n");
153
- };
162
+ }, "composeActionExamples");
154
163
  function formatActionNames(actions) {
155
164
  return actions.sort(() => 0.5 - Math.random()).map((action) => `${action.name}`).join(", ");
156
165
  }
166
+ __name(formatActionNames, "formatActionNames");
157
167
  function formatActions(actions) {
158
168
  return actions.sort(() => 0.5 - Math.random()).map((action) => `${action.name}: ${action.description}`).join(",\n");
159
169
  }
170
+ __name(formatActions, "formatActions");
160
171
 
161
172
  // src/database.ts
162
173
  var DatabaseAdapter = class {
174
+ static {
175
+ __name(this, "DatabaseAdapter");
176
+ }
163
177
  /**
164
178
  * The database instance.
165
179
  */
@@ -175,13 +189,26 @@ import { names as names2, uniqueNamesGenerator as uniqueNamesGenerator2 } from "
175
189
  import pino from "pino";
176
190
  import pretty from "pino-pretty";
177
191
  var InMemoryDestination = class {
192
+ static {
193
+ __name(this, "InMemoryDestination");
194
+ }
178
195
  logs = [];
179
196
  maxLogs = 1e3;
180
197
  // Keep last 1000 logs
181
198
  stream;
199
+ /**
200
+ * Constructor for creating a new instance of the class.
201
+ * @param {DestinationStream|null} stream - The stream to assign to the instance. Can be null.
202
+ */
182
203
  constructor(stream2) {
183
204
  this.stream = stream2;
184
205
  }
206
+ /**
207
+ * Writes a log entry to the memory buffer and forwards it to the pretty print stream if available.
208
+ *
209
+ * @param {string | LogEntry} data - The data to be written, which can be either a string or a LogEntry object.
210
+ * @returns {void}
211
+ */
185
212
  write(data) {
186
213
  const logEntry = typeof data === "string" ? JSON.parse(data) : data;
187
214
  if (!logEntry.time) {
@@ -196,6 +223,11 @@ var InMemoryDestination = class {
196
223
  this.stream.write(stringData);
197
224
  }
198
225
  }
226
+ /**
227
+ * Retrieves the recent logs from the system.
228
+ *
229
+ * @returns {LogEntry[]} An array of LogEntry objects representing the recent logs.
230
+ */
199
231
  recentLogs() {
200
232
  return this.logs;
201
233
  }
@@ -212,7 +244,7 @@ var customLevels = {
212
244
  trace: 10
213
245
  };
214
246
  var raw = parseBooleanFromText(process?.env?.LOG_JSON_FORMAT) || false;
215
- var createStream = () => {
247
+ var createStream = /* @__PURE__ */ __name(() => {
216
248
  if (raw) {
217
249
  return void 0;
218
250
  }
@@ -221,7 +253,7 @@ var createStream = () => {
221
253
  translateTime: "yyyy-mm-dd HH:MM:ss",
222
254
  ignore: "pid,hostname"
223
255
  });
224
- };
256
+ }, "createStream");
225
257
  var defaultLevel = process?.env?.DEFAULT_LOG_LEVEL || process?.env?.LOG_LEVEL || "info";
226
258
  var options = {
227
259
  level: defaultLevel,
@@ -258,7 +290,7 @@ var elizaLogger = logger;
258
290
  var logger_default = logger;
259
291
 
260
292
  // src/prompts.ts
261
- var composePrompt = ({
293
+ var composePrompt = /* @__PURE__ */ __name(({
262
294
  state,
263
295
  template
264
296
  }) => {
@@ -266,24 +298,24 @@ var composePrompt = ({
266
298
  const templateFunction = handlebars.compile(templateStr);
267
299
  const output = composeRandomUser(templateFunction(state.values), 10);
268
300
  return output;
269
- };
270
- var addHeader = (header, body) => {
301
+ }, "composePrompt");
302
+ var addHeader = /* @__PURE__ */ __name((header, body) => {
271
303
  return body.length > 0 ? `${header ? `${header}
272
304
  ` : header}${body}
273
305
  ` : "";
274
- };
275
- var composeRandomUser = (template, length) => {
306
+ }, "addHeader");
307
+ var composeRandomUser = /* @__PURE__ */ __name((template, length) => {
276
308
  const exampleNames = Array.from(
277
309
  { length },
278
310
  () => uniqueNamesGenerator2({ dictionaries: [names2] })
279
311
  );
280
312
  let result = template;
281
313
  for (let i = 0; i < exampleNames.length; i++) {
282
- result = result.replaceAll(`{{user${i + 1}}}`, exampleNames[i]);
314
+ result = result.replaceAll(`{{name${i + 1}}}`, exampleNames[i]);
283
315
  }
284
316
  return result;
285
- };
286
- var formatPosts = ({
317
+ }, "composeRandomUser");
318
+ var formatPosts = /* @__PURE__ */ __name(({
287
319
  messages,
288
320
  entities,
289
321
  conversationHeader = true
@@ -322,8 +354,8 @@ ${message.content.text}`;
322
354
  return `${header}${messageStrings.join("\n\n")}`;
323
355
  });
324
356
  return formattedPosts.join("\n\n");
325
- };
326
- var formatMessages = ({
357
+ }, "formatPosts");
358
+ var formatMessages = /* @__PURE__ */ __name(({
327
359
  messages,
328
360
  entities
329
361
  }) => {
@@ -358,8 +390,8 @@ var formatMessages = ({
358
390
  return messageString;
359
391
  }).join("\n");
360
392
  return messageStrings;
361
- };
362
- var formatTimestamp = (messageDate) => {
393
+ }, "formatMessages");
394
+ var formatTimestamp = /* @__PURE__ */ __name((messageDate) => {
363
395
  const now = /* @__PURE__ */ new Date();
364
396
  const diff = now.getTime() - messageDate;
365
397
  const absDiff = Math.abs(diff);
@@ -377,7 +409,7 @@ var formatTimestamp = (messageDate) => {
377
409
  return `${hours} hour${hours !== 1 ? "s" : ""} ago`;
378
410
  }
379
411
  return `${days} day${days !== 1 ? "s" : ""} ago`;
380
- };
412
+ }, "formatTimestamp");
381
413
  var jsonBlockPattern = /```json\n([\s\S]*?)\n```/;
382
414
  var shouldRespondTemplate = `# Task: Decide on behalf of {{agentName}} whether they should respond to the message, ignore it or stop the conversation.
383
415
  {{providers}}
@@ -390,6 +422,7 @@ Response format should be formatted in a valid JSON block like this:
390
422
  \`\`\`json
391
423
  {
392
424
  "name": "{{agentName}}",
425
+ "reasoning": "<string>",
393
426
  "action": "RESPOND" | "IGNORE" | "STOP",
394
427
  "providers": ["<string>", "<string>", ...]
395
428
  }
@@ -431,6 +464,7 @@ function parseBooleanFromText(value) {
431
464
  }
432
465
  return false;
433
466
  }
467
+ __name(parseBooleanFromText, "parseBooleanFromText");
434
468
  var stringArrayFooter = `Respond with a JSON array containing the values in a valid JSON block formatted for markdown with this structure:
435
469
  \`\`\`json
436
470
  [
@@ -474,6 +508,7 @@ function parseJsonArrayFromText(text) {
474
508
  }
475
509
  return null;
476
510
  }
511
+ __name(parseJsonArrayFromText, "parseJsonArrayFromText");
477
512
  function parseJSONObjectFromText(text) {
478
513
  let jsonData = null;
479
514
  const jsonBlockMatch = text.match(jsonBlockPattern);
@@ -493,6 +528,7 @@ function parseJSONObjectFromText(text) {
493
528
  logger_default.warn("Could not parse text as JSON, returning null");
494
529
  return null;
495
530
  }
531
+ __name(parseJSONObjectFromText, "parseJSONObjectFromText");
496
532
  function extractAttributes(response, attributesToExtract) {
497
533
  const attributes = {};
498
534
  if (!attributesToExtract || attributesToExtract.length === 0) {
@@ -512,7 +548,8 @@ function extractAttributes(response, attributesToExtract) {
512
548
  }
513
549
  return attributes;
514
550
  }
515
- var normalizeJsonString = (str) => {
551
+ __name(extractAttributes, "extractAttributes");
552
+ var normalizeJsonString = /* @__PURE__ */ __name((str) => {
516
553
  str = str.replace(/\{\s+/, "{").replace(/\s+\}/, "}").trim();
517
554
  str = str.replace(
518
555
  /("[\w\d_-]+")\s*: \s*(?!"|\[)([\s\S]+?)(?=(,\s*"|\}$))/g,
@@ -525,12 +562,13 @@ var normalizeJsonString = (str) => {
525
562
  str = str.replace(/("[\w\d_-]+")\s*:\s*([A-Za-z_]+)(?!["\w])/g, '$1: "$2"');
526
563
  str = str.replace(/(?:"')|(?:'")/g, '"');
527
564
  return str;
528
- };
565
+ }, "normalizeJsonString");
529
566
  function cleanJsonResponse(response) {
530
567
  return response.replace(/```json\s*/g, "").replace(/```\s*/g, "").replace(/(\r\n|\n|\r)/g, "").trim();
531
568
  }
569
+ __name(cleanJsonResponse, "cleanJsonResponse");
532
570
  var postActionResponseFooter = "Choose any combination of [LIKE], [RETWEET], [QUOTE], and [REPLY] that are appropriate. Each action must be on its own line. Your response must only include the chosen actions.";
533
- var parseActionResponseFromText = (text) => {
571
+ var parseActionResponseFromText = /* @__PURE__ */ __name((text) => {
534
572
  const actions = {
535
573
  like: false,
536
574
  retweet: false,
@@ -554,7 +592,7 @@ var parseActionResponseFromText = (text) => {
554
592
  if (trimmed === "[REPLY]") actions.reply = true;
555
593
  }
556
594
  return { actions };
557
- };
595
+ }, "parseActionResponseFromText");
558
596
  function truncateToCompleteSentence(text, maxLength) {
559
597
  if (text.length <= maxLength) {
560
598
  return text;
@@ -576,6 +614,7 @@ function truncateToCompleteSentence(text, maxLength) {
576
614
  const hardTruncated = text.slice(0, maxLength - 3).trim();
577
615
  return `${hardTruncated}...`;
578
616
  }
617
+ __name(truncateToCompleteSentence, "truncateToCompleteSentence");
579
618
  var TOKENS_PER_CHAR = 4;
580
619
  var TARGET_TOKENS = 3e3;
581
620
  var _TARGET_CHARS = Math.floor(TARGET_TOKENS / TOKENS_PER_CHAR);
@@ -592,6 +631,7 @@ async function splitChunks(content, chunkSize = 512, bleed = 20) {
592
631
  });
593
632
  return chunks;
594
633
  }
634
+ __name(splitChunks, "splitChunks");
595
635
  async function trimTokens(prompt, maxTokens, runtime) {
596
636
  if (!prompt) throw new Error("Trim tokens received a null prompt");
597
637
  if (prompt.length < maxTokens / 5) return prompt;
@@ -612,6 +652,7 @@ async function trimTokens(prompt, maxTokens, runtime) {
612
652
  return prompt.slice(-maxTokens * 4);
613
653
  }
614
654
  }
655
+ __name(trimTokens, "trimTokens");
615
656
 
616
657
  // src/entities.ts
617
658
  var entityResolutionTemplate = `# Task: Resolve Entity Name
@@ -678,6 +719,7 @@ async function getRecentInteractions(runtime, sourceEntityId, candidateEntities,
678
719
  }
679
720
  return results.sort((a, b) => b.count - a.count);
680
721
  }
722
+ __name(getRecentInteractions, "getRecentInteractions");
681
723
  async function findEntityByName(runtime, message, state) {
682
724
  try {
683
725
  const room = state.data.room ?? await runtime.getDatabaseAdapter().getRoom(message.roomId);
@@ -726,11 +768,14 @@ async function findEntityByName(runtime, message, state) {
726
768
  const prompt = composePrompt({
727
769
  state: {
728
770
  ...state,
729
- roomName: room.name || room.id,
730
- worldName: world?.name || "Unknown",
731
- entitiesInRoom: JSON.stringify(filteredEntities, null, 2),
732
- entityId: message.entityId,
733
- senderId: message.entityId
771
+ values: {
772
+ ...state.values,
773
+ roomName: room.name || room.id,
774
+ worldName: world?.name || "Unknown",
775
+ entitiesInRoom: JSON.stringify(filteredEntities, null, 2),
776
+ entityId: message.entityId,
777
+ senderId: message.entityId
778
+ }
734
779
  },
735
780
  template: entityResolutionTemplate
736
781
  });
@@ -789,13 +834,14 @@ async function findEntityByName(runtime, message, state) {
789
834
  return null;
790
835
  }
791
836
  }
792
- var createUniqueUuid = (runtime, baseUserId) => {
837
+ __name(findEntityByName, "findEntityByName");
838
+ var createUniqueUuid = /* @__PURE__ */ __name((runtime, baseUserId) => {
793
839
  if (baseUserId === runtime.agentId) {
794
840
  return runtime.agentId;
795
841
  }
796
842
  const combinedString = `${baseUserId}:${runtime.agentId}`;
797
843
  return stringToUuid(combinedString);
798
- };
844
+ }, "createUniqueUuid");
799
845
  async function getEntityDetails({
800
846
  runtime,
801
847
  roomId
@@ -832,11 +878,12 @@ async function getEntityDetails({
832
878
  }
833
879
  return Array.from(uniqueEntities.values());
834
880
  }
881
+ __name(getEntityDetails, "getEntityDetails");
835
882
 
836
883
  // src/environment.ts
837
- import { config } from "dotenv";
838
884
  import fs from "node:fs";
839
885
  import path from "node:path";
886
+ import { config } from "dotenv";
840
887
 
841
888
  // ../../node_modules/zod/lib/index.mjs
842
889
  var util;
@@ -844,10 +891,12 @@ var util;
844
891
  util2.assertEqual = (val) => val;
845
892
  function assertIs(_arg) {
846
893
  }
894
+ __name(assertIs, "assertIs");
847
895
  util2.assertIs = assertIs;
848
896
  function assertNever(_x) {
849
897
  throw new Error();
850
898
  }
899
+ __name(assertNever, "assertNever");
851
900
  util2.assertNever = assertNever;
852
901
  util2.arrayToEnum = (items) => {
853
902
  const obj = {};
@@ -889,6 +938,7 @@ var util;
889
938
  function joinValues(array, separator = " | ") {
890
939
  return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
891
940
  }
941
+ __name(joinValues, "joinValues");
892
942
  util2.joinValues = joinValues;
893
943
  util2.jsonStringifyReplacer = (_, value) => {
894
944
  if (typeof value === "bigint") {
@@ -929,7 +979,7 @@ var ZodParsedType = util.arrayToEnum([
929
979
  "map",
930
980
  "set"
931
981
  ]);
932
- var getParsedType = (data) => {
982
+ var getParsedType = /* @__PURE__ */ __name((data) => {
933
983
  const t = typeof data;
934
984
  switch (t) {
935
985
  case "undefined":
@@ -969,7 +1019,7 @@ var getParsedType = (data) => {
969
1019
  default:
970
1020
  return ZodParsedType.unknown;
971
1021
  }
972
- };
1022
+ }, "getParsedType");
973
1023
  var ZodIssueCode = util.arrayToEnum([
974
1024
  "invalid_type",
975
1025
  "invalid_literal",
@@ -988,11 +1038,14 @@ var ZodIssueCode = util.arrayToEnum([
988
1038
  "not_multiple_of",
989
1039
  "not_finite"
990
1040
  ]);
991
- var quotelessJson = (obj) => {
1041
+ var quotelessJson = /* @__PURE__ */ __name((obj) => {
992
1042
  const json = JSON.stringify(obj, null, 2);
993
1043
  return json.replace(/"([^"]+)":/g, "$1:");
994
- };
1044
+ }, "quotelessJson");
995
1045
  var ZodError = class _ZodError extends Error {
1046
+ static {
1047
+ __name(this, "ZodError");
1048
+ }
996
1049
  get errors() {
997
1050
  return this.issues;
998
1051
  }
@@ -1019,7 +1072,7 @@ var ZodError = class _ZodError extends Error {
1019
1072
  return issue.message;
1020
1073
  };
1021
1074
  const fieldErrors = { _errors: [] };
1022
- const processError = (error) => {
1075
+ const processError = /* @__PURE__ */ __name((error) => {
1023
1076
  for (const issue of error.issues) {
1024
1077
  if (issue.code === "invalid_union") {
1025
1078
  issue.unionErrors.map(processError);
@@ -1046,7 +1099,7 @@ var ZodError = class _ZodError extends Error {
1046
1099
  }
1047
1100
  }
1048
1101
  }
1049
- };
1102
+ }, "processError");
1050
1103
  processError(this);
1051
1104
  return fieldErrors;
1052
1105
  }
@@ -1085,7 +1138,7 @@ ZodError.create = (issues) => {
1085
1138
  const error = new ZodError(issues);
1086
1139
  return error;
1087
1140
  };
1088
- var errorMap = (issue, _ctx) => {
1141
+ var errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
1089
1142
  let message;
1090
1143
  switch (issue.code) {
1091
1144
  case ZodIssueCode.invalid_type:
@@ -1182,15 +1235,17 @@ var errorMap = (issue, _ctx) => {
1182
1235
  util.assertNever(issue);
1183
1236
  }
1184
1237
  return { message };
1185
- };
1238
+ }, "errorMap");
1186
1239
  var overrideErrorMap = errorMap;
1187
1240
  function setErrorMap(map) {
1188
1241
  overrideErrorMap = map;
1189
1242
  }
1243
+ __name(setErrorMap, "setErrorMap");
1190
1244
  function getErrorMap() {
1191
1245
  return overrideErrorMap;
1192
1246
  }
1193
- var makeIssue = (params) => {
1247
+ __name(getErrorMap, "getErrorMap");
1248
+ var makeIssue = /* @__PURE__ */ __name((params) => {
1194
1249
  const { data, path: path2, errorMaps, issueData } = params;
1195
1250
  const fullPath = [...path2, ...issueData.path || []];
1196
1251
  const fullIssue = {
@@ -1214,7 +1269,7 @@ var makeIssue = (params) => {
1214
1269
  path: fullPath,
1215
1270
  message: errorMessage
1216
1271
  };
1217
- };
1272
+ }, "makeIssue");
1218
1273
  var EMPTY_PATH = [];
1219
1274
  function addIssueToContext(ctx, issueData) {
1220
1275
  const overrideMap = getErrorMap();
@@ -1235,7 +1290,11 @@ function addIssueToContext(ctx, issueData) {
1235
1290
  });
1236
1291
  ctx.common.issues.push(issue);
1237
1292
  }
1293
+ __name(addIssueToContext, "addIssueToContext");
1238
1294
  var ParseStatus = class _ParseStatus {
1295
+ static {
1296
+ __name(this, "ParseStatus");
1297
+ }
1239
1298
  constructor() {
1240
1299
  this.value = "valid";
1241
1300
  }
@@ -1292,23 +1351,25 @@ var ParseStatus = class _ParseStatus {
1292
1351
  var INVALID = Object.freeze({
1293
1352
  status: "aborted"
1294
1353
  });
1295
- var DIRTY = (value) => ({ status: "dirty", value });
1296
- var OK = (value) => ({ status: "valid", value });
1297
- var isAborted = (x) => x.status === "aborted";
1298
- var isDirty = (x) => x.status === "dirty";
1299
- var isValid = (x) => x.status === "valid";
1300
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1354
+ var DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
1355
+ var OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
1356
+ var isAborted = /* @__PURE__ */ __name((x) => x.status === "aborted", "isAborted");
1357
+ var isDirty = /* @__PURE__ */ __name((x) => x.status === "dirty", "isDirty");
1358
+ var isValid = /* @__PURE__ */ __name((x) => x.status === "valid", "isValid");
1359
+ var isAsync = /* @__PURE__ */ __name((x) => typeof Promise !== "undefined" && x instanceof Promise, "isAsync");
1301
1360
  function __classPrivateFieldGet(receiver, state, kind, f) {
1302
1361
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1303
1362
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1304
1363
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1305
1364
  }
1365
+ __name(__classPrivateFieldGet, "__classPrivateFieldGet");
1306
1366
  function __classPrivateFieldSet(receiver, state, value, kind, f) {
1307
1367
  if (kind === "m") throw new TypeError("Private method is not writable");
1308
1368
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1309
1369
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1310
1370
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
1311
1371
  }
1372
+ __name(__classPrivateFieldSet, "__classPrivateFieldSet");
1312
1373
  var errorUtil;
1313
1374
  (function(errorUtil2) {
1314
1375
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
@@ -1317,6 +1378,9 @@ var errorUtil;
1317
1378
  var _ZodEnum_cache;
1318
1379
  var _ZodNativeEnum_cache;
1319
1380
  var ParseInputLazyPath = class {
1381
+ static {
1382
+ __name(this, "ParseInputLazyPath");
1383
+ }
1320
1384
  constructor(parent, value, path2, key) {
1321
1385
  this._cachedPath = [];
1322
1386
  this.parent = parent;
@@ -1335,7 +1399,7 @@ var ParseInputLazyPath = class {
1335
1399
  return this._cachedPath;
1336
1400
  }
1337
1401
  };
1338
- var handleResult = (ctx, result) => {
1402
+ var handleResult = /* @__PURE__ */ __name((ctx, result) => {
1339
1403
  if (isValid(result)) {
1340
1404
  return { success: true, data: result.value };
1341
1405
  } else {
@@ -1353,7 +1417,7 @@ var handleResult = (ctx, result) => {
1353
1417
  }
1354
1418
  };
1355
1419
  }
1356
- };
1420
+ }, "handleResult");
1357
1421
  function processCreateParams(params) {
1358
1422
  if (!params)
1359
1423
  return {};
@@ -1363,7 +1427,7 @@ function processCreateParams(params) {
1363
1427
  }
1364
1428
  if (errorMap2)
1365
1429
  return { errorMap: errorMap2, description };
1366
- const customMap = (iss, ctx) => {
1430
+ const customMap = /* @__PURE__ */ __name((iss, ctx) => {
1367
1431
  var _a, _b;
1368
1432
  const { message } = params;
1369
1433
  if (iss.code === "invalid_enum_value") {
@@ -1375,10 +1439,14 @@ function processCreateParams(params) {
1375
1439
  if (iss.code !== "invalid_type")
1376
1440
  return { message: ctx.defaultError };
1377
1441
  return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
1378
- };
1442
+ }, "customMap");
1379
1443
  return { errorMap: customMap, description };
1380
1444
  }
1445
+ __name(processCreateParams, "processCreateParams");
1381
1446
  var ZodType = class {
1447
+ static {
1448
+ __name(this, "ZodType");
1449
+ }
1382
1450
  get description() {
1383
1451
  return this._def.description;
1384
1452
  }
@@ -1503,7 +1571,7 @@ var ZodType = class {
1503
1571
  return handleResult(ctx, result);
1504
1572
  }
1505
1573
  refine(check, message) {
1506
- const getIssueProperties = (val) => {
1574
+ const getIssueProperties = /* @__PURE__ */ __name((val) => {
1507
1575
  if (typeof message === "string" || typeof message === "undefined") {
1508
1576
  return { message };
1509
1577
  } else if (typeof message === "function") {
@@ -1511,13 +1579,13 @@ var ZodType = class {
1511
1579
  } else {
1512
1580
  return message;
1513
1581
  }
1514
- };
1582
+ }, "getIssueProperties");
1515
1583
  return this._refinement((val, ctx) => {
1516
1584
  const result = check(val);
1517
- const setError = () => ctx.addIssue({
1585
+ const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
1518
1586
  code: ZodIssueCode.custom,
1519
1587
  ...getIssueProperties(val)
1520
- });
1588
+ }), "setError");
1521
1589
  if (typeof Promise !== "undefined" && result instanceof Promise) {
1522
1590
  return result.then((data) => {
1523
1591
  if (!data) {
@@ -1586,7 +1654,7 @@ var ZodType = class {
1586
1654
  this["~standard"] = {
1587
1655
  version: 1,
1588
1656
  vendor: "zod",
1589
- validate: (data) => this["~validate"](data)
1657
+ validate: /* @__PURE__ */ __name((data) => this["~validate"](data), "validate")
1590
1658
  };
1591
1659
  }
1592
1660
  optional() {
@@ -1690,9 +1758,11 @@ function timeRegexSource(args) {
1690
1758
  }
1691
1759
  return regex;
1692
1760
  }
1761
+ __name(timeRegexSource, "timeRegexSource");
1693
1762
  function timeRegex(args) {
1694
1763
  return new RegExp(`^${timeRegexSource(args)}$`);
1695
1764
  }
1765
+ __name(timeRegex, "timeRegex");
1696
1766
  function datetimeRegex(args) {
1697
1767
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1698
1768
  const opts = [];
@@ -1702,6 +1772,7 @@ function datetimeRegex(args) {
1702
1772
  regex = `${regex}(${opts.join("|")})`;
1703
1773
  return new RegExp(`^${regex}$`);
1704
1774
  }
1775
+ __name(datetimeRegex, "datetimeRegex");
1705
1776
  function isValidIP(ip, version) {
1706
1777
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1707
1778
  return true;
@@ -1711,6 +1782,7 @@ function isValidIP(ip, version) {
1711
1782
  }
1712
1783
  return false;
1713
1784
  }
1785
+ __name(isValidIP, "isValidIP");
1714
1786
  function isValidJWT(jwt, alg) {
1715
1787
  if (!jwtRegex.test(jwt))
1716
1788
  return false;
@@ -1729,6 +1801,7 @@ function isValidJWT(jwt, alg) {
1729
1801
  return false;
1730
1802
  }
1731
1803
  }
1804
+ __name(isValidJWT, "isValidJWT");
1732
1805
  function isValidCidr(ip, version) {
1733
1806
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1734
1807
  return true;
@@ -1738,7 +1811,11 @@ function isValidCidr(ip, version) {
1738
1811
  }
1739
1812
  return false;
1740
1813
  }
1814
+ __name(isValidCidr, "isValidCidr");
1741
1815
  var ZodString = class _ZodString extends ZodType {
1816
+ static {
1817
+ __name(this, "ZodString");
1818
+ }
1742
1819
  _parse(input) {
1743
1820
  if (this._def.coerce) {
1744
1821
  input.data = String(input.data);
@@ -2294,7 +2371,11 @@ function floatSafeRemainder(val, step) {
2294
2371
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
2295
2372
  return valInt % stepInt / Math.pow(10, decCount);
2296
2373
  }
2374
+ __name(floatSafeRemainder, "floatSafeRemainder");
2297
2375
  var ZodNumber = class _ZodNumber extends ZodType {
2376
+ static {
2377
+ __name(this, "ZodNumber");
2378
+ }
2298
2379
  constructor() {
2299
2380
  super(...arguments);
2300
2381
  this.min = this.gte;
@@ -2526,6 +2607,9 @@ ZodNumber.create = (params) => {
2526
2607
  });
2527
2608
  };
2528
2609
  var ZodBigInt = class _ZodBigInt extends ZodType {
2610
+ static {
2611
+ __name(this, "ZodBigInt");
2612
+ }
2529
2613
  constructor() {
2530
2614
  super(...arguments);
2531
2615
  this.min = this.gte;
@@ -2699,6 +2783,9 @@ ZodBigInt.create = (params) => {
2699
2783
  });
2700
2784
  };
2701
2785
  var ZodBoolean = class extends ZodType {
2786
+ static {
2787
+ __name(this, "ZodBoolean");
2788
+ }
2702
2789
  _parse(input) {
2703
2790
  if (this._def.coerce) {
2704
2791
  input.data = Boolean(input.data);
@@ -2724,6 +2811,9 @@ ZodBoolean.create = (params) => {
2724
2811
  });
2725
2812
  };
2726
2813
  var ZodDate = class _ZodDate extends ZodType {
2814
+ static {
2815
+ __name(this, "ZodDate");
2816
+ }
2727
2817
  _parse(input) {
2728
2818
  if (this._def.coerce) {
2729
2819
  input.data = new Date(input.data);
@@ -2833,6 +2923,9 @@ ZodDate.create = (params) => {
2833
2923
  });
2834
2924
  };
2835
2925
  var ZodSymbol = class extends ZodType {
2926
+ static {
2927
+ __name(this, "ZodSymbol");
2928
+ }
2836
2929
  _parse(input) {
2837
2930
  const parsedType = this._getType(input);
2838
2931
  if (parsedType !== ZodParsedType.symbol) {
@@ -2854,6 +2947,9 @@ ZodSymbol.create = (params) => {
2854
2947
  });
2855
2948
  };
2856
2949
  var ZodUndefined = class extends ZodType {
2950
+ static {
2951
+ __name(this, "ZodUndefined");
2952
+ }
2857
2953
  _parse(input) {
2858
2954
  const parsedType = this._getType(input);
2859
2955
  if (parsedType !== ZodParsedType.undefined) {
@@ -2875,6 +2971,9 @@ ZodUndefined.create = (params) => {
2875
2971
  });
2876
2972
  };
2877
2973
  var ZodNull = class extends ZodType {
2974
+ static {
2975
+ __name(this, "ZodNull");
2976
+ }
2878
2977
  _parse(input) {
2879
2978
  const parsedType = this._getType(input);
2880
2979
  if (parsedType !== ZodParsedType.null) {
@@ -2896,6 +2995,9 @@ ZodNull.create = (params) => {
2896
2995
  });
2897
2996
  };
2898
2997
  var ZodAny = class extends ZodType {
2998
+ static {
2999
+ __name(this, "ZodAny");
3000
+ }
2899
3001
  constructor() {
2900
3002
  super(...arguments);
2901
3003
  this._any = true;
@@ -2911,6 +3013,9 @@ ZodAny.create = (params) => {
2911
3013
  });
2912
3014
  };
2913
3015
  var ZodUnknown = class extends ZodType {
3016
+ static {
3017
+ __name(this, "ZodUnknown");
3018
+ }
2914
3019
  constructor() {
2915
3020
  super(...arguments);
2916
3021
  this._unknown = true;
@@ -2926,6 +3031,9 @@ ZodUnknown.create = (params) => {
2926
3031
  });
2927
3032
  };
2928
3033
  var ZodNever = class extends ZodType {
3034
+ static {
3035
+ __name(this, "ZodNever");
3036
+ }
2929
3037
  _parse(input) {
2930
3038
  const ctx = this._getOrReturnCtx(input);
2931
3039
  addIssueToContext(ctx, {
@@ -2943,6 +3051,9 @@ ZodNever.create = (params) => {
2943
3051
  });
2944
3052
  };
2945
3053
  var ZodVoid = class extends ZodType {
3054
+ static {
3055
+ __name(this, "ZodVoid");
3056
+ }
2946
3057
  _parse(input) {
2947
3058
  const parsedType = this._getType(input);
2948
3059
  if (parsedType !== ZodParsedType.undefined) {
@@ -2964,6 +3075,9 @@ ZodVoid.create = (params) => {
2964
3075
  });
2965
3076
  };
2966
3077
  var ZodArray = class _ZodArray extends ZodType {
3078
+ static {
3079
+ __name(this, "ZodArray");
3080
+ }
2967
3081
  _parse(input) {
2968
3082
  const { ctx, status } = this._processInputParams(input);
2969
3083
  const def = this._def;
@@ -3073,7 +3187,7 @@ function deepPartialify(schema) {
3073
3187
  }
3074
3188
  return new ZodObject({
3075
3189
  ...schema._def,
3076
- shape: () => newShape
3190
+ shape: /* @__PURE__ */ __name(() => newShape, "shape")
3077
3191
  });
3078
3192
  } else if (schema instanceof ZodArray) {
3079
3193
  return new ZodArray({
@@ -3090,7 +3204,11 @@ function deepPartialify(schema) {
3090
3204
  return schema;
3091
3205
  }
3092
3206
  }
3207
+ __name(deepPartialify, "deepPartialify");
3093
3208
  var ZodObject = class _ZodObject extends ZodType {
3209
+ static {
3210
+ __name(this, "ZodObject");
3211
+ }
3094
3212
  constructor() {
3095
3213
  super(...arguments);
3096
3214
  this._cached = null;
@@ -3199,7 +3317,7 @@ var ZodObject = class _ZodObject extends ZodType {
3199
3317
  ...this._def,
3200
3318
  unknownKeys: "strict",
3201
3319
  ...message !== void 0 ? {
3202
- errorMap: (issue, ctx) => {
3320
+ errorMap: /* @__PURE__ */ __name((issue, ctx) => {
3203
3321
  var _a, _b, _c, _d;
3204
3322
  const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
3205
3323
  if (issue.code === "unrecognized_keys")
@@ -3209,7 +3327,7 @@ var ZodObject = class _ZodObject extends ZodType {
3209
3327
  return {
3210
3328
  message: defaultError
3211
3329
  };
3212
- }
3330
+ }, "errorMap")
3213
3331
  } : {}
3214
3332
  });
3215
3333
  }
@@ -3245,10 +3363,10 @@ var ZodObject = class _ZodObject extends ZodType {
3245
3363
  extend(augmentation) {
3246
3364
  return new _ZodObject({
3247
3365
  ...this._def,
3248
- shape: () => ({
3366
+ shape: /* @__PURE__ */ __name(() => ({
3249
3367
  ...this._def.shape(),
3250
3368
  ...augmentation
3251
- })
3369
+ }), "shape")
3252
3370
  });
3253
3371
  }
3254
3372
  /**
@@ -3260,10 +3378,10 @@ var ZodObject = class _ZodObject extends ZodType {
3260
3378
  const merged = new _ZodObject({
3261
3379
  unknownKeys: merging._def.unknownKeys,
3262
3380
  catchall: merging._def.catchall,
3263
- shape: () => ({
3381
+ shape: /* @__PURE__ */ __name(() => ({
3264
3382
  ...this._def.shape(),
3265
3383
  ...merging._def.shape()
3266
- }),
3384
+ }), "shape"),
3267
3385
  typeName: ZodFirstPartyTypeKind.ZodObject
3268
3386
  });
3269
3387
  return merged;
@@ -3342,7 +3460,7 @@ var ZodObject = class _ZodObject extends ZodType {
3342
3460
  });
3343
3461
  return new _ZodObject({
3344
3462
  ...this._def,
3345
- shape: () => shape
3463
+ shape: /* @__PURE__ */ __name(() => shape, "shape")
3346
3464
  });
3347
3465
  }
3348
3466
  omit(mask) {
@@ -3354,7 +3472,7 @@ var ZodObject = class _ZodObject extends ZodType {
3354
3472
  });
3355
3473
  return new _ZodObject({
3356
3474
  ...this._def,
3357
- shape: () => shape
3475
+ shape: /* @__PURE__ */ __name(() => shape, "shape")
3358
3476
  });
3359
3477
  }
3360
3478
  /**
@@ -3375,7 +3493,7 @@ var ZodObject = class _ZodObject extends ZodType {
3375
3493
  });
3376
3494
  return new _ZodObject({
3377
3495
  ...this._def,
3378
- shape: () => newShape
3496
+ shape: /* @__PURE__ */ __name(() => newShape, "shape")
3379
3497
  });
3380
3498
  }
3381
3499
  required(mask) {
@@ -3394,7 +3512,7 @@ var ZodObject = class _ZodObject extends ZodType {
3394
3512
  });
3395
3513
  return new _ZodObject({
3396
3514
  ...this._def,
3397
- shape: () => newShape
3515
+ shape: /* @__PURE__ */ __name(() => newShape, "shape")
3398
3516
  });
3399
3517
  }
3400
3518
  keyof() {
@@ -3403,7 +3521,7 @@ var ZodObject = class _ZodObject extends ZodType {
3403
3521
  };
3404
3522
  ZodObject.create = (shape, params) => {
3405
3523
  return new ZodObject({
3406
- shape: () => shape,
3524
+ shape: /* @__PURE__ */ __name(() => shape, "shape"),
3407
3525
  unknownKeys: "strip",
3408
3526
  catchall: ZodNever.create(),
3409
3527
  typeName: ZodFirstPartyTypeKind.ZodObject,
@@ -3412,7 +3530,7 @@ ZodObject.create = (shape, params) => {
3412
3530
  };
3413
3531
  ZodObject.strictCreate = (shape, params) => {
3414
3532
  return new ZodObject({
3415
- shape: () => shape,
3533
+ shape: /* @__PURE__ */ __name(() => shape, "shape"),
3416
3534
  unknownKeys: "strict",
3417
3535
  catchall: ZodNever.create(),
3418
3536
  typeName: ZodFirstPartyTypeKind.ZodObject,
@@ -3429,6 +3547,9 @@ ZodObject.lazycreate = (shape, params) => {
3429
3547
  });
3430
3548
  };
3431
3549
  var ZodUnion = class extends ZodType {
3550
+ static {
3551
+ __name(this, "ZodUnion");
3552
+ }
3432
3553
  _parse(input) {
3433
3554
  const { ctx } = this._processInputParams(input);
3434
3555
  const options2 = this._def.options;
@@ -3451,6 +3572,7 @@ var ZodUnion = class extends ZodType {
3451
3572
  });
3452
3573
  return INVALID;
3453
3574
  }
3575
+ __name(handleResults, "handleResults");
3454
3576
  if (ctx.common.async) {
3455
3577
  return Promise.all(options2.map(async (option) => {
3456
3578
  const childCtx = {
@@ -3519,7 +3641,7 @@ ZodUnion.create = (types, params) => {
3519
3641
  ...processCreateParams(params)
3520
3642
  });
3521
3643
  };
3522
- var getDiscriminator = (type) => {
3644
+ var getDiscriminator = /* @__PURE__ */ __name((type) => {
3523
3645
  if (type instanceof ZodLazy) {
3524
3646
  return getDiscriminator(type.schema);
3525
3647
  } else if (type instanceof ZodEffects) {
@@ -3549,8 +3671,11 @@ var getDiscriminator = (type) => {
3549
3671
  } else {
3550
3672
  return [];
3551
3673
  }
3552
- };
3674
+ }, "getDiscriminator");
3553
3675
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
3676
+ static {
3677
+ __name(this, "ZodDiscriminatedUnion");
3678
+ }
3554
3679
  _parse(input) {
3555
3680
  const { ctx } = this._processInputParams(input);
3556
3681
  if (ctx.parsedType !== ZodParsedType.object) {
@@ -3664,10 +3789,14 @@ function mergeValues(a, b) {
3664
3789
  return { valid: false };
3665
3790
  }
3666
3791
  }
3792
+ __name(mergeValues, "mergeValues");
3667
3793
  var ZodIntersection = class extends ZodType {
3794
+ static {
3795
+ __name(this, "ZodIntersection");
3796
+ }
3668
3797
  _parse(input) {
3669
3798
  const { status, ctx } = this._processInputParams(input);
3670
- const handleParsed = (parsedLeft, parsedRight) => {
3799
+ const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
3671
3800
  if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3672
3801
  return INVALID;
3673
3802
  }
@@ -3682,7 +3811,7 @@ var ZodIntersection = class extends ZodType {
3682
3811
  status.dirty();
3683
3812
  }
3684
3813
  return { status: status.value, value: merged.data };
3685
- };
3814
+ }, "handleParsed");
3686
3815
  if (ctx.common.async) {
3687
3816
  return Promise.all([
3688
3817
  this._def.left._parseAsync({
@@ -3718,6 +3847,9 @@ ZodIntersection.create = (left, right, params) => {
3718
3847
  });
3719
3848
  };
3720
3849
  var ZodTuple = class _ZodTuple extends ZodType {
3850
+ static {
3851
+ __name(this, "ZodTuple");
3852
+ }
3721
3853
  _parse(input) {
3722
3854
  const { status, ctx } = this._processInputParams(input);
3723
3855
  if (ctx.parsedType !== ZodParsedType.array) {
@@ -3785,6 +3917,9 @@ ZodTuple.create = (schemas, params) => {
3785
3917
  });
3786
3918
  };
3787
3919
  var ZodRecord = class _ZodRecord extends ZodType {
3920
+ static {
3921
+ __name(this, "ZodRecord");
3922
+ }
3788
3923
  get keySchema() {
3789
3924
  return this._def.keyType;
3790
3925
  }
@@ -3838,6 +3973,9 @@ var ZodRecord = class _ZodRecord extends ZodType {
3838
3973
  }
3839
3974
  };
3840
3975
  var ZodMap = class extends ZodType {
3976
+ static {
3977
+ __name(this, "ZodMap");
3978
+ }
3841
3979
  get keySchema() {
3842
3980
  return this._def.keyType;
3843
3981
  }
@@ -3904,6 +4042,9 @@ ZodMap.create = (keyType, valueType, params) => {
3904
4042
  });
3905
4043
  };
3906
4044
  var ZodSet = class _ZodSet extends ZodType {
4045
+ static {
4046
+ __name(this, "ZodSet");
4047
+ }
3907
4048
  _parse(input) {
3908
4049
  const { status, ctx } = this._processInputParams(input);
3909
4050
  if (ctx.parsedType !== ZodParsedType.set) {
@@ -3953,6 +4094,7 @@ var ZodSet = class _ZodSet extends ZodType {
3953
4094
  }
3954
4095
  return { status: status.value, value: parsedSet };
3955
4096
  }
4097
+ __name(finalizeSet, "finalizeSet");
3956
4098
  const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3957
4099
  if (ctx.common.async) {
3958
4100
  return Promise.all(elements).then((elements2) => finalizeSet(elements2));
@@ -3989,6 +4131,9 @@ ZodSet.create = (valueType, params) => {
3989
4131
  });
3990
4132
  };
3991
4133
  var ZodFunction = class _ZodFunction extends ZodType {
4134
+ static {
4135
+ __name(this, "ZodFunction");
4136
+ }
3992
4137
  constructor() {
3993
4138
  super(...arguments);
3994
4139
  this.validate = this.implement;
@@ -4019,6 +4164,7 @@ var ZodFunction = class _ZodFunction extends ZodType {
4019
4164
  }
4020
4165
  });
4021
4166
  }
4167
+ __name(makeArgsIssue, "makeArgsIssue");
4022
4168
  function makeReturnsIssue(returns, error) {
4023
4169
  return makeIssue({
4024
4170
  data: returns,
@@ -4035,6 +4181,7 @@ var ZodFunction = class _ZodFunction extends ZodType {
4035
4181
  }
4036
4182
  });
4037
4183
  }
4184
+ __name(makeReturnsIssue, "makeReturnsIssue");
4038
4185
  const params = { errorMap: ctx.common.contextualErrorMap };
4039
4186
  const fn = ctx.data;
4040
4187
  if (this._def.returns instanceof ZodPromise) {
@@ -4104,6 +4251,9 @@ var ZodFunction = class _ZodFunction extends ZodType {
4104
4251
  }
4105
4252
  };
4106
4253
  var ZodLazy = class extends ZodType {
4254
+ static {
4255
+ __name(this, "ZodLazy");
4256
+ }
4107
4257
  get schema() {
4108
4258
  return this._def.getter();
4109
4259
  }
@@ -4121,6 +4271,9 @@ ZodLazy.create = (getter, params) => {
4121
4271
  });
4122
4272
  };
4123
4273
  var ZodLiteral = class extends ZodType {
4274
+ static {
4275
+ __name(this, "ZodLiteral");
4276
+ }
4124
4277
  _parse(input) {
4125
4278
  if (input.data !== this._def.value) {
4126
4279
  const ctx = this._getOrReturnCtx(input);
@@ -4151,7 +4304,11 @@ function createZodEnum(values, params) {
4151
4304
  ...processCreateParams(params)
4152
4305
  });
4153
4306
  }
4307
+ __name(createZodEnum, "createZodEnum");
4154
4308
  var ZodEnum = class _ZodEnum extends ZodType {
4309
+ static {
4310
+ __name(this, "ZodEnum");
4311
+ }
4155
4312
  constructor() {
4156
4313
  super(...arguments);
4157
4314
  _ZodEnum_cache.set(this, void 0);
@@ -4222,6 +4379,9 @@ var ZodEnum = class _ZodEnum extends ZodType {
4222
4379
  _ZodEnum_cache = /* @__PURE__ */ new WeakMap();
4223
4380
  ZodEnum.create = createZodEnum;
4224
4381
  var ZodNativeEnum = class extends ZodType {
4382
+ static {
4383
+ __name(this, "ZodNativeEnum");
4384
+ }
4225
4385
  constructor() {
4226
4386
  super(...arguments);
4227
4387
  _ZodNativeEnum_cache.set(this, void 0);
@@ -4265,6 +4425,9 @@ ZodNativeEnum.create = (values, params) => {
4265
4425
  });
4266
4426
  };
4267
4427
  var ZodPromise = class extends ZodType {
4428
+ static {
4429
+ __name(this, "ZodPromise");
4430
+ }
4268
4431
  unwrap() {
4269
4432
  return this._def.type;
4270
4433
  }
@@ -4295,6 +4458,9 @@ ZodPromise.create = (schema, params) => {
4295
4458
  });
4296
4459
  };
4297
4460
  var ZodEffects = class extends ZodType {
4461
+ static {
4462
+ __name(this, "ZodEffects");
4463
+ }
4298
4464
  innerType() {
4299
4465
  return this._def.schema;
4300
4466
  }
@@ -4305,14 +4471,14 @@ var ZodEffects = class extends ZodType {
4305
4471
  const { status, ctx } = this._processInputParams(input);
4306
4472
  const effect = this._def.effect || null;
4307
4473
  const checkCtx = {
4308
- addIssue: (arg) => {
4474
+ addIssue: /* @__PURE__ */ __name((arg) => {
4309
4475
  addIssueToContext(ctx, arg);
4310
4476
  if (arg.fatal) {
4311
4477
  status.abort();
4312
4478
  } else {
4313
4479
  status.dirty();
4314
4480
  }
4315
- },
4481
+ }, "addIssue"),
4316
4482
  get path() {
4317
4483
  return ctx.path;
4318
4484
  }
@@ -4355,7 +4521,7 @@ var ZodEffects = class extends ZodType {
4355
4521
  }
4356
4522
  }
4357
4523
  if (effect.type === "refinement") {
4358
- const executeRefinement = (acc) => {
4524
+ const executeRefinement = /* @__PURE__ */ __name((acc) => {
4359
4525
  const result = effect.refinement(acc, checkCtx);
4360
4526
  if (ctx.common.async) {
4361
4527
  return Promise.resolve(result);
@@ -4364,7 +4530,7 @@ var ZodEffects = class extends ZodType {
4364
4530
  throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4365
4531
  }
4366
4532
  return acc;
4367
- };
4533
+ }, "executeRefinement");
4368
4534
  if (ctx.common.async === false) {
4369
4535
  const inner = this._def.schema._parseSync({
4370
4536
  data: ctx.data,
@@ -4431,6 +4597,9 @@ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4431
4597
  });
4432
4598
  };
4433
4599
  var ZodOptional = class extends ZodType {
4600
+ static {
4601
+ __name(this, "ZodOptional");
4602
+ }
4434
4603
  _parse(input) {
4435
4604
  const parsedType = this._getType(input);
4436
4605
  if (parsedType === ZodParsedType.undefined) {
@@ -4450,6 +4619,9 @@ ZodOptional.create = (type, params) => {
4450
4619
  });
4451
4620
  };
4452
4621
  var ZodNullable = class extends ZodType {
4622
+ static {
4623
+ __name(this, "ZodNullable");
4624
+ }
4453
4625
  _parse(input) {
4454
4626
  const parsedType = this._getType(input);
4455
4627
  if (parsedType === ZodParsedType.null) {
@@ -4469,6 +4641,9 @@ ZodNullable.create = (type, params) => {
4469
4641
  });
4470
4642
  };
4471
4643
  var ZodDefault = class extends ZodType {
4644
+ static {
4645
+ __name(this, "ZodDefault");
4646
+ }
4472
4647
  _parse(input) {
4473
4648
  const { ctx } = this._processInputParams(input);
4474
4649
  let data = ctx.data;
@@ -4494,6 +4669,9 @@ ZodDefault.create = (type, params) => {
4494
4669
  });
4495
4670
  };
4496
4671
  var ZodCatch = class extends ZodType {
4672
+ static {
4673
+ __name(this, "ZodCatch");
4674
+ }
4497
4675
  _parse(input) {
4498
4676
  const { ctx } = this._processInputParams(input);
4499
4677
  const newCtx = {
@@ -4547,6 +4725,9 @@ ZodCatch.create = (type, params) => {
4547
4725
  });
4548
4726
  };
4549
4727
  var ZodNaN = class extends ZodType {
4728
+ static {
4729
+ __name(this, "ZodNaN");
4730
+ }
4550
4731
  _parse(input) {
4551
4732
  const parsedType = this._getType(input);
4552
4733
  if (parsedType !== ZodParsedType.nan) {
@@ -4569,6 +4750,9 @@ ZodNaN.create = (params) => {
4569
4750
  };
4570
4751
  var BRAND = Symbol("zod_brand");
4571
4752
  var ZodBranded = class extends ZodType {
4753
+ static {
4754
+ __name(this, "ZodBranded");
4755
+ }
4572
4756
  _parse(input) {
4573
4757
  const { ctx } = this._processInputParams(input);
4574
4758
  const data = ctx.data;
@@ -4583,10 +4767,13 @@ var ZodBranded = class extends ZodType {
4583
4767
  }
4584
4768
  };
4585
4769
  var ZodPipeline = class _ZodPipeline extends ZodType {
4770
+ static {
4771
+ __name(this, "ZodPipeline");
4772
+ }
4586
4773
  _parse(input) {
4587
4774
  const { status, ctx } = this._processInputParams(input);
4588
4775
  if (ctx.common.async) {
4589
- const handleAsync = async () => {
4776
+ const handleAsync = /* @__PURE__ */ __name(async () => {
4590
4777
  const inResult = await this._def.in._parseAsync({
4591
4778
  data: ctx.data,
4592
4779
  path: ctx.path,
@@ -4604,7 +4791,7 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
4604
4791
  parent: ctx
4605
4792
  });
4606
4793
  }
4607
- };
4794
+ }, "handleAsync");
4608
4795
  return handleAsync();
4609
4796
  } else {
4610
4797
  const inResult = this._def.in._parseSync({
@@ -4638,14 +4825,17 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
4638
4825
  }
4639
4826
  };
4640
4827
  var ZodReadonly = class extends ZodType {
4828
+ static {
4829
+ __name(this, "ZodReadonly");
4830
+ }
4641
4831
  _parse(input) {
4642
4832
  const result = this._def.innerType._parse(input);
4643
- const freeze = (data) => {
4833
+ const freeze = /* @__PURE__ */ __name((data) => {
4644
4834
  if (isValid(data)) {
4645
4835
  data.value = Object.freeze(data.value);
4646
4836
  }
4647
4837
  return data;
4648
- };
4838
+ }, "freeze");
4649
4839
  return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4650
4840
  }
4651
4841
  unwrap() {
@@ -4672,6 +4862,7 @@ function custom(check, params = {}, fatal) {
4672
4862
  });
4673
4863
  return ZodAny.create();
4674
4864
  }
4865
+ __name(custom, "custom");
4675
4866
  var late = {
4676
4867
  object: ZodObject.lazycreate
4677
4868
  };
@@ -4714,9 +4905,9 @@ var ZodFirstPartyTypeKind;
4714
4905
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4715
4906
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4716
4907
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4717
- var instanceOfType = (cls, params = {
4908
+ var instanceOfType = /* @__PURE__ */ __name((cls, params = {
4718
4909
  message: `Input not instance of ${cls.name}`
4719
- }) => custom((data) => data instanceof cls, params);
4910
+ }) => custom((data) => data instanceof cls, params), "instanceOfType");
4720
4911
  var stringType = ZodString.create;
4721
4912
  var numberType = ZodNumber.create;
4722
4913
  var nanType = ZodNaN.create;
@@ -4751,18 +4942,18 @@ var optionalType = ZodOptional.create;
4751
4942
  var nullableType = ZodNullable.create;
4752
4943
  var preprocessType = ZodEffects.createWithPreprocess;
4753
4944
  var pipelineType = ZodPipeline.create;
4754
- var ostring = () => stringType().optional();
4755
- var onumber = () => numberType().optional();
4756
- var oboolean = () => booleanType().optional();
4945
+ var ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
4946
+ var onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
4947
+ var oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
4757
4948
  var coerce = {
4758
- string: (arg) => ZodString.create({ ...arg, coerce: true }),
4759
- number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4760
- boolean: (arg) => ZodBoolean.create({
4949
+ string: /* @__PURE__ */ __name((arg) => ZodString.create({ ...arg, coerce: true }), "string"),
4950
+ number: /* @__PURE__ */ __name((arg) => ZodNumber.create({ ...arg, coerce: true }), "number"),
4951
+ boolean: /* @__PURE__ */ __name((arg) => ZodBoolean.create({
4761
4952
  ...arg,
4762
4953
  coerce: true
4763
- }),
4764
- bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4765
- date: (arg) => ZodDate.create({ ...arg, coerce: true })
4954
+ }), "boolean"),
4955
+ bigint: /* @__PURE__ */ __name((arg) => ZodBigInt.create({ ...arg, coerce: true }), "bigint"),
4956
+ date: /* @__PURE__ */ __name((arg) => ZodDate.create({ ...arg, coerce: true }), "date")
4766
4957
  };
4767
4958
  var NEVER = INVALID;
4768
4959
  var z = /* @__PURE__ */ Object.freeze({
@@ -4884,9 +5075,9 @@ var z = /* @__PURE__ */ Object.freeze({
4884
5075
 
4885
5076
  // src/environment.ts
4886
5077
  var environmentSettings = {};
4887
- var isBrowser = () => {
5078
+ var isBrowser = /* @__PURE__ */ __name(() => {
4888
5079
  return typeof window !== "undefined" && typeof window.document !== "undefined";
4889
- };
5080
+ }, "isBrowser");
4890
5081
  function findNearestEnvFile(startDir = process.cwd()) {
4891
5082
  if (isBrowser()) return null;
4892
5083
  let currentDir = startDir;
@@ -4900,9 +5091,11 @@ function findNearestEnvFile(startDir = process.cwd()) {
4900
5091
  const rootEnvPath = path.join(path.parse(currentDir).root, ".env");
4901
5092
  return fs.existsSync(rootEnvPath) ? rootEnvPath : null;
4902
5093
  }
5094
+ __name(findNearestEnvFile, "findNearestEnvFile");
4903
5095
  function configureSettings(settings2) {
4904
5096
  environmentSettings = { ...settings2 };
4905
5097
  }
5098
+ __name(configureSettings, "configureSettings");
4906
5099
  function loadEnvConfig() {
4907
5100
  if (isBrowser()) {
4908
5101
  return environmentSettings;
@@ -4918,18 +5111,21 @@ function loadEnvConfig() {
4918
5111
  });
4919
5112
  return process.env;
4920
5113
  }
5114
+ __name(loadEnvConfig, "loadEnvConfig");
4921
5115
  function getEnvVariable(key, defaultValue) {
4922
5116
  if (isBrowser()) {
4923
5117
  return environmentSettings[key] || defaultValue;
4924
5118
  }
4925
5119
  return process.env[key] || defaultValue;
4926
5120
  }
5121
+ __name(getEnvVariable, "getEnvVariable");
4927
5122
  function hasEnvVariable(key) {
4928
5123
  if (isBrowser()) {
4929
5124
  return key in environmentSettings;
4930
5125
  }
4931
5126
  return key in process.env;
4932
5127
  }
5128
+ __name(hasEnvVariable, "hasEnvVariable");
4933
5129
  function parseNamespacedSettings(env) {
4934
5130
  const namespaced = {};
4935
5131
  for (const [key, value] of Object.entries(env)) {
@@ -4942,6 +5138,7 @@ function parseNamespacedSettings(env) {
4942
5138
  }
4943
5139
  return namespaced;
4944
5140
  }
5141
+ __name(parseNamespacedSettings, "parseNamespacedSettings");
4945
5142
  var settings = isBrowser() ? environmentSettings : loadEnvConfig();
4946
5143
  var MessageExampleSchema = z.object({
4947
5144
  name: z.string(),
@@ -5041,19 +5238,20 @@ function validateCharacterConfig(json) {
5041
5238
  throw error;
5042
5239
  }
5043
5240
  }
5241
+ __name(validateCharacterConfig, "validateCharacterConfig");
5044
5242
 
5045
5243
  // src/import.ts
5046
5244
  var registrations = /* @__PURE__ */ new Map();
5047
- var dynamicImport = async (specifier) => {
5245
+ var dynamicImport = /* @__PURE__ */ __name(async (specifier) => {
5048
5246
  const module = registrations.get(specifier);
5049
5247
  if (module !== void 0) {
5050
5248
  return module;
5051
5249
  }
5052
5250
  return await import(specifier);
5053
- };
5054
- var registerDynamicImport = (specifier, module) => {
5251
+ }, "dynamicImport");
5252
+ var registerDynamicImport = /* @__PURE__ */ __name((specifier, module) => {
5055
5253
  registrations.set(specifier, module);
5056
- };
5254
+ }, "registerDynamicImport");
5057
5255
  async function handlePluginImporting(plugins) {
5058
5256
  if (plugins.length > 0) {
5059
5257
  logger_default.debug("Imported are: ", plugins);
@@ -5073,11 +5271,15 @@ async function handlePluginImporting(plugins) {
5073
5271
  }
5074
5272
  return [];
5075
5273
  }
5274
+ __name(handlePluginImporting, "handlePluginImporting");
5076
5275
 
5077
5276
  // src/memory.ts
5078
5277
  var defaultMatchThreshold = 0.1;
5079
5278
  var defaultMatchCount = 10;
5080
5279
  var MemoryManager = class {
5280
+ static {
5281
+ __name(this, "MemoryManager");
5282
+ }
5081
5283
  /**
5082
5284
  * The AgentRuntime instance associated with this manager.
5083
5285
  */
@@ -5299,23 +5501,31 @@ var MemoryManager = class {
5299
5501
  // src/roles.ts
5300
5502
  async function getUserServerRole(runtime, entityId, serverId) {
5301
5503
  try {
5504
+ console.log("*** GET USER SERVER ROLE ***\n", entityId, serverId);
5302
5505
  const worldId = createUniqueUuid(runtime, serverId);
5506
+ console.log("*** WORLD ID ***\n", worldId);
5303
5507
  const world = await runtime.getDatabaseAdapter().getWorld(worldId);
5508
+ console.log("*** WORLD ***\n", world);
5304
5509
  if (!world || !world.metadata?.roles) {
5510
+ console.log("*** NO ROLES ***\n");
5305
5511
  return "NONE" /* NONE */;
5306
5512
  }
5307
- if (world.metadata.roles[entityId]?.role) {
5308
- return world.metadata.roles[entityId].role;
5513
+ if (world.metadata.roles[entityId]) {
5514
+ console.log("*** ROLE ***\n", world.metadata.roles[entityId]);
5515
+ return world.metadata.roles[entityId];
5309
5516
  }
5310
- if (world.metadata.roles[entityId]?.role) {
5311
- return world.metadata.roles[entityId].role;
5517
+ if (world.metadata.roles[entityId]) {
5518
+ console.log("*** ROLE ***\n", world.metadata.roles[entityId]);
5519
+ return world.metadata.roles[entityId];
5312
5520
  }
5521
+ console.log("WORLD METADATA IS", JSON.stringify(world.metadata, null, 2));
5313
5522
  return "NONE" /* NONE */;
5314
5523
  } catch (error) {
5315
5524
  logger.error(`Error getting user role: ${error}`);
5316
5525
  return "NONE" /* NONE */;
5317
5526
  }
5318
5527
  }
5528
+ __name(getUserServerRole, "getUserServerRole");
5319
5529
  async function findWorldForOwner(runtime, entityId) {
5320
5530
  try {
5321
5531
  if (!entityId) {
@@ -5339,6 +5549,7 @@ async function findWorldForOwner(runtime, entityId) {
5339
5549
  return null;
5340
5550
  }
5341
5551
  }
5552
+ __name(findWorldForOwner, "findWorldForOwner");
5342
5553
 
5343
5554
  // src/runtime.ts
5344
5555
  import { join } from "node:path";
@@ -5352,7 +5563,7 @@ var optionExtractionTemplate = `# Task: Extract selected task and option from us
5352
5563
 
5353
5564
  # Available Tasks:
5354
5565
  {{#each tasks}}
5355
- Task {{taskId}}: {{name}}
5566
+ Task ID: {{taskId}} - {{name}}
5356
5567
  Available options:
5357
5568
  {{#each options}}
5358
5569
  - {{name}}: {{description}}
@@ -5367,13 +5578,13 @@ Available options:
5367
5578
  # Instructions:
5368
5579
  1. Review the user's message and identify which task and option they are selecting
5369
5580
  2. Match against the available tasks and their options, including ABORT
5370
- 3. Return the task ID and selected option name exactly as listed above
5581
+ 3. Return the task ID (shortened UUID) and selected option name exactly as listed above
5371
5582
  4. If no clear selection is made, return null for both fields
5372
5583
 
5373
5584
  Return in JSON format:
5374
5585
  \`\`\`json
5375
5586
  {
5376
- "taskId": number | null,
5587
+ "taskId": "string" | null,
5377
5588
  "selectedOption": "OPTION_NAME" | null
5378
5589
  }
5379
5590
  \`\`\`
@@ -5383,7 +5594,7 @@ var choiceAction = {
5383
5594
  name: "CHOOSE_OPTION",
5384
5595
  similes: ["SELECT_OPTION", "SELECT", "PICK", "CHOOSE"],
5385
5596
  description: "Selects an option for a pending task that has multiple options",
5386
- validate: async (runtime, message, state) => {
5597
+ validate: /* @__PURE__ */ __name(async (runtime, message, state) => {
5387
5598
  const pendingTasks = await runtime.getDatabaseAdapter().getTasks({
5388
5599
  roomId: message.roomId,
5389
5600
  tags: ["AWAITING_CHOICE"]
@@ -5398,62 +5609,113 @@ var choiceAction = {
5398
5609
  return false;
5399
5610
  }
5400
5611
  return pendingTasks && pendingTasks.length > 0 && pendingTasks.some((task) => task.metadata?.options);
5401
- },
5402
- handler: async (runtime, message, state, _options, callback, responses) => {
5612
+ }, "validate"),
5613
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback, responses) => {
5403
5614
  try {
5404
- for (const response of responses) {
5405
- await callback(response.content);
5406
- }
5615
+ console.log("*** CHOICE HANDLER ***\n");
5616
+ console.log("*** MESSAGE ***\n", JSON.stringify(message, null, 2));
5407
5617
  const pendingTasks = await runtime.getDatabaseAdapter().getTasks({
5408
5618
  roomId: message.roomId,
5409
5619
  tags: ["AWAITING_CHOICE"]
5410
5620
  });
5621
+ console.log(
5622
+ "*** PENDING TASKS ***\n",
5623
+ JSON.stringify(pendingTasks, null, 2)
5624
+ );
5411
5625
  if (!pendingTasks?.length) {
5412
5626
  throw new Error("No pending tasks with options found");
5413
5627
  }
5414
5628
  const tasksWithOptions = pendingTasks.filter(
5415
5629
  (task) => task.metadata?.options
5416
5630
  );
5631
+ console.log(
5632
+ "*** TASKS WITH OPTIONS ***\n",
5633
+ JSON.stringify(tasksWithOptions, null, 2)
5634
+ );
5417
5635
  if (!tasksWithOptions.length) {
5418
5636
  throw new Error("No tasks currently have options to select from.");
5419
5637
  }
5420
- const formattedTasks = tasksWithOptions.map((task, index) => ({
5421
- taskId: index + 1,
5422
- name: task.name,
5423
- options: task.metadata.options.map((opt) => ({
5424
- name: typeof opt === "string" ? opt : opt.name,
5425
- description: typeof opt === "string" ? opt : opt.description || opt.name
5426
- }))
5427
- }));
5638
+ const formattedTasks = tasksWithOptions.map((task) => {
5639
+ const shortId = task.id.substring(0, 8);
5640
+ return {
5641
+ taskId: shortId,
5642
+ fullId: task.id,
5643
+ name: task.name,
5644
+ options: task.metadata.options.map((opt) => ({
5645
+ name: typeof opt === "string" ? opt : opt.name,
5646
+ description: typeof opt === "string" ? opt : opt.description || opt.name
5647
+ }))
5648
+ };
5649
+ });
5650
+ console.log(
5651
+ "*** FORMATTED TASKS ***\n",
5652
+ JSON.stringify(formattedTasks, null, 2)
5653
+ );
5428
5654
  const prompt = composePrompt({
5429
5655
  state: {
5430
5656
  ...state,
5431
- tasks: formattedTasks,
5432
- recentMessages: message.content.text
5657
+ values: {
5658
+ ...state.values,
5659
+ tasks: formattedTasks,
5660
+ recentMessages: message.content.text
5661
+ }
5433
5662
  },
5434
5663
  template: optionExtractionTemplate
5435
5664
  });
5665
+ console.log("*** PROMPT ***\n", prompt);
5436
5666
  const result = await runtime.useModel(ModelTypes.TEXT_SMALL, {
5437
5667
  prompt,
5438
5668
  stopSequences: []
5439
5669
  });
5670
+ console.log("*** RESULT ***\n", result);
5440
5671
  const parsed = parseJSONObjectFromText(result);
5441
5672
  const { taskId, selectedOption } = parsed;
5442
5673
  if (taskId && selectedOption) {
5443
- const selectedTask = tasksWithOptions[taskId - 1];
5674
+ console.log(
5675
+ "*** TASK ID AND SELECTED OPTION ***\n",
5676
+ taskId,
5677
+ selectedOption
5678
+ );
5679
+ const taskMap = new Map(
5680
+ formattedTasks.map((task) => [task.taskId, task])
5681
+ );
5682
+ const taskInfo = taskMap.get(taskId);
5683
+ if (!taskInfo) {
5684
+ await callback({
5685
+ text: `Could not find a task matching ID: ${taskId}. Please try again.`,
5686
+ actions: ["SELECT_OPTION_ERROR"],
5687
+ source: message.content.source
5688
+ });
5689
+ return;
5690
+ }
5691
+ const selectedTask = tasksWithOptions.find(
5692
+ (task) => task.id === taskInfo.fullId
5693
+ );
5694
+ if (!selectedTask) {
5695
+ await callback({
5696
+ text: "Error locating the selected task. Please try again.",
5697
+ actions: ["SELECT_OPTION_ERROR"],
5698
+ source: message.content.source
5699
+ });
5700
+ return;
5701
+ }
5444
5702
  if (selectedOption === "ABORT") {
5703
+ console.log("*** ABORT ***\n");
5445
5704
  await runtime.getDatabaseAdapter().deleteTask(selectedTask.id);
5446
5705
  await callback({
5447
5706
  text: `Task "${selectedTask.name}" has been cancelled.`,
5448
- actions: ["CHOOSE_OPTION"],
5707
+ actions: ["CHOOSE_OPTION_CANCELLED"],
5449
5708
  source: message.content.source
5450
5709
  });
5451
5710
  return;
5452
5711
  }
5453
5712
  try {
5454
5713
  const taskWorker = runtime.getTaskWorker(selectedTask.name);
5455
- await taskWorker.execute(runtime, { option: selectedOption });
5456
- await runtime.getDatabaseAdapter().deleteTask(selectedTask.id);
5714
+ await taskWorker.execute(
5715
+ runtime,
5716
+ { option: selectedOption },
5717
+ selectedTask
5718
+ );
5457
5719
  await callback({
5458
5720
  text: `Selected option: ${selectedOption} for task: ${selectedTask.name}`,
5459
5721
  actions: ["CHOOSE_OPTION"],
@@ -5471,8 +5733,9 @@ var choiceAction = {
5471
5733
  }
5472
5734
  }
5473
5735
  let optionsText = "Please select a valid option from one of these tasks:\n\n";
5474
- tasksWithOptions.forEach((task, index) => {
5475
- optionsText += `${index + 1}. **${task.name}**:
5736
+ tasksWithOptions.forEach((task) => {
5737
+ const shortId = task.id.substring(0, 8);
5738
+ optionsText += `**${task.name}** (ID: ${shortId}):
5476
5739
  `;
5477
5740
  const options2 = task.metadata.options.map(
5478
5741
  (opt) => typeof opt === "string" ? opt : opt.name
@@ -5494,7 +5757,7 @@ var choiceAction = {
5494
5757
  source: message.content.source
5495
5758
  });
5496
5759
  }
5497
- },
5760
+ }, "handler"),
5498
5761
  examples: [
5499
5762
  [
5500
5763
  {
@@ -5551,7 +5814,7 @@ var followRoomAction = {
5551
5814
  "FOLLOW_THREAD"
5552
5815
  ],
5553
5816
  description: "Start following this channel with great interest, chiming in without needing to be explicitly mentioned. Only do this if explicitly asked to.",
5554
- validate: async (runtime, message) => {
5817
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
5555
5818
  const keywords = [
5556
5819
  "follow",
5557
5820
  "participate",
@@ -5568,8 +5831,8 @@ var followRoomAction = {
5568
5831
  const roomId = message.roomId;
5569
5832
  const roomState = await runtime.getDatabaseAdapter().getParticipantUserState(roomId, runtime.agentId);
5570
5833
  return roomState !== "FOLLOWED" && roomState !== "MUTED";
5571
- },
5572
- handler: async (runtime, message, state, _options, _callback, _responses) => {
5834
+ }, "validate"),
5835
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, _callback, _responses) => {
5573
5836
  async function _shouldFollow(state2) {
5574
5837
  const shouldFollowPrompt = composePrompt({
5575
5838
  state: state2,
@@ -5617,6 +5880,7 @@ var followRoomAction = {
5617
5880
  logger_default.warn(`Unclear boolean response: ${response}, defaulting to false`);
5618
5881
  return false;
5619
5882
  }
5883
+ __name(_shouldFollow, "_shouldFollow");
5620
5884
  if (await _shouldFollow(state)) {
5621
5885
  await runtime.getDatabaseAdapter().setParticipantUserState(message.roomId, runtime.agentId, "FOLLOWED");
5622
5886
  }
@@ -5630,7 +5894,7 @@ var followRoomAction = {
5630
5894
  actions: ["FOLLOW_ROOM_START"]
5631
5895
  }
5632
5896
  });
5633
- },
5897
+ }, "handler"),
5634
5898
  examples: [
5635
5899
  [
5636
5900
  {
@@ -5910,13 +6174,13 @@ var followRoomAction = {
5910
6174
  var ignoreAction = {
5911
6175
  name: "IGNORE",
5912
6176
  similes: ["STOP_TALKING", "STOP_CHATTING", "STOP_CONVERSATION"],
5913
- validate: async (_runtime, _message) => {
6177
+ validate: /* @__PURE__ */ __name(async (_runtime, _message) => {
5914
6178
  return true;
5915
- },
6179
+ }, "validate"),
5916
6180
  description: "Call this action if ignoring the user. If the user is aggressive, creepy or is finished with the conversation, use this action. Or, if both you and the user have already said goodbye, use this action instead of saying bye again. Use IGNORE any time the conversation has naturally ended. Do not use IGNORE if the user has engaged directly, or if something went wrong an you need to tell them. Only ignore if the user should be ignored.",
5917
- handler: async (_runtime, _message) => {
6181
+ handler: /* @__PURE__ */ __name(async (_runtime, _message) => {
5918
6182
  return true;
5919
- },
6183
+ }, "handler"),
5920
6184
  examples: [
5921
6185
  [
5922
6186
  {
@@ -6148,12 +6412,12 @@ var muteRoomAction = {
6148
6412
  "MUTE_CHANNEL"
6149
6413
  ],
6150
6414
  description: "Mutes a room, ignoring all messages unless explicitly mentioned. Only do this if explicitly asked to, or if you're annoying people.",
6151
- validate: async (runtime, message) => {
6415
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
6152
6416
  const roomId = message.roomId;
6153
6417
  const roomState = await runtime.getDatabaseAdapter().getParticipantUserState(roomId, runtime.agentId);
6154
6418
  return roomState !== "MUTED";
6155
- },
6156
- handler: async (runtime, message, state, _options, _callback, _responses) => {
6419
+ }, "validate"),
6420
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, _callback, _responses) => {
6157
6421
  async function _shouldMute(state2) {
6158
6422
  const shouldMutePrompt = composePrompt({
6159
6423
  state: state2,
@@ -6200,6 +6464,7 @@ var muteRoomAction = {
6200
6464
  logger_default.warn(`Unclear boolean response: ${response}, defaulting to false`);
6201
6465
  return false;
6202
6466
  }
6467
+ __name(_shouldMute, "_shouldMute");
6203
6468
  if (await _shouldMute(state)) {
6204
6469
  await runtime.getDatabaseAdapter().setParticipantUserState(message.roomId, runtime.agentId, "MUTED");
6205
6470
  }
@@ -6213,7 +6478,7 @@ var muteRoomAction = {
6213
6478
  actions: ["MUTE_ROOM_START"]
6214
6479
  }
6215
6480
  });
6216
- },
6481
+ }, "handler"),
6217
6482
  examples: [
6218
6483
  [
6219
6484
  {
@@ -6328,21 +6593,14 @@ var muteRoomAction = {
6328
6593
  // src/actions/none.ts
6329
6594
  var noneAction = {
6330
6595
  name: "NONE",
6331
- similes: [
6332
- "NO_ACTION",
6333
- "NO_RESPONSE",
6334
- "NO_REACTION",
6335
- "RESPONSE",
6336
- "REPLY",
6337
- "DEFAULT"
6338
- ],
6339
- validate: async (_runtime, _message) => {
6596
+ similes: ["NO_ACTION", "NO_RESPONSE", "NO_REACTION"],
6597
+ validate: /* @__PURE__ */ __name(async (_runtime, _message) => {
6340
6598
  return true;
6341
- },
6599
+ }, "validate"),
6342
6600
  description: "Respond but perform no additional action. This is the default if the agent is speaking and not doing anything additional.",
6343
- handler: async (_runtime, _message) => {
6601
+ handler: /* @__PURE__ */ __name(async (_runtime, _message) => {
6344
6602
  return true;
6345
- },
6603
+ }, "handler"),
6346
6604
  examples: [
6347
6605
  [
6348
6606
  {
@@ -6486,10 +6744,10 @@ var replyAction = {
6486
6744
  name: "REPLY",
6487
6745
  similes: ["REPLY_TO_MESSAGE", "SEND_REPLY", "RESPOND"],
6488
6746
  description: "Replies to the current conversation with the text from the generated message. Default if the agent is responding with a message and no other action. Use REPLY at the beginning of a chain of actions as an acknowledgement, and at the end of a chain of actions as a final response.",
6489
- validate: async (_runtime) => {
6747
+ validate: /* @__PURE__ */ __name(async (_runtime) => {
6490
6748
  return true;
6491
- },
6492
- handler: async (runtime, message, state, _options, callback) => {
6749
+ }, "validate"),
6750
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback) => {
6493
6751
  state = await runtime.composeState(message, [
6494
6752
  ...message.content.providers ?? [],
6495
6753
  "RECENT_MESSAGES"
@@ -6508,7 +6766,7 @@ var replyAction = {
6508
6766
  actions: ["REPLY"]
6509
6767
  };
6510
6768
  await callback(responseContent);
6511
- },
6769
+ }, "handler"),
6512
6770
  examples: [
6513
6771
  [
6514
6772
  {
@@ -6574,7 +6832,7 @@ var replyAction = {
6574
6832
  };
6575
6833
 
6576
6834
  // src/actions/roles.ts
6577
- var generateObject = async ({
6835
+ var generateObject = /* @__PURE__ */ __name(async ({
6578
6836
  runtime,
6579
6837
  prompt,
6580
6838
  modelType,
@@ -6641,8 +6899,8 @@ var generateObject = async ({
6641
6899
  logger.error(jsonString);
6642
6900
  return null;
6643
6901
  }
6644
- };
6645
- var canModifyRole = (currentRole, targetRole, newRole) => {
6902
+ }, "generateObject");
6903
+ var canModifyRole = /* @__PURE__ */ __name((currentRole, targetRole, newRole) => {
6646
6904
  if (currentRole === "OWNER" /* OWNER */) {
6647
6905
  return targetRole !== "OWNER" /* OWNER */;
6648
6906
  }
@@ -6650,7 +6908,7 @@ var canModifyRole = (currentRole, targetRole, newRole) => {
6650
6908
  return (!targetRole || targetRole === "NONE" /* NONE */) && !["OWNER" /* OWNER */, "ADMIN" /* ADMIN */].includes(newRole);
6651
6909
  }
6652
6910
  return false;
6653
- };
6911
+ }, "canModifyRole");
6654
6912
  var extractionTemplate = `# Task: Extract role assignments from the conversation
6655
6913
 
6656
6914
  # Current Server Members:
@@ -6709,11 +6967,12 @@ async function generateObjectArray({
6709
6967
  }
6710
6968
  return schema ? schema.parse(result) : result;
6711
6969
  }
6970
+ __name(generateObjectArray, "generateObjectArray");
6712
6971
  var updateRoleAction = {
6713
6972
  name: "UPDATE_ROLE",
6714
6973
  similes: ["CHANGE_ROLE", "SET_ROLE", "MODIFY_ROLE"],
6715
6974
  description: "Updates the role for a user with respect to the agent, world being the server they are in. For example, if an admin tells the agent that a user is their boss, set their role to ADMIN. Can only be used to set roles to ADMIN, OWNER or NONE. Can't be used to ban.",
6716
- validate: async (runtime, message, state) => {
6975
+ validate: /* @__PURE__ */ __name(async (runtime, message, state) => {
6717
6976
  logger.info("Starting role update validation");
6718
6977
  if (message.content.source !== "discord") {
6719
6978
  logger.info("Validation failed: Not a discord message");
@@ -6755,8 +7014,8 @@ var updateRoleAction = {
6755
7014
  logger.error("Error validating updateOrgRole action:", error);
6756
7015
  return false;
6757
7016
  }
6758
- },
6759
- handler: async (runtime, message, state, _options, callback, responses) => {
7017
+ }, "validate"),
7018
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback, responses) => {
6760
7019
  for (const response of responses) {
6761
7020
  await callback(response.content);
6762
7021
  }
@@ -6785,15 +7044,18 @@ var updateRoleAction = {
6785
7044
  const discordData = entity.components?.find(
6786
7045
  (c) => c.type === "discord"
6787
7046
  )?.data;
6788
- const name2 = discordData?.username || entity.names[0];
7047
+ const name = discordData?.username || entity.names[0];
6789
7048
  const id = entity.id;
6790
- return `${name2} (${id})`;
7049
+ return `${name} (${id})`;
6791
7050
  }).join("\n");
6792
7051
  const extractionPrompt = composePrompt({
6793
7052
  state: {
6794
7053
  ...state,
6795
- serverMembers: serverMembersContext,
6796
- speakerRole: requesterRole
7054
+ values: {
7055
+ ...state.values,
7056
+ serverMembers: serverMembersContext,
7057
+ speakerRole: requesterRole
7058
+ }
6797
7059
  },
6798
7060
  template: extractionTemplate
6799
7061
  });
@@ -6841,7 +7103,7 @@ var updateRoleAction = {
6841
7103
  await runtime.getDatabaseAdapter().updateWorld(world);
6842
7104
  logger.info(`Updated roles in world metadata for server ${serverId}`);
6843
7105
  }
6844
- },
7106
+ }, "handler"),
6845
7107
  examples: [
6846
7108
  [
6847
7109
  {
@@ -6946,14 +7208,14 @@ var sendMessageAction = {
6946
7208
  name: "SEND_MESSAGE",
6947
7209
  similes: ["DM", "MESSAGE", "SEND_DM", "POST_MESSAGE"],
6948
7210
  description: "Send a message to a user or room (other than the current one)",
6949
- validate: async (runtime, message, _state) => {
7211
+ validate: /* @__PURE__ */ __name(async (runtime, message, _state) => {
6950
7212
  const worldId = message.roomId;
6951
7213
  const agentId = runtime.agentId;
6952
7214
  const roomComponents = await runtime.getDatabaseAdapter().getComponents(message.roomId, worldId, agentId);
6953
7215
  const availableSources = new Set(roomComponents.map((c) => c.type));
6954
7216
  return availableSources.size > 0;
6955
- },
6956
- handler: async (runtime, message, state, _options, callback, responses) => {
7217
+ }, "validate"),
7218
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback, responses) => {
6957
7219
  try {
6958
7220
  for (const response of responses) {
6959
7221
  await callback(response.content);
@@ -7080,7 +7342,7 @@ var sendMessageAction = {
7080
7342
  source: message.content.source
7081
7343
  });
7082
7344
  }
7083
- },
7345
+ }, "handler"),
7084
7346
  examples: [
7085
7347
  [
7086
7348
  {
@@ -7228,6 +7490,7 @@ var extractionTemplate2 = `# Task: Extract setting values from the conversation
7228
7490
  # Available Settings:
7229
7491
  {{#each settings}}
7230
7492
  {{key}}:
7493
+ Key: {{key}}
7231
7494
  Name: {{name}}
7232
7495
  Description: {{description}}
7233
7496
  Current Value: {{value}}
@@ -7244,7 +7507,7 @@ var extractionTemplate2 = `# Task: Extract setting values from the conversation
7244
7507
  # Instructions:
7245
7508
  1. Review the ENTIRE conversation and identify ALL values provided for settings
7246
7509
  2. For each setting mentioned, extract:
7247
- - The setting key (must exactly match one of the available settings above)
7510
+ - Infer the settings key the user is trying to set (must exactly match one of the available settings above)
7248
7511
  - The provided value that matches the setting's description and purpose
7249
7512
  3. Return an array of ALL setting updates found, even if mentioned earlier in the conversation
7250
7513
 
@@ -7255,7 +7518,7 @@ Return ONLY a JSON array of objects with 'key' and 'value' properties. Format:
7255
7518
  ]
7256
7519
 
7257
7520
  IMPORTANT: Only include settings from the Available Settings list above. Ignore any other potential settings.`;
7258
- var generateObject2 = async ({
7521
+ var generateObject2 = /* @__PURE__ */ __name(async ({
7259
7522
  runtime,
7260
7523
  prompt,
7261
7524
  modelType = ModelTypes.TEXT_LARGE,
@@ -7322,7 +7585,7 @@ var generateObject2 = async ({
7322
7585
  logger.error(jsonString);
7323
7586
  return null;
7324
7587
  }
7325
- };
7588
+ }, "generateObject");
7326
7589
  async function generateObjectArray2({
7327
7590
  runtime,
7328
7591
  prompt,
@@ -7348,6 +7611,7 @@ async function generateObjectArray2({
7348
7611
  }
7349
7612
  return schema ? schema.parse(result) : result;
7350
7613
  }
7614
+ __name(generateObjectArray2, "generateObjectArray");
7351
7615
  async function getWorldSettings(runtime, serverId) {
7352
7616
  try {
7353
7617
  const worldId = createUniqueUuid(runtime, serverId);
@@ -7361,6 +7625,7 @@ async function getWorldSettings(runtime, serverId) {
7361
7625
  return null;
7362
7626
  }
7363
7627
  }
7628
+ __name(getWorldSettings, "getWorldSettings");
7364
7629
  async function updateWorldSettings(runtime, serverId, worldSettings) {
7365
7630
  try {
7366
7631
  const worldId = createUniqueUuid(runtime, serverId);
@@ -7380,14 +7645,18 @@ async function updateWorldSettings(runtime, serverId, worldSettings) {
7380
7645
  return false;
7381
7646
  }
7382
7647
  }
7648
+ __name(updateWorldSettings, "updateWorldSettings");
7383
7649
  function formatSettingsList(worldSettings) {
7650
+ console.log("*** WORLD SETTINGS ***\n", worldSettings);
7384
7651
  const settings2 = Object.entries(worldSettings).filter(([key]) => !key.startsWith("_")).map(([key, setting]) => {
7385
7652
  const status = setting.value !== null ? "Configured" : "Not configured";
7386
7653
  const required = setting.required ? "Required" : "Optional";
7387
7654
  return `- ${setting.name} (${key}): ${status}, ${required}`;
7388
7655
  }).join("\n");
7656
+ console.log("*** SETTINGS LIST ***\n", settings2);
7389
7657
  return settings2 || "No settings available";
7390
7658
  }
7659
+ __name(formatSettingsList, "formatSettingsList");
7391
7660
  function categorizeSettings(worldSettings) {
7392
7661
  const configured = [];
7393
7662
  const requiredUnconfigured = [];
@@ -7404,24 +7673,31 @@ function categorizeSettings(worldSettings) {
7404
7673
  }
7405
7674
  return { configured, requiredUnconfigured, optionalUnconfigured };
7406
7675
  }
7676
+ __name(categorizeSettings, "categorizeSettings");
7407
7677
  async function extractSettingValues(runtime, _message, state, worldSettings) {
7408
7678
  try {
7679
+ console.log("*** WORLD SETTINGS ***\n", worldSettings);
7409
7680
  const prompt = composePrompt({
7410
7681
  state: {
7411
7682
  ...state,
7412
- settings: Object.entries(worldSettings).filter(([key]) => !key.startsWith("_")).map(([key, setting]) => ({
7413
- key,
7414
- ...setting
7415
- })),
7416
- settingsStatus: formatSettingsList(worldSettings)
7683
+ values: {
7684
+ ...state.values,
7685
+ settings: Object.entries(worldSettings).filter(([key]) => !key.startsWith("_")).map(([key, setting]) => ({
7686
+ key,
7687
+ ...setting
7688
+ })),
7689
+ settingsStatus: formatSettingsList(worldSettings)
7690
+ }
7417
7691
  },
7418
7692
  template: extractionTemplate2
7419
7693
  });
7694
+ console.log("*** EXTRACTION PROMPT ***\n", prompt);
7420
7695
  const extractions = await generateObjectArray2({
7421
7696
  runtime,
7422
7697
  prompt,
7423
7698
  modelType: ModelTypes.TEXT_LARGE
7424
7699
  });
7700
+ console.log("*** EXTRACTIONS ***\n", extractions);
7425
7701
  logger.info(`Extracted ${extractions.length} potential setting updates`);
7426
7702
  const validExtractions = extractions.filter((update) => {
7427
7703
  const setting = worldSettings[update.key];
@@ -7442,6 +7718,7 @@ async function extractSettingValues(runtime, _message, state, worldSettings) {
7442
7718
  return [];
7443
7719
  }
7444
7720
  }
7721
+ __name(extractSettingValues, "extractSettingValues");
7445
7722
  async function processSettingUpdates(runtime, serverId, worldSettings, updates) {
7446
7723
  if (!updates.length) {
7447
7724
  return { updatedAny: false, messages: [] };
@@ -7494,12 +7771,16 @@ async function processSettingUpdates(runtime, serverId, worldSettings, updates)
7494
7771
  };
7495
7772
  }
7496
7773
  }
7774
+ __name(processSettingUpdates, "processSettingUpdates");
7497
7775
  async function handleOnboardingComplete(runtime, worldSettings, state, callback) {
7498
7776
  try {
7499
7777
  const prompt = composePrompt({
7500
7778
  state: {
7501
7779
  ...state,
7502
- settingsStatus: formatSettingsList(worldSettings)
7780
+ values: {
7781
+ ...state.values,
7782
+ settingsStatus: formatSettingsList(worldSettings)
7783
+ }
7503
7784
  },
7504
7785
  template: completionTemplate
7505
7786
  });
@@ -7521,6 +7802,7 @@ async function handleOnboardingComplete(runtime, worldSettings, state, callback)
7521
7802
  });
7522
7803
  }
7523
7804
  }
7805
+ __name(handleOnboardingComplete, "handleOnboardingComplete");
7524
7806
  async function generateSuccessResponse(runtime, worldSettings, state, messages, callback) {
7525
7807
  try {
7526
7808
  const { requiredUnconfigured } = categorizeSettings(worldSettings);
@@ -7531,9 +7813,12 @@ async function generateSuccessResponse(runtime, worldSettings, state, messages,
7531
7813
  const prompt = composePrompt({
7532
7814
  state: {
7533
7815
  ...state,
7534
- updateMessages: messages.join("\n"),
7535
- nextSetting: requiredUnconfigured[0][1],
7536
- remainingRequired: requiredUnconfigured.length
7816
+ values: {
7817
+ ...state.values,
7818
+ updateMessages: messages.join("\n"),
7819
+ nextSetting: requiredUnconfigured[0][1],
7820
+ remainingRequired: requiredUnconfigured.length
7821
+ }
7537
7822
  },
7538
7823
  template: successTemplate
7539
7824
  });
@@ -7555,6 +7840,7 @@ async function generateSuccessResponse(runtime, worldSettings, state, messages,
7555
7840
  });
7556
7841
  }
7557
7842
  }
7843
+ __name(generateSuccessResponse, "generateSuccessResponse");
7558
7844
  async function generateFailureResponse(runtime, worldSettings, state, callback) {
7559
7845
  try {
7560
7846
  const { requiredUnconfigured } = categorizeSettings(worldSettings);
@@ -7565,8 +7851,11 @@ async function generateFailureResponse(runtime, worldSettings, state, callback)
7565
7851
  const prompt = composePrompt({
7566
7852
  state: {
7567
7853
  ...state,
7568
- nextSetting: requiredUnconfigured[0][1],
7569
- remainingRequired: requiredUnconfigured.length
7854
+ values: {
7855
+ ...state.values,
7856
+ nextSetting: requiredUnconfigured[0][1],
7857
+ remainingRequired: requiredUnconfigured.length
7858
+ }
7570
7859
  },
7571
7860
  template: failureTemplate
7572
7861
  });
@@ -7588,6 +7877,7 @@ async function generateFailureResponse(runtime, worldSettings, state, callback)
7588
7877
  });
7589
7878
  }
7590
7879
  }
7880
+ __name(generateFailureResponse, "generateFailureResponse");
7591
7881
  async function generateErrorResponse(runtime, state, callback) {
7592
7882
  try {
7593
7883
  const prompt = composePrompt({
@@ -7612,11 +7902,12 @@ async function generateErrorResponse(runtime, state, callback) {
7612
7902
  });
7613
7903
  }
7614
7904
  }
7905
+ __name(generateErrorResponse, "generateErrorResponse");
7615
7906
  var updateSettingsAction = {
7616
7907
  name: "UPDATE_SETTINGS",
7617
7908
  similes: ["UPDATE_SETTING", "SAVE_SETTING", "SET_CONFIGURATION", "CONFIGURE"],
7618
- description: "Saves a setting during the settings process",
7619
- validate: async (runtime, message, _state) => {
7909
+ description: "Saves a configuration setting during the onboarding process, or update an existing setting. Use this when you are onboarding with a world owner or admin.",
7910
+ validate: /* @__PURE__ */ __name(async (runtime, message, _state) => {
7620
7911
  try {
7621
7912
  if (message.content.channelType !== "DM" /* DM */) {
7622
7913
  logger.info(
@@ -7641,8 +7932,8 @@ var updateSettingsAction = {
7641
7932
  logger.error(`Error validating settings action: ${error}`);
7642
7933
  return false;
7643
7934
  }
7644
- },
7645
- handler: async (runtime, message, state, _options, callback) => {
7935
+ }, "validate"),
7936
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback) => {
7646
7937
  try {
7647
7938
  logger.info(`Handler looking for server for user ${message.entityId}`);
7648
7939
  const serverOwnership = await findWorldForOwner(
@@ -7709,7 +8000,7 @@ var updateSettingsAction = {
7709
8000
  logger.error(`Error in settings handler: ${error}`);
7710
8001
  await generateErrorResponse(runtime, state, callback);
7711
8002
  }
7712
- },
8003
+ }, "handler"),
7713
8004
  examples: [
7714
8005
  [
7715
8006
  {
@@ -7907,12 +8198,12 @@ var unfollowRoomAction = {
7907
8198
  "UNFOLLOW_THREAD"
7908
8199
  ],
7909
8200
  description: "Stop following this channel. You can still respond if explicitly mentioned, but you won't automatically chime in anymore. Unfollow if you're annoying people or have been asked to.",
7910
- validate: async (runtime, message) => {
8201
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
7911
8202
  const roomId = message.roomId;
7912
8203
  const roomState = await runtime.getDatabaseAdapter().getParticipantUserState(roomId, runtime.agentId);
7913
8204
  return roomState === "FOLLOWED";
7914
- },
7915
- handler: async (runtime, message, state, _options, _callback, _responses) => {
8205
+ }, "validate"),
8206
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, _callback, _responses) => {
7916
8207
  async function _shouldUnfollow(state2) {
7917
8208
  const shouldUnfollowPrompt = composePrompt({
7918
8209
  state: state2,
@@ -7925,6 +8216,7 @@ var unfollowRoomAction = {
7925
8216
  const parsedResponse = parseBooleanFromText(response.trim());
7926
8217
  return parsedResponse;
7927
8218
  }
8219
+ __name(_shouldUnfollow, "_shouldUnfollow");
7928
8220
  if (await _shouldUnfollow(state)) {
7929
8221
  await runtime.getDatabaseAdapter().setParticipantUserState(message.roomId, runtime.agentId, null);
7930
8222
  const room = state.data.room ?? await runtime.getDatabaseAdapter().getRoom(message.roomId);
@@ -7952,7 +8244,7 @@ var unfollowRoomAction = {
7952
8244
  }
7953
8245
  });
7954
8246
  }
7955
- },
8247
+ }, "handler"),
7956
8248
  examples: [
7957
8249
  [
7958
8250
  {
@@ -8222,12 +8514,12 @@ var unmuteRoomAction = {
8222
8514
  "UNMUTE_THREAD"
8223
8515
  ],
8224
8516
  description: "Unmutes a room, allowing the agent to consider responding to messages again.",
8225
- validate: async (runtime, message) => {
8517
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
8226
8518
  const roomId = message.roomId;
8227
8519
  const roomState = await runtime.getDatabaseAdapter().getParticipantUserState(roomId, runtime.agentId);
8228
8520
  return roomState === "MUTED";
8229
- },
8230
- handler: async (runtime, message, state, _options, _callback, _responses) => {
8521
+ }, "validate"),
8522
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, _callback, _responses) => {
8231
8523
  async function _shouldUnmute(state2) {
8232
8524
  const shouldUnmutePrompt = composePrompt({
8233
8525
  state: state2,
@@ -8275,6 +8567,7 @@ var unmuteRoomAction = {
8275
8567
  logger_default.warn(`Unclear boolean response: ${response}, defaulting to false`);
8276
8568
  return false;
8277
8569
  }
8570
+ __name(_shouldUnmute, "_shouldUnmute");
8278
8571
  if (await _shouldUnmute(state)) {
8279
8572
  await runtime.getDatabaseAdapter().setParticipantUserState(message.roomId, runtime.agentId, null);
8280
8573
  }
@@ -8288,7 +8581,7 @@ var unmuteRoomAction = {
8288
8581
  actions: ["UNMUTE_ROOM_START"]
8289
8582
  }
8290
8583
  });
8291
- },
8584
+ }, "handler"),
8292
8585
  examples: [
8293
8586
  [
8294
8587
  {
@@ -8438,19 +8731,13 @@ Example outputs:
8438
8731
 
8439
8732
  Make sure to include the \`\`\`json\`\`\` tags around the JSON object.`;
8440
8733
  var updateEntityAction = {
8441
- name: "UPDATE_ENTITY",
8442
- similes: [
8443
- "CREATE_ENTITY",
8444
- "UPDATE_USER",
8445
- "EDIT_ENTITY",
8446
- "UPDATE_COMPONENT",
8447
- "CREATE_COMPONENT"
8448
- ],
8449
- description: "Add or edit contact details for a user entity (like twitter, discord, email address, etc.)",
8450
- validate: async (_runtime, _message, _state) => {
8734
+ name: "UPDATE_CONTACT",
8735
+ similes: ["UPDATE_ENTITY"],
8736
+ description: "Add or edit contact details for a person you are talking to or observing in the conversation. Use this when you learn this information from the conversation about a contact. This is for the agent to relate entities across platforms, not for world settings or configuration.",
8737
+ validate: /* @__PURE__ */ __name(async (_runtime, _message, _state) => {
8451
8738
  return true;
8452
- },
8453
- handler: async (runtime, message, state, _options, callback, responses) => {
8739
+ }, "validate"),
8740
+ handler: /* @__PURE__ */ __name(async (runtime, message, state, _options, callback, responses) => {
8454
8741
  try {
8455
8742
  for (const response of responses) {
8456
8743
  await callback(response.content);
@@ -8541,7 +8828,7 @@ var updateEntityAction = {
8541
8828
  source: message.content.source
8542
8829
  });
8543
8830
  }
8544
- },
8831
+ }, "handler"),
8545
8832
  examples: [
8546
8833
  [
8547
8834
  {
@@ -8591,7 +8878,7 @@ var updateEntityAction = {
8591
8878
  ]
8592
8879
  };
8593
8880
 
8594
- // src/evaluators/goal.ts
8881
+ // src/actions/goal.ts
8595
8882
  var goalsTemplate = `# TASK: Update Goal
8596
8883
  Analyze the conversation and update the status of the goals based on the new information provided.
8597
8884
 
@@ -8665,188 +8952,104 @@ async function handler(runtime, message, state, options2 = { onlyInProgress: tru
8665
8952
  }
8666
8953
  return updatedGoals;
8667
8954
  }
8668
- var goalEvaluator = {
8955
+ __name(handler, "handler");
8956
+ var goalAction = {
8669
8957
  name: "UPDATE_GOAL",
8958
+ description: "Analyze the conversation and update the status of the goals based on the new information provided.",
8670
8959
  similes: [
8671
8960
  "UPDATE_GOALS",
8672
8961
  "EDIT_GOAL",
8673
8962
  "UPDATE_GOAL_STATUS",
8674
8963
  "UPDATE_OBJECTIVES"
8675
8964
  ],
8676
- validate: async (runtime, message) => {
8965
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
8677
8966
  const goals = await runtime.getDatabaseAdapter().getGoals({
8678
8967
  count: 1,
8679
8968
  onlyInProgress: true,
8680
8969
  roomId: message.roomId
8681
8970
  });
8682
8971
  return goals.length > 0;
8683
- },
8684
- description: "Analyze the conversation and update the status of the goals based on the new information provided.",
8972
+ }, "validate"),
8685
8973
  handler,
8686
8974
  examples: [
8687
- {
8688
- prompt: `People in the scene:
8689
- {{name1}}: An avid reader and member of a book club.
8690
- {{name2}}: The organizer of the book club.
8691
-
8692
- Goals:
8693
- - Name: Finish reading "War and Peace"
8694
- id: 12345-67890-12345-67890
8695
- Status: IN_PROGRESS
8696
- Objectives:
8697
- - Read up to chapter 20 by the end of the month
8698
- - Discuss the first part in the next meeting`,
8699
- messages: [
8700
- {
8701
- name: "{{name1}}",
8702
- content: {
8703
- text: "I've just finished chapter 20 of 'War and Peace'"
8704
- }
8705
- },
8706
- {
8707
- name: "{{name2}}",
8708
- content: {
8709
- text: "Were you able to grasp the complexities of the characters"
8710
- }
8711
- },
8712
- {
8713
- name: "{{name1}}",
8714
- content: {
8715
- text: "Yep. I've prepared some notes for our discussion"
8716
- }
8717
- }
8718
- ],
8719
- outcome: `[
8720
- {
8721
- "id": "12345-67890-12345-67890",
8722
- "status": "DONE",
8723
- "objectives": [
8724
- { "description": "Read up to chapter 20 by the end of the month", "completed": true },
8725
- { "description": "Prepare notes for the next discussion", "completed": true }
8726
- ]
8727
- }
8728
- ]`
8729
- },
8730
- {
8731
- prompt: `People in the scene:
8732
- {{name1}}: A fitness enthusiast working towards a marathon.
8733
- {{name2}}: A personal trainer.
8734
-
8735
- Goals:
8736
- - Name: Complete a marathon
8737
- id: 23456-78901-23456-78901
8738
- Status: IN_PROGRESS
8739
- Objectives:
8740
- - Increase running distance to 30 miles a week
8741
- - Complete a half-marathon as practice`,
8742
- messages: [
8743
- {
8744
- name: "{{name1}}",
8745
- content: { text: "I managed to run 30 miles this week" }
8746
- },
8747
- {
8748
- name: "{{name2}}",
8749
- content: {
8750
- text: "Impressive progress! How do you feel about the half-marathon next month?"
8751
- }
8752
- },
8753
- {
8754
- name: "{{name1}}",
8755
- content: {
8756
- text: "I feel confident. The training is paying off."
8757
- }
8975
+ [
8976
+ {
8977
+ name: "{{name1}}",
8978
+ content: {
8979
+ text: "I've just finished chapter 20 of 'War and Peace'"
8758
8980
  }
8759
- ],
8760
- outcome: `[
8761
- {
8762
- "id": "23456-78901-23456-78901",
8763
- "objectives": [
8764
- { "description": "Increase running distance to 30 miles a week", "completed": true },
8765
- { "description": "Complete a half-marathon as practice", "completed": false }
8766
- ]
8981
+ },
8982
+ {
8983
+ name: "{{name2}}",
8984
+ content: {
8985
+ text: "Were you able to grasp the complexities of the characters"
8767
8986
  }
8768
- ]`
8769
- },
8770
- {
8771
- prompt: `People in the scene:
8772
- {{name1}}: A student working on a final year project.
8773
- {{name2}}: The project supervisor.
8774
-
8775
- Goals:
8776
- - Name: Finish the final year project
8777
- id: 34567-89012-34567-89012
8778
- Status: IN_PROGRESS
8779
- Objectives:
8780
- - Submit the first draft of the thesis
8781
- - Complete the project prototype`,
8782
- messages: [
8783
- {
8784
- name: "{{name1}}",
8785
- content: {
8786
- text: "I've submitted the first draft of my thesis."
8787
- }
8788
- },
8789
- {
8790
- name: "{{name2}}",
8791
- content: {
8792
- text: "Well done. How is the prototype coming along?"
8793
- }
8794
- },
8795
- {
8796
- name: "{{name1}}",
8797
- content: {
8798
- text: "It's almost done. I just need to finalize the testing phase."
8799
- }
8987
+ },
8988
+ {
8989
+ name: "{{name1}}",
8990
+ content: {
8991
+ text: "Yep. I've prepared some notes for our discussion"
8800
8992
  }
8801
- ],
8802
- outcome: `[
8803
- {
8804
- "id": "34567-89012-34567-89012",
8805
- "objectives": [
8806
- { "description": "Submit the first draft of the thesis", "completed": true },
8807
- { "description": "Complete the project prototype", "completed": false }
8808
- ]
8993
+ }
8994
+ ],
8995
+ [
8996
+ {
8997
+ name: "{{name1}}",
8998
+ content: { text: "I managed to run 30 miles this week" }
8999
+ },
9000
+ {
9001
+ name: "{{name2}}",
9002
+ content: {
9003
+ text: "Impressive progress! How do you feel about the half-marathon next month?"
8809
9004
  }
8810
- ]`
8811
- },
8812
- {
8813
- prompt: `People in the scene:
8814
- {{name1}}: A project manager working on a software development project.
8815
- {{name2}}: A software developer in the project team.
8816
-
8817
- Goals:
8818
- - Name: Launch the new software version
8819
- id: 45678-90123-45678-90123
8820
- Status: IN_PROGRESS
8821
- Objectives:
8822
- - Complete the coding for the new features
8823
- - Perform comprehensive testing of the software`,
8824
- messages: [
8825
- {
8826
- name: "{{name1}}",
8827
- content: {
8828
- text: "How's the progress on the new features?"
8829
- }
8830
- },
8831
- {
8832
- name: "{{name2}}",
8833
- content: {
8834
- text: "We've encountered some unexpected challenges and are currently troubleshooting."
8835
- }
8836
- },
8837
- {
8838
- name: "{{name1}}",
8839
- content: {
8840
- text: "Let's move on and cancel the task."
8841
- }
9005
+ },
9006
+ {
9007
+ name: "{{name1}}",
9008
+ content: {
9009
+ text: "I feel confident. The training is paying off."
8842
9010
  }
8843
- ],
8844
- outcome: `[
8845
- {
8846
- "id": "45678-90123-45678-90123",
8847
- "status": "FAILED"
8848
- ]`
8849
- }
9011
+ }
9012
+ ],
9013
+ [
9014
+ {
9015
+ name: "{{name1}}",
9016
+ content: {
9017
+ text: "I've submitted the first draft of my thesis."
9018
+ }
9019
+ },
9020
+ {
9021
+ name: "{{name2}}",
9022
+ content: {
9023
+ text: "Well done. How is the prototype coming along?"
9024
+ }
9025
+ },
9026
+ {
9027
+ name: "{{name1}}",
9028
+ content: {
9029
+ text: "It's almost done. I just need to finalize the testing phase."
9030
+ }
9031
+ }
9032
+ ],
9033
+ [
9034
+ {
9035
+ name: "{{name1}}",
9036
+ content: {
9037
+ text: "How's the progress on the new features?"
9038
+ }
9039
+ },
9040
+ {
9041
+ name: "{{name2}}",
9042
+ content: {
9043
+ text: "We've encountered some unexpected challenges and are currently troubleshooting."
9044
+ }
9045
+ },
9046
+ {
9047
+ name: "{{name1}}",
9048
+ content: {
9049
+ text: "Let's move on and cancel the task."
9050
+ }
9051
+ }
9052
+ ]
8850
9053
  ]
8851
9054
  };
8852
9055
 
@@ -8944,9 +9147,10 @@ function resolveEntity(entityId, entities) {
8944
9147
  if (entity) {
8945
9148
  return entity.id;
8946
9149
  }
8947
- throw new Error(`Could not resolve name "${name}" to a valid UUID`);
9150
+ throw new Error(`Could not resolve entityId "${entityId}" to a valid UUID`);
8948
9151
  }
8949
- var generateObject3 = async ({
9152
+ __name(resolveEntity, "resolveEntity");
9153
+ var generateObject3 = /* @__PURE__ */ __name(async ({
8950
9154
  runtime,
8951
9155
  prompt,
8952
9156
  modelType = ModelTypes.TEXT_SMALL,
@@ -9013,7 +9217,7 @@ var generateObject3 = async ({
9013
9217
  logger_default.error(jsonString);
9014
9218
  return null;
9015
9219
  }
9016
- };
9220
+ }, "generateObject");
9017
9221
  async function handler2(runtime, message, state) {
9018
9222
  const { agentId, roomId } = message;
9019
9223
  const factsManager = new MemoryManager({
@@ -9032,14 +9236,18 @@ async function handler2(runtime, message, state) {
9032
9236
  unique: true
9033
9237
  })
9034
9238
  ]);
9239
+ console.log("****** entities ******\n", entities);
9035
9240
  const prompt = composePrompt({
9036
9241
  state: {
9037
9242
  ...state,
9038
- knownFacts: formatFacts(knownFacts),
9039
- roomType: message.content.channelType,
9040
- entitiesInRoom: JSON.stringify(entities),
9041
- existingRelationships: JSON.stringify(existingRelationships),
9042
- senderId: message.entityId
9243
+ values: {
9244
+ ...state.values,
9245
+ knownFacts: formatFacts(knownFacts),
9246
+ roomType: message.content.channelType,
9247
+ entitiesInRoom: JSON.stringify(entities),
9248
+ existingRelationships: JSON.stringify(existingRelationships),
9249
+ senderId: message.entityId
9250
+ }
9043
9251
  },
9044
9252
  template: runtime.character.templates?.reflectionTemplate || reflectionTemplate
9045
9253
  });
@@ -9113,6 +9321,7 @@ async function handler2(runtime, message, state) {
9113
9321
  );
9114
9322
  return reflection;
9115
9323
  }
9324
+ __name(handler2, "handler");
9116
9325
  var reflectionEvaluator = {
9117
9326
  name: "REFLECTION",
9118
9327
  similes: [
@@ -9121,7 +9330,7 @@ var reflectionEvaluator = {
9121
9330
  "EVALUATE_INTERACTION",
9122
9331
  "ASSESS_SITUATION"
9123
9332
  ],
9124
- validate: async (runtime, message) => {
9333
+ validate: /* @__PURE__ */ __name(async (runtime, message) => {
9125
9334
  const lastMessageId = await runtime.getDatabaseAdapter().getCache(`${message.roomId}-reflection-last-processed`);
9126
9335
  const messages = await runtime.getMemoryManager("messages").getMemories({
9127
9336
  roomId: message.roomId,
@@ -9137,7 +9346,7 @@ var reflectionEvaluator = {
9137
9346
  }
9138
9347
  const reflectionInterval = Math.ceil(runtime.getConversationLength() / 4);
9139
9348
  return messages.length > reflectionInterval;
9140
- },
9349
+ }, "validate"),
9141
9350
  description: "Generate a self-reflective thought on the conversation, then extract facts and relationships between entities in the conversation.",
9142
9351
  handler: handler2,
9143
9352
  examples: [
@@ -9308,48 +9517,14 @@ Message Sender: Lisa (user-789)`,
9308
9517
  function formatFacts(facts) {
9309
9518
  return facts.reverse().map((fact) => fact.content.text).join("\n");
9310
9519
  }
9520
+ __name(formatFacts, "formatFacts");
9311
9521
 
9312
- // src/providers/providers.ts
9313
- var providersProvider = {
9314
- name: "PROVIDERS",
9315
- description: "List of all data providers the agent can use to get additional information",
9316
- get: async (runtime, _message) => {
9317
- const dynamicProviders = runtime.providers.filter(
9318
- (provider) => provider.dynamic === true
9319
- );
9320
- const providerDescriptions = dynamicProviders.map((provider) => {
9321
- return `- **${provider.name}**: ${provider.description || "No description available"}`;
9322
- });
9323
- const headerText = "# Providers\n\nThese providers are available for the agent to select and use:";
9324
- if (providerDescriptions.length === 0) {
9325
- return {
9326
- text: addHeader(
9327
- headerText,
9328
- "No dynamic providers are currently available."
9329
- )
9330
- };
9331
- }
9332
- const providersText = providerDescriptions.join("\n");
9333
- const text = addHeader(headerText, providersText);
9334
- const data = {
9335
- dynamicProviders: dynamicProviders.map((provider) => ({
9336
- name: provider.name,
9337
- description: provider.description || ""
9338
- }))
9339
- };
9340
- return {
9341
- text,
9342
- data
9343
- };
9344
- }
9345
- };
9346
-
9347
- // src/providers/actionExamples.ts
9522
+ // src/providers/actions.ts
9348
9523
  var actionsProvider = {
9349
9524
  name: "ACTIONS",
9350
9525
  description: "Possible response actions",
9351
9526
  position: -1,
9352
- get: async (runtime, message, state) => {
9527
+ get: /* @__PURE__ */ __name(async (runtime, message, state) => {
9353
9528
  const actionPromises = runtime.actions.map(async (action) => {
9354
9529
  const result = await action.validate(runtime, message, state);
9355
9530
  if (result) {
@@ -9378,13 +9553,15 @@ var actionsProvider = {
9378
9553
  values,
9379
9554
  text
9380
9555
  };
9381
- }
9556
+ }, "get")
9382
9557
  };
9383
9558
 
9384
9559
  // src/providers/anxiety.ts
9385
9560
  var anxietyProvider = {
9386
9561
  name: "ANXIETY",
9387
- get: async (_runtime, message) => {
9562
+ description: "Social directions for the AI to follow based on the channel type",
9563
+ dynamic: true,
9564
+ get: /* @__PURE__ */ __name(async (_runtime, message) => {
9388
9565
  const channelType = message.content.channelType;
9389
9566
  const groupAnxietyExamples = [
9390
9567
  "As an AI, your responses tend to be too long and verbose, and you respond when you shouldn't. You also tend to repeat yourself. Please don't speak and use IGNORE instead of responding when you aren't sure what to do.",
@@ -9458,14 +9635,15 @@ var anxietyProvider = {
9458
9635
  },
9459
9636
  text: anxiety
9460
9637
  };
9461
- }
9638
+ }, "get")
9462
9639
  };
9463
9640
 
9464
9641
  // src/providers/attachments.ts
9465
9642
  var attachmentsProvider = {
9466
9643
  name: "ATTACHMENTS",
9467
- description: "List of attachments in the current conversation",
9468
- get: async (runtime, message) => {
9644
+ description: "List of attachments sent during the current conversation, including names, descriptions, and summaries",
9645
+ dynamic: true,
9646
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
9469
9647
  let allAttachments = message.content.attachments || [];
9470
9648
  const { roomId } = message;
9471
9649
  const conversationLength = runtime.getConversationLength();
@@ -9515,13 +9693,13 @@ var attachmentsProvider = {
9515
9693
  data,
9516
9694
  text
9517
9695
  };
9518
- }
9696
+ }, "get")
9519
9697
  };
9520
9698
 
9521
9699
  // src/providers/capabilities.ts
9522
9700
  var capabilitiesProvider = {
9523
9701
  name: "CAPABILITIES",
9524
- get: async (runtime, _message) => {
9702
+ get: /* @__PURE__ */ __name(async (runtime, _message) => {
9525
9703
  try {
9526
9704
  const services = runtime.getAllServices();
9527
9705
  if (!services || services.size === 0) {
@@ -9557,23 +9735,22 @@ ${formattedCapabilities}`
9557
9735
  text: "Error retrieving capabilities from services."
9558
9736
  };
9559
9737
  }
9560
- }
9738
+ }, "get")
9561
9739
  };
9562
9740
 
9563
9741
  // src/providers/character.ts
9564
9742
  var characterProvider = {
9565
9743
  name: "CHARACTER",
9566
9744
  description: "Character information",
9567
- get: async (runtime, message, state) => {
9745
+ get: /* @__PURE__ */ __name(async (runtime, message, state) => {
9568
9746
  const character = runtime.character;
9569
9747
  const agentName = character.name;
9570
- let bio = character.bio || "";
9571
- if (Array.isArray(bio)) {
9572
- bio = bio.sort(() => 0.5 - Math.random()).slice(0, 3).join(" ");
9573
- }
9748
+ const bioText = Array.isArray(character.bio) ? character.bio.sort(() => 0.5 - Math.random()).slice(0, 10).join(" ") : character.bio || "";
9749
+ const bio = addHeader(`# About ${character.name}`, bioText);
9574
9750
  const system = character.system ?? "";
9575
- const topic = character.topics && character.topics.length > 0 ? character.topics[Math.floor(Math.random() * character.topics.length)] : null;
9576
- const topics = character.topics && character.topics.length > 0 ? `${character.name} is interested in ${character.topics.sort(() => 0.5 - Math.random()).slice(0, 5).map((topic2, index, array) => {
9751
+ const topicString = character.topics && character.topics.length > 0 ? character.topics[Math.floor(Math.random() * character.topics.length)] : null;
9752
+ const topic = topicString ? `${character.name} is currently interested in ${topicString}` : "";
9753
+ const topics = character.topics && character.topics.length > 0 ? `${character.name} is also interested in ${character.topics.filter((topic2) => topic2 !== topicString).sort(() => 0.5 - Math.random()).slice(0, 5).map((topic2, index, array) => {
9577
9754
  if (index === array.length - 2) {
9578
9755
  return `${topic2} and `;
9579
9756
  }
@@ -9582,7 +9759,8 @@ var characterProvider = {
9582
9759
  }
9583
9760
  return `${topic2}, `;
9584
9761
  }).join("")}` : "";
9585
- const adjective = character.adjectives && character.adjectives.length > 0 ? character.adjectives[Math.floor(Math.random() * character.adjectives.length)] : "";
9762
+ const adjectiveString = character.adjectives && character.adjectives.length > 0 ? character.adjectives[Math.floor(Math.random() * character.adjectives.length)] : "";
9763
+ const adjective = adjectiveString ? `${character.name} is ${adjectiveString}` : "";
9586
9764
  const formattedCharacterPostExamples = !character.postExamples ? "" : character.postExamples.sort(() => 0.5 - Math.random()).map((post) => {
9587
9765
  const messageString = `${post}`;
9588
9766
  return messageString;
@@ -9598,9 +9776,9 @@ var characterProvider = {
9598
9776
  );
9599
9777
  return example.map((message2) => {
9600
9778
  let messageString = `${message2.name}: ${message2.content.text}${message2.content.actions ? ` (actions: ${message2.content.actions.join(", ")})` : ""}`;
9601
- exampleNames.forEach((name2, index) => {
9602
- const placeholder = `{{user${index + 1}}}`;
9603
- messageString = messageString.replaceAll(placeholder, name2);
9779
+ exampleNames.forEach((name, index) => {
9780
+ const placeholder = `{{name${index + 1}}}`;
9781
+ messageString = messageString.replaceAll(placeholder, name);
9604
9782
  });
9605
9783
  return messageString;
9606
9784
  }).join("\n");
@@ -9643,18 +9821,38 @@ var characterProvider = {
9643
9821
  characterPostExamples,
9644
9822
  characterMessageExamples
9645
9823
  };
9646
- const text = [directions, examples].filter(Boolean).join("\n\n");
9824
+ const data = {
9825
+ bio,
9826
+ adjective,
9827
+ topic,
9828
+ topics,
9829
+ character,
9830
+ directions,
9831
+ examples,
9832
+ system
9833
+ };
9834
+ const text = [
9835
+ bio,
9836
+ adjective,
9837
+ topic,
9838
+ topics,
9839
+ adjective,
9840
+ directions,
9841
+ examples,
9842
+ system
9843
+ ].filter(Boolean).join("\n\n");
9647
9844
  return {
9648
9845
  values,
9846
+ data,
9649
9847
  text
9650
9848
  };
9651
- }
9849
+ }, "get")
9652
9850
  };
9653
9851
 
9654
9852
  // src/providers/choice.ts
9655
9853
  var choiceProvider = {
9656
9854
  name: "CHOICE",
9657
- get: async (runtime, message) => {
9855
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
9658
9856
  try {
9659
9857
  const pendingTasks = await runtime.getDatabaseAdapter().getTasks({
9660
9858
  roomId: message.roomId,
@@ -9732,7 +9930,7 @@ var choiceProvider = {
9732
9930
  text: "There was an error retrieving pending tasks with options."
9733
9931
  };
9734
9932
  }
9735
- }
9933
+ }, "get")
9736
9934
  };
9737
9935
 
9738
9936
  // src/providers/entities.ts
@@ -9746,10 +9944,12 @@ Data: ${JSON.stringify(entity.metadata)}
9746
9944
  });
9747
9945
  return entityStrings.join("\n");
9748
9946
  }
9947
+ __name(formatEntities, "formatEntities");
9749
9948
  var entitiesProvider = {
9750
9949
  name: "ENTITIES",
9751
- description: "Entities in the current conversation",
9752
- get: async (runtime, message) => {
9950
+ description: "People in the current conversation",
9951
+ dynamic: true,
9952
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
9753
9953
  const { roomId, entityId } = message;
9754
9954
  const entitiesData = await getEntityDetails({ runtime, roomId });
9755
9955
  const formattedEntities = formatEntities({ entities: entitiesData ?? [] });
@@ -9769,7 +9969,7 @@ var entitiesProvider = {
9769
9969
  values,
9770
9970
  text: entities
9771
9971
  };
9772
- }
9972
+ }, "get")
9773
9973
  };
9774
9974
 
9775
9975
  // src/providers/evaluators.ts
@@ -9777,6 +9977,7 @@ import { names as names3, uniqueNamesGenerator as uniqueNamesGenerator3 } from "
9777
9977
  function formatEvaluatorNames(evaluators) {
9778
9978
  return evaluators.map((evaluator) => `'${evaluator.name}'`).join(",\n");
9779
9979
  }
9980
+ __name(formatEvaluatorNames, "formatEvaluatorNames");
9780
9981
  function formatEvaluatorExamples(evaluators) {
9781
9982
  return evaluators.map((evaluator) => {
9782
9983
  return evaluator.examples.map((example) => {
@@ -9786,16 +9987,16 @@ function formatEvaluatorExamples(evaluators) {
9786
9987
  );
9787
9988
  let formattedPrompt = example.prompt;
9788
9989
  let formattedOutcome = example.outcome;
9789
- exampleNames.forEach((name2, index) => {
9790
- const placeholder = `{{user${index + 1}}}`;
9791
- formattedPrompt = formattedPrompt.replaceAll(placeholder, name2);
9792
- formattedOutcome = formattedOutcome.replaceAll(placeholder, name2);
9990
+ exampleNames.forEach((name, index) => {
9991
+ const placeholder = `{{name${index + 1}}}`;
9992
+ formattedPrompt = formattedPrompt.replaceAll(placeholder, name);
9993
+ formattedOutcome = formattedOutcome.replaceAll(placeholder, name);
9793
9994
  });
9794
9995
  const formattedMessages = example.messages.map((message) => {
9795
9996
  let messageString = `${message.name}: ${message.content.text}`;
9796
- exampleNames.forEach((name2, index) => {
9797
- const placeholder = `{{user${index + 1}}}`;
9798
- messageString = messageString.replaceAll(placeholder, name2);
9997
+ exampleNames.forEach((name, index) => {
9998
+ const placeholder = `{{name${index + 1}}}`;
9999
+ messageString = messageString.replaceAll(placeholder, name);
9799
10000
  });
9800
10001
  return messageString + (message.content.actions ? ` (${message.content.actions.join(", ")})` : "");
9801
10002
  }).join("\n");
@@ -9810,16 +10011,18 @@ ${formattedOutcome}`;
9810
10011
  }).join("\n\n");
9811
10012
  }).join("\n\n");
9812
10013
  }
10014
+ __name(formatEvaluatorExamples, "formatEvaluatorExamples");
9813
10015
  function formatEvaluators(evaluators) {
9814
10016
  return evaluators.map(
9815
10017
  (evaluator) => `'${evaluator.name}: ${evaluator.description}'`
9816
10018
  ).join(",\n");
9817
10019
  }
10020
+ __name(formatEvaluators, "formatEvaluators");
9818
10021
  var evaluatorsProvider = {
9819
10022
  name: "EVALUATORS",
9820
10023
  description: "Evaluators that can be used to evaluate the conversation after responding",
9821
10024
  private: true,
9822
- get: async (runtime, message, state) => {
10025
+ get: /* @__PURE__ */ __name(async (runtime, message, state) => {
9823
10026
  const evaluatorPromises = runtime.evaluators.map(
9824
10027
  async (evaluator) => {
9825
10028
  const result = await evaluator.validate(runtime, message, state);
@@ -9848,18 +10051,19 @@ var evaluatorsProvider = {
9848
10051
  values,
9849
10052
  text
9850
10053
  };
9851
- }
10054
+ }, "get")
9852
10055
  };
9853
10056
 
9854
10057
  // src/providers/facts.ts
9855
10058
  function formatFacts2(facts) {
9856
10059
  return facts.reverse().map((fact) => fact.content.text).join("\n");
9857
10060
  }
10061
+ __name(formatFacts2, "formatFacts");
9858
10062
  var factsProvider = {
9859
10063
  name: "FACTS",
9860
- description: "Key facts that {{agentName}} knows",
10064
+ description: "Key facts that the agent knows",
9861
10065
  dynamic: true,
9862
- get: async (runtime, message, _state) => {
10066
+ get: /* @__PURE__ */ __name(async (runtime, message, _state) => {
9863
10067
  const recentMessages = await runtime.getMemoryManager("messages").getMemories({
9864
10068
  roomId: message.roomId,
9865
10069
  count: 10,
@@ -9913,15 +10117,15 @@ var factsProvider = {
9913
10117
  },
9914
10118
  text
9915
10119
  };
9916
- }
10120
+ }, "get")
9917
10121
  };
9918
10122
 
9919
10123
  // src/providers/knowledge.ts
9920
10124
  var knowledgeProvider = {
9921
10125
  name: "KNOWLEDGE",
9922
- description: "Knowledge from the knowledge base that {{agentName}} knows",
10126
+ description: "Knowledge from the knowledge base that the agent knows",
9923
10127
  dynamic: true,
9924
- get: async (runtime, message) => {
10128
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
9925
10129
  const knowledgeData = await runtime.getKnowledge(message);
9926
10130
  const knowledge = knowledgeData && knowledgeData.length > 0 ? addHeader(
9927
10131
  "# Knowledge",
@@ -9936,23 +10140,58 @@ var knowledgeProvider = {
9936
10140
  },
9937
10141
  text: knowledge
9938
10142
  };
9939
- }
10143
+ }, "get")
10144
+ };
10145
+
10146
+ // src/providers/providers.ts
10147
+ var providersProvider = {
10148
+ name: "PROVIDERS",
10149
+ description: "List of all data providers the agent can use to get additional information",
10150
+ get: /* @__PURE__ */ __name(async (runtime, _message) => {
10151
+ const dynamicProviders = runtime.providers.filter(
10152
+ (provider) => provider.dynamic === true
10153
+ );
10154
+ const providerDescriptions = dynamicProviders.map((provider) => {
10155
+ return `- **${provider.name}**: ${provider.description || "No description available"}`;
10156
+ });
10157
+ const headerText = "# Providers\n\nThese providers are available for the agent to select and use:";
10158
+ if (providerDescriptions.length === 0) {
10159
+ return {
10160
+ text: addHeader(
10161
+ headerText,
10162
+ "No dynamic providers are currently available."
10163
+ )
10164
+ };
10165
+ }
10166
+ const providersText = providerDescriptions.join("\n");
10167
+ const text = addHeader(headerText, providersText);
10168
+ const data = {
10169
+ dynamicProviders: dynamicProviders.map((provider) => ({
10170
+ name: provider.name,
10171
+ description: provider.description || ""
10172
+ }))
10173
+ };
10174
+ return {
10175
+ text,
10176
+ data
10177
+ };
10178
+ }, "get")
9940
10179
  };
9941
10180
 
9942
10181
  // src/providers/recentMessages.ts
9943
- var getRecentInteractions2 = async (runtime, sourceEntityId, targetEntityId, excludeRoomId) => {
10182
+ var getRecentInteractions2 = /* @__PURE__ */ __name(async (runtime, sourceEntityId, targetEntityId, excludeRoomId) => {
9944
10183
  const rooms = await runtime.getDatabaseAdapter().getRoomsForParticipants([sourceEntityId, targetEntityId]);
9945
10184
  return runtime.getMemoryManager("messages").getMemoriesByRoomIds({
9946
10185
  // filter out the current room id from rooms
9947
10186
  roomIds: rooms.filter((room) => room !== excludeRoomId),
9948
10187
  limit: 20
9949
10188
  });
9950
- };
10189
+ }, "getRecentInteractions");
9951
10190
  var recentMessagesProvider = {
9952
10191
  name: "RECENT_MESSAGES",
9953
10192
  description: "Recent messages, interactions and other memories",
9954
10193
  position: 100,
9955
- get: async (runtime, message) => {
10194
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
9956
10195
  const { roomId } = message;
9957
10196
  const conversationLength = runtime.getConversationLength();
9958
10197
  const [entitiesData, room, recentMessagesData, recentInteractionsData] = await Promise.all([
@@ -10015,7 +10254,7 @@ var recentMessagesProvider = {
10015
10254
  });
10016
10255
  }
10017
10256
  }
10018
- const getRecentMessageInteractions = async (recentInteractionsData2) => {
10257
+ const getRecentMessageInteractions = /* @__PURE__ */ __name(async (recentInteractionsData2) => {
10019
10258
  const formattedInteractions = recentInteractionsData2.map((message2) => {
10020
10259
  const isSelf = message2.entityId === runtime.agentId;
10021
10260
  let sender;
@@ -10027,8 +10266,8 @@ var recentMessagesProvider = {
10027
10266
  return `${sender}: ${message2.content.text}`;
10028
10267
  });
10029
10268
  return formattedInteractions.join("\n");
10030
- };
10031
- const getRecentPostInteractions = async (recentInteractionsData2, entities) => {
10269
+ }, "getRecentMessageInteractions");
10270
+ const getRecentPostInteractions = /* @__PURE__ */ __name(async (recentInteractionsData2, entities) => {
10032
10271
  const combinedActors = [...entities];
10033
10272
  const actorIds = new Set(entities.map((entity) => entity.id));
10034
10273
  for (const [id, entity] of interactionEntityMap.entries()) {
@@ -10042,7 +10281,7 @@ var recentMessagesProvider = {
10042
10281
  conversationHeader: true
10043
10282
  });
10044
10283
  return formattedInteractions;
10045
- };
10284
+ }, "getRecentPostInteractions");
10046
10285
  const [recentMessageInteractions, recentPostInteractions] = await Promise.all([
10047
10286
  getRecentMessageInteractions(recentInteractionsData),
10048
10287
  getRecentPostInteractions(recentInteractionsData, entitiesData)
@@ -10064,7 +10303,7 @@ var recentMessagesProvider = {
10064
10303
  values,
10065
10304
  text
10066
10305
  };
10067
- }
10306
+ }, "get")
10068
10307
  };
10069
10308
 
10070
10309
  // src/providers/relationships.ts
@@ -10087,13 +10326,13 @@ async function formatRelationships(runtime, relationships) {
10087
10326
  entityMap.set(uniqueEntityIds[index], entity);
10088
10327
  }
10089
10328
  });
10090
- const formatMetadata = (metadata) => {
10329
+ const formatMetadata = /* @__PURE__ */ __name((metadata) => {
10091
10330
  return JSON.stringify(
10092
10331
  Object.entries(metadata).map(
10093
10332
  ([key, value]) => `${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`
10094
10333
  ).join("\n")
10095
10334
  );
10096
- };
10335
+ }, "formatMetadata");
10097
10336
  const formattedRelationships = sortedRelationships.map((rel) => {
10098
10337
  const targetEntityId = rel.targetEntityId;
10099
10338
  const entity = entityMap.get(targetEntityId);
@@ -10108,10 +10347,12 @@ ${formatMetadata(entity.metadata)}
10108
10347
  }).filter(Boolean);
10109
10348
  return formattedRelationships.join("\n");
10110
10349
  }
10350
+ __name(formatRelationships, "formatRelationships");
10111
10351
  var relationshipsProvider = {
10112
10352
  name: "RELATIONSHIPS",
10113
10353
  description: "Relationships between {{agentName}} and other people, or between other people that {{agentName}} has observed interacting with",
10114
- get: async (runtime, message) => {
10354
+ dynamic: true,
10355
+ get: /* @__PURE__ */ __name(async (runtime, message) => {
10115
10356
  const relationships = await runtime.getDatabaseAdapter().getRelationships({
10116
10357
  entityId: message.entityId
10117
10358
  });
@@ -10151,14 +10392,14 @@ var relationshipsProvider = {
10151
10392
  text: `# ${runtime.character.name} has observed ${message.content.senderName || message.content.name} interacting with these people:
10152
10393
  ${formattedRelationships}`
10153
10394
  };
10154
- }
10395
+ }, "get")
10155
10396
  };
10156
10397
 
10157
10398
  // src/providers/roles.ts
10158
10399
  var roleProvider = {
10159
10400
  name: "ROLES",
10160
10401
  description: "Roles in the server, default are OWNER, ADMIN and MEMBER (as well as NONE)",
10161
- get: async (runtime, message, state) => {
10402
+ get: /* @__PURE__ */ __name(async (runtime, message, state) => {
10162
10403
  const room = state.data.room ?? await runtime.getDatabaseAdapter().getRoom(message.roomId);
10163
10404
  if (!room) {
10164
10405
  throw new Error("No room found");
@@ -10215,7 +10456,7 @@ var roleProvider = {
10215
10456
  for (const entityId of Object.keys(roles)) {
10216
10457
  const userRole = roles[entityId];
10217
10458
  const user = await runtime.getDatabaseAdapter().getEntityById(entityId);
10218
- const name2 = user.metadata[room.source]?.name;
10459
+ const name = user.metadata[room.source]?.name;
10219
10460
  const username = user.metadata[room.source]?.username;
10220
10461
  const names4 = user.names;
10221
10462
  if (owners.some((owner) => owner.username === username) || admins.some((admin) => admin.username === username) || members.some((member) => member.username === username)) {
@@ -10223,13 +10464,13 @@ var roleProvider = {
10223
10464
  }
10224
10465
  switch (userRole) {
10225
10466
  case "OWNER":
10226
- owners.push({ name: name2, username, names: names4 });
10467
+ owners.push({ name, username, names: names4 });
10227
10468
  break;
10228
10469
  case "ADMIN":
10229
- admins.push({ name: name2, username, names: names4 });
10470
+ admins.push({ name, username, names: names4 });
10230
10471
  break;
10231
10472
  default:
10232
- members.push({ name: name2, username, names: names4 });
10473
+ members.push({ name, username, names: names4 });
10233
10474
  break;
10234
10475
  }
10235
10476
  }
@@ -10278,7 +10519,7 @@ var roleProvider = {
10278
10519
  text: "There was an error retrieving role information."
10279
10520
  };
10280
10521
  }
10281
- }
10522
+ }, "get")
10282
10523
  };
10283
10524
 
10284
10525
  // src/settings.ts
@@ -10298,32 +10539,68 @@ function createSettingFromConfig(configSetting) {
10298
10539
  visibleIf: configSetting.visibleIf || null
10299
10540
  };
10300
10541
  }
10542
+ __name(createSettingFromConfig, "createSettingFromConfig");
10301
10543
  function getSalt(runtime) {
10302
10544
  const secretSalt = process.env.SECRET_SALT || "secretsalt";
10303
- return secretSalt + runtime.agentId;
10545
+ const agentId = runtime.agentId;
10546
+ if (!agentId) {
10547
+ logger.warn("AgentId is missing when generating encryption salt");
10548
+ }
10549
+ const salt = secretSalt + (agentId || "");
10550
+ logger.debug(
10551
+ `Generated salt with length: ${salt.length} (truncated for security)`
10552
+ );
10553
+ return salt;
10304
10554
  }
10555
+ __name(getSalt, "getSalt");
10305
10556
  function saltSettingValue(setting, salt) {
10306
10557
  const settingCopy = { ...setting };
10307
10558
  if (setting.secret === true && typeof setting.value === "string" && setting.value) {
10308
- const key = crypto.createHash("sha256").update(salt).digest().slice(0, 32);
10309
- const iv = crypto.randomBytes(16);
10310
- const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
10311
- let encrypted = cipher.update(setting.value, "utf8", "hex");
10312
- encrypted += cipher.final("hex");
10313
- settingCopy.value = `${iv.toString("hex")}:${encrypted}`;
10559
+ try {
10560
+ const parts = setting.value.split(":");
10561
+ if (parts.length === 2) {
10562
+ try {
10563
+ const possibleIv = Buffer.from(parts[0], "hex");
10564
+ if (possibleIv.length === 16) {
10565
+ logger.debug(
10566
+ "Value appears to be already encrypted, skipping re-encryption"
10567
+ );
10568
+ return settingCopy;
10569
+ }
10570
+ } catch (e) {
10571
+ }
10572
+ }
10573
+ const key = crypto.createHash("sha256").update(salt).digest().slice(0, 32);
10574
+ const iv = crypto.randomBytes(16);
10575
+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
10576
+ let encrypted = cipher.update(setting.value, "utf8", "hex");
10577
+ encrypted += cipher.final("hex");
10578
+ settingCopy.value = `${iv.toString("hex")}:${encrypted}`;
10579
+ logger.debug(`Successfully encrypted value with IV length: ${iv.length}`);
10580
+ } catch (error) {
10581
+ logger.error(`Error encrypting setting value: ${error}`);
10582
+ }
10314
10583
  }
10315
10584
  return settingCopy;
10316
10585
  }
10586
+ __name(saltSettingValue, "saltSettingValue");
10317
10587
  function unsaltSettingValue(setting, salt) {
10318
10588
  const settingCopy = { ...setting };
10319
10589
  if (setting.secret === true && typeof setting.value === "string" && setting.value) {
10320
10590
  try {
10321
10591
  const parts = setting.value.split(":");
10322
10592
  if (parts.length !== 2) {
10323
- throw new Error("Invalid encrypted value format");
10593
+ logger.warn(
10594
+ `Invalid encrypted value format for setting - expected 'iv:encrypted'`
10595
+ );
10596
+ return settingCopy;
10324
10597
  }
10325
10598
  const iv = Buffer.from(parts[0], "hex");
10326
10599
  const encrypted = parts[1];
10600
+ if (iv.length !== 16) {
10601
+ logger.warn(`Invalid IV length (${iv.length}) - expected 16 bytes`);
10602
+ return settingCopy;
10603
+ }
10327
10604
  const key = crypto.createHash("sha256").update(salt).digest().slice(0, 32);
10328
10605
  const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
10329
10606
  let decrypted = decipher.update(encrypted, "hex", "utf8");
@@ -10335,6 +10612,7 @@ function unsaltSettingValue(setting, salt) {
10335
10612
  }
10336
10613
  return settingCopy;
10337
10614
  }
10615
+ __name(unsaltSettingValue, "unsaltSettingValue");
10338
10616
  function saltWorldSettings(worldSettings, salt) {
10339
10617
  const saltedSettings = {};
10340
10618
  for (const [key, setting] of Object.entries(worldSettings)) {
@@ -10342,6 +10620,7 @@ function saltWorldSettings(worldSettings, salt) {
10342
10620
  }
10343
10621
  return saltedSettings;
10344
10622
  }
10623
+ __name(saltWorldSettings, "saltWorldSettings");
10345
10624
  function unsaltWorldSettings(worldSettings, salt) {
10346
10625
  const unsaltedSettings = {};
10347
10626
  for (const [key, setting] of Object.entries(worldSettings)) {
@@ -10349,6 +10628,7 @@ function unsaltWorldSettings(worldSettings, salt) {
10349
10628
  }
10350
10629
  return unsaltedSettings;
10351
10630
  }
10631
+ __name(unsaltWorldSettings, "unsaltWorldSettings");
10352
10632
  async function updateWorldSettings2(runtime, serverId, worldSettings) {
10353
10633
  try {
10354
10634
  const worldId = createUniqueUuid(runtime, serverId);
@@ -10370,6 +10650,7 @@ async function updateWorldSettings2(runtime, serverId, worldSettings) {
10370
10650
  return false;
10371
10651
  }
10372
10652
  }
10653
+ __name(updateWorldSettings2, "updateWorldSettings");
10373
10654
  async function getWorldSettings2(runtime, serverId) {
10374
10655
  try {
10375
10656
  const worldId = createUniqueUuid(runtime, serverId);
@@ -10385,6 +10666,7 @@ async function getWorldSettings2(runtime, serverId) {
10385
10666
  return null;
10386
10667
  }
10387
10668
  }
10669
+ __name(getWorldSettings2, "getWorldSettings");
10388
10670
  async function initializeOnboarding(runtime, world, config2) {
10389
10671
  try {
10390
10672
  if (world.metadata?.settings) {
@@ -10413,16 +10695,17 @@ async function initializeOnboarding(runtime, world, config2) {
10413
10695
  return null;
10414
10696
  }
10415
10697
  }
10698
+ __name(initializeOnboarding, "initializeOnboarding");
10416
10699
 
10417
10700
  // src/providers/settings.ts
10418
- var formatSettingValue = (setting, isOnboarding) => {
10701
+ var formatSettingValue = /* @__PURE__ */ __name((setting, isOnboarding) => {
10419
10702
  if (setting.value === null) return "Not set";
10420
10703
  if (setting.secret && !isOnboarding) return "****************";
10421
10704
  return String(setting.value);
10422
- };
10705
+ }, "formatSettingValue");
10423
10706
  function generateStatusMessage(runtime, worldSettings, isOnboarding, state) {
10424
10707
  try {
10425
- const formattedSettings = Object.entries(worldSettings).map(([_key, setting]) => {
10708
+ const formattedSettings = Object.entries(worldSettings).map(([key, setting]) => {
10426
10709
  if (typeof setting !== "object" || !setting.name) return null;
10427
10710
  const description = setting.description || "";
10428
10711
  const usageDescription = setting.usageDescription || "";
@@ -10430,6 +10713,7 @@ function generateStatusMessage(runtime, worldSettings, isOnboarding, state) {
10430
10713
  return null;
10431
10714
  }
10432
10715
  return {
10716
+ key,
10433
10717
  name: setting.name,
10434
10718
  value: formatSettingValue(setting, isOnboarding),
10435
10719
  description,
@@ -10446,9 +10730,13 @@ function generateStatusMessage(runtime, worldSettings, isOnboarding, state) {
10446
10730
  return `# PRIORITY TASK: Onboarding with ${state.senderName}
10447
10731
  ${runtime.character.name} still needs to configure ${requiredUnconfigured} required settings:
10448
10732
 
10449
- ${formattedSettings.filter((s) => s.required && !s.configured).map((s) => `${s.name}: ${s.usageDescription}
10450
- Value: ${s.value}`).join(
10451
- "\n\n"
10733
+ ${formattedSettings.filter((s) => s.required && !s.configured).map((s) => `${s.key}: ${s.value}
10734
+ (${s.name}) ${s.usageDescription}`).join("\n\n")}
10735
+
10736
+ Valid settings keys: ${Object.keys(
10737
+ worldSettings
10738
+ ).join(
10739
+ ", "
10452
10740
  )}
10453
10741
 
10454
10742
  If the user gives any information related to the settings, ${runtime.character.name} should use the UPDATE_SETTINGS action to update the settings with this new information. ${runtime.character.name} can update any, some or all settings.`;
@@ -10472,10 +10760,11 @@ ${requiredUnconfigured > 0 ? `IMPORTANT!: ${requiredUnconfigured} required setti
10472
10760
  return "Error generating configuration status.";
10473
10761
  }
10474
10762
  }
10763
+ __name(generateStatusMessage, "generateStatusMessage");
10475
10764
  var settingsProvider = {
10476
10765
  name: "SETTINGS",
10477
10766
  description: "Current settings for the server",
10478
- get: async (runtime, message, state) => {
10767
+ get: /* @__PURE__ */ __name(async (runtime, message, state) => {
10479
10768
  try {
10480
10769
  const [room, userWorld] = await Promise.all([
10481
10770
  runtime.getDatabaseAdapter().getRoom(message.roomId),
@@ -10597,13 +10886,13 @@ var settingsProvider = {
10597
10886
  text: "Error retrieving configuration information. Please try again later."
10598
10887
  };
10599
10888
  }
10600
- }
10889
+ }, "get")
10601
10890
  };
10602
10891
 
10603
10892
  // src/providers/time.ts
10604
10893
  var timeProvider = {
10605
10894
  name: "TIME",
10606
- get: async (_runtime, _message) => {
10895
+ get: /* @__PURE__ */ __name(async (_runtime, _message) => {
10607
10896
  const currentDate = /* @__PURE__ */ new Date();
10608
10897
  const options2 = {
10609
10898
  timeZone: "UTC",
@@ -10622,210 +10911,70 @@ var timeProvider = {
10622
10911
  },
10623
10912
  text: `The current date and time is ${humanReadable}. Please use this as your reference for any time-based operations or responses.`
10624
10913
  };
10625
- }
10914
+ }, "get")
10626
10915
  };
10627
10916
 
10628
- // src/services/task.ts
10629
- var TaskService = class _TaskService extends Service {
10630
- timer = null;
10631
- TICK_INTERVAL = 1e3;
10632
- // Check every second
10633
- static serviceType = ServiceTypes.TASK;
10634
- capabilityDescription = "The agent is able to schedule and execute tasks";
10917
+ // src/services/scenario.ts
10918
+ import { v4 as uuidv42 } from "uuid";
10919
+ var ScenarioService = class _ScenarioService extends Service {
10920
+ /**
10921
+ * Constructor for creating a new instance of the class.
10922
+ *
10923
+ * @param runtime - The IAgentRuntime instance to be passed to the constructor.
10924
+ */
10925
+ constructor(runtime) {
10926
+ super(runtime);
10927
+ this.runtime = runtime;
10928
+ }
10929
+ static {
10930
+ __name(this, "ScenarioService");
10931
+ }
10932
+ static serviceType = "scenario";
10933
+ capabilityDescription = "The agent is currently in a scenario testing environment. It can create rooms, send messages, and talk to other agents in a live interactive testing environment.";
10934
+ messageHandlers = /* @__PURE__ */ new Map();
10935
+ rooms = /* @__PURE__ */ new Map();
10936
+ /**
10937
+ * Start the scenario service with the given runtime.
10938
+ * @param {IAgentRuntime} runtime - The agent runtime
10939
+ * @returns {Promise<ScenarioService>} - The started scenario service
10940
+ */
10635
10941
  static async start(runtime) {
10636
- const service = new _TaskService(runtime);
10637
- await service.startTimer();
10942
+ const service = new _ScenarioService(runtime);
10638
10943
  return service;
10639
10944
  }
10640
- async createTestTasks() {
10641
- this.runtime.registerTaskWorker({
10642
- name: "REPEATING_TEST_TASK",
10643
- validate: async (_runtime, _message, _state) => {
10644
- logger_default.debug("Validating repeating test task");
10645
- return true;
10646
- },
10647
- execute: async (_runtime, _options) => {
10648
- logger_default.debug("Executing repeating test task");
10649
- }
10650
- });
10651
- this.runtime.registerTaskWorker({
10652
- name: "ONETIME_TEST_TASK",
10653
- validate: async (_runtime, _message, _state) => {
10654
- logger_default.debug("Validating one-time test task");
10655
- return true;
10656
- },
10657
- execute: async (_runtime, _options) => {
10658
- logger_default.debug("Executing one-time test task");
10659
- }
10660
- });
10661
- const tasks = await this.runtime.getDatabaseAdapter().getTasksByName("REPEATING_TEST_TASK");
10662
- if (tasks.length === 0) {
10663
- await this.runtime.getDatabaseAdapter().createTask({
10664
- name: "REPEATING_TEST_TASK",
10665
- description: "A test task that repeats every minute",
10666
- metadata: {
10667
- updatedAt: Date.now(),
10668
- // Use timestamp instead of Date object
10669
- updateInterval: 1e3 * 60
10670
- // 1 minute
10671
- },
10672
- tags: ["queue", "repeat", "test"]
10673
- });
10945
+ /**
10946
+ * Stops the Scenario service associated with the given runtime.
10947
+ *
10948
+ * @param {IAgentRuntime} runtime The runtime to stop the service for.
10949
+ * @throws {Error} When the Scenario service is not found.
10950
+ */
10951
+ static async stop(runtime) {
10952
+ const service = runtime.getService(_ScenarioService.serviceType);
10953
+ if (!service) {
10954
+ throw new Error("Scenario service not found");
10674
10955
  }
10675
- await this.runtime.getDatabaseAdapter().createTask({
10676
- name: "ONETIME_TEST_TASK",
10677
- description: "A test task that runs once",
10678
- metadata: {
10679
- updatedAt: Date.now()
10680
- },
10681
- tags: ["queue", "test"]
10682
- });
10956
+ service.stop();
10683
10957
  }
10684
- startTimer() {
10685
- if (this.timer) {
10686
- clearInterval(this.timer);
10687
- }
10688
- this.timer = setInterval(async () => {
10689
- await this.checkTasks();
10690
- }, this.TICK_INTERVAL);
10691
- }
10692
- async validateTasks(tasks) {
10693
- const validatedTasks = [];
10694
- for (const task of tasks) {
10695
- if (!task.id) {
10696
- continue;
10697
- }
10698
- const worker = this.runtime.getTaskWorker(task.name);
10699
- if (!worker) {
10700
- continue;
10701
- }
10702
- if (worker.validate) {
10703
- try {
10704
- const isValid2 = await worker.validate(
10705
- this.runtime,
10706
- {},
10707
- {}
10708
- );
10709
- if (!isValid2) {
10710
- continue;
10711
- }
10712
- } catch (error) {
10713
- logger_default.error(`Error validating task ${task.name}:`, error);
10714
- continue;
10715
- }
10716
- }
10717
- validatedTasks.push(task);
10718
- }
10719
- return validatedTasks;
10720
- }
10721
- async checkTasks() {
10722
- try {
10723
- const allTasks = await this.runtime.getDatabaseAdapter().getTasks({
10724
- tags: ["queue"]
10725
- });
10726
- const tasks = await this.validateTasks(allTasks);
10727
- if (tasks.length > 0) {
10728
- logger_default.debug(`Found ${tasks.length} queued tasks`);
10729
- }
10730
- const now = Date.now();
10731
- for (const task of tasks) {
10732
- const taskStartTime = new Date(task.updatedAt || 0).getTime();
10733
- const updateIntervalMs = task.metadata.updateInterval ?? 0;
10734
- if (!task.tags?.includes("repeat")) {
10735
- await this.executeTask(task);
10736
- continue;
10737
- }
10738
- if (now - taskStartTime >= updateIntervalMs) {
10739
- logger_default.debug(
10740
- `Executing task ${task.name} - interval of ${updateIntervalMs}ms has elapsed`
10741
- );
10742
- await this.executeTask(task);
10743
- }
10744
- }
10745
- } catch (error) {
10746
- logger_default.error("Error checking tasks:", error);
10747
- }
10748
- }
10749
- async executeTask(task) {
10750
- try {
10751
- if (!task) {
10752
- logger_default.debug(`Task ${task.id} not found`);
10753
- return;
10754
- }
10755
- const worker = this.runtime.getTaskWorker(task.name);
10756
- if (!worker) {
10757
- logger_default.debug(`No worker found for task type: ${task.name}`);
10758
- return;
10759
- }
10760
- logger_default.debug(`Executing task ${task.name} (${task.id})`);
10761
- await worker.execute(this.runtime, task.metadata || {});
10762
- logger_default.debug("task.tags are", task.tags);
10763
- if (task.tags?.includes("repeat")) {
10764
- await this.runtime.getDatabaseAdapter().updateTask(task.id, {
10765
- metadata: {
10766
- ...task.metadata,
10767
- updatedAt: Date.now()
10768
- }
10769
- });
10770
- logger_default.debug(
10771
- `Updated repeating task ${task.name} (${task.id}) with new timestamp`
10772
- );
10773
- } else {
10774
- await this.runtime.getDatabaseAdapter().deleteTask(task.id);
10775
- logger_default.debug(
10776
- `Deleted non-repeating task ${task.name} (${task.id}) after execution`
10777
- );
10778
- }
10779
- } catch (error) {
10780
- logger_default.error(`Error executing task ${task.id}:`, error);
10781
- }
10782
- }
10783
- static async stop(runtime) {
10784
- const service = runtime.getService(ServiceTypes.TASK);
10785
- if (service) {
10786
- await service.stop();
10787
- }
10788
- }
10789
- async stop() {
10790
- if (this.timer) {
10791
- clearInterval(this.timer);
10792
- this.timer = null;
10793
- }
10794
- }
10795
- };
10796
-
10797
- // src/services/scenario.ts
10798
- import { v4 as uuidv42 } from "uuid";
10799
- var ScenarioService = class _ScenarioService extends Service {
10800
- constructor(runtime) {
10801
- super(runtime);
10802
- this.runtime = runtime;
10803
- }
10804
- static serviceType = "scenario";
10805
- capabilityDescription = "The agent is currently in a scenario testing environment. It can create rooms, send messages, and talk to other agents in a live interactive testing environment.";
10806
- messageHandlers = /* @__PURE__ */ new Map();
10807
- rooms = /* @__PURE__ */ new Map();
10808
- static async start(runtime) {
10809
- const service = new _ScenarioService(runtime);
10810
- return service;
10811
- }
10812
- static async stop(runtime) {
10813
- const service = runtime.getService(_ScenarioService.serviceType);
10814
- if (!service) {
10815
- throw new Error("Scenario service not found");
10816
- }
10817
- service.stop();
10818
- }
10819
- async stop() {
10820
- this.messageHandlers.clear();
10821
- this.rooms.clear();
10958
+ /**
10959
+ * Asynchronously stops the current process by clearing all message handlers and rooms.
10960
+ */
10961
+ async stop() {
10962
+ this.messageHandlers.clear();
10963
+ this.rooms.clear();
10822
10964
  }
10823
10965
  // Create a room for an agent
10824
- async createRoom(agentId, name2) {
10966
+ /**
10967
+ * Creates a room for the specified agent with the given agentId and optional name.
10968
+ *
10969
+ * @param {string} agentId The ID of the agent for whom the room is being created.
10970
+ * @param {string} [name] Optional. The name of the room. If not provided, a default name will be generated.
10971
+ * @returns {Promise<void>} A promise that resolves once the room has been created.
10972
+ */
10973
+ async createRoom(agentId, name) {
10825
10974
  const roomId = uuidv42();
10826
10975
  await this.runtime.ensureRoomExists({
10827
10976
  id: roomId,
10828
- name: name2 || `Room for ${agentId}`,
10977
+ name: name || `Room for ${agentId}`,
10829
10978
  source: "scenario",
10830
10979
  type: "GROUP" /* GROUP */,
10831
10980
  channelId: roomId,
@@ -10834,6 +10983,14 @@ var ScenarioService = class _ScenarioService extends Service {
10834
10983
  this.rooms.set(agentId, { roomId });
10835
10984
  }
10836
10985
  // Save a message in all agents' memory without emitting events
10986
+ /**
10987
+ * Saves a message from a sender to multiple receivers.
10988
+ *
10989
+ * @param {IAgentRuntime} sender - The agent sending the message.
10990
+ * @param {IAgentRuntime[]} receivers - The agents receiving the message.
10991
+ * @param {string} text - The text of the message.
10992
+ * @returns {Promise<void>} - A Promise that resolves when the message is successfully saved for all receivers.
10993
+ */
10837
10994
  async saveMessage(sender, receivers, text) {
10838
10995
  for (const receiver of receivers) {
10839
10996
  const roomData = this.rooms.get(receiver.agentId);
@@ -10863,6 +11020,13 @@ var ScenarioService = class _ScenarioService extends Service {
10863
11020
  }
10864
11021
  }
10865
11022
  // Send a live message that triggers handlers
11023
+ /**
11024
+ * Send a message to the specified receivers.
11025
+ *
11026
+ * @param {IAgentRuntime} sender - The agent sending the message.
11027
+ * @param {IAgentRuntime[]} receivers - The agents receiving the message.
11028
+ * @param {string} text - The text content of the message.
11029
+ */
10866
11030
  async sendMessage(sender, receivers, text) {
10867
11031
  for (const receiver of receivers) {
10868
11032
  const roomData = this.rooms.get(receiver.agentId);
@@ -10910,6 +11074,11 @@ var ScenarioService = class _ScenarioService extends Service {
10910
11074
  }
10911
11075
  }
10912
11076
  // Get conversation history for all participants
11077
+ /**
11078
+ * Asynchronously retrieves conversations for the given participants.
11079
+ * @param {IAgentRuntime[]} participants - List of participants for whom to retrieve conversations
11080
+ * @returns {Promise<IMessageMemory[][]>} - Promise that resolves to an array of arrays of message memories for each participant
11081
+ */
10913
11082
  async getConversations(participants) {
10914
11083
  const conversations = await Promise.all(
10915
11084
  participants.map(async (member) => {
@@ -10932,9 +11101,220 @@ ${participants[i].character.name}'s perspective:`);
10932
11101
  }
10933
11102
  };
10934
11103
 
11104
+ // src/services/task.ts
11105
+ var TaskService = class _TaskService extends Service {
11106
+ static {
11107
+ __name(this, "TaskService");
11108
+ }
11109
+ timer = null;
11110
+ TICK_INTERVAL = 1e3;
11111
+ // Check every second
11112
+ static serviceType = ServiceTypes.TASK;
11113
+ capabilityDescription = "The agent is able to schedule and execute tasks";
11114
+ /**
11115
+ * Start the TaskService with the given runtime.
11116
+ * @param {IAgentRuntime} runtime - The runtime for the TaskService.
11117
+ * @returns {Promise<TaskService>} A promise that resolves with the TaskService instance.
11118
+ */
11119
+ static async start(runtime) {
11120
+ const service = new _TaskService(runtime);
11121
+ await service.startTimer();
11122
+ return service;
11123
+ }
11124
+ /**
11125
+ * Asynchronously creates test tasks by registering task workers for repeating and one-time tasks,
11126
+ * validates the tasks, executes the tasks, and creates the tasks if they do not already exist.
11127
+ */
11128
+ async createTestTasks() {
11129
+ this.runtime.registerTaskWorker({
11130
+ name: "REPEATING_TEST_TASK",
11131
+ validate: /* @__PURE__ */ __name(async (_runtime, _message, _state) => {
11132
+ logger_default.debug("Validating repeating test task");
11133
+ return true;
11134
+ }, "validate"),
11135
+ execute: /* @__PURE__ */ __name(async (_runtime, _options) => {
11136
+ logger_default.debug("Executing repeating test task");
11137
+ }, "execute")
11138
+ });
11139
+ this.runtime.registerTaskWorker({
11140
+ name: "ONETIME_TEST_TASK",
11141
+ validate: /* @__PURE__ */ __name(async (_runtime, _message, _state) => {
11142
+ logger_default.debug("Validating one-time test task");
11143
+ return true;
11144
+ }, "validate"),
11145
+ execute: /* @__PURE__ */ __name(async (_runtime, _options) => {
11146
+ logger_default.debug("Executing one-time test task");
11147
+ }, "execute")
11148
+ });
11149
+ const tasks = await this.runtime.getDatabaseAdapter().getTasksByName("REPEATING_TEST_TASK");
11150
+ if (tasks.length === 0) {
11151
+ await this.runtime.getDatabaseAdapter().createTask({
11152
+ name: "REPEATING_TEST_TASK",
11153
+ description: "A test task that repeats every minute",
11154
+ metadata: {
11155
+ updatedAt: Date.now(),
11156
+ // Use timestamp instead of Date object
11157
+ updateInterval: 1e3 * 60
11158
+ // 1 minute
11159
+ },
11160
+ tags: ["queue", "repeat", "test"]
11161
+ });
11162
+ }
11163
+ await this.runtime.getDatabaseAdapter().createTask({
11164
+ name: "ONETIME_TEST_TASK",
11165
+ description: "A test task that runs once",
11166
+ metadata: {
11167
+ updatedAt: Date.now()
11168
+ },
11169
+ tags: ["queue", "test"]
11170
+ });
11171
+ }
11172
+ /**
11173
+ * Starts a timer that runs a function to check tasks at a specified interval.
11174
+ */
11175
+ startTimer() {
11176
+ if (this.timer) {
11177
+ clearInterval(this.timer);
11178
+ }
11179
+ this.timer = setInterval(async () => {
11180
+ await this.checkTasks();
11181
+ }, this.TICK_INTERVAL);
11182
+ }
11183
+ /**
11184
+ * Validates an array of Task objects.
11185
+ * Skips tasks without IDs or if no worker is found for the task.
11186
+ * If a worker has a `validate` function, it will run the validation using the `runtime`, `Memory`, and `State` parameters.
11187
+ * If the validation fails, the task will be skipped and the error will be logged.
11188
+ * @param {Task[]} tasks - An array of Task objects to validate.
11189
+ * @returns {Promise<Task[]>} - A Promise that resolves with an array of validated Task objects.
11190
+ */
11191
+ async validateTasks(tasks) {
11192
+ const validatedTasks = [];
11193
+ for (const task of tasks) {
11194
+ if (!task.id) {
11195
+ continue;
11196
+ }
11197
+ const worker = this.runtime.getTaskWorker(task.name);
11198
+ if (!worker) {
11199
+ continue;
11200
+ }
11201
+ if (worker.validate) {
11202
+ try {
11203
+ const isValid2 = await worker.validate(
11204
+ this.runtime,
11205
+ {},
11206
+ {}
11207
+ );
11208
+ if (!isValid2) {
11209
+ continue;
11210
+ }
11211
+ } catch (error) {
11212
+ logger_default.error(`Error validating task ${task.name}:`, error);
11213
+ continue;
11214
+ }
11215
+ }
11216
+ validatedTasks.push(task);
11217
+ }
11218
+ return validatedTasks;
11219
+ }
11220
+ /**
11221
+ * Asynchronous method that checks tasks with "queue" tag, validates and sorts them, then executes them based on interval and tags.
11222
+ *
11223
+ * @returns {Promise<void>} Promise that resolves once all tasks are checked and executed
11224
+ */
11225
+ async checkTasks() {
11226
+ try {
11227
+ const allTasks = await this.runtime.getDatabaseAdapter().getTasks({
11228
+ tags: ["queue"]
11229
+ });
11230
+ const tasks = await this.validateTasks(allTasks);
11231
+ if (tasks.length > 0) {
11232
+ logger_default.debug(`Found ${tasks.length} queued tasks`);
11233
+ }
11234
+ const now = Date.now();
11235
+ for (const task of tasks) {
11236
+ const taskStartTime = new Date(task.updatedAt || 0).getTime();
11237
+ const updateIntervalMs = task.metadata.updateInterval ?? 0;
11238
+ if (!task.tags?.includes("repeat")) {
11239
+ await this.executeTask(task);
11240
+ continue;
11241
+ }
11242
+ if (now - taskStartTime >= updateIntervalMs) {
11243
+ logger_default.debug(
11244
+ `Executing task ${task.name} - interval of ${updateIntervalMs}ms has elapsed`
11245
+ );
11246
+ await this.executeTask(task);
11247
+ }
11248
+ }
11249
+ } catch (error) {
11250
+ logger_default.error("Error checking tasks:", error);
11251
+ }
11252
+ }
11253
+ /**
11254
+ * Executes a given task asynchronously.
11255
+ *
11256
+ * @param {Task} task - The task to be executed.
11257
+ */
11258
+ async executeTask(task) {
11259
+ try {
11260
+ if (!task) {
11261
+ logger_default.debug(`Task ${task.id} not found`);
11262
+ return;
11263
+ }
11264
+ const worker = this.runtime.getTaskWorker(task.name);
11265
+ if (!worker) {
11266
+ logger_default.debug(`No worker found for task type: ${task.name}`);
11267
+ return;
11268
+ }
11269
+ logger_default.debug(`Executing task ${task.name} (${task.id})`);
11270
+ await worker.execute(this.runtime, task.metadata || {}, task);
11271
+ logger_default.debug("task.tags are", task.tags);
11272
+ if (task.tags?.includes("repeat")) {
11273
+ await this.runtime.getDatabaseAdapter().updateTask(task.id, {
11274
+ metadata: {
11275
+ ...task.metadata,
11276
+ updatedAt: Date.now()
11277
+ }
11278
+ });
11279
+ logger_default.debug(
11280
+ `Updated repeating task ${task.name} (${task.id}) with new timestamp`
11281
+ );
11282
+ } else {
11283
+ await this.runtime.getDatabaseAdapter().deleteTask(task.id);
11284
+ logger_default.debug(
11285
+ `Deleted non-repeating task ${task.name} (${task.id}) after execution`
11286
+ );
11287
+ }
11288
+ } catch (error) {
11289
+ logger_default.error(`Error executing task ${task.id}:`, error);
11290
+ }
11291
+ }
11292
+ /**
11293
+ * Stops the TASK service in the given agent runtime.
11294
+ *
11295
+ * @param {IAgentRuntime} runtime - The agent runtime containing the service.
11296
+ * @returns {Promise<void>} - A promise that resolves once the service has been stopped.
11297
+ */
11298
+ static async stop(runtime) {
11299
+ const service = runtime.getService(ServiceTypes.TASK);
11300
+ if (service) {
11301
+ await service.stop();
11302
+ }
11303
+ }
11304
+ /**
11305
+ * Stops the timer if it is currently running.
11306
+ */
11307
+ async stop() {
11308
+ if (this.timer) {
11309
+ clearInterval(this.timer);
11310
+ this.timer = null;
11311
+ }
11312
+ }
11313
+ };
11314
+
10935
11315
  // src/bootstrap.ts
10936
11316
  var latestResponseIds = /* @__PURE__ */ new Map();
10937
- var messageReceivedHandler = async ({
11317
+ var messageReceivedHandler = /* @__PURE__ */ __name(async ({
10938
11318
  runtime,
10939
11319
  message,
10940
11320
  callback
@@ -10968,9 +11348,17 @@ var messageReceivedHandler = async ({
10968
11348
  state,
10969
11349
  template: runtime.character.templates?.shouldRespondTemplate || shouldRespondTemplate
10970
11350
  });
11351
+ logger.debug(
11352
+ `*** Should Respond Prompt for ${runtime.character.name} ***`,
11353
+ shouldRespondPrompt
11354
+ );
10971
11355
  const response = await runtime.useModel(ModelTypes.TEXT_SMALL, {
10972
11356
  prompt: shouldRespondPrompt
10973
11357
  });
11358
+ logger.debug(
11359
+ `*** Should Respond Response for ${runtime.character.name} ***`,
11360
+ response
11361
+ );
10974
11362
  const responseObject = parseJSONObjectFromText(response);
10975
11363
  const providers = responseObject.providers;
10976
11364
  const shouldRespond = responseObject?.action && responseObject.action === "RESPOND";
@@ -11038,8 +11426,8 @@ var messageReceivedHandler = async ({
11038
11426
  callback,
11039
11427
  responseMessages
11040
11428
  );
11041
- };
11042
- var reactionReceivedHandler = async ({
11429
+ }, "messageReceivedHandler");
11430
+ var reactionReceivedHandler = /* @__PURE__ */ __name(async ({
11043
11431
  runtime,
11044
11432
  message
11045
11433
  }) => {
@@ -11052,8 +11440,8 @@ var reactionReceivedHandler = async ({
11052
11440
  }
11053
11441
  logger.error("Error in reaction handler:", error);
11054
11442
  }
11055
- };
11056
- var syncSingleUser = async (entityId, runtime, user, serverId, channelId, type, source) => {
11443
+ }, "reactionReceivedHandler");
11444
+ var syncSingleUser = /* @__PURE__ */ __name(async (entityId, runtime, user, serverId, channelId, type, source) => {
11057
11445
  logger.info(`Syncing user: ${user.username || user.id}`);
11058
11446
  try {
11059
11447
  if (!channelId) {
@@ -11079,8 +11467,8 @@ var syncSingleUser = async (entityId, runtime, user, serverId, channelId, type,
11079
11467
  `Error syncing user: ${error instanceof Error ? error.message : String(error)}`
11080
11468
  );
11081
11469
  }
11082
- };
11083
- var handleServerSync = async ({
11470
+ }, "syncSingleUser");
11471
+ var handleServerSync = /* @__PURE__ */ __name(async ({
11084
11472
  runtime,
11085
11473
  world,
11086
11474
  rooms,
@@ -11150,7 +11538,7 @@ var handleServerSync = async ({
11150
11538
  `Error processing standardized server data: ${error instanceof Error ? error.message : String(error)}`
11151
11539
  );
11152
11540
  }
11153
- };
11541
+ }, "handleServerSync");
11154
11542
  var events = {
11155
11543
  MESSAGE_RECEIVED: [
11156
11544
  async ({ runtime, message, callback }) => {
@@ -11200,6 +11588,7 @@ var bootstrapPlugin = {
11200
11588
  name: "bootstrap",
11201
11589
  description: "Agent bootstrap with basic actions and evaluators",
11202
11590
  actions: [
11591
+ replyAction,
11203
11592
  followRoomAction,
11204
11593
  unfollowRoomAction,
11205
11594
  ignoreAction,
@@ -11210,17 +11599,15 @@ var bootstrapPlugin = {
11210
11599
  updateEntityAction,
11211
11600
  choiceAction,
11212
11601
  roles_default,
11213
- settings_default,
11214
- replyAction
11602
+ settings_default
11215
11603
  ],
11216
11604
  events,
11217
- evaluators: [reflectionEvaluator, goalEvaluator],
11605
+ evaluators: [reflectionEvaluator, goalAction],
11218
11606
  providers: [
11219
11607
  evaluatorsProvider,
11220
11608
  anxietyProvider,
11221
11609
  knowledgeProvider,
11222
11610
  timeProvider,
11223
- characterProvider,
11224
11611
  entitiesProvider,
11225
11612
  relationshipsProvider,
11226
11613
  choiceProvider,
@@ -11231,6 +11618,7 @@ var bootstrapPlugin = {
11231
11618
  attachmentsProvider,
11232
11619
  providersProvider,
11233
11620
  actionsProvider,
11621
+ characterProvider,
11234
11622
  recentMessagesProvider
11235
11623
  ],
11236
11624
  services: [TaskService, ScenarioService]
@@ -11243,6 +11631,7 @@ function validateUuid(value) {
11243
11631
  const result = uuidSchema.safeParse(value);
11244
11632
  return result.success ? result.data : null;
11245
11633
  }
11634
+ __name(validateUuid, "validateUuid");
11246
11635
  function stringToUuid(target) {
11247
11636
  if (typeof target === "number") {
11248
11637
  target = target.toString();
@@ -11250,19 +11639,19 @@ function stringToUuid(target) {
11250
11639
  if (typeof target !== "string") {
11251
11640
  throw TypeError("Value must be string");
11252
11641
  }
11253
- const _uint8ToHex = (ubyte) => {
11642
+ const _uint8ToHex = /* @__PURE__ */ __name((ubyte) => {
11254
11643
  const first = ubyte >> 4;
11255
11644
  const second = ubyte - (first << 4);
11256
11645
  const HEX_DIGITS = "0123456789abcdef".split("");
11257
11646
  return HEX_DIGITS[first] + HEX_DIGITS[second];
11258
- };
11259
- const _uint8ArrayToHex = (buf) => {
11647
+ }, "_uint8ToHex");
11648
+ const _uint8ArrayToHex = /* @__PURE__ */ __name((buf) => {
11260
11649
  let out = "";
11261
11650
  for (let i = 0; i < buf.length; i++) {
11262
11651
  out += _uint8ToHex(buf[i]);
11263
11652
  }
11264
11653
  return out;
11265
- };
11654
+ }, "_uint8ArrayToHex");
11266
11655
  const escapedStr = encodeURIComponent(target);
11267
11656
  const buffer = new Uint8Array(escapedStr.length);
11268
11657
  for (let i = 0; i < escapedStr.length; i++) {
@@ -11275,9 +11664,13 @@ function stringToUuid(target) {
11275
11664
  }
11276
11665
  return `${_uint8ArrayToHex(hashBuffer.slice(0, 4))}-${_uint8ArrayToHex(hashBuffer.slice(4, 6))}-${_uint8ToHex(hashBuffer[6] & 15)}${_uint8ToHex(hashBuffer[7])}-${_uint8ToHex(hashBuffer[8] & 63 | 128)}${_uint8ToHex(hashBuffer[9])}-${_uint8ArrayToHex(hashBuffer.slice(10, 16))}`;
11277
11666
  }
11667
+ __name(stringToUuid, "stringToUuid");
11278
11668
 
11279
11669
  // src/runtime.ts
11280
11670
  var AgentRuntime = class {
11671
+ static {
11672
+ __name(this, "AgentRuntime");
11673
+ }
11281
11674
  #conversationLength = 32;
11282
11675
  agentId;
11283
11676
  character;
@@ -11290,7 +11683,7 @@ var AgentRuntime = class {
11290
11683
  stateCache = /* @__PURE__ */ new Map();
11291
11684
  fetch = fetch;
11292
11685
  services = /* @__PURE__ */ new Map();
11293
- adapters;
11686
+ adapter;
11294
11687
  knowledgeRoot;
11295
11688
  models = /* @__PURE__ */ new Map();
11296
11689
  routes = [];
@@ -11307,7 +11700,7 @@ var AgentRuntime = class {
11307
11700
  }
11308
11701
  logger.success(`Agent ID: ${this.agentId}`);
11309
11702
  this.fetch = opts.fetch ?? this.fetch;
11310
- this.adapters = opts.adapters ?? [];
11703
+ this.adapter = opts.adapter;
11311
11704
  const plugins = opts?.plugins ?? [];
11312
11705
  if (!opts?.ignoreBootstrap) {
11313
11706
  plugins.push(bootstrapPlugin);
@@ -11320,15 +11713,15 @@ var AgentRuntime = class {
11320
11713
  */
11321
11714
  async registerPlugin(plugin) {
11322
11715
  if (!plugin) {
11716
+ console.log("*** registerPlugin plugin is undefined");
11323
11717
  return;
11324
11718
  }
11719
+ console.log("*** registerPlugin plugin", plugin);
11325
11720
  if (!this.plugins.some((p) => p.name === plugin.name)) {
11326
11721
  this.plugins.push(plugin);
11327
11722
  }
11328
- if (plugin.adapters) {
11329
- for (const adapter of plugin.adapters) {
11330
- this.adapters.push(adapter);
11331
- }
11723
+ if (plugin.adapter) {
11724
+ this.registerDatabaseAdapter(plugin.adapter);
11332
11725
  }
11333
11726
  if (plugin.actions) {
11334
11727
  for (const action of plugin.actions) {
@@ -11385,6 +11778,26 @@ var AgentRuntime = class {
11385
11778
  }
11386
11779
  }
11387
11780
  async initialize() {
11781
+ const registeredPluginNames = /* @__PURE__ */ new Set();
11782
+ const pluginRegistrationPromises = [];
11783
+ if (this.character.plugins) {
11784
+ const characterPlugins = await handlePluginImporting(
11785
+ this.character.plugins
11786
+ );
11787
+ for (const plugin of characterPlugins) {
11788
+ if (plugin && !registeredPluginNames.has(plugin.name)) {
11789
+ registeredPluginNames.add(plugin.name);
11790
+ pluginRegistrationPromises.push(this.registerPlugin(plugin));
11791
+ }
11792
+ }
11793
+ }
11794
+ for (const plugin of [...this.plugins]) {
11795
+ if (plugin && !registeredPluginNames.has(plugin.name)) {
11796
+ registeredPluginNames.add(plugin.name);
11797
+ pluginRegistrationPromises.push(this.registerPlugin(plugin));
11798
+ }
11799
+ }
11800
+ await this.getDatabaseAdapter().init();
11388
11801
  try {
11389
11802
  await this.getDatabaseAdapter().ensureAgentExists(
11390
11803
  this.character
@@ -11414,25 +11827,6 @@ var AgentRuntime = class {
11414
11827
  );
11415
11828
  throw error;
11416
11829
  }
11417
- const registeredPluginNames = /* @__PURE__ */ new Set();
11418
- const pluginRegistrationPromises = [];
11419
- if (this.character.plugins) {
11420
- const characterPlugins = await handlePluginImporting(
11421
- this.character.plugins
11422
- );
11423
- for (const plugin of characterPlugins) {
11424
- if (plugin && !registeredPluginNames.has(plugin.name)) {
11425
- registeredPluginNames.add(plugin.name);
11426
- pluginRegistrationPromises.push(this.registerPlugin(plugin));
11427
- }
11428
- }
11429
- }
11430
- for (const plugin of [...this.plugins]) {
11431
- if (plugin && !registeredPluginNames.has(plugin.name)) {
11432
- registeredPluginNames.add(plugin.name);
11433
- pluginRegistrationPromises.push(this.registerPlugin(plugin));
11434
- }
11435
- }
11436
11830
  try {
11437
11831
  await Promise.all([
11438
11832
  this.ensureRoomExists({
@@ -11626,13 +12020,16 @@ var AgentRuntime = class {
11626
12020
  return this.#conversationLength;
11627
12021
  }
11628
12022
  registerDatabaseAdapter(adapter) {
11629
- this.adapters.push(adapter);
11630
- }
11631
- getDatabaseAdapters() {
11632
- return this.adapters;
12023
+ if (this.adapter) {
12024
+ logger.warn(
12025
+ "Database adapter already registered. Additional adapters will be ignored. This may lead to unexpected behavior."
12026
+ );
12027
+ } else {
12028
+ this.adapter = adapter;
12029
+ }
11633
12030
  }
11634
12031
  getDatabaseAdapter() {
11635
- return this.adapters[0];
12032
+ return this.adapter;
11636
12033
  }
11637
12034
  /**
11638
12035
  * Register a provider for the agent to use.
@@ -11649,7 +12046,13 @@ var AgentRuntime = class {
11649
12046
  logger.success(
11650
12047
  `${this.character.name}(${this.agentId}) - Registering action: ${action.name}`
11651
12048
  );
11652
- this.actions.push(action);
12049
+ if (this.actions.find((a) => a.name === action.name)) {
12050
+ logger.warn(
12051
+ `${this.character.name}(${this.agentId}) - Action ${action.name} already exists. Skipping registration.`
12052
+ );
12053
+ } else {
12054
+ this.actions.push(action);
12055
+ }
11653
12056
  }
11654
12057
  /**
11655
12058
  * Register an evaluator to assess and guide the agent's responses.
@@ -11677,6 +12080,7 @@ var AgentRuntime = class {
11677
12080
  let normalizeAction = function(action) {
11678
12081
  return action.toLowerCase().replace("_", "");
11679
12082
  };
12083
+ __name(normalizeAction, "normalizeAction");
11680
12084
  if (!response.content?.actions || response.content.actions.length === 0) {
11681
12085
  logger.warn("No action found in the response content.");
11682
12086
  continue;
@@ -11722,10 +12126,10 @@ var AgentRuntime = class {
11722
12126
  logger.error(`Action ${action.name} has no handler.`);
11723
12127
  continue;
11724
12128
  }
11725
- logger.success(`Executing handler for action: ${action.name}`);
11726
12129
  try {
11727
12130
  logger.info(`Executing handler for action: ${action.name}`);
11728
12131
  await action.handler(this, message, state, {}, callback, responses);
12132
+ logger.success(`Action ${action.name} executed successfully.`);
11729
12133
  await this.getDatabaseAdapter().log({
11730
12134
  entityId: message.entityId,
11731
12135
  roomId: message.roomId,
@@ -11832,7 +12236,7 @@ var AgentRuntime = class {
11832
12236
  entityId,
11833
12237
  roomId,
11834
12238
  userName,
11835
- name: name2,
12239
+ name,
11836
12240
  source,
11837
12241
  type,
11838
12242
  channelId,
@@ -11845,10 +12249,10 @@ var AgentRuntime = class {
11845
12249
  if (!worldId && serverId) {
11846
12250
  worldId = createUniqueUuid(this, serverId);
11847
12251
  }
11848
- const names4 = [name2, userName];
12252
+ const names4 = [name, userName];
11849
12253
  const metadata = {
11850
12254
  [source]: {
11851
- name: name2,
12255
+ name,
11852
12256
  userName
11853
12257
  }
11854
12258
  };
@@ -11891,19 +12295,19 @@ var AgentRuntime = class {
11891
12295
  /**
11892
12296
  * Ensure the existence of a world.
11893
12297
  */
11894
- async ensureWorldExists({ id, name: name2, serverId, metadata }) {
12298
+ async ensureWorldExists({ id, name, serverId, metadata }) {
11895
12299
  try {
11896
12300
  const world = await this.getDatabaseAdapter().getWorld(id);
11897
12301
  if (!world) {
11898
12302
  logger.info("Creating world:", {
11899
12303
  id,
11900
- name: name2,
12304
+ name,
11901
12305
  serverId,
11902
12306
  agentId: this.agentId
11903
12307
  });
11904
12308
  await this.getDatabaseAdapter().createWorld({
11905
12309
  id,
11906
- name: name2,
12310
+ name,
11907
12311
  agentId: this.agentId,
11908
12312
  serverId: serverId || "default",
11909
12313
  metadata
@@ -11926,7 +12330,7 @@ var AgentRuntime = class {
11926
12330
  */
11927
12331
  async ensureRoomExists({
11928
12332
  id,
11929
- name: name2,
12333
+ name,
11930
12334
  source,
11931
12335
  type,
11932
12336
  channelId,
@@ -11937,7 +12341,7 @@ var AgentRuntime = class {
11937
12341
  if (!room) {
11938
12342
  await this.getDatabaseAdapter().createRoom({
11939
12343
  id,
11940
- name: name2,
12344
+ name,
11941
12345
  agentId: this.agentId,
11942
12346
  source,
11943
12347
  type,
@@ -11964,14 +12368,14 @@ var AgentRuntime = class {
11964
12368
  const existingProviderNames = cachedState.data.providers ? Object.keys(cachedState.data.providers) : [];
11965
12369
  const providerNames = /* @__PURE__ */ new Set();
11966
12370
  if (filterList && filterList.length > 0) {
11967
- filterList.forEach((name2) => providerNames.add(name2));
12371
+ filterList.forEach((name) => providerNames.add(name));
11968
12372
  } else {
11969
12373
  this.providers.filter(
11970
12374
  (p) => !p.private && !p.dynamic && !existingProviderNames.includes(p.name)
11971
12375
  ).forEach((p) => providerNames.add(p.name));
11972
12376
  }
11973
12377
  if (includeList && includeList.length > 0) {
11974
- includeList.forEach((name2) => providerNames.add(name2));
12378
+ includeList.forEach((name) => providerNames.add(name));
11975
12379
  }
11976
12380
  const providersToGet = Array.from(
11977
12381
  new Set(this.providers.filter((p) => providerNames.has(p.name)))
@@ -12166,8 +12570,8 @@ ${newProvidersText}`;
12166
12570
  }
12167
12571
  this.taskWorkers.set(taskHandler.name, taskHandler);
12168
12572
  }
12169
- getTaskWorker(name2) {
12170
- return this.taskWorkers.get(name2);
12573
+ getTaskWorker(name) {
12574
+ return this.taskWorkers.get(name);
12171
12575
  }
12172
12576
  };
12173
12577
  export {