@ai-sdk/workflow 1.0.0-beta.3 → 1.0.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // src/workflow-agent.ts
2
2
  import {
3
- Output
3
+ Output,
4
+ experimental_filterActiveTools as filterActiveTools2
4
5
  } from "ai";
5
6
  import {
6
7
  convertToLanguageModelPrompt,
@@ -9,11 +10,16 @@ import {
9
10
  standardizePrompt
10
11
  } from "ai/internal";
11
12
 
13
+ // src/stream-text-iterator.ts
14
+ import {
15
+ experimental_filterActiveTools as filterActiveTools
16
+ } from "ai";
17
+
12
18
  // src/do-stream-step.ts
13
19
  import {
14
- experimental_streamLanguageModelCall as streamModelCall
20
+ experimental_streamLanguageModelCall as streamModelCall,
21
+ gateway
15
22
  } from "ai";
16
- import { gateway } from "ai";
17
23
 
18
24
  // src/serializable-schema.ts
19
25
  import { asSchema, jsonSchema } from "@ai-sdk/provider-utils";
@@ -22,12 +28,14 @@ import Ajv from "ajv";
22
28
  function serializeToolSet(tools) {
23
29
  return Object.fromEntries(
24
30
  Object.entries(tools).map(([name, t]) => {
31
+ var _a;
25
32
  const def = {
26
33
  description: t.description,
27
34
  inputSchema: asSchema(t.inputSchema).jsonSchema
28
35
  };
29
36
  if (t.type === "provider") {
30
37
  def.type = "provider";
38
+ def.isProviderExecuted = (_a = t.isProviderExecuted) != null ? _a : false;
31
39
  def.id = t.id;
32
40
  def.args = t.args;
33
41
  }
@@ -39,7 +47,7 @@ function resolveSerializableTools(tools) {
39
47
  const ajv = new Ajv();
40
48
  return Object.fromEntries(
41
49
  Object.entries(tools).map(([name, t]) => {
42
- var _a;
50
+ var _a, _b;
43
51
  if (t.type === "provider") {
44
52
  return [
45
53
  name,
@@ -47,6 +55,7 @@ function resolveSerializableTools(tools) {
47
55
  type: "provider",
48
56
  id: t.id,
49
57
  args: (_a = t.args) != null ? _a : {},
58
+ isProviderExecuted: (_b = t.isProviderExecuted) != null ? _b : false,
50
59
  inputSchema: jsonSchema(t.inputSchema)
51
60
  })
52
61
  ];
@@ -85,6 +94,7 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
85
94
  // pre-converted LanguageModelV4Prompt. standardizePrompt inside
86
95
  // streamModelCall handles both formats.
87
96
  messages: conversationPrompt,
97
+ allowSystemInMessages: true,
88
98
  tools,
89
99
  toolChoice: options == null ? void 0 : options.toolChoice,
90
100
  includeRawChunks: options == null ? void 0 : options.includeRawChunks,
@@ -187,7 +197,8 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
187
197
  },
188
198
  functionId: void 0,
189
199
  metadata: void 0,
190
- context: void 0,
200
+ runtimeContext: void 0,
201
+ toolsContext: {},
191
202
  content: [
192
203
  ...text ? [{ type: "text", text }] : [],
193
204
  ...toolCalls.filter((tc) => !tc.invalid).map((tc) => ({
@@ -265,7 +276,6 @@ async function* streamTextIterator({
265
276
  writable,
266
277
  model,
267
278
  stopConditions,
268
- maxSteps,
269
279
  onStepFinish,
270
280
  onStepStart,
271
281
  onError,
@@ -273,12 +283,12 @@ async function* streamTextIterator({
273
283
  generationSettings,
274
284
  toolChoice,
275
285
  experimental_context,
276
- experimental_telemetry,
286
+ telemetry,
277
287
  includeRawChunks = false,
278
288
  repairToolCall,
279
289
  responseFormat
280
290
  }) {
281
- var _a;
291
+ var _a, _b;
282
292
  let conversationPrompt = [...prompt];
283
293
  let currentModel = model;
284
294
  let currentGenerationSettings = generationSettings != null ? generationSettings : {};
@@ -291,11 +301,7 @@ async function* streamTextIterator({
291
301
  let stepNumber = 0;
292
302
  let lastStep;
293
303
  let lastStepWasToolCalls = false;
294
- const effectiveMaxSteps = maxSteps != null ? maxSteps : Infinity;
295
304
  while (!done) {
296
- if (stepNumber >= effectiveMaxSteps) {
297
- break;
298
- }
299
305
  if ((_a = currentGenerationSettings.abortSignal) == null ? void 0 : _a.aborted) {
300
306
  break;
301
307
  }
@@ -406,11 +412,15 @@ async function* streamTextIterator({
406
412
  await onStepStart({
407
413
  stepNumber,
408
414
  model: currentModel,
409
- messages: conversationPrompt
415
+ messages: conversationPrompt,
416
+ steps: [...steps]
410
417
  });
411
418
  }
412
419
  try {
413
- const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? filterToolSet(tools, currentActiveTools) : tools;
420
+ const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? (_b = filterActiveTools({
421
+ tools,
422
+ activeTools: currentActiveTools
423
+ })) != null ? _b : tools : tools;
414
424
  const serializedTools = serializeToolSet(effectiveTools);
415
425
  const { toolCalls, finish, step, providerExecutedToolResults } = await doStreamStep(
416
426
  conversationPrompt,
@@ -421,7 +431,7 @@ async function* streamTextIterator({
421
431
  ...currentGenerationSettings,
422
432
  toolChoice: currentToolChoice,
423
433
  includeRawChunks,
424
- experimental_telemetry,
434
+ telemetry,
425
435
  repairToolCall,
426
436
  responseFormat
427
437
  }
@@ -514,15 +524,6 @@ async function* streamTextIterator({
514
524
  }
515
525
  return conversationPrompt;
516
526
  }
517
- function filterToolSet(tools, activeTools) {
518
- const filtered = {};
519
- for (const toolName of activeTools) {
520
- if (toolName in tools) {
521
- filtered[toolName] = tools[toolName];
522
- }
523
- }
524
- return filtered;
525
- }
526
527
  function sanitizeProviderMetadataForToolCall(metadata) {
527
528
  if (metadata == null) return void 0;
528
529
  const meta = metadata;
@@ -547,20 +548,26 @@ function sanitizeProviderMetadataForToolCall(metadata) {
547
548
  // src/workflow-agent.ts
548
549
  var WorkflowAgent = class {
549
550
  constructor(options) {
550
- var _a, _b;
551
+ var _a, _b, _c;
552
+ this.id = options.id;
551
553
  this.model = options.model;
552
554
  this.tools = (_a = options.tools) != null ? _a : {};
553
555
  this.instructions = (_b = options.instructions) != null ? _b : options.system;
554
556
  this.toolChoice = options.toolChoice;
555
- this.telemetry = options.experimental_telemetry;
557
+ this.telemetry = (_c = options.telemetry) != null ? _c : options.experimental_telemetry;
556
558
  this.experimentalContext = options.experimental_context;
559
+ this.stopWhen = options.stopWhen;
560
+ this.activeTools = options.activeTools;
561
+ this.output = options.output;
562
+ this.experimentalRepairToolCall = options.experimental_repairToolCall;
563
+ this.experimentalDownload = options.experimental_download;
557
564
  this.prepareStep = options.prepareStep;
558
565
  this.constructorOnStepFinish = options.onStepFinish;
559
566
  this.constructorOnFinish = options.onFinish;
560
567
  this.constructorOnStart = options.experimental_onStart;
561
568
  this.constructorOnStepStart = options.experimental_onStepStart;
562
- this.constructorOnToolCallStart = options.experimental_onToolCallStart;
563
- this.constructorOnToolCallFinish = options.experimental_onToolCallFinish;
569
+ this.constructorOnToolExecutionStart = options.experimental_onToolExecutionStart;
570
+ this.constructorOnToolExecutionEnd = options.experimental_onToolExecutionEnd;
564
571
  this.prepareCall = options.prepareCall;
565
572
  this.generationSettings = {
566
573
  maxOutputTokens: options.maxOutputTokens,
@@ -581,35 +588,42 @@ var WorkflowAgent = class {
581
588
  throw new Error("Not implemented");
582
589
  }
583
590
  async stream(options) {
584
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
591
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C;
585
592
  let effectiveModel = this.model;
586
593
  let effectiveInstructions = (_a = options.system) != null ? _a : this.instructions;
594
+ let effectivePrompt = options.prompt;
587
595
  let effectiveMessages = options.messages;
588
596
  let effectiveGenerationSettings = { ...this.generationSettings };
589
597
  let effectiveExperimentalContext = (_b = options.experimental_context) != null ? _b : this.experimentalContext;
590
598
  let effectiveToolChoiceFromPrepare = (_c = options.toolChoice) != null ? _c : this.toolChoice;
591
- let effectiveTelemetryFromPrepare = (_d = options.experimental_telemetry) != null ? _d : this.telemetry;
599
+ let effectiveTelemetryFromPrepare = (_e = (_d = options.telemetry) != null ? _d : options.experimental_telemetry) != null ? _e : this.telemetry;
600
+ const resolvedMessagesForPrepareCall = (_f = effectiveMessages != null ? effectiveMessages : typeof effectivePrompt === "string" ? [{ role: "user", content: effectivePrompt }] : effectivePrompt) != null ? _f : [];
592
601
  if (this.prepareCall) {
593
602
  const prepared = await this.prepareCall({
594
603
  model: effectiveModel,
595
604
  tools: this.tools,
596
605
  instructions: effectiveInstructions,
597
606
  toolChoice: effectiveToolChoiceFromPrepare,
607
+ telemetry: effectiveTelemetryFromPrepare,
598
608
  experimental_telemetry: effectiveTelemetryFromPrepare,
599
609
  experimental_context: effectiveExperimentalContext,
600
- messages: effectiveMessages,
610
+ messages: resolvedMessagesForPrepareCall,
601
611
  ...effectiveGenerationSettings
602
612
  });
603
613
  if (prepared.model !== void 0) effectiveModel = prepared.model;
604
614
  if (prepared.instructions !== void 0)
605
615
  effectiveInstructions = prepared.instructions;
606
- if (prepared.messages !== void 0)
616
+ if (prepared.messages !== void 0) {
607
617
  effectiveMessages = prepared.messages;
618
+ effectivePrompt = void 0;
619
+ }
608
620
  if (prepared.experimental_context !== void 0)
609
621
  effectiveExperimentalContext = prepared.experimental_context;
610
622
  if (prepared.toolChoice !== void 0)
611
623
  effectiveToolChoiceFromPrepare = prepared.toolChoice;
612
- if (prepared.experimental_telemetry !== void 0)
624
+ if (prepared.telemetry !== void 0)
625
+ effectiveTelemetryFromPrepare = prepared.telemetry;
626
+ else if (prepared.experimental_telemetry !== void 0)
613
627
  effectiveTelemetryFromPrepare = prepared.experimental_telemetry;
614
628
  if (prepared.maxOutputTokens !== void 0)
615
629
  effectiveGenerationSettings.maxOutputTokens = prepared.maxOutputTokens;
@@ -634,7 +648,9 @@ var WorkflowAgent = class {
634
648
  }
635
649
  const prompt = await standardizePrompt({
636
650
  system: effectiveInstructions,
637
- messages: effectiveMessages
651
+ allowSystemInMessages: true,
652
+ // TODO: consider exposing this as a parameter
653
+ ...effectivePrompt != null ? { prompt: effectivePrompt } : { messages: effectiveMessages }
638
654
  });
639
655
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovalsFromMessages(prompt.messages);
640
656
  if (approvedToolApprovals.length > 0 || deniedToolApprovals.length > 0) {
@@ -730,11 +746,11 @@ var WorkflowAgent = class {
730
746
  const modelPrompt = await convertToLanguageModelPrompt({
731
747
  prompt,
732
748
  supportedUrls: {},
733
- download: options.experimental_download
749
+ download: (_g = options.experimental_download) != null ? _g : this.experimentalDownload
734
750
  });
735
751
  const effectiveAbortSignal = mergeAbortSignals(
736
- (_e = options.abortSignal) != null ? _e : effectiveGenerationSettings.abortSignal,
737
- options.timeout != null ? AbortSignal.timeout(options.timeout) : void 0
752
+ (_h = options.abortSignal) != null ? _h : effectiveGenerationSettings.abortSignal,
753
+ options.timeout
738
754
  );
739
755
  const mergedGenerationSettings = {
740
756
  ...effectiveGenerationSettings,
@@ -783,17 +799,21 @@ var WorkflowAgent = class {
783
799
  this.constructorOnStepStart,
784
800
  options.experimental_onStepStart
785
801
  );
786
- const mergedOnToolCallStart = mergeCallbacks(
787
- this.constructorOnToolCallStart,
788
- options.experimental_onToolCallStart
802
+ const mergedOnToolExecutionStart = mergeCallbacks(
803
+ this.constructorOnToolExecutionStart,
804
+ options.experimental_onToolExecutionStart
789
805
  );
790
- const mergedOnToolCallFinish = mergeCallbacks(
791
- this.constructorOnToolCallFinish,
792
- options.experimental_onToolCallFinish
806
+ const mergedOnToolExecutionEnd = mergeCallbacks(
807
+ this.constructorOnToolExecutionEnd,
808
+ options.experimental_onToolExecutionEnd
793
809
  );
794
810
  const effectiveToolChoice = effectiveToolChoiceFromPrepare;
795
811
  const effectiveTelemetry = effectiveTelemetryFromPrepare;
796
- const effectiveTools = options.activeTools && options.activeTools.length > 0 ? filterTools(this.tools, options.activeTools) : this.tools;
812
+ const effectiveActiveTools = (_i = options.activeTools) != null ? _i : this.activeTools;
813
+ const effectiveTools = effectiveActiveTools && effectiveActiveTools.length > 0 ? (_j = filterActiveTools2({
814
+ tools: this.tools,
815
+ activeTools: effectiveActiveTools
816
+ })) != null ? _j : this.tools : this.tools;
797
817
  let experimentalContext = effectiveExperimentalContext;
798
818
  const steps = [];
799
819
  let lastStepToolCalls = [];
@@ -801,61 +821,68 @@ var WorkflowAgent = class {
801
821
  if (mergedOnStart) {
802
822
  await mergedOnStart({
803
823
  model: effectiveModel,
804
- messages: effectiveMessages
824
+ messages: prompt.messages
805
825
  });
806
826
  }
807
- const executeToolWithCallbacks = async (toolCall, tools, messages2, context) => {
808
- if (mergedOnToolCallStart) {
809
- await mergedOnToolCallStart({
810
- toolCall: {
811
- type: "tool-call",
812
- toolCallId: toolCall.toolCallId,
813
- toolName: toolCall.toolName,
814
- input: toolCall.input
815
- }
827
+ const executeToolWithCallbacks = async (toolCall, tools, messages2, context, currentStepNumber = 0) => {
828
+ const toolCallEvent = {
829
+ type: "tool-call",
830
+ toolCallId: toolCall.toolCallId,
831
+ toolName: toolCall.toolName,
832
+ input: toolCall.input
833
+ };
834
+ if (mergedOnToolExecutionStart) {
835
+ await mergedOnToolExecutionStart({
836
+ toolCall: toolCallEvent,
837
+ stepNumber: currentStepNumber
816
838
  });
817
839
  }
840
+ const startTime = Date.now();
818
841
  let result;
819
842
  try {
820
843
  result = await executeTool(toolCall, tools, messages2, context);
821
844
  } catch (err) {
822
- if (mergedOnToolCallFinish) {
823
- await mergedOnToolCallFinish({
824
- toolCall: {
825
- type: "tool-call",
826
- toolCallId: toolCall.toolCallId,
827
- toolName: toolCall.toolName,
828
- input: toolCall.input
829
- },
845
+ const durationMs2 = Date.now() - startTime;
846
+ if (mergedOnToolExecutionEnd) {
847
+ await mergedOnToolExecutionEnd({
848
+ toolCall: toolCallEvent,
849
+ stepNumber: currentStepNumber,
850
+ durationMs: durationMs2,
851
+ success: false,
830
852
  error: err
831
853
  });
832
854
  }
833
855
  throw err;
834
856
  }
835
- if (mergedOnToolCallFinish) {
857
+ const durationMs = Date.now() - startTime;
858
+ if (mergedOnToolExecutionEnd) {
836
859
  const isError = result.output && "type" in result.output && (result.output.type === "error-text" || result.output.type === "error-json");
837
- await mergedOnToolCallFinish({
838
- toolCall: {
839
- type: "tool-call",
840
- toolCallId: toolCall.toolCallId,
841
- toolName: toolCall.toolName,
842
- input: toolCall.input
843
- },
844
- ...isError ? {
860
+ if (isError) {
861
+ await mergedOnToolExecutionEnd({
862
+ toolCall: toolCallEvent,
863
+ stepNumber: currentStepNumber,
864
+ durationMs,
865
+ success: false,
845
866
  error: "value" in result.output ? result.output.value : void 0
846
- } : {
847
- result: result.output && "value" in result.output ? result.output.value : void 0
848
- }
849
- });
867
+ });
868
+ } else {
869
+ await mergedOnToolExecutionEnd({
870
+ toolCall: toolCallEvent,
871
+ stepNumber: currentStepNumber,
872
+ durationMs,
873
+ success: true,
874
+ output: result.output && "value" in result.output ? result.output.value : void 0
875
+ });
876
+ }
850
877
  }
851
878
  return result;
852
879
  };
853
- if ((_f = mergedGenerationSettings.abortSignal) == null ? void 0 : _f.aborted) {
880
+ if ((_k = mergedGenerationSettings.abortSignal) == null ? void 0 : _k.aborted) {
854
881
  if (options.onAbort) {
855
882
  await options.onAbort({ steps });
856
883
  }
857
884
  return {
858
- messages: options.messages,
885
+ messages: prompt.messages,
859
886
  steps,
860
887
  toolCalls: [],
861
888
  toolResults: [],
@@ -867,19 +894,18 @@ var WorkflowAgent = class {
867
894
  tools: effectiveTools,
868
895
  writable: options.writable,
869
896
  prompt: modelPrompt,
870
- stopConditions: options.stopWhen,
871
- maxSteps: options.maxSteps,
897
+ stopConditions: (_l = options.stopWhen) != null ? _l : this.stopWhen,
872
898
  onStepFinish: mergedOnStepFinish,
873
899
  onStepStart: mergedOnStepStart,
874
900
  onError: options.onError,
875
- prepareStep: (_g = options.prepareStep) != null ? _g : this.prepareStep,
901
+ prepareStep: (_m = options.prepareStep) != null ? _m : this.prepareStep,
876
902
  generationSettings: mergedGenerationSettings,
877
903
  toolChoice: effectiveToolChoice,
878
904
  experimental_context: experimentalContext,
879
- experimental_telemetry: effectiveTelemetry,
880
- includeRawChunks: (_h = options.includeRawChunks) != null ? _h : false,
881
- repairToolCall: options.experimental_repairToolCall,
882
- responseFormat: await ((_i = options.output) == null ? void 0 : _i.responseFormat)
905
+ telemetry: effectiveTelemetry,
906
+ includeRawChunks: (_n = options.includeRawChunks) != null ? _n : false,
907
+ repairToolCall: (_o = options.experimental_repairToolCall) != null ? _o : this.experimentalRepairToolCall,
908
+ responseFormat: await ((_q = (_p = options.output) != null ? _p : this.output) == null ? void 0 : _q.responseFormat)
883
909
  });
884
910
  let finalMessages;
885
911
  let encounteredError;
@@ -887,7 +913,7 @@ var WorkflowAgent = class {
887
913
  try {
888
914
  let result = await iterator.next();
889
915
  while (!result.done) {
890
- if ((_j = mergedGenerationSettings.abortSignal) == null ? void 0 : _j.aborted) {
916
+ if ((_r = mergedGenerationSettings.abortSignal) == null ? void 0 : _r.aborted) {
891
917
  wasAborted = true;
892
918
  if (options.onAbort) {
893
919
  await options.onAbort({ steps });
@@ -901,6 +927,7 @@ var WorkflowAgent = class {
901
927
  context,
902
928
  providerExecutedToolResults
903
929
  } = result.value;
930
+ const currentStepNumber = steps.length;
904
931
  if (step) {
905
932
  steps.push(step);
906
933
  }
@@ -908,10 +935,14 @@ var WorkflowAgent = class {
908
935
  experimentalContext = context;
909
936
  }
910
937
  if (toolCalls.length > 0) {
911
- const nonProviderToolCalls = toolCalls.filter(
938
+ const invalidToolCalls = toolCalls.filter((tc) => tc.invalid === true);
939
+ const validToolCalls = toolCalls.filter((tc) => tc.invalid !== true);
940
+ const nonProviderToolCalls = validToolCalls.filter(
912
941
  (tc) => !tc.providerExecuted
913
942
  );
914
- const providerToolCalls = toolCalls.filter((tc) => tc.providerExecuted);
943
+ const providerToolCalls = validToolCalls.filter(
944
+ (tc) => tc.providerExecuted
945
+ );
915
946
  const approvalNeeded = await Promise.all(
916
947
  nonProviderToolCalls.map(async (tc) => {
917
948
  const tool2 = effectiveTools[tc.toolName];
@@ -941,7 +972,8 @@ var WorkflowAgent = class {
941
972
  toolCall,
942
973
  effectiveTools,
943
974
  iterMessages,
944
- experimentalContext
975
+ experimentalContext,
976
+ currentStepNumber
945
977
  )
946
978
  )
947
979
  );
@@ -951,14 +983,22 @@ var WorkflowAgent = class {
951
983
  providerExecutedToolResults
952
984
  )
953
985
  );
954
- const resolvedResults = [...executableResults, ...providerResults];
986
+ const continuationInvalidResults = invalidToolCalls.map(
987
+ createInvalidToolResult
988
+ );
989
+ const resolvedResults = [
990
+ ...executableResults,
991
+ ...providerResults,
992
+ ...continuationInvalidResults
993
+ ];
994
+ const executedResults = [...executableResults, ...providerResults];
955
995
  const allToolCalls = toolCalls.map((tc) => ({
956
996
  type: "tool-call",
957
997
  toolCallId: tc.toolCallId,
958
998
  toolName: tc.toolName,
959
999
  input: tc.input
960
1000
  }));
961
- const allToolResults = resolvedResults.map((r) => {
1001
+ const allToolResults = executedResults.map((r) => {
962
1002
  var _a2;
963
1003
  return {
964
1004
  type: "tool-result",
@@ -980,8 +1020,8 @@ var WorkflowAgent = class {
980
1020
  await mergedOnFinish({
981
1021
  steps,
982
1022
  messages: messages2,
983
- text: (_k = lastStep == null ? void 0 : lastStep.text) != null ? _k : "",
984
- finishReason: (_l = lastStep == null ? void 0 : lastStep.finishReason) != null ? _l : "other",
1023
+ text: (_s = lastStep == null ? void 0 : lastStep.text) != null ? _s : "",
1024
+ finishReason: (_t = lastStep == null ? void 0 : lastStep.finishReason) != null ? _t : "other",
985
1025
  totalUsage: aggregateUsage(steps),
986
1026
  experimental_context: experimentalContext,
987
1027
  output: void 0
@@ -1005,8 +1045,8 @@ var WorkflowAgent = class {
1005
1045
  }
1006
1046
  }
1007
1047
  if (options.writable) {
1008
- const sendFinish = (_m = options.sendFinish) != null ? _m : true;
1009
- const preventClose = (_n = options.preventClose) != null ? _n : false;
1048
+ const sendFinish = (_u = options.sendFinish) != null ? _u : true;
1049
+ const preventClose = (_v = options.preventClose) != null ? _v : false;
1010
1050
  if (sendFinish || !preventClose) {
1011
1051
  await closeStream(options.writable, preventClose, sendFinish);
1012
1052
  }
@@ -1025,33 +1065,39 @@ var WorkflowAgent = class {
1025
1065
  toolCall,
1026
1066
  effectiveTools,
1027
1067
  iterMessages,
1028
- experimentalContext
1068
+ experimentalContext,
1069
+ currentStepNumber
1029
1070
  )
1030
1071
  )
1031
1072
  );
1032
1073
  const providerToolResults = providerToolCalls.map(
1033
1074
  (toolCall) => resolveProviderToolResult(toolCall, providerExecutedToolResults)
1034
1075
  );
1035
- const toolResults = toolCalls.map((tc) => {
1076
+ const continuationInvalidToolResults = invalidToolCalls.map(
1077
+ createInvalidToolResult
1078
+ );
1079
+ const continuationToolResults = toolCalls.flatMap((tc) => {
1080
+ const invalidResult = continuationInvalidToolResults.find(
1081
+ (r) => r.toolCallId === tc.toolCallId
1082
+ );
1083
+ if (invalidResult) return [invalidResult];
1036
1084
  const clientResult = clientToolResults.find(
1037
1085
  (r) => r.toolCallId === tc.toolCallId
1038
1086
  );
1039
- if (clientResult) return clientResult;
1087
+ if (clientResult) return [clientResult];
1040
1088
  const providerResult = providerToolResults.find(
1041
1089
  (r) => r.toolCallId === tc.toolCallId
1042
1090
  );
1043
- if (providerResult) return providerResult;
1044
- return {
1045
- type: "tool-result",
1046
- toolCallId: tc.toolCallId,
1047
- toolName: tc.toolName,
1048
- output: { type: "text", value: "" }
1049
- };
1091
+ if (providerResult) return [providerResult];
1092
+ return [];
1050
1093
  });
1094
+ const executedToolResults = continuationToolResults.filter(
1095
+ (result2) => !invalidToolCalls.some((tc) => tc.toolCallId === result2.toolCallId)
1096
+ );
1051
1097
  if (options.writable) {
1052
1098
  await writeToolResultsWithStepBoundary(
1053
1099
  options.writable,
1054
- toolResults.map((r) => {
1100
+ executedToolResults.map((r) => {
1055
1101
  var _a2;
1056
1102
  return {
1057
1103
  toolCallId: r.toolCallId,
@@ -1068,7 +1114,7 @@ var WorkflowAgent = class {
1068
1114
  toolName: tc.toolName,
1069
1115
  input: tc.input
1070
1116
  }));
1071
- lastStepToolResults = toolResults.map((r) => {
1117
+ lastStepToolResults = executedToolResults.map((r) => {
1072
1118
  var _a2;
1073
1119
  return {
1074
1120
  type: "tool-result",
@@ -1078,7 +1124,7 @@ var WorkflowAgent = class {
1078
1124
  output: "value" in r.output ? r.output.value : void 0
1079
1125
  };
1080
1126
  });
1081
- result = await iterator.next(toolResults);
1127
+ result = await iterator.next(continuationToolResults);
1082
1128
  } else {
1083
1129
  lastStepToolCalls = [];
1084
1130
  lastStepToolResults = [];
@@ -1099,14 +1145,15 @@ var WorkflowAgent = class {
1099
1145
  await options.onError({ error });
1100
1146
  }
1101
1147
  }
1102
- const messages = finalMessages != null ? finalMessages : options.messages;
1148
+ const messages = finalMessages != null ? finalMessages : prompt.messages;
1149
+ const effectiveOutput = (_w = options.output) != null ? _w : this.output;
1103
1150
  let experimentalOutput = void 0;
1104
- if (options.output && steps.length > 0) {
1151
+ if (effectiveOutput && steps.length > 0) {
1105
1152
  const lastStep = steps[steps.length - 1];
1106
1153
  const text = lastStep.text;
1107
1154
  if (text) {
1108
1155
  try {
1109
- experimentalOutput = await options.output.parseCompleteOutput(
1156
+ experimentalOutput = await effectiveOutput.parseCompleteOutput(
1110
1157
  { text },
1111
1158
  {
1112
1159
  response: lastStep.response,
@@ -1126,8 +1173,8 @@ var WorkflowAgent = class {
1126
1173
  await mergedOnFinish({
1127
1174
  steps,
1128
1175
  messages,
1129
- text: (_o = lastStep == null ? void 0 : lastStep.text) != null ? _o : "",
1130
- finishReason: (_p = lastStep == null ? void 0 : lastStep.finishReason) != null ? _p : "other",
1176
+ text: (_x = lastStep == null ? void 0 : lastStep.text) != null ? _x : "",
1177
+ finishReason: (_y = lastStep == null ? void 0 : lastStep.finishReason) != null ? _y : "other",
1131
1178
  totalUsage: aggregateUsage(steps),
1132
1179
  experimental_context: experimentalContext,
1133
1180
  output: experimentalOutput
@@ -1135,8 +1182,8 @@ var WorkflowAgent = class {
1135
1182
  }
1136
1183
  if (encounteredError) {
1137
1184
  if (options.writable) {
1138
- const sendFinish = (_q = options.sendFinish) != null ? _q : true;
1139
- const preventClose = (_r = options.preventClose) != null ? _r : false;
1185
+ const sendFinish = (_z = options.sendFinish) != null ? _z : true;
1186
+ const preventClose = (_A = options.preventClose) != null ? _A : false;
1140
1187
  if (sendFinish || !preventClose) {
1141
1188
  await closeStream(options.writable, preventClose, sendFinish);
1142
1189
  }
@@ -1144,8 +1191,8 @@ var WorkflowAgent = class {
1144
1191
  throw encounteredError;
1145
1192
  }
1146
1193
  if (options.writable) {
1147
- const sendFinish = (_s = options.sendFinish) != null ? _s : true;
1148
- const preventClose = (_t = options.preventClose) != null ? _t : false;
1194
+ const sendFinish = (_B = options.sendFinish) != null ? _B : true;
1195
+ const preventClose = (_C = options.preventClose) != null ? _C : false;
1149
1196
  if (sendFinish || !preventClose) {
1150
1197
  await closeStream(options.writable, preventClose, sendFinish);
1151
1198
  }
@@ -1246,15 +1293,6 @@ function aggregateUsage(steps) {
1246
1293
  totalTokens: inputTokens + outputTokens
1247
1294
  };
1248
1295
  }
1249
- function filterTools(tools, activeTools) {
1250
- const filtered = {};
1251
- for (const toolName of activeTools) {
1252
- if (toolName in tools) {
1253
- filtered[toolName] = tools[toolName];
1254
- }
1255
- }
1256
- return filtered;
1257
- }
1258
1296
  function getErrorMessage(error) {
1259
1297
  if (error == null) {
1260
1298
  return "unknown error";
@@ -1298,6 +1336,17 @@ function resolveProviderToolResult(toolCall, providerExecutedToolResults) {
1298
1336
  }
1299
1337
  };
1300
1338
  }
1339
+ function createInvalidToolResult(toolCall) {
1340
+ return {
1341
+ type: "tool-result",
1342
+ toolCallId: toolCall.toolCallId,
1343
+ toolName: toolCall.toolName,
1344
+ output: {
1345
+ type: "error-text",
1346
+ value: getErrorMessage(toolCall.error)
1347
+ }
1348
+ };
1349
+ }
1301
1350
  async function executeTool(toolCall, tools, messages, experimentalContext) {
1302
1351
  const tool2 = tools[toolCall.toolName];
1303
1352
  if (!tool2) throw new Error(`Tool "${toolCall.toolName}" not found`);