@ai-sdk/workflow 1.0.0-beta.1 → 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,19 +143,8 @@ 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;
80
- let model;
81
- if (typeof modelInit === "string") {
82
- model = gateway.languageModel(modelInit);
83
- } else if (typeof modelInit === "function") {
84
- model = await modelInit();
85
- } else if (typeof modelInit === "object" && modelInit !== null && "modelId" in modelInit) {
86
- model = modelInit;
87
- } else {
88
- throw new Error(
89
- 'Invalid "model initialization" argument. Must be a string, a LanguageModel instance, or a function that returns a LanguageModel instance.'
90
- );
91
- }
146
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
147
+ const model = typeof modelInit === "string" ? gateway.languageModel(modelInit) : modelInit;
92
148
  const tools = serializedTools ? resolveSerializableTools(serializedTools) : void 0;
93
149
  const { stream: modelStream } = await streamModelCall({
94
150
  model,
@@ -96,6 +152,7 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
96
152
  // pre-converted LanguageModelV4Prompt. standardizePrompt inside
97
153
  // streamModelCall handles both formats.
98
154
  messages: conversationPrompt,
155
+ allowSystemInMessages: true,
99
156
  tools,
100
157
  toolChoice: options == null ? void 0 : options.toolChoice,
101
158
  includeRawChunks: options == null ? void 0 : options.includeRawChunks,
@@ -117,11 +174,15 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
117
174
  let finish;
118
175
  let text = "";
119
176
  const reasoningParts = [];
177
+ const chunks = [];
120
178
  let responseMetadata;
121
179
  let warnings;
122
180
  const writer = writable == null ? void 0 : writable.getWriter();
123
181
  try {
124
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
+ }
125
186
  switch (part.type) {
126
187
  case "text-delta":
127
188
  text += part.text;
@@ -191,14 +252,15 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
191
252
  const reasoningText = reasoningParts.map((r) => r.text).join("") || void 0;
192
253
  const step = {
193
254
  callId: "workflow-agent",
194
- stepNumber: 0,
255
+ stepNumber: (_a = options == null ? void 0 : options.stepNumber) != null ? _a : 0,
195
256
  model: {
196
- provider: (_b = (_a = responseMetadata == null ? void 0 : responseMetadata.modelId) == null ? void 0 : _a.split(":")[0]) != null ? _b : "unknown",
197
- 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"
198
259
  },
199
260
  functionId: void 0,
200
261
  metadata: void 0,
201
- 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 : {},
202
264
  content: [
203
265
  ...text ? [{ type: "text", text }] : [],
204
266
  ...toolCalls.filter((tc) => !tc.invalid).map((tc) => ({
@@ -235,9 +297,9 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
235
297
  toolResults: [],
236
298
  staticToolResults: [],
237
299
  dynamicToolResults: [],
238
- finishReason: (_d = finish == null ? void 0 : finish.finishReason) != null ? _d : "other",
300
+ finishReason: (_g = finish == null ? void 0 : finish.finishReason) != null ? _g : "other",
239
301
  rawFinishReason: finish == null ? void 0 : finish.rawFinishReason,
240
- usage: (_e = finish == null ? void 0 : finish.usage) != null ? _e : {
302
+ usage: (_h = finish == null ? void 0 : finish.usage) != null ? _h : {
241
303
  inputTokens: 0,
242
304
  inputTokenDetails: {
243
305
  noCacheTokens: void 0,
@@ -251,20 +313,35 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
251
313
  },
252
314
  totalTokens: 0
253
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
+ },
254
326
  warnings,
255
- request: { body: "" },
327
+ request: {
328
+ body: "",
329
+ messages: []
330
+ // TODO implement step request messages
331
+ },
256
332
  response: {
257
- id: (_f = responseMetadata == null ? void 0 : responseMetadata.id) != null ? _f : "unknown",
258
- timestamp: (_g = responseMetadata == null ? void 0 : responseMetadata.timestamp) != null ? _g : /* @__PURE__ */ new Date(),
259
- 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",
260
336
  messages: []
261
337
  },
262
- providerMetadata: (_i = finish == null ? void 0 : finish.providerMetadata) != null ? _i : {}
338
+ providerMetadata: (_l = finish == null ? void 0 : finish.providerMetadata) != null ? _l : {}
263
339
  };
264
340
  return {
265
341
  toolCalls,
266
342
  finish,
267
343
  step,
344
+ chunks,
268
345
  providerExecutedToolResults
269
346
  };
270
347
  }
@@ -276,25 +353,27 @@ async function* streamTextIterator({
276
353
  writable,
277
354
  model,
278
355
  stopConditions,
279
- maxSteps,
356
+ onStepEnd,
280
357
  onStepFinish,
281
358
  onStepStart,
282
359
  onError,
283
360
  prepareStep,
284
361
  generationSettings,
285
362
  toolChoice,
286
- experimental_context,
287
- experimental_telemetry,
363
+ runtimeContext,
364
+ toolsContext,
365
+ telemetry,
288
366
  includeRawChunks = false,
289
367
  repairToolCall,
290
368
  responseFormat
291
369
  }) {
292
- var _a;
370
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
293
371
  let conversationPrompt = [...prompt];
294
372
  let currentModel = model;
295
373
  let currentGenerationSettings = generationSettings != null ? generationSettings : {};
296
374
  let currentToolChoice = toolChoice;
297
- let currentContext = experimental_context;
375
+ let currentRuntimeContext = runtimeContext != null ? runtimeContext : {};
376
+ let currentToolsContext = toolsContext != null ? toolsContext : {};
298
377
  let currentActiveTools;
299
378
  const steps = [];
300
379
  let done = false;
@@ -302,11 +381,12 @@ async function* streamTextIterator({
302
381
  let stepNumber = 0;
303
382
  let lastStep;
304
383
  let lastStepWasToolCalls = false;
305
- 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
+ });
306
389
  while (!done) {
307
- if (stepNumber >= effectiveMaxSteps) {
308
- break;
309
- }
310
390
  if ((_a = currentGenerationSettings.abortSignal) == null ? void 0 : _a.aborted) {
311
391
  break;
312
392
  }
@@ -316,15 +396,16 @@ async function* streamTextIterator({
316
396
  stepNumber,
317
397
  steps,
318
398
  messages: conversationPrompt,
319
- experimental_context: currentContext
399
+ runtimeContext: currentRuntimeContext,
400
+ toolsContext: currentToolsContext
320
401
  });
321
- if (prepareResult.model !== void 0) {
402
+ if ((prepareResult == null ? void 0 : prepareResult.model) !== void 0) {
322
403
  currentModel = prepareResult.model;
323
404
  }
324
- if (prepareResult.messages !== void 0) {
405
+ if ((prepareResult == null ? void 0 : prepareResult.messages) !== void 0) {
325
406
  conversationPrompt = [...prepareResult.messages];
326
407
  }
327
- if (prepareResult.system !== void 0) {
408
+ if ((prepareResult == null ? void 0 : prepareResult.system) !== void 0) {
328
409
  if (conversationPrompt.length > 0 && conversationPrompt[0].role === "system") {
329
410
  conversationPrompt[0] = {
330
411
  role: "system",
@@ -337,79 +418,82 @@ async function* streamTextIterator({
337
418
  });
338
419
  }
339
420
  }
340
- if (prepareResult.experimental_context !== void 0) {
341
- 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;
342
426
  }
343
- if (prepareResult.activeTools !== void 0) {
427
+ if ((prepareResult == null ? void 0 : prepareResult.activeTools) !== void 0) {
344
428
  currentActiveTools = prepareResult.activeTools;
345
429
  }
346
- if (prepareResult.maxOutputTokens !== void 0) {
430
+ if ((prepareResult == null ? void 0 : prepareResult.maxOutputTokens) !== void 0) {
347
431
  currentGenerationSettings = {
348
432
  ...currentGenerationSettings,
349
433
  maxOutputTokens: prepareResult.maxOutputTokens
350
434
  };
351
435
  }
352
- if (prepareResult.temperature !== void 0) {
436
+ if ((prepareResult == null ? void 0 : prepareResult.temperature) !== void 0) {
353
437
  currentGenerationSettings = {
354
438
  ...currentGenerationSettings,
355
439
  temperature: prepareResult.temperature
356
440
  };
357
441
  }
358
- if (prepareResult.topP !== void 0) {
442
+ if ((prepareResult == null ? void 0 : prepareResult.topP) !== void 0) {
359
443
  currentGenerationSettings = {
360
444
  ...currentGenerationSettings,
361
445
  topP: prepareResult.topP
362
446
  };
363
447
  }
364
- if (prepareResult.topK !== void 0) {
448
+ if ((prepareResult == null ? void 0 : prepareResult.topK) !== void 0) {
365
449
  currentGenerationSettings = {
366
450
  ...currentGenerationSettings,
367
451
  topK: prepareResult.topK
368
452
  };
369
453
  }
370
- if (prepareResult.presencePenalty !== void 0) {
454
+ if ((prepareResult == null ? void 0 : prepareResult.presencePenalty) !== void 0) {
371
455
  currentGenerationSettings = {
372
456
  ...currentGenerationSettings,
373
457
  presencePenalty: prepareResult.presencePenalty
374
458
  };
375
459
  }
376
- if (prepareResult.frequencyPenalty !== void 0) {
460
+ if ((prepareResult == null ? void 0 : prepareResult.frequencyPenalty) !== void 0) {
377
461
  currentGenerationSettings = {
378
462
  ...currentGenerationSettings,
379
463
  frequencyPenalty: prepareResult.frequencyPenalty
380
464
  };
381
465
  }
382
- if (prepareResult.stopSequences !== void 0) {
466
+ if ((prepareResult == null ? void 0 : prepareResult.stopSequences) !== void 0) {
383
467
  currentGenerationSettings = {
384
468
  ...currentGenerationSettings,
385
469
  stopSequences: prepareResult.stopSequences
386
470
  };
387
471
  }
388
- if (prepareResult.seed !== void 0) {
472
+ if ((prepareResult == null ? void 0 : prepareResult.seed) !== void 0) {
389
473
  currentGenerationSettings = {
390
474
  ...currentGenerationSettings,
391
475
  seed: prepareResult.seed
392
476
  };
393
477
  }
394
- if (prepareResult.maxRetries !== void 0) {
478
+ if ((prepareResult == null ? void 0 : prepareResult.maxRetries) !== void 0) {
395
479
  currentGenerationSettings = {
396
480
  ...currentGenerationSettings,
397
481
  maxRetries: prepareResult.maxRetries
398
482
  };
399
483
  }
400
- if (prepareResult.headers !== void 0) {
484
+ if ((prepareResult == null ? void 0 : prepareResult.headers) !== void 0) {
401
485
  currentGenerationSettings = {
402
486
  ...currentGenerationSettings,
403
487
  headers: prepareResult.headers
404
488
  };
405
489
  }
406
- if (prepareResult.providerOptions !== void 0) {
490
+ if ((prepareResult == null ? void 0 : prepareResult.providerOptions) !== void 0) {
407
491
  currentGenerationSettings = {
408
492
  ...currentGenerationSettings,
409
493
  providerOptions: prepareResult.providerOptions
410
494
  };
411
495
  }
412
- if (prepareResult.toolChoice !== void 0) {
496
+ if ((prepareResult == null ? void 0 : prepareResult.toolChoice) !== void 0) {
413
497
  currentToolChoice = prepareResult.toolChoice;
414
498
  }
415
499
  }
@@ -417,12 +501,54 @@ async function* streamTextIterator({
417
501
  await onStepStart({
418
502
  stepNumber,
419
503
  model: currentModel,
420
- messages: conversationPrompt
504
+ messages: conversationPrompt,
505
+ steps: [...steps],
506
+ runtimeContext: currentRuntimeContext,
507
+ toolsContext: currentToolsContext
421
508
  });
422
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
+ }));
423
527
  try {
424
- 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;
425
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
+ }));
426
552
  const { toolCalls, finish, step, providerExecutedToolResults } = await doStreamStep(
427
553
  conversationPrompt,
428
554
  currentModel,
@@ -432,11 +558,22 @@ async function* streamTextIterator({
432
558
  ...currentGenerationSettings,
433
559
  toolChoice: currentToolChoice,
434
560
  includeRawChunks,
435
- experimental_telemetry,
436
561
  repairToolCall,
437
- responseFormat
562
+ responseFormat,
563
+ runtimeContext: currentRuntimeContext,
564
+ toolsContext: currentToolsContext,
565
+ stepNumber
438
566
  }
439
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
+ }));
440
577
  _isFirstIteration = false;
441
578
  stepNumber++;
442
579
  steps.push(step);
@@ -464,7 +601,8 @@ async function* streamTextIterator({
464
601
  toolCalls,
465
602
  messages: conversationPrompt,
466
603
  step,
467
- context: currentContext,
604
+ runtimeContext: currentRuntimeContext,
605
+ toolsContext: currentToolsContext,
468
606
  providerExecutedToolResults
469
607
  };
470
608
  conversationPrompt.push({
@@ -505,9 +643,11 @@ async function* streamTextIterator({
505
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}`
506
644
  );
507
645
  }
508
- if (onStepFinish) {
509
- await onStepFinish(step);
646
+ const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;
647
+ if (resolvedOnStepEnd) {
648
+ await resolvedOnStepEnd(step);
510
649
  }
650
+ await ((_j = telemetryDispatcher.onStepEnd) == null ? void 0 : _j.call(telemetryDispatcher, normalizeStepForTelemetry(step)));
511
651
  } catch (error) {
512
652
  if (onError) {
513
653
  await onError({ error });
@@ -520,19 +660,22 @@ async function* streamTextIterator({
520
660
  toolCalls: [],
521
661
  messages: conversationPrompt,
522
662
  step: lastStep,
523
- context: currentContext
663
+ runtimeContext: currentRuntimeContext,
664
+ toolsContext: currentToolsContext
524
665
  };
525
666
  }
526
667
  return conversationPrompt;
527
668
  }
528
- function filterToolSet(tools, activeTools) {
529
- const filtered = {};
530
- for (const toolName of activeTools) {
531
- if (toolName in tools) {
532
- filtered[toolName] = tools[toolName];
533
- }
534
- }
535
- 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
+ };
536
679
  }
537
680
  function sanitizeProviderMetadataForToolCall(metadata) {
538
681
  if (metadata == null) return void 0;
@@ -558,20 +701,28 @@ function sanitizeProviderMetadataForToolCall(metadata) {
558
701
  // src/workflow-agent.ts
559
702
  var WorkflowAgent = class {
560
703
  constructor(options) {
561
- var _a, _b;
704
+ var _a, _b, _c;
705
+ this.id = options.id;
562
706
  this.model = options.model;
563
707
  this.tools = (_a = options.tools) != null ? _a : {};
564
708
  this.instructions = (_b = options.instructions) != null ? _b : options.system;
565
709
  this.toolChoice = options.toolChoice;
566
- this.telemetry = options.experimental_telemetry;
567
- this.experimentalContext = options.experimental_context;
710
+ this.telemetry = options.telemetry;
711
+ this.runtimeContext = options.runtimeContext;
712
+ this.toolsContext = options.toolsContext;
713
+ this.stopWhen = options.stopWhen;
714
+ this.activeTools = options.activeTools;
715
+ this.output = options.output;
716
+ this.experimentalRepairToolCall = options.experimental_repairToolCall;
717
+ this.experimentalDownload = options.experimental_download;
568
718
  this.prepareStep = options.prepareStep;
569
- this.constructorOnStepFinish = options.onStepFinish;
570
- this.constructorOnFinish = options.onFinish;
719
+ this.constructorOnStepEnd = (_c = options.onStepEnd) != null ? _c : options.onStepFinish;
720
+ const { onFinish, onEnd = onFinish } = options;
721
+ this.constructorOnEnd = onEnd;
571
722
  this.constructorOnStart = options.experimental_onStart;
572
723
  this.constructorOnStepStart = options.experimental_onStepStart;
573
- this.constructorOnToolCallStart = options.experimental_onToolCallStart;
574
- this.constructorOnToolCallFinish = options.experimental_onToolCallFinish;
724
+ this.constructorOnToolExecutionStart = options.onToolExecutionStart;
725
+ this.constructorOnToolExecutionEnd = options.onToolExecutionEnd;
575
726
  this.prepareCall = options.prepareCall;
576
727
  this.generationSettings = {
577
728
  maxOutputTokens: options.maxOutputTokens,
@@ -592,36 +743,45 @@ var WorkflowAgent = class {
592
743
  throw new Error("Not implemented");
593
744
  }
594
745
  async stream(options) {
595
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
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;
596
748
  let effectiveModel = this.model;
597
749
  let effectiveInstructions = (_a = options.system) != null ? _a : this.instructions;
750
+ let effectivePrompt = options.prompt;
598
751
  let effectiveMessages = options.messages;
599
752
  let effectiveGenerationSettings = { ...this.generationSettings };
600
- let effectiveExperimentalContext = (_b = options.experimental_context) != null ? _b : this.experimentalContext;
601
- let effectiveToolChoiceFromPrepare = (_c = options.toolChoice) != null ? _c : this.toolChoice;
602
- let effectiveTelemetryFromPrepare = (_d = options.experimental_telemetry) != null ? _d : this.telemetry;
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 : [];
603
758
  if (this.prepareCall) {
604
759
  const prepared = await this.prepareCall({
605
760
  model: effectiveModel,
606
761
  tools: this.tools,
607
762
  instructions: effectiveInstructions,
608
763
  toolChoice: effectiveToolChoiceFromPrepare,
609
- experimental_telemetry: effectiveTelemetryFromPrepare,
610
- experimental_context: effectiveExperimentalContext,
611
- messages: effectiveMessages,
764
+ telemetry: effectiveTelemetryFromPrepare,
765
+ runtimeContext: effectiveRuntimeContext,
766
+ toolsContext: effectiveToolsContext,
767
+ messages: resolvedMessagesForPrepareCall,
612
768
  ...effectiveGenerationSettings
613
769
  });
614
770
  if (prepared.model !== void 0) effectiveModel = prepared.model;
615
771
  if (prepared.instructions !== void 0)
616
772
  effectiveInstructions = prepared.instructions;
617
- if (prepared.messages !== void 0)
773
+ if (prepared.messages !== void 0) {
618
774
  effectiveMessages = prepared.messages;
619
- if (prepared.experimental_context !== void 0)
620
- effectiveExperimentalContext = prepared.experimental_context;
775
+ effectivePrompt = void 0;
776
+ }
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,
648
- messages: effectiveMessages
814
+ allowSystemInMessages: true,
815
+ // TODO: consider exposing this as a parameter
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: options.experimental_download
1070
+ download
745
1071
  });
746
1072
  const effectiveAbortSignal = mergeAbortSignals(
747
- (_e = options.abortSignal) != null ? _e : 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,79 +1120,205 @@ 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 effectiveTools = options.activeTools && options.activeTools.length > 0 ? filterTools(this.tools, options.activeTools) : this.tools;
808
- 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;
809
1140
  const steps = [];
810
1141
  let lastStepToolCalls = [];
811
1142
  let lastStepToolResults = [];
812
1143
  if (mergedOnStart) {
813
1144
  await mergedOnStart({
814
1145
  model: effectiveModel,
815
- messages: effectiveMessages
1146
+ messages: prompt.messages,
1147
+ runtimeContext,
1148
+ toolsContext
816
1149
  });
817
1150
  }
818
- const executeToolWithCallbacks = async (toolCall, tools, messages2, context) => {
819
- if (mergedOnToolCallStart) {
820
- await mergedOnToolCallStart({
821
- toolCall: {
822
- type: "tool-call",
823
- toolCallId: toolCall.toolCallId,
824
- toolName: toolCall.toolName,
825
- input: toolCall.input
826
- }
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;
1179
+ const toolCallEvent = {
1180
+ type: "tool-call",
1181
+ toolCallId: toolCall.toolCallId,
1182
+ toolName: toolCall.toolName,
1183
+ input: toolCall.input
1184
+ };
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({
1194
+ toolCall: toolCallEvent,
1195
+ stepNumber: currentStepNumber,
1196
+ messages: modelMessages,
1197
+ toolContext: resolvedContext
827
1198
  });
828
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
+ }));
1206
+ const startTime = Date.now();
829
1207
  let result;
830
1208
  try {
831
- 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();
832
1215
  } catch (err) {
833
- if (mergedOnToolCallFinish) {
834
- await mergedOnToolCallFinish({
835
- toolCall: {
836
- type: "tool-call",
837
- toolCallId: toolCall.toolCallId,
838
- toolName: toolCall.toolName,
839
- input: toolCall.input
840
- },
1216
+ const durationMs2 = Date.now() - startTime;
1217
+ if (mergedOnToolExecutionEnd) {
1218
+ await mergedOnToolExecutionEnd({
1219
+ toolCall: toolCallEvent,
1220
+ stepNumber: currentStepNumber,
1221
+ durationMs: durationMs2,
1222
+ messages: modelMessages,
1223
+ toolContext: resolvedContext,
1224
+ success: false,
841
1225
  error: err
842
1226
  });
843
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
+ }));
844
1237
  throw err;
845
1238
  }
846
- if (mergedOnToolCallFinish) {
847
- const isError = result.output && "type" in result.output && (result.output.type === "error-text" || result.output.type === "error-json");
848
- await mergedOnToolCallFinish({
849
- toolCall: {
850
- type: "tool-call",
851
- toolCallId: toolCall.toolCallId,
852
- toolName: toolCall.toolName,
853
- input: toolCall.input
854
- },
855
- ...isError ? {
856
- error: "value" in result.output ? result.output.value : void 0
857
- } : {
858
- result: result.output && "value" in result.output ? result.output.value : void 0
859
- }
860
- });
1239
+ const durationMs = Date.now() - startTime;
1240
+ if (mergedOnToolExecutionEnd) {
1241
+ if (result.isError) {
1242
+ await mergedOnToolExecutionEnd({
1243
+ toolCall: toolCallEvent,
1244
+ stepNumber: currentStepNumber,
1245
+ durationMs,
1246
+ messages: modelMessages,
1247
+ toolContext: resolvedContext,
1248
+ success: false,
1249
+ error: result.rawOutput
1250
+ });
1251
+ } else {
1252
+ await mergedOnToolExecutionEnd({
1253
+ toolCall: toolCallEvent,
1254
+ stepNumber: currentStepNumber,
1255
+ durationMs,
1256
+ messages: modelMessages,
1257
+ toolContext: resolvedContext,
1258
+ success: true,
1259
+ output: result.rawOutput
1260
+ });
1261
+ }
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
+ }));
861
1283
  }
862
1284
  return result;
863
1285
  };
864
- if ((_f = mergedGenerationSettings.abortSignal) == null ? void 0 : _f.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) {
865
1317
  if (options.onAbort) {
866
1318
  await options.onAbort({ steps });
867
1319
  }
868
1320
  return {
869
- messages: options.messages,
1321
+ messages: prompt.messages,
870
1322
  steps,
871
1323
  toolCalls: [],
872
1324
  toolResults: [],
@@ -878,19 +1330,19 @@ var WorkflowAgent = class {
878
1330
  tools: effectiveTools,
879
1331
  writable: options.writable,
880
1332
  prompt: modelPrompt,
881
- stopConditions: options.stopWhen,
882
- maxSteps: options.maxSteps,
883
- onStepFinish: mergedOnStepFinish,
1333
+ stopConditions: (_v = options.stopWhen) != null ? _v : this.stopWhen,
1334
+ onStepEnd: mergedOnStepEnd,
884
1335
  onStepStart: mergedOnStepStart,
885
1336
  onError: options.onError,
886
- prepareStep: (_g = options.prepareStep) != null ? _g : this.prepareStep,
1337
+ prepareStep: (_w = options.prepareStep) != null ? _w : this.prepareStep,
887
1338
  generationSettings: mergedGenerationSettings,
888
1339
  toolChoice: effectiveToolChoice,
889
- experimental_context: experimentalContext,
890
- experimental_telemetry: effectiveTelemetry,
891
- includeRawChunks: (_h = options.includeRawChunks) != null ? _h : false,
892
- repairToolCall: options.experimental_repairToolCall,
893
- responseFormat: await ((_i = options.output) == null ? void 0 : _i.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)
894
1346
  });
895
1347
  let finalMessages;
896
1348
  let encounteredError;
@@ -898,7 +1350,7 @@ var WorkflowAgent = class {
898
1350
  try {
899
1351
  let result = await iterator.next();
900
1352
  while (!result.done) {
901
- if ((_j = mergedGenerationSettings.abortSignal) == null ? void 0 : _j.aborted) {
1353
+ if ((_B = mergedGenerationSettings.abortSignal) == null ? void 0 : _B.aborted) {
902
1354
  wasAborted = true;
903
1355
  if (options.onAbort) {
904
1356
  await options.onAbort({ steps });
@@ -909,20 +1361,29 @@ var WorkflowAgent = class {
909
1361
  toolCalls,
910
1362
  messages: iterMessages,
911
1363
  step,
912
- context,
1364
+ runtimeContext: yieldedRuntimeContext,
1365
+ toolsContext: yieldedToolsContext,
913
1366
  providerExecutedToolResults
914
1367
  } = result.value;
1368
+ const currentStepNumber = steps.length;
915
1369
  if (step) {
916
1370
  steps.push(step);
917
1371
  }
918
- if (context !== void 0) {
919
- experimentalContext = context;
1372
+ if (yieldedRuntimeContext !== void 0) {
1373
+ runtimeContext = yieldedRuntimeContext;
1374
+ }
1375
+ if (yieldedToolsContext !== void 0) {
1376
+ toolsContext = yieldedToolsContext;
920
1377
  }
921
1378
  if (toolCalls.length > 0) {
922
- 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(
923
1382
  (tc) => !tc.providerExecuted
924
1383
  );
925
- const providerToolCalls = toolCalls.filter((tc) => tc.providerExecuted);
1384
+ const providerToolCalls = validToolCalls.filter(
1385
+ (tc) => tc.providerExecuted
1386
+ );
926
1387
  const approvalNeeded = await Promise.all(
927
1388
  nonProviderToolCalls.map(async (tc) => {
928
1389
  const tool2 = effectiveTools[tc.toolName];
@@ -930,10 +1391,15 @@ var WorkflowAgent = class {
930
1391
  if (tool2.needsApproval == null) return false;
931
1392
  if (typeof tool2.needsApproval === "boolean")
932
1393
  return tool2.needsApproval;
1394
+ const resolvedContext = await resolveToolContext({
1395
+ toolName: tc.toolName,
1396
+ tool: tool2,
1397
+ toolsContext
1398
+ });
933
1399
  return tool2.needsApproval(tc.input, {
934
1400
  toolCallId: tc.toolCallId,
935
1401
  messages: iterMessages,
936
- context: experimentalContext
1402
+ context: resolvedContext
937
1403
  });
938
1404
  })
939
1405
  );
@@ -952,31 +1418,56 @@ var WorkflowAgent = class {
952
1418
  toolCall,
953
1419
  effectiveTools,
954
1420
  iterMessages,
955
- experimentalContext
1421
+ toolsContext,
1422
+ currentStepNumber
956
1423
  )
957
1424
  )
958
1425
  );
959
- const providerResults = providerToolCalls.map(
960
- (toolCall) => resolveProviderToolResult(
961
- toolCall,
962
- providerExecutedToolResults
1426
+ const providerResults = await Promise.all(
1427
+ providerToolCalls.map(
1428
+ (toolCall) => resolveProviderToolResult(
1429
+ toolCall,
1430
+ providerExecutedToolResults,
1431
+ effectiveTools,
1432
+ download
1433
+ )
963
1434
  )
964
1435
  );
965
- 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];
966
1455
  const allToolCalls = toolCalls.map((tc) => ({
967
1456
  type: "tool-call",
968
1457
  toolCallId: tc.toolCallId,
969
1458
  toolName: tc.toolName,
970
1459
  input: tc.input
971
1460
  }));
972
- const allToolResults = resolvedResults.map((r) => {
1461
+ const allToolResults = executedResults.map((r) => {
973
1462
  var _a2;
974
1463
  return {
975
1464
  type: "tool-result",
976
- toolCallId: r.toolCallId,
977
- toolName: r.toolName,
978
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
979
- 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
980
1471
  };
981
1472
  });
982
1473
  if (resolvedResults.length > 0) {
@@ -986,18 +1477,32 @@ var WorkflowAgent = class {
986
1477
  });
987
1478
  }
988
1479
  const messages2 = iterMessages;
989
- if (mergedOnFinish && !wasAborted) {
1480
+ if (mergedOnEnd && !wasAborted) {
990
1481
  const lastStep = steps[steps.length - 1];
991
- await mergedOnFinish({
1482
+ const totalUsage = aggregateUsage(steps);
1483
+ await mergedOnEnd({
992
1484
  steps,
993
1485
  messages: messages2,
994
- text: (_k = lastStep == null ? void 0 : lastStep.text) != null ? _k : "",
995
- finishReason: (_l = lastStep == null ? void 0 : lastStep.finishReason) != null ? _l : "other",
996
- totalUsage: aggregateUsage(steps),
997
- 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,
998
1492
  output: void 0
999
1493
  });
1000
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
+ }
1001
1506
  if (options.writable) {
1002
1507
  const approvalToolCalls = pausedToolCalls.filter((_, i) => {
1003
1508
  const tcIndex = nonProviderToolCalls.indexOf(
@@ -1016,8 +1521,8 @@ var WorkflowAgent = class {
1016
1521
  }
1017
1522
  }
1018
1523
  if (options.writable) {
1019
- const sendFinish = (_m = options.sendFinish) != null ? _m : true;
1020
- const preventClose = (_n = options.preventClose) != null ? _n : false;
1524
+ const sendFinish = (_F = options.sendFinish) != null ? _F : true;
1525
+ const preventClose = (_G = options.preventClose) != null ? _G : false;
1021
1526
  if (sendFinish || !preventClose) {
1022
1527
  await closeStream(options.writable, preventClose, sendFinish);
1023
1528
  }
@@ -1036,39 +1541,68 @@ var WorkflowAgent = class {
1036
1541
  toolCall,
1037
1542
  effectiveTools,
1038
1543
  iterMessages,
1039
- experimentalContext
1544
+ toolsContext,
1545
+ currentStepNumber
1040
1546
  )
1041
1547
  )
1042
1548
  );
1043
- const providerToolResults = providerToolCalls.map(
1044
- (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
+ )
1045
1558
  );
1046
- const toolResults = toolCalls.map((tc) => {
1559
+ await Promise.all(
1560
+ providerToolCalls.map(
1561
+ (toolCall, index) => recordProviderExecutedToolTelemetry(
1562
+ toolCall,
1563
+ providerToolResults[index],
1564
+ iterMessages,
1565
+ currentStepNumber
1566
+ )
1567
+ )
1568
+ );
1569
+ const continuationInvalidToolResults = invalidToolCalls.map(
1570
+ createInvalidToolResult
1571
+ );
1572
+ const executedToolResults = toolCalls.flatMap((tc) => {
1047
1573
  const clientResult = clientToolResults.find(
1048
- (r) => r.toolCallId === tc.toolCallId
1574
+ (r) => r.modelResult.toolCallId === tc.toolCallId
1049
1575
  );
1050
- if (clientResult) return clientResult;
1576
+ if (clientResult) return [clientResult];
1051
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(
1052
1585
  (r) => r.toolCallId === tc.toolCallId
1053
1586
  );
1054
- if (providerResult) return providerResult;
1055
- return {
1056
- type: "tool-result",
1057
- toolCallId: tc.toolCallId,
1058
- toolName: tc.toolName,
1059
- output: { type: "text", value: "" }
1060
- };
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 [];
1061
1593
  });
1062
1594
  if (options.writable) {
1063
1595
  await writeToolResultsWithStepBoundary(
1064
1596
  options.writable,
1065
- toolResults.map((r) => {
1597
+ executedToolResults.map((r) => {
1066
1598
  var _a2;
1067
1599
  return {
1068
- toolCallId: r.toolCallId,
1069
- toolName: r.toolName,
1070
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
1071
- 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
1072
1606
  };
1073
1607
  })
1074
1608
  );
@@ -1079,17 +1613,19 @@ var WorkflowAgent = class {
1079
1613
  toolName: tc.toolName,
1080
1614
  input: tc.input
1081
1615
  }));
1082
- lastStepToolResults = toolResults.map((r) => {
1616
+ lastStepToolResults = executedToolResults.map((r) => {
1083
1617
  var _a2;
1084
1618
  return {
1085
1619
  type: "tool-result",
1086
- toolCallId: r.toolCallId,
1087
- toolName: r.toolName,
1088
- input: (_a2 = toolCalls.find((tc) => tc.toolCallId === r.toolCallId)) == null ? void 0 : _a2.input,
1089
- 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
1090
1626
  };
1091
1627
  });
1092
- result = await iterator.next(toolResults);
1628
+ result = await iterator.next(continuationToolResults);
1093
1629
  } else {
1094
1630
  lastStepToolCalls = [];
1095
1631
  lastStepToolResults = [];
@@ -1109,15 +1645,17 @@ var WorkflowAgent = class {
1109
1645
  } else if (options.onError) {
1110
1646
  await options.onError({ error });
1111
1647
  }
1648
+ await ((_H = telemetryDispatcher.onError) == null ? void 0 : _H.call(telemetryDispatcher, error));
1112
1649
  }
1113
- const messages = finalMessages != null ? finalMessages : options.messages;
1650
+ const messages = finalMessages != null ? finalMessages : prompt.messages;
1651
+ const effectiveOutput = (_I = options.output) != null ? _I : this.output;
1114
1652
  let experimentalOutput = void 0;
1115
- if (options.output && steps.length > 0) {
1653
+ if (effectiveOutput && steps.length > 0) {
1116
1654
  const lastStep = steps[steps.length - 1];
1117
1655
  const text = lastStep.text;
1118
1656
  if (text) {
1119
1657
  try {
1120
- experimentalOutput = await options.output.parseCompleteOutput(
1658
+ experimentalOutput = await effectiveOutput.parseCompleteOutput(
1121
1659
  { text },
1122
1660
  {
1123
1661
  response: lastStep.response,
@@ -1132,22 +1670,36 @@ var WorkflowAgent = class {
1132
1670
  }
1133
1671
  }
1134
1672
  }
1135
- if (mergedOnFinish && !wasAborted) {
1673
+ if (mergedOnEnd && !wasAborted) {
1136
1674
  const lastStep = steps[steps.length - 1];
1137
- await mergedOnFinish({
1675
+ const totalUsage = aggregateUsage(steps);
1676
+ await mergedOnEnd({
1138
1677
  steps,
1139
1678
  messages,
1140
- text: (_o = lastStep == null ? void 0 : lastStep.text) != null ? _o : "",
1141
- finishReason: (_p = lastStep == null ? void 0 : lastStep.finishReason) != null ? _p : "other",
1142
- totalUsage: aggregateUsage(steps),
1143
- 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,
1144
1685
  output: experimentalOutput
1145
1686
  });
1146
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
+ }
1147
1699
  if (encounteredError) {
1148
1700
  if (options.writable) {
1149
- const sendFinish = (_q = options.sendFinish) != null ? _q : true;
1150
- const preventClose = (_r = options.preventClose) != null ? _r : false;
1701
+ const sendFinish = (_M = options.sendFinish) != null ? _M : true;
1702
+ const preventClose = (_N = options.preventClose) != null ? _N : false;
1151
1703
  if (sendFinish || !preventClose) {
1152
1704
  await closeStream(options.writable, preventClose, sendFinish);
1153
1705
  }
@@ -1155,8 +1707,8 @@ var WorkflowAgent = class {
1155
1707
  throw encounteredError;
1156
1708
  }
1157
1709
  if (options.writable) {
1158
- const sendFinish = (_s = options.sendFinish) != null ? _s : true;
1159
- const preventClose = (_t = options.preventClose) != null ? _t : false;
1710
+ const sendFinish = (_O = options.sendFinish) != null ? _O : true;
1711
+ const preventClose = (_P = options.preventClose) != null ? _P : false;
1160
1712
  if (sendFinish || !preventClose) {
1161
1713
  await closeStream(options.writable, preventClose, sendFinish);
1162
1714
  }
@@ -1170,6 +1722,17 @@ var WorkflowAgent = class {
1170
1722
  };
1171
1723
  }
1172
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
+ }
1173
1736
  async function closeStream(writable, preventClose, sendFinish) {
1174
1737
  "use step";
1175
1738
  if (sendFinish) {
@@ -1243,6 +1806,22 @@ async function writeApprovalToolResults(writable, approvedResults, deniedResults
1243
1806
  writer.releaseLock();
1244
1807
  }
1245
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
+ }
1246
1825
  function aggregateUsage(steps) {
1247
1826
  var _a, _b, _c, _d;
1248
1827
  let inputTokens = 0;
@@ -1257,59 +1836,65 @@ function aggregateUsage(steps) {
1257
1836
  totalTokens: inputTokens + outputTokens
1258
1837
  };
1259
1838
  }
1260
- function filterTools(tools, activeTools) {
1261
- const filtered = {};
1262
- for (const toolName of activeTools) {
1263
- if (toolName in tools) {
1264
- filtered[toolName] = tools[toolName];
1265
- }
1266
- }
1267
- return filtered;
1268
- }
1269
- function getErrorMessage(error) {
1270
- if (error == null) {
1271
- return "unknown error";
1272
- }
1273
- if (typeof error === "string") {
1274
- return error;
1275
- }
1276
- if (error instanceof Error) {
1277
- return error.message;
1278
- }
1279
- return JSON.stringify(error);
1280
- }
1281
- function resolveProviderToolResult(toolCall, providerExecutedToolResults) {
1839
+ async function resolveProviderToolResult(toolCall, providerExecutedToolResults, tools, download) {
1282
1840
  const streamResult = providerExecutedToolResults == null ? void 0 : providerExecutedToolResults.get(toolCall.toolCallId);
1283
1841
  if (!streamResult) {
1284
1842
  console.warn(
1285
1843
  `[WorkflowAgent] Provider-executed tool "${toolCall.toolName}" (${toolCall.toolCallId}) did not receive a result from the stream. This may indicate a provider issue.`
1286
1844
  );
1287
1845
  return {
1288
- type: "tool-result",
1289
- toolCallId: toolCall.toolCallId,
1290
- toolName: toolCall.toolName,
1291
- output: {
1292
- type: "text",
1293
- value: ""
1294
- }
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
1295
1857
  };
1296
1858
  }
1297
1859
  const result = streamResult.result;
1298
- 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) {
1299
1882
  return {
1300
1883
  type: "tool-result",
1301
1884
  toolCallId: toolCall.toolCallId,
1302
1885
  toolName: toolCall.toolName,
1303
- output: isString ? streamResult.isError ? { type: "error-text", value: result } : { type: "text", value: result } : streamResult.isError ? {
1304
- type: "error-json",
1305
- value: result
1306
- } : {
1307
- type: "json",
1308
- value: result
1886
+ output: {
1887
+ type: "error-text",
1888
+ value: getErrorMessage(toolCall.error)
1309
1889
  }
1310
1890
  };
1311
1891
  }
1312
- 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) {
1313
1898
  const tool2 = tools[toolCall.toolName];
1314
1899
  if (!tool2) throw new Error(`Tool "${toolCall.toolName}" not found`);
1315
1900
  if (typeof tool2.execute !== "function") {
@@ -1318,97 +1903,57 @@ async function executeTool(toolCall, tools, messages, experimentalContext) {
1318
1903
  );
1319
1904
  }
1320
1905
  const parsedInput = toolCall.input;
1906
+ let toolResult;
1321
1907
  try {
1322
1908
  const { execute } = tool2;
1323
- const toolResult = await execute(parsedInput, {
1909
+ toolResult = await execute(parsedInput, {
1324
1910
  toolCallId: toolCall.toolCallId,
1325
1911
  // Pass the conversation messages to the tool so it has context about the conversation
1326
1912
  messages,
1327
- // Pass context to the tool
1328
- context: experimentalContext
1913
+ // Pass per-tool context to the tool (resolved from `toolsContext`)
1914
+ context
1329
1915
  });
1330
- const output = typeof toolResult === "string" ? { type: "text", value: toolResult } : { type: "json", value: toolResult };
1331
- return {
1332
- type: "tool-result",
1333
- toolCallId: toolCall.toolCallId,
1334
- toolName: toolCall.toolName,
1335
- output
1336
- };
1337
1916
  } catch (error) {
1917
+ const errorMessage = getErrorMessage(error);
1338
1918
  return {
1339
- type: "tool-result",
1340
- toolCallId: toolCall.toolCallId,
1341
- toolName: toolCall.toolName,
1342
- output: {
1343
- type: "error-text",
1344
- value: getErrorMessage(error)
1345
- }
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
1346
1936
  };
1347
1937
  }
1348
- }
1349
- function collectToolApprovalsFromMessages(messages) {
1350
- var _a;
1351
- const lastMessage = messages.at(-1);
1352
- if ((lastMessage == null ? void 0 : lastMessage.role) !== "tool") {
1353
- return { approvedToolApprovals: [], deniedToolApprovals: [] };
1354
- }
1355
- const toolCallsByToolCallId = {};
1356
- for (const message of messages) {
1357
- if (message.role === "assistant" && Array.isArray(message.content)) {
1358
- for (const part of message.content) {
1359
- if (part.type === "tool-call") {
1360
- toolCallsByToolCallId[part.toolCallId] = {
1361
- toolName: part.toolName,
1362
- input: (_a = part.input) != null ? _a : part.args
1363
- };
1364
- }
1365
- }
1366
- }
1367
- }
1368
- const approvalRequestsByApprovalId = {};
1369
- for (const message of messages) {
1370
- if (message.role === "assistant" && Array.isArray(message.content)) {
1371
- for (const part of message.content) {
1372
- if (part.type === "tool-approval-request") {
1373
- approvalRequestsByApprovalId[part.approvalId] = {
1374
- approvalId: part.approvalId,
1375
- toolCallId: part.toolCallId
1376
- };
1377
- }
1378
- }
1379
- }
1380
- }
1381
- const existingToolResults = /* @__PURE__ */ new Set();
1382
- for (const part of lastMessage.content) {
1383
- if (part.type === "tool-result") {
1384
- existingToolResults.add(part.toolCallId);
1385
- }
1386
- }
1387
- const approvedToolApprovals = [];
1388
- const deniedToolApprovals = [];
1389
- const approvalResponses = lastMessage.content.filter(
1390
- (part) => part.type === "tool-approval-response"
1391
- );
1392
- for (const response of approvalResponses) {
1393
- const approvalRequest = approvalRequestsByApprovalId[response.approvalId];
1394
- if (approvalRequest == null) continue;
1395
- if (existingToolResults.has(approvalRequest.toolCallId)) continue;
1396
- const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
1397
- if (toolCall == null) continue;
1398
- const approval = {
1399
- toolCallId: approvalRequest.toolCallId,
1938
+ return {
1939
+ modelResult: {
1940
+ type: "tool-result",
1941
+ toolCallId: toolCall.toolCallId,
1400
1942
  toolName: toolCall.toolName,
1401
- input: toolCall.input,
1402
- approvalId: response.approvalId,
1403
- reason: response.reason
1404
- };
1405
- if (response.approved) {
1406
- approvedToolApprovals.push(approval);
1407
- } else {
1408
- deniedToolApprovals.push(approval);
1409
- }
1410
- }
1411
- 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
+ };
1412
1957
  }
1413
1958
 
1414
1959
  // src/to-ui-message-chunk.ts
@@ -1543,16 +2088,16 @@ function toUIMessageChunk(part) {
1543
2088
  case "raw":
1544
2089
  return void 0;
1545
2090
  default: {
1546
- const p = part;
1547
- if (p.type === "tool-approval-request") {
2091
+ const passthroughPart = part;
2092
+ if (passthroughPart.type === "tool-approval-request") {
1548
2093
  return {
1549
2094
  type: "tool-approval-request",
1550
- approvalId: p.approvalId,
1551
- toolCallId: p.toolCallId
2095
+ approvalId: passthroughPart.approvalId,
2096
+ toolCallId: passthroughPart.toolCallId
1552
2097
  };
1553
2098
  }
1554
- if (p.type === "finish-step" || p.type === "start-step" || p.type === "tool-output-denied") {
1555
- return p;
2099
+ if (passthroughPart.type === "finish-step" || passthroughPart.type === "start-step" || passthroughPart.type === "tool-output-denied") {
2100
+ return passthroughPart;
1556
2101
  }
1557
2102
  return void 0;
1558
2103
  }
@@ -1651,7 +2196,7 @@ var WorkflowChatTransport = class {
1651
2196
  messageId
1652
2197
  }) : void 0;
1653
2198
  const url = (_a = requestConfig == null ? void 0 : requestConfig.api) != null ? _a : this.api;
1654
- const res = await this.fetch(url, {
2199
+ const response = await this.fetch(url, {
1655
2200
  method: "POST",
1656
2201
  body: JSON.stringify(
1657
2202
  (_b = requestConfig == null ? void 0 : requestConfig.body) != null ? _b : { messages, ...options.body }
@@ -1660,21 +2205,21 @@ var WorkflowChatTransport = class {
1660
2205
  credentials: requestConfig == null ? void 0 : requestConfig.credentials,
1661
2206
  signal: abortSignal
1662
2207
  });
1663
- if (!res.ok || !res.body) {
2208
+ if (!response.ok || !response.body) {
1664
2209
  throw new Error(
1665
- `Failed to fetch chat: ${res.status} ${await res.text()}`
2210
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
1666
2211
  );
1667
2212
  }
1668
- const workflowRunId = res.headers.get("x-workflow-run-id");
2213
+ const workflowRunId = response.headers.get("x-workflow-run-id");
1669
2214
  if (!workflowRunId) {
1670
2215
  throw new Error(
1671
2216
  'Workflow run ID not found in "x-workflow-run-id" response header'
1672
2217
  );
1673
2218
  }
1674
- 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));
1675
2220
  try {
1676
2221
  const chunkStream = parseJsonEventStream({
1677
- stream: res.body,
2222
+ stream: response.body,
1678
2223
  schema: uiMessageChunkSchema
1679
2224
  });
1680
2225
  for await (const chunk of createAsyncIterableStream(chunkStream)) {
@@ -1709,8 +2254,8 @@ var WorkflowChatTransport = class {
1709
2254
  * @throws Error if the reconnection request fails or returns a non-OK status
1710
2255
  */
1711
2256
  async reconnectToStream(options) {
1712
- const it = this.reconnectToStreamIterator(options);
1713
- return convertAsyncIteratorToReadableStream(it);
2257
+ const reconnectIterator = this.reconnectToStreamIterator(options);
2258
+ return convertAsyncIteratorToReadableStream(reconnectIterator);
1714
2259
  }
1715
2260
  async *reconnectToStreamIterator(options, workflowRunId, initialChunkIndex = 0) {
1716
2261
  var _a, _b;
@@ -1733,20 +2278,22 @@ var WorkflowChatTransport = class {
1733
2278
  while (!gotFinish) {
1734
2279
  const startIndex = useExplicitStartIndex ? explicitStartIndex : replayFromStart ? 0 : chunkIndex;
1735
2280
  const url = `${baseUrl}?startIndex=${startIndex}`;
1736
- const res = await this.fetch(url, {
2281
+ const response = await this.fetch(url, {
1737
2282
  headers: requestConfig == null ? void 0 : requestConfig.headers,
1738
2283
  credentials: requestConfig == null ? void 0 : requestConfig.credentials,
1739
2284
  signal: options.abortSignal
1740
2285
  });
1741
- if (!res.ok || !res.body) {
2286
+ if (!response.ok || !response.body) {
1742
2287
  throw new Error(
1743
- `Failed to fetch chat: ${res.status} ${await res.text()}`
2288
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
1744
2289
  );
1745
2290
  }
1746
2291
  if (useExplicitStartIndex && explicitStartIndex > 0) {
1747
2292
  chunkIndex = explicitStartIndex;
1748
2293
  } else if (useExplicitStartIndex && explicitStartIndex < 0) {
1749
- const tailIndexHeader = res.headers.get("x-workflow-stream-tail-index");
2294
+ const tailIndexHeader = response.headers.get(
2295
+ "x-workflow-stream-tail-index"
2296
+ );
1750
2297
  const tailIndex = tailIndexHeader !== null ? parseInt(tailIndexHeader, 10) : NaN;
1751
2298
  if (!Number.isNaN(tailIndex)) {
1752
2299
  chunkIndex = Math.max(0, tailIndex + 1 + explicitStartIndex);
@@ -1760,7 +2307,7 @@ var WorkflowChatTransport = class {
1760
2307
  useExplicitStartIndex = false;
1761
2308
  try {
1762
2309
  const chunkStream = parseJsonEventStream({
1763
- stream: res.body,
2310
+ stream: response.body,
1764
2311
  schema: uiMessageChunkSchema
1765
2312
  });
1766
2313
  for await (const chunk of createAsyncIterableStream(chunkStream)) {