@ax-llm/ax 11.0.16 → 11.0.18

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/index.js CHANGED
@@ -221,28 +221,24 @@ var AxAIServiceError = class extends Error {
221
221
  this.timestamp = (/* @__PURE__ */ new Date()).toISOString();
222
222
  this.errorId = crypto.randomUUID();
223
223
  this.context = context;
224
+ this.stack = this.toString();
224
225
  }
225
226
  timestamp;
226
227
  errorId;
227
228
  context;
228
229
  toString() {
229
- return `${this.name} [${this.errorId}]: ${this.message}
230
- Timestamp: ${this.timestamp}
231
- URL: ${this.url}${this.requestBody ? `
232
- Request Body: ${JSON.stringify(this.requestBody, null, 2)}` : ""}${Object.keys(this.context).length ? `
233
- Context: ${JSON.stringify(this.context, null, 2)}` : ""}`;
234
- }
235
- toJSON() {
236
- return {
237
- name: this.name,
238
- errorId: this.errorId,
239
- message: this.message,
240
- timestamp: this.timestamp,
241
- url: this.url,
242
- requestBody: this.requestBody,
243
- context: this.context,
244
- stack: this.stack
245
- };
230
+ return [
231
+ `${this.name}: ${this.message}`,
232
+ `URL: ${this.url}`,
233
+ `Request Body: ${JSON.stringify(this.requestBody, null, 2)}`,
234
+ `Context: ${JSON.stringify(this.context, null, 2)}`,
235
+ `Timestamp: ${this.timestamp}`,
236
+ `Error ID: ${this.errorId}`
237
+ ].join("\n");
238
+ }
239
+ // For Node.js, override the custom inspect method so console.log shows our custom string.
240
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, _options) {
241
+ return this.toString();
246
242
  }
247
243
  };
248
244
  var AxAIServiceStatusError = class extends AxAIServiceError {
@@ -560,6 +556,37 @@ var apiCall = async (api, json) => {
560
556
  }
561
557
  };
562
558
 
559
+ // util/transform.ts
560
+ import {
561
+ TransformStream as TransformStream4
562
+ } from "stream/web";
563
+ var TypeTransformer = class {
564
+ buffer;
565
+ doneCallback;
566
+ transformFn;
567
+ constructor(transformFn, doneCallback) {
568
+ this.transformFn = transformFn;
569
+ this.doneCallback = doneCallback;
570
+ this.buffer = doneCallback ? [] : void 0;
571
+ }
572
+ async transform(obj, controller) {
573
+ const val = this.transformFn(obj);
574
+ if (val) {
575
+ controller.enqueue(val);
576
+ this.buffer?.push(val);
577
+ }
578
+ }
579
+ async flush(controller) {
580
+ await this.doneCallback?.(this.buffer ?? []);
581
+ controller.terminate();
582
+ }
583
+ };
584
+ var RespTransformStream = class extends TransformStream4 {
585
+ constructor(transformFn, doneCallback) {
586
+ super(new TypeTransformer(transformFn, doneCallback));
587
+ }
588
+ };
589
+
563
590
  // util/log.ts
564
591
  var ColorLog = class {
565
592
  // ANSI escape codes for different colors
@@ -591,44 +618,106 @@ var ColorLog = class {
591
618
  }
592
619
  };
593
620
 
594
- // util/transform.ts
595
- import {
596
- TransformStream as TransformStream4
597
- } from "stream/web";
598
- var TypeTransformer = class {
599
- buffer;
600
- doneCallback;
601
- transformFn;
602
- constructor(transformFn, doneCallback) {
603
- this.transformFn = transformFn;
604
- this.doneCallback = doneCallback;
605
- this.buffer = doneCallback ? [] : void 0;
606
- }
607
- async transform(obj, controller) {
608
- const val = this.transformFn(obj);
609
- if (val) {
610
- controller.enqueue(val);
611
- this.buffer?.push(val);
621
+ // ai/debug.ts
622
+ var colorLog = new ColorLog();
623
+ var formatChatMessage = (msg, hideContent) => {
624
+ switch (msg.role) {
625
+ case "system":
626
+ return `
627
+ ${colorLog.blueBright("System:")}
628
+ ${colorLog.whiteBright(msg.content)}`;
629
+ case "function":
630
+ return `
631
+ ${colorLog.blueBright("Function Result:")}
632
+ ${colorLog.whiteBright(msg.result)}`;
633
+ case "user": {
634
+ if (typeof msg.content === "string") {
635
+ return `
636
+ ${colorLog.blueBright("User:")}
637
+ ${colorLog.whiteBright(msg.content)}`;
638
+ }
639
+ const items = msg.content.map((v) => {
640
+ switch (v.type) {
641
+ case "text":
642
+ return `${colorLog.whiteBright(v.text)}`;
643
+ case "image":
644
+ return `(Image, ${v.mimeType}) ${colorLog.whiteBright(v.image.substring(0, 10))}`;
645
+ default:
646
+ throw new Error("Invalid content type");
647
+ }
648
+ });
649
+ return `
650
+ ${colorLog.blueBright("User:")}
651
+ ${items.join("\n")}`;
652
+ }
653
+ case "assistant": {
654
+ if (msg.functionCalls) {
655
+ const fns = msg.functionCalls?.map(({ function: fn }) => {
656
+ const args = typeof fn.params !== "string" ? JSON.stringify(fn.params, null, 2) : fn.params;
657
+ return `${fn.name}(${args})`;
658
+ });
659
+ return `
660
+ ${colorLog.blueBright("\nFunctions:")}
661
+ ${colorLog.whiteBright(fns.join("\n"))}`;
662
+ }
663
+ return `
664
+ ${colorLog.blueBright("\nAssistant:")}
665
+ ${hideContent ? "" : colorLog.whiteBright(msg.content ?? "<empty>")}`;
612
666
  }
667
+ default:
668
+ throw new Error("Invalid role");
613
669
  }
614
- async flush(controller) {
615
- await this.doneCallback?.(this.buffer ?? []);
616
- controller.terminate();
670
+ };
671
+ var logChatRequestMessage = (msg) => {
672
+ process.stdout.write(formatChatMessage(msg) + "\n");
673
+ process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
674
+ };
675
+ var logChatRequest = (chatPrompt) => {
676
+ const items = chatPrompt?.map((msg) => formatChatMessage(msg));
677
+ if (items) {
678
+ process.stdout.write(items.join("\n"));
679
+ process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
617
680
  }
618
681
  };
619
- var RespTransformStream = class extends TransformStream4 {
620
- constructor(transformFn, doneCallback) {
621
- super(new TypeTransformer(transformFn, doneCallback));
682
+ var logResponseResult = (r) => {
683
+ if (r.content) {
684
+ process.stdout.write(colorLog.greenBright(r.content));
685
+ }
686
+ if (r.functionCalls) {
687
+ for (const [i, f] of r.functionCalls.entries()) {
688
+ if (f.function.name) {
689
+ if (i > 0) {
690
+ process.stdout.write("\n");
691
+ }
692
+ process.stdout.write(
693
+ `Function ${i + 1} -> ${colorLog.greenBright(f.function.name)}`
694
+ );
695
+ }
696
+ if (f.function.params) {
697
+ const params = typeof f.function.params === "string" ? f.function.params : JSON.stringify(f.function.params, null, 2);
698
+ process.stdout.write(`${colorLog.greenBright(params)}`);
699
+ }
700
+ }
622
701
  }
623
702
  };
703
+ var logResponse = (resp) => {
704
+ if (!resp.results) {
705
+ return;
706
+ }
707
+ for (const r of resp.results) {
708
+ logResponseResult(r);
709
+ }
710
+ };
711
+ var logResponseDelta = (delta) => {
712
+ process.stdout.write(colorLog.greenBright(delta));
713
+ };
624
714
 
625
715
  // ai/base.ts
626
- var colorLog = new ColorLog();
627
716
  var axBaseAIDefaultConfig = () => structuredClone({
628
717
  maxTokens: 2e3,
629
718
  temperature: 0,
630
719
  topK: 40,
631
- frequencyPenalty: 0.2
720
+ topP: 0.9
632
721
  });
633
722
  var AxBaseAI = class {
634
723
  constructor(aiImpl, {
@@ -908,8 +997,8 @@ var AxBaseAI = class {
908
997
  );
909
998
  return res2;
910
999
  };
911
- if (this.debug) {
912
- logChatRequest(req);
1000
+ if (options?.debug ?? this.debug) {
1001
+ logChatRequest(req["chatPrompt"]);
913
1002
  }
914
1003
  const rt = options?.rateLimiter ?? this.rt;
915
1004
  const rv = rt ? await rt(fn, { modelUsage: this.modelUsage }) : await fn();
@@ -927,13 +1016,13 @@ var AxBaseAI = class {
927
1016
  if (span?.isRecording()) {
928
1017
  setResponseAttr(res2, span);
929
1018
  }
930
- if (this.debug) {
1019
+ if (options?.debug ?? this.debug) {
931
1020
  logResponse(res2);
932
1021
  }
933
1022
  return res2;
934
1023
  };
935
1024
  const doneCb = async (_values) => {
936
- if (this.debug) {
1025
+ if (options?.debug ?? this.debug) {
937
1026
  process.stdout.write("\n");
938
1027
  }
939
1028
  };
@@ -956,7 +1045,7 @@ var AxBaseAI = class {
956
1045
  if (span?.isRecording()) {
957
1046
  setResponseAttr(res, span);
958
1047
  }
959
- if (this.debug) {
1048
+ if (options?.debug ?? this.debug) {
960
1049
  logResponse(res);
961
1050
  }
962
1051
  span?.end();
@@ -1047,83 +1136,6 @@ var AxBaseAI = class {
1047
1136
  return { ...headers, ...await this.headers() };
1048
1137
  }
1049
1138
  };
1050
- var logChatRequest = (req) => {
1051
- const hasAssistant = req.chatPrompt?.some((msg) => msg.role === "assistant");
1052
- const items = req.chatPrompt?.map((msg) => {
1053
- if (hasAssistant && msg.role === "system") {
1054
- return "";
1055
- }
1056
- switch (msg.role) {
1057
- case "system":
1058
- return `${colorLog.blueBright("System:")}
1059
- ${colorLog.whiteBright(msg.content)}`;
1060
- case "function":
1061
- return `${colorLog.blueBright("Function Result:")}
1062
- ${colorLog.whiteBright(msg.result)}`;
1063
- case "user": {
1064
- if (typeof msg.content === "string") {
1065
- return `${colorLog.blueBright("User:")}
1066
- ${colorLog.whiteBright(msg.content)}`;
1067
- }
1068
- const items2 = msg.content.map((v) => {
1069
- switch (v.type) {
1070
- case "text":
1071
- return `${colorLog.whiteBright(v.text)}`;
1072
- case "image":
1073
- return `(Image, ${v.mimeType}) ${colorLog.whiteBright(v.image.substring(0, 10))}`;
1074
- default:
1075
- throw new Error("Invalid content type");
1076
- }
1077
- });
1078
- return `${colorLog.blueBright("User:")}
1079
- ${items2.join("\n")}`;
1080
- }
1081
- case "assistant": {
1082
- if (msg.functionCalls) {
1083
- const fns = msg.functionCalls?.map(({ function: fn }) => {
1084
- const args = typeof fn.params !== "string" ? JSON.stringify(fn.params, null, 2) : fn.params;
1085
- return `${fn.name}(${args})`;
1086
- });
1087
- return `${colorLog.blueBright("\nFunctions:")}
1088
- ${colorLog.whiteBright(fns.join("\n"))}`;
1089
- }
1090
- return `${colorLog.blueBright("\nAssistant:")}
1091
- ${colorLog.whiteBright(msg.content ?? "<empty>")}`;
1092
- }
1093
- default:
1094
- throw new Error("Invalid role");
1095
- }
1096
- });
1097
- if (items) {
1098
- process.stdout.write("\n===\n" + items.join("\n") + "\n\n---\n");
1099
- }
1100
- };
1101
- var logResponse = (resp) => {
1102
- if (!resp.results) {
1103
- return;
1104
- }
1105
- for (const r of resp.results) {
1106
- if (r.content) {
1107
- process.stdout.write(colorLog.greenBright(r.content));
1108
- }
1109
- if (r.functionCalls) {
1110
- for (const [i, f] of r.functionCalls.entries()) {
1111
- if (f.function.name) {
1112
- if (i > 0) {
1113
- process.stdout.write("\n\n");
1114
- }
1115
- process.stdout.write(
1116
- `Function ${i + 1} -> ${colorLog.greenBright(f.function.name)} `
1117
- );
1118
- }
1119
- if (f.function.params) {
1120
- const params = typeof f.function.params === "string" ? f.function.params : JSON.stringify(f.function.params, null, 2);
1121
- process.stdout.write(`${colorLog.greenBright(params)}`);
1122
- }
1123
- }
1124
- }
1125
- }
1126
- };
1127
1139
  var setResponseAttr = (res, span) => {
1128
1140
  if (res.modelUsage) {
1129
1141
  span.setAttributes({
@@ -2747,8 +2759,10 @@ var AxAIGoogleGeminiImpl = class {
2747
2759
  temperature: req.modelConfig?.temperature ?? this.config.temperature,
2748
2760
  topP: req.modelConfig?.topP ?? this.config.topP,
2749
2761
  topK: req.modelConfig?.topK ?? this.config.topK,
2762
+ frequencyPenalty: req.modelConfig?.frequencyPenalty ?? this.config.frequencyPenalty,
2750
2763
  candidateCount: 1,
2751
- stopSequences: req.modelConfig?.stopSequences ?? this.config.stopSequences
2764
+ stopSequences: req.modelConfig?.stopSequences ?? this.config.stopSequences,
2765
+ responseMimeType: "text/plain"
2752
2766
  };
2753
2767
  const safetySettings2 = this.config.safetySettings;
2754
2768
  const reqValue = {
@@ -3693,14 +3707,15 @@ function mergeFunctionCalls(functionCalls, functionCallDeltas) {
3693
3707
  // mem/memory.ts
3694
3708
  var defaultLimit = 1e4;
3695
3709
  var MemoryImpl = class {
3696
- constructor(limit = defaultLimit) {
3710
+ constructor(limit = defaultLimit, debug = false) {
3697
3711
  this.limit = limit;
3712
+ this.debug = debug;
3698
3713
  if (limit <= 0) {
3699
3714
  throw Error("argument 'limit' must be greater than 0");
3700
3715
  }
3701
3716
  }
3702
3717
  data = [];
3703
- add(value) {
3718
+ addMemory(value) {
3704
3719
  if (Array.isArray(value)) {
3705
3720
  this.data.push(...value.map((chat) => ({ chat: structuredClone(chat) })));
3706
3721
  } else {
@@ -3713,7 +3728,13 @@ var MemoryImpl = class {
3713
3728
  this.data.splice(0, removeCount);
3714
3729
  }
3715
3730
  }
3716
- addResult({
3731
+ add(value) {
3732
+ this.addMemory(value);
3733
+ if (this.debug) {
3734
+ debugRequest(value);
3735
+ }
3736
+ }
3737
+ addResultMessage({
3717
3738
  content,
3718
3739
  name,
3719
3740
  functionCalls
@@ -3721,26 +3742,44 @@ var MemoryImpl = class {
3721
3742
  if (!content && (!functionCalls || functionCalls.length === 0)) {
3722
3743
  return;
3723
3744
  }
3724
- this.add({ content, name, role: "assistant", functionCalls });
3745
+ this.addMemory({ content, name, role: "assistant", functionCalls });
3725
3746
  }
3726
- updateResult({
3747
+ addResult({
3727
3748
  content,
3728
3749
  name,
3729
3750
  functionCalls
3751
+ }) {
3752
+ this.addResultMessage({ content, name, functionCalls });
3753
+ if (this.debug) {
3754
+ debugResponse({ content, name, functionCalls });
3755
+ }
3756
+ }
3757
+ updateResult({
3758
+ content,
3759
+ name,
3760
+ functionCalls,
3761
+ delta
3730
3762
  }) {
3731
3763
  const lastItem = this.data.at(-1);
3732
3764
  if (!lastItem || lastItem.chat.role !== "assistant") {
3733
- this.addResult({ content, name, functionCalls });
3734
- return;
3735
- }
3736
- if ("content" in lastItem.chat && content) {
3737
- lastItem.chat.content = content;
3738
- }
3739
- if ("name" in lastItem.chat && name) {
3740
- lastItem.chat.name = name;
3765
+ this.addResultMessage({ content, name, functionCalls });
3766
+ } else {
3767
+ if ("content" in lastItem.chat && content) {
3768
+ lastItem.chat.content = content;
3769
+ }
3770
+ if ("name" in lastItem.chat && name) {
3771
+ lastItem.chat.name = name;
3772
+ }
3773
+ if ("functionCalls" in lastItem.chat && functionCalls) {
3774
+ lastItem.chat.functionCalls = functionCalls;
3775
+ }
3741
3776
  }
3742
- if ("functionCalls" in lastItem.chat && functionCalls) {
3743
- lastItem.chat.functionCalls = functionCalls;
3777
+ if (this.debug) {
3778
+ if (delta) {
3779
+ debugResponseDelta(delta);
3780
+ } else if (lastItem) {
3781
+ debugResponse({ content, name, functionCalls });
3782
+ }
3744
3783
  }
3745
3784
  }
3746
3785
  addTag(name) {
@@ -3780,16 +3819,21 @@ var MemoryImpl = class {
3780
3819
  }
3781
3820
  getLast() {
3782
3821
  const lastItem = this.data.at(-1);
3783
- return lastItem?.chat;
3822
+ if (!lastItem) return void 0;
3823
+ return {
3824
+ chat: lastItem.chat,
3825
+ tags: lastItem.tags
3826
+ };
3784
3827
  }
3785
3828
  reset() {
3786
3829
  this.data = [];
3787
3830
  }
3788
3831
  };
3789
3832
  var AxMemory = class {
3790
- constructor(limit = defaultLimit) {
3833
+ constructor(limit = defaultLimit, debug = false) {
3791
3834
  this.limit = limit;
3792
- this.defaultMemory = new MemoryImpl(limit);
3835
+ this.debug = debug;
3836
+ this.defaultMemory = new MemoryImpl(limit, debug);
3793
3837
  }
3794
3838
  memories = /* @__PURE__ */ new Map();
3795
3839
  defaultMemory;
@@ -3831,6 +3875,19 @@ var AxMemory = class {
3831
3875
  }
3832
3876
  }
3833
3877
  };
3878
+ function debugRequest(value) {
3879
+ if (Array.isArray(value)) {
3880
+ logChatRequest(value);
3881
+ } else {
3882
+ logChatRequestMessage(value);
3883
+ }
3884
+ }
3885
+ function debugResponse(value) {
3886
+ logResponseResult(value);
3887
+ }
3888
+ function debugResponseDelta(delta) {
3889
+ logResponseDelta(delta);
3890
+ }
3834
3891
 
3835
3892
  // dsp/asserts.ts
3836
3893
  var AxAssertionError = class extends Error {
@@ -3865,7 +3922,7 @@ var assertAssertions = (asserts, values) => {
3865
3922
  }
3866
3923
  }
3867
3924
  };
3868
- var assertStreamingAssertions = (asserts, values, xstate, content, final) => {
3925
+ var assertStreamingAssertions = (asserts, xstate, content, final = false) => {
3869
3926
  if (!xstate.currField || xstate.s === -1 || !asserts || asserts.length === 0) {
3870
3927
  return;
3871
3928
  }
@@ -4068,7 +4125,8 @@ ${pointer}`;
4068
4125
  "image",
4069
4126
  "audio",
4070
4127
  "datetime",
4071
- "date"
4128
+ "date",
4129
+ "code"
4072
4130
  ];
4073
4131
  const foundType = types.find((type) => this.match(type));
4074
4132
  if (!foundType) {
@@ -4375,6 +4433,8 @@ var validateValue = (field, value) => {
4375
4433
  const ft = field.type ?? { name: "string", isArray: false };
4376
4434
  const validateSingleValue = (expectedType, val) => {
4377
4435
  switch (expectedType) {
4436
+ case "code":
4437
+ return typeof val === "string";
4378
4438
  case "string":
4379
4439
  return typeof val === "string";
4380
4440
  case "number":
@@ -4508,7 +4568,9 @@ function mergeDeltas(base, delta) {
4508
4568
  for (const key of Object.keys(delta)) {
4509
4569
  const baseValue = base[key];
4510
4570
  const deltaValue = delta[key];
4511
- if ((baseValue === void 0 || Array.isArray(baseValue)) && Array.isArray(deltaValue)) {
4571
+ if (baseValue === void 0 && Array.isArray(deltaValue)) {
4572
+ base[key] = [...deltaValue];
4573
+ } else if (Array.isArray(baseValue) && Array.isArray(deltaValue)) {
4512
4574
  base[key] = [...baseValue ?? [], ...deltaValue];
4513
4575
  } else if ((baseValue === void 0 || typeof baseValue === "string") && typeof deltaValue === "string") {
4514
4576
  base[key] = (baseValue ?? "") + deltaValue;
@@ -4546,7 +4608,10 @@ var LRUCache = class {
4546
4608
  };
4547
4609
  var globalPrefixCache = new LRUCache(500);
4548
4610
  function matchesContent(content, prefix, startIndex = 0, prefixCache = globalPrefixCache) {
4549
- if (/^\s*$/.test(content)) {
4611
+ if (/^```[a-zA-Z]*\s*$/.test(content)) {
4612
+ return -4;
4613
+ }
4614
+ if (/^[\s`]*$/.test(content)) {
4550
4615
  return -3;
4551
4616
  }
4552
4617
  const exactMatchIndex = content.indexOf(prefix, startIndex);
@@ -4758,12 +4823,11 @@ var functionCallInstructions = `
4758
4823
  - Call functions step-by-step, using the output of one function as input to the next.
4759
4824
  - Use the function results to generate the output fields.`;
4760
4825
  var formattingRules = `
4761
- ## Output Formatting Rules
4762
- - Output must strictly follow the defined plain-text \`key: value\` field format.
4763
- - Each output key, value must strictly adhere to the specified output field formatting rules.
4764
- - No preamble, postscript, or supplementary information.
4765
- - Do not repeat output fields.
4766
- - Do not use JSON to format the output.`;
4826
+ ## Strict Output Formatting Rules
4827
+ - Output must strictly follow the defined plain-text \`field name: value\` field format.
4828
+ - Output field, values must strictly adhere to the specified output field formatting rules.
4829
+ - Do not add any text before or after the output fields, just the field name and value.
4830
+ - Do not use code blocks.`;
4767
4831
  var AxPromptTemplate = class {
4768
4832
  sig;
4769
4833
  fieldTemplates;
@@ -4772,25 +4836,23 @@ var AxPromptTemplate = class {
4772
4836
  this.sig = sig;
4773
4837
  this.fieldTemplates = fieldTemplates;
4774
4838
  const task = [];
4775
- const inArgs = this.renderDescFields(this.sig.getInputFields());
4776
- const outArgs = this.renderDescFields(this.sig.getOutputFields());
4839
+ const inArgs = renderDescFields(this.sig.getInputFields());
4840
+ const outArgs = renderDescFields(this.sig.getOutputFields());
4777
4841
  task.push(
4778
4842
  `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
4779
4843
  );
4780
4844
  const funcs = functions?.map(
4781
4845
  (f) => "toFunction" in f ? f.toFunction() : f
4782
4846
  );
4783
- const funcList = funcs?.map(
4784
- (fn) => `- \`${fn.name}\`: ${capitalizeFirstLetter(fn.description)}.`
4785
- ).join("\n");
4847
+ const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
4786
4848
  if (funcList && funcList.length > 0) {
4787
4849
  task.push(`## Available Functions
4788
4850
  ${funcList}`);
4789
4851
  }
4790
- const inputFields = this.renderFields(this.sig.getInputFields());
4852
+ const inputFields = renderInputFields(this.sig.getInputFields());
4791
4853
  task.push(`## Input Fields
4792
4854
  ${inputFields}`);
4793
- const outputFields = this.renderFields(this.sig.getOutputFields());
4855
+ const outputFields = renderOutputFields(this.sig.getOutputFields());
4794
4856
  task.push(`## Output Fields
4795
4857
  ${outputFields}`);
4796
4858
  if (funcList && funcList.length > 0) {
@@ -4799,10 +4861,8 @@ ${outputFields}`);
4799
4861
  task.push(formattingRules.trim());
4800
4862
  const desc = this.sig.getDescription();
4801
4863
  if (desc) {
4802
- const capitalized = capitalizeFirstLetter(desc.trim());
4803
- const text = capitalized.endsWith(".") ? capitalized : capitalized + ".";
4804
- task.push(`---
4805
- ${text}`);
4864
+ const text = formatDescription(desc);
4865
+ task.push(text);
4806
4866
  }
4807
4867
  this.task = {
4808
4868
  type: "text",
@@ -4825,7 +4885,7 @@ ${text}`);
4825
4885
  let systemContent = this.task.text;
4826
4886
  if (examplesInSystemPrompt) {
4827
4887
  const combinedItems = [
4828
- { type: "text", text: systemContent + "\n\n" },
4888
+ { type: "text", text: systemContent },
4829
4889
  ...renderedExamples,
4830
4890
  ...renderedDemos
4831
4891
  ];
@@ -5041,17 +5101,27 @@ ${text}`);
5041
5101
  }
5042
5102
  return [{ type: "text", text: text.join("") }];
5043
5103
  };
5044
- renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
5045
- renderFields = (fields) => {
5046
- const rows = fields.map((field) => {
5047
- const name = field.title;
5048
- const type = field.type?.name ? toFieldType(field.type) : "string";
5049
- const required = field.isOptional ? "optional" : "required";
5050
- const description = field.description ? `: ${capitalizeFirstLetter(field.description)}` : "";
5051
- return `- \`${name}:\` (${type}, ${required}) ${description}.`.trim();
5052
- });
5053
- return rows.join("\n");
5054
- };
5104
+ };
5105
+ var renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
5106
+ var renderInputFields = (fields) => {
5107
+ const rows = fields.map((field) => {
5108
+ const name = field.title;
5109
+ const type = field.type?.name ? toFieldType(field.type) : "string";
5110
+ const requiredMsg = field.isOptional ? `This optional ${type} field may be omitted` : `A ${type} field`;
5111
+ const description = field.description ? ` ${formatDescription(field.description)}` : "";
5112
+ return `${name}: (${requiredMsg})${description}`.trim();
5113
+ });
5114
+ return rows.join("\n");
5115
+ };
5116
+ var renderOutputFields = (fields) => {
5117
+ const rows = fields.map((field) => {
5118
+ const name = field.title;
5119
+ const type = field.type?.name ? toFieldType(field.type) : "string";
5120
+ const requiredMsg = field.isOptional ? `Only include this ${type} field is it's value is available` : `This ${type} field must be included`;
5121
+ const description = field.description ? ` ${formatDescription(field.description)}` : "";
5122
+ return `${name}: (${requiredMsg})${description}`.trim();
5123
+ });
5124
+ return rows.join("\n");
5055
5125
  };
5056
5126
  var processValue = (field, value) => {
5057
5127
  if (field.type?.name === "date" && value instanceof Date) {
@@ -5092,6 +5162,8 @@ var toFieldType = (type) => {
5092
5162
  return "JSON object";
5093
5163
  case "class":
5094
5164
  return `classification class (allowed classes: ${type.classes?.join(", ")})`;
5165
+ case "code":
5166
+ return "code";
5095
5167
  default:
5096
5168
  return "string";
5097
5169
  }
@@ -5125,11 +5197,9 @@ var isEmptyValue = (field, value) => {
5125
5197
  }
5126
5198
  return false;
5127
5199
  };
5128
- function capitalizeFirstLetter(str) {
5129
- if (str.length === 0) {
5130
- return "";
5131
- }
5132
- return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
5200
+ function formatDescription(str) {
5201
+ const value = str.trim();
5202
+ return value.length > 0 ? `${value.charAt(0).toUpperCase()}${value.slice(1)}${value.endsWith(".") ? "" : "."}` : "";
5133
5203
  }
5134
5204
 
5135
5205
  // dsp/validate.ts
@@ -5264,7 +5334,7 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5264
5334
  let e = matchesContent(content, prefix, xstate.s + 1);
5265
5335
  switch (e) {
5266
5336
  case -1:
5267
- if (streamingValidation && xstate.s == -1 && !field.isOptional) {
5337
+ if (streamingValidation && values.length == 0 && !field.isOptional) {
5268
5338
  throw new ValidationError({
5269
5339
  message: "Required field not found",
5270
5340
  fields: [field]
@@ -5277,6 +5347,10 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5277
5347
  // Partial match at end, skip and gather more content
5278
5348
  case -3:
5279
5349
  return true;
5350
+ // String is only whitespace, skip and gather more content
5351
+ case -4:
5352
+ xstate.inBlock = true;
5353
+ return true;
5280
5354
  }
5281
5355
  let prefixLen = prefix.length;
5282
5356
  if (xstate.currField) {
@@ -5285,6 +5359,7 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5285
5359
  if (parsedValue !== void 0) {
5286
5360
  values[xstate.currField.name] = parsedValue;
5287
5361
  }
5362
+ xstate.lastDelta = val;
5288
5363
  }
5289
5364
  checkMissingRequiredFields(xstate, values, index);
5290
5365
  xstate.s = e + prefixLen;
@@ -5297,7 +5372,7 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5297
5372
  };
5298
5373
  var streamingExtractFinalValue = (sig, values, xstate, content) => {
5299
5374
  if (xstate.currField) {
5300
- const val = content.substring(xstate.s).trim();
5375
+ let val = content.substring(xstate.s).trim();
5301
5376
  const parsedValue = validateAndParseFieldValue(xstate.currField, val);
5302
5377
  if (parsedValue !== void 0) {
5303
5378
  values[xstate.currField.name] = parsedValue;
@@ -5308,6 +5383,8 @@ var streamingExtractFinalValue = (sig, values, xstate, content) => {
5308
5383
  };
5309
5384
  var convertValueToType = (field, val) => {
5310
5385
  switch (field.type?.name) {
5386
+ case "code":
5387
+ return extractBlock(val);
5311
5388
  case "string":
5312
5389
  return val;
5313
5390
  case "number": {
@@ -5346,47 +5423,74 @@ var convertValueToType = (field, val) => {
5346
5423
  return val;
5347
5424
  }
5348
5425
  };
5349
- function* streamValues(sig, values, xstate, content, final = false) {
5426
+ function processStreamingDelta(content, xstate) {
5350
5427
  if (!xstate.currField) {
5351
- return;
5428
+ return null;
5352
5429
  }
5353
- const fieldName = xstate.currField.name;
5430
+ const { name: fieldName, type: fieldType } = xstate.currField ?? {};
5431
+ const { isArray: fieldIsArray, name: fieldTypeName } = fieldType ?? {};
5354
5432
  if (!xstate.streamedIndex) {
5355
5433
  xstate.streamedIndex = { [fieldName]: 0 };
5356
5434
  }
5357
- if (!final) {
5358
- if (!xstate.currField.type || !xstate.currField.type.isArray && xstate.currField.type.name === "string") {
5359
- const pos = xstate.streamedIndex[fieldName] ?? 0;
5360
- const s = xstate.s + pos;
5361
- const v = content.substring(s);
5362
- const v1 = v.replace(/[\s\n\t]+$/, "");
5363
- const v2 = pos === 0 ? v1.trimStart() : v1;
5364
- if (v2.length > 0) {
5365
- yield { [fieldName]: v2 };
5366
- xstate.streamedIndex[fieldName] = pos + v1.length;
5367
- }
5368
- return;
5369
- }
5435
+ if (fieldIsArray) {
5436
+ return null;
5437
+ }
5438
+ if (fieldTypeName !== "string" && fieldTypeName !== "code") {
5439
+ return null;
5440
+ }
5441
+ const pos = xstate.streamedIndex[fieldName] ?? 0;
5442
+ const s = xstate.s + pos;
5443
+ const isFirstChunk = pos === 0;
5444
+ const d1 = content.substring(s);
5445
+ let d2 = d1.replace(/\s+$/, "");
5446
+ if (xstate.currField?.type?.name === "code") {
5447
+ d2 = d2.replace(/\s*```\s*$/, "");
5448
+ }
5449
+ let d3 = isFirstChunk ? d2.trimStart() : d2;
5450
+ if (xstate.currField?.type?.name === "code") {
5451
+ d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
5452
+ }
5453
+ if (d3.length > 0) {
5454
+ xstate.streamedIndex[fieldName] = pos + d2.length;
5455
+ }
5456
+ return d3;
5457
+ }
5458
+ function getStreamingDelta(content, xstate) {
5459
+ if (xstate.lastDelta) {
5460
+ processStreamingDelta(xstate.lastDelta, xstate);
5461
+ xstate.lastDelta = void 0;
5462
+ }
5463
+ return processStreamingDelta(content, xstate);
5464
+ }
5465
+ function* streamValues(sig, values, xstate, delta) {
5466
+ if (!xstate.currField) {
5467
+ return;
5468
+ }
5469
+ const fieldName = xstate.currField.name;
5470
+ if (delta && delta.length > 0) {
5471
+ yield { [fieldName]: delta };
5472
+ return;
5370
5473
  }
5371
5474
  for (const key of Object.keys(values)) {
5372
5475
  const value = values[key];
5373
5476
  if (Array.isArray(value)) {
5374
- const s = xstate.streamedIndex[key] ?? 0;
5477
+ const s = xstate.streamedIndex?.[key] ?? 0;
5375
5478
  const v = value.slice(s);
5376
5479
  if (v && v.length > 0) {
5377
5480
  yield { [key]: v };
5378
- xstate.streamedIndex[key] = s + 1;
5481
+ if (xstate.streamedIndex) {
5482
+ xstate.streamedIndex[key] = s + 1;
5483
+ } else {
5484
+ xstate.streamedIndex = { [key]: s + 1 };
5485
+ }
5379
5486
  }
5380
- continue;
5381
- }
5382
- if (!xstate.streamedIndex[key]) {
5487
+ } else {
5383
5488
  yield { [key]: value };
5384
- xstate.streamedIndex[key] = 1;
5385
5489
  }
5386
5490
  }
5387
5491
  }
5388
5492
  function validateAndParseFieldValue(field, fieldValue) {
5389
- if (!fieldValue || fieldValue === "" || fieldValue === "null" || fieldValue === "NULL" || fieldValue === "undefined") {
5493
+ if (!fieldValue || fieldValue === "" || /^(null|undefined)\s*$/i.test(fieldValue)) {
5390
5494
  if (field.isOptional) {
5391
5495
  return;
5392
5496
  }
@@ -5452,8 +5556,8 @@ function validateAndParseFieldValue(field, fieldValue) {
5452
5556
  return value;
5453
5557
  }
5454
5558
  var extractBlock = (input) => {
5455
- const jsonBlockPattern = /```([A-Za-z]+)?\s*([\s\S]*?)\s*```/g;
5456
- const match = jsonBlockPattern.exec(input);
5559
+ const markdownBlockPattern = /```([A-Za-z]*)\n([\s\S]*?)\n```/g;
5560
+ const match = markdownBlockPattern.exec(input);
5457
5561
  if (!match) {
5458
5562
  return input;
5459
5563
  }
@@ -5466,6 +5570,61 @@ var extractBlock = (input) => {
5466
5570
  return input;
5467
5571
  };
5468
5572
 
5573
+ // dsp/fieldProcessor.ts
5574
+ async function processFieldProcessors(fieldProcessors, values, mem, sessionId) {
5575
+ for (const processor of fieldProcessors) {
5576
+ if (values[processor.field.name] === void 0) {
5577
+ continue;
5578
+ }
5579
+ const result = await processor.process(values[processor.field.name], {
5580
+ sessionId,
5581
+ values,
5582
+ done: true
5583
+ });
5584
+ addToMemory(processor.field, mem, result, sessionId);
5585
+ }
5586
+ }
5587
+ async function processStreamingFieldProcessors(fieldProcessors, content, xstate, mem, values, sessionId, done = false) {
5588
+ for (const processor of fieldProcessors) {
5589
+ if (xstate.currField?.name !== processor.field.name) {
5590
+ continue;
5591
+ }
5592
+ let value = content.substring(xstate.s);
5593
+ if (xstate.currField?.type?.name === "code") {
5594
+ value = value.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
5595
+ value = value.replace(/\s*```\s*$/, "");
5596
+ }
5597
+ const result = await processor.process(value, {
5598
+ sessionId,
5599
+ values,
5600
+ done
5601
+ });
5602
+ addToMemory(xstate.currField, mem, result, sessionId);
5603
+ }
5604
+ }
5605
+ var addToMemory = (field, mem, result, sessionId) => {
5606
+ if (result === void 0 || typeof result === "string" && (result === "" || /^(null|undefined)\s*$/i.test(result))) {
5607
+ return;
5608
+ }
5609
+ let resultText = JSON.stringify(
5610
+ result,
5611
+ (key, value) => typeof value === "bigint" ? Number(value) : value,
5612
+ 2
5613
+ );
5614
+ const text = getFieldProcessingMessage(field, resultText);
5615
+ mem.add({ role: "user", content: [{ type: "text", text }] }, sessionId);
5616
+ mem.addTag(`processor`, sessionId);
5617
+ };
5618
+ function getFieldProcessingMessage(field, resultText) {
5619
+ const isCodeField = field.type?.name === "code";
5620
+ const fieldTitle = field.title;
5621
+ if (isCodeField) {
5622
+ return `Code in the field "${fieldTitle}" was executed. The code execution produced the following output: ${resultText}`;
5623
+ } else {
5624
+ return `The field "${fieldTitle}" was processed. The field contents were transformed into the following output: ${resultText}`;
5625
+ }
5626
+ }
5627
+
5469
5628
  // dsp/jsonschema.ts
5470
5629
  var validateJSONSchema = (schema) => {
5471
5630
  const errors = [];
@@ -5683,6 +5842,8 @@ var AxGen = class extends AxProgramWithSignature {
5683
5842
  options;
5684
5843
  functions;
5685
5844
  functionsExecuted = /* @__PURE__ */ new Set();
5845
+ fieldProcessors = [];
5846
+ streamingFieldProcessors = [];
5686
5847
  constructor(signature, options) {
5687
5848
  super(signature, { description: options?.description });
5688
5849
  this.options = options;
@@ -5703,6 +5864,24 @@ var AxGen = class extends AxProgramWithSignature {
5703
5864
  addStreamingAssert = (fieldName, fn, message) => {
5704
5865
  this.streamingAsserts.push({ fieldName, fn, message });
5705
5866
  };
5867
+ addFieldProcessor = (fieldName, fn, streaming = false) => {
5868
+ const field = this.signature.getOutputFields().find((f) => f.name === fieldName);
5869
+ if (!field) {
5870
+ throw new Error(`addFieldProcessor: field ${fieldName} not found`);
5871
+ }
5872
+ if (streaming) {
5873
+ const ft = field.type?.name;
5874
+ const isText = !ft || ft === "string" || ft === "code";
5875
+ if (!isText) {
5876
+ throw new Error(
5877
+ `addFieldProcessor: field ${fieldName} is must be a text field`
5878
+ );
5879
+ }
5880
+ this.streamingFieldProcessors.push({ field, process: fn });
5881
+ } else {
5882
+ this.fieldProcessors.push({ field, process: fn });
5883
+ }
5884
+ };
5706
5885
  async forwardSendRequest({
5707
5886
  ai,
5708
5887
  mem,
@@ -5735,7 +5914,8 @@ var AxGen = class extends AxProgramWithSignature {
5735
5914
  sessionId,
5736
5915
  traceId,
5737
5916
  rateLimiter,
5738
- stream
5917
+ stream,
5918
+ debug: false
5739
5919
  }
5740
5920
  );
5741
5921
  return res;
@@ -5745,7 +5925,8 @@ var AxGen = class extends AxProgramWithSignature {
5745
5925
  mem,
5746
5926
  options
5747
5927
  }) {
5748
- const { sessionId, traceId, model, functions, earlyFail } = options ?? {};
5928
+ const { sessionId, traceId, model, functions } = options ?? {};
5929
+ const fastFail = options?.fastFail ?? this.options?.fastFail;
5749
5930
  const usageInfo = {
5750
5931
  ai: ai.getName(),
5751
5932
  model: ai.getModelInfo().name
@@ -5765,7 +5946,7 @@ var AxGen = class extends AxProgramWithSignature {
5765
5946
  traceId,
5766
5947
  sessionId,
5767
5948
  functions,
5768
- earlyFail
5949
+ fastFail
5769
5950
  });
5770
5951
  } else {
5771
5952
  yield await this.processResponse({
@@ -5789,9 +5970,9 @@ var AxGen = class extends AxProgramWithSignature {
5789
5970
  sessionId,
5790
5971
  traceId,
5791
5972
  functions,
5792
- earlyFail
5973
+ fastFail
5793
5974
  }) {
5794
- const streamingValidation = earlyFail ?? ai.getFeatures().functionCot !== true;
5975
+ const streamingValidation = fastFail ?? ai.getFeatures().functionCot !== true;
5795
5976
  const functionCalls = [];
5796
5977
  const values = {};
5797
5978
  const xstate = {
@@ -5810,12 +5991,20 @@ var AxGen = class extends AxProgramWithSignature {
5810
5991
  if (result.functionCalls) {
5811
5992
  mergeFunctionCalls(functionCalls, result.functionCalls);
5812
5993
  mem.updateResult(
5813
- { name: result.name, content, functionCalls },
5994
+ {
5995
+ name: result.name,
5996
+ content,
5997
+ functionCalls,
5998
+ delta: result.functionCalls?.[0]?.function?.params
5999
+ },
5814
6000
  sessionId
5815
6001
  );
5816
6002
  } else if (result.content) {
5817
6003
  content += result.content;
5818
- mem.updateResult({ name: result.name, content }, sessionId);
6004
+ mem.updateResult(
6005
+ { name: result.name, content, delta: result.content },
6006
+ sessionId
6007
+ );
5819
6008
  const skip = streamingExtractValues(
5820
6009
  this.signature,
5821
6010
  values,
@@ -5826,15 +6015,20 @@ var AxGen = class extends AxProgramWithSignature {
5826
6015
  if (skip) {
5827
6016
  continue;
5828
6017
  }
5829
- assertStreamingAssertions(
5830
- this.streamingAsserts,
5831
- values,
5832
- xstate,
5833
- content,
5834
- false
5835
- );
6018
+ assertStreamingAssertions(this.streamingAsserts, xstate, content);
5836
6019
  assertAssertions(this.asserts, values);
5837
- yield* streamValues(this.signature, values, xstate, content);
6020
+ if (this.streamingFieldProcessors.length !== 0) {
6021
+ await processStreamingFieldProcessors(
6022
+ this.streamingFieldProcessors,
6023
+ content,
6024
+ xstate,
6025
+ mem,
6026
+ values,
6027
+ sessionId
6028
+ );
6029
+ }
6030
+ const delta = getStreamingDelta(content, xstate);
6031
+ yield* streamValues(this.signature, values, xstate, delta);
5838
6032
  }
5839
6033
  if (result.finishReason === "length") {
5840
6034
  throw new Error("Max tokens reached before completion");
@@ -5856,15 +6050,29 @@ var AxGen = class extends AxProgramWithSignature {
5856
6050
  this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
5857
6051
  } else {
5858
6052
  streamingExtractFinalValue(this.signature, values, xstate, content);
5859
- assertStreamingAssertions(
5860
- this.streamingAsserts,
5861
- values,
5862
- xstate,
5863
- content,
5864
- true
5865
- );
6053
+ assertStreamingAssertions(this.streamingAsserts, xstate, content, true);
5866
6054
  assertAssertions(this.asserts, values);
5867
- yield* streamValues(this.signature, values, xstate, content, true);
6055
+ if (this.fieldProcessors.length) {
6056
+ await processFieldProcessors(
6057
+ this.fieldProcessors,
6058
+ values,
6059
+ mem,
6060
+ sessionId
6061
+ );
6062
+ }
6063
+ if (this.streamingFieldProcessors.length !== 0) {
6064
+ await processStreamingFieldProcessors(
6065
+ this.streamingFieldProcessors,
6066
+ content,
6067
+ xstate,
6068
+ mem,
6069
+ values,
6070
+ sessionId,
6071
+ true
6072
+ );
6073
+ }
6074
+ const delta = getStreamingDelta(content, xstate);
6075
+ yield* streamValues(this.signature, values, xstate, delta);
5868
6076
  }
5869
6077
  }
5870
6078
  async processResponse({
@@ -5905,6 +6113,14 @@ var AxGen = class extends AxProgramWithSignature {
5905
6113
  } else if (result.content) {
5906
6114
  extractValues(this.signature, values, result.content);
5907
6115
  assertAssertions(this.asserts, values);
6116
+ if (this.fieldProcessors.length) {
6117
+ await processFieldProcessors(
6118
+ this.fieldProcessors,
6119
+ values,
6120
+ mem,
6121
+ sessionId
6122
+ );
6123
+ }
5908
6124
  }
5909
6125
  if (result.finishReason === "length") {
5910
6126
  throw new Error("Max tokens reached before completion");
@@ -5916,7 +6132,8 @@ var AxGen = class extends AxProgramWithSignature {
5916
6132
  const stopFunction = (options?.stopFunction ?? this.options?.stopFunction)?.toLowerCase();
5917
6133
  const maxRetries = options.maxRetries ?? this.options?.maxRetries ?? 10;
5918
6134
  const maxSteps = options.maxSteps ?? this.options?.maxSteps ?? 10;
5919
- const mem = options.mem ?? this.options?.mem ?? new AxMemory();
6135
+ const debug = options.debug ?? ai.getOptions().debug;
6136
+ const mem = options.mem ?? this.options?.mem ?? new AxMemory(1e4, debug);
5920
6137
  let err;
5921
6138
  if (options?.functions && options.functions.length > 0) {
5922
6139
  const promptTemplate = this.options?.promptTemplate ?? AxPromptTemplate;
@@ -5947,6 +6164,9 @@ var AxGen = class extends AxProgramWithSignature {
5947
6164
  if (shouldContinue) {
5948
6165
  continue multiStepLoop;
5949
6166
  }
6167
+ if (debug) {
6168
+ process.stdout.write("\n");
6169
+ }
5950
6170
  return;
5951
6171
  } catch (e) {
5952
6172
  let errorFields;
@@ -5979,10 +6199,12 @@ var AxGen = class extends AxProgramWithSignature {
5979
6199
  }
5980
6200
  shouldContinueSteps(lastMemItem, stopFunction) {
5981
6201
  const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
5982
- if (lastMemItem?.role === "function" && stopFunction && stopFunctionExecuted) {
6202
+ const isFunction = lastMemItem?.chat?.role === "function";
6203
+ const isProcessor = lastMemItem?.tags ? lastMemItem.tags.some((tag) => tag === "processor") : false;
6204
+ if (isFunction && stopFunction && stopFunctionExecuted) {
5983
6205
  return false;
5984
6206
  }
5985
- if (lastMemItem?.role === "function") {
6207
+ if (isFunction || isProcessor) {
5986
6208
  return true;
5987
6209
  }
5988
6210
  return false;
@@ -6062,17 +6284,18 @@ function processChildAgentFunction(childFunction, parentValues, parentInputKeys,
6062
6284
  injectionKeys
6063
6285
  );
6064
6286
  const originalFunc = processedFunction.func;
6065
- processedFunction.func = (childArgs, funcOptions) => {
6287
+ processedFunction.func = async (childArgs, funcOptions) => {
6066
6288
  const updatedChildArgs = {
6067
6289
  ...childArgs,
6068
6290
  ...pick(parentValues, injectionKeys)
6069
6291
  };
6070
6292
  if (options.debug && injectionKeys.length > 0) {
6071
6293
  process.stdout.write(
6072
- `Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`
6294
+ `
6295
+ Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`
6073
6296
  );
6074
6297
  }
6075
- return originalFunc(updatedChildArgs, funcOptions);
6298
+ return await originalFunc(updatedChildArgs, funcOptions);
6076
6299
  };
6077
6300
  }
6078
6301
  return processedFunction;
@@ -6098,6 +6321,7 @@ var AxAgent = class {
6098
6321
  agents;
6099
6322
  disableSmartModelRouting;
6100
6323
  excludeFieldsFromPassthrough;
6324
+ debug;
6101
6325
  name;
6102
6326
  // private subAgentList?: string
6103
6327
  func;
@@ -6110,12 +6334,13 @@ var AxAgent = class {
6110
6334
  agents,
6111
6335
  functions
6112
6336
  }, options) {
6113
- const { disableSmartModelRouting, excludeFieldsFromPassthrough } = options ?? {};
6337
+ const { disableSmartModelRouting, excludeFieldsFromPassthrough, debug } = options ?? {};
6114
6338
  this.ai = ai;
6115
6339
  this.agents = agents;
6116
6340
  this.functions = functions;
6117
6341
  this.disableSmartModelRouting = disableSmartModelRouting;
6118
6342
  this.excludeFieldsFromPassthrough = excludeFieldsFromPassthrough ?? [];
6343
+ this.debug = debug;
6119
6344
  if (!name || name.length < 5) {
6120
6345
  throw new Error(
6121
6346
  `Agent name must be at least 10 characters (more descriptive)`
@@ -6175,10 +6400,21 @@ var AxAgent = class {
6175
6400
  if (!ai) {
6176
6401
  throw new Error("AI service is required to run the agent");
6177
6402
  }
6403
+ const debug = this.getDebug(ai, options);
6404
+ if (debug) {
6405
+ process.stdout.write(`
6406
+ --- Agent Engaged: ${this.name} ---
6407
+ `);
6408
+ }
6178
6409
  const ret = await boundFunc(ai, values, {
6179
6410
  ...options,
6180
6411
  model
6181
6412
  });
6413
+ if (debug) {
6414
+ process.stdout.write(`
6415
+ --- Agent Done: ${this.name} ---
6416
+ `);
6417
+ }
6182
6418
  const sig = this.program.getSignature();
6183
6419
  const outFields = sig.getOutputFields();
6184
6420
  const result = Object.keys(ret).map((k) => {
@@ -6209,10 +6445,11 @@ var AxAgent = class {
6209
6445
  const mm = ai?.getModelList();
6210
6446
  const parentSchema = this.program.getSignature().getInputFields();
6211
6447
  const parentKeys = parentSchema.map((p) => p.name);
6448
+ const debug = this.getDebug(ai, options);
6212
6449
  const agentFuncs = this.agents?.map((agent) => {
6213
6450
  const f = agent.getFeatures();
6214
6451
  const processOptions = {
6215
- debug: ai?.getOptions()?.debug ?? false,
6452
+ debug,
6216
6453
  disableSmartModelRouting: !!this.disableSmartModelRouting,
6217
6454
  excludeFieldsFromPassthrough: f.excludeFieldsFromPassthrough,
6218
6455
  canConfigureSmartModelRouting: f.canConfigureSmartModelRouting
@@ -6229,16 +6466,21 @@ var AxAgent = class {
6229
6466
  ...options?.functions ?? this.functions ?? [],
6230
6467
  ...agentFuncs ?? []
6231
6468
  ];
6232
- return { ai, functions };
6469
+ return { ai, functions, debug };
6233
6470
  }
6234
6471
  async forward(parentAi, values, options) {
6235
- const { ai, functions } = this.init(parentAi, values, options);
6236
- return await this.program.forward(ai, values, { ...options, functions });
6472
+ const { ai, functions, debug } = this.init(parentAi, values, options);
6473
+ return await this.program.forward(ai, values, {
6474
+ ...options,
6475
+ debug,
6476
+ functions
6477
+ });
6237
6478
  }
6238
6479
  async *streamingForward(parentAi, values, options) {
6239
- const { ai, functions } = this.init(parentAi, values, options);
6480
+ const { ai, functions, debug } = this.init(parentAi, values, options);
6240
6481
  return yield* this.program.streamingForward(ai, values, {
6241
6482
  ...options,
6483
+ debug,
6242
6484
  functions
6243
6485
  });
6244
6486
  }
@@ -6262,6 +6504,9 @@ var AxAgent = class {
6262
6504
  }
6263
6505
  this.program.getSignature().setDescription(definition);
6264
6506
  }
6507
+ getDebug(ai, options) {
6508
+ return options?.debug ?? this.debug ?? ai?.getOptions()?.debug ?? false;
6509
+ }
6265
6510
  };
6266
6511
  function toCamelCase(inputString) {
6267
6512
  const words = inputString.split(/[^a-zA-Z0-9]/);