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.
@@ -74,12 +74,18 @@ export interface Steering {
74
74
  * @param message - The user message, or its text.
75
75
  * @param options.id - The id of the message. Sending a message again with
76
76
  * the same id returns the outcome of the first message.
77
+ * @param options.interrupt - Cancels the current model call when it has not
78
+ * produced any output yet, and makes it again in the same step with the
79
+ * message. Otherwise the message is added at the next step boundary. Running
80
+ * tools are never interrupted. A cancelled model call can still be billed by
81
+ * the provider, and it is not included in the usage. The step is not counted
82
+ * again, so stop conditions do not limit how often a step is redone.
77
83
  *
78
84
  * @returns The outcome of the message. It never rejects.
79
85
  */
80
86
  steer(
81
87
  message: string | UserModelMessage,
82
- options?: { id?: string },
88
+ options?: { id?: string; interrupt?: boolean },
83
89
  ): Promise<SteeringOutcome>;
84
90
 
85
91
  /**
@@ -129,6 +135,14 @@ export type SteeringRun = {
129
135
  sentMessages: ReadonlyArray<ModelMessage>;
130
136
  }): Array<{ id: string; message: UserModelMessage }>;
131
137
 
138
+ /**
139
+ * Watches for interrupting messages while a model call has not produced any
140
+ * output yet. Calls `onInterrupt` at most once, right away when an
141
+ * interrupting message is already waiting. Returns a function that stops
142
+ * watching.
143
+ */
144
+ watchInterrupt(onInterrupt: () => void): () => void;
145
+
132
146
  end(reason: SteeringNotDeliveredReason): void;
133
147
  };
134
148
 
@@ -144,12 +158,41 @@ class DefaultSteering implements Steering {
144
158
  private queued: Array<PendingSteer> = [];
145
159
  private taken: Array<PendingSteer> = [];
146
160
  private outcomes = new Map<string, Promise<SteeringOutcome>>();
161
+ // An interrupt that arrived while no model call was watching, e.g. during
162
+ // prepareStep or tool execution. It is dropped when the messages are taken
163
+ // at a step boundary, because they are then delivered without cancelling a
164
+ // model call.
165
+ private interruptRequested = false;
166
+ private onInterrupt: (() => void) | undefined;
147
167
 
148
168
  steer(
149
169
  message: string | UserModelMessage,
150
- options?: { id?: string },
170
+ options?: { id?: string; interrupt?: boolean },
151
171
  ): Promise<SteeringOutcome> {
152
- return this.add({ message, id: options?.id, target: this.pending });
172
+ const isNew = options?.id == null || !this.outcomes.has(options.id);
173
+ const outcome = this.add({
174
+ message,
175
+ id: options?.id,
176
+ target: this.pending,
177
+ });
178
+
179
+ if (options?.interrupt === true && isNew) {
180
+ this.requestInterrupt();
181
+ }
182
+
183
+ return outcome;
184
+ }
185
+
186
+ private requestInterrupt() {
187
+ const onInterrupt = this.onInterrupt;
188
+
189
+ if (onInterrupt == null) {
190
+ this.interruptRequested = true;
191
+ return;
192
+ }
193
+
194
+ this.onInterrupt = undefined;
195
+ onInterrupt();
153
196
  }
154
197
 
155
198
  queue(
@@ -228,10 +271,31 @@ class DefaultSteering implements Steering {
228
271
 
229
272
  this.taken = [...this.taken, ...this.pending];
230
273
  this.pending = [];
274
+ this.interruptRequested = false;
231
275
 
232
276
  return this.taken.map(({ message }) => message);
233
277
  },
234
278
 
279
+ watchInterrupt: onInterrupt => {
280
+ if (this.state !== 'running') {
281
+ return () => {};
282
+ }
283
+
284
+ if (this.interruptRequested) {
285
+ this.interruptRequested = false;
286
+ onInterrupt();
287
+ return () => {};
288
+ }
289
+
290
+ this.onInterrupt = onInterrupt;
291
+
292
+ return () => {
293
+ if (this.onInterrupt === onInterrupt) {
294
+ this.onInterrupt = undefined;
295
+ }
296
+ };
297
+ },
298
+
235
299
  resolveTakenMessages: ({ stepNumber, sentMessages }) => {
236
300
  const taken = this.taken;
237
301
  this.taken = [];
@@ -265,6 +329,8 @@ class DefaultSteering implements Steering {
265
329
  this.pending = [];
266
330
  this.queued = [];
267
331
  this.state = 'ended';
332
+ this.interruptRequested = false;
333
+ this.onInterrupt = undefined;
268
334
 
269
335
  for (const { id, message, resolve } of notDelivered) {
270
336
  resolve({ type: 'not-delivered', id, message, reason });
@@ -33,7 +33,7 @@ import type { LanguageModelCallOptions } from '../prompt/language-model-call-opt
33
33
  import { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';
34
34
  import { prepareToolChoice } from '../prompt/prepare-tool-choice';
35
35
  import { prepareTools } from '../prompt/prepare-tools';
36
- import type { Prompt } from '../prompt/prompt';
36
+ import type { Instructions, Prompt } from '../prompt/prompt';
37
37
  import {
38
38
  getChunkTimeoutMs,
39
39
  getFirstChunkTimeoutMs,
@@ -47,6 +47,7 @@ import { wrapGatewayError } from '../prompt/wrap-gateway-error';
47
47
  import type { TelemetryDispatcher } from '../telemetry/telemetry';
48
48
  import type { TelemetryOptions } from '../telemetry/telemetry-options';
49
49
  import { getGlobalTelemetryIntegrations } from '../telemetry/telemetry-registry';
50
+ import type { TracingChannelContext } from '../telemetry/tracing-channel-publisher';
50
51
  import { createTextStreamResponse } from '../text-stream/create-text-stream-response';
51
52
  import { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';
52
53
  import { toTextStream } from '../text-stream/to-text-stream';
@@ -2474,16 +2475,36 @@ class DefaultStreamTextResult<
2474
2475
  async function streamStep({
2475
2476
  currentStep,
2476
2477
  usage,
2478
+ redo,
2477
2479
  }: {
2478
2480
  currentStep: number;
2479
2481
  usage: LanguageModelUsage;
2482
+
2483
+ // A step that a steering interrupt cancelled is made again as the same
2484
+ // step. Its timeout keeps running and its tracing span stays open, so
2485
+ // that the step is not timed or traced twice.
2486
+ redo?: {
2487
+ steeringMessages: Array<UserModelMessage>;
2488
+ deliveredSteeringMessages: Array<UserModelMessage>;
2489
+ stepStart: { notified: boolean; enqueued: boolean };
2490
+ stepTimeoutId: ReturnType<typeof setTimeout> | undefined;
2491
+ stepTracingChannelContext: TracingChannelContext | undefined;
2492
+ stepStartState: {
2493
+ instructions: Instructions | undefined;
2494
+ runtimeContext: RUNTIME_CONTEXT;
2495
+ toolsContext: InferToolSetContext<TOOLS>;
2496
+ };
2497
+ };
2480
2498
  }) {
2481
2499
  // Set up step timeout if configured
2482
- const stepTimeoutId = setAbortTimeout({
2483
- abortController: stepAbortController,
2484
- label: 'Step',
2485
- timeoutMs: stepTimeoutMs,
2486
- });
2500
+ const stepTimeoutId =
2501
+ redo != null
2502
+ ? redo.stepTimeoutId
2503
+ : setAbortTimeout({
2504
+ abortController: stepAbortController,
2505
+ label: 'Step',
2506
+ timeoutMs: stepTimeoutMs,
2507
+ });
2487
2508
 
2488
2509
  // The first-content timeout is armed when the provider response stream
2489
2510
  // starts and is cleared by the first semantic output chunk.
@@ -2565,14 +2586,17 @@ class DefaultStreamTextResult<
2565
2586
  });
2566
2587
 
2567
2588
  try {
2568
- stepFinish = new DelayedPromise<void>();
2569
-
2589
+ if (redo == null) {
2590
+ stepFinish = new DelayedPromise<void>();
2591
+ }
2570
2592
  const stepTracingChannelContext =
2571
- telemetryDispatcher.startTracingChannelContext?.({
2572
- type: 'step',
2573
- event: { callId, stepNumber: currentStep },
2574
- completion: stepFinish.promise,
2575
- });
2593
+ redo != null
2594
+ ? redo.stepTracingChannelContext
2595
+ : telemetryDispatcher.startTracingChannelContext?.({
2596
+ type: 'step',
2597
+ event: { callId, stepNumber: currentStep },
2598
+ completion: stepFinish.promise,
2599
+ });
2576
2600
  // Re-enter the current step before creating child spans.
2577
2601
  const runInStepTracingChannelContext = <T>(execute: () => T): T =>
2578
2602
  stepTracingChannelContext?.run(execute) ?? execute();
@@ -2584,7 +2608,22 @@ class DefaultStreamTextResult<
2584
2608
  ...initialResponseMessages,
2585
2609
  ...responseMessagesFromPreviousSteps,
2586
2610
  ];
2587
- const steeringMessages = steeringRun?.takeMessages() ?? [];
2611
+ const steeringMessages = [
2612
+ ...(redo?.steeringMessages ?? []),
2613
+ ...(steeringRun?.takeMessages() ?? []),
2614
+ ];
2615
+
2616
+ // prepareStep runs again when the step is redone. It must get the
2617
+ // instructions and contexts that the step started with, not the ones
2618
+ // that it returned for the cancelled model call:
2619
+ const stepStartState = redo?.stepStartState ?? {
2620
+ instructions: instructionsForNextStep,
2621
+ runtimeContext,
2622
+ toolsContext,
2623
+ };
2624
+ instructionsForNextStep = stepStartState.instructions;
2625
+ runtimeContext = stepStartState.runtimeContext;
2626
+ toolsContext = stepStartState.toolsContext;
2588
2627
 
2589
2628
  const stepInputMessages = [
2590
2629
  ...(stepMessagesForNextStep ?? [
@@ -2673,9 +2712,10 @@ class DefaultStreamTextResult<
2673
2712
  stepNumber: currentStep,
2674
2713
  sentMessages: stepMessages,
2675
2714
  }) ?? [];
2676
- currentStepSteeringMessages = deliveredSteeringMessages.map(
2677
- ({ message }) => message,
2678
- );
2715
+ currentStepSteeringMessages = [
2716
+ ...(redo?.deliveredSteeringMessages ?? []),
2717
+ ...deliveredSteeringMessages.map(({ message }) => message),
2718
+ ];
2679
2719
 
2680
2720
  // delivered steering messages are streamed before the step output:
2681
2721
  if (deliveredSteeringMessages.length > 0) {
@@ -2714,7 +2754,55 @@ class DefaultStreamTextResult<
2714
2754
  const stepStartTimestampMs = now();
2715
2755
 
2716
2756
  const { retry } = prepareRetries({ maxRetries, abortSignal });
2717
- let hasNotifiedStepStart = false;
2757
+ const stepStart = redo?.stepStart ?? {
2758
+ notified: false,
2759
+ enqueued: false,
2760
+ };
2761
+ const interruptController =
2762
+ steeringRun == null ? undefined : new AbortController();
2763
+ const interruptRequested =
2764
+ interruptController == null
2765
+ ? undefined
2766
+ : new Promise<'interrupted'>(resolve => {
2767
+ interruptController.signal.addEventListener(
2768
+ 'abort',
2769
+ () => resolve('interrupted'),
2770
+ { once: true },
2771
+ );
2772
+ });
2773
+ const stopWatchingInterrupt =
2774
+ steeringRun?.watchInterrupt(() => interruptController?.abort()) ??
2775
+ (() => {});
2776
+ // A caller abort or a timeout wins over an interrupt: the run ends
2777
+ // instead of making the model call again.
2778
+ const isInterrupted = () =>
2779
+ interruptController?.signal.aborted === true &&
2780
+ abortSignal?.aborted !== true;
2781
+ const modelCallAbortSignal = mergeAbortSignals(
2782
+ abortSignal,
2783
+ interruptController?.signal,
2784
+ );
2785
+ const redoStep = () => {
2786
+ // the redo adds its own listener for the step timeout that it
2787
+ // takes over:
2788
+ abortSignal?.removeEventListener('abort', cleanupStepTimeouts);
2789
+ clearModelOutputTimeouts();
2790
+
2791
+ return streamStep({
2792
+ currentStep,
2793
+ usage,
2794
+ redo: {
2795
+ steeringMessages,
2796
+ deliveredSteeringMessages: currentStepSteeringMessages,
2797
+ stepStart,
2798
+ stepTimeoutId,
2799
+ stepTracingChannelContext,
2800
+ stepStartState,
2801
+ },
2802
+ });
2803
+ };
2804
+ let interruptWindowClosed = false;
2805
+ let attemptInterrupted = false;
2718
2806
 
2719
2807
  const callLanguageModel = () =>
2720
2808
  runInStepTracingChannelContext(() =>
@@ -2729,7 +2817,7 @@ class DefaultStreamTextResult<
2729
2817
  allowSystemInMessages,
2730
2818
  repairToolCall,
2731
2819
  refineToolInput,
2732
- abortSignal,
2820
+ abortSignal: modelCallAbortSignal,
2733
2821
  headers,
2734
2822
  includeRawChunks: include.rawChunks,
2735
2823
  providerOptions: stepProviderOptions,
@@ -2753,10 +2841,10 @@ class DefaultStreamTextResult<
2753
2841
  | OnLanguageModelCallEndCallback<TOOLS>,
2754
2842
  ),
2755
2843
  onStart: async ({ promptMessages }) => {
2756
- if (hasNotifiedStepStart) {
2844
+ if (stepStart.notified) {
2757
2845
  return;
2758
2846
  }
2759
- hasNotifiedStepStart = true;
2847
+ stepStart.notified = true;
2760
2848
 
2761
2849
  const stepStartEvent = {
2762
2850
  callId,
@@ -2795,7 +2883,19 @@ class DefaultStreamTextResult<
2795
2883
  ),
2796
2884
  );
2797
2885
 
2798
- const initialLanguageModelCall = await callLanguageModel();
2886
+ let initialLanguageModelCall: Awaited<
2887
+ ReturnType<typeof callLanguageModel>
2888
+ >;
2889
+ try {
2890
+ initialLanguageModelCall = await callLanguageModel();
2891
+ } catch (error) {
2892
+ if (!isInterrupted()) {
2893
+ stopWatchingInterrupt();
2894
+ throw error;
2895
+ }
2896
+ await redoStep();
2897
+ return;
2898
+ }
2799
2899
  let request = initialLanguageModelCall.request;
2800
2900
  let response = initialLanguageModelCall.response;
2801
2901
  let languageModelStreamReader =
@@ -2853,18 +2953,63 @@ class DefaultStreamTextResult<
2853
2953
  openReasoningParts.clear();
2854
2954
  };
2855
2955
 
2956
+ const interruptAttempt = async () => {
2957
+ await languageModelStreamReader.cancel().catch(() => {});
2958
+ bufferedAttemptParts = [];
2959
+ closeOpenAttemptParts();
2960
+ clearModelOutputTimeouts();
2961
+ attemptInterrupted = true;
2962
+ controller.close();
2963
+ };
2964
+
2856
2965
  while (true) {
2857
- let result: ReadableStreamReadResult<
2858
- LanguageModelStreamPart<TOOLS>
2859
- >;
2966
+ let result:
2967
+ | ReadableStreamReadResult<LanguageModelStreamPart<TOOLS>>
2968
+ | 'interrupted';
2860
2969
  try {
2861
- result = await languageModelStreamReader.read();
2970
+ if (interruptRequested == null || interruptWindowClosed) {
2971
+ result = await languageModelStreamReader.read();
2972
+ } else {
2973
+ result = await Promise.race([
2974
+ languageModelStreamReader.read(),
2975
+ interruptRequested,
2976
+ ]);
2977
+ }
2862
2978
  } catch (error) {
2979
+ if (!interruptWindowClosed && isInterrupted()) {
2980
+ await interruptAttempt();
2981
+ return;
2982
+ }
2983
+ stopWatchingInterrupt();
2863
2984
  clearModelOutputTimeouts();
2864
2985
  throw error;
2865
2986
  }
2987
+
2988
+ if (
2989
+ result === 'interrupted' ||
2990
+ (!interruptWindowClosed && isInterrupted())
2991
+ ) {
2992
+ await interruptAttempt();
2993
+ return;
2994
+ }
2995
+
2866
2996
  const { done, value } = result;
2867
2997
 
2998
+ // The model call can only be interrupted until it produces
2999
+ // output. A tool input start is not an output chunk, but it
3000
+ // ends the window as well because the UI already shows a
3001
+ // pending tool call for it.
3002
+ if (
3003
+ !interruptWindowClosed &&
3004
+ (done ||
3005
+ value.type === 'model-call-end' ||
3006
+ value.type === 'tool-input-start' ||
3007
+ isOutputChunk(value))
3008
+ ) {
3009
+ interruptWindowClosed = true;
3010
+ stopWatchingInterrupt();
3011
+ }
3012
+
2868
3013
  if (enqueueStreamRetryAttemptBoundary) {
2869
3014
  controller.enqueue(
2870
3015
  createStreamRetryAttemptBoundaryPart({
@@ -2973,6 +3118,10 @@ class DefaultStreamTextResult<
2973
3118
  try {
2974
3119
  retryLanguageModelCall = await callLanguageModel();
2975
3120
  } catch (retryError) {
3121
+ if (!interruptWindowClosed && isInterrupted()) {
3122
+ await interruptAttempt();
3123
+ return;
3124
+ }
2976
3125
  controller.enqueue({
2977
3126
  type: 'error',
2978
3127
  error: retryError,
@@ -3157,11 +3306,24 @@ class DefaultStreamTextResult<
3157
3306
  stepFirstChunk = false;
3158
3307
 
3159
3308
  // Step start:
3160
- enqueueStepPart(controller, {
3161
- type: 'start-step',
3309
+ const stepStartMetadata = {
3162
3310
  request: getStepRequest(),
3163
3311
  warnings: warnings ?? [],
3164
- });
3312
+ } satisfies StreamRetryBoundaryMetadata;
3313
+ if (!stepStart.enqueued) {
3314
+ stepStart.enqueued = true;
3315
+ enqueueStepPart(controller, {
3316
+ type: 'start-step',
3317
+ ...stepStartMetadata,
3318
+ });
3319
+ } else {
3320
+ // The cancelled model call already sent the start-step
3321
+ // part of this step. The boundary replaces what the step
3322
+ // recorded for it, e.g. its request and warnings.
3323
+ controller.enqueue({
3324
+ [streamRetryBoundarySymbol]: stepStartMetadata,
3325
+ });
3326
+ }
3165
3327
  }
3166
3328
 
3167
3329
  const chunkType = chunk.type;
@@ -3318,6 +3480,28 @@ class DefaultStreamTextResult<
3318
3480
 
3319
3481
  // invoke onEnd callback and resolve toolResults promise when the stream is about to close:
3320
3482
  async flush(controller) {
3483
+ stopWatchingInterrupt();
3484
+
3485
+ // starts the stream that follows this one: the redo of the
3486
+ // step or the next step
3487
+ const startFollowingStream = async (
3488
+ start: () => Promise<void>,
3489
+ ) => {
3490
+ try {
3491
+ await runInStreamTextTracingChannelContext(start);
3492
+ } catch (error) {
3493
+ steeringRun?.end('error');
3494
+ enqueueStepPart(controller, { type: 'error', error });
3495
+ self.closeStream();
3496
+ }
3497
+ };
3498
+
3499
+ // the step is not finished, its model call is made again:
3500
+ if (attemptInterrupted) {
3501
+ await startFollowingStream(redoStep);
3502
+ return;
3503
+ }
3504
+
3321
3505
  // emit an error when an incomplete model stream produced no
3322
3506
  // output instead of recording an empty step. incomplete
3323
3507
  // streams with partial output retain the partial result:
@@ -3473,23 +3657,12 @@ class DefaultStreamTextResult<
3473
3657
  };
3474
3658
 
3475
3659
  if (await shouldStartNextStep()) {
3476
- try {
3477
- await runInStreamTextTracingChannelContext(() =>
3478
- streamStep({
3479
- currentStep: currentStep + 1,
3480
- usage: combinedUsage,
3481
- }),
3482
- );
3483
- } catch (error) {
3484
- steeringRun?.end('error');
3485
-
3486
- enqueueStepPart(controller, {
3487
- type: 'error',
3488
- error,
3489
- });
3490
-
3491
- self.closeStream();
3492
- }
3660
+ await startFollowingStream(() =>
3661
+ streamStep({
3662
+ currentStep: currentStep + 1,
3663
+ usage: combinedUsage,
3664
+ }),
3665
+ );
3493
3666
  } else {
3494
3667
  steeringRun?.end(steeringEndReason);
3495
3668