@ai-sdk/workflow 1.0.0-beta.10 → 1.0.0-beta.100

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,19 +1,82 @@
1
1
  // src/workflow-agent.ts
2
2
  import {
3
- Output
3
+ getErrorMessage,
4
+ validateTypes
5
+ } from "@ai-sdk/provider-utils";
6
+ import {
7
+ Output,
8
+ experimental_filterActiveTools as filterActiveTools2
4
9
  } from "ai";
5
10
  import {
11
+ createRestrictedTelemetryDispatcher as createRestrictedTelemetryDispatcher2,
12
+ collectToolApprovals,
6
13
  convertToLanguageModelPrompt,
7
14
  mergeAbortSignals,
8
15
  mergeCallbacks,
9
- standardizePrompt
16
+ standardizePrompt,
17
+ validateApprovedToolApprovals
10
18
  } from "ai/internal";
11
19
 
20
+ // src/create-language-model-tool-result-output.ts
21
+ import {
22
+ createDefaultDownloadFunction,
23
+ createToolModelOutput,
24
+ downloadAssets,
25
+ mapToolResultOutput
26
+ } from "ai/internal";
27
+ async function createLanguageModelToolResultOutput({
28
+ toolCallId,
29
+ toolName,
30
+ input,
31
+ output,
32
+ tool: tool2,
33
+ errorMode,
34
+ supportedUrls,
35
+ download = createDefaultDownloadFunction(),
36
+ provider
37
+ }) {
38
+ const modelOutput = await createToolModelOutput({
39
+ toolCallId,
40
+ input,
41
+ output,
42
+ tool: tool2,
43
+ errorMode
44
+ });
45
+ const downloadedAssets = modelOutput.type === "content" ? await downloadAssets(
46
+ [
47
+ {
48
+ role: "tool",
49
+ content: [
50
+ {
51
+ type: "tool-result",
52
+ toolCallId,
53
+ toolName,
54
+ output: modelOutput
55
+ }
56
+ ]
57
+ }
58
+ ],
59
+ download,
60
+ supportedUrls
61
+ ) : {};
62
+ return mapToolResultOutput({
63
+ output: modelOutput,
64
+ provider,
65
+ downloadedAssets
66
+ });
67
+ }
68
+
69
+ // src/stream-text-iterator.ts
70
+ import {
71
+ experimental_filterActiveTools as filterActiveTools
72
+ } from "ai";
73
+ import { createRestrictedTelemetryDispatcher } from "ai/internal";
74
+
12
75
  // src/do-stream-step.ts
13
76
  import {
14
- experimental_streamLanguageModelCall as streamModelCall
77
+ experimental_streamLanguageModelCall as streamModelCall,
78
+ gateway
15
79
  } from "ai";
16
- import { gateway } from "ai";
17
80
 
18
81
  // src/serializable-schema.ts
19
82
  import { asSchema, jsonSchema } from "@ai-sdk/provider-utils";
@@ -22,12 +85,15 @@ import Ajv from "ajv";
22
85
  function serializeToolSet(tools) {
23
86
  return Object.fromEntries(
24
87
  Object.entries(tools).map(([name, t]) => {
88
+ var _a;
25
89
  const def = {
26
90
  description: t.description,
91
+ // TODO support tools with function descriptions
27
92
  inputSchema: asSchema(t.inputSchema).jsonSchema
28
93
  };
29
94
  if (t.type === "provider") {
30
95
  def.type = "provider";
96
+ def.isProviderExecuted = (_a = t.isProviderExecuted) != null ? _a : false;
31
97
  def.id = t.id;
32
98
  def.args = t.args;
33
99
  }
@@ -39,7 +105,7 @@ function resolveSerializableTools(tools) {
39
105
  const ajv = new Ajv();
40
106
  return Object.fromEntries(
41
107
  Object.entries(tools).map(([name, t]) => {
42
- var _a;
108
+ var _a, _b;
43
109
  if (t.type === "provider") {
44
110
  return [
45
111
  name,
@@ -47,6 +113,7 @@ function resolveSerializableTools(tools) {
47
113
  type: "provider",
48
114
  id: t.id,
49
115
  args: (_a = t.args) != null ? _a : {},
116
+ isProviderExecuted: (_b = t.isProviderExecuted) != null ? _b : false,
50
117
  inputSchema: jsonSchema(t.inputSchema)
51
118
  })
52
119
  ];
@@ -76,7 +143,7 @@ function resolveSerializableTools(tools) {
76
143
  // src/do-stream-step.ts
77
144
  async function doStreamStep(conversationPrompt, modelInit, writable, serializedTools, options) {
78
145
  "use step";
79
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
146
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
80
147
  const model = typeof modelInit === "string" ? gateway.languageModel(modelInit) : modelInit;
81
148
  const tools = serializedTools ? resolveSerializableTools(serializedTools) : void 0;
82
149
  const { stream: modelStream } = await streamModelCall({
@@ -85,6 +152,7 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
85
152
  // pre-converted LanguageModelV4Prompt. standardizePrompt inside
86
153
  // streamModelCall handles both formats.
87
154
  messages: conversationPrompt,
155
+ allowSystemInMessages: true,
88
156
  tools,
89
157
  toolChoice: options == null ? void 0 : options.toolChoice,
90
158
  includeRawChunks: options == null ? void 0 : options.includeRawChunks,
@@ -106,11 +174,15 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
106
174
  let finish;
107
175
  let text = "";
108
176
  const reasoningParts = [];
177
+ const chunks = [];
109
178
  let responseMetadata;
110
179
  let warnings;
111
180
  const writer = writable == null ? void 0 : writable.getWriter();
112
181
  try {
113
182
  for await (const part of modelStream) {
183
+ if (part.type !== "model-call-start" && part.type !== "model-call-end" && part.type !== "model-call-response-metadata") {
184
+ chunks.push(part);
185
+ }
114
186
  switch (part.type) {
115
187
  case "text-delta":
116
188
  text += part.text;
@@ -180,14 +252,15 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
180
252
  const reasoningText = reasoningParts.map((r) => r.text).join("") || void 0;
181
253
  const step = {
182
254
  callId: "workflow-agent",
183
- stepNumber: 0,
255
+ stepNumber: (_a = options == null ? void 0 : options.stepNumber) != null ? _a : 0,
184
256
  model: {
185
- provider: (_b = (_a = responseMetadata == null ? void 0 : responseMetadata.modelId) == null ? void 0 : _a.split(":")[0]) != null ? _b : "unknown",
186
- modelId: (_c = responseMetadata == null ? void 0 : responseMetadata.modelId) != null ? _c : "unknown"
257
+ provider: (_c = (_b = responseMetadata == null ? void 0 : responseMetadata.modelId) == null ? void 0 : _b.split(":")[0]) != null ? _c : "unknown",
258
+ modelId: (_d = responseMetadata == null ? void 0 : responseMetadata.modelId) != null ? _d : "unknown"
187
259
  },
188
260
  functionId: void 0,
189
261
  metadata: void 0,
190
- context: void 0,
262
+ runtimeContext: (_e = options == null ? void 0 : options.runtimeContext) != null ? _e : {},
263
+ toolsContext: (_f = options == null ? void 0 : options.toolsContext) != null ? _f : {},
191
264
  content: [
192
265
  ...text ? [{ type: "text", text }] : [],
193
266
  ...toolCalls.filter((tc) => !tc.invalid).map((tc) => ({
@@ -224,9 +297,9 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
224
297
  toolResults: [],
225
298
  staticToolResults: [],
226
299
  dynamicToolResults: [],
227
- finishReason: (_d = finish == null ? void 0 : finish.finishReason) != null ? _d : "other",
300
+ finishReason: (_g = finish == null ? void 0 : finish.finishReason) != null ? _g : "other",
228
301
  rawFinishReason: finish == null ? void 0 : finish.rawFinishReason,
229
- usage: (_e = finish == null ? void 0 : finish.usage) != null ? _e : {
302
+ usage: (_h = finish == null ? void 0 : finish.usage) != null ? _h : {
230
303
  inputTokens: 0,
231
304
  inputTokenDetails: {
232
305
  noCacheTokens: void 0,
@@ -240,20 +313,35 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
240
313
  },
241
314
  totalTokens: 0
242
315
  },
316
+ performance: {
317
+ effectiveOutputTokensPerSecond: 0,
318
+ outputTokensPerSecond: void 0,
319
+ inputTokensPerSecond: void 0,
320
+ effectiveTotalTokensPerSecond: 0,
321
+ stepTimeMs: 0,
322
+ responseTimeMs: 0,
323
+ toolExecutionMs: {},
324
+ timeToFirstOutputMs: void 0
325
+ },
243
326
  warnings,
244
- request: { body: "" },
327
+ request: {
328
+ body: "",
329
+ messages: []
330
+ // TODO implement step request messages
331
+ },
245
332
  response: {
246
- id: (_f = responseMetadata == null ? void 0 : responseMetadata.id) != null ? _f : "unknown",
247
- timestamp: (_g = responseMetadata == null ? void 0 : responseMetadata.timestamp) != null ? _g : /* @__PURE__ */ new Date(),
248
- modelId: (_h = responseMetadata == null ? void 0 : responseMetadata.modelId) != null ? _h : "unknown",
333
+ id: (_i = responseMetadata == null ? void 0 : responseMetadata.id) != null ? _i : "unknown",
334
+ timestamp: (_j = responseMetadata == null ? void 0 : responseMetadata.timestamp) != null ? _j : /* @__PURE__ */ new Date(),
335
+ modelId: (_k = responseMetadata == null ? void 0 : responseMetadata.modelId) != null ? _k : "unknown",
249
336
  messages: []
250
337
  },
251
- providerMetadata: (_i = finish == null ? void 0 : finish.providerMetadata) != null ? _i : {}
338
+ providerMetadata: (_l = finish == null ? void 0 : finish.providerMetadata) != null ? _l : {}
252
339
  };
253
340
  return {
254
341
  toolCalls,
255
342
  finish,
256
343
  step,
344
+ chunks,
257
345
  providerExecutedToolResults
258
346
  };
259
347
  }
@@ -265,25 +353,27 @@ async function* streamTextIterator({
265
353
  writable,
266
354
  model,
267
355
  stopConditions,
268
- maxSteps,
356
+ onStepEnd,
269
357
  onStepFinish,
270
358
  onStepStart,
271
359
  onError,
272
360
  prepareStep,
273
361
  generationSettings,
274
362
  toolChoice,
275
- experimental_context,
276
- experimental_telemetry,
363
+ runtimeContext,
364
+ toolsContext,
365
+ telemetry,
277
366
  includeRawChunks = false,
278
367
  repairToolCall,
279
368
  responseFormat
280
369
  }) {
281
- var _a;
370
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
282
371
  let conversationPrompt = [...prompt];
283
372
  let currentModel = model;
284
373
  let currentGenerationSettings = generationSettings != null ? generationSettings : {};
285
374
  let currentToolChoice = toolChoice;
286
- let currentContext = experimental_context;
375
+ let currentRuntimeContext = runtimeContext != null ? runtimeContext : {};
376
+ let currentToolsContext = toolsContext != null ? toolsContext : {};
287
377
  let currentActiveTools;
288
378
  const steps = [];
289
379
  let done = false;
@@ -291,11 +381,12 @@ async function* streamTextIterator({
291
381
  let stepNumber = 0;
292
382
  let lastStep;
293
383
  let lastStepWasToolCalls = false;
294
- const effectiveMaxSteps = maxSteps != null ? maxSteps : Infinity;
384
+ const telemetryDispatcher = createRestrictedTelemetryDispatcher({
385
+ telemetry,
386
+ includeRuntimeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext,
387
+ includeToolsContext: telemetry == null ? void 0 : telemetry.includeToolsContext
388
+ });
295
389
  while (!done) {
296
- if (stepNumber >= effectiveMaxSteps) {
297
- break;
298
- }
299
390
  if ((_a = currentGenerationSettings.abortSignal) == null ? void 0 : _a.aborted) {
300
391
  break;
301
392
  }
@@ -305,15 +396,16 @@ async function* streamTextIterator({
305
396
  stepNumber,
306
397
  steps,
307
398
  messages: conversationPrompt,
308
- experimental_context: currentContext
399
+ runtimeContext: currentRuntimeContext,
400
+ toolsContext: currentToolsContext
309
401
  });
310
- if (prepareResult.model !== void 0) {
402
+ if ((prepareResult == null ? void 0 : prepareResult.model) !== void 0) {
311
403
  currentModel = prepareResult.model;
312
404
  }
313
- if (prepareResult.messages !== void 0) {
405
+ if ((prepareResult == null ? void 0 : prepareResult.messages) !== void 0) {
314
406
  conversationPrompt = [...prepareResult.messages];
315
407
  }
316
- if (prepareResult.system !== void 0) {
408
+ if ((prepareResult == null ? void 0 : prepareResult.system) !== void 0) {
317
409
  if (conversationPrompt.length > 0 && conversationPrompt[0].role === "system") {
318
410
  conversationPrompt[0] = {
319
411
  role: "system",
@@ -326,79 +418,82 @@ async function* streamTextIterator({
326
418
  });
327
419
  }
328
420
  }
329
- if (prepareResult.experimental_context !== void 0) {
330
- currentContext = prepareResult.experimental_context;
421
+ if ((prepareResult == null ? void 0 : prepareResult.runtimeContext) !== void 0) {
422
+ currentRuntimeContext = prepareResult.runtimeContext;
423
+ }
424
+ if ((prepareResult == null ? void 0 : prepareResult.toolsContext) !== void 0) {
425
+ currentToolsContext = prepareResult.toolsContext;
331
426
  }
332
- if (prepareResult.activeTools !== void 0) {
427
+ if ((prepareResult == null ? void 0 : prepareResult.activeTools) !== void 0) {
333
428
  currentActiveTools = prepareResult.activeTools;
334
429
  }
335
- if (prepareResult.maxOutputTokens !== void 0) {
430
+ if ((prepareResult == null ? void 0 : prepareResult.maxOutputTokens) !== void 0) {
336
431
  currentGenerationSettings = {
337
432
  ...currentGenerationSettings,
338
433
  maxOutputTokens: prepareResult.maxOutputTokens
339
434
  };
340
435
  }
341
- if (prepareResult.temperature !== void 0) {
436
+ if ((prepareResult == null ? void 0 : prepareResult.temperature) !== void 0) {
342
437
  currentGenerationSettings = {
343
438
  ...currentGenerationSettings,
344
439
  temperature: prepareResult.temperature
345
440
  };
346
441
  }
347
- if (prepareResult.topP !== void 0) {
442
+ if ((prepareResult == null ? void 0 : prepareResult.topP) !== void 0) {
348
443
  currentGenerationSettings = {
349
444
  ...currentGenerationSettings,
350
445
  topP: prepareResult.topP
351
446
  };
352
447
  }
353
- if (prepareResult.topK !== void 0) {
448
+ if ((prepareResult == null ? void 0 : prepareResult.topK) !== void 0) {
354
449
  currentGenerationSettings = {
355
450
  ...currentGenerationSettings,
356
451
  topK: prepareResult.topK
357
452
  };
358
453
  }
359
- if (prepareResult.presencePenalty !== void 0) {
454
+ if ((prepareResult == null ? void 0 : prepareResult.presencePenalty) !== void 0) {
360
455
  currentGenerationSettings = {
361
456
  ...currentGenerationSettings,
362
457
  presencePenalty: prepareResult.presencePenalty
363
458
  };
364
459
  }
365
- if (prepareResult.frequencyPenalty !== void 0) {
460
+ if ((prepareResult == null ? void 0 : prepareResult.frequencyPenalty) !== void 0) {
366
461
  currentGenerationSettings = {
367
462
  ...currentGenerationSettings,
368
463
  frequencyPenalty: prepareResult.frequencyPenalty
369
464
  };
370
465
  }
371
- if (prepareResult.stopSequences !== void 0) {
466
+ if ((prepareResult == null ? void 0 : prepareResult.stopSequences) !== void 0) {
372
467
  currentGenerationSettings = {
373
468
  ...currentGenerationSettings,
374
469
  stopSequences: prepareResult.stopSequences
375
470
  };
376
471
  }
377
- if (prepareResult.seed !== void 0) {
472
+ if ((prepareResult == null ? void 0 : prepareResult.seed) !== void 0) {
378
473
  currentGenerationSettings = {
379
474
  ...currentGenerationSettings,
380
475
  seed: prepareResult.seed
381
476
  };
382
477
  }
383
- if (prepareResult.maxRetries !== void 0) {
478
+ if ((prepareResult == null ? void 0 : prepareResult.maxRetries) !== void 0) {
384
479
  currentGenerationSettings = {
385
480
  ...currentGenerationSettings,
386
481
  maxRetries: prepareResult.maxRetries
387
482
  };
388
483
  }
389
- if (prepareResult.headers !== void 0) {
484
+ if ((prepareResult == null ? void 0 : prepareResult.headers) !== void 0) {
390
485
  currentGenerationSettings = {
391
486
  ...currentGenerationSettings,
392
487
  headers: prepareResult.headers
393
488
  };
394
489
  }
395
- if (prepareResult.providerOptions !== void 0) {
490
+ if ((prepareResult == null ? void 0 : prepareResult.providerOptions) !== void 0) {
396
491
  currentGenerationSettings = {
397
492
  ...currentGenerationSettings,
398
493
  providerOptions: prepareResult.providerOptions
399
494
  };
400
495
  }
401
- if (prepareResult.toolChoice !== void 0) {
496
+ if ((prepareResult == null ? void 0 : prepareResult.toolChoice) !== void 0) {
402
497
  currentToolChoice = prepareResult.toolChoice;
403
498
  }
404
499
  }
@@ -407,12 +502,53 @@ async function* streamTextIterator({
407
502
  stepNumber,
408
503
  model: currentModel,
409
504
  messages: conversationPrompt,
410
- steps: [...steps]
505
+ steps: [...steps],
506
+ runtimeContext: currentRuntimeContext,
507
+ toolsContext: currentToolsContext
411
508
  });
412
509
  }
510
+ const stepStartModelInfo = getModelInfo(currentModel);
511
+ await ((_b = telemetryDispatcher.onStepStart) == null ? void 0 : _b.call(telemetryDispatcher, {
512
+ callId: "workflow-agent",
513
+ provider: stepStartModelInfo.provider,
514
+ modelId: stepStartModelInfo.modelId,
515
+ stepNumber,
516
+ system: void 0,
517
+ messages: conversationPrompt,
518
+ tools,
519
+ toolChoice: currentToolChoice,
520
+ activeTools: currentActiveTools,
521
+ steps: steps.map(normalizeStepForTelemetry),
522
+ providerOptions: currentGenerationSettings.providerOptions,
523
+ output: void 0,
524
+ runtimeContext: currentRuntimeContext,
525
+ toolsContext: currentToolsContext
526
+ }));
413
527
  try {
414
- const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? filterToolSet(tools, currentActiveTools) : tools;
528
+ const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? (_c = filterActiveTools({
529
+ tools,
530
+ activeTools: currentActiveTools
531
+ })) != null ? _c : tools : tools;
415
532
  const serializedTools = serializeToolSet(effectiveTools);
533
+ const modelCallInfo = getModelInfo(currentModel);
534
+ await ((_d = telemetryDispatcher.onLanguageModelCallStart) == null ? void 0 : _d.call(telemetryDispatcher, {
535
+ callId: "workflow-agent",
536
+ provider: modelCallInfo.provider,
537
+ modelId: modelCallInfo.modelId,
538
+ system: void 0,
539
+ messages: conversationPrompt,
540
+ tools: serializedTools == null ? void 0 : Object.values(serializedTools).map((tool2) => ({ ...tool2 })),
541
+ maxOutputTokens: currentGenerationSettings.maxOutputTokens,
542
+ temperature: currentGenerationSettings.temperature,
543
+ topP: currentGenerationSettings.topP,
544
+ topK: currentGenerationSettings.topK,
545
+ presencePenalty: currentGenerationSettings.presencePenalty,
546
+ frequencyPenalty: currentGenerationSettings.frequencyPenalty,
547
+ stopSequences: currentGenerationSettings.stopSequences,
548
+ seed: currentGenerationSettings.seed,
549
+ providerOptions: currentGenerationSettings.providerOptions,
550
+ headers: currentGenerationSettings.headers
551
+ }));
416
552
  const { toolCalls, finish, step, providerExecutedToolResults } = await doStreamStep(
417
553
  conversationPrompt,
418
554
  currentModel,
@@ -422,11 +558,22 @@ async function* streamTextIterator({
422
558
  ...currentGenerationSettings,
423
559
  toolChoice: currentToolChoice,
424
560
  includeRawChunks,
425
- experimental_telemetry,
426
561
  repairToolCall,
427
- responseFormat
562
+ responseFormat,
563
+ runtimeContext: currentRuntimeContext,
564
+ toolsContext: currentToolsContext,
565
+ stepNumber
428
566
  }
429
567
  );
568
+ await ((_i = telemetryDispatcher.onLanguageModelCallEnd) == null ? void 0 : _i.call(telemetryDispatcher, {
569
+ callId: step.callId,
570
+ provider: (_f = (_e = step.model) == null ? void 0 : _e.provider) != null ? _f : "unknown",
571
+ modelId: (_h = (_g = step.model) == null ? void 0 : _g.modelId) != null ? _h : "unknown",
572
+ finishReason: step.finishReason,
573
+ usage: step.usage,
574
+ content: step.content,
575
+ responseId: step.response.id
576
+ }));
430
577
  _isFirstIteration = false;
431
578
  stepNumber++;
432
579
  steps.push(step);
@@ -454,7 +601,8 @@ async function* streamTextIterator({
454
601
  toolCalls,
455
602
  messages: conversationPrompt,
456
603
  step,
457
- context: currentContext,
604
+ runtimeContext: currentRuntimeContext,
605
+ toolsContext: currentToolsContext,
458
606
  providerExecutedToolResults
459
607
  };
460
608
  conversationPrompt.push({
@@ -495,9 +643,11 @@ async function* streamTextIterator({
495
643
  `Unexpected finish reason: ${typeof (finish == null ? void 0 : finish.finishReason) === "object" ? JSON.stringify(finish == null ? void 0 : finish.finishReason) : finish == null ? void 0 : finish.finishReason}`
496
644
  );
497
645
  }
498
- if (onStepFinish) {
499
- await onStepFinish(step);
646
+ const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;
647
+ if (resolvedOnStepEnd) {
648
+ await resolvedOnStepEnd(step);
500
649
  }
650
+ await ((_j = telemetryDispatcher.onStepEnd) == null ? void 0 : _j.call(telemetryDispatcher, normalizeStepForTelemetry(step)));
501
651
  } catch (error) {
502
652
  if (onError) {
503
653
  await onError({ error });
@@ -510,19 +660,22 @@ async function* streamTextIterator({
510
660
  toolCalls: [],
511
661
  messages: conversationPrompt,
512
662
  step: lastStep,
513
- context: currentContext
663
+ runtimeContext: currentRuntimeContext,
664
+ toolsContext: currentToolsContext
514
665
  };
515
666
  }
516
667
  return conversationPrompt;
517
668
  }
518
- function filterToolSet(tools, activeTools) {
519
- const filtered = {};
520
- for (const toolName of activeTools) {
521
- if (toolName in tools) {
522
- filtered[toolName] = tools[toolName];
523
- }
524
- }
525
- return filtered;
669
+ function getModelInfo(model) {
670
+ var _a;
671
+ return typeof model === "string" ? { provider: (_a = model.split("/")[0]) != null ? _a : "gateway", modelId: model } : { provider: model.provider, modelId: model.modelId };
672
+ }
673
+ function normalizeStepForTelemetry(step) {
674
+ var _a;
675
+ return {
676
+ ...step,
677
+ model: (_a = step.model) != null ? _a : { provider: "unknown", modelId: "unknown" }
678
+ };
526
679
  }
527
680
  function sanitizeProviderMetadataForToolCall(metadata) {
528
681
  if (metadata == null) return void 0;
@@ -548,26 +701,28 @@ function sanitizeProviderMetadataForToolCall(metadata) {
548
701
  // src/workflow-agent.ts
549
702
  var WorkflowAgent = class {
550
703
  constructor(options) {
551
- var _a, _b;
704
+ var _a, _b, _c;
552
705
  this.id = options.id;
553
706
  this.model = options.model;
554
707
  this.tools = (_a = options.tools) != null ? _a : {};
555
708
  this.instructions = (_b = options.instructions) != null ? _b : options.system;
556
709
  this.toolChoice = options.toolChoice;
557
- this.telemetry = options.experimental_telemetry;
558
- this.experimentalContext = options.experimental_context;
710
+ this.telemetry = options.telemetry;
711
+ this.runtimeContext = options.runtimeContext;
712
+ this.toolsContext = options.toolsContext;
559
713
  this.stopWhen = options.stopWhen;
560
714
  this.activeTools = options.activeTools;
561
715
  this.output = options.output;
562
716
  this.experimentalRepairToolCall = options.experimental_repairToolCall;
563
717
  this.experimentalDownload = options.experimental_download;
564
718
  this.prepareStep = options.prepareStep;
565
- this.constructorOnStepFinish = options.onStepFinish;
566
- this.constructorOnFinish = options.onFinish;
719
+ this.constructorOnStepEnd = (_c = options.onStepEnd) != null ? _c : options.onStepFinish;
720
+ const { onFinish, onEnd = onFinish } = options;
721
+ this.constructorOnEnd = onEnd;
567
722
  this.constructorOnStart = options.experimental_onStart;
568
723
  this.constructorOnStepStart = options.experimental_onStepStart;
569
- this.constructorOnToolCallStart = options.experimental_onToolCallStart;
570
- this.constructorOnToolCallFinish = options.experimental_onToolCallFinish;
724
+ this.constructorOnToolExecutionStart = options.onToolExecutionStart;
725
+ this.constructorOnToolExecutionEnd = options.onToolExecutionEnd;
571
726
  this.prepareCall = options.prepareCall;
572
727
  this.generationSettings = {
573
728
  maxOutputTokens: options.maxOutputTokens,
@@ -588,24 +743,27 @@ var WorkflowAgent = class {
588
743
  throw new Error("Not implemented");
589
744
  }
590
745
  async stream(options) {
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;
746
+ 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, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P;
747
+ const { onFinish, onEnd = onFinish } = options;
592
748
  let effectiveModel = this.model;
593
749
  let effectiveInstructions = (_a = options.system) != null ? _a : this.instructions;
594
750
  let effectivePrompt = options.prompt;
595
751
  let effectiveMessages = options.messages;
596
752
  let effectiveGenerationSettings = { ...this.generationSettings };
597
- let effectiveExperimentalContext = (_b = options.experimental_context) != null ? _b : this.experimentalContext;
598
- let effectiveToolChoiceFromPrepare = (_c = options.toolChoice) != null ? _c : this.toolChoice;
599
- let effectiveTelemetryFromPrepare = (_d = options.experimental_telemetry) != null ? _d : this.telemetry;
600
- const resolvedMessagesForPrepareCall = (_e = effectiveMessages != null ? effectiveMessages : typeof effectivePrompt === "string" ? [{ role: "user", content: effectivePrompt }] : effectivePrompt) != null ? _e : [];
753
+ let effectiveRuntimeContext = (_c = (_b = options.runtimeContext) != null ? _b : this.runtimeContext) != null ? _c : {};
754
+ let effectiveToolsContext = (_e = (_d = options.toolsContext) != null ? _d : this.toolsContext) != null ? _e : {};
755
+ let effectiveToolChoiceFromPrepare = (_f = options.toolChoice) != null ? _f : this.toolChoice;
756
+ let effectiveTelemetryFromPrepare = (_g = options.telemetry) != null ? _g : this.telemetry;
757
+ const resolvedMessagesForPrepareCall = (_h = effectiveMessages != null ? effectiveMessages : typeof effectivePrompt === "string" ? [{ role: "user", content: effectivePrompt }] : effectivePrompt) != null ? _h : [];
601
758
  if (this.prepareCall) {
602
759
  const prepared = await this.prepareCall({
603
760
  model: effectiveModel,
604
761
  tools: this.tools,
605
762
  instructions: effectiveInstructions,
606
763
  toolChoice: effectiveToolChoiceFromPrepare,
607
- experimental_telemetry: effectiveTelemetryFromPrepare,
608
- experimental_context: effectiveExperimentalContext,
764
+ telemetry: effectiveTelemetryFromPrepare,
765
+ runtimeContext: effectiveRuntimeContext,
766
+ toolsContext: effectiveToolsContext,
609
767
  messages: resolvedMessagesForPrepareCall,
610
768
  ...effectiveGenerationSettings
611
769
  });
@@ -616,12 +774,14 @@ var WorkflowAgent = class {
616
774
  effectiveMessages = prepared.messages;
617
775
  effectivePrompt = void 0;
618
776
  }
619
- if (prepared.experimental_context !== void 0)
620
- effectiveExperimentalContext = prepared.experimental_context;
777
+ if (prepared.runtimeContext !== void 0)
778
+ effectiveRuntimeContext = prepared.runtimeContext;
779
+ if (prepared.toolsContext !== void 0)
780
+ effectiveToolsContext = prepared.toolsContext;
621
781
  if (prepared.toolChoice !== void 0)
622
782
  effectiveToolChoiceFromPrepare = prepared.toolChoice;
623
- if (prepared.experimental_telemetry !== void 0)
624
- effectiveTelemetryFromPrepare = prepared.experimental_telemetry;
783
+ if (prepared.telemetry !== void 0)
784
+ effectiveTelemetryFromPrepare = prepared.telemetry;
625
785
  if (prepared.maxOutputTokens !== void 0)
626
786
  effectiveGenerationSettings.maxOutputTokens = prepared.maxOutputTokens;
627
787
  if (prepared.temperature !== void 0)
@@ -643,44 +803,215 @@ var WorkflowAgent = class {
643
803
  if (prepared.providerOptions !== void 0)
644
804
  effectiveGenerationSettings.providerOptions = prepared.providerOptions;
645
805
  }
806
+ const effectiveTelemetry = effectiveTelemetryFromPrepare;
807
+ const telemetryDispatcher = createRestrictedTelemetryDispatcher2({
808
+ telemetry: effectiveTelemetry,
809
+ includeRuntimeContext: effectiveTelemetry == null ? void 0 : effectiveTelemetry.includeRuntimeContext,
810
+ includeToolsContext: effectiveTelemetry == null ? void 0 : effectiveTelemetry.includeToolsContext
811
+ });
646
812
  const prompt = await standardizePrompt({
647
813
  system: effectiveInstructions,
814
+ allowSystemInMessages: true,
815
+ // TODO: consider exposing this as a parameter
648
816
  ...effectivePrompt != null ? { prompt: effectivePrompt } : { messages: effectiveMessages }
649
817
  });
650
- const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovalsFromMessages(prompt.messages);
818
+ const download = (_i = options.experimental_download) != null ? _i : this.experimentalDownload;
819
+ const collectedApprovals = collectToolApprovals({
820
+ messages: prompt.messages
821
+ });
822
+ const approvedToolApprovals = collectedApprovals.approvedToolApprovals.map(
823
+ (collected) => ({
824
+ toolCallId: collected.toolCall.toolCallId,
825
+ toolName: collected.toolCall.toolName,
826
+ input: collected.toolCall.input,
827
+ reason: collected.approvalResponse.reason,
828
+ providerExecuted: collected.toolCall.providerExecuted === true,
829
+ collected
830
+ })
831
+ );
832
+ const deniedToolApprovals = collectedApprovals.deniedToolApprovals.map(
833
+ (collected) => ({
834
+ toolCallId: collected.toolCall.toolCallId,
835
+ toolName: collected.toolCall.toolName,
836
+ input: collected.toolCall.input,
837
+ reason: collected.approvalResponse.reason,
838
+ providerExecuted: collected.toolCall.providerExecuted === true
839
+ })
840
+ );
841
+ const providerExecutedApprovalIds = new Set(
842
+ [
843
+ ...collectedApprovals.approvedToolApprovals,
844
+ ...collectedApprovals.deniedToolApprovals
845
+ ].filter((collected) => collected.toolCall.providerExecuted === true).map((collected) => collected.approvalResponse.approvalId)
846
+ );
651
847
  if (approvedToolApprovals.length > 0 || deniedToolApprovals.length > 0) {
652
848
  const _toolResultMessages = [];
653
849
  const toolResultContent = [];
850
+ const approvedRawResults = [];
654
851
  for (const approval of approvedToolApprovals) {
852
+ if (approval.providerExecuted) {
853
+ continue;
854
+ }
655
855
  const tool2 = this.tools[approval.toolName];
656
856
  if (tool2 && typeof tool2.execute === "function") {
857
+ if (!tool2.needsApproval) {
858
+ const reason = `Tool "${approval.toolName}" does not require approval`;
859
+ toolResultContent.push({
860
+ type: "tool-result",
861
+ toolCallId: approval.toolCallId,
862
+ toolName: approval.toolName,
863
+ output: await createLanguageModelToolResultOutput({
864
+ toolCallId: approval.toolCallId,
865
+ toolName: approval.toolName,
866
+ input: approval.input,
867
+ output: reason,
868
+ tool: tool2,
869
+ errorMode: "text",
870
+ supportedUrls: {},
871
+ download
872
+ })
873
+ });
874
+ continue;
875
+ }
876
+ let revalidationReason;
877
+ try {
878
+ const { deniedToolApprovals: policyDenied } = await validateApprovedToolApprovals({
879
+ approvedToolApprovals: [approval.collected],
880
+ tools: this.tools,
881
+ toolApproval: void 0,
882
+ messages: prompt.messages,
883
+ toolsContext: effectiveToolsContext,
884
+ runtimeContext: effectiveRuntimeContext
885
+ });
886
+ if (policyDenied.length > 0) {
887
+ revalidationReason = (_j = policyDenied[0].approvalResponse.reason) != null ? _j : "Tool approval denied";
888
+ }
889
+ } catch (error) {
890
+ revalidationReason = getErrorMessage(error);
891
+ }
892
+ if (revalidationReason != null) {
893
+ toolResultContent.push({
894
+ type: "tool-result",
895
+ toolCallId: approval.toolCallId,
896
+ toolName: approval.toolName,
897
+ output: await createLanguageModelToolResultOutput({
898
+ toolCallId: approval.toolCallId,
899
+ toolName: approval.toolName,
900
+ input: approval.input,
901
+ output: revalidationReason,
902
+ tool: tool2,
903
+ errorMode: "text",
904
+ supportedUrls: {},
905
+ download
906
+ })
907
+ });
908
+ continue;
909
+ }
657
910
  try {
658
911
  const { execute } = tool2;
659
- const toolResult = await execute(approval.input, {
912
+ const resolvedContext = await resolveToolContext({
913
+ toolName: approval.toolName,
914
+ tool: tool2,
915
+ toolsContext: effectiveToolsContext
916
+ });
917
+ const toolCallEvent = {
918
+ type: "tool-call",
919
+ toolCallId: approval.toolCallId,
920
+ toolName: approval.toolName,
921
+ input: approval.input
922
+ };
923
+ const messages2 = prompt.messages;
924
+ await ((_k = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _k.call(telemetryDispatcher, {
925
+ toolCall: toolCallEvent,
926
+ stepNumber: 0,
927
+ messages: messages2,
928
+ toolContext: resolvedContext
929
+ }));
930
+ const startTime = Date.now();
931
+ const executeApprovedTool = () => execute(approval.input, {
660
932
  toolCallId: approval.toolCallId,
661
933
  messages: [],
662
- context: effectiveExperimentalContext
934
+ context: resolvedContext
663
935
  });
936
+ const toolResult = telemetryDispatcher.executeTool != null ? await telemetryDispatcher.executeTool({
937
+ callId: "workflow-agent",
938
+ toolCallId: approval.toolCallId,
939
+ execute: executeApprovedTool
940
+ }) : await executeApprovedTool();
941
+ await ((_l = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _l.call(telemetryDispatcher, {
942
+ toolCall: toolCallEvent,
943
+ stepNumber: 0,
944
+ durationMs: Date.now() - startTime,
945
+ messages: messages2,
946
+ toolContext: resolvedContext,
947
+ success: true,
948
+ output: toolResult
949
+ }));
664
950
  toolResultContent.push({
665
951
  type: "tool-result",
666
952
  toolCallId: approval.toolCallId,
667
953
  toolName: approval.toolName,
668
- output: typeof toolResult === "string" ? { type: "text", value: toolResult } : { type: "json", value: toolResult }
954
+ output: await createLanguageModelToolResultOutput({
955
+ toolCallId: approval.toolCallId,
956
+ toolName: approval.toolName,
957
+ input: approval.input,
958
+ output: toolResult,
959
+ tool: tool2,
960
+ errorMode: "none",
961
+ supportedUrls: {},
962
+ download
963
+ })
964
+ });
965
+ approvedRawResults.push({
966
+ toolCallId: approval.toolCallId,
967
+ toolName: approval.toolName,
968
+ input: approval.input,
969
+ output: toolResult
669
970
  });
670
971
  } catch (error) {
972
+ const errorMessage = getErrorMessage(error);
973
+ await ((_m = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _m.call(telemetryDispatcher, {
974
+ toolCall: {
975
+ type: "tool-call",
976
+ toolCallId: approval.toolCallId,
977
+ toolName: approval.toolName,
978
+ input: approval.input
979
+ },
980
+ stepNumber: 0,
981
+ durationMs: 0,
982
+ messages: prompt.messages,
983
+ toolContext: void 0,
984
+ success: false,
985
+ error
986
+ }));
671
987
  toolResultContent.push({
672
988
  type: "tool-result",
673
989
  toolCallId: approval.toolCallId,
674
990
  toolName: approval.toolName,
675
- output: {
676
- type: "text",
677
- value: getErrorMessage(error)
678
- }
991
+ output: await createLanguageModelToolResultOutput({
992
+ toolCallId: approval.toolCallId,
993
+ toolName: approval.toolName,
994
+ input: approval.input,
995
+ output: errorMessage,
996
+ tool: tool2,
997
+ errorMode: "text",
998
+ supportedUrls: {},
999
+ download
1000
+ })
1001
+ });
1002
+ approvedRawResults.push({
1003
+ toolCallId: approval.toolCallId,
1004
+ toolName: approval.toolName,
1005
+ input: approval.input,
1006
+ output: errorMessage
679
1007
  });
680
1008
  }
681
1009
  }
682
1010
  }
683
1011
  for (const denial of deniedToolApprovals) {
1012
+ if (denial.providerExecuted) {
1013
+ continue;
1014
+ }
684
1015
  toolResultContent.push({
685
1016
  type: "tool-result",
686
1017
  toolCallId: denial.toolCallId,
@@ -695,15 +1026,21 @@ var WorkflowAgent = class {
695
1026
  for (const msg of prompt.messages) {
696
1027
  if (msg.role === "assistant" && Array.isArray(msg.content)) {
697
1028
  const filtered = msg.content.filter(
698
- (p) => p.type !== "tool-approval-request"
1029
+ (p) => p.type !== "tool-approval-request" || providerExecutedApprovalIds.has(p.approvalId)
699
1030
  );
700
1031
  if (filtered.length > 0) {
701
1032
  cleanedMessages.push({ ...msg, content: filtered });
702
1033
  }
703
1034
  } else if (msg.role === "tool") {
704
- const filtered = msg.content.filter(
705
- (p) => p.type !== "tool-approval-response"
706
- );
1035
+ const filtered = msg.content.flatMap((p) => {
1036
+ if (p.type !== "tool-approval-response") {
1037
+ return [p];
1038
+ }
1039
+ if (!providerExecutedApprovalIds.has(p.approvalId)) {
1040
+ return [];
1041
+ }
1042
+ return [{ ...p, providerExecuted: true }];
1043
+ });
707
1044
  if (filtered.length > 0) {
708
1045
  cleanedMessages.push({ ...msg, content: filtered });
709
1046
  }
@@ -719,21 +1056,10 @@ var WorkflowAgent = class {
719
1056
  }
720
1057
  prompt.messages = cleanedMessages;
721
1058
  if (options.writable && toolResultContent.length > 0) {
722
- const approvedResults = toolResultContent.filter((r) => r.output.type !== "execution-denied").map((r) => {
723
- var _a2;
724
- return {
725
- toolCallId: r.toolCallId,
726
- toolName: r.toolName,
727
- input: (_a2 = approvedToolApprovals.find(
728
- (a) => a.toolCallId === r.toolCallId
729
- )) == null ? void 0 : _a2.input,
730
- output: "value" in r.output ? r.output.value : void 0
731
- };
732
- });
733
1059
  const deniedResults = toolResultContent.filter((r) => r.output.type === "execution-denied").map((r) => ({ toolCallId: r.toolCallId }));
734
1060
  await writeApprovalToolResults(
735
1061
  options.writable,
736
- approvedResults,
1062
+ approvedRawResults,
737
1063
  deniedResults
738
1064
  );
739
1065
  }
@@ -741,11 +1067,11 @@ var WorkflowAgent = class {
741
1067
  const modelPrompt = await convertToLanguageModelPrompt({
742
1068
  prompt,
743
1069
  supportedUrls: {},
744
- download: (_f = options.experimental_download) != null ? _f : this.experimentalDownload
1070
+ download
745
1071
  });
746
1072
  const effectiveAbortSignal = mergeAbortSignals(
747
- (_g = options.abortSignal) != null ? _g : effectiveGenerationSettings.abortSignal,
748
- options.timeout != null ? AbortSignal.timeout(options.timeout) : void 0
1073
+ (_n = options.abortSignal) != null ? _n : effectiveGenerationSettings.abortSignal,
1074
+ options.timeout
749
1075
  );
750
1076
  const mergedGenerationSettings = {
751
1077
  ...effectiveGenerationSettings,
@@ -778,13 +1104,13 @@ var WorkflowAgent = class {
778
1104
  providerOptions: options.providerOptions
779
1105
  }
780
1106
  };
781
- const mergedOnStepFinish = mergeCallbacks(
782
- this.constructorOnStepFinish,
783
- options.onStepFinish
1107
+ const mergedOnStepEnd = mergeCallbacks(
1108
+ this.constructorOnStepEnd,
1109
+ (_o = options.onStepEnd) != null ? _o : options.onStepFinish
784
1110
  );
785
- const mergedOnFinish = mergeCallbacks(
786
- this.constructorOnFinish,
787
- options.onFinish
1111
+ const mergedOnEnd = mergeCallbacks(
1112
+ this.constructorOnEnd,
1113
+ onEnd
788
1114
  );
789
1115
  const mergedOnStart = mergeCallbacks(
790
1116
  this.constructorOnStart,
@@ -794,82 +1120,200 @@ var WorkflowAgent = class {
794
1120
  this.constructorOnStepStart,
795
1121
  options.experimental_onStepStart
796
1122
  );
797
- const mergedOnToolCallStart = mergeCallbacks(
798
- this.constructorOnToolCallStart,
799
- options.experimental_onToolCallStart
1123
+ const mergedOnToolExecutionStart = mergeCallbacks(
1124
+ this.constructorOnToolExecutionStart,
1125
+ options.onToolExecutionStart
800
1126
  );
801
- const mergedOnToolCallFinish = mergeCallbacks(
802
- this.constructorOnToolCallFinish,
803
- options.experimental_onToolCallFinish
1127
+ const mergedOnToolExecutionEnd = mergeCallbacks(
1128
+ this.constructorOnToolExecutionEnd,
1129
+ options.onToolExecutionEnd
804
1130
  );
805
1131
  const effectiveToolChoice = effectiveToolChoiceFromPrepare;
806
- const effectiveTelemetry = effectiveTelemetryFromPrepare;
807
- const effectiveActiveTools = (_h = options.activeTools) != null ? _h : this.activeTools;
808
- const effectiveTools = effectiveActiveTools && effectiveActiveTools.length > 0 ? filterTools(this.tools, effectiveActiveTools) : this.tools;
809
- let experimentalContext = effectiveExperimentalContext;
1132
+ const effectiveActiveTools = (_p = options.activeTools) != null ? _p : this.activeTools;
1133
+ const effectiveTools = effectiveActiveTools && effectiveActiveTools.length > 0 ? (_q = filterActiveTools2({
1134
+ tools: this.tools,
1135
+ activeTools: effectiveActiveTools
1136
+ })) != null ? _q : this.tools : this.tools;
1137
+ const effectiveModelInfo = getModelInfo2(effectiveModel);
1138
+ let runtimeContext = effectiveRuntimeContext;
1139
+ let toolsContext = effectiveToolsContext;
810
1140
  const steps = [];
811
1141
  let lastStepToolCalls = [];
812
1142
  let lastStepToolResults = [];
813
1143
  if (mergedOnStart) {
814
1144
  await mergedOnStart({
815
1145
  model: effectiveModel,
816
- messages: prompt.messages
1146
+ messages: prompt.messages,
1147
+ runtimeContext,
1148
+ toolsContext
817
1149
  });
818
1150
  }
819
- const executeToolWithCallbacks = async (toolCall, tools, messages2, context, currentStepNumber = 0) => {
1151
+ await ((_t = telemetryDispatcher.onStart) == null ? void 0 : _t.call(telemetryDispatcher, {
1152
+ callId: "workflow-agent",
1153
+ operationId: "ai.workflowAgent.stream",
1154
+ provider: effectiveModelInfo.provider,
1155
+ modelId: effectiveModelInfo.modelId,
1156
+ system: void 0,
1157
+ messages: prompt.messages,
1158
+ tools: effectiveTools,
1159
+ toolChoice: effectiveToolChoice,
1160
+ activeTools: effectiveActiveTools,
1161
+ maxOutputTokens: mergedGenerationSettings.maxOutputTokens,
1162
+ temperature: mergedGenerationSettings.temperature,
1163
+ topP: mergedGenerationSettings.topP,
1164
+ topK: mergedGenerationSettings.topK,
1165
+ presencePenalty: mergedGenerationSettings.presencePenalty,
1166
+ frequencyPenalty: mergedGenerationSettings.frequencyPenalty,
1167
+ stopSequences: mergedGenerationSettings.stopSequences,
1168
+ seed: mergedGenerationSettings.seed,
1169
+ maxRetries: (_r = mergedGenerationSettings.maxRetries) != null ? _r : 2,
1170
+ timeout: void 0,
1171
+ headers: mergedGenerationSettings.headers,
1172
+ providerOptions: mergedGenerationSettings.providerOptions,
1173
+ output: (_s = options.output) != null ? _s : this.output,
1174
+ runtimeContext,
1175
+ toolsContext
1176
+ }));
1177
+ const executeToolWithCallbacks = async (toolCall, tools, messages2, perToolContexts, currentStepNumber = 0) => {
1178
+ var _a2, _b2, _c2, _d2;
820
1179
  const toolCallEvent = {
821
1180
  type: "tool-call",
822
1181
  toolCallId: toolCall.toolCallId,
823
1182
  toolName: toolCall.toolName,
824
1183
  input: toolCall.input
825
1184
  };
826
- if (mergedOnToolCallStart) {
827
- await mergedOnToolCallStart({
1185
+ const tool2 = tools[toolCall.toolName];
1186
+ const resolvedContext = tool2 ? await resolveToolContext({
1187
+ toolName: toolCall.toolName,
1188
+ tool: tool2,
1189
+ toolsContext: perToolContexts
1190
+ }) : void 0;
1191
+ const modelMessages = getToolCallbackMessages(messages2);
1192
+ if (mergedOnToolExecutionStart) {
1193
+ await mergedOnToolExecutionStart({
828
1194
  toolCall: toolCallEvent,
829
- stepNumber: currentStepNumber
1195
+ stepNumber: currentStepNumber,
1196
+ messages: modelMessages,
1197
+ toolContext: resolvedContext
830
1198
  });
831
1199
  }
1200
+ await ((_a2 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a2.call(telemetryDispatcher, {
1201
+ toolCall: toolCallEvent,
1202
+ stepNumber: currentStepNumber,
1203
+ messages: modelMessages,
1204
+ toolContext: resolvedContext
1205
+ }));
832
1206
  const startTime = Date.now();
833
1207
  let result;
834
1208
  try {
835
- result = await executeTool(toolCall, tools, messages2, context);
1209
+ const execute = () => executeTool(toolCall, tools, messages2, resolvedContext, download);
1210
+ result = telemetryDispatcher.executeTool != null ? await telemetryDispatcher.executeTool({
1211
+ callId: "workflow-agent",
1212
+ toolCallId: toolCall.toolCallId,
1213
+ execute
1214
+ }) : await execute();
836
1215
  } catch (err) {
837
1216
  const durationMs2 = Date.now() - startTime;
838
- if (mergedOnToolCallFinish) {
839
- await mergedOnToolCallFinish({
1217
+ if (mergedOnToolExecutionEnd) {
1218
+ await mergedOnToolExecutionEnd({
840
1219
  toolCall: toolCallEvent,
841
1220
  stepNumber: currentStepNumber,
842
1221
  durationMs: durationMs2,
1222
+ messages: modelMessages,
1223
+ toolContext: resolvedContext,
843
1224
  success: false,
844
1225
  error: err
845
1226
  });
846
1227
  }
1228
+ await ((_b2 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _b2.call(telemetryDispatcher, {
1229
+ toolCall: toolCallEvent,
1230
+ stepNumber: currentStepNumber,
1231
+ durationMs: durationMs2,
1232
+ messages: modelMessages,
1233
+ toolContext: resolvedContext,
1234
+ success: false,
1235
+ error: err
1236
+ }));
847
1237
  throw err;
848
1238
  }
849
1239
  const durationMs = Date.now() - startTime;
850
- if (mergedOnToolCallFinish) {
851
- const isError = result.output && "type" in result.output && (result.output.type === "error-text" || result.output.type === "error-json");
852
- if (isError) {
853
- await mergedOnToolCallFinish({
1240
+ if (mergedOnToolExecutionEnd) {
1241
+ if (result.isError) {
1242
+ await mergedOnToolExecutionEnd({
854
1243
  toolCall: toolCallEvent,
855
1244
  stepNumber: currentStepNumber,
856
1245
  durationMs,
1246
+ messages: modelMessages,
1247
+ toolContext: resolvedContext,
857
1248
  success: false,
858
- error: "value" in result.output ? result.output.value : void 0
1249
+ error: result.rawOutput
859
1250
  });
860
1251
  } else {
861
- await mergedOnToolCallFinish({
1252
+ await mergedOnToolExecutionEnd({
862
1253
  toolCall: toolCallEvent,
863
1254
  stepNumber: currentStepNumber,
864
1255
  durationMs,
1256
+ messages: modelMessages,
1257
+ toolContext: resolvedContext,
865
1258
  success: true,
866
- output: result.output && "value" in result.output ? result.output.value : void 0
1259
+ output: result.rawOutput
867
1260
  });
868
1261
  }
869
1262
  }
1263
+ if (result.isError) {
1264
+ await ((_c2 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _c2.call(telemetryDispatcher, {
1265
+ toolCall: toolCallEvent,
1266
+ stepNumber: currentStepNumber,
1267
+ durationMs,
1268
+ messages: modelMessages,
1269
+ toolContext: resolvedContext,
1270
+ success: false,
1271
+ error: result.rawOutput
1272
+ }));
1273
+ } else {
1274
+ await ((_d2 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _d2.call(telemetryDispatcher, {
1275
+ toolCall: toolCallEvent,
1276
+ stepNumber: currentStepNumber,
1277
+ durationMs,
1278
+ messages: modelMessages,
1279
+ toolContext: resolvedContext,
1280
+ success: true,
1281
+ output: result.rawOutput
1282
+ }));
1283
+ }
870
1284
  return result;
871
1285
  };
872
- if ((_i = mergedGenerationSettings.abortSignal) == null ? void 0 : _i.aborted) {
1286
+ const recordProviderExecutedToolTelemetry = async (toolCall, result, messages2, currentStepNumber) => {
1287
+ var _a2, _b2;
1288
+ const toolCallEvent = {
1289
+ type: "tool-call",
1290
+ toolCallId: toolCall.toolCallId,
1291
+ toolName: toolCall.toolName,
1292
+ input: toolCall.input
1293
+ };
1294
+ const modelMessages = getToolCallbackMessages(messages2);
1295
+ await ((_a2 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a2.call(telemetryDispatcher, {
1296
+ toolCall: toolCallEvent,
1297
+ stepNumber: currentStepNumber,
1298
+ messages: modelMessages,
1299
+ toolContext: void 0
1300
+ }));
1301
+ await ((_b2 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _b2.call(telemetryDispatcher, {
1302
+ toolCall: toolCallEvent,
1303
+ stepNumber: currentStepNumber,
1304
+ durationMs: 0,
1305
+ messages: modelMessages,
1306
+ toolContext: void 0,
1307
+ ...result.isError ? {
1308
+ success: false,
1309
+ error: result.rawOutput
1310
+ } : {
1311
+ success: true,
1312
+ output: result.rawOutput
1313
+ }
1314
+ }));
1315
+ };
1316
+ if ((_u = mergedGenerationSettings.abortSignal) == null ? void 0 : _u.aborted) {
873
1317
  if (options.onAbort) {
874
1318
  await options.onAbort({ steps });
875
1319
  }
@@ -886,19 +1330,19 @@ var WorkflowAgent = class {
886
1330
  tools: effectiveTools,
887
1331
  writable: options.writable,
888
1332
  prompt: modelPrompt,
889
- stopConditions: (_j = options.stopWhen) != null ? _j : this.stopWhen,
890
- maxSteps: options.maxSteps,
891
- onStepFinish: mergedOnStepFinish,
1333
+ stopConditions: (_v = options.stopWhen) != null ? _v : this.stopWhen,
1334
+ onStepEnd: mergedOnStepEnd,
892
1335
  onStepStart: mergedOnStepStart,
893
1336
  onError: options.onError,
894
- prepareStep: (_k = options.prepareStep) != null ? _k : this.prepareStep,
1337
+ prepareStep: (_w = options.prepareStep) != null ? _w : this.prepareStep,
895
1338
  generationSettings: mergedGenerationSettings,
896
1339
  toolChoice: effectiveToolChoice,
897
- experimental_context: experimentalContext,
898
- experimental_telemetry: effectiveTelemetry,
899
- includeRawChunks: (_l = options.includeRawChunks) != null ? _l : false,
900
- repairToolCall: (_m = options.experimental_repairToolCall) != null ? _m : this.experimentalRepairToolCall,
901
- responseFormat: await ((_o = (_n = options.output) != null ? _n : this.output) == null ? void 0 : _o.responseFormat)
1340
+ runtimeContext,
1341
+ toolsContext,
1342
+ telemetry: effectiveTelemetry,
1343
+ includeRawChunks: (_x = options.includeRawChunks) != null ? _x : false,
1344
+ repairToolCall: (_y = options.experimental_repairToolCall) != null ? _y : this.experimentalRepairToolCall,
1345
+ responseFormat: await ((_A = (_z = options.output) != null ? _z : this.output) == null ? void 0 : _A.responseFormat)
902
1346
  });
903
1347
  let finalMessages;
904
1348
  let encounteredError;
@@ -906,7 +1350,7 @@ var WorkflowAgent = class {
906
1350
  try {
907
1351
  let result = await iterator.next();
908
1352
  while (!result.done) {
909
- if ((_p = mergedGenerationSettings.abortSignal) == null ? void 0 : _p.aborted) {
1353
+ if ((_B = mergedGenerationSettings.abortSignal) == null ? void 0 : _B.aborted) {
910
1354
  wasAborted = true;
911
1355
  if (options.onAbort) {
912
1356
  await options.onAbort({ steps });
@@ -917,21 +1361,29 @@ var WorkflowAgent = class {
917
1361
  toolCalls,
918
1362
  messages: iterMessages,
919
1363
  step,
920
- context,
1364
+ runtimeContext: yieldedRuntimeContext,
1365
+ toolsContext: yieldedToolsContext,
921
1366
  providerExecutedToolResults
922
1367
  } = result.value;
923
1368
  const currentStepNumber = steps.length;
924
1369
  if (step) {
925
1370
  steps.push(step);
926
1371
  }
927
- if (context !== void 0) {
928
- experimentalContext = context;
1372
+ if (yieldedRuntimeContext !== void 0) {
1373
+ runtimeContext = yieldedRuntimeContext;
1374
+ }
1375
+ if (yieldedToolsContext !== void 0) {
1376
+ toolsContext = yieldedToolsContext;
929
1377
  }
930
1378
  if (toolCalls.length > 0) {
931
- const nonProviderToolCalls = toolCalls.filter(
1379
+ const invalidToolCalls = toolCalls.filter((tc) => tc.invalid === true);
1380
+ const validToolCalls = toolCalls.filter((tc) => tc.invalid !== true);
1381
+ const nonProviderToolCalls = validToolCalls.filter(
932
1382
  (tc) => !tc.providerExecuted
933
1383
  );
934
- const providerToolCalls = toolCalls.filter((tc) => tc.providerExecuted);
1384
+ const providerToolCalls = validToolCalls.filter(
1385
+ (tc) => tc.providerExecuted
1386
+ );
935
1387
  const approvalNeeded = await Promise.all(
936
1388
  nonProviderToolCalls.map(async (tc) => {
937
1389
  const tool2 = effectiveTools[tc.toolName];
@@ -939,10 +1391,15 @@ var WorkflowAgent = class {
939
1391
  if (tool2.needsApproval == null) return false;
940
1392
  if (typeof tool2.needsApproval === "boolean")
941
1393
  return tool2.needsApproval;
1394
+ const resolvedContext = await resolveToolContext({
1395
+ toolName: tc.toolName,
1396
+ tool: tool2,
1397
+ toolsContext
1398
+ });
942
1399
  return tool2.needsApproval(tc.input, {
943
1400
  toolCallId: tc.toolCallId,
944
1401
  messages: iterMessages,
945
- context: experimentalContext
1402
+ context: resolvedContext
946
1403
  });
947
1404
  })
948
1405
  );
@@ -961,32 +1418,56 @@ var WorkflowAgent = class {
961
1418
  toolCall,
962
1419
  effectiveTools,
963
1420
  iterMessages,
964
- experimentalContext,
1421
+ toolsContext,
965
1422
  currentStepNumber
966
1423
  )
967
1424
  )
968
1425
  );
969
- const providerResults = providerToolCalls.map(
970
- (toolCall) => resolveProviderToolResult(
971
- toolCall,
972
- providerExecutedToolResults
1426
+ const providerResults = await Promise.all(
1427
+ providerToolCalls.map(
1428
+ (toolCall) => resolveProviderToolResult(
1429
+ toolCall,
1430
+ providerExecutedToolResults,
1431
+ effectiveTools,
1432
+ download
1433
+ )
973
1434
  )
974
1435
  );
975
- const resolvedResults = [...executableResults, ...providerResults];
1436
+ await Promise.all(
1437
+ providerToolCalls.map(
1438
+ (toolCall, index) => recordProviderExecutedToolTelemetry(
1439
+ toolCall,
1440
+ providerResults[index],
1441
+ iterMessages,
1442
+ currentStepNumber
1443
+ )
1444
+ )
1445
+ );
1446
+ const continuationInvalidResults = invalidToolCalls.map(
1447
+ createInvalidToolResult
1448
+ );
1449
+ const resolvedResults = [
1450
+ ...executableResults.map((result2) => result2.modelResult),
1451
+ ...providerResults.map((result2) => result2.modelResult),
1452
+ ...continuationInvalidResults
1453
+ ];
1454
+ const executedResults = [...executableResults, ...providerResults];
976
1455
  const allToolCalls = toolCalls.map((tc) => ({
977
1456
  type: "tool-call",
978
1457
  toolCallId: tc.toolCallId,
979
1458
  toolName: tc.toolName,
980
1459
  input: tc.input
981
1460
  }));
982
- const allToolResults = resolvedResults.map((r) => {
1461
+ const allToolResults = executedResults.map((r) => {
983
1462
  var _a2;
984
1463
  return {
985
1464
  type: "tool-result",
986
- toolCallId: r.toolCallId,
987
- toolName: r.toolName,
988
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
989
- output: "value" in r.output ? r.output.value : void 0
1465
+ toolCallId: r.modelResult.toolCallId,
1466
+ toolName: r.modelResult.toolName,
1467
+ input: (_a2 = toolCalls.find(
1468
+ (tc) => tc.toolCallId === r.modelResult.toolCallId
1469
+ )) == null ? void 0 : _a2.input,
1470
+ output: r.rawOutput
990
1471
  };
991
1472
  });
992
1473
  if (resolvedResults.length > 0) {
@@ -996,18 +1477,32 @@ var WorkflowAgent = class {
996
1477
  });
997
1478
  }
998
1479
  const messages2 = iterMessages;
999
- if (mergedOnFinish && !wasAborted) {
1480
+ if (mergedOnEnd && !wasAborted) {
1000
1481
  const lastStep = steps[steps.length - 1];
1001
- await mergedOnFinish({
1482
+ const totalUsage = aggregateUsage(steps);
1483
+ await mergedOnEnd({
1002
1484
  steps,
1003
1485
  messages: messages2,
1004
- text: (_q = lastStep == null ? void 0 : lastStep.text) != null ? _q : "",
1005
- finishReason: (_r = lastStep == null ? void 0 : lastStep.finishReason) != null ? _r : "other",
1006
- totalUsage: aggregateUsage(steps),
1007
- experimental_context: experimentalContext,
1486
+ text: (_C = lastStep == null ? void 0 : lastStep.text) != null ? _C : "",
1487
+ finishReason: (_D = lastStep == null ? void 0 : lastStep.finishReason) != null ? _D : "other",
1488
+ usage: totalUsage,
1489
+ totalUsage,
1490
+ runtimeContext,
1491
+ toolsContext,
1008
1492
  output: void 0
1009
1493
  });
1010
1494
  }
1495
+ if (!wasAborted && steps.length > 0) {
1496
+ const telemetrySteps = steps.map(normalizeStepForTelemetry2);
1497
+ const lastStep = telemetrySteps[telemetrySteps.length - 1];
1498
+ const totalUsage = aggregateUsage(steps);
1499
+ await ((_E = telemetryDispatcher.onEnd) == null ? void 0 : _E.call(telemetryDispatcher, {
1500
+ ...lastStep,
1501
+ steps: telemetrySteps,
1502
+ usage: totalUsage,
1503
+ totalUsage
1504
+ }));
1505
+ }
1011
1506
  if (options.writable) {
1012
1507
  const approvalToolCalls = pausedToolCalls.filter((_, i) => {
1013
1508
  const tcIndex = nonProviderToolCalls.indexOf(
@@ -1026,8 +1521,8 @@ var WorkflowAgent = class {
1026
1521
  }
1027
1522
  }
1028
1523
  if (options.writable) {
1029
- const sendFinish = (_s = options.sendFinish) != null ? _s : true;
1030
- const preventClose = (_t = options.preventClose) != null ? _t : false;
1524
+ const sendFinish = (_F = options.sendFinish) != null ? _F : true;
1525
+ const preventClose = (_G = options.preventClose) != null ? _G : false;
1031
1526
  if (sendFinish || !preventClose) {
1032
1527
  await closeStream(options.writable, preventClose, sendFinish);
1033
1528
  }
@@ -1046,40 +1541,68 @@ var WorkflowAgent = class {
1046
1541
  toolCall,
1047
1542
  effectiveTools,
1048
1543
  iterMessages,
1049
- experimentalContext,
1544
+ toolsContext,
1050
1545
  currentStepNumber
1051
1546
  )
1052
1547
  )
1053
1548
  );
1054
- const providerToolResults = providerToolCalls.map(
1055
- (toolCall) => resolveProviderToolResult(toolCall, providerExecutedToolResults)
1549
+ const providerToolResults = await Promise.all(
1550
+ providerToolCalls.map(
1551
+ (toolCall) => resolveProviderToolResult(
1552
+ toolCall,
1553
+ providerExecutedToolResults,
1554
+ effectiveTools,
1555
+ download
1556
+ )
1557
+ )
1558
+ );
1559
+ await Promise.all(
1560
+ providerToolCalls.map(
1561
+ (toolCall, index) => recordProviderExecutedToolTelemetry(
1562
+ toolCall,
1563
+ providerToolResults[index],
1564
+ iterMessages,
1565
+ currentStepNumber
1566
+ )
1567
+ )
1056
1568
  );
1057
- const toolResults = toolCalls.map((tc) => {
1569
+ const continuationInvalidToolResults = invalidToolCalls.map(
1570
+ createInvalidToolResult
1571
+ );
1572
+ const executedToolResults = toolCalls.flatMap((tc) => {
1058
1573
  const clientResult = clientToolResults.find(
1059
- (r) => r.toolCallId === tc.toolCallId
1574
+ (r) => r.modelResult.toolCallId === tc.toolCallId
1060
1575
  );
1061
- if (clientResult) return clientResult;
1576
+ if (clientResult) return [clientResult];
1062
1577
  const providerResult = providerToolResults.find(
1578
+ (r) => r.modelResult.toolCallId === tc.toolCallId
1579
+ );
1580
+ if (providerResult) return [providerResult];
1581
+ return [];
1582
+ });
1583
+ const continuationToolResults = toolCalls.flatMap((tc) => {
1584
+ const invalidResult = continuationInvalidToolResults.find(
1063
1585
  (r) => r.toolCallId === tc.toolCallId
1064
1586
  );
1065
- if (providerResult) return providerResult;
1066
- return {
1067
- type: "tool-result",
1068
- toolCallId: tc.toolCallId,
1069
- toolName: tc.toolName,
1070
- output: { type: "text", value: "" }
1071
- };
1587
+ if (invalidResult) return [invalidResult];
1588
+ const executedResult = executedToolResults.find(
1589
+ (r) => r.modelResult.toolCallId === tc.toolCallId
1590
+ );
1591
+ if (executedResult) return [executedResult.modelResult];
1592
+ return [];
1072
1593
  });
1073
1594
  if (options.writable) {
1074
1595
  await writeToolResultsWithStepBoundary(
1075
1596
  options.writable,
1076
- toolResults.map((r) => {
1597
+ executedToolResults.map((r) => {
1077
1598
  var _a2;
1078
1599
  return {
1079
- toolCallId: r.toolCallId,
1080
- toolName: r.toolName,
1081
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
1082
- output: "value" in r.output ? r.output.value : void 0
1600
+ toolCallId: r.modelResult.toolCallId,
1601
+ toolName: r.modelResult.toolName,
1602
+ input: (_a2 = toolCalls.find(
1603
+ (tc) => tc.toolCallId === r.modelResult.toolCallId
1604
+ )) == null ? void 0 : _a2.input,
1605
+ output: r.rawOutput
1083
1606
  };
1084
1607
  })
1085
1608
  );
@@ -1090,17 +1613,19 @@ var WorkflowAgent = class {
1090
1613
  toolName: tc.toolName,
1091
1614
  input: tc.input
1092
1615
  }));
1093
- lastStepToolResults = toolResults.map((r) => {
1616
+ lastStepToolResults = executedToolResults.map((r) => {
1094
1617
  var _a2;
1095
1618
  return {
1096
1619
  type: "tool-result",
1097
- toolCallId: r.toolCallId,
1098
- toolName: r.toolName,
1099
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
1100
- output: "value" in r.output ? r.output.value : void 0
1620
+ toolCallId: r.modelResult.toolCallId,
1621
+ toolName: r.modelResult.toolName,
1622
+ input: (_a2 = toolCalls.find(
1623
+ (tc) => tc.toolCallId === r.modelResult.toolCallId
1624
+ )) == null ? void 0 : _a2.input,
1625
+ output: r.rawOutput
1101
1626
  };
1102
1627
  });
1103
- result = await iterator.next(toolResults);
1628
+ result = await iterator.next(continuationToolResults);
1104
1629
  } else {
1105
1630
  lastStepToolCalls = [];
1106
1631
  lastStepToolResults = [];
@@ -1120,9 +1645,10 @@ var WorkflowAgent = class {
1120
1645
  } else if (options.onError) {
1121
1646
  await options.onError({ error });
1122
1647
  }
1648
+ await ((_H = telemetryDispatcher.onError) == null ? void 0 : _H.call(telemetryDispatcher, error));
1123
1649
  }
1124
1650
  const messages = finalMessages != null ? finalMessages : prompt.messages;
1125
- const effectiveOutput = (_u = options.output) != null ? _u : this.output;
1651
+ const effectiveOutput = (_I = options.output) != null ? _I : this.output;
1126
1652
  let experimentalOutput = void 0;
1127
1653
  if (effectiveOutput && steps.length > 0) {
1128
1654
  const lastStep = steps[steps.length - 1];
@@ -1144,22 +1670,36 @@ var WorkflowAgent = class {
1144
1670
  }
1145
1671
  }
1146
1672
  }
1147
- if (mergedOnFinish && !wasAborted) {
1673
+ if (mergedOnEnd && !wasAborted) {
1148
1674
  const lastStep = steps[steps.length - 1];
1149
- await mergedOnFinish({
1675
+ const totalUsage = aggregateUsage(steps);
1676
+ await mergedOnEnd({
1150
1677
  steps,
1151
1678
  messages,
1152
- text: (_v = lastStep == null ? void 0 : lastStep.text) != null ? _v : "",
1153
- finishReason: (_w = lastStep == null ? void 0 : lastStep.finishReason) != null ? _w : "other",
1154
- totalUsage: aggregateUsage(steps),
1155
- experimental_context: experimentalContext,
1679
+ text: (_J = lastStep == null ? void 0 : lastStep.text) != null ? _J : "",
1680
+ finishReason: (_K = lastStep == null ? void 0 : lastStep.finishReason) != null ? _K : "other",
1681
+ usage: totalUsage,
1682
+ totalUsage,
1683
+ runtimeContext,
1684
+ toolsContext,
1156
1685
  output: experimentalOutput
1157
1686
  });
1158
1687
  }
1688
+ if (!wasAborted && steps.length > 0) {
1689
+ const telemetrySteps = steps.map(normalizeStepForTelemetry2);
1690
+ const lastStep = telemetrySteps[telemetrySteps.length - 1];
1691
+ const totalUsage = aggregateUsage(steps);
1692
+ await ((_L = telemetryDispatcher.onEnd) == null ? void 0 : _L.call(telemetryDispatcher, {
1693
+ ...lastStep,
1694
+ steps: telemetrySteps,
1695
+ usage: totalUsage,
1696
+ totalUsage
1697
+ }));
1698
+ }
1159
1699
  if (encounteredError) {
1160
1700
  if (options.writable) {
1161
- const sendFinish = (_x = options.sendFinish) != null ? _x : true;
1162
- const preventClose = (_y = options.preventClose) != null ? _y : false;
1701
+ const sendFinish = (_M = options.sendFinish) != null ? _M : true;
1702
+ const preventClose = (_N = options.preventClose) != null ? _N : false;
1163
1703
  if (sendFinish || !preventClose) {
1164
1704
  await closeStream(options.writable, preventClose, sendFinish);
1165
1705
  }
@@ -1167,8 +1707,8 @@ var WorkflowAgent = class {
1167
1707
  throw encounteredError;
1168
1708
  }
1169
1709
  if (options.writable) {
1170
- const sendFinish = (_z = options.sendFinish) != null ? _z : true;
1171
- const preventClose = (_A = options.preventClose) != null ? _A : false;
1710
+ const sendFinish = (_O = options.sendFinish) != null ? _O : true;
1711
+ const preventClose = (_P = options.preventClose) != null ? _P : false;
1172
1712
  if (sendFinish || !preventClose) {
1173
1713
  await closeStream(options.writable, preventClose, sendFinish);
1174
1714
  }
@@ -1182,6 +1722,17 @@ var WorkflowAgent = class {
1182
1722
  };
1183
1723
  }
1184
1724
  };
1725
+ function getModelInfo2(model) {
1726
+ var _a;
1727
+ return typeof model === "string" ? { provider: (_a = model.split("/")[0]) != null ? _a : "gateway", modelId: model } : { provider: model.provider, modelId: model.modelId };
1728
+ }
1729
+ function normalizeStepForTelemetry2(step) {
1730
+ var _a;
1731
+ return {
1732
+ ...step,
1733
+ model: (_a = step.model) != null ? _a : { provider: "unknown", modelId: "unknown" }
1734
+ };
1735
+ }
1185
1736
  async function closeStream(writable, preventClose, sendFinish) {
1186
1737
  "use step";
1187
1738
  if (sendFinish) {
@@ -1255,6 +1806,22 @@ async function writeApprovalToolResults(writable, approvedResults, deniedResults
1255
1806
  writer.releaseLock();
1256
1807
  }
1257
1808
  }
1809
+ async function resolveToolContext({
1810
+ toolName,
1811
+ tool: tool2,
1812
+ toolsContext
1813
+ }) {
1814
+ const contextSchema = tool2.contextSchema;
1815
+ const entry = toolsContext == null ? void 0 : toolsContext[toolName];
1816
+ if (contextSchema == null) {
1817
+ return entry;
1818
+ }
1819
+ return await validateTypes({
1820
+ value: entry,
1821
+ schema: contextSchema,
1822
+ context: { field: "tool context", entityName: toolName }
1823
+ });
1824
+ }
1258
1825
  function aggregateUsage(steps) {
1259
1826
  var _a, _b, _c, _d;
1260
1827
  let inputTokens = 0;
@@ -1269,59 +1836,65 @@ function aggregateUsage(steps) {
1269
1836
  totalTokens: inputTokens + outputTokens
1270
1837
  };
1271
1838
  }
1272
- function filterTools(tools, activeTools) {
1273
- const filtered = {};
1274
- for (const toolName of activeTools) {
1275
- if (toolName in tools) {
1276
- filtered[toolName] = tools[toolName];
1277
- }
1278
- }
1279
- return filtered;
1280
- }
1281
- function getErrorMessage(error) {
1282
- if (error == null) {
1283
- return "unknown error";
1284
- }
1285
- if (typeof error === "string") {
1286
- return error;
1287
- }
1288
- if (error instanceof Error) {
1289
- return error.message;
1290
- }
1291
- return JSON.stringify(error);
1292
- }
1293
- function resolveProviderToolResult(toolCall, providerExecutedToolResults) {
1839
+ async function resolveProviderToolResult(toolCall, providerExecutedToolResults, tools, download) {
1294
1840
  const streamResult = providerExecutedToolResults == null ? void 0 : providerExecutedToolResults.get(toolCall.toolCallId);
1295
1841
  if (!streamResult) {
1296
1842
  console.warn(
1297
1843
  `[WorkflowAgent] Provider-executed tool "${toolCall.toolName}" (${toolCall.toolCallId}) did not receive a result from the stream. This may indicate a provider issue.`
1298
1844
  );
1299
1845
  return {
1300
- type: "tool-result",
1301
- toolCallId: toolCall.toolCallId,
1302
- toolName: toolCall.toolName,
1303
- output: {
1304
- type: "text",
1305
- value: ""
1306
- }
1846
+ modelResult: {
1847
+ type: "tool-result",
1848
+ toolCallId: toolCall.toolCallId,
1849
+ toolName: toolCall.toolName,
1850
+ output: {
1851
+ type: "text",
1852
+ value: ""
1853
+ }
1854
+ },
1855
+ rawOutput: "",
1856
+ isError: false
1307
1857
  };
1308
1858
  }
1309
1859
  const result = streamResult.result;
1310
- const isString = typeof result === "string";
1860
+ const errorMode = streamResult.isError ? typeof result === "string" ? "text" : "json" : "none";
1861
+ return {
1862
+ modelResult: {
1863
+ type: "tool-result",
1864
+ toolCallId: toolCall.toolCallId,
1865
+ toolName: toolCall.toolName,
1866
+ output: await createLanguageModelToolResultOutput({
1867
+ toolCallId: toolCall.toolCallId,
1868
+ toolName: toolCall.toolName,
1869
+ input: toolCall.input,
1870
+ output: result,
1871
+ tool: tools == null ? void 0 : tools[toolCall.toolName],
1872
+ errorMode,
1873
+ supportedUrls: {},
1874
+ download
1875
+ })
1876
+ },
1877
+ rawOutput: result,
1878
+ isError: streamResult.isError === true
1879
+ };
1880
+ }
1881
+ function createInvalidToolResult(toolCall) {
1311
1882
  return {
1312
1883
  type: "tool-result",
1313
1884
  toolCallId: toolCall.toolCallId,
1314
1885
  toolName: toolCall.toolName,
1315
- output: isString ? streamResult.isError ? { type: "error-text", value: result } : { type: "text", value: result } : streamResult.isError ? {
1316
- type: "error-json",
1317
- value: result
1318
- } : {
1319
- type: "json",
1320
- value: result
1886
+ output: {
1887
+ type: "error-text",
1888
+ value: getErrorMessage(toolCall.error)
1321
1889
  }
1322
1890
  };
1323
1891
  }
1324
- async function executeTool(toolCall, tools, messages, experimentalContext) {
1892
+ function getToolCallbackMessages(messages) {
1893
+ var _a;
1894
+ const withoutAssistantToolCall = ((_a = messages.at(-1)) == null ? void 0 : _a.role) === "assistant" ? messages.slice(0, -1) : messages;
1895
+ return withoutAssistantToolCall;
1896
+ }
1897
+ async function executeTool(toolCall, tools, messages, context, download) {
1325
1898
  const tool2 = tools[toolCall.toolName];
1326
1899
  if (!tool2) throw new Error(`Tool "${toolCall.toolName}" not found`);
1327
1900
  if (typeof tool2.execute !== "function") {
@@ -1330,97 +1903,57 @@ async function executeTool(toolCall, tools, messages, experimentalContext) {
1330
1903
  );
1331
1904
  }
1332
1905
  const parsedInput = toolCall.input;
1906
+ let toolResult;
1333
1907
  try {
1334
1908
  const { execute } = tool2;
1335
- const toolResult = await execute(parsedInput, {
1909
+ toolResult = await execute(parsedInput, {
1336
1910
  toolCallId: toolCall.toolCallId,
1337
1911
  // Pass the conversation messages to the tool so it has context about the conversation
1338
1912
  messages,
1339
- // Pass context to the tool
1340
- context: experimentalContext
1913
+ // Pass per-tool context to the tool (resolved from `toolsContext`)
1914
+ context
1341
1915
  });
1342
- const output = typeof toolResult === "string" ? { type: "text", value: toolResult } : { type: "json", value: toolResult };
1343
- return {
1344
- type: "tool-result",
1345
- toolCallId: toolCall.toolCallId,
1346
- toolName: toolCall.toolName,
1347
- output
1348
- };
1349
1916
  } catch (error) {
1917
+ const errorMessage = getErrorMessage(error);
1350
1918
  return {
1351
- type: "tool-result",
1352
- toolCallId: toolCall.toolCallId,
1353
- toolName: toolCall.toolName,
1354
- output: {
1355
- type: "error-text",
1356
- value: getErrorMessage(error)
1357
- }
1919
+ modelResult: {
1920
+ type: "tool-result",
1921
+ toolCallId: toolCall.toolCallId,
1922
+ toolName: toolCall.toolName,
1923
+ output: await createLanguageModelToolResultOutput({
1924
+ toolCallId: toolCall.toolCallId,
1925
+ toolName: toolCall.toolName,
1926
+ input: parsedInput,
1927
+ output: errorMessage,
1928
+ tool: tool2,
1929
+ errorMode: "text",
1930
+ supportedUrls: {},
1931
+ download
1932
+ })
1933
+ },
1934
+ rawOutput: errorMessage,
1935
+ isError: true
1358
1936
  };
1359
1937
  }
1360
- }
1361
- function collectToolApprovalsFromMessages(messages) {
1362
- var _a;
1363
- const lastMessage = messages.at(-1);
1364
- if ((lastMessage == null ? void 0 : lastMessage.role) !== "tool") {
1365
- return { approvedToolApprovals: [], deniedToolApprovals: [] };
1366
- }
1367
- const toolCallsByToolCallId = {};
1368
- for (const message of messages) {
1369
- if (message.role === "assistant" && Array.isArray(message.content)) {
1370
- for (const part of message.content) {
1371
- if (part.type === "tool-call") {
1372
- toolCallsByToolCallId[part.toolCallId] = {
1373
- toolName: part.toolName,
1374
- input: (_a = part.input) != null ? _a : part.args
1375
- };
1376
- }
1377
- }
1378
- }
1379
- }
1380
- const approvalRequestsByApprovalId = {};
1381
- for (const message of messages) {
1382
- if (message.role === "assistant" && Array.isArray(message.content)) {
1383
- for (const part of message.content) {
1384
- if (part.type === "tool-approval-request") {
1385
- approvalRequestsByApprovalId[part.approvalId] = {
1386
- approvalId: part.approvalId,
1387
- toolCallId: part.toolCallId
1388
- };
1389
- }
1390
- }
1391
- }
1392
- }
1393
- const existingToolResults = /* @__PURE__ */ new Set();
1394
- for (const part of lastMessage.content) {
1395
- if (part.type === "tool-result") {
1396
- existingToolResults.add(part.toolCallId);
1397
- }
1398
- }
1399
- const approvedToolApprovals = [];
1400
- const deniedToolApprovals = [];
1401
- const approvalResponses = lastMessage.content.filter(
1402
- (part) => part.type === "tool-approval-response"
1403
- );
1404
- for (const response of approvalResponses) {
1405
- const approvalRequest = approvalRequestsByApprovalId[response.approvalId];
1406
- if (approvalRequest == null) continue;
1407
- if (existingToolResults.has(approvalRequest.toolCallId)) continue;
1408
- const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
1409
- if (toolCall == null) continue;
1410
- const approval = {
1411
- toolCallId: approvalRequest.toolCallId,
1938
+ return {
1939
+ modelResult: {
1940
+ type: "tool-result",
1941
+ toolCallId: toolCall.toolCallId,
1412
1942
  toolName: toolCall.toolName,
1413
- input: toolCall.input,
1414
- approvalId: response.approvalId,
1415
- reason: response.reason
1416
- };
1417
- if (response.approved) {
1418
- approvedToolApprovals.push(approval);
1419
- } else {
1420
- deniedToolApprovals.push(approval);
1421
- }
1422
- }
1423
- return { approvedToolApprovals, deniedToolApprovals };
1943
+ output: await createLanguageModelToolResultOutput({
1944
+ toolCallId: toolCall.toolCallId,
1945
+ toolName: toolCall.toolName,
1946
+ input: parsedInput,
1947
+ output: toolResult,
1948
+ tool: tool2,
1949
+ errorMode: "none",
1950
+ supportedUrls: {},
1951
+ download
1952
+ })
1953
+ },
1954
+ rawOutput: toolResult,
1955
+ isError: false
1956
+ };
1424
1957
  }
1425
1958
 
1426
1959
  // src/to-ui-message-chunk.ts
@@ -1555,16 +2088,16 @@ function toUIMessageChunk(part) {
1555
2088
  case "raw":
1556
2089
  return void 0;
1557
2090
  default: {
1558
- const p = part;
1559
- if (p.type === "tool-approval-request") {
2091
+ const passthroughPart = part;
2092
+ if (passthroughPart.type === "tool-approval-request") {
1560
2093
  return {
1561
2094
  type: "tool-approval-request",
1562
- approvalId: p.approvalId,
1563
- toolCallId: p.toolCallId
2095
+ approvalId: passthroughPart.approvalId,
2096
+ toolCallId: passthroughPart.toolCallId
1564
2097
  };
1565
2098
  }
1566
- if (p.type === "finish-step" || p.type === "start-step" || p.type === "tool-output-denied") {
1567
- return p;
2099
+ if (passthroughPart.type === "finish-step" || passthroughPart.type === "start-step" || passthroughPart.type === "tool-output-denied") {
2100
+ return passthroughPart;
1568
2101
  }
1569
2102
  return void 0;
1570
2103
  }
@@ -1663,7 +2196,7 @@ var WorkflowChatTransport = class {
1663
2196
  messageId
1664
2197
  }) : void 0;
1665
2198
  const url = (_a = requestConfig == null ? void 0 : requestConfig.api) != null ? _a : this.api;
1666
- const res = await this.fetch(url, {
2199
+ const response = await this.fetch(url, {
1667
2200
  method: "POST",
1668
2201
  body: JSON.stringify(
1669
2202
  (_b = requestConfig == null ? void 0 : requestConfig.body) != null ? _b : { messages, ...options.body }
@@ -1672,21 +2205,21 @@ var WorkflowChatTransport = class {
1672
2205
  credentials: requestConfig == null ? void 0 : requestConfig.credentials,
1673
2206
  signal: abortSignal
1674
2207
  });
1675
- if (!res.ok || !res.body) {
2208
+ if (!response.ok || !response.body) {
1676
2209
  throw new Error(
1677
- `Failed to fetch chat: ${res.status} ${await res.text()}`
2210
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
1678
2211
  );
1679
2212
  }
1680
- const workflowRunId = res.headers.get("x-workflow-run-id");
2213
+ const workflowRunId = response.headers.get("x-workflow-run-id");
1681
2214
  if (!workflowRunId) {
1682
2215
  throw new Error(
1683
2216
  'Workflow run ID not found in "x-workflow-run-id" response header'
1684
2217
  );
1685
2218
  }
1686
- await ((_c = this.onChatSendMessage) == null ? void 0 : _c.call(this, res, options));
2219
+ await ((_c = this.onChatSendMessage) == null ? void 0 : _c.call(this, response, options));
1687
2220
  try {
1688
2221
  const chunkStream = parseJsonEventStream({
1689
- stream: res.body,
2222
+ stream: response.body,
1690
2223
  schema: uiMessageChunkSchema
1691
2224
  });
1692
2225
  for await (const chunk of createAsyncIterableStream(chunkStream)) {
@@ -1721,8 +2254,8 @@ var WorkflowChatTransport = class {
1721
2254
  * @throws Error if the reconnection request fails or returns a non-OK status
1722
2255
  */
1723
2256
  async reconnectToStream(options) {
1724
- const it = this.reconnectToStreamIterator(options);
1725
- return convertAsyncIteratorToReadableStream(it);
2257
+ const reconnectIterator = this.reconnectToStreamIterator(options);
2258
+ return convertAsyncIteratorToReadableStream(reconnectIterator);
1726
2259
  }
1727
2260
  async *reconnectToStreamIterator(options, workflowRunId, initialChunkIndex = 0) {
1728
2261
  var _a, _b;
@@ -1745,20 +2278,22 @@ var WorkflowChatTransport = class {
1745
2278
  while (!gotFinish) {
1746
2279
  const startIndex = useExplicitStartIndex ? explicitStartIndex : replayFromStart ? 0 : chunkIndex;
1747
2280
  const url = `${baseUrl}?startIndex=${startIndex}`;
1748
- const res = await this.fetch(url, {
2281
+ const response = await this.fetch(url, {
1749
2282
  headers: requestConfig == null ? void 0 : requestConfig.headers,
1750
2283
  credentials: requestConfig == null ? void 0 : requestConfig.credentials,
1751
2284
  signal: options.abortSignal
1752
2285
  });
1753
- if (!res.ok || !res.body) {
2286
+ if (!response.ok || !response.body) {
1754
2287
  throw new Error(
1755
- `Failed to fetch chat: ${res.status} ${await res.text()}`
2288
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
1756
2289
  );
1757
2290
  }
1758
2291
  if (useExplicitStartIndex && explicitStartIndex > 0) {
1759
2292
  chunkIndex = explicitStartIndex;
1760
2293
  } else if (useExplicitStartIndex && explicitStartIndex < 0) {
1761
- const tailIndexHeader = res.headers.get("x-workflow-stream-tail-index");
2294
+ const tailIndexHeader = response.headers.get(
2295
+ "x-workflow-stream-tail-index"
2296
+ );
1762
2297
  const tailIndex = tailIndexHeader !== null ? parseInt(tailIndexHeader, 10) : NaN;
1763
2298
  if (!Number.isNaN(tailIndex)) {
1764
2299
  chunkIndex = Math.max(0, tailIndex + 1 + explicitStartIndex);
@@ -1772,7 +2307,7 @@ var WorkflowChatTransport = class {
1772
2307
  useExplicitStartIndex = false;
1773
2308
  try {
1774
2309
  const chunkStream = parseJsonEventStream({
1775
- stream: res.body,
2310
+ stream: response.body,
1776
2311
  schema: uiMessageChunkSchema
1777
2312
  });
1778
2313
  for await (const chunk of createAsyncIterableStream(chunkStream)) {