ai 7.0.176 → 7.0.177

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.
@@ -18,6 +18,7 @@ import {
18
18
  type InferToolSetContext,
19
19
  type ProviderOptions,
20
20
  type ToolSet,
21
+ type UserModelMessage,
21
22
  } from '@ai-sdk/provider-utils';
22
23
  import { ToolChoiceViolationError } from '../error';
23
24
  import { logWarnings } from '../logger/log-warnings';
@@ -1029,308 +1030,636 @@ async function generateTextInternal<
1029
1030
  });
1030
1031
  const stepNumber = steps.length;
1031
1032
 
1032
- const steeringMessages = steeringRun?.takeMessages() ?? [];
1033
+ let steeringMessages = steeringRun?.takeMessages() ?? [];
1033
1034
  if (steeringMessages.length > 0) {
1034
1035
  messagesForNextStep = [...messagesForNextStep, ...steeringMessages];
1035
1036
  }
1037
+ // A step that a steering interrupt cancelled is made again as the same
1038
+ // step. It keeps the steering messages that it already delivered, and
1039
+ // onStepStart is called once for it.
1040
+ let stepSteeringMessages: Array<UserModelMessage> = [];
1041
+ let hasNotifiedStepStart = false;
1042
+
1043
+ // prepareStep runs again when the step is redone. It must get the
1044
+ // contexts that the step started with, not the ones that it returned
1045
+ // for the cancelled model call:
1046
+ const stepStartRuntimeContext = runtimeContext;
1047
+ const stepStartToolsContext = toolsContext;
1036
1048
 
1037
1049
  try {
1038
1050
  await runInTracingChannelSpan({
1039
1051
  type: 'step',
1040
1052
  event: { callId, stepNumber },
1041
- execute: async () => {
1042
- const accumulatedResponseMessages = [
1043
- ...initialResponseMessages,
1044
- ...steps.flatMap(step => step.response.messages),
1045
- ];
1046
- const stepInputMessages = messagesForNextStep;
1047
-
1048
- const prepareStepResult = await prepareStep?.({
1049
- model,
1050
- steps,
1051
- stepNumber: steps.length,
1052
- instructions: instructionsForNextStep,
1053
- initialInstructions: initialPrompt.instructions,
1054
- messages: stepInputMessages,
1055
- initialMessages,
1056
- responseMessages: accumulatedResponseMessages,
1057
- ...(steeringMessages.length > 0
1058
- ? { experimental_steeringMessages: steeringMessages }
1059
- : {}),
1060
- runtimeContext,
1061
- toolsContext,
1062
- experimental_sandbox: sandbox,
1063
- });
1064
-
1065
- const stepSandbox =
1066
- prepareStepResult?.experimental_sandbox ?? sandbox;
1067
-
1068
- const stepModel = resolveLanguageModel(
1069
- prepareStepResult?.model ?? model,
1070
- );
1071
-
1072
- const stepInstructions =
1073
- prepareStepResult?.instructions ??
1074
- prepareStepResult?.system ??
1075
- instructionsForNextStep;
1076
-
1077
- runtimeContext =
1078
- prepareStepResult?.runtimeContext ?? runtimeContext;
1079
- toolsContext = prepareStepResult?.toolsContext ?? toolsContext;
1080
-
1081
- const stepActiveTools = filterActiveTools({
1082
- tools,
1083
- activeTools: prepareStepResult?.activeTools ?? activeTools,
1084
- });
1085
- const {
1086
- executionTools,
1087
- modelTools: stepModelTools,
1088
- toolCallerMessages,
1089
- } = prepareToolsForToolCallers({
1090
- tools: prepareToolSearch(stepActiveTools, {
1091
- toolsContext,
1092
- experimental_sandbox: stepSandbox,
1093
- }),
1094
- toolCallers: resolvedToolCallers,
1095
- });
1096
- const stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;
1097
-
1098
- const stepTools = await prepareTools({
1099
- tools: stepModelTools as ActiveToolSubset<
1100
- TOOLS,
1101
- ActiveTools<NoInfer<TOOLS>>
1102
- >,
1103
- toolOrder: stepToolOrder as ToolOrder<
1104
- ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>
1105
- >,
1106
- // active tools context is a subset of the tools context, so we can cast to the unknown type
1107
- toolsContext: toolsContext as unknown as InferToolSetContext<
1108
- ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>
1109
- >,
1110
- experimental_sandbox: stepSandbox,
1111
- });
1112
-
1113
- const stepToolChoice = prepareToolChoice({
1114
- toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1115
- });
1116
- const stepExecutionTools =
1117
- stepToolChoice.type === 'none' ? undefined : executionTools;
1118
-
1119
- const stepMessages = appendToolCallerMessages({
1120
- messages: prepareStepResult?.messages ?? stepInputMessages,
1121
- toolCallerMessages,
1122
- });
1123
-
1124
- // steering messages are delivered when they are in the messages
1125
- // that are sent to the model after prepareStep:
1126
- const deliveredSteeringMessages = (
1127
- steeringRun?.resolveTakenMessages({
1128
- stepNumber,
1129
- sentMessages: stepMessages,
1130
- }) ?? []
1131
- ).map(({ message }) => message);
1132
-
1133
- const promptMessages = await convertToLanguageModelPrompt({
1134
- prompt: {
1135
- instructions: stepInstructions,
1136
- messages: stepMessages,
1053
+ execute: () =>
1054
+ redoInterruptedStepAttempts({
1055
+ onInterrupt: () => {
1056
+ runtimeContext = stepStartRuntimeContext;
1057
+ toolsContext = stepStartToolsContext;
1058
+
1059
+ const interruptMessages = steeringRun?.takeMessages() ?? [];
1060
+ steeringMessages = [
1061
+ ...steeringMessages,
1062
+ ...interruptMessages,
1063
+ ];
1064
+ messagesForNextStep = [
1065
+ ...messagesForNextStep,
1066
+ ...interruptMessages,
1067
+ ];
1137
1068
  },
1138
- supportedUrls: await stepModel.supportedUrls,
1139
- download,
1140
- abortSignal: mergedAbortSignal,
1141
- provider: stepModel.provider.split('.')[0],
1142
- });
1143
-
1144
- const stepProviderOptions = mergeObjects(
1145
- providerOptions,
1146
- prepareStepResult?.providerOptions,
1147
- );
1148
-
1149
- const stepCallSettings = prepareStepCallSettings({
1150
- callSettings,
1151
- stepSettings: prepareStepResult,
1152
- });
1153
-
1154
- const stepStartEvent = {
1155
- callId,
1156
- provider: stepModel.provider,
1157
- modelId: stepModel.modelId,
1158
- stepNumber,
1159
- instructions: stepInstructions,
1160
- messages: stepMessages,
1161
- tools,
1162
- toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1163
- activeTools: prepareStepResult?.activeTools ?? activeTools,
1164
- toolOrder: stepToolOrder,
1165
- steps: [...steps],
1166
- providerOptions: stepProviderOptions,
1167
- output,
1168
- runtimeContext,
1169
- promptMessages,
1170
- stepTools,
1171
- stepToolChoice,
1172
- toolsContext,
1173
- };
1174
-
1175
- await notify({
1176
- event: stepStartEvent,
1177
- callbacks: [
1178
- resolvedOnStepStart,
1179
- telemetryDispatcher.onStepStart,
1180
- ],
1181
- });
1182
-
1183
- openStep = stepStartEvent;
1184
-
1185
- const languageModelCallContext = {
1186
- provider: stepModel.provider,
1187
- modelId: stepModel.modelId,
1188
- instructions: stepInstructions,
1189
- messages: stepMessages,
1190
- tools: stepTools,
1191
- ...stepCallSettings,
1192
- };
1193
- const languageModelCallStartEvent = {
1194
- callId,
1195
- ...languageModelCallContext,
1196
- };
1197
-
1198
- const stepStartTimestampMs = now();
1199
-
1200
- await notify({
1201
- event: languageModelCallStartEvent,
1202
- callbacks: [
1203
- resolvedOnLanguageModelCallStart,
1204
- telemetryDispatcher.onLanguageModelCallStart as
1205
- | undefined
1206
- | OnLanguageModelCallStartCallback,
1207
- ],
1208
- });
1209
-
1210
- const executeLanguageModelCallInTelemetryContext =
1211
- telemetryDispatcher.executeLanguageModelCall ??
1212
- (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>
1213
- await execute());
1214
-
1215
- currentModelResponse = await retry(async () => {
1216
- const result = await executeLanguageModelCallInTelemetryContext(
1217
- {
1218
- ...languageModelCallStartEvent,
1219
- execute: async () => {
1220
- const result = await stepModel.doGenerate({
1221
- ...stepCallSettings,
1222
- tools: stepTools,
1223
- toolChoice: stepToolChoice,
1224
- responseFormat: await output?.responseFormat,
1225
- prompt: promptMessages,
1226
- providerOptions: stepProviderOptions,
1227
- abortSignal: mergedAbortSignal,
1228
- headers: headersWithUserAgent,
1229
- });
1069
+ attempt: async () => {
1070
+ const accumulatedResponseMessages = [
1071
+ ...initialResponseMessages,
1072
+ ...steps.flatMap(step => step.response.messages),
1073
+ ];
1074
+ const stepInputMessages = messagesForNextStep;
1075
+
1076
+ const prepareStepResult = await prepareStep?.({
1077
+ model,
1078
+ steps,
1079
+ stepNumber: steps.length,
1080
+ instructions: instructionsForNextStep,
1081
+ initialInstructions: initialPrompt.instructions,
1082
+ messages: stepInputMessages,
1083
+ initialMessages,
1084
+ responseMessages: accumulatedResponseMessages,
1085
+ ...(steeringMessages.length > 0
1086
+ ? { experimental_steeringMessages: steeringMessages }
1087
+ : {}),
1088
+ runtimeContext,
1089
+ toolsContext,
1090
+ experimental_sandbox: sandbox,
1091
+ });
1092
+
1093
+ const stepSandbox =
1094
+ prepareStepResult?.experimental_sandbox ?? sandbox;
1095
+
1096
+ const stepModel = resolveLanguageModel(
1097
+ prepareStepResult?.model ?? model,
1098
+ );
1099
+
1100
+ const stepInstructions =
1101
+ prepareStepResult?.instructions ??
1102
+ prepareStepResult?.system ??
1103
+ instructionsForNextStep;
1104
+
1105
+ runtimeContext =
1106
+ prepareStepResult?.runtimeContext ?? runtimeContext;
1107
+ toolsContext =
1108
+ prepareStepResult?.toolsContext ?? toolsContext;
1109
+
1110
+ const stepActiveTools = filterActiveTools({
1111
+ tools,
1112
+ activeTools: prepareStepResult?.activeTools ?? activeTools,
1113
+ });
1114
+ const {
1115
+ executionTools,
1116
+ modelTools: stepModelTools,
1117
+ toolCallerMessages,
1118
+ } = prepareToolsForToolCallers({
1119
+ tools: prepareToolSearch(stepActiveTools, {
1120
+ toolsContext,
1121
+ experimental_sandbox: stepSandbox,
1122
+ }),
1123
+ toolCallers: resolvedToolCallers,
1124
+ });
1125
+ const stepToolOrder =
1126
+ prepareStepResult?.toolOrder ?? toolOrder;
1127
+
1128
+ const stepTools = await prepareTools({
1129
+ tools: stepModelTools as ActiveToolSubset<
1130
+ TOOLS,
1131
+ ActiveTools<NoInfer<TOOLS>>
1132
+ >,
1133
+ toolOrder: stepToolOrder as ToolOrder<
1134
+ ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>
1135
+ >,
1136
+ // active tools context is a subset of the tools context, so we can cast to the unknown type
1137
+ toolsContext:
1138
+ toolsContext as unknown as InferToolSetContext<
1139
+ ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>
1140
+ >,
1141
+ experimental_sandbox: stepSandbox,
1142
+ });
1143
+
1144
+ const stepToolChoice = prepareToolChoice({
1145
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1146
+ });
1147
+ const stepExecutionTools =
1148
+ stepToolChoice.type === 'none' ? undefined : executionTools;
1149
+
1150
+ const stepMessages = appendToolCallerMessages({
1151
+ messages: prepareStepResult?.messages ?? stepInputMessages,
1152
+ toolCallerMessages,
1153
+ });
1154
+
1155
+ // steering messages are delivered when they are in the messages
1156
+ // that are sent to the model after prepareStep:
1157
+ stepSteeringMessages = [
1158
+ ...stepSteeringMessages,
1159
+ ...(
1160
+ steeringRun?.resolveTakenMessages({
1161
+ stepNumber,
1162
+ sentMessages: stepMessages,
1163
+ }) ?? []
1164
+ ).map(({ message }) => message),
1165
+ ];
1166
+
1167
+ const promptMessages = await convertToLanguageModelPrompt({
1168
+ prompt: {
1169
+ instructions: stepInstructions,
1170
+ messages: stepMessages,
1171
+ },
1172
+ supportedUrls: await stepModel.supportedUrls,
1173
+ download,
1174
+ abortSignal: mergedAbortSignal,
1175
+ provider: stepModel.provider.split('.')[0],
1176
+ });
1177
+
1178
+ const stepProviderOptions = mergeObjects(
1179
+ providerOptions,
1180
+ prepareStepResult?.providerOptions,
1181
+ );
1182
+
1183
+ const stepCallSettings = prepareStepCallSettings({
1184
+ callSettings,
1185
+ stepSettings: prepareStepResult,
1186
+ });
1187
+
1188
+ const stepStartEvent = {
1189
+ callId,
1190
+ provider: stepModel.provider,
1191
+ modelId: stepModel.modelId,
1192
+ stepNumber,
1193
+ instructions: stepInstructions,
1194
+ messages: stepMessages,
1195
+ tools,
1196
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1197
+ activeTools: prepareStepResult?.activeTools ?? activeTools,
1198
+ toolOrder: stepToolOrder,
1199
+ steps: [...steps],
1200
+ providerOptions: stepProviderOptions,
1201
+ output,
1202
+ runtimeContext,
1203
+ promptMessages,
1204
+ stepTools,
1205
+ stepToolChoice,
1206
+ toolsContext,
1207
+ };
1208
+
1209
+ if (!hasNotifiedStepStart) {
1210
+ hasNotifiedStepStart = true;
1211
+ await notify({
1212
+ event: stepStartEvent,
1213
+ callbacks: [
1214
+ resolvedOnStepStart,
1215
+ telemetryDispatcher.onStepStart,
1216
+ ],
1217
+ });
1218
+ }
1219
+
1220
+ openStep = stepStartEvent;
1221
+
1222
+ const languageModelCallContext = {
1223
+ provider: stepModel.provider,
1224
+ modelId: stepModel.modelId,
1225
+ instructions: stepInstructions,
1226
+ messages: stepMessages,
1227
+ tools: stepTools,
1228
+ ...stepCallSettings,
1229
+ };
1230
+ const languageModelCallStartEvent = {
1231
+ callId,
1232
+ ...languageModelCallContext,
1233
+ };
1234
+
1235
+ const stepStartTimestampMs = now();
1236
+
1237
+ await notify({
1238
+ event: languageModelCallStartEvent,
1239
+ callbacks: [
1240
+ resolvedOnLanguageModelCallStart,
1241
+ telemetryDispatcher.onLanguageModelCallStart as
1242
+ | undefined
1243
+ | OnLanguageModelCallStartCallback,
1244
+ ],
1245
+ });
1246
+
1247
+ const executeLanguageModelCallInTelemetryContext =
1248
+ telemetryDispatcher.executeLanguageModelCall ??
1249
+ (async <T>({
1250
+ execute,
1251
+ }: {
1252
+ execute: () => PromiseLike<T>;
1253
+ }) => await execute());
1254
+
1255
+ const interruptController =
1256
+ steeringRun == null ? undefined : new AbortController();
1257
+ const stopWatchingInterrupt = steeringRun?.watchInterrupt(
1258
+ () => interruptController?.abort(),
1259
+ );
1260
+ const modelCallAbortSignal = mergeAbortSignals(
1261
+ mergedAbortSignal,
1262
+ interruptController?.signal,
1263
+ );
1264
+
1265
+ try {
1266
+ currentModelResponse = await retry(async () => {
1267
+ const result =
1268
+ await executeLanguageModelCallInTelemetryContext({
1269
+ ...languageModelCallStartEvent,
1270
+ execute: async () => {
1271
+ const result = await stepModel.doGenerate({
1272
+ ...stepCallSettings,
1273
+ tools: stepTools,
1274
+ toolChoice: stepToolChoice,
1275
+ responseFormat: await output?.responseFormat,
1276
+ prompt: promptMessages,
1277
+ providerOptions: stepProviderOptions,
1278
+ abortSignal: modelCallAbortSignal,
1279
+ headers: headersWithUserAgent,
1280
+ });
1281
+ return {
1282
+ ...result,
1283
+ ...(result.request && {
1284
+ request: sanitizeRequestMetadata(
1285
+ result.request,
1286
+ ),
1287
+ }),
1288
+ };
1289
+ },
1290
+ });
1291
+
1230
1292
  return {
1231
1293
  ...result,
1232
- ...(result.request && {
1233
- request: sanitizeRequestMetadata(result.request),
1234
- }),
1294
+ response: {
1295
+ id: result.response?.id ?? generateId(),
1296
+ timestamp: result.response?.timestamp ?? new Date(),
1297
+ modelId:
1298
+ result.response?.modelId ?? stepModel.modelId,
1299
+ headers: result.response?.headers,
1300
+ body: result.response?.body,
1301
+ },
1235
1302
  };
1303
+ });
1304
+ } catch (error) {
1305
+ if (interruptController?.signal.aborted === true) {
1306
+ // A caller abort or a timeout wins over an interrupt: the
1307
+ // run ends instead of making the model call again.
1308
+ if (mergedAbortSignal?.aborted === true) {
1309
+ throw mergedAbortSignal.reason;
1310
+ }
1311
+ throw new InterruptedStepAttempt();
1312
+ }
1313
+ throw error;
1314
+ } finally {
1315
+ stopWatchingInterrupt?.();
1316
+ }
1317
+ const responseTimeMs = now() - stepStartTimestampMs;
1318
+ const stepUsage = asLanguageModelUsage(
1319
+ currentModelResponse.usage,
1320
+ );
1321
+
1322
+ // parse tool calls:
1323
+ const stepToolCalls: TypedToolCall<TOOLS>[] =
1324
+ await Promise.all(
1325
+ currentModelResponse.content
1326
+ .filter(
1327
+ (part): part is LanguageModelV4ToolCall =>
1328
+ part.type === 'tool-call',
1329
+ )
1330
+ .map(toolCall =>
1331
+ parseToolCall({
1332
+ toolCall,
1333
+ tools: stepModelTools as TOOLS,
1334
+ // tool calls are rejected with tool choice none,
1335
+ // so user callbacks must not process them:
1336
+ repairToolCall:
1337
+ stepToolChoice.type === 'none'
1338
+ ? undefined
1339
+ : repairToolCall,
1340
+ refineToolInput:
1341
+ stepToolChoice.type === 'none'
1342
+ ? undefined
1343
+ : refineToolInput,
1344
+ instructions: stepInstructions,
1345
+ messages: stepMessages,
1346
+ abortSignal: mergedAbortSignal,
1347
+ }),
1348
+ ),
1349
+ );
1350
+
1351
+ const toolApprovalRequests: Record<
1352
+ string,
1353
+ ToolApprovalRequestOutput<TOOLS>
1354
+ > = {};
1355
+ const stepToolApprovalResponses: Record<
1356
+ string,
1357
+ ToolApprovalResponseOutput<TOOLS>
1358
+ > = {};
1359
+ const blockedToolCallIds = new Set<string>();
1360
+
1361
+ const generatedFileDataCache: Parameters<
1362
+ typeof convertLanguageModelContent
1363
+ >[0]['generatedFileDataCache'] = new WeakMap();
1364
+ const modelCallContent = await convertLanguageModelContent({
1365
+ content: currentModelResponse.content,
1366
+ toolCalls: stepToolCalls,
1367
+ toolOutputs: [],
1368
+ toolApprovalRequests: [],
1369
+ toolApprovalResponses: [],
1370
+ tools,
1371
+ download,
1372
+ abortSignal: mergedAbortSignal,
1373
+ generatedFileDataCache,
1374
+ });
1375
+
1376
+ await notify({
1377
+ event: {
1378
+ callId,
1379
+ provider: stepModel.provider,
1380
+ modelId: currentModelResponse.response.modelId,
1381
+ finishReason: currentModelResponse.finishReason.unified,
1382
+ usage: stepUsage,
1383
+ content: modelCallContent,
1384
+ responseId: currentModelResponse.response.id,
1385
+ ...(currentModelResponse.request?.url != null
1386
+ ? {
1387
+ request: {
1388
+ url: getRequestOrigin(
1389
+ currentModelResponse.request.url,
1390
+ ),
1391
+ },
1392
+ }
1393
+ : {}),
1394
+ ...(currentModelResponse.providerMetadata != null
1395
+ ? {
1396
+ providerMetadata:
1397
+ currentModelResponse.providerMetadata,
1398
+ }
1399
+ : {}),
1400
+ performance: {
1401
+ responseTimeMs,
1402
+ effectiveOutputTokensPerSecond:
1403
+ calculateTokensPerSecond({
1404
+ tokens: stepUsage.outputTokens,
1405
+ durationMs: responseTimeMs,
1406
+ }),
1407
+ outputTokensPerSecond: undefined,
1408
+ inputTokensPerSecond: undefined,
1409
+ effectiveTotalTokensPerSecond: calculateTokensPerSecond(
1410
+ {
1411
+ tokens: sumTokenCounts(
1412
+ stepUsage.inputTokens,
1413
+ stepUsage.outputTokens,
1414
+ ),
1415
+ durationMs: responseTimeMs,
1416
+ },
1417
+ ),
1418
+ timeToFirstOutputMs: undefined,
1419
+ },
1236
1420
  },
1237
- },
1238
- );
1239
-
1240
- return {
1241
- ...result,
1242
- response: {
1243
- id: result.response?.id ?? generateId(),
1244
- timestamp: result.response?.timestamp ?? new Date(),
1245
- modelId: result.response?.modelId ?? stepModel.modelId,
1246
- headers: result.response?.headers,
1247
- body: result.response?.body,
1248
- },
1249
- };
1250
- });
1251
- const responseTimeMs = now() - stepStartTimestampMs;
1252
- const stepUsage = asLanguageModelUsage(
1253
- currentModelResponse.usage,
1254
- );
1255
-
1256
- // parse tool calls:
1257
- const stepToolCalls: TypedToolCall<TOOLS>[] = await Promise.all(
1258
- currentModelResponse.content
1259
- .filter(
1260
- (part): part is LanguageModelV4ToolCall =>
1261
- part.type === 'tool-call',
1262
- )
1263
- .map(toolCall =>
1264
- parseToolCall({
1421
+ callbacks: [
1422
+ resolvedOnLanguageModelCallEnd,
1423
+ telemetryDispatcher.onLanguageModelCallEnd as
1424
+ | undefined
1425
+ | OnLanguageModelCallEndCallback<TOOLS>,
1426
+ ],
1427
+ });
1428
+
1429
+ const enforcedToolChoice =
1430
+ stepToolChoice.type === 'auto' ? undefined : stepToolChoice;
1431
+
1432
+ if (
1433
+ enforcedToolChoice != null &&
1434
+ (enforcedToolChoice.type === 'none'
1435
+ ? stepToolCalls.length > 0
1436
+ : currentModelResponse.finishReason.unified !==
1437
+ 'interrupted' &&
1438
+ !stepToolCalls.some(
1439
+ toolCall =>
1440
+ enforcedToolChoice.type === 'required' ||
1441
+ toolCall.toolName === enforcedToolChoice.toolName,
1442
+ ))
1443
+ ) {
1444
+ throw new ToolChoiceViolationError({
1445
+ toolChoice: enforcedToolChoice,
1446
+ finishReason: currentModelResponse.finishReason.unified,
1447
+ provider: stepModel.provider,
1448
+ modelId: stepModel.modelId,
1449
+ content: currentModelResponse.content,
1450
+ });
1451
+ }
1452
+
1453
+ // notify the tools that the tool calls are available:
1454
+ for (const toolCall of stepToolCalls) {
1455
+ if (toolCall.invalid) {
1456
+ continue; // ignore invalid tool calls
1457
+ }
1458
+
1459
+ const tool = getOwn(stepExecutionTools, toolCall.toolName);
1460
+
1461
+ if (tool == null) {
1462
+ // ignore tool calls for tools that are not available,
1463
+ // e.g. provider-executed dynamic tools
1464
+ continue;
1465
+ }
1466
+
1467
+ if (
1468
+ tool.onInputStart != null ||
1469
+ tool.onInputAvailable != null
1470
+ ) {
1471
+ const context = await validateToolContext({
1472
+ toolName: toolCall.toolName,
1473
+ context: getOwn(toolsContext, toolCall.toolName),
1474
+ contextSchema: tool.contextSchema,
1475
+ });
1476
+
1477
+ if (tool.onInputStart != null) {
1478
+ await tool.onInputStart({
1479
+ toolCallId: toolCall.toolCallId,
1480
+ messages: stepMessages,
1481
+ abortSignal: mergedAbortSignal,
1482
+ context,
1483
+ });
1484
+ }
1485
+
1486
+ if (tool.onInputAvailable != null) {
1487
+ await tool.onInputAvailable({
1488
+ input: toolCall.input,
1489
+ toolCallId: toolCall.toolCallId,
1490
+ messages: stepMessages,
1491
+ abortSignal: mergedAbortSignal,
1492
+ context,
1493
+ });
1494
+ }
1495
+ }
1496
+
1497
+ const toolApprovalStatus = await resolveToolApproval({
1498
+ tools: stepExecutionTools as TOOLS,
1499
+ toolApproval,
1265
1500
  toolCall,
1266
- tools: stepModelTools as TOOLS,
1267
- // tool calls are rejected with tool choice none,
1268
- // so user callbacks must not process them:
1269
- repairToolCall:
1270
- stepToolChoice.type === 'none'
1271
- ? undefined
1272
- : repairToolCall,
1273
- refineToolInput:
1274
- stepToolChoice.type === 'none'
1275
- ? undefined
1276
- : refineToolInput,
1277
- instructions: stepInstructions,
1278
1501
  messages: stepMessages,
1279
- abortSignal: mergedAbortSignal,
1280
- }),
1281
- ),
1282
- );
1283
-
1284
- const toolApprovalRequests: Record<
1285
- string,
1286
- ToolApprovalRequestOutput<TOOLS>
1287
- > = {};
1288
- const stepToolApprovalResponses: Record<
1289
- string,
1290
- ToolApprovalResponseOutput<TOOLS>
1291
- > = {};
1292
- const blockedToolCallIds = new Set<string>();
1293
-
1294
- const generatedFileDataCache: Parameters<
1295
- typeof convertLanguageModelContent
1296
- >[0]['generatedFileDataCache'] = new WeakMap();
1297
- const modelCallContent = await convertLanguageModelContent({
1298
- content: currentModelResponse.content,
1299
- toolCalls: stepToolCalls,
1300
- toolOutputs: [],
1301
- toolApprovalRequests: [],
1302
- toolApprovalResponses: [],
1303
- tools,
1304
- download,
1305
- abortSignal: mergedAbortSignal,
1306
- generatedFileDataCache,
1307
- });
1308
-
1309
- await notify({
1310
- event: {
1311
- callId,
1312
- provider: stepModel.provider,
1313
- modelId: currentModelResponse.response.modelId,
1314
- finishReason: currentModelResponse.finishReason.unified,
1315
- usage: stepUsage,
1316
- content: modelCallContent,
1317
- responseId: currentModelResponse.response.id,
1318
- ...(currentModelResponse.request?.url != null
1319
- ? {
1320
- request: {
1321
- url: getRequestOrigin(
1322
- currentModelResponse.request.url,
1323
- ),
1324
- },
1502
+ toolsContext,
1503
+ runtimeContext,
1504
+ });
1505
+
1506
+ // Tools that don't require approval ('not-applicable') must not
1507
+ // consume an approval id, so that id generation stays stable for
1508
+ // callers that rely on deterministic id sequences.
1509
+ if (toolApprovalStatus.type === 'not-applicable') {
1510
+ continue;
1511
+ }
1512
+
1513
+ const approvalId = generateId();
1514
+ const signature = await maybeSignApproval({
1515
+ secret: experimental_toolApprovalSecret,
1516
+ approvalId,
1517
+ toolCallId: toolCall.toolCallId,
1518
+ toolName: toolCall.toolName,
1519
+ input: toolCall.input,
1520
+ });
1521
+
1522
+ switch (toolApprovalStatus.type) {
1523
+ case 'user-approval': {
1524
+ toolApprovalRequests[toolCall.toolCallId] = {
1525
+ type: 'tool-approval-request',
1526
+ approvalId,
1527
+ toolCall,
1528
+ ...(toolApprovalStatus.reason != null
1529
+ ? { reason: toolApprovalStatus.reason }
1530
+ : {}),
1531
+ ...(signature != null ? { signature } : {}),
1532
+ };
1533
+ blockedToolCallIds.add(toolCall.toolCallId);
1534
+ break;
1325
1535
  }
1326
- : {}),
1327
- ...(currentModelResponse.providerMetadata != null
1328
- ? {
1329
- providerMetadata: currentModelResponse.providerMetadata,
1536
+
1537
+ case 'approved': {
1538
+ toolApprovalRequests[toolCall.toolCallId] = {
1539
+ type: 'tool-approval-request',
1540
+ approvalId,
1541
+ toolCall,
1542
+ isAutomatic: true,
1543
+ ...(signature != null ? { signature } : {}),
1544
+ };
1545
+ stepToolApprovalResponses[toolCall.toolCallId] = {
1546
+ type: 'tool-approval-response',
1547
+ approvalId,
1548
+ toolCall,
1549
+ approved: true,
1550
+ reason: toolApprovalStatus.reason,
1551
+ providerExecuted: toolCall.providerExecuted,
1552
+ };
1553
+ break;
1330
1554
  }
1331
- : {}),
1332
- performance: {
1333
- responseTimeMs,
1555
+
1556
+ case 'denied': {
1557
+ toolApprovalRequests[toolCall.toolCallId] = {
1558
+ type: 'tool-approval-request',
1559
+ approvalId,
1560
+ toolCall,
1561
+ isAutomatic: true,
1562
+ ...(signature != null ? { signature } : {}),
1563
+ };
1564
+ stepToolApprovalResponses[toolCall.toolCallId] = {
1565
+ type: 'tool-approval-response',
1566
+ approvalId,
1567
+ toolCall,
1568
+ approved: false,
1569
+ reason: toolApprovalStatus.reason,
1570
+ providerExecuted: toolCall.providerExecuted,
1571
+ };
1572
+ blockedToolCallIds.add(toolCall.toolCallId);
1573
+ break;
1574
+ }
1575
+ }
1576
+ }
1577
+
1578
+ // insert error tool outputs for invalid tool calls:
1579
+ // TODO AI SDK 6: invalid inputs should not require output parts
1580
+ const invalidToolCalls = stepToolCalls.filter(
1581
+ toolCall =>
1582
+ toolCall.invalid &&
1583
+ toolCall.dynamic &&
1584
+ !toolCall.providerExecuted,
1585
+ );
1586
+
1587
+ clientToolOutputs = [];
1588
+
1589
+ for (const toolCall of invalidToolCalls) {
1590
+ clientToolOutputs.push({
1591
+ type: 'tool-error',
1592
+ toolCallId: toolCall.toolCallId,
1593
+ toolName: toolCall.toolName,
1594
+ input: toolCall.input,
1595
+ error: getErrorMessage(toolCall.error!),
1596
+ dynamic: true,
1597
+ });
1598
+ }
1599
+
1600
+ // execute client tool calls:
1601
+ clientToolCalls = stepToolCalls.filter(
1602
+ toolCall => !toolCall.providerExecuted,
1603
+ );
1604
+ toolApprovalResponses = Object.values(
1605
+ stepToolApprovalResponses,
1606
+ );
1607
+ deniedToolApprovalResponses = toolApprovalResponses.filter(
1608
+ toolApprovalResponse =>
1609
+ toolApprovalResponse.approved === false,
1610
+ );
1611
+ const toolExecutionMs: Record<string, number> = {};
1612
+
1613
+ if (
1614
+ stepExecutionTools != null &&
1615
+ isToolExecutionAllowedFinishReason(
1616
+ currentModelResponse.finishReason.unified,
1617
+ )
1618
+ ) {
1619
+ const toolExecutionResults = await executeTools({
1620
+ toolCalls: clientToolCalls.filter(
1621
+ toolCall =>
1622
+ !toolCall.invalid &&
1623
+ !blockedToolCallIds.has(toolCall.toolCallId),
1624
+ ),
1625
+ tools: stepExecutionTools as TOOLS,
1626
+ callId,
1627
+ messages: stepMessages,
1628
+ abortSignal: mergedAbortSignal,
1629
+ timeout,
1630
+ experimental_sandbox: stepSandbox,
1631
+ toolsContext,
1632
+ onToolExecutionStart: event =>
1633
+ notify({
1634
+ event,
1635
+ callbacks: [
1636
+ resolvedOnToolExecutionStart,
1637
+ telemetryDispatcher.onToolExecutionStart,
1638
+ ],
1639
+ }),
1640
+ onToolExecutionEnd: event =>
1641
+ notify({
1642
+ event,
1643
+ callbacks: [
1644
+ resolvedOnToolExecutionEnd,
1645
+ telemetryDispatcher.onToolExecutionEnd,
1646
+ ],
1647
+ }),
1648
+ executeToolInTelemetryContext:
1649
+ telemetryDispatcher.executeTool,
1650
+ runInTracingChannelSpan,
1651
+ toolCallConcurrency: resolvedToolCallConcurrency,
1652
+ });
1653
+
1654
+ for (const result of toolExecutionResults) {
1655
+ toolExecutionMs[result.output.toolCallId] =
1656
+ result.toolExecutionMs;
1657
+ clientToolOutputs.push(result.output);
1658
+ }
1659
+ }
1660
+
1661
+ const stepTimeMs = now() - stepStartTimestampMs;
1662
+ const stepPerformance: StepResultPerformance = {
1334
1663
  effectiveOutputTokensPerSecond: calculateTokensPerSecond({
1335
1664
  tokens: stepUsage.outputTokens,
1336
1665
  durationMs: responseTimeMs,
@@ -1344,376 +1673,132 @@ async function generateTextInternal<
1344
1673
  ),
1345
1674
  durationMs: responseTimeMs,
1346
1675
  }),
1676
+ stepTimeMs,
1677
+ responseTimeMs,
1678
+ toolExecutionMs,
1347
1679
  timeToFirstOutputMs: undefined,
1348
- },
1349
- },
1350
- callbacks: [
1351
- resolvedOnLanguageModelCallEnd,
1352
- telemetryDispatcher.onLanguageModelCallEnd as
1353
- | undefined
1354
- | OnLanguageModelCallEndCallback<TOOLS>,
1355
- ],
1356
- });
1357
-
1358
- const enforcedToolChoice =
1359
- stepToolChoice.type === 'auto' ? undefined : stepToolChoice;
1360
-
1361
- if (
1362
- enforcedToolChoice != null &&
1363
- (enforcedToolChoice.type === 'none'
1364
- ? stepToolCalls.length > 0
1365
- : currentModelResponse.finishReason.unified !==
1366
- 'interrupted' &&
1367
- !stepToolCalls.some(
1368
- toolCall =>
1369
- enforcedToolChoice.type === 'required' ||
1370
- toolCall.toolName === enforcedToolChoice.toolName,
1371
- ))
1372
- ) {
1373
- throw new ToolChoiceViolationError({
1374
- toolChoice: enforcedToolChoice,
1375
- finishReason: currentModelResponse.finishReason.unified,
1376
- provider: stepModel.provider,
1377
- modelId: stepModel.modelId,
1378
- content: currentModelResponse.content,
1379
- });
1380
- }
1381
-
1382
- // notify the tools that the tool calls are available:
1383
- for (const toolCall of stepToolCalls) {
1384
- if (toolCall.invalid) {
1385
- continue; // ignore invalid tool calls
1386
- }
1387
-
1388
- const tool = getOwn(stepExecutionTools, toolCall.toolName);
1389
-
1390
- if (tool == null) {
1391
- // ignore tool calls for tools that are not available,
1392
- // e.g. provider-executed dynamic tools
1393
- continue;
1394
- }
1395
-
1396
- if (
1397
- tool.onInputStart != null ||
1398
- tool.onInputAvailable != null
1399
- ) {
1400
- const context = await validateToolContext({
1401
- toolName: toolCall.toolName,
1402
- context: getOwn(toolsContext, toolCall.toolName),
1403
- contextSchema: tool.contextSchema,
1404
- });
1405
-
1406
- if (tool.onInputStart != null) {
1407
- await tool.onInputStart({
1408
- toolCallId: toolCall.toolCallId,
1409
- messages: stepMessages,
1410
- abortSignal: mergedAbortSignal,
1411
- context,
1412
- });
1680
+ };
1681
+
1682
+ // Track provider-executed tool calls that support deferred results.
1683
+ // In programmatic tool calling, a server tool (e.g., code_execution) may
1684
+ // trigger a client tool, and the server tool's result is deferred until
1685
+ // the client tool's result is sent back.
1686
+ for (const toolCall of stepToolCalls) {
1687
+ if (!toolCall.providerExecuted) continue;
1688
+ const tool = getOwn(stepExecutionTools, toolCall.toolName);
1689
+ if (
1690
+ tool?.type === 'provider' &&
1691
+ tool.supportsDeferredResults
1692
+ ) {
1693
+ // Check if this tool call already has a result in the current response
1694
+ const hasResultInResponse =
1695
+ currentModelResponse.content.some(
1696
+ part =>
1697
+ part.type === 'tool-result' &&
1698
+ part.toolCallId === toolCall.toolCallId,
1699
+ );
1700
+ if (!hasResultInResponse) {
1701
+ pendingDeferredToolCalls.set(toolCall.toolCallId, {
1702
+ toolName: toolCall.toolName,
1703
+ });
1704
+ }
1705
+ }
1413
1706
  }
1414
1707
 
1415
- if (tool.onInputAvailable != null) {
1416
- await tool.onInputAvailable({
1417
- input: toolCall.input,
1418
- toolCallId: toolCall.toolCallId,
1419
- messages: stepMessages,
1420
- abortSignal: mergedAbortSignal,
1421
- context,
1422
- });
1423
- }
1424
- }
1425
-
1426
- const toolApprovalStatus = await resolveToolApproval({
1427
- tools: stepExecutionTools as TOOLS,
1428
- toolApproval,
1429
- toolCall,
1430
- messages: stepMessages,
1431
- toolsContext,
1432
- runtimeContext,
1433
- });
1434
-
1435
- // Tools that don't require approval ('not-applicable') must not
1436
- // consume an approval id, so that id generation stays stable for
1437
- // callers that rely on deterministic id sequences.
1438
- if (toolApprovalStatus.type === 'not-applicable') {
1439
- continue;
1440
- }
1441
-
1442
- const approvalId = generateId();
1443
- const signature = await maybeSignApproval({
1444
- secret: experimental_toolApprovalSecret,
1445
- approvalId,
1446
- toolCallId: toolCall.toolCallId,
1447
- toolName: toolCall.toolName,
1448
- input: toolCall.input,
1449
- });
1450
-
1451
- switch (toolApprovalStatus.type) {
1452
- case 'user-approval': {
1453
- toolApprovalRequests[toolCall.toolCallId] = {
1454
- type: 'tool-approval-request',
1455
- approvalId,
1456
- toolCall,
1457
- ...(toolApprovalStatus.reason != null
1458
- ? { reason: toolApprovalStatus.reason }
1459
- : {}),
1460
- ...(signature != null ? { signature } : {}),
1461
- };
1462
- blockedToolCallIds.add(toolCall.toolCallId);
1463
- break;
1708
+ // Mark deferred tool calls as resolved when we receive their results
1709
+ for (const part of currentModelResponse.content) {
1710
+ if (part.type === 'tool-result') {
1711
+ pendingDeferredToolCalls.delete(part.toolCallId);
1712
+ }
1464
1713
  }
1465
1714
 
1466
- case 'approved': {
1467
- toolApprovalRequests[toolCall.toolCallId] = {
1468
- type: 'tool-approval-request',
1469
- approvalId,
1470
- toolCall,
1471
- isAutomatic: true,
1472
- ...(signature != null ? { signature } : {}),
1473
- };
1474
- stepToolApprovalResponses[toolCall.toolCallId] = {
1475
- type: 'tool-approval-response',
1476
- approvalId,
1477
- toolCall,
1478
- approved: true,
1479
- reason: toolApprovalStatus.reason,
1480
- providerExecuted: toolCall.providerExecuted,
1481
- };
1482
- break;
1483
- }
1715
+ // content:
1716
+ const stepContent = await convertLanguageModelContent({
1717
+ content: currentModelResponse.content,
1718
+ toolCalls: stepToolCalls,
1719
+ toolOutputs: clientToolOutputs,
1720
+ toolApprovalRequests: Object.values(toolApprovalRequests),
1721
+ toolApprovalResponses,
1722
+ tools,
1723
+ download,
1724
+ abortSignal: mergedAbortSignal,
1725
+ generatedFileDataCache,
1726
+ });
1484
1727
 
1485
- case 'denied': {
1486
- toolApprovalRequests[toolCall.toolCallId] = {
1487
- type: 'tool-approval-request',
1488
- approvalId,
1489
- toolCall,
1490
- isAutomatic: true,
1491
- ...(signature != null ? { signature } : {}),
1492
- };
1493
- stepToolApprovalResponses[toolCall.toolCallId] = {
1494
- type: 'tool-approval-response',
1495
- approvalId,
1496
- toolCall,
1497
- approved: false,
1498
- reason: toolApprovalStatus.reason,
1499
- providerExecuted: toolCall.providerExecuted,
1500
- };
1501
- blockedToolCallIds.add(toolCall.toolCallId);
1502
- break;
1503
- }
1504
- }
1505
- }
1506
-
1507
- // insert error tool outputs for invalid tool calls:
1508
- // TODO AI SDK 6: invalid inputs should not require output parts
1509
- const invalidToolCalls = stepToolCalls.filter(
1510
- toolCall =>
1511
- toolCall.invalid &&
1512
- toolCall.dynamic &&
1513
- !toolCall.providerExecuted,
1514
- );
1515
-
1516
- clientToolOutputs = [];
1517
-
1518
- for (const toolCall of invalidToolCalls) {
1519
- clientToolOutputs.push({
1520
- type: 'tool-error',
1521
- toolCallId: toolCall.toolCallId,
1522
- toolName: toolCall.toolName,
1523
- input: toolCall.input,
1524
- error: getErrorMessage(toolCall.error!),
1525
- dynamic: true,
1526
- });
1527
- }
1528
-
1529
- // execute client tool calls:
1530
- clientToolCalls = stepToolCalls.filter(
1531
- toolCall => !toolCall.providerExecuted,
1532
- );
1533
- toolApprovalResponses = Object.values(stepToolApprovalResponses);
1534
- deniedToolApprovalResponses = toolApprovalResponses.filter(
1535
- toolApprovalResponse => toolApprovalResponse.approved === false,
1536
- );
1537
- const toolExecutionMs: Record<string, number> = {};
1538
-
1539
- if (
1540
- stepExecutionTools != null &&
1541
- isToolExecutionAllowedFinishReason(
1542
- currentModelResponse.finishReason.unified,
1543
- )
1544
- ) {
1545
- const toolExecutionResults = await executeTools({
1546
- toolCalls: clientToolCalls.filter(
1547
- toolCall =>
1548
- !toolCall.invalid &&
1549
- !blockedToolCallIds.has(toolCall.toolCallId),
1550
- ),
1551
- tools: stepExecutionTools as TOOLS,
1552
- callId,
1553
- messages: stepMessages,
1554
- abortSignal: mergedAbortSignal,
1555
- timeout,
1556
- experimental_sandbox: stepSandbox,
1557
- toolsContext,
1558
- onToolExecutionStart: event =>
1559
- notify({
1560
- event,
1561
- callbacks: [
1562
- resolvedOnToolExecutionStart,
1563
- telemetryDispatcher.onToolExecutionStart,
1564
- ],
1565
- }),
1566
- onToolExecutionEnd: event =>
1567
- notify({
1568
- event,
1569
- callbacks: [
1570
- resolvedOnToolExecutionEnd,
1571
- telemetryDispatcher.onToolExecutionEnd,
1572
- ],
1573
- }),
1574
- executeToolInTelemetryContext:
1575
- telemetryDispatcher.executeTool,
1576
- runInTracingChannelSpan,
1577
- toolCallConcurrency: resolvedToolCallConcurrency,
1578
- });
1579
-
1580
- for (const result of toolExecutionResults) {
1581
- toolExecutionMs[result.output.toolCallId] =
1582
- result.toolExecutionMs;
1583
- clientToolOutputs.push(result.output);
1584
- }
1585
- }
1586
-
1587
- const stepTimeMs = now() - stepStartTimestampMs;
1588
- const stepPerformance: StepResultPerformance = {
1589
- effectiveOutputTokensPerSecond: calculateTokensPerSecond({
1590
- tokens: stepUsage.outputTokens,
1591
- durationMs: responseTimeMs,
1592
- }),
1593
- outputTokensPerSecond: undefined,
1594
- inputTokensPerSecond: undefined,
1595
- effectiveTotalTokensPerSecond: calculateTokensPerSecond({
1596
- tokens: sumTokenCounts(
1597
- stepUsage.inputTokens,
1598
- stepUsage.outputTokens,
1599
- ),
1600
- durationMs: responseTimeMs,
1601
- }),
1602
- stepTimeMs,
1603
- responseTimeMs,
1604
- toolExecutionMs,
1605
- timeToFirstOutputMs: undefined,
1606
- };
1607
-
1608
- // Track provider-executed tool calls that support deferred results.
1609
- // In programmatic tool calling, a server tool (e.g., code_execution) may
1610
- // trigger a client tool, and the server tool's result is deferred until
1611
- // the client tool's result is sent back.
1612
- for (const toolCall of stepToolCalls) {
1613
- if (!toolCall.providerExecuted) continue;
1614
- const tool = getOwn(stepExecutionTools, toolCall.toolName);
1615
- if (tool?.type === 'provider' && tool.supportsDeferredResults) {
1616
- // Check if this tool call already has a result in the current response
1617
- const hasResultInResponse = currentModelResponse.content.some(
1618
- part =>
1619
- part.type === 'tool-result' &&
1620
- part.toolCallId === toolCall.toolCallId,
1621
- );
1622
- if (!hasResultInResponse) {
1623
- pendingDeferredToolCalls.set(toolCall.toolCallId, {
1624
- toolName: toolCall.toolName,
1728
+ const stepResponseMessages = await toResponseMessages({
1729
+ content: stepContent,
1730
+ tools,
1731
+ });
1732
+
1733
+ // Add step information (after response messages are updated):
1734
+ // Conditionally include request.body and response.body based on include settings.
1735
+ // Large payloads (e.g., base64-encoded images) can cause memory issues.
1736
+ const stepRequest: LanguageModelRequestMetadata = {
1737
+ ...currentModelResponse.request,
1738
+ body: include.requestBody
1739
+ ? currentModelResponse.request?.body
1740
+ : undefined,
1741
+ messages: include.requestMessages
1742
+ ? cloneModelMessages(stepMessages)
1743
+ : undefined,
1744
+ };
1745
+
1746
+ const stepResponse = {
1747
+ ...currentModelResponse.response,
1748
+ // deep clone msgs to avoid mutating step results in multi-step:
1749
+ messages: cloneModelMessages(stepResponseMessages),
1750
+ // Conditionally include response body:
1751
+ body: include.responseBody
1752
+ ? currentModelResponse.response?.body
1753
+ : undefined,
1754
+ };
1755
+
1756
+ const currentStepResult: StepResult<TOOLS, RUNTIME_CONTEXT> =
1757
+ new DefaultStepResult({
1758
+ callId,
1759
+ stepNumber,
1760
+ provider: stepModel.provider,
1761
+ modelId: stepModel.modelId,
1762
+ runtimeContext,
1763
+ content: stepContent,
1764
+ finishReason: currentModelResponse.finishReason.unified,
1765
+ rawFinishReason: currentModelResponse.finishReason.raw,
1766
+ usage: stepUsage,
1767
+ performance: stepPerformance,
1768
+ warnings: currentModelResponse.warnings,
1769
+ providerMetadata: currentModelResponse.providerMetadata,
1770
+ request: stepRequest,
1771
+ response: stepResponse,
1772
+ toolsContext,
1773
+ steeringMessages: stepSteeringMessages,
1625
1774
  });
1626
- }
1627
- }
1628
- }
1629
-
1630
- // Mark deferred tool calls as resolved when we receive their results
1631
- for (const part of currentModelResponse.content) {
1632
- if (part.type === 'tool-result') {
1633
- pendingDeferredToolCalls.delete(part.toolCallId);
1634
- }
1635
- }
1636
-
1637
- // content:
1638
- const stepContent = await convertLanguageModelContent({
1639
- content: currentModelResponse.content,
1640
- toolCalls: stepToolCalls,
1641
- toolOutputs: clientToolOutputs,
1642
- toolApprovalRequests: Object.values(toolApprovalRequests),
1643
- toolApprovalResponses,
1644
- tools,
1645
- download,
1646
- abortSignal: mergedAbortSignal,
1647
- generatedFileDataCache,
1648
- });
1649
-
1650
- const stepResponseMessages = await toResponseMessages({
1651
- content: stepContent,
1652
- tools,
1653
- });
1654
-
1655
- // Add step information (after response messages are updated):
1656
- // Conditionally include request.body and response.body based on include settings.
1657
- // Large payloads (e.g., base64-encoded images) can cause memory issues.
1658
- const stepRequest: LanguageModelRequestMetadata = {
1659
- ...currentModelResponse.request,
1660
- body: include.requestBody
1661
- ? currentModelResponse.request?.body
1662
- : undefined,
1663
- messages: include.requestMessages
1664
- ? cloneModelMessages(stepMessages)
1665
- : undefined,
1666
- };
1667
-
1668
- const stepResponse = {
1669
- ...currentModelResponse.response,
1670
- // deep clone msgs to avoid mutating step results in multi-step:
1671
- messages: cloneModelMessages(stepResponseMessages),
1672
- // Conditionally include response body:
1673
- body: include.responseBody
1674
- ? currentModelResponse.response?.body
1675
- : undefined,
1676
- };
1677
-
1678
- const currentStepResult: StepResult<TOOLS, RUNTIME_CONTEXT> =
1679
- new DefaultStepResult({
1680
- callId,
1681
- stepNumber,
1682
- provider: stepModel.provider,
1683
- modelId: stepModel.modelId,
1684
- runtimeContext,
1685
- content: stepContent,
1686
- finishReason: currentModelResponse.finishReason.unified,
1687
- rawFinishReason: currentModelResponse.finishReason.raw,
1688
- usage: stepUsage,
1689
- performance: stepPerformance,
1690
- warnings: currentModelResponse.warnings,
1691
- providerMetadata: currentModelResponse.providerMetadata,
1692
- request: stepRequest,
1693
- response: stepResponse,
1694
- toolsContext,
1695
- steeringMessages: deliveredSteeringMessages,
1696
- });
1697
-
1698
- logWarnings({
1699
- warnings: currentModelResponse.warnings ?? [],
1700
- provider: stepModel.provider,
1701
- model: stepModel.modelId,
1702
- });
1703
-
1704
- steps.push(currentStepResult);
1705
- instructionsForNextStep = stepInstructions;
1706
- messagesForNextStep = [...stepMessages, ...stepResponseMessages];
1707
-
1708
- openStep = undefined;
1709
-
1710
- await notify({
1711
- event: currentStepResult,
1712
- callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd],
1713
- });
1714
-
1715
- return currentStepResult;
1716
- },
1775
+
1776
+ logWarnings({
1777
+ warnings: currentModelResponse.warnings ?? [],
1778
+ provider: stepModel.provider,
1779
+ model: stepModel.modelId,
1780
+ });
1781
+
1782
+ steps.push(currentStepResult);
1783
+ instructionsForNextStep = stepInstructions;
1784
+ messagesForNextStep = [
1785
+ ...stepMessages,
1786
+ ...stepResponseMessages,
1787
+ ];
1788
+
1789
+ openStep = undefined;
1790
+
1791
+ await notify({
1792
+ event: currentStepResult,
1793
+ callbacks: [
1794
+ resolvedOnStepEnd,
1795
+ telemetryDispatcher.onStepEnd,
1796
+ ],
1797
+ });
1798
+
1799
+ return currentStepResult;
1800
+ },
1801
+ }),
1717
1802
  });
1718
1803
  } finally {
1719
1804
  if (stepTimeoutId != null) {
@@ -1910,3 +1995,33 @@ async function executeTools<TOOLS extends ToolSet>({
1910
1995
  (result): result is NonNullable<typeof result> => result != null,
1911
1996
  );
1912
1997
  }
1998
+
1999
+ /**
2000
+ * Thrown inside a step attempt when a steering interrupt cancelled its model
2001
+ * call. It is not an error that callers see. It only ends the attempt so that
2002
+ * the step is made again.
2003
+ */
2004
+ class InterruptedStepAttempt {}
2005
+
2006
+ /**
2007
+ * Runs a step attempt, and runs it again for as long as steering interrupts
2008
+ * cancel its model call.
2009
+ */
2010
+ async function redoInterruptedStepAttempts<T>({
2011
+ attempt,
2012
+ onInterrupt,
2013
+ }: {
2014
+ attempt: () => Promise<T>;
2015
+ onInterrupt: () => void;
2016
+ }): Promise<T> {
2017
+ for (;;) {
2018
+ try {
2019
+ return await attempt();
2020
+ } catch (error) {
2021
+ if (!(error instanceof InterruptedStepAttempt)) {
2022
+ throw error;
2023
+ }
2024
+ onInterrupt();
2025
+ }
2026
+ }
2027
+ }