@statelyai/agent 0.0.8 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.vscode/launch.json +12 -1
  2. package/CHANGELOG.md +18 -0
  3. package/dist/index.d.mts +3 -0
  4. package/dist/index.d.ts +286 -44
  5. package/dist/index.js +695 -1225
  6. package/dist/index.mjs +7 -0
  7. package/examples/chatbot.ts +79 -0
  8. package/examples/cot.ts +91 -0
  9. package/examples/email.ts +118 -0
  10. package/examples/example.ts +81 -0
  11. package/examples/goal.ts +94 -0
  12. package/examples/joke.ts +98 -84
  13. package/examples/multi.ts +103 -0
  14. package/examples/newspaper.ts +324 -0
  15. package/examples/number.ts +102 -0
  16. package/examples/raffle.ts +105 -0
  17. package/examples/simple.ts +39 -0
  18. package/examples/support.ts +147 -0
  19. package/examples/ticTacToe.ts +77 -77
  20. package/examples/todo.ts +135 -0
  21. package/examples/tutor.ts +100 -0
  22. package/examples/verify.ts +120 -0
  23. package/examples/weather.ts +42 -45
  24. package/examples/wiki.ts +30 -0
  25. package/examples/word.ts +168 -0
  26. package/package.json +29 -23
  27. package/readme.md +9 -38
  28. package/src/adapters/vercel.ts +7 -0
  29. package/src/agent-experimental.ts +221 -0
  30. package/src/agent.test.ts +187 -0
  31. package/src/agent.ts +260 -6
  32. package/src/decision.test.ts +179 -0
  33. package/src/decision.ts +83 -0
  34. package/src/index.ts +3 -2
  35. package/src/memory.ts +25 -0
  36. package/src/planners/shortestPathPlanner.ts +22 -0
  37. package/src/planners/simplePlanner.ts +126 -0
  38. package/src/schemas.ts +9 -20
  39. package/src/strategies/chain-of-note.ts +155 -0
  40. package/src/templates/defaultText.ts +18 -0
  41. package/src/templates/defaultToolCall.ts +10 -0
  42. package/src/text.ts +232 -0
  43. package/src/types.ts +363 -46
  44. package/src/utils.ts +13 -72
  45. package/tsconfig.json +1 -1
  46. package/examples/multiAgentCollaboration.ts +0 -0
  47. package/examples/numberGuesser.ts +0 -101
  48. package/examples/wordGuesser.ts +0 -144
  49. package/src/adapter.test.ts +0 -217
  50. package/src/adapters/openai.ts +0 -303
package/dist/index.js CHANGED
@@ -20,55 +20,36 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ agentDecide: () => agentDecide,
24
+ agentGenerateText: () => agentGenerateText,
23
25
  createAgent: () => createAgent,
24
- createOpenAIAdapter: () => createOpenAIAdapter,
25
- defineEvents: () => defineEvents
26
+ fromDecision: () => fromDecision,
27
+ fromText: () => fromText,
28
+ fromTextStream: () => fromTextStream
26
29
  });
27
30
  module.exports = __toCommonJS(src_exports);
28
31
 
29
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
30
- function addErrorMessage(res, key, errorMessage, refs) {
31
- if (!refs?.errorMessages)
32
- return;
33
- if (errorMessage) {
34
- res.errorMessage = {
35
- ...res.errorMessage,
36
- [key]: errorMessage
37
- };
38
- }
32
+ // src/agent.ts
33
+ var import_xstate3 = require("xstate");
34
+
35
+ // src/planners/simplePlanner.ts
36
+ var import_ai = require("ai");
37
+
38
+ // src/utils.ts
39
+ function getAllTransitions(state) {
40
+ const nodes = state._nodes;
41
+ const transitions = nodes.map((node) => [...node.transitions.values()]).flat(2).map((transition) => ({
42
+ ...transition,
43
+ guard: typeof transition.guard === "string" ? { type: transition.guard } : transition.guard
44
+ // TODO: fix
45
+ }));
46
+ return transitions;
39
47
  }
40
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
41
- res[key] = value;
42
- addErrorMessage(res, key, errorMessage, refs);
48
+ function wrapInXml(tagName, content) {
49
+ return `<${tagName}>${content}</${tagName}>`;
43
50
  }
44
51
 
45
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Options.js
46
- var defaultOptions = {
47
- name: void 0,
48
- $refStrategy: "root",
49
- basePath: ["#"],
50
- effectStrategy: "input",
51
- pipeStrategy: "all",
52
- dateStrategy: "string",
53
- mapStrategy: "entries",
54
- definitionPath: "definitions",
55
- target: "jsonSchema7",
56
- strictUnions: false,
57
- definitions: {},
58
- errorMessages: false,
59
- markdownDescription: false,
60
- patternStrategy: "escape",
61
- emailStrategy: "format:email"
62
- };
63
- var getDefaultOptions = (options) => typeof options === "string" ? {
64
- ...defaultOptions,
65
- name: options
66
- } : {
67
- ...defaultOptions,
68
- ...options
69
- };
70
-
71
- // node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs
52
+ // node_modules/.pnpm/zod@3.23.8/node_modules/zod/lib/index.mjs
72
53
  var util;
73
54
  (function(util2) {
74
55
  util2.assertEqual = (val) => val;
@@ -222,7 +203,7 @@ var quotelessJson = (obj) => {
222
203
  const json = JSON.stringify(obj, null, 2);
223
204
  return json.replace(/"([^"]+)":/g, "$1:");
224
205
  };
225
- var ZodError = class extends Error {
206
+ var ZodError = class _ZodError extends Error {
226
207
  constructor(issues) {
227
208
  super();
228
209
  this.issues = [];
@@ -280,6 +261,11 @@ var ZodError = class extends Error {
280
261
  processError(this);
281
262
  return fieldErrors;
282
263
  }
264
+ static assert(value) {
265
+ if (!(value instanceof _ZodError)) {
266
+ throw new Error(`Not a ZodError: ${value}`);
267
+ }
268
+ }
283
269
  toString() {
284
270
  return this.message;
285
271
  }
@@ -422,6 +408,13 @@ var makeIssue = (params) => {
422
408
  ...issueData,
423
409
  path: fullPath
424
410
  };
411
+ if (issueData.message !== void 0) {
412
+ return {
413
+ ...issueData,
414
+ path: fullPath,
415
+ message: issueData.message
416
+ };
417
+ }
425
418
  let errorMessage = "";
426
419
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
427
420
  for (const map of maps) {
@@ -430,11 +423,12 @@ var makeIssue = (params) => {
430
423
  return {
431
424
  ...issueData,
432
425
  path: fullPath,
433
- message: issueData.message || errorMessage
426
+ message: errorMessage
434
427
  };
435
428
  };
436
429
  var EMPTY_PATH = [];
437
430
  function addIssueToContext(ctx, issueData) {
431
+ const overrideMap = getErrorMap();
438
432
  const issue = makeIssue({
439
433
  issueData,
440
434
  data: ctx.data,
@@ -442,8 +436,8 @@ function addIssueToContext(ctx, issueData) {
442
436
  errorMaps: [
443
437
  ctx.common.contextualErrorMap,
444
438
  ctx.schemaErrorMap,
445
- getErrorMap(),
446
- errorMap
439
+ overrideMap,
440
+ overrideMap === errorMap ? void 0 : errorMap
447
441
  // then global default map
448
442
  ].filter((x) => !!x)
449
443
  });
@@ -475,9 +469,11 @@ var ParseStatus = class _ParseStatus {
475
469
  static async mergeObjectAsync(status, pairs) {
476
470
  const syncPairs = [];
477
471
  for (const pair of pairs) {
472
+ const key = await pair.key;
473
+ const value = await pair.value;
478
474
  syncPairs.push({
479
- key: await pair.key,
480
- value: await pair.value
475
+ key,
476
+ value
481
477
  });
482
478
  }
483
479
  return _ParseStatus.mergeObjectSync(status, syncPairs);
@@ -510,11 +506,24 @@ var isAborted = (x) => x.status === "aborted";
510
506
  var isDirty = (x) => x.status === "dirty";
511
507
  var isValid = (x) => x.status === "valid";
512
508
  var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
509
+ function __classPrivateFieldGet(receiver, state, kind, f) {
510
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
511
+ 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");
512
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
513
+ }
514
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
515
+ if (kind === "m") throw new TypeError("Private method is not writable");
516
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
517
+ 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");
518
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
519
+ }
513
520
  var errorUtil;
514
521
  (function(errorUtil2) {
515
522
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
516
523
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
517
524
  })(errorUtil || (errorUtil = {}));
525
+ var _ZodEnum_cache;
526
+ var _ZodNativeEnum_cache;
518
527
  var ParseInputLazyPath = class {
519
528
  constructor(parent, value, path, key) {
520
529
  this._cachedPath = [];
@@ -563,12 +572,17 @@ function processCreateParams(params) {
563
572
  if (errorMap2)
564
573
  return { errorMap: errorMap2, description };
565
574
  const customMap = (iss, ctx) => {
566
- if (iss.code !== "invalid_type")
567
- return { message: ctx.defaultError };
575
+ var _a, _b;
576
+ const { message } = params;
577
+ if (iss.code === "invalid_enum_value") {
578
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
579
+ }
568
580
  if (typeof ctx.data === "undefined") {
569
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
581
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
570
582
  }
571
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
583
+ if (iss.code !== "invalid_type")
584
+ return { message: ctx.defaultError };
585
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
572
586
  };
573
587
  return { errorMap: customMap, description };
574
588
  }
@@ -816,35 +830,40 @@ var ZodType = class {
816
830
  }
817
831
  };
818
832
  var cuidRegex = /^c[^\s-]{8,}$/i;
819
- var cuid2Regex = /^[a-z][a-z0-9]*$/;
833
+ var cuid2Regex = /^[0-9a-z]+$/;
820
834
  var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
821
835
  var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
822
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
836
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
837
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
838
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
823
839
  var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
824
840
  var emojiRegex;
825
- var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
841
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
826
842
  var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
827
- var datetimeRegex = (args) => {
843
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
844
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
845
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
846
+ function timeRegexSource(args) {
847
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
828
848
  if (args.precision) {
829
- if (args.offset) {
830
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
831
- } else {
832
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
833
- }
834
- } else if (args.precision === 0) {
835
- if (args.offset) {
836
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
837
- } else {
838
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
839
- }
840
- } else {
841
- if (args.offset) {
842
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
843
- } else {
844
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
845
- }
849
+ regex = `${regex}\\.\\d{${args.precision}}`;
850
+ } else if (args.precision == null) {
851
+ regex = `${regex}(\\.\\d+)?`;
846
852
  }
847
- };
853
+ return regex;
854
+ }
855
+ function timeRegex(args) {
856
+ return new RegExp(`^${timeRegexSource(args)}$`);
857
+ }
858
+ function datetimeRegex(args) {
859
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
860
+ const opts = [];
861
+ opts.push(args.local ? `Z?` : `Z`);
862
+ if (args.offset)
863
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
864
+ regex = `${regex}(${opts.join("|")})`;
865
+ return new RegExp(`^${regex}$`);
866
+ }
848
867
  function isValidIP(ip, version) {
849
868
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
850
869
  return true;
@@ -862,15 +881,11 @@ var ZodString = class _ZodString extends ZodType {
862
881
  const parsedType = this._getType(input);
863
882
  if (parsedType !== ZodParsedType.string) {
864
883
  const ctx2 = this._getOrReturnCtx(input);
865
- addIssueToContext(
866
- ctx2,
867
- {
868
- code: ZodIssueCode.invalid_type,
869
- expected: ZodParsedType.string,
870
- received: ctx2.parsedType
871
- }
872
- //
873
- );
884
+ addIssueToContext(ctx2, {
885
+ code: ZodIssueCode.invalid_type,
886
+ expected: ZodParsedType.string,
887
+ received: ctx2.parsedType
888
+ });
874
889
  return INVALID;
875
890
  }
876
891
  const status = new ParseStatus();
@@ -961,6 +976,16 @@ var ZodString = class _ZodString extends ZodType {
961
976
  });
962
977
  status.dirty();
963
978
  }
979
+ } else if (check.kind === "nanoid") {
980
+ if (!nanoidRegex.test(input.data)) {
981
+ ctx = this._getOrReturnCtx(input, ctx);
982
+ addIssueToContext(ctx, {
983
+ validation: "nanoid",
984
+ code: ZodIssueCode.invalid_string,
985
+ message: check.message
986
+ });
987
+ status.dirty();
988
+ }
964
989
  } else if (check.kind === "cuid") {
965
990
  if (!cuidRegex.test(input.data)) {
966
991
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1062,6 +1087,38 @@ var ZodString = class _ZodString extends ZodType {
1062
1087
  });
1063
1088
  status.dirty();
1064
1089
  }
1090
+ } else if (check.kind === "date") {
1091
+ const regex = dateRegex;
1092
+ if (!regex.test(input.data)) {
1093
+ ctx = this._getOrReturnCtx(input, ctx);
1094
+ addIssueToContext(ctx, {
1095
+ code: ZodIssueCode.invalid_string,
1096
+ validation: "date",
1097
+ message: check.message
1098
+ });
1099
+ status.dirty();
1100
+ }
1101
+ } else if (check.kind === "time") {
1102
+ const regex = timeRegex(check);
1103
+ if (!regex.test(input.data)) {
1104
+ ctx = this._getOrReturnCtx(input, ctx);
1105
+ addIssueToContext(ctx, {
1106
+ code: ZodIssueCode.invalid_string,
1107
+ validation: "time",
1108
+ message: check.message
1109
+ });
1110
+ status.dirty();
1111
+ }
1112
+ } else if (check.kind === "duration") {
1113
+ if (!durationRegex.test(input.data)) {
1114
+ ctx = this._getOrReturnCtx(input, ctx);
1115
+ addIssueToContext(ctx, {
1116
+ validation: "duration",
1117
+ code: ZodIssueCode.invalid_string,
1118
+ message: check.message
1119
+ });
1120
+ status.dirty();
1121
+ }
1065
1122
  } else if (check.kind === "ip") {
1066
1123
  if (!isValidIP(input.data, check.version)) {
1067
1124
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1072,6 +1129,16 @@ var ZodString = class _ZodString extends ZodType {
1072
1129
  });
1073
1130
  status.dirty();
1074
1131
  }
1132
+ } else if (check.kind === "base64") {
1133
+ if (!base64Regex.test(input.data)) {
1134
+ ctx = this._getOrReturnCtx(input, ctx);
1135
+ addIssueToContext(ctx, {
1136
+ validation: "base64",
1137
+ code: ZodIssueCode.invalid_string,
1138
+ message: check.message
1139
+ });
1140
+ status.dirty();
1141
+ }
1075
1142
  } else {
1076
1143
  util.assertNever(check);
1077
1144
  }
@@ -1103,6 +1170,9 @@ var ZodString = class _ZodString extends ZodType {
1103
1170
  uuid(message) {
1104
1171
  return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1105
1172
  }
1173
+ nanoid(message) {
1174
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1175
+ }
1106
1176
  cuid(message) {
1107
1177
  return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1108
1178
  }
@@ -1112,16 +1182,20 @@ var ZodString = class _ZodString extends ZodType {
1112
1182
  ulid(message) {
1113
1183
  return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1114
1184
  }
1185
+ base64(message) {
1186
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1187
+ }
1115
1188
  ip(options) {
1116
1189
  return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1117
1190
  }
1118
1191
  datetime(options) {
1119
- var _a;
1192
+ var _a, _b;
1120
1193
  if (typeof options === "string") {
1121
1194
  return this._addCheck({
1122
1195
  kind: "datetime",
1123
1196
  precision: null,
1124
1197
  offset: false,
1198
+ local: false,
1125
1199
  message: options
1126
1200
  });
1127
1201
  }
@@ -1129,9 +1203,30 @@ var ZodString = class _ZodString extends ZodType {
1129
1203
  kind: "datetime",
1130
1204
  precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1131
1205
  offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1206
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
1207
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1208
+ });
1209
+ }
1210
+ date(message) {
1211
+ return this._addCheck({ kind: "date", message });
1212
+ }
1213
+ time(options) {
1214
+ if (typeof options === "string") {
1215
+ return this._addCheck({
1216
+ kind: "time",
1217
+ precision: null,
1218
+ message: options
1219
+ });
1220
+ }
1221
+ return this._addCheck({
1222
+ kind: "time",
1223
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1132
1224
  ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1133
1225
  });
1134
1226
  }
1227
+ duration(message) {
1228
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1229
+ }
1135
1230
  regex(regex, message) {
1136
1231
  return this._addCheck({
1137
1232
  kind: "regex",
@@ -1210,6 +1305,15 @@ var ZodString = class _ZodString extends ZodType {
1210
1305
  get isDatetime() {
1211
1306
  return !!this._def.checks.find((ch) => ch.kind === "datetime");
1212
1307
  }
1308
+ get isDate() {
1309
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1310
+ }
1311
+ get isTime() {
1312
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1313
+ }
1314
+ get isDuration() {
1315
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1316
+ }
1213
1317
  get isEmail() {
1214
1318
  return !!this._def.checks.find((ch) => ch.kind === "email");
1215
1319
  }
@@ -1222,6 +1326,9 @@ var ZodString = class _ZodString extends ZodType {
1222
1326
  get isUUID() {
1223
1327
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
1224
1328
  }
1329
+ get isNANOID() {
1330
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1331
+ }
1225
1332
  get isCUID() {
1226
1333
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
1227
1334
  }
@@ -1234,6 +1341,9 @@ var ZodString = class _ZodString extends ZodType {
1234
1341
  get isIP() {
1235
1342
  return !!this._def.checks.find((ch) => ch.kind === "ip");
1236
1343
  }
1344
+ get isBase64() {
1345
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1346
+ }
1237
1347
  get minLength() {
1238
1348
  let min = null;
1239
1349
  for (const ch of this._def.checks) {
@@ -2123,8 +2233,7 @@ var ZodObject = class _ZodObject extends ZodType {
2123
2233
  });
2124
2234
  status.dirty();
2125
2235
  }
2126
- } else if (unknownKeys === "strip")
2127
- ;
2236
+ } else if (unknownKeys === "strip") ;
2128
2237
  else {
2129
2238
  throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2130
2239
  }
@@ -2147,9 +2256,10 @@ var ZodObject = class _ZodObject extends ZodType {
2147
2256
  const syncPairs = [];
2148
2257
  for (const pair of pairs) {
2149
2258
  const key = await pair.key;
2259
+ const value = await pair.value;
2150
2260
  syncPairs.push({
2151
2261
  key,
2152
- value: await pair.value,
2262
+ value,
2153
2263
  alwaysSet: pair.alwaysSet
2154
2264
  });
2155
2265
  }
@@ -2500,15 +2610,25 @@ var getDiscriminator = (type) => {
2500
2610
  } else if (type instanceof ZodEnum) {
2501
2611
  return type.options;
2502
2612
  } else if (type instanceof ZodNativeEnum) {
2503
- return Object.keys(type.enum);
2613
+ return util.objectValues(type.enum);
2504
2614
  } else if (type instanceof ZodDefault) {
2505
2615
  return getDiscriminator(type._def.innerType);
2506
2616
  } else if (type instanceof ZodUndefined) {
2507
2617
  return [void 0];
2508
2618
  } else if (type instanceof ZodNull) {
2509
2619
  return [null];
2620
+ } else if (type instanceof ZodOptional) {
2621
+ return [void 0, ...getDiscriminator(type.unwrap())];
2622
+ } else if (type instanceof ZodNullable) {
2623
+ return [null, ...getDiscriminator(type.unwrap())];
2624
+ } else if (type instanceof ZodBranded) {
2625
+ return getDiscriminator(type.unwrap());
2626
+ } else if (type instanceof ZodReadonly) {
2627
+ return getDiscriminator(type.unwrap());
2628
+ } else if (type instanceof ZodCatch) {
2629
+ return getDiscriminator(type._def.innerType);
2510
2630
  } else {
2511
- return null;
2631
+ return [];
2512
2632
  }
2513
2633
  };
2514
2634
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
@@ -2568,7 +2688,7 @@ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2568
2688
  const optionsMap = /* @__PURE__ */ new Map();
2569
2689
  for (const type of options) {
2570
2690
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2571
- if (!discriminatorValues) {
2691
+ if (!discriminatorValues.length) {
2572
2692
  throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2573
2693
  }
2574
2694
  for (const value of discriminatorValues) {
@@ -2768,7 +2888,8 @@ var ZodRecord = class _ZodRecord extends ZodType {
2768
2888
  for (const key in ctx.data) {
2769
2889
  pairs.push({
2770
2890
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2771
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
2891
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2892
+ alwaysSet: key in ctx.data
2772
2893
  });
2773
2894
  }
2774
2895
  if (ctx.common.async) {
@@ -3112,6 +3233,10 @@ function createZodEnum(values, params) {
3112
3233
  });
3113
3234
  }
3114
3235
  var ZodEnum = class _ZodEnum extends ZodType {
3236
+ constructor() {
3237
+ super(...arguments);
3238
+ _ZodEnum_cache.set(this, void 0);
3239
+ }
3115
3240
  _parse(input) {
3116
3241
  if (typeof input.data !== "string") {
3117
3242
  const ctx = this._getOrReturnCtx(input);
@@ -3123,7 +3248,10 @@ var ZodEnum = class _ZodEnum extends ZodType {
3123
3248
  });
3124
3249
  return INVALID;
3125
3250
  }
3126
- if (this._def.values.indexOf(input.data) === -1) {
3251
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
3252
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
3253
+ }
3254
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3127
3255
  const ctx = this._getOrReturnCtx(input);
3128
3256
  const expectedValues = this._def.values;
3129
3257
  addIssueToContext(ctx, {
@@ -3159,15 +3287,26 @@ var ZodEnum = class _ZodEnum extends ZodType {
3159
3287
  }
3160
3288
  return enumValues;
3161
3289
  }
3162
- extract(values) {
3163
- return _ZodEnum.create(values);
3290
+ extract(values, newDef = this._def) {
3291
+ return _ZodEnum.create(values, {
3292
+ ...this._def,
3293
+ ...newDef
3294
+ });
3164
3295
  }
3165
- exclude(values) {
3166
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
3296
+ exclude(values, newDef = this._def) {
3297
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3298
+ ...this._def,
3299
+ ...newDef
3300
+ });
3167
3301
  }
3168
3302
  };
3303
+ _ZodEnum_cache = /* @__PURE__ */ new WeakMap();
3169
3304
  ZodEnum.create = createZodEnum;
3170
3305
  var ZodNativeEnum = class extends ZodType {
3306
+ constructor() {
3307
+ super(...arguments);
3308
+ _ZodNativeEnum_cache.set(this, void 0);
3309
+ }
3171
3310
  _parse(input) {
3172
3311
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
3173
3312
  const ctx = this._getOrReturnCtx(input);
@@ -3180,7 +3319,10 @@ var ZodNativeEnum = class extends ZodType {
3180
3319
  });
3181
3320
  return INVALID;
3182
3321
  }
3183
- if (nativeEnumValues.indexOf(input.data) === -1) {
3322
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
3323
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
3324
+ }
3325
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3184
3326
  const expectedValues = util.objectValues(nativeEnumValues);
3185
3327
  addIssueToContext(ctx, {
3186
3328
  received: ctx.data,
@@ -3195,6 +3337,7 @@ var ZodNativeEnum = class extends ZodType {
3195
3337
  return this._def.values;
3196
3338
  }
3197
3339
  };
3340
+ _ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
3198
3341
  ZodNativeEnum.create = (values, params) => {
3199
3342
  return new ZodNativeEnum({
3200
3343
  values,
@@ -3258,26 +3401,38 @@ var ZodEffects = class extends ZodType {
3258
3401
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3259
3402
  if (effect.type === "preprocess") {
3260
3403
  const processed = effect.transform(ctx.data, checkCtx);
3261
- if (ctx.common.issues.length) {
3262
- return {
3263
- status: "dirty",
3264
- value: ctx.data
3265
- };
3266
- }
3267
3404
  if (ctx.common.async) {
3268
- return Promise.resolve(processed).then((processed2) => {
3269
- return this._def.schema._parseAsync({
3405
+ return Promise.resolve(processed).then(async (processed2) => {
3406
+ if (status.value === "aborted")
3407
+ return INVALID;
3408
+ const result = await this._def.schema._parseAsync({
3270
3409
  data: processed2,
3271
3410
  path: ctx.path,
3272
3411
  parent: ctx
3273
3412
  });
3413
+ if (result.status === "aborted")
3414
+ return INVALID;
3415
+ if (result.status === "dirty")
3416
+ return DIRTY(result.value);
3417
+ if (status.value === "dirty")
3418
+ return DIRTY(result.value);
3419
+ return result;
3274
3420
  });
3275
3421
  } else {
3276
- return this._def.schema._parseSync({
3422
+ if (status.value === "aborted")
3423
+ return INVALID;
3424
+ const result = this._def.schema._parseSync({
3277
3425
  data: processed,
3278
3426
  path: ctx.path,
3279
3427
  parent: ctx
3280
3428
  });
3429
+ if (result.status === "aborted")
3430
+ return INVALID;
3431
+ if (result.status === "dirty")
3432
+ return DIRTY(result.value);
3433
+ if (status.value === "dirty")
3434
+ return DIRTY(result.value);
3435
+ return result;
3281
3436
  }
3282
3437
  }
3283
3438
  if (effect.type === "refinement") {
@@ -3566,10 +3721,16 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
3566
3721
  var ZodReadonly = class extends ZodType {
3567
3722
  _parse(input) {
3568
3723
  const result = this._def.innerType._parse(input);
3569
- if (isValid(result)) {
3570
- result.value = Object.freeze(result.value);
3571
- }
3572
- return result;
3724
+ const freeze = (data) => {
3725
+ if (isValid(data)) {
3726
+ data.value = Object.freeze(data.value);
3727
+ }
3728
+ return data;
3729
+ };
3730
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3731
+ }
3732
+ unwrap() {
3733
+ return this._def.innerType;
3573
3734
  }
3574
3735
  };
3575
3736
  ZodReadonly.create = (type, params) => {
@@ -3579,7 +3740,7 @@ ZodReadonly.create = (type, params) => {
3579
3740
  ...processCreateParams(params)
3580
3741
  });
3581
3742
  };
3582
- var custom = (check, params = {}, fatal) => {
3743
+ function custom(check, params = {}, fatal) {
3583
3744
  if (check)
3584
3745
  return ZodAny.create().superRefine((data, ctx) => {
3585
3746
  var _a, _b;
@@ -3591,7 +3752,7 @@ var custom = (check, params = {}, fatal) => {
3591
3752
  }
3592
3753
  });
3593
3754
  return ZodAny.create();
3594
- };
3755
+ }
3595
3756
  var late = {
3596
3757
  object: ZodObject.lazycreate
3597
3758
  };
@@ -3710,6 +3871,7 @@ var z = /* @__PURE__ */ Object.freeze({
3710
3871
  ZodParsedType,
3711
3872
  getParsedType,
3712
3873
  ZodType,
3874
+ datetimeRegex,
3713
3875
  ZodString,
3714
3876
  ZodNumber,
3715
3877
  ZodBigInt,
@@ -3801,1183 +3963,491 @@ var z = /* @__PURE__ */ Object.freeze({
3801
3963
  ZodError
3802
3964
  });
3803
3965
 
3804
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
3805
- function parseAnyDef() {
3806
- return {};
3807
- }
3966
+ // src/templates/defaultText.ts
3967
+ var defaultTextTemplate = (data) => {
3968
+ const preamble = [
3969
+ data.context ? wrapInXml("context", JSON.stringify(data.context)) : void 0
3970
+ ].filter(Boolean).join("\n");
3971
+ return `
3972
+ ${preamble}
3808
3973
 
3809
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
3810
- function parseArrayDef(def, refs) {
3811
- const res = {
3812
- type: "array"
3813
- };
3814
- if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
3815
- res.items = parseDef(def.type._def, {
3816
- ...refs,
3817
- currentPath: [...refs.currentPath, "items"]
3818
- });
3819
- }
3820
- if (def.minLength) {
3821
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
3822
- }
3823
- if (def.maxLength) {
3824
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
3825
- }
3826
- if (def.exactLength) {
3827
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
3828
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
3829
- }
3830
- return res;
3831
- }
3974
+ ${data.goal}
3975
+ `.trim();
3976
+ };
3832
3977
 
3833
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
3834
- function parseBigintDef(def, refs) {
3835
- const res = {
3836
- type: "integer",
3837
- format: "int64"
3838
- };
3839
- if (!def.checks)
3840
- return res;
3841
- for (const check of def.checks) {
3842
- switch (check.kind) {
3843
- case "min":
3844
- if (refs.target === "jsonSchema7") {
3845
- if (check.inclusive) {
3846
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
3847
- } else {
3848
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
3849
- }
3850
- } else {
3851
- if (!check.inclusive) {
3852
- res.exclusiveMinimum = true;
3853
- }
3854
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
3855
- }
3856
- break;
3857
- case "max":
3858
- if (refs.target === "jsonSchema7") {
3859
- if (check.inclusive) {
3860
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
3861
- } else {
3862
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
3863
- }
3864
- } else {
3865
- if (!check.inclusive) {
3866
- res.exclusiveMaximum = true;
3867
- }
3868
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
3869
- }
3870
- break;
3871
- case "multipleOf":
3872
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
3873
- break;
3874
- }
3978
+ // src/planners/simplePlanner.ts
3979
+ function getTransitions(state, machine) {
3980
+ if (!machine) {
3981
+ return [];
3875
3982
  }
3876
- return res;
3877
- }
3878
-
3879
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
3880
- function parseBooleanDef() {
3881
- return {
3882
- type: "boolean"
3883
- };
3884
- }
3885
-
3886
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
3887
- function parseBrandedDef(_def, refs) {
3888
- return parseDef(_def.type._def, refs);
3983
+ const resolvedState = machine.resolveState(state);
3984
+ return getAllTransitions(resolvedState);
3889
3985
  }
3986
+ var simplePlannerPromptTemplate = (data) => {
3987
+ return `
3988
+ ${defaultTextTemplate(data)}
3890
3989
 
3891
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
3892
- var parseCatchDef = (def, refs) => {
3893
- return parseDef(def.innerType._def, refs);
3990
+ Only make a single tool call to achieve the above goal.
3991
+ `.trim();
3894
3992
  };
3895
-
3896
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
3897
- function parseDateDef(def, refs) {
3898
- if (refs.dateStrategy == "integer") {
3899
- return integerDateParser(def, refs);
3900
- } else {
3993
+ async function simplePlanner(agent, input) {
3994
+ const transitions = input.machine ? getTransitions(input.state, input.machine) : Object.entries(input.events).map(([eventType, { description }]) => ({
3995
+ eventType,
3996
+ description
3997
+ }));
3998
+ const filter = (eventType) => Object.keys(input.events).includes(eventType);
3999
+ const functionNameMapping = {};
4000
+ const toolTransitions = transitions.filter((t) => {
4001
+ return filter(t.eventType);
4002
+ }).map((t) => {
4003
+ const name = t.eventType.replace(/\./g, "_");
4004
+ functionNameMapping[name] = t.eventType;
3901
4005
  return {
3902
- type: "string",
3903
- format: "date-time"
4006
+ type: "function",
4007
+ eventType: t.eventType,
4008
+ description: t.description,
4009
+ name
3904
4010
  };
4011
+ });
4012
+ const toolMap = {};
4013
+ for (const toolTransitionData of toolTransitions) {
4014
+ const toolZodType = input.events?.[toolTransitionData.eventType];
4015
+ toolMap[toolTransitionData.name] = (0, import_ai.tool)({
4016
+ description: toolZodType?.description ?? toolTransitionData.description,
4017
+ parameters: toolZodType ?? z.object({}),
4018
+ execute: async (params) => {
4019
+ const event = {
4020
+ type: toolTransitionData.eventType,
4021
+ ...params
4022
+ };
4023
+ return event;
4024
+ }
4025
+ });
3905
4026
  }
3906
- }
3907
- var integerDateParser = (def, refs) => {
3908
- const res = {
3909
- type: "integer",
3910
- format: "unix-time"
3911
- };
3912
- for (const check of def.checks) {
3913
- switch (check.kind) {
3914
- case "min":
3915
- if (refs.target === "jsonSchema7") {
3916
- setResponseValueAndErrors(
3917
- res,
3918
- "minimum",
3919
- check.value,
3920
- // This is in milliseconds
3921
- check.message,
3922
- refs
3923
- );
3924
- }
3925
- break;
3926
- case "max":
3927
- if (refs.target === "jsonSchema7") {
3928
- setResponseValueAndErrors(
3929
- res,
3930
- "maximum",
3931
- check.value,
3932
- // This is in milliseconds
3933
- check.message,
3934
- refs
3935
- );
3936
- }
3937
- break;
3938
- }
4027
+ const prompt = simplePlannerPromptTemplate({
4028
+ context: input.state.context,
4029
+ goal: input.goal
4030
+ });
4031
+ const result = await agent.generateText({
4032
+ prompt,
4033
+ tools: toolMap,
4034
+ toolChoice: "required",
4035
+ ...input
4036
+ });
4037
+ const singleResult = result.toolResults[0];
4038
+ if (!singleResult) {
4039
+ console.warn("No tool call results returned");
4040
+ return void 0;
3939
4041
  }
3940
- return res;
3941
- };
3942
-
3943
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
3944
- function parseDefaultDef(_def, refs) {
3945
4042
  return {
3946
- ...parseDef(_def.innerType._def, refs),
3947
- default: _def.defaultValue()
4043
+ goal: input.goal,
4044
+ state: input.state,
4045
+ steps: [
4046
+ {
4047
+ event: singleResult.result
4048
+ }
4049
+ ],
4050
+ nextEvent: singleResult.result,
4051
+ sessionId: agent.sessionId,
4052
+ timestamp: Date.now()
3948
4053
  };
3949
4054
  }
3950
4055
 
3951
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
3952
- function parseEffectsDef(_def, refs) {
3953
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
3954
- }
3955
-
3956
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
3957
- function parseEnumDef(def) {
3958
- return {
3959
- type: "string",
3960
- enum: def.values
3961
- };
3962
- }
4056
+ // src/agent.ts
4057
+ var import_crypto2 = require("crypto");
3963
4058
 
3964
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
3965
- var isJsonSchema7AllOfType = (type) => {
3966
- if ("type" in type && type.type === "string")
3967
- return false;
3968
- return "allOf" in type;
3969
- };
3970
- function parseIntersectionDef(def, refs) {
3971
- const allOf = [
3972
- parseDef(def.left._def, {
3973
- ...refs,
3974
- currentPath: [...refs.currentPath, "allOf", "0"]
3975
- }),
3976
- parseDef(def.right._def, {
3977
- ...refs,
3978
- currentPath: [...refs.currentPath, "allOf", "1"]
3979
- })
3980
- ].filter((x) => !!x);
3981
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
3982
- const mergedAllOf = [];
3983
- allOf.forEach((schema) => {
3984
- if (isJsonSchema7AllOfType(schema)) {
3985
- mergedAllOf.push(...schema.allOf);
3986
- if (schema.unevaluatedProperties === void 0) {
3987
- unevaluatedProperties = void 0;
3988
- }
3989
- } else {
3990
- let nestedSchema = schema;
3991
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
3992
- const { additionalProperties, ...rest } = schema;
3993
- nestedSchema = rest;
3994
- } else {
3995
- unevaluatedProperties = void 0;
3996
- }
3997
- mergedAllOf.push(nestedSchema);
3998
- }
4059
+ // src/text.ts
4060
+ var import_crypto = require("crypto");
4061
+ var import_xstate = require("xstate");
4062
+ async function getMessages(agent, prompt, options) {
4063
+ let messages = [];
4064
+ if (options.messages === true) {
4065
+ messages = agent.select((s) => s.messages);
4066
+ } else if (typeof options.messages === "function") {
4067
+ messages = await options.messages(agent);
4068
+ } else if (options.messages) {
4069
+ messages = options.messages;
4070
+ }
4071
+ messages = messages.concat({
4072
+ role: "user",
4073
+ content: prompt
3999
4074
  });
4000
- return mergedAllOf.length ? {
4001
- allOf: mergedAllOf,
4002
- ...unevaluatedProperties
4003
- } : void 0;
4075
+ return messages;
4004
4076
  }
4005
-
4006
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
4007
- function parseLiteralDef(def, refs) {
4008
- const parsedType = typeof def.value;
4009
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
4010
- return {
4011
- type: Array.isArray(def.value) ? "array" : "object"
4012
- };
4013
- }
4014
- if (refs.target === "openApi3") {
4015
- return {
4016
- type: parsedType === "bigint" ? "integer" : parsedType,
4017
- enum: [def.value]
4018
- };
4019
- }
4020
- return {
4021
- type: parsedType === "bigint" ? "integer" : parsedType,
4022
- const: def.value
4077
+ async function agentGenerateText(agent, options) {
4078
+ const resolvedOptions = {
4079
+ ...agent.defaultOptions,
4080
+ ...options
4023
4081
  };
4082
+ const template = resolvedOptions.template ?? defaultTextTemplate;
4083
+ const id = (0, import_crypto.randomUUID)();
4084
+ const goal = typeof resolvedOptions.prompt === "string" ? resolvedOptions.prompt : await resolvedOptions.prompt(agent);
4085
+ const promptWithContext = template({
4086
+ goal,
4087
+ context: resolvedOptions.context
4088
+ });
4089
+ const messages = await getMessages(agent, promptWithContext, resolvedOptions);
4090
+ agent.addMessage({
4091
+ id,
4092
+ role: "user",
4093
+ content: promptWithContext,
4094
+ timestamp: Date.now()
4095
+ });
4096
+ const result = await agent.adapter.generateText({
4097
+ ...resolvedOptions,
4098
+ prompt: void 0,
4099
+ messages
4100
+ });
4101
+ agent.addMessage({
4102
+ content: result.text,
4103
+ id,
4104
+ role: "assistant",
4105
+ timestamp: Date.now(),
4106
+ responseId: id,
4107
+ result
4108
+ });
4109
+ return result;
4024
4110
  }
4025
-
4026
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
4027
- var zodPatterns = {
4028
- /**
4029
- * `c` was changed to `[cC]` to replicate /i flag
4030
- */
4031
- cuid: "^[cC][^\\s-]{8,}$",
4032
- cuid2: "^[a-z][a-z0-9]*$",
4033
- ulid: "^[0-9A-HJKMNP-TV-Z]{26}$",
4034
- /**
4035
- * `a-z` was added to replicate /i flag
4036
- */
4037
- email: "^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_+-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$",
4038
- emoji: "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
4039
- /**
4040
- * Unused
4041
- */
4042
- uuid: "^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$",
4043
- /**
4044
- * Unused
4045
- */
4046
- ipv4: "^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$",
4047
- /**
4048
- * Unused
4049
- */
4050
- ipv6: "^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$"
4051
- };
4052
- function parseStringDef(def, refs) {
4053
- const res = {
4054
- type: "string"
4111
+ async function agentStreamText(agent, options) {
4112
+ const resolvedOptions = {
4113
+ ...agent.defaultOptions,
4114
+ ...options
4055
4115
  };
4056
- function processPattern(value) {
4057
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(value) : value;
4058
- }
4059
- if (def.checks) {
4060
- for (const check of def.checks) {
4061
- switch (check.kind) {
4062
- case "min":
4063
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
4064
- break;
4065
- case "max":
4066
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
4067
- break;
4068
- case "email":
4069
- switch (refs.emailStrategy) {
4070
- case "format:email":
4071
- addFormat(res, "email", check.message, refs);
4072
- break;
4073
- case "format:idn-email":
4074
- addFormat(res, "idn-email", check.message, refs);
4075
- break;
4076
- case "pattern:zod":
4077
- addPattern(res, zodPatterns.email, check.message, refs);
4078
- break;
4079
- }
4080
- break;
4081
- case "url":
4082
- addFormat(res, "uri", check.message, refs);
4083
- break;
4084
- case "uuid":
4085
- addFormat(res, "uuid", check.message, refs);
4086
- break;
4087
- case "regex":
4088
- addPattern(res, check.regex.source, check.message, refs);
4089
- break;
4090
- case "cuid":
4091
- addPattern(res, zodPatterns.cuid, check.message, refs);
4092
- break;
4093
- case "cuid2":
4094
- addPattern(res, zodPatterns.cuid2, check.message, refs);
4095
- break;
4096
- case "startsWith":
4097
- addPattern(res, "^" + processPattern(check.value), check.message, refs);
4098
- break;
4099
- case "endsWith":
4100
- addPattern(res, processPattern(check.value) + "$", check.message, refs);
4101
- break;
4102
- case "datetime":
4103
- addFormat(res, "date-time", check.message, refs);
4104
- break;
4105
- case "length":
4106
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
4107
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
4108
- break;
4109
- case "includes": {
4110
- addPattern(res, processPattern(check.value), check.message, refs);
4111
- break;
4112
- }
4113
- case "ip": {
4114
- if (check.version !== "v6") {
4115
- addFormat(res, "ipv4", check.message, refs);
4116
- }
4117
- if (check.version !== "v4") {
4118
- addFormat(res, "ipv6", check.message, refs);
4119
- }
4120
- break;
4121
- }
4122
- case "emoji":
4123
- addPattern(res, zodPatterns.emoji, check.message, refs);
4124
- break;
4125
- case "ulid": {
4126
- addPattern(res, zodPatterns.ulid, check.message, refs);
4127
- break;
4128
- }
4129
- case "toLowerCase":
4130
- case "toUpperCase":
4131
- case "trim":
4132
- break;
4133
- default:
4134
- /* @__PURE__ */ ((_) => {
4135
- })(check);
4136
- }
4137
- }
4138
- }
4139
- return res;
4140
- }
4141
- var escapeNonAlphaNumeric = (value) => Array.from(value).map((c) => /[a-zA-Z0-9]/.test(c) ? c : `\\${c}`).join("");
4142
- var addFormat = (schema, value, message, refs) => {
4143
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
4144
- if (!schema.anyOf) {
4145
- schema.anyOf = [];
4146
- }
4147
- if (schema.format) {
4148
- schema.anyOf.push({
4149
- format: schema.format,
4150
- ...schema.errorMessage && refs.errorMessages && {
4151
- errorMessage: { format: schema.errorMessage.format }
4152
- }
4116
+ const template = resolvedOptions.template ?? defaultTextTemplate;
4117
+ const id = (0, import_crypto.randomUUID)();
4118
+ const goal = typeof resolvedOptions.prompt === "string" ? resolvedOptions.prompt : await resolvedOptions.prompt(agent);
4119
+ const promptWithContext = template({
4120
+ goal,
4121
+ context: resolvedOptions.context
4122
+ });
4123
+ const messages = await getMessages(agent, promptWithContext, resolvedOptions);
4124
+ agent.addMessage({
4125
+ role: "user",
4126
+ content: promptWithContext,
4127
+ id,
4128
+ timestamp: Date.now()
4129
+ });
4130
+ const result = await agent.adapter.streamText({
4131
+ ...resolvedOptions,
4132
+ prompt: void 0,
4133
+ messages,
4134
+ onFinish: async (res) => {
4135
+ agent.addMessage({
4136
+ role: "assistant",
4137
+ result: {
4138
+ text: res.text,
4139
+ finishReason: res.finishReason,
4140
+ logprobs: void 0,
4141
+ responseMessages: [],
4142
+ toolCalls: [],
4143
+ toolResults: [],
4144
+ usage: res.usage,
4145
+ warnings: res.warnings,
4146
+ rawResponse: res.rawResponse
4147
+ },
4148
+ content: res.text,
4149
+ id: (0, import_crypto.randomUUID)(),
4150
+ timestamp: Date.now(),
4151
+ responseId: id
4153
4152
  });
4154
- delete schema.format;
4155
- if (schema.errorMessage) {
4156
- delete schema.errorMessage.format;
4157
- if (Object.keys(schema.errorMessage).length === 0) {
4158
- delete schema.errorMessage;
4159
- }
4160
- }
4161
- }
4162
- schema.anyOf.push({
4163
- format: value,
4164
- ...message && refs.errorMessages && { errorMessage: { format: message } }
4165
- });
4166
- } else {
4167
- setResponseValueAndErrors(schema, "format", value, message, refs);
4168
- }
4169
- };
4170
- var addPattern = (schema, value, message, refs) => {
4171
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
4172
- if (!schema.allOf) {
4173
- schema.allOf = [];
4174
4153
  }
4175
- if (schema.pattern) {
4176
- schema.allOf.push({
4177
- pattern: schema.pattern,
4178
- ...schema.errorMessage && refs.errorMessages && {
4179
- errorMessage: { pattern: schema.errorMessage.pattern }
4180
- }
4154
+ });
4155
+ return result;
4156
+ }
4157
+ function fromTextStream(agent, defaultOptions) {
4158
+ return (0, import_xstate.fromObservable)(({ input, self }) => {
4159
+ const context = input.context === true ? (self._parent?.getSnapshot()).context : input.context;
4160
+ const observers = /* @__PURE__ */ new Set();
4161
+ (async () => {
4162
+ const result = await agentStreamText(agent, {
4163
+ ...defaultOptions,
4164
+ ...input,
4165
+ context
4181
4166
  });
4182
- delete schema.pattern;
4183
- if (schema.errorMessage) {
4184
- delete schema.errorMessage.pattern;
4185
- if (Object.keys(schema.errorMessage).length === 0) {
4186
- delete schema.errorMessage;
4167
+ for await (const part of result.fullStream) {
4168
+ if (part.type === "text-delta") {
4169
+ observers.forEach((observer) => {
4170
+ observer.next?.(part);
4171
+ });
4187
4172
  }
4188
4173
  }
4189
- }
4190
- schema.allOf.push({
4191
- pattern: value,
4192
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
4193
- });
4194
- } else {
4195
- setResponseValueAndErrors(schema, "pattern", value, message, refs);
4196
- }
4197
- };
4198
-
4199
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
4200
- function parseRecordDef(def, refs) {
4201
- if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
4174
+ })();
4202
4175
  return {
4203
- type: "object",
4204
- required: def.keyType._def.values,
4205
- properties: def.keyType._def.values.reduce((acc, key) => ({
4206
- ...acc,
4207
- [key]: parseDef(def.valueType._def, {
4208
- ...refs,
4209
- currentPath: [...refs.currentPath, "properties", key]
4210
- }) ?? {}
4211
- }), {}),
4212
- additionalProperties: false
4213
- };
4214
- }
4215
- const schema = {
4216
- type: "object",
4217
- additionalProperties: parseDef(def.valueType._def, {
4218
- ...refs,
4219
- currentPath: [...refs.currentPath, "additionalProperties"]
4220
- }) ?? {}
4221
- };
4222
- if (refs.target === "openApi3") {
4223
- return schema;
4224
- }
4225
- if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
4226
- const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => key === "type" ? acc : { ...acc, [key]: value }, {});
4227
- return {
4228
- ...schema,
4229
- propertyNames: keyType
4230
- };
4231
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
4232
- return {
4233
- ...schema,
4234
- propertyNames: {
4235
- enum: def.keyType._def.values
4176
+ subscribe: (...args) => {
4177
+ const observer = (0, import_xstate.toObserver)(...args);
4178
+ observers.add(observer);
4179
+ return {
4180
+ unsubscribe: () => {
4181
+ observers.delete(observer);
4182
+ }
4183
+ };
4236
4184
  }
4237
4185
  };
4238
- }
4239
- return schema;
4240
- }
4241
-
4242
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
4243
- function parseMapDef(def, refs) {
4244
- if (refs.mapStrategy === "record") {
4245
- return parseRecordDef(def, refs);
4246
- }
4247
- const keys = parseDef(def.keyType._def, {
4248
- ...refs,
4249
- currentPath: [...refs.currentPath, "items", "items", "0"]
4250
- }) || {};
4251
- const values = parseDef(def.valueType._def, {
4252
- ...refs,
4253
- currentPath: [...refs.currentPath, "items", "items", "1"]
4254
- }) || {};
4255
- return {
4256
- type: "array",
4257
- maxItems: 125,
4258
- items: {
4259
- type: "array",
4260
- items: [keys, values],
4261
- minItems: 2,
4262
- maxItems: 2
4263
- }
4264
- };
4265
- }
4266
-
4267
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
4268
- function parseNativeEnumDef(def) {
4269
- const object = def.values;
4270
- const actualKeys = Object.keys(def.values).filter((key) => {
4271
- return typeof object[object[key]] !== "number";
4272
4186
  });
4273
- const actualValues = actualKeys.map((key) => object[key]);
4274
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
4275
- return {
4276
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
4277
- enum: actualValues
4278
- };
4279
4187
  }
4280
-
4281
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
4282
- function parseNeverDef() {
4283
- return {
4284
- not: {}
4285
- };
4188
+ function fromText(agent, defaultOptions) {
4189
+ return (0, import_xstate.fromPromise)(async ({ input, self }) => {
4190
+ const context = input.context === true ? (self._parent?.getSnapshot()).context : input.context;
4191
+ return await agentGenerateText(agent, {
4192
+ ...input,
4193
+ ...defaultOptions,
4194
+ context
4195
+ });
4196
+ });
4286
4197
  }
4287
4198
 
4288
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
4289
- function parseNullDef(refs) {
4290
- return refs.target === "openApi3" ? {
4291
- enum: ["null"],
4292
- nullable: true
4293
- } : {
4294
- type: "null"
4199
+ // src/decision.ts
4200
+ var import_xstate2 = require("xstate");
4201
+ async function agentDecide(agent, options) {
4202
+ const resolvedOptions = {
4203
+ ...agent.defaultOptions,
4204
+ ...options
4295
4205
  };
4296
- }
4297
-
4298
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
4299
- var primitiveMappings = {
4300
- ZodString: "string",
4301
- ZodNumber: "number",
4302
- ZodBigInt: "integer",
4303
- ZodBoolean: "boolean",
4304
- ZodNull: "null"
4305
- };
4306
- function parseUnionDef(def, refs) {
4307
- if (refs.target === "openApi3")
4308
- return asAnyOf(def, refs);
4309
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
4310
- if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
4311
- const types = options.reduce((types2, x) => {
4312
- const type = primitiveMappings[x._def.typeName];
4313
- return type && !types2.includes(type) ? [...types2, type] : types2;
4314
- }, []);
4315
- return {
4316
- type: types.length > 1 ? types : types[0]
4317
- };
4318
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
4319
- const types = options.reduce((acc, x) => {
4320
- const type = typeof x._def.value;
4321
- switch (type) {
4322
- case "string":
4323
- case "number":
4324
- case "boolean":
4325
- return [...acc, type];
4326
- case "bigint":
4327
- return [...acc, "integer"];
4328
- case "object":
4329
- if (x._def.value === null)
4330
- return [...acc, "null"];
4331
- case "symbol":
4332
- case "undefined":
4333
- case "function":
4334
- default:
4335
- return acc;
4336
- }
4337
- }, []);
4338
- if (types.length === options.length) {
4339
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
4340
- return {
4341
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
4342
- enum: options.reduce((acc, x) => {
4343
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
4344
- }, [])
4345
- };
4346
- }
4347
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
4348
- return {
4349
- type: "string",
4350
- enum: options.reduce((acc, x) => [
4351
- ...acc,
4352
- ...x._def.values.filter((x2) => !acc.includes(x2))
4353
- ], [])
4354
- };
4206
+ const {
4207
+ planner = simplePlanner,
4208
+ goal,
4209
+ events = agent.events,
4210
+ state,
4211
+ machine,
4212
+ model = agent.model,
4213
+ ...otherPlanInput
4214
+ } = resolvedOptions;
4215
+ const plan = await planner(agent, {
4216
+ model,
4217
+ goal,
4218
+ events,
4219
+ state,
4220
+ machine,
4221
+ ...otherPlanInput
4222
+ });
4223
+ if (plan?.nextEvent) {
4224
+ agent.addPlan(plan);
4225
+ await resolvedOptions.execute?.(plan.nextEvent);
4355
4226
  }
4356
- return asAnyOf(def, refs);
4227
+ return plan;
4357
4228
  }
4358
- var asAnyOf = (def, refs) => {
4359
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
4360
- ...refs,
4361
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
4362
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
4363
- return anyOf.length ? { anyOf } : void 0;
4364
- };
4365
-
4366
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
4367
- function parseNullableDef(def, refs) {
4368
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
4369
- if (refs.target === "openApi3") {
4370
- return {
4371
- type: primitiveMappings[def.innerType._def.typeName],
4372
- nullable: true
4373
- };
4229
+ function fromDecision(agent, defaultInput) {
4230
+ return (0, import_xstate2.fromPromise)(async ({ input, self }) => {
4231
+ const parentRef = self._parent;
4232
+ if (!parentRef) {
4233
+ return;
4374
4234
  }
4375
- return {
4376
- type: [
4377
- primitiveMappings[def.innerType._def.typeName],
4378
- "null"
4379
- ]
4235
+ const snapshot = parentRef.getSnapshot();
4236
+ const inputObject = typeof input === "string" ? { goal: input } : input;
4237
+ const resolvedInput = {
4238
+ ...defaultInput,
4239
+ ...inputObject
4380
4240
  };
4381
- }
4382
- if (refs.target === "openApi3") {
4383
- const base2 = parseDef(def.innerType._def, {
4384
- ...refs,
4385
- currentPath: [...refs.currentPath]
4241
+ const contextToInclude = resolvedInput.context === true ? (
4242
+ // include entire context
4243
+ parentRef.getSnapshot().context
4244
+ ) : resolvedInput.context;
4245
+ const state = {
4246
+ value: snapshot.value,
4247
+ context: contextToInclude
4248
+ };
4249
+ const plan = await agentDecide(agent, {
4250
+ machine: parentRef.src,
4251
+ state,
4252
+ execute: async (event) => {
4253
+ parentRef.send(event);
4254
+ },
4255
+ ...resolvedInput
4386
4256
  });
4387
- if (base2 && "$ref" in base2)
4388
- return { allOf: [base2], nullable: true };
4389
- return base2 && { ...base2, nullable: true };
4390
- }
4391
- const base = parseDef(def.innerType._def, {
4392
- ...refs,
4393
- currentPath: [...refs.currentPath, "anyOf", "0"]
4257
+ return plan;
4394
4258
  });
4395
- return base && { anyOf: [base, { type: "null" }] };
4396
4259
  }
4397
4260
 
4398
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
4399
- function parseNumberDef(def, refs) {
4400
- const res = {
4401
- type: "number"
4402
- };
4403
- if (!def.checks)
4404
- return res;
4405
- for (const check of def.checks) {
4406
- switch (check.kind) {
4407
- case "int":
4408
- res.type = "integer";
4409
- addErrorMessage(res, "type", check.message, refs);
4261
+ // src/adapters/vercel.ts
4262
+ var import_ai2 = require("ai");
4263
+ var vercelAdapter = {
4264
+ generateText: import_ai2.generateText,
4265
+ streamText: import_ai2.streamText
4266
+ };
4267
+
4268
+ // src/agent.ts
4269
+ var agentLogic = (0, import_xstate3.fromTransition)(
4270
+ (state, event, { emit }) => {
4271
+ switch (event.type) {
4272
+ case "agent.feedback": {
4273
+ state.feedback.push(event.feedback);
4274
+ emit({
4275
+ type: "feedback",
4276
+ // @ts-ignore TODO: fix types in XState
4277
+ feedback: event.feedback
4278
+ });
4410
4279
  break;
4411
- case "min":
4412
- if (refs.target === "jsonSchema7") {
4413
- if (check.inclusive) {
4414
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
4415
- } else {
4416
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
4417
- }
4418
- } else {
4419
- if (!check.inclusive) {
4420
- res.exclusiveMinimum = true;
4421
- }
4422
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
4423
- }
4280
+ }
4281
+ case "agent.observe": {
4282
+ state.observations.push(event.observation);
4283
+ emit({
4284
+ type: "observation",
4285
+ // @ts-ignore TODO: fix types in XState
4286
+ observation: event.observation
4287
+ });
4424
4288
  break;
4425
- case "max":
4426
- if (refs.target === "jsonSchema7") {
4427
- if (check.inclusive) {
4428
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
4429
- } else {
4430
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
4431
- }
4432
- } else {
4433
- if (!check.inclusive) {
4434
- res.exclusiveMaximum = true;
4435
- }
4436
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
4437
- }
4289
+ }
4290
+ case "agent.message": {
4291
+ state.messages.push(event.message);
4292
+ emit({
4293
+ type: "message",
4294
+ // @ts-ignore TODO: fix types in XState
4295
+ message: event.message
4296
+ });
4297
+ break;
4298
+ }
4299
+ case "agent.plan": {
4300
+ state.plans.push(event.plan);
4301
+ emit({
4302
+ type: "plan",
4303
+ // @ts-ignore TODO: fix types in XState
4304
+ plan: event.plan
4305
+ });
4438
4306
  break;
4439
- case "multipleOf":
4440
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
4307
+ }
4308
+ default:
4441
4309
  break;
4442
4310
  }
4443
- }
4444
- return res;
4445
- }
4446
-
4447
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
4448
- function parseObjectDef(def, refs) {
4449
- const result = {
4450
- type: "object",
4451
- ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
4452
- if (propDef === void 0 || propDef._def === void 0)
4453
- return acc;
4454
- const parsedDef = parseDef(propDef._def, {
4455
- ...refs,
4456
- currentPath: [...refs.currentPath, "properties", propName],
4457
- propertyPath: [...refs.currentPath, "properties", propName]
4458
- });
4459
- if (parsedDef === void 0)
4460
- return acc;
4461
- return {
4462
- properties: { ...acc.properties, [propName]: parsedDef },
4463
- required: propDef.isOptional() ? acc.required : [...acc.required, propName]
4464
- };
4465
- }, { properties: {}, required: [] }),
4466
- additionalProperties: def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, {
4467
- ...refs,
4468
- currentPath: [...refs.currentPath, "additionalProperties"]
4469
- }) ?? true
4311
+ return state;
4312
+ },
4313
+ {
4314
+ feedback: [],
4315
+ messages: [],
4316
+ observations: [],
4317
+ plans: []
4318
+ }
4319
+ );
4320
+ function createAgent({
4321
+ name,
4322
+ description,
4323
+ model,
4324
+ events,
4325
+ planner = simplePlanner,
4326
+ stringify = JSON.stringify,
4327
+ getMemory,
4328
+ logic = agentLogic,
4329
+ adapter = vercelAdapter,
4330
+ ...generateTextOptions
4331
+ }) {
4332
+ const messageHistoryListeners = [];
4333
+ const agent = (0, import_xstate3.createActor)(logic);
4334
+ agent.events = events;
4335
+ agent.model = model;
4336
+ agent.name = name;
4337
+ agent.description = description;
4338
+ agent.adapter = adapter;
4339
+ agent.defaultOptions = { ...generateTextOptions, model };
4340
+ agent.select = (selector) => {
4341
+ return selector(agent.getSnapshot().context);
4470
4342
  };
4471
- if (!result.required.length)
4472
- delete result.required;
4473
- return result;
4474
- }
4475
-
4476
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
4477
- var parseOptionalDef = (def, refs) => {
4478
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
4479
- return parseDef(def.innerType._def, refs);
4480
- }
4481
- const innerSchema = parseDef(def.innerType._def, {
4482
- ...refs,
4483
- currentPath: [...refs.currentPath, "anyOf", "1"]
4484
- });
4485
- return innerSchema ? {
4486
- anyOf: [
4487
- {
4488
- not: {}
4489
- },
4490
- innerSchema
4491
- ]
4492
- } : {};
4493
- };
4494
-
4495
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
4496
- var parsePipelineDef = (def, refs) => {
4497
- if (refs.pipeStrategy === "input") {
4498
- return parseDef(def.in._def, refs);
4499
- } else if (refs.pipeStrategy === "output") {
4500
- return parseDef(def.out._def, refs);
4501
- }
4502
- const a = parseDef(def.in._def, {
4503
- ...refs,
4504
- currentPath: [...refs.currentPath, "allOf", "0"]
4505
- });
4506
- const b = parseDef(def.out._def, {
4507
- ...refs,
4508
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
4509
- });
4510
- return {
4511
- allOf: [a, b].filter((x) => x !== void 0)
4343
+ agent.memory = getMemory ? getMemory(agent) : void 0;
4344
+ agent.onMessage = (callback) => {
4345
+ messageHistoryListeners.push((0, import_xstate3.toObserver)(callback));
4512
4346
  };
4513
- };
4514
-
4515
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
4516
- function parsePromiseDef(def, refs) {
4517
- return parseDef(def.type._def, refs);
4518
- }
4519
-
4520
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
4521
- function parseSetDef(def, refs) {
4522
- const items = parseDef(def.valueType._def, {
4523
- ...refs,
4524
- currentPath: [...refs.currentPath, "items"]
4525
- });
4526
- const schema = {
4527
- type: "array",
4528
- uniqueItems: true,
4529
- items
4347
+ agent.decide = (opts) => {
4348
+ return agentDecide(agent, opts);
4530
4349
  };
4531
- if (def.minSize) {
4532
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
4533
- }
4534
- if (def.maxSize) {
4535
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
4536
- }
4537
- return schema;
4538
- }
4539
-
4540
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
4541
- function parseTupleDef(def, refs) {
4542
- if (def.rest) {
4543
- return {
4544
- type: "array",
4545
- minItems: def.items.length,
4546
- items: def.items.map((x, i) => parseDef(x._def, {
4547
- ...refs,
4548
- currentPath: [...refs.currentPath, "items", `${i}`]
4549
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
4550
- additionalItems: parseDef(def.rest._def, {
4551
- ...refs,
4552
- currentPath: [...refs.currentPath, "additionalItems"]
4553
- })
4350
+ agent.addMessage = (messageInput) => {
4351
+ const message = {
4352
+ ...messageInput,
4353
+ id: messageInput.id ?? (0, import_crypto2.randomUUID)(),
4354
+ timestamp: messageInput.timestamp ?? Date.now(),
4355
+ sessionId: agent.sessionId
4554
4356
  };
4555
- } else {
4556
- return {
4557
- type: "array",
4558
- minItems: def.items.length,
4559
- maxItems: def.items.length,
4560
- items: def.items.map((x, i) => parseDef(x._def, {
4561
- ...refs,
4562
- currentPath: [...refs.currentPath, "items", `${i}`]
4563
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
4564
- };
4565
- }
4566
- }
4567
-
4568
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
4569
- function parseUndefinedDef() {
4570
- return {
4571
- not: {}
4357
+ agent.send({
4358
+ type: "agent.message",
4359
+ message
4360
+ });
4361
+ return message;
4572
4362
  };
4573
- }
4574
-
4575
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
4576
- function parseUnknownDef() {
4577
- return {};
4578
- }
4579
-
4580
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
4581
- var parseReadonlyDef = (def, refs) => {
4582
- return parseDef(def.innerType._def, refs);
4583
- };
4584
-
4585
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parseDef.js
4586
- function parseDef(def, refs, forceResolution = false) {
4587
- const seenItem = refs.seen.get(def);
4588
- if (seenItem && !forceResolution) {
4589
- const seenSchema = get$ref(seenItem, refs);
4590
- if (seenSchema !== void 0) {
4591
- return seenSchema;
4592
- }
4593
- }
4594
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
4595
- refs.seen.set(def, newItem);
4596
- const jsonSchema = selectParser(def, def.typeName, refs);
4597
- if (jsonSchema) {
4598
- addMeta(def, refs, jsonSchema);
4599
- }
4600
- newItem.jsonSchema = jsonSchema;
4601
- return jsonSchema;
4602
- }
4603
- var get$ref = (item, refs) => {
4604
- switch (refs.$refStrategy) {
4605
- case "root":
4606
- return { $ref: item.path.join("/") };
4607
- case "relative":
4608
- return { $ref: getRelativePath(refs.currentPath, item.path) };
4609
- case "none":
4610
- case "seen": {
4611
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
4612
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
4613
- return {};
4614
- }
4615
- return refs.$refStrategy === "seen" ? {} : void 0;
4616
- }
4617
- }
4618
- };
4619
- var getRelativePath = (pathA, pathB) => {
4620
- let i = 0;
4621
- for (; i < pathA.length && i < pathB.length; i++) {
4622
- if (pathA[i] !== pathB[i])
4623
- break;
4624
- }
4625
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
4626
- };
4627
- var selectParser = (def, typeName, refs) => {
4628
- switch (typeName) {
4629
- case ZodFirstPartyTypeKind.ZodString:
4630
- return parseStringDef(def, refs);
4631
- case ZodFirstPartyTypeKind.ZodNumber:
4632
- return parseNumberDef(def, refs);
4633
- case ZodFirstPartyTypeKind.ZodObject:
4634
- return parseObjectDef(def, refs);
4635
- case ZodFirstPartyTypeKind.ZodBigInt:
4636
- return parseBigintDef(def, refs);
4637
- case ZodFirstPartyTypeKind.ZodBoolean:
4638
- return parseBooleanDef();
4639
- case ZodFirstPartyTypeKind.ZodDate:
4640
- return parseDateDef(def, refs);
4641
- case ZodFirstPartyTypeKind.ZodUndefined:
4642
- return parseUndefinedDef();
4643
- case ZodFirstPartyTypeKind.ZodNull:
4644
- return parseNullDef(refs);
4645
- case ZodFirstPartyTypeKind.ZodArray:
4646
- return parseArrayDef(def, refs);
4647
- case ZodFirstPartyTypeKind.ZodUnion:
4648
- case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
4649
- return parseUnionDef(def, refs);
4650
- case ZodFirstPartyTypeKind.ZodIntersection:
4651
- return parseIntersectionDef(def, refs);
4652
- case ZodFirstPartyTypeKind.ZodTuple:
4653
- return parseTupleDef(def, refs);
4654
- case ZodFirstPartyTypeKind.ZodRecord:
4655
- return parseRecordDef(def, refs);
4656
- case ZodFirstPartyTypeKind.ZodLiteral:
4657
- return parseLiteralDef(def, refs);
4658
- case ZodFirstPartyTypeKind.ZodEnum:
4659
- return parseEnumDef(def);
4660
- case ZodFirstPartyTypeKind.ZodNativeEnum:
4661
- return parseNativeEnumDef(def);
4662
- case ZodFirstPartyTypeKind.ZodNullable:
4663
- return parseNullableDef(def, refs);
4664
- case ZodFirstPartyTypeKind.ZodOptional:
4665
- return parseOptionalDef(def, refs);
4666
- case ZodFirstPartyTypeKind.ZodMap:
4667
- return parseMapDef(def, refs);
4668
- case ZodFirstPartyTypeKind.ZodSet:
4669
- return parseSetDef(def, refs);
4670
- case ZodFirstPartyTypeKind.ZodLazy:
4671
- return parseDef(def.getter()._def, refs);
4672
- case ZodFirstPartyTypeKind.ZodPromise:
4673
- return parsePromiseDef(def, refs);
4674
- case ZodFirstPartyTypeKind.ZodNaN:
4675
- case ZodFirstPartyTypeKind.ZodNever:
4676
- return parseNeverDef();
4677
- case ZodFirstPartyTypeKind.ZodEffects:
4678
- return parseEffectsDef(def, refs);
4679
- case ZodFirstPartyTypeKind.ZodAny:
4680
- return parseAnyDef();
4681
- case ZodFirstPartyTypeKind.ZodUnknown:
4682
- return parseUnknownDef();
4683
- case ZodFirstPartyTypeKind.ZodDefault:
4684
- return parseDefaultDef(def, refs);
4685
- case ZodFirstPartyTypeKind.ZodBranded:
4686
- return parseBrandedDef(def, refs);
4687
- case ZodFirstPartyTypeKind.ZodReadonly:
4688
- return parseReadonlyDef(def, refs);
4689
- case ZodFirstPartyTypeKind.ZodCatch:
4690
- return parseCatchDef(def, refs);
4691
- case ZodFirstPartyTypeKind.ZodPipeline:
4692
- return parsePipelineDef(def, refs);
4693
- case ZodFirstPartyTypeKind.ZodFunction:
4694
- case ZodFirstPartyTypeKind.ZodVoid:
4695
- case ZodFirstPartyTypeKind.ZodSymbol:
4696
- return void 0;
4697
- default:
4698
- return /* @__PURE__ */ ((_) => void 0)(typeName);
4699
- }
4700
- };
4701
- var addMeta = (def, refs, jsonSchema) => {
4702
- if (def.description) {
4703
- jsonSchema.description = def.description;
4704
- if (refs.markdownDescription) {
4705
- jsonSchema.markdownDescription = def.description;
4706
- }
4707
- }
4708
- return jsonSchema;
4709
- };
4710
-
4711
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Refs.js
4712
- var getRefs = (options) => {
4713
- const _options = getDefaultOptions(options);
4714
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
4715
- return {
4716
- ..._options,
4717
- currentPath,
4718
- propertyPath: void 0,
4719
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
4720
- def._def,
4721
- {
4722
- def: def._def,
4723
- path: [..._options.basePath, _options.definitionPath, name],
4724
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
4725
- jsonSchema: void 0
4726
- }
4727
- ]))
4363
+ agent.generateText = (opts) => agentGenerateText(agent, opts);
4364
+ agent.streamText = (opts) => agentStreamText(agent, opts);
4365
+ agent.addFeedback = (feedbackInput) => {
4366
+ const feedback = {
4367
+ ...feedbackInput,
4368
+ timestamp: feedbackInput.timestamp ?? Date.now(),
4369
+ sessionId: agent.sessionId
4370
+ };
4371
+ agent.send({
4372
+ type: "agent.feedback",
4373
+ feedback
4374
+ });
4375
+ return feedback;
4728
4376
  };
4729
- };
4730
-
4731
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
4732
- var zodToJsonSchema = (schema, options) => {
4733
- const refs = getRefs(options);
4734
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
4735
- ...acc,
4736
- [name2]: parseDef(schema2._def, {
4737
- ...refs,
4738
- currentPath: [...refs.basePath, refs.definitionPath, name2]
4739
- }, true) ?? {}
4740
- }), {}) : void 0;
4741
- const name = typeof options === "string" ? options : options?.name;
4742
- const main = parseDef(schema._def, name === void 0 ? refs : {
4743
- ...refs,
4744
- currentPath: [...refs.basePath, refs.definitionPath, name]
4745
- }, false) ?? {};
4746
- const combined = name === void 0 ? definitions ? {
4747
- ...main,
4748
- [refs.definitionPath]: definitions
4749
- } : main : {
4750
- $ref: [
4751
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
4752
- refs.definitionPath,
4753
- name
4754
- ].join("/"),
4755
- [refs.definitionPath]: {
4756
- ...definitions,
4757
- [name]: main
4758
- }
4377
+ agent.addObservation = (observationInput) => {
4378
+ const observation = {
4379
+ ...observationInput,
4380
+ id: observationInput.id ?? (0, import_crypto2.randomUUID)(),
4381
+ sessionId: agent.sessionId,
4382
+ timestamp: observationInput.timestamp ?? Date.now()
4383
+ };
4384
+ agent.send({
4385
+ type: "agent.observe",
4386
+ observation
4387
+ });
4388
+ return observation;
4759
4389
  };
4760
- if (refs.target === "jsonSchema7") {
4761
- combined.$schema = "http://json-schema.org/draft-07/schema#";
4762
- } else if (refs.target === "jsonSchema2019-09") {
4763
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
4764
- }
4765
- return combined;
4766
- };
4767
-
4768
- // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/index.js
4769
- var esm_default = zodToJsonSchema;
4770
-
4771
- // src/utils.ts
4772
- function getAllTransitions(state) {
4773
- const nodes = state._nodes;
4774
- const transitions = nodes.map((node) => [...node.transitions.values()]).flat(2);
4775
- return transitions;
4776
- }
4777
- function createZodEventSchemas(eventSchemaMap) {
4778
- const resolvedEventSchemaMap = {};
4779
- for (const [eventType, zodType] of Object.entries(eventSchemaMap)) {
4780
- resolvedEventSchemaMap[eventType] = esm_default(
4781
- zodType.extend({
4782
- type: z.literal(eventType)
4783
- })
4784
- );
4785
- }
4786
- return resolvedEventSchemaMap;
4787
- }
4788
-
4789
- // src/schemas.ts
4790
- function defineEvents(events) {
4791
- return {
4792
- types: {},
4793
- schemas: createZodEventSchemas(events)
4390
+ agent.addPlan = (plan) => {
4391
+ agent.send({
4392
+ type: "agent.plan",
4393
+ plan
4394
+ });
4794
4395
  };
4795
- }
4796
-
4797
- // src/agent.ts
4798
- var import_xstate = require("xstate");
4799
- function createAgent(...args) {
4800
- const [machine, options] = args;
4801
- return (0, import_xstate.createActor)(machine, options);
4802
- }
4803
-
4804
- // src/adapters/openai.ts
4805
- var import_xstate2 = require("xstate");
4806
- function fromChatCompletion(openai, agentSettings, inputFn) {
4807
- return (0, import_xstate2.fromPromise)(
4808
- async ({ input }) => {
4809
- const openAiInput = inputFn(input);
4810
- const params = typeof openAiInput === "string" ? {
4811
- model: agentSettings.model,
4812
- messages: [
4813
- {
4814
- role: "user",
4815
- content: openAiInput
4816
- }
4817
- ]
4818
- } : openAiInput;
4819
- const response = await openai.chat.completions.create(params);
4820
- return response;
4821
- }
4822
- );
4823
- }
4824
- function fromChatStream(openai, agentSettings, inputFn) {
4825
- return (0, import_xstate2.fromObservable)(
4826
- ({ input }) => {
4827
- const observers = /* @__PURE__ */ new Set();
4828
- (async () => {
4829
- const openAiInput = inputFn(input);
4830
- const resolvedParams = typeof openAiInput === "string" ? {
4831
- model: agentSettings.model,
4832
- messages: [
4833
- {
4834
- role: "user",
4835
- content: openAiInput
4836
- }
4837
- ]
4838
- } : openAiInput;
4839
- const stream = await openai.chat.completions.create({
4840
- ...resolvedParams,
4841
- stream: true
4842
- });
4843
- for await (const part of stream) {
4844
- observers.forEach((observer) => {
4845
- observer.next?.(part);
4846
- });
4847
- }
4848
- })();
4849
- return {
4850
- subscribe: (...args) => {
4851
- const observer = (0, import_xstate2.toObserver)(...args);
4852
- observers.add(observer);
4853
- return {
4854
- unsubscribe: () => {
4855
- observers.delete(observer);
4856
- }
4857
- };
4858
- }
4859
- };
4860
- }
4861
- );
4862
- }
4863
- function fromEvent(openai, agentSettings, inputFn) {
4864
- return (0, import_xstate2.fromPromise)(
4865
- async ({ input, self, system }) => {
4866
- const parentSnapshot = self._parent?.getSnapshot();
4867
- if (!parentSnapshot || !(0, import_xstate2.isMachineSnapshot)(parentSnapshot)) {
4868
- return void 0;
4869
- }
4870
- const schemas = parentSnapshot.machine.schemas;
4871
- const eventSchemaMap = schemas.events ?? {};
4872
- const transitions = getAllTransitions(self._parent.getSnapshot());
4873
- const functionNameMapping = {};
4874
- const tools = transitions.filter((t) => {
4875
- return !t.eventType.startsWith("xstate.");
4876
- }).map((t) => {
4877
- const name = t.eventType.replace(/\./g, "_");
4878
- functionNameMapping[name] = t.eventType;
4879
- const eventSchema = eventSchemaMap[t.eventType];
4880
- const {
4881
- description,
4882
- properties: { type, ...properties }
4883
- } = eventSchema ?? {};
4884
- return {
4885
- type: "function",
4886
- function: {
4887
- name,
4888
- description: t.description ?? description,
4889
- parameters: {
4890
- type: "object",
4891
- properties: properties ?? {}
4892
- }
4893
- }
4894
- };
4895
- });
4896
- const openAiInput = inputFn(input);
4897
- const completionParams = typeof openAiInput === "string" ? {
4898
- model: agentSettings.model,
4899
- messages: [
4900
- {
4901
- role: "user",
4902
- content: openAiInput
4903
- }
4904
- ]
4905
- } : openAiInput;
4906
- const completion = await openai.chat.completions.create({
4907
- ...completionParams,
4908
- tools
4909
- });
4910
- const toolCalls = completion.choices[0]?.message.tool_calls;
4911
- if (toolCalls?.length) {
4912
- const events = toolCalls.map((tc) => {
4913
- return {
4914
- type: functionNameMapping[tc.function.name],
4915
- ...JSON.parse(tc.function.arguments)
4916
- };
4396
+ agent.interact = (actorRef, getInput) => {
4397
+ let prevState = void 0;
4398
+ let subscribed = true;
4399
+ async function handleObservation(observationInput) {
4400
+ const observation = agent.addObservation(observationInput);
4401
+ const input = getInput?.(observation);
4402
+ if (input) {
4403
+ await agentDecide(agent, {
4404
+ machine: actorRef.src,
4405
+ state: observation.state,
4406
+ execute: async (event) => {
4407
+ actorRef.send(event);
4408
+ },
4409
+ ...input
4917
4410
  });
4918
- const event = events[0];
4919
- system._relay(self, self._parent, event);
4920
4411
  }
4921
- return void 0;
4412
+ prevState = observationInput.state;
4922
4413
  }
4923
- );
4924
- }
4925
- function fromTool(openai, agentSettings, tools, inputFn) {
4926
- return (0, import_xstate2.fromPromise)(async ({ input }) => {
4927
- const resolvedTools = Object.entries(tools).map(([key, value]) => {
4928
- return {
4929
- type: "function",
4930
- function: {
4931
- name: key,
4932
- description: value.description,
4933
- parameters: value.inputSchema
4414
+ actorRef.system.inspect({
4415
+ next: async (inspEvent) => {
4416
+ if (!subscribed || inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
4417
+ return;
4934
4418
  }
4935
- };
4936
- });
4937
- const openAiInput = inputFn(input);
4938
- const completionParams = typeof openAiInput === "string" ? {
4939
- model: agentSettings.model,
4940
- messages: [
4941
- {
4942
- role: "user",
4943
- content: openAiInput
4944
- }
4945
- ]
4946
- } : openAiInput;
4947
- const completion = await openai.chat.completions.create({
4948
- ...completionParams,
4949
- tools: resolvedTools
4950
- });
4951
- const toolCalls = completion.choices[0]?.message.tool_calls;
4952
- if (toolCalls?.length) {
4953
- const toolCall = toolCalls[0];
4954
- const tool = tools[toolCall.function.name];
4955
- const args = JSON.parse(toolCall.function.arguments);
4956
- if (tool) {
4957
- const result = await tool.run(args);
4958
- return {
4959
- toolCall,
4960
- tool: toolCall.function.name,
4961
- result
4419
+ const observationInput = {
4420
+ event: inspEvent.event,
4421
+ prevState,
4422
+ state: inspEvent.snapshot
4962
4423
  };
4424
+ await handleObservation(observationInput);
4963
4425
  }
4426
+ });
4427
+ if (actorRef._processingStatus === 1) {
4428
+ handleObservation({
4429
+ prevState: void 0,
4430
+ event: { type: "" },
4431
+ // TODO: unknown events?
4432
+ state: actorRef.getSnapshot()
4433
+ });
4964
4434
  }
4965
- return void 0;
4966
- });
4967
- }
4968
- function createOpenAIAdapter(openai, settings) {
4969
- const agentSettings = {
4970
- model: settings.model,
4971
- fromEvent: (input) => fromEvent(openai, agentSettings, input),
4972
- fromChat: (input) => fromChatCompletion(openai, agentSettings, input),
4973
- fromChatStream: (input) => fromChatStream(openai, agentSettings, input),
4974
- fromTool: (input, tools) => fromTool(openai, agentSettings, tools, input)
4435
+ return {
4436
+ unsubscribe: () => {
4437
+ subscribed = false;
4438
+ }
4439
+ // TODO: make this actually unsubscribe
4440
+ };
4975
4441
  };
4976
- return agentSettings;
4442
+ agent.start();
4443
+ return agent;
4977
4444
  }
4978
4445
  // Annotate the CommonJS export names for ESM import in node:
4979
4446
  0 && (module.exports = {
4447
+ agentDecide,
4448
+ agentGenerateText,
4980
4449
  createAgent,
4981
- createOpenAIAdapter,
4982
- defineEvents
4450
+ fromDecision,
4451
+ fromText,
4452
+ fromTextStream
4983
4453
  });