ai 7.0.175 → 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.
package/dist/index.js CHANGED
@@ -1265,7 +1265,7 @@ function cloneValue(value, seen) {
1265
1265
  }
1266
1266
  //#endregion
1267
1267
  //#region src/version.ts
1268
- const VERSION = "7.0.175";
1268
+ const VERSION = "7.0.177";
1269
1269
  //#endregion
1270
1270
  //#region src/util/download/download.ts
1271
1271
  /**
@@ -4890,13 +4890,26 @@ var DefaultSteering = class {
4890
4890
  this.queued = [];
4891
4891
  this.taken = [];
4892
4892
  this.outcomes = /* @__PURE__ */ new Map();
4893
+ this.interruptRequested = false;
4893
4894
  }
4894
4895
  steer(message, options) {
4895
- return this.add({
4896
+ const isNew = options?.id == null || !this.outcomes.has(options.id);
4897
+ const outcome = this.add({
4896
4898
  message,
4897
4899
  id: options?.id,
4898
4900
  target: this.pending
4899
4901
  });
4902
+ if (options?.interrupt === true && isNew) this.requestInterrupt();
4903
+ return outcome;
4904
+ }
4905
+ requestInterrupt() {
4906
+ const onInterrupt = this.onInterrupt;
4907
+ if (onInterrupt == null) {
4908
+ this.interruptRequested = true;
4909
+ return;
4910
+ }
4911
+ this.onInterrupt = void 0;
4912
+ onInterrupt();
4900
4913
  }
4901
4914
  queue(message, options) {
4902
4915
  return this.add({
@@ -4946,8 +4959,21 @@ var DefaultSteering = class {
4946
4959
  if (this.state !== "running") return [];
4947
4960
  this.taken = [...this.taken, ...this.pending];
4948
4961
  this.pending = [];
4962
+ this.interruptRequested = false;
4949
4963
  return this.taken.map(({ message }) => message);
4950
4964
  },
4965
+ watchInterrupt: (onInterrupt) => {
4966
+ if (this.state !== "running") return () => {};
4967
+ if (this.interruptRequested) {
4968
+ this.interruptRequested = false;
4969
+ onInterrupt();
4970
+ return () => {};
4971
+ }
4972
+ this.onInterrupt = onInterrupt;
4973
+ return () => {
4974
+ if (this.onInterrupt === onInterrupt) this.onInterrupt = void 0;
4975
+ };
4976
+ },
4951
4977
  resolveTakenMessages: ({ stepNumber, sentMessages }) => {
4952
4978
  const taken = this.taken;
4953
4979
  this.taken = [];
@@ -4985,6 +5011,8 @@ var DefaultSteering = class {
4985
5011
  this.pending = [];
4986
5012
  this.queued = [];
4987
5013
  this.state = "ended";
5014
+ this.interruptRequested = false;
5015
+ this.onInterrupt = void 0;
4988
5016
  for (const { id, message, resolve } of notDelivered) resolve({
4989
5017
  type: "not-delivered",
4990
5018
  id,
@@ -5820,8 +5848,12 @@ async function generateTextInternal({ model: modelArg, tools, toolChoice, instru
5820
5848
  timeoutMs: stepTimeoutMs
5821
5849
  });
5822
5850
  const stepNumber = steps.length;
5823
- const steeringMessages = steeringRun?.takeMessages() ?? [];
5851
+ let steeringMessages = steeringRun?.takeMessages() ?? [];
5824
5852
  if (steeringMessages.length > 0) messagesForNextStep = [...messagesForNextStep, ...steeringMessages];
5853
+ let stepSteeringMessages = [];
5854
+ let hasNotifiedStepStart = false;
5855
+ const stepStartRuntimeContext = runtimeContext;
5856
+ const stepStartToolsContext = toolsContext;
5825
5857
  try {
5826
5858
  await runInTracingChannelSpan({
5827
5859
  type: "step",
@@ -5829,419 +5861,444 @@ async function generateTextInternal({ model: modelArg, tools, toolChoice, instru
5829
5861
  callId,
5830
5862
  stepNumber
5831
5863
  },
5832
- execute: async () => {
5833
- const accumulatedResponseMessages = [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)];
5834
- const stepInputMessages = messagesForNextStep;
5835
- const prepareStepResult = await prepareStep?.({
5836
- model,
5837
- steps,
5838
- stepNumber: steps.length,
5839
- instructions: instructionsForNextStep,
5840
- initialInstructions: initialPrompt.instructions,
5841
- messages: stepInputMessages,
5842
- initialMessages,
5843
- responseMessages: accumulatedResponseMessages,
5844
- ...steeringMessages.length > 0 ? { experimental_steeringMessages: steeringMessages } : {},
5845
- runtimeContext,
5846
- toolsContext,
5847
- experimental_sandbox: sandbox
5848
- });
5849
- const stepSandbox = prepareStepResult?.experimental_sandbox ?? sandbox;
5850
- const stepModel = resolveLanguageModel(prepareStepResult?.model ?? model);
5851
- const stepInstructions = prepareStepResult?.instructions ?? prepareStepResult?.system ?? instructionsForNextStep;
5852
- runtimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;
5853
- toolsContext = prepareStepResult?.toolsContext ?? toolsContext;
5854
- const stepActiveTools = filterActiveTools({
5855
- tools,
5856
- activeTools: prepareStepResult?.activeTools ?? activeTools
5857
- });
5858
- const { executionTools, modelTools: stepModelTools, toolCallerMessages } = prepareToolsForToolCallers({
5859
- tools: prepareToolSearch(stepActiveTools, {
5864
+ execute: () => redoInterruptedStepAttempts({
5865
+ onInterrupt: () => {
5866
+ runtimeContext = stepStartRuntimeContext;
5867
+ toolsContext = stepStartToolsContext;
5868
+ const interruptMessages = steeringRun?.takeMessages() ?? [];
5869
+ steeringMessages = [...steeringMessages, ...interruptMessages];
5870
+ messagesForNextStep = [...messagesForNextStep, ...interruptMessages];
5871
+ },
5872
+ attempt: async () => {
5873
+ const accumulatedResponseMessages = [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)];
5874
+ const stepInputMessages = messagesForNextStep;
5875
+ const prepareStepResult = await prepareStep?.({
5876
+ model,
5877
+ steps,
5878
+ stepNumber: steps.length,
5879
+ instructions: instructionsForNextStep,
5880
+ initialInstructions: initialPrompt.instructions,
5881
+ messages: stepInputMessages,
5882
+ initialMessages,
5883
+ responseMessages: accumulatedResponseMessages,
5884
+ ...steeringMessages.length > 0 ? { experimental_steeringMessages: steeringMessages } : {},
5885
+ runtimeContext,
5886
+ toolsContext,
5887
+ experimental_sandbox: sandbox
5888
+ });
5889
+ const stepSandbox = prepareStepResult?.experimental_sandbox ?? sandbox;
5890
+ const stepModel = resolveLanguageModel(prepareStepResult?.model ?? model);
5891
+ const stepInstructions = prepareStepResult?.instructions ?? prepareStepResult?.system ?? instructionsForNextStep;
5892
+ runtimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;
5893
+ toolsContext = prepareStepResult?.toolsContext ?? toolsContext;
5894
+ const stepActiveTools = filterActiveTools({
5895
+ tools,
5896
+ activeTools: prepareStepResult?.activeTools ?? activeTools
5897
+ });
5898
+ const { executionTools, modelTools: stepModelTools, toolCallerMessages } = prepareToolsForToolCallers({
5899
+ tools: prepareToolSearch(stepActiveTools, {
5900
+ toolsContext,
5901
+ experimental_sandbox: stepSandbox
5902
+ }),
5903
+ toolCallers: resolvedToolCallers
5904
+ });
5905
+ const stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;
5906
+ const stepTools = await prepareTools({
5907
+ tools: stepModelTools,
5908
+ toolOrder: stepToolOrder,
5860
5909
  toolsContext,
5861
5910
  experimental_sandbox: stepSandbox
5862
- }),
5863
- toolCallers: resolvedToolCallers
5864
- });
5865
- const stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;
5866
- const stepTools = await prepareTools({
5867
- tools: stepModelTools,
5868
- toolOrder: stepToolOrder,
5869
- toolsContext,
5870
- experimental_sandbox: stepSandbox
5871
- });
5872
- const stepToolChoice = prepareToolChoice({ toolChoice: prepareStepResult?.toolChoice ?? toolChoice });
5873
- const stepExecutionTools = stepToolChoice.type === "none" ? void 0 : executionTools;
5874
- const stepMessages = appendToolCallerMessages({
5875
- messages: prepareStepResult?.messages ?? stepInputMessages,
5876
- toolCallerMessages
5877
- });
5878
- const deliveredSteeringMessages = (steeringRun?.resolveTakenMessages({
5879
- stepNumber,
5880
- sentMessages: stepMessages
5881
- }) ?? []).map(({ message }) => message);
5882
- const promptMessages = await convertToLanguageModelPrompt({
5883
- prompt: {
5911
+ });
5912
+ const stepToolChoice = prepareToolChoice({ toolChoice: prepareStepResult?.toolChoice ?? toolChoice });
5913
+ const stepExecutionTools = stepToolChoice.type === "none" ? void 0 : executionTools;
5914
+ const stepMessages = appendToolCallerMessages({
5915
+ messages: prepareStepResult?.messages ?? stepInputMessages,
5916
+ toolCallerMessages
5917
+ });
5918
+ stepSteeringMessages = [...stepSteeringMessages, ...(steeringRun?.resolveTakenMessages({
5919
+ stepNumber,
5920
+ sentMessages: stepMessages
5921
+ }) ?? []).map(({ message }) => message)];
5922
+ const promptMessages = await convertToLanguageModelPrompt({
5923
+ prompt: {
5924
+ instructions: stepInstructions,
5925
+ messages: stepMessages
5926
+ },
5927
+ supportedUrls: await stepModel.supportedUrls,
5928
+ download,
5929
+ abortSignal: mergedAbortSignal,
5930
+ provider: stepModel.provider.split(".")[0]
5931
+ });
5932
+ const stepProviderOptions = mergeObjects(providerOptions, prepareStepResult?.providerOptions);
5933
+ const stepCallSettings = prepareStepCallSettings({
5934
+ callSettings,
5935
+ stepSettings: prepareStepResult
5936
+ });
5937
+ const stepStartEvent = {
5938
+ callId,
5939
+ provider: stepModel.provider,
5940
+ modelId: stepModel.modelId,
5941
+ stepNumber,
5884
5942
  instructions: stepInstructions,
5885
- messages: stepMessages
5886
- },
5887
- supportedUrls: await stepModel.supportedUrls,
5888
- download,
5889
- abortSignal: mergedAbortSignal,
5890
- provider: stepModel.provider.split(".")[0]
5891
- });
5892
- const stepProviderOptions = mergeObjects(providerOptions, prepareStepResult?.providerOptions);
5893
- const stepCallSettings = prepareStepCallSettings({
5894
- callSettings,
5895
- stepSettings: prepareStepResult
5896
- });
5897
- const stepStartEvent = {
5898
- callId,
5899
- provider: stepModel.provider,
5900
- modelId: stepModel.modelId,
5901
- stepNumber,
5902
- instructions: stepInstructions,
5903
- messages: stepMessages,
5904
- tools,
5905
- toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
5906
- activeTools: prepareStepResult?.activeTools ?? activeTools,
5907
- toolOrder: stepToolOrder,
5908
- steps: [...steps],
5909
- providerOptions: stepProviderOptions,
5910
- output,
5911
- runtimeContext,
5912
- promptMessages,
5913
- stepTools,
5914
- stepToolChoice,
5915
- toolsContext
5916
- };
5917
- await notify({
5918
- event: stepStartEvent,
5919
- callbacks: [resolvedOnStepStart, telemetryDispatcher.onStepStart]
5920
- });
5921
- openStep = stepStartEvent;
5922
- const languageModelCallContext = {
5923
- provider: stepModel.provider,
5924
- modelId: stepModel.modelId,
5925
- instructions: stepInstructions,
5926
- messages: stepMessages,
5927
- tools: stepTools,
5928
- ...stepCallSettings
5929
- };
5930
- const languageModelCallStartEvent = {
5931
- callId,
5932
- ...languageModelCallContext
5933
- };
5934
- const stepStartTimestampMs = now$4();
5935
- await notify({
5936
- event: languageModelCallStartEvent,
5937
- callbacks: [resolvedOnLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart]
5938
- });
5939
- const executeLanguageModelCallInTelemetryContext = telemetryDispatcher.executeLanguageModelCall ?? (async ({ execute }) => await execute());
5940
- currentModelResponse = await retry(async () => {
5941
- const result = await executeLanguageModelCallInTelemetryContext({
5942
- ...languageModelCallStartEvent,
5943
- execute: async () => {
5944
- const result = await stepModel.doGenerate({
5945
- ...stepCallSettings,
5946
- tools: stepTools,
5947
- toolChoice: stepToolChoice,
5948
- responseFormat: await output?.responseFormat,
5949
- prompt: promptMessages,
5950
- providerOptions: stepProviderOptions,
5951
- abortSignal: mergedAbortSignal,
5952
- headers: headersWithUserAgent
5943
+ messages: stepMessages,
5944
+ tools,
5945
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
5946
+ activeTools: prepareStepResult?.activeTools ?? activeTools,
5947
+ toolOrder: stepToolOrder,
5948
+ steps: [...steps],
5949
+ providerOptions: stepProviderOptions,
5950
+ output,
5951
+ runtimeContext,
5952
+ promptMessages,
5953
+ stepTools,
5954
+ stepToolChoice,
5955
+ toolsContext
5956
+ };
5957
+ if (!hasNotifiedStepStart) {
5958
+ hasNotifiedStepStart = true;
5959
+ await notify({
5960
+ event: stepStartEvent,
5961
+ callbacks: [resolvedOnStepStart, telemetryDispatcher.onStepStart]
5962
+ });
5963
+ }
5964
+ openStep = stepStartEvent;
5965
+ const languageModelCallContext = {
5966
+ provider: stepModel.provider,
5967
+ modelId: stepModel.modelId,
5968
+ instructions: stepInstructions,
5969
+ messages: stepMessages,
5970
+ tools: stepTools,
5971
+ ...stepCallSettings
5972
+ };
5973
+ const languageModelCallStartEvent = {
5974
+ callId,
5975
+ ...languageModelCallContext
5976
+ };
5977
+ const stepStartTimestampMs = now$4();
5978
+ await notify({
5979
+ event: languageModelCallStartEvent,
5980
+ callbacks: [resolvedOnLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart]
5981
+ });
5982
+ const executeLanguageModelCallInTelemetryContext = telemetryDispatcher.executeLanguageModelCall ?? (async ({ execute }) => await execute());
5983
+ const interruptController = steeringRun == null ? void 0 : new AbortController();
5984
+ const stopWatchingInterrupt = steeringRun?.watchInterrupt(() => interruptController?.abort());
5985
+ const modelCallAbortSignal = mergeAbortSignals(mergedAbortSignal, interruptController?.signal);
5986
+ try {
5987
+ currentModelResponse = await retry(async () => {
5988
+ const result = await executeLanguageModelCallInTelemetryContext({
5989
+ ...languageModelCallStartEvent,
5990
+ execute: async () => {
5991
+ const result = await stepModel.doGenerate({
5992
+ ...stepCallSettings,
5993
+ tools: stepTools,
5994
+ toolChoice: stepToolChoice,
5995
+ responseFormat: await output?.responseFormat,
5996
+ prompt: promptMessages,
5997
+ providerOptions: stepProviderOptions,
5998
+ abortSignal: modelCallAbortSignal,
5999
+ headers: headersWithUserAgent
6000
+ });
6001
+ return {
6002
+ ...result,
6003
+ ...result.request && { request: sanitizeRequestMetadata(result.request) }
6004
+ };
6005
+ }
5953
6006
  });
5954
6007
  return {
5955
6008
  ...result,
5956
- ...result.request && { request: sanitizeRequestMetadata(result.request) }
6009
+ response: {
6010
+ id: result.response?.id ?? generateId(),
6011
+ timestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),
6012
+ modelId: result.response?.modelId ?? stepModel.modelId,
6013
+ headers: result.response?.headers,
6014
+ body: result.response?.body
6015
+ }
5957
6016
  };
6017
+ });
6018
+ } catch (error) {
6019
+ if (interruptController?.signal.aborted === true) {
6020
+ if (mergedAbortSignal?.aborted === true) throw mergedAbortSignal.reason;
6021
+ throw new InterruptedStepAttempt();
5958
6022
  }
6023
+ throw error;
6024
+ } finally {
6025
+ stopWatchingInterrupt?.();
6026
+ }
6027
+ const responseTimeMs = now$4() - stepStartTimestampMs;
6028
+ const stepUsage = asLanguageModelUsage(currentModelResponse.usage);
6029
+ const stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === "tool-call").map((toolCall) => parseToolCall({
6030
+ toolCall,
6031
+ tools: stepModelTools,
6032
+ repairToolCall: stepToolChoice.type === "none" ? void 0 : repairToolCall,
6033
+ refineToolInput: stepToolChoice.type === "none" ? void 0 : refineToolInput,
6034
+ instructions: stepInstructions,
6035
+ messages: stepMessages,
6036
+ abortSignal: mergedAbortSignal
6037
+ })));
6038
+ const toolApprovalRequests = {};
6039
+ const stepToolApprovalResponses = {};
6040
+ const blockedToolCallIds = /* @__PURE__ */ new Set();
6041
+ const generatedFileDataCache = /* @__PURE__ */ new WeakMap();
6042
+ const modelCallContent = await convertLanguageModelContent({
6043
+ content: currentModelResponse.content,
6044
+ toolCalls: stepToolCalls,
6045
+ toolOutputs: [],
6046
+ toolApprovalRequests: [],
6047
+ toolApprovalResponses: [],
6048
+ tools,
6049
+ download,
6050
+ abortSignal: mergedAbortSignal,
6051
+ generatedFileDataCache
5959
6052
  });
5960
- return {
5961
- ...result,
5962
- response: {
5963
- id: result.response?.id ?? generateId(),
5964
- timestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),
5965
- modelId: result.response?.modelId ?? stepModel.modelId,
5966
- headers: result.response?.headers,
5967
- body: result.response?.body
5968
- }
5969
- };
5970
- });
5971
- const responseTimeMs = now$4() - stepStartTimestampMs;
5972
- const stepUsage = asLanguageModelUsage(currentModelResponse.usage);
5973
- const stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === "tool-call").map((toolCall) => parseToolCall({
5974
- toolCall,
5975
- tools: stepModelTools,
5976
- repairToolCall: stepToolChoice.type === "none" ? void 0 : repairToolCall,
5977
- refineToolInput: stepToolChoice.type === "none" ? void 0 : refineToolInput,
5978
- instructions: stepInstructions,
5979
- messages: stepMessages,
5980
- abortSignal: mergedAbortSignal
5981
- })));
5982
- const toolApprovalRequests = {};
5983
- const stepToolApprovalResponses = {};
5984
- const blockedToolCallIds = /* @__PURE__ */ new Set();
5985
- const generatedFileDataCache = /* @__PURE__ */ new WeakMap();
5986
- const modelCallContent = await convertLanguageModelContent({
5987
- content: currentModelResponse.content,
5988
- toolCalls: stepToolCalls,
5989
- toolOutputs: [],
5990
- toolApprovalRequests: [],
5991
- toolApprovalResponses: [],
5992
- tools,
5993
- download,
5994
- abortSignal: mergedAbortSignal,
5995
- generatedFileDataCache
5996
- });
5997
- await notify({
5998
- event: {
5999
- callId,
6000
- provider: stepModel.provider,
6001
- modelId: currentModelResponse.response.modelId,
6053
+ await notify({
6054
+ event: {
6055
+ callId,
6056
+ provider: stepModel.provider,
6057
+ modelId: currentModelResponse.response.modelId,
6058
+ finishReason: currentModelResponse.finishReason.unified,
6059
+ usage: stepUsage,
6060
+ content: modelCallContent,
6061
+ responseId: currentModelResponse.response.id,
6062
+ ...currentModelResponse.request?.url != null ? { request: { url: getRequestOrigin(currentModelResponse.request.url) } } : {},
6063
+ ...currentModelResponse.providerMetadata != null ? { providerMetadata: currentModelResponse.providerMetadata } : {},
6064
+ performance: {
6065
+ responseTimeMs,
6066
+ effectiveOutputTokensPerSecond: calculateTokensPerSecond({
6067
+ tokens: stepUsage.outputTokens,
6068
+ durationMs: responseTimeMs
6069
+ }),
6070
+ outputTokensPerSecond: void 0,
6071
+ inputTokensPerSecond: void 0,
6072
+ effectiveTotalTokensPerSecond: calculateTokensPerSecond({
6073
+ tokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),
6074
+ durationMs: responseTimeMs
6075
+ }),
6076
+ timeToFirstOutputMs: void 0
6077
+ }
6078
+ },
6079
+ callbacks: [resolvedOnLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd]
6080
+ });
6081
+ const enforcedToolChoice = stepToolChoice.type === "auto" ? void 0 : stepToolChoice;
6082
+ if (enforcedToolChoice != null && (enforcedToolChoice.type === "none" ? stepToolCalls.length > 0 : currentModelResponse.finishReason.unified !== "interrupted" && !stepToolCalls.some((toolCall) => enforcedToolChoice.type === "required" || toolCall.toolName === enforcedToolChoice.toolName))) throw new ToolChoiceViolationError({
6083
+ toolChoice: enforcedToolChoice,
6002
6084
  finishReason: currentModelResponse.finishReason.unified,
6003
- usage: stepUsage,
6004
- content: modelCallContent,
6005
- responseId: currentModelResponse.response.id,
6006
- ...currentModelResponse.request?.url != null ? { request: { url: getRequestOrigin(currentModelResponse.request.url) } } : {},
6007
- ...currentModelResponse.providerMetadata != null ? { providerMetadata: currentModelResponse.providerMetadata } : {},
6008
- performance: {
6009
- responseTimeMs,
6010
- effectiveOutputTokensPerSecond: calculateTokensPerSecond({
6011
- tokens: stepUsage.outputTokens,
6012
- durationMs: responseTimeMs
6013
- }),
6014
- outputTokensPerSecond: void 0,
6015
- inputTokensPerSecond: void 0,
6016
- effectiveTotalTokensPerSecond: calculateTokensPerSecond({
6017
- tokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),
6018
- durationMs: responseTimeMs
6019
- }),
6020
- timeToFirstOutputMs: void 0
6085
+ provider: stepModel.provider,
6086
+ modelId: stepModel.modelId,
6087
+ content: currentModelResponse.content
6088
+ });
6089
+ for (const toolCall of stepToolCalls) {
6090
+ if (toolCall.invalid) continue;
6091
+ const tool = getOwn(stepExecutionTools, toolCall.toolName);
6092
+ if (tool == null) continue;
6093
+ if (tool.onInputStart != null || tool.onInputAvailable != null) {
6094
+ const context = await validateToolContext({
6095
+ toolName: toolCall.toolName,
6096
+ context: getOwn(toolsContext, toolCall.toolName),
6097
+ contextSchema: tool.contextSchema
6098
+ });
6099
+ if (tool.onInputStart != null) await tool.onInputStart({
6100
+ toolCallId: toolCall.toolCallId,
6101
+ messages: stepMessages,
6102
+ abortSignal: mergedAbortSignal,
6103
+ context
6104
+ });
6105
+ if (tool.onInputAvailable != null) await tool.onInputAvailable({
6106
+ input: toolCall.input,
6107
+ toolCallId: toolCall.toolCallId,
6108
+ messages: stepMessages,
6109
+ abortSignal: mergedAbortSignal,
6110
+ context
6111
+ });
6021
6112
  }
6022
- },
6023
- callbacks: [resolvedOnLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd]
6024
- });
6025
- const enforcedToolChoice = stepToolChoice.type === "auto" ? void 0 : stepToolChoice;
6026
- if (enforcedToolChoice != null && (enforcedToolChoice.type === "none" ? stepToolCalls.length > 0 : currentModelResponse.finishReason.unified !== "interrupted" && !stepToolCalls.some((toolCall) => enforcedToolChoice.type === "required" || toolCall.toolName === enforcedToolChoice.toolName))) throw new ToolChoiceViolationError({
6027
- toolChoice: enforcedToolChoice,
6028
- finishReason: currentModelResponse.finishReason.unified,
6029
- provider: stepModel.provider,
6030
- modelId: stepModel.modelId,
6031
- content: currentModelResponse.content
6032
- });
6033
- for (const toolCall of stepToolCalls) {
6034
- if (toolCall.invalid) continue;
6035
- const tool = getOwn(stepExecutionTools, toolCall.toolName);
6036
- if (tool == null) continue;
6037
- if (tool.onInputStart != null || tool.onInputAvailable != null) {
6038
- const context = await validateToolContext({
6039
- toolName: toolCall.toolName,
6040
- context: getOwn(toolsContext, toolCall.toolName),
6041
- contextSchema: tool.contextSchema
6042
- });
6043
- if (tool.onInputStart != null) await tool.onInputStart({
6044
- toolCallId: toolCall.toolCallId,
6113
+ const toolApprovalStatus = await resolveToolApproval({
6114
+ tools: stepExecutionTools,
6115
+ toolApproval,
6116
+ toolCall,
6045
6117
  messages: stepMessages,
6046
- abortSignal: mergedAbortSignal,
6047
- context
6118
+ toolsContext,
6119
+ runtimeContext
6048
6120
  });
6049
- if (tool.onInputAvailable != null) await tool.onInputAvailable({
6050
- input: toolCall.input,
6121
+ if (toolApprovalStatus.type === "not-applicable") continue;
6122
+ const approvalId = generateId();
6123
+ const signature = await maybeSignApproval({
6124
+ secret: experimental_toolApprovalSecret,
6125
+ approvalId,
6051
6126
  toolCallId: toolCall.toolCallId,
6052
- messages: stepMessages,
6053
- abortSignal: mergedAbortSignal,
6054
- context
6127
+ toolName: toolCall.toolName,
6128
+ input: toolCall.input
6055
6129
  });
6130
+ switch (toolApprovalStatus.type) {
6131
+ case "user-approval":
6132
+ toolApprovalRequests[toolCall.toolCallId] = {
6133
+ type: "tool-approval-request",
6134
+ approvalId,
6135
+ toolCall,
6136
+ ...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},
6137
+ ...signature != null ? { signature } : {}
6138
+ };
6139
+ blockedToolCallIds.add(toolCall.toolCallId);
6140
+ break;
6141
+ case "approved":
6142
+ toolApprovalRequests[toolCall.toolCallId] = {
6143
+ type: "tool-approval-request",
6144
+ approvalId,
6145
+ toolCall,
6146
+ isAutomatic: true,
6147
+ ...signature != null ? { signature } : {}
6148
+ };
6149
+ stepToolApprovalResponses[toolCall.toolCallId] = {
6150
+ type: "tool-approval-response",
6151
+ approvalId,
6152
+ toolCall,
6153
+ approved: true,
6154
+ reason: toolApprovalStatus.reason,
6155
+ providerExecuted: toolCall.providerExecuted
6156
+ };
6157
+ break;
6158
+ case "denied":
6159
+ toolApprovalRequests[toolCall.toolCallId] = {
6160
+ type: "tool-approval-request",
6161
+ approvalId,
6162
+ toolCall,
6163
+ isAutomatic: true,
6164
+ ...signature != null ? { signature } : {}
6165
+ };
6166
+ stepToolApprovalResponses[toolCall.toolCallId] = {
6167
+ type: "tool-approval-response",
6168
+ approvalId,
6169
+ toolCall,
6170
+ approved: false,
6171
+ reason: toolApprovalStatus.reason,
6172
+ providerExecuted: toolCall.providerExecuted
6173
+ };
6174
+ blockedToolCallIds.add(toolCall.toolCallId);
6175
+ }
6056
6176
  }
6057
- const toolApprovalStatus = await resolveToolApproval({
6058
- tools: stepExecutionTools,
6059
- toolApproval,
6060
- toolCall,
6061
- messages: stepMessages,
6062
- toolsContext,
6063
- runtimeContext
6064
- });
6065
- if (toolApprovalStatus.type === "not-applicable") continue;
6066
- const approvalId = generateId();
6067
- const signature = await maybeSignApproval({
6068
- secret: experimental_toolApprovalSecret,
6069
- approvalId,
6177
+ const invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic && !toolCall.providerExecuted);
6178
+ clientToolOutputs = [];
6179
+ for (const toolCall of invalidToolCalls) clientToolOutputs.push({
6180
+ type: "tool-error",
6070
6181
  toolCallId: toolCall.toolCallId,
6071
6182
  toolName: toolCall.toolName,
6072
- input: toolCall.input
6183
+ input: toolCall.input,
6184
+ error: getErrorMessage(toolCall.error),
6185
+ dynamic: true
6073
6186
  });
6074
- switch (toolApprovalStatus.type) {
6075
- case "user-approval":
6076
- toolApprovalRequests[toolCall.toolCallId] = {
6077
- type: "tool-approval-request",
6078
- approvalId,
6079
- toolCall,
6080
- ...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},
6081
- ...signature != null ? { signature } : {}
6082
- };
6083
- blockedToolCallIds.add(toolCall.toolCallId);
6084
- break;
6085
- case "approved":
6086
- toolApprovalRequests[toolCall.toolCallId] = {
6087
- type: "tool-approval-request",
6088
- approvalId,
6089
- toolCall,
6090
- isAutomatic: true,
6091
- ...signature != null ? { signature } : {}
6092
- };
6093
- stepToolApprovalResponses[toolCall.toolCallId] = {
6094
- type: "tool-approval-response",
6095
- approvalId,
6096
- toolCall,
6097
- approved: true,
6098
- reason: toolApprovalStatus.reason,
6099
- providerExecuted: toolCall.providerExecuted
6100
- };
6101
- break;
6102
- case "denied":
6103
- toolApprovalRequests[toolCall.toolCallId] = {
6104
- type: "tool-approval-request",
6105
- approvalId,
6106
- toolCall,
6107
- isAutomatic: true,
6108
- ...signature != null ? { signature } : {}
6109
- };
6110
- stepToolApprovalResponses[toolCall.toolCallId] = {
6111
- type: "tool-approval-response",
6112
- approvalId,
6113
- toolCall,
6114
- approved: false,
6115
- reason: toolApprovalStatus.reason,
6116
- providerExecuted: toolCall.providerExecuted
6117
- };
6118
- blockedToolCallIds.add(toolCall.toolCallId);
6187
+ clientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);
6188
+ toolApprovalResponses = Object.values(stepToolApprovalResponses);
6189
+ deniedToolApprovalResponses = toolApprovalResponses.filter((toolApprovalResponse) => toolApprovalResponse.approved === false);
6190
+ const toolExecutionMs = {};
6191
+ if (stepExecutionTools != null && isToolExecutionAllowedFinishReason(currentModelResponse.finishReason.unified)) {
6192
+ const toolExecutionResults = await executeTools({
6193
+ toolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId)),
6194
+ tools: stepExecutionTools,
6195
+ callId,
6196
+ messages: stepMessages,
6197
+ abortSignal: mergedAbortSignal,
6198
+ timeout,
6199
+ experimental_sandbox: stepSandbox,
6200
+ toolsContext,
6201
+ onToolExecutionStart: (event) => notify({
6202
+ event,
6203
+ callbacks: [resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart]
6204
+ }),
6205
+ onToolExecutionEnd: (event) => notify({
6206
+ event,
6207
+ callbacks: [resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd]
6208
+ }),
6209
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool,
6210
+ runInTracingChannelSpan,
6211
+ toolCallConcurrency: resolvedToolCallConcurrency
6212
+ });
6213
+ for (const result of toolExecutionResults) {
6214
+ toolExecutionMs[result.output.toolCallId] = result.toolExecutionMs;
6215
+ clientToolOutputs.push(result.output);
6216
+ }
6119
6217
  }
6120
- }
6121
- const invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic && !toolCall.providerExecuted);
6122
- clientToolOutputs = [];
6123
- for (const toolCall of invalidToolCalls) clientToolOutputs.push({
6124
- type: "tool-error",
6125
- toolCallId: toolCall.toolCallId,
6126
- toolName: toolCall.toolName,
6127
- input: toolCall.input,
6128
- error: getErrorMessage(toolCall.error),
6129
- dynamic: true
6130
- });
6131
- clientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);
6132
- toolApprovalResponses = Object.values(stepToolApprovalResponses);
6133
- deniedToolApprovalResponses = toolApprovalResponses.filter((toolApprovalResponse) => toolApprovalResponse.approved === false);
6134
- const toolExecutionMs = {};
6135
- if (stepExecutionTools != null && isToolExecutionAllowedFinishReason(currentModelResponse.finishReason.unified)) {
6136
- const toolExecutionResults = await executeTools({
6137
- toolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId)),
6138
- tools: stepExecutionTools,
6139
- callId,
6140
- messages: stepMessages,
6141
- abortSignal: mergedAbortSignal,
6142
- timeout,
6143
- experimental_sandbox: stepSandbox,
6144
- toolsContext,
6145
- onToolExecutionStart: (event) => notify({
6146
- event,
6147
- callbacks: [resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart]
6218
+ const stepTimeMs = now$4() - stepStartTimestampMs;
6219
+ const stepPerformance = {
6220
+ effectiveOutputTokensPerSecond: calculateTokensPerSecond({
6221
+ tokens: stepUsage.outputTokens,
6222
+ durationMs: responseTimeMs
6148
6223
  }),
6149
- onToolExecutionEnd: (event) => notify({
6150
- event,
6151
- callbacks: [resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd]
6224
+ outputTokensPerSecond: void 0,
6225
+ inputTokensPerSecond: void 0,
6226
+ effectiveTotalTokensPerSecond: calculateTokensPerSecond({
6227
+ tokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),
6228
+ durationMs: responseTimeMs
6152
6229
  }),
6153
- executeToolInTelemetryContext: telemetryDispatcher.executeTool,
6154
- runInTracingChannelSpan,
6155
- toolCallConcurrency: resolvedToolCallConcurrency
6156
- });
6157
- for (const result of toolExecutionResults) {
6158
- toolExecutionMs[result.output.toolCallId] = result.toolExecutionMs;
6159
- clientToolOutputs.push(result.output);
6160
- }
6161
- }
6162
- const stepTimeMs = now$4() - stepStartTimestampMs;
6163
- const stepPerformance = {
6164
- effectiveOutputTokensPerSecond: calculateTokensPerSecond({
6165
- tokens: stepUsage.outputTokens,
6166
- durationMs: responseTimeMs
6167
- }),
6168
- outputTokensPerSecond: void 0,
6169
- inputTokensPerSecond: void 0,
6170
- effectiveTotalTokensPerSecond: calculateTokensPerSecond({
6171
- tokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),
6172
- durationMs: responseTimeMs
6173
- }),
6174
- stepTimeMs,
6175
- responseTimeMs,
6176
- toolExecutionMs,
6177
- timeToFirstOutputMs: void 0
6178
- };
6179
- for (const toolCall of stepToolCalls) {
6180
- if (!toolCall.providerExecuted) continue;
6181
- const tool = getOwn(stepExecutionTools, toolCall.toolName);
6182
- if (tool?.type === "provider" && tool.supportsDeferredResults) {
6183
- if (!currentModelResponse.content.some((part) => part.type === "tool-result" && part.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });
6230
+ stepTimeMs,
6231
+ responseTimeMs,
6232
+ toolExecutionMs,
6233
+ timeToFirstOutputMs: void 0
6234
+ };
6235
+ for (const toolCall of stepToolCalls) {
6236
+ if (!toolCall.providerExecuted) continue;
6237
+ const tool = getOwn(stepExecutionTools, toolCall.toolName);
6238
+ if (tool?.type === "provider" && tool.supportsDeferredResults) {
6239
+ if (!currentModelResponse.content.some((part) => part.type === "tool-result" && part.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });
6240
+ }
6184
6241
  }
6242
+ for (const part of currentModelResponse.content) if (part.type === "tool-result") pendingDeferredToolCalls.delete(part.toolCallId);
6243
+ const stepContent = await convertLanguageModelContent({
6244
+ content: currentModelResponse.content,
6245
+ toolCalls: stepToolCalls,
6246
+ toolOutputs: clientToolOutputs,
6247
+ toolApprovalRequests: Object.values(toolApprovalRequests),
6248
+ toolApprovalResponses,
6249
+ tools,
6250
+ download,
6251
+ abortSignal: mergedAbortSignal,
6252
+ generatedFileDataCache
6253
+ });
6254
+ const stepResponseMessages = await toResponseMessages({
6255
+ content: stepContent,
6256
+ tools
6257
+ });
6258
+ const stepRequest = {
6259
+ ...currentModelResponse.request,
6260
+ body: include.requestBody ? currentModelResponse.request?.body : void 0,
6261
+ messages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0
6262
+ };
6263
+ const stepResponse = {
6264
+ ...currentModelResponse.response,
6265
+ messages: cloneModelMessages(stepResponseMessages),
6266
+ body: include.responseBody ? currentModelResponse.response?.body : void 0
6267
+ };
6268
+ const currentStepResult = new DefaultStepResult({
6269
+ callId,
6270
+ stepNumber,
6271
+ provider: stepModel.provider,
6272
+ modelId: stepModel.modelId,
6273
+ runtimeContext,
6274
+ content: stepContent,
6275
+ finishReason: currentModelResponse.finishReason.unified,
6276
+ rawFinishReason: currentModelResponse.finishReason.raw,
6277
+ usage: stepUsage,
6278
+ performance: stepPerformance,
6279
+ warnings: currentModelResponse.warnings,
6280
+ providerMetadata: currentModelResponse.providerMetadata,
6281
+ request: stepRequest,
6282
+ response: stepResponse,
6283
+ toolsContext,
6284
+ steeringMessages: stepSteeringMessages
6285
+ });
6286
+ logWarnings({
6287
+ warnings: currentModelResponse.warnings ?? [],
6288
+ provider: stepModel.provider,
6289
+ model: stepModel.modelId
6290
+ });
6291
+ steps.push(currentStepResult);
6292
+ instructionsForNextStep = stepInstructions;
6293
+ messagesForNextStep = [...stepMessages, ...stepResponseMessages];
6294
+ openStep = void 0;
6295
+ await notify({
6296
+ event: currentStepResult,
6297
+ callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd]
6298
+ });
6299
+ return currentStepResult;
6185
6300
  }
6186
- for (const part of currentModelResponse.content) if (part.type === "tool-result") pendingDeferredToolCalls.delete(part.toolCallId);
6187
- const stepContent = await convertLanguageModelContent({
6188
- content: currentModelResponse.content,
6189
- toolCalls: stepToolCalls,
6190
- toolOutputs: clientToolOutputs,
6191
- toolApprovalRequests: Object.values(toolApprovalRequests),
6192
- toolApprovalResponses,
6193
- tools,
6194
- download,
6195
- abortSignal: mergedAbortSignal,
6196
- generatedFileDataCache
6197
- });
6198
- const stepResponseMessages = await toResponseMessages({
6199
- content: stepContent,
6200
- tools
6201
- });
6202
- const stepRequest = {
6203
- ...currentModelResponse.request,
6204
- body: include.requestBody ? currentModelResponse.request?.body : void 0,
6205
- messages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0
6206
- };
6207
- const stepResponse = {
6208
- ...currentModelResponse.response,
6209
- messages: cloneModelMessages(stepResponseMessages),
6210
- body: include.responseBody ? currentModelResponse.response?.body : void 0
6211
- };
6212
- const currentStepResult = new DefaultStepResult({
6213
- callId,
6214
- stepNumber,
6215
- provider: stepModel.provider,
6216
- modelId: stepModel.modelId,
6217
- runtimeContext,
6218
- content: stepContent,
6219
- finishReason: currentModelResponse.finishReason.unified,
6220
- rawFinishReason: currentModelResponse.finishReason.raw,
6221
- usage: stepUsage,
6222
- performance: stepPerformance,
6223
- warnings: currentModelResponse.warnings,
6224
- providerMetadata: currentModelResponse.providerMetadata,
6225
- request: stepRequest,
6226
- response: stepResponse,
6227
- toolsContext,
6228
- steeringMessages: deliveredSteeringMessages
6229
- });
6230
- logWarnings({
6231
- warnings: currentModelResponse.warnings ?? [],
6232
- provider: stepModel.provider,
6233
- model: stepModel.modelId
6234
- });
6235
- steps.push(currentStepResult);
6236
- instructionsForNextStep = stepInstructions;
6237
- messagesForNextStep = [...stepMessages, ...stepResponseMessages];
6238
- openStep = void 0;
6239
- await notify({
6240
- event: currentStepResult,
6241
- callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd]
6242
- });
6243
- return currentStepResult;
6244
- }
6301
+ })
6245
6302
  });
6246
6303
  } finally {
6247
6304
  if (stepTimeoutId != null) clearTimeout(stepTimeoutId);
@@ -6367,6 +6424,24 @@ async function executeTools({ toolCalls, tools, callId, messages, abortSignal, t
6367
6424
  })
6368
6425
  })).filter((result) => result != null);
6369
6426
  }
6427
+ /**
6428
+ * Thrown inside a step attempt when a steering interrupt cancelled its model
6429
+ * call. It is not an error that callers see. It only ends the attempt so that
6430
+ * the step is made again.
6431
+ */
6432
+ var InterruptedStepAttempt = class {};
6433
+ /**
6434
+ * Runs a step attempt, and runs it again for as long as steering interrupts
6435
+ * cancel its model call.
6436
+ */
6437
+ async function redoInterruptedStepAttempts({ attempt, onInterrupt }) {
6438
+ for (;;) try {
6439
+ return await attempt();
6440
+ } catch (error) {
6441
+ if (!(error instanceof InterruptedStepAttempt)) throw error;
6442
+ onInterrupt();
6443
+ }
6444
+ }
6370
6445
  //#endregion
6371
6446
  //#region src/util/prepare-headers.ts
6372
6447
  function prepareHeaders(headers, defaultHeaders) {
@@ -10269,8 +10344,8 @@ var DefaultStreamTextResult = class {
10269
10344
  }
10270
10345
  }
10271
10346
  self._initialResponseMessages.resolve(initialResponseMessages);
10272
- async function streamStep({ currentStep, usage }) {
10273
- const stepTimeoutId = setAbortTimeout({
10347
+ async function streamStep({ currentStep, usage, redo }) {
10348
+ const stepTimeoutId = redo != null ? redo.stepTimeoutId : setAbortTimeout({
10274
10349
  abortController: stepAbortController,
10275
10350
  label: "Step",
10276
10351
  timeoutMs: stepTimeoutMs
@@ -10323,8 +10398,8 @@ var DefaultStreamTextResult = class {
10323
10398
  }
10324
10399
  abortSignal?.addEventListener("abort", cleanupStepTimeouts, { once: true });
10325
10400
  try {
10326
- stepFinish = new DelayedPromise();
10327
- const stepTracingChannelContext = telemetryDispatcher.startTracingChannelContext?.({
10401
+ if (redo == null) stepFinish = new DelayedPromise();
10402
+ const stepTracingChannelContext = redo != null ? redo.stepTracingChannelContext : telemetryDispatcher.startTracingChannelContext?.({
10328
10403
  type: "step",
10329
10404
  event: {
10330
10405
  callId,
@@ -10335,7 +10410,15 @@ var DefaultStreamTextResult = class {
10335
10410
  const runInStepTracingChannelContext = (execute) => stepTracingChannelContext?.run(execute) ?? execute();
10336
10411
  const responseMessagesFromPreviousSteps = recordedSteps.flatMap((step) => step.response.messages);
10337
10412
  const accumulatedResponseMessages = [...initialResponseMessages, ...responseMessagesFromPreviousSteps];
10338
- const steeringMessages = steeringRun?.takeMessages() ?? [];
10413
+ const steeringMessages = [...redo?.steeringMessages ?? [], ...steeringRun?.takeMessages() ?? []];
10414
+ const stepStartState = redo?.stepStartState ?? {
10415
+ instructions: instructionsForNextStep,
10416
+ runtimeContext,
10417
+ toolsContext
10418
+ };
10419
+ instructionsForNextStep = stepStartState.instructions;
10420
+ runtimeContext = stepStartState.runtimeContext;
10421
+ toolsContext = stepStartState.toolsContext;
10339
10422
  const stepInputMessages = [...stepMessagesForNextStep ?? [...initialMessages, ...initialResponseMessages], ...steeringMessages];
10340
10423
  const prepareStepResult = await prepareStep?.({
10341
10424
  model,
@@ -10385,7 +10468,7 @@ var DefaultStreamTextResult = class {
10385
10468
  stepNumber: currentStep,
10386
10469
  sentMessages: stepMessages
10387
10470
  }) ?? [];
10388
- currentStepSteeringMessages = deliveredSteeringMessages.map(({ message }) => message);
10471
+ currentStepSteeringMessages = [...redo?.deliveredSteeringMessages ?? [], ...deliveredSteeringMessages.map(({ message }) => message)];
10389
10472
  if (deliveredSteeringMessages.length > 0) self.addStream(new ReadableStream({ start(controller) {
10390
10473
  for (const { id, message } of deliveredSteeringMessages) controller.enqueue({
10391
10474
  type: "steering-message",
@@ -10407,7 +10490,35 @@ var DefaultStreamTextResult = class {
10407
10490
  maxRetries,
10408
10491
  abortSignal
10409
10492
  });
10410
- let hasNotifiedStepStart = false;
10493
+ const stepStart = redo?.stepStart ?? {
10494
+ notified: false,
10495
+ enqueued: false
10496
+ };
10497
+ const interruptController = steeringRun == null ? void 0 : new AbortController();
10498
+ const interruptRequested = interruptController == null ? void 0 : new Promise((resolve) => {
10499
+ interruptController.signal.addEventListener("abort", () => resolve("interrupted"), { once: true });
10500
+ });
10501
+ const stopWatchingInterrupt = steeringRun?.watchInterrupt(() => interruptController?.abort()) ?? (() => {});
10502
+ const isInterrupted = () => interruptController?.signal.aborted === true && abortSignal?.aborted !== true;
10503
+ const modelCallAbortSignal = mergeAbortSignals(abortSignal, interruptController?.signal);
10504
+ const redoStep = () => {
10505
+ abortSignal?.removeEventListener("abort", cleanupStepTimeouts);
10506
+ clearModelOutputTimeouts();
10507
+ return streamStep({
10508
+ currentStep,
10509
+ usage,
10510
+ redo: {
10511
+ steeringMessages,
10512
+ deliveredSteeringMessages: currentStepSteeringMessages,
10513
+ stepStart,
10514
+ stepTimeoutId,
10515
+ stepTracingChannelContext,
10516
+ stepStartState
10517
+ }
10518
+ });
10519
+ };
10520
+ let interruptWindowClosed = false;
10521
+ let attemptInterrupted = false;
10411
10522
  const callLanguageModel = () => runInStepTracingChannelContext(() => retry(async () => streamLanguageModelCall({
10412
10523
  model: prepareStepResult?.model ?? model,
10413
10524
  tools: stepModelTools,
@@ -10418,7 +10529,7 @@ var DefaultStreamTextResult = class {
10418
10529
  allowSystemInMessages,
10419
10530
  repairToolCall,
10420
10531
  refineToolInput,
10421
- abortSignal,
10532
+ abortSignal: modelCallAbortSignal,
10422
10533
  headers,
10423
10534
  includeRawChunks: include.rawChunks,
10424
10535
  providerOptions: stepProviderOptions,
@@ -10431,8 +10542,8 @@ var DefaultStreamTextResult = class {
10431
10542
  onLanguageModelCallStart: filterNullable(onLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart),
10432
10543
  onLanguageModelCallEnd: filterNullable(onLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd),
10433
10544
  onStart: async ({ promptMessages }) => {
10434
- if (hasNotifiedStepStart) return;
10435
- hasNotifiedStepStart = true;
10545
+ if (stepStart.notified) return;
10546
+ stepStart.notified = true;
10436
10547
  const stepStartEvent = {
10437
10548
  callId,
10438
10549
  provider: stepModel.provider,
@@ -10465,7 +10576,17 @@ var DefaultStreamTextResult = class {
10465
10576
  },
10466
10577
  ...stepCallSettings
10467
10578
  })));
10468
- const initialLanguageModelCall = await callLanguageModel();
10579
+ let initialLanguageModelCall;
10580
+ try {
10581
+ initialLanguageModelCall = await callLanguageModel();
10582
+ } catch (error) {
10583
+ if (!isInterrupted()) {
10584
+ stopWatchingInterrupt();
10585
+ throw error;
10586
+ }
10587
+ await redoStep();
10588
+ return;
10589
+ }
10469
10590
  let request = initialLanguageModelCall.request;
10470
10591
  let response = initialLanguageModelCall.response;
10471
10592
  let languageModelStreamReader = initialLanguageModelCall.stream.getReader();
@@ -10509,15 +10630,37 @@ var DefaultStreamTextResult = class {
10509
10630
  });
10510
10631
  openReasoningParts.clear();
10511
10632
  };
10633
+ const interruptAttempt = async () => {
10634
+ await languageModelStreamReader.cancel().catch(() => {});
10635
+ bufferedAttemptParts = [];
10636
+ closeOpenAttemptParts();
10637
+ clearModelOutputTimeouts();
10638
+ attemptInterrupted = true;
10639
+ controller.close();
10640
+ };
10512
10641
  while (true) {
10513
10642
  let result;
10514
10643
  try {
10515
- result = await languageModelStreamReader.read();
10644
+ if (interruptRequested == null || interruptWindowClosed) result = await languageModelStreamReader.read();
10645
+ else result = await Promise.race([languageModelStreamReader.read(), interruptRequested]);
10516
10646
  } catch (error) {
10647
+ if (!interruptWindowClosed && isInterrupted()) {
10648
+ await interruptAttempt();
10649
+ return;
10650
+ }
10651
+ stopWatchingInterrupt();
10517
10652
  clearModelOutputTimeouts();
10518
10653
  throw error;
10519
10654
  }
10655
+ if (result === "interrupted" || !interruptWindowClosed && isInterrupted()) {
10656
+ await interruptAttempt();
10657
+ return;
10658
+ }
10520
10659
  const { done, value } = result;
10660
+ if (!interruptWindowClosed && (done || value.type === "model-call-end" || value.type === "tool-input-start" || isOutputChunk$1(value))) {
10661
+ interruptWindowClosed = true;
10662
+ stopWatchingInterrupt();
10663
+ }
10521
10664
  if (enqueueStreamRetryAttemptBoundary) {
10522
10665
  controller.enqueue(createStreamRetryAttemptBoundaryPart({ warnings: !done && value.type === "model-call-start" ? value.warnings : [] }));
10523
10666
  enqueueStreamRetryAttemptBoundary = false;
@@ -10575,6 +10718,10 @@ var DefaultStreamTextResult = class {
10575
10718
  try {
10576
10719
  retryLanguageModelCall = await callLanguageModel();
10577
10720
  } catch (retryError) {
10721
+ if (!interruptWindowClosed && isInterrupted()) {
10722
+ await interruptAttempt();
10723
+ return;
10724
+ }
10578
10725
  controller.enqueue({
10579
10726
  type: "error",
10580
10727
  error: retryError
@@ -10687,11 +10834,17 @@ var DefaultStreamTextResult = class {
10687
10834
  }
10688
10835
  if (stepFirstChunk) {
10689
10836
  stepFirstChunk = false;
10690
- enqueueStepPart(controller, {
10691
- type: "start-step",
10837
+ const stepStartMetadata = {
10692
10838
  request: getStepRequest(),
10693
10839
  warnings: warnings ?? []
10694
- });
10840
+ };
10841
+ if (!stepStart.enqueued) {
10842
+ stepStart.enqueued = true;
10843
+ enqueueStepPart(controller, {
10844
+ type: "start-step",
10845
+ ...stepStartMetadata
10846
+ });
10847
+ } else controller.enqueue({ [streamRetryBoundarySymbol]: stepStartMetadata });
10695
10848
  }
10696
10849
  const chunkType = chunk.type;
10697
10850
  if (isOutputChunk$1(chunk)) hasReceivedOutputChunk = true;
@@ -10798,6 +10951,23 @@ var DefaultStreamTextResult = class {
10798
10951
  }
10799
10952
  },
10800
10953
  async flush(controller) {
10954
+ stopWatchingInterrupt();
10955
+ const startFollowingStream = async (start) => {
10956
+ try {
10957
+ await runInStreamTextTracingChannelContext(start);
10958
+ } catch (error) {
10959
+ steeringRun?.end("error");
10960
+ enqueueStepPart(controller, {
10961
+ type: "error",
10962
+ error
10963
+ });
10964
+ self.closeStream();
10965
+ }
10966
+ };
10967
+ if (attemptInterrupted) {
10968
+ await startFollowingStream(redoStep);
10969
+ return;
10970
+ }
10801
10971
  if (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {
10802
10972
  enqueueStepPart(controller, {
10803
10973
  type: "error",
@@ -10863,19 +11033,10 @@ var DefaultStreamTextResult = class {
10863
11033
  }
10864
11034
  return true;
10865
11035
  };
10866
- if (await shouldStartNextStep()) try {
10867
- await runInStreamTextTracingChannelContext(() => streamStep({
10868
- currentStep: currentStep + 1,
10869
- usage: combinedUsage
10870
- }));
10871
- } catch (error) {
10872
- steeringRun?.end("error");
10873
- enqueueStepPart(controller, {
10874
- type: "error",
10875
- error
10876
- });
10877
- self.closeStream();
10878
- }
11036
+ if (await shouldStartNextStep()) await startFollowingStream(() => streamStep({
11037
+ currentStep: currentStep + 1,
11038
+ usage: combinedUsage
11039
+ }));
10879
11040
  else {
10880
11041
  steeringRun?.end(steeringEndReason);
10881
11042
  enqueueStepPart(controller, {