ai 7.0.142 → 7.0.143

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
@@ -1174,7 +1174,7 @@ function cloneValue(value) {
1174
1174
  }
1175
1175
  //#endregion
1176
1176
  //#region src/version.ts
1177
- const VERSION = "7.0.142";
1177
+ const VERSION = "7.0.143";
1178
1178
  //#endregion
1179
1179
  //#region src/util/download/download.ts
1180
1180
  /**
@@ -8132,6 +8132,46 @@ function invokeToolCallbacksFromStream({ stream, tools, stepInputMessages, abort
8132
8132
  } }));
8133
8133
  }
8134
8134
  //#endregion
8135
+ //#region src/generate-text/stream-text-single-consumer-result.ts
8136
+ /** Expose only the stream and completion metadata for a single consumer. */
8137
+ function createSingleConsumerStreamTextResult(result) {
8138
+ return {
8139
+ get textStream() {
8140
+ return result.textStream;
8141
+ },
8142
+ get stream() {
8143
+ return result.stream;
8144
+ },
8145
+ get fullStream() {
8146
+ return result.fullStream;
8147
+ },
8148
+ get partialOutputStream() {
8149
+ return result.partialOutputStream;
8150
+ },
8151
+ get elementStream() {
8152
+ return result.elementStream;
8153
+ },
8154
+ get totalUsage() {
8155
+ return result.totalUsage;
8156
+ },
8157
+ get usage() {
8158
+ return result.usage;
8159
+ },
8160
+ get finishReason() {
8161
+ return result.finishReason;
8162
+ },
8163
+ get rawFinishReason() {
8164
+ return result.rawFinishReason;
8165
+ },
8166
+ consumeStream: result.consumeStream.bind(result),
8167
+ toUIMessageStream: result.toUIMessageStream.bind(result),
8168
+ toUIMessageStreamResponse: result.toUIMessageStreamResponse.bind(result),
8169
+ toTextStreamResponse: result.toTextStreamResponse.bind(result),
8170
+ pipeUIMessageStreamToResponse: result.pipeUIMessageStreamToResponse.bind(result),
8171
+ pipeTextStreamToResponse: result.pipeTextStreamToResponse.bind(result)
8172
+ };
8173
+ }
8174
+ //#endregion
8135
8175
  //#region src/prompt/normalize-stream-provider-error.ts
8136
8176
  /**
8137
8177
  * Normalizes well-formed provider error payloads without changing existing
@@ -8259,7 +8299,7 @@ const originalGenerateCallId$8 = createIdGenerator$1({
8259
8299
  *
8260
8300
  * @returns A stream of model call parts together with request and response metadata when available.
8261
8301
  */
8262
- async function streamLanguageModelCall({ model, tools, toolOrder, output, toolChoice, prompt, system, instructions, messages, allowSystemInMessages, download, abortSignal, headers, includeRawChunks, providerOptions, repairToolCall, refineToolInput, executeLanguageModelCallInTelemetryContext = async ({ execute }) => await execute(), callId, toolsContext, experimental_sandbox: sandbox, _internal: { generateId = originalGenerateId$3, generateCallId = originalGenerateCallId$8, now: now$3 = now } = {}, onStart, onLanguageModelCallStart, onLanguageModelCallEnd, ...callSettings }) {
8302
+ async function streamLanguageModelCall({ model, tools, toolOrder, output, toolChoice, prompt, system, instructions, messages, allowSystemInMessages, download, abortSignal, headers, includeRawChunks, providerOptions, repairToolCall, refineToolInput, executeLanguageModelCallInTelemetryContext = async ({ execute }) => await execute(), callId, toolsContext, experimental_sandbox: sandbox, _internal: { generateId = originalGenerateId$3, generateCallId = originalGenerateCallId$8, now: now$3 = now, collectContent = true } = {}, onStart, onLanguageModelCallStart, onLanguageModelCallEnd, ...callSettings }) {
8263
8303
  const resolvedModel = resolveLanguageModel(model);
8264
8304
  const effectiveCallId = callId ?? generateCallId();
8265
8305
  const standardizedPrompt = await standardizePrompt({
@@ -8333,13 +8373,14 @@ async function streamLanguageModelCall({ model, tools, toolOrder, output, toolCh
8333
8373
  generateId,
8334
8374
  now: now$3,
8335
8375
  callStartTimestampMs,
8336
- onLanguageModelCallEnd
8376
+ onLanguageModelCallEnd,
8377
+ collectContent
8337
8378
  }))),
8338
8379
  response,
8339
8380
  request
8340
8381
  };
8341
8382
  }
8342
- function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ tools, instructions, messages, repairToolCall, refineToolInput, abortSignal, callId, provider, modelId, toolChoice, generateId, now, callStartTimestampMs, onLanguageModelCallEnd }) {
8383
+ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ tools, instructions, messages, repairToolCall, refineToolInput, abortSignal, callId, provider, modelId, toolChoice, generateId, now, callStartTimestampMs, onLanguageModelCallEnd, collectContent }) {
8343
8384
  const toolCallsByToolCallId = /* @__PURE__ */ new Map();
8344
8385
  const modelCallContent = [];
8345
8386
  const rawModelCallContent = [];
@@ -8368,6 +8409,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8368
8409
  break;
8369
8410
  case "text-start":
8370
8411
  upsertTextContentPart({
8412
+ enabled: collectContent,
8371
8413
  content: modelCallContent,
8372
8414
  rawContent: rawModelCallContent,
8373
8415
  partIndexes: textPartIndexes,
@@ -8380,6 +8422,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8380
8422
  break;
8381
8423
  case "text-delta":
8382
8424
  upsertTextContentPart({
8425
+ enabled: collectContent,
8383
8426
  content: modelCallContent,
8384
8427
  rawContent: rawModelCallContent,
8385
8428
  partIndexes: textPartIndexes,
@@ -8398,6 +8441,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8398
8441
  break;
8399
8442
  case "text-end":
8400
8443
  upsertTextContentPart({
8444
+ enabled: collectContent,
8401
8445
  content: modelCallContent,
8402
8446
  rawContent: rawModelCallContent,
8403
8447
  partIndexes: textPartIndexes,
@@ -8412,6 +8456,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8412
8456
  break;
8413
8457
  case "reasoning-start":
8414
8458
  upsertTextContentPart({
8459
+ enabled: collectContent,
8415
8460
  content: modelCallContent,
8416
8461
  rawContent: rawModelCallContent,
8417
8462
  partIndexes: reasoningPartIndexes,
@@ -8424,6 +8469,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8424
8469
  break;
8425
8470
  case "reasoning-delta":
8426
8471
  upsertTextContentPart({
8472
+ enabled: collectContent,
8427
8473
  content: modelCallContent,
8428
8474
  rawContent: rawModelCallContent,
8429
8475
  partIndexes: reasoningPartIndexes,
@@ -8442,6 +8488,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8442
8488
  break;
8443
8489
  case "reasoning-end":
8444
8490
  upsertTextContentPart({
8491
+ enabled: collectContent,
8445
8492
  content: modelCallContent,
8446
8493
  rawContent: rawModelCallContent,
8447
8494
  partIndexes: reasoningPartIndexes,
@@ -8463,12 +8510,12 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8463
8510
  }),
8464
8511
  mediaType: chunk.mediaType
8465
8512
  });
8466
- modelCallContent.push({
8513
+ if (collectContent) modelCallContent.push({
8467
8514
  type: chunk.type,
8468
8515
  file,
8469
8516
  ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
8470
8517
  });
8471
- rawModelCallContent.push(chunk);
8518
+ if (collectContent) rawModelCallContent.push(chunk);
8472
8519
  controller.enqueue({
8473
8520
  type: chunk.type,
8474
8521
  file,
@@ -8540,7 +8587,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8540
8587
  break;
8541
8588
  }
8542
8589
  case "tool-call":
8543
- rawModelCallContent.push(chunk);
8590
+ if (collectContent) rawModelCallContent.push(chunk);
8544
8591
  try {
8545
8592
  const toolCall = await parseToolCall({
8546
8593
  toolCall: chunk,
@@ -8553,7 +8600,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8553
8600
  });
8554
8601
  toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);
8555
8602
  controller.enqueue(toolCall);
8556
- modelCallContent.push(toolCall);
8603
+ if (collectContent) modelCallContent.push(toolCall);
8557
8604
  if (toolCall.invalid) {
8558
8605
  if (!toolCall.providerExecuted) controller.enqueue({
8559
8606
  type: "tool-error",
@@ -8575,7 +8622,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8575
8622
  }
8576
8623
  break;
8577
8624
  case "tool-approval-request": {
8578
- rawModelCallContent.push(chunk);
8625
+ if (collectContent) rawModelCallContent.push(chunk);
8579
8626
  const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);
8580
8627
  if (toolCall == null) {
8581
8628
  controller.enqueue({
@@ -8593,11 +8640,11 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8593
8640
  toolCall
8594
8641
  };
8595
8642
  controller.enqueue(toolApprovalRequest);
8596
- modelCallContent.push(toolApprovalRequest);
8643
+ if (collectContent) modelCallContent.push(toolApprovalRequest);
8597
8644
  break;
8598
8645
  }
8599
8646
  case "tool-result": {
8600
- rawModelCallContent.push(chunk);
8647
+ if (collectContent) rawModelCallContent.push(chunk);
8601
8648
  const toolName = chunk.toolName;
8602
8649
  const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);
8603
8650
  const toolResultPart = chunk.isError ? {
@@ -8622,7 +8669,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8622
8669
  ...toolCall?.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}
8623
8670
  };
8624
8671
  controller.enqueue(toolResultPart);
8625
- modelCallContent.push(toolResultPart);
8672
+ if (collectContent) modelCallContent.push(toolResultPart);
8626
8673
  break;
8627
8674
  }
8628
8675
  case "tool-input-start": {
@@ -8653,8 +8700,8 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ too
8653
8700
  break;
8654
8701
  default:
8655
8702
  if (chunk.type === "custom" || chunk.type === "source") {
8656
- modelCallContent.push(chunk);
8657
- rawModelCallContent.push(chunk);
8703
+ if (collectContent) modelCallContent.push(chunk);
8704
+ if (collectContent) rawModelCallContent.push(chunk);
8658
8705
  }
8659
8706
  controller.enqueue(chunk);
8660
8707
  }
@@ -8686,7 +8733,8 @@ function calculateNearestRankPercentile(sortedValues, percentile) {
8686
8733
  /**
8687
8734
  * Appends a text or reasoning content part into the content array and updates the part indexes.
8688
8735
  */
8689
- function upsertTextContentPart({ content, rawContent, partIndexes, rawPartIndexes, id, type, textDelta, providerMetadata }) {
8736
+ function upsertTextContentPart({ enabled, content, rawContent, partIndexes, rawPartIndexes, id, type, textDelta, providerMetadata }) {
8737
+ if (!enabled) return;
8690
8738
  let partIndex = partIndexes.get(id);
8691
8739
  if (partIndex == null) {
8692
8740
  partIndex = content.push({
@@ -8726,75 +8774,26 @@ const originalGenerateCallId$7 = createIdGenerator$1({
8726
8774
  prefix: "call",
8727
8775
  size: 24
8728
8776
  });
8729
- /**
8730
- * Generate a text and call tools for a given prompt using a language model.
8731
- *
8732
- * This function streams the output. If you do not want to stream the output, use `generateText` instead.
8733
- *
8734
- * @param model - The language model to use.
8735
- * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
8736
- * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically.
8737
- * @param toolCallConcurrency - Maximum number of tool calls that may execute concurrently within a step. Set to 1 for sequential execution. Default: unlimited.
8738
- *
8739
- * @param system - A system message that will be part of the prompt.
8740
- * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
8741
- * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
8742
- * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.
8743
- *
8744
- * @param maxOutputTokens - Maximum number of tokens to generate.
8745
- * @param temperature - Temperature setting.
8746
- * The value is passed through to the provider. The range depends on the provider and model.
8747
- * It is recommended to set either `temperature` or `topP`, but not both.
8748
- * @param topP - Nucleus sampling.
8749
- * The value is passed through to the provider. The range depends on the provider and model.
8750
- * It is recommended to set either `temperature` or `topP`, but not both.
8751
- * @param topK - Only sample from the top K options for each subsequent token.
8752
- * Used to remove "long tail" low probability responses.
8753
- * Recommended for advanced use cases only. You usually only need to use temperature.
8754
- * @param presencePenalty - Presence penalty setting.
8755
- * It affects the likelihood of the model to repeat information that is already in the prompt.
8756
- * The value is passed through to the provider. The range depends on the provider and model.
8757
- * @param frequencyPenalty - Frequency penalty setting.
8758
- * It affects the likelihood of the model to repeatedly use the same words or phrases.
8759
- * The value is passed through to the provider. The range depends on the provider and model.
8760
- * @param stopSequences - Stop sequences.
8761
- * If set, the model will stop generating text when one of the stop sequences is generated.
8762
- * @param seed - The seed (integer) to use for random sampling.
8763
- * If set and supported by the model, calls will generate deterministic results.
8764
- *
8765
- * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
8766
- * @param streamRetries - Maximum number of retries for provider errors received after streaming starts. Set to 0 to disable automatic stream retries while allowing `onError` to request retries. Omit to disable all stream retry behavior. Default: 0.
8767
- * @param abortSignal - An optional abort signal that can be used to cancel the call.
8768
- * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.
8769
- * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
8770
- *
8771
- * @param experimental_sandbox - The sandbox environment that is passed through to tool execution.
8772
- * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.
8773
- * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded.
8774
- *
8775
- * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.
8776
- * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.
8777
- * @param onStart - Callback invoked when generation begins, before any LLM calls.
8778
- * @param experimental_onStart - Deprecated alias for `onStart`.
8779
- * @param onStepStart - Callback invoked when each step begins, before the provider is called.
8780
- * @param experimental_onStepStart - Deprecated alias for `onStepStart`.
8781
- * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins.
8782
- * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`.
8783
- * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed.
8784
- * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`.
8785
- * @param onToolExecutionStart - Callback invoked before each tool execution begins.
8786
- * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`.
8787
- * @param onToolExecutionEnd - Callback invoked after each tool execution completes.
8788
- * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.
8789
- * @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps.
8790
- * @param onStepFinish - Deprecated alias for `onStepEnd`.
8791
- * @param onEnd - Callback that is called when all steps are finished and the response is complete.
8792
- * @param onFinish - Deprecated alias for `onEnd`.
8793
- *
8794
- * @returns
8795
- * A result object for accessing different stream types and additional information.
8796
- */
8797
- function streamText({ model, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries, streamRetries, abortSignal, timeout, headers, stopWhen = isStepCount(1), experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry = experimental_telemetry, prepareStep, providerOptions, activeTools, toolOrder, toolCallConcurrency, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError: onErrorArg, onFinish, onEnd = onFinish, onAbort, onStepEnd, onStepFinish, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, runtimeContext = {}, toolsContext = {}, experimental_include, include = experimental_include, _internal: { now: now$2 = now, generateId = originalGenerateId$2, generateCallId = originalGenerateCallId$7 } = {}, ...settings }) {
8777
+ function streamText({ experimental_lowMemory = false, ...options }) {
8778
+ if (!experimental_lowMemory) return streamTextInternal({ ...options });
8779
+ const telemetry = options.telemetry ?? options.experimental_telemetry;
8780
+ const integrations = telemetry?.integrations != null ? asArray(telemetry.integrations) : getGlobalTelemetryIntegrations();
8781
+ const collectContent = options.tools != null && Object.keys(options.tools).length > 0 || options.toolChoice != null || options.output != null || options.prepareStep != null || options.stopWhen != null || options.onEnd != null || options.onFinish != null || options.onStepEnd != null || options.onStepFinish != null || options.onAbort != null || options.onLanguageModelCallEnd != null || options.experimental_onLanguageModelCallEnd != null || telemetry?.isEnabled !== false && integrations.length > 0;
8782
+ return createSingleConsumerStreamTextResult(streamTextInternal({
8783
+ ...options,
8784
+ _internal: {
8785
+ ...options._internal,
8786
+ retention: {
8787
+ replay: false,
8788
+ collectContent
8789
+ }
8790
+ }
8791
+ }));
8792
+ }
8793
+ function streamTextInternal({ model, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries, streamRetries, abortSignal, timeout, headers, stopWhen = isStepCount(1), experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry = experimental_telemetry, prepareStep, providerOptions, activeTools, toolOrder, toolCallConcurrency, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError: onErrorArg, onFinish, onEnd = onFinish, onAbort, onStepEnd, onStepFinish, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, runtimeContext = {}, toolsContext = {}, experimental_include, include = experimental_include, _internal: { now: now$2 = now, generateId = originalGenerateId$2, generateCallId = originalGenerateCallId$7, retention = {
8794
+ replay: true,
8795
+ collectContent: true
8796
+ } } = {}, ...settings }) {
8798
8797
  const resolvedToolCallConcurrency = prepareToolCallConcurrency(toolCallConcurrency);
8799
8798
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
8800
8799
  const stepTimeoutMs = getStepTimeoutMs(timeout);
@@ -8814,6 +8813,7 @@ function streamText({ model, tools, toolChoice, instructions, system, prompt, me
8814
8813
  const resolvedOnToolExecutionEnd = onToolExecutionEnd ?? experimental_onToolCallFinish;
8815
8814
  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;
8816
8815
  return new DefaultStreamTextResult({
8816
+ retention,
8817
8817
  model: resolveLanguageModel(model),
8818
8818
  telemetry,
8819
8819
  headers,
@@ -8883,7 +8883,7 @@ async function markPromiseAsHandled$1(promise) {
8883
8883
  await promise;
8884
8884
  } catch {}
8885
8885
  }
8886
- function createOutputTransformStream(output) {
8886
+ function createOutputTransformStream(output, collectOutput = true) {
8887
8887
  let firstTextChunkId = void 0;
8888
8888
  let text = "";
8889
8889
  let textChunk = "";
@@ -8917,6 +8917,13 @@ function createOutputTransformStream(output) {
8917
8917
  textChunk = "";
8918
8918
  }
8919
8919
  return new TransformStream({ async transform(chunk, controller) {
8920
+ if (!collectOutput) {
8921
+ controller.enqueue(isStreamRetryBoundaryPart(chunk) ? chunk : {
8922
+ part: chunk,
8923
+ partialOutput: void 0
8924
+ });
8925
+ return;
8926
+ }
8920
8927
  if (isStreamRetryBoundaryPart(chunk)) {
8921
8928
  resetOutputState();
8922
8929
  controller.enqueue(chunk);
@@ -9047,12 +9054,14 @@ function applyStreamTextTransforms({ stream, transforms, tools, stopStream }) {
9047
9054
  });
9048
9055
  }
9049
9056
  var DefaultStreamTextResult = class {
9050
- constructor({ model, telemetry, headers, settings, maxRetries: maxRetriesArg, streamRetries: streamRetriesArg, abortSignal, stepTimeoutMs, stepAbortController, firstChunkTimeoutMs, firstChunkAbortController, chunkTimeoutMs, chunkAbortController, instructions, system, prompt, messages, allowSystemInMessages, experimental_sandbox: sandbox, tools, toolChoice, transforms, activeTools, toolOrder, toolCallConcurrency, repairToolCall, refineToolInput, stopConditions, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, providerOptions, prepareStep, now, generateId, generateCallId, timeout, onChunk, onError, canRetryStreamViaOnError, onEnd, onAbort, onStepFinish, onStart, onStepStart, onLanguageModelCallStart, onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, runtimeContext, toolsContext, download, include }) {
9057
+ constructor({ retention, model, telemetry, headers, settings, maxRetries: maxRetriesArg, streamRetries: streamRetriesArg, abortSignal, stepTimeoutMs, stepAbortController, firstChunkTimeoutMs, firstChunkAbortController, chunkTimeoutMs, chunkAbortController, instructions, system, prompt, messages, allowSystemInMessages, experimental_sandbox: sandbox, tools, toolChoice, transforms, activeTools, toolOrder, toolCallConcurrency, repairToolCall, refineToolInput, stopConditions, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, providerOptions, prepareStep, now, generateId, generateCallId, timeout, onChunk, onError, canRetryStreamViaOnError, onEnd, onAbort, onStepFinish, onStart, onStepStart, onLanguageModelCallStart, onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, runtimeContext, toolsContext, download, include }) {
9051
9058
  this._totalUsage = new DelayedPromise();
9052
9059
  this._finishReason = new DelayedPromise();
9053
9060
  this._rawFinishReason = new DelayedPromise();
9054
9061
  this._steps = new DelayedPromise();
9055
9062
  this._initialResponseMessages = new DelayedPromise();
9063
+ this.streamClaimed = false;
9064
+ this.retention = retention;
9056
9065
  this.outputSpecification = output;
9057
9066
  this.tools = tools;
9058
9067
  const resolvedToolCallers = resolveToolCallerConfiguration({
@@ -9076,7 +9085,7 @@ var DefaultStreamTextResult = class {
9076
9085
  let recordedRequest = {};
9077
9086
  let recordedRequestMessages = [];
9078
9087
  let recordedWarnings = [];
9079
- const recordedSteps = [];
9088
+ let recordedSteps = [];
9080
9089
  const initialResponseMessages = [];
9081
9090
  let stepMessagesForNextStep;
9082
9091
  let currentStepMessages = [];
@@ -9134,14 +9143,16 @@ var DefaultStreamTextResult = class {
9134
9143
  }
9135
9144
  });
9136
9145
  }
9137
- if (part.type === "custom" || part.type === "source" || part.type === "tool-call" || part.type === "tool-approval-request" || part.type === "tool-approval-response" || part.type === "tool-error") recordedContent.push(part);
9146
+ if (part.type === "custom" || part.type === "source" || part.type === "tool-call" || part.type === "tool-approval-request" || part.type === "tool-approval-response" || part.type === "tool-error") {
9147
+ if (retention.collectContent) recordedContent.push(part);
9148
+ }
9138
9149
  if (part.type === "text-start") {
9139
9150
  activeTextContent[part.id] = {
9140
9151
  type: "text",
9141
9152
  text: "",
9142
9153
  providerMetadata: part.providerMetadata
9143
9154
  };
9144
- recordedContent.push(activeTextContent[part.id]);
9155
+ if (retention.collectContent) recordedContent.push(activeTextContent[part.id]);
9145
9156
  }
9146
9157
  if (part.type === "text-delta") {
9147
9158
  const activeText = activeTextContent[part.id];
@@ -9155,7 +9166,7 @@ var DefaultStreamTextResult = class {
9155
9166
  });
9156
9167
  return;
9157
9168
  }
9158
- activeText.text += part.text;
9169
+ if (retention.collectContent) activeText.text += part.text;
9159
9170
  activeText.providerMetadata = part.providerMetadata ?? activeText.providerMetadata;
9160
9171
  }
9161
9172
  if (part.type === "text-end") {
@@ -9180,7 +9191,7 @@ var DefaultStreamTextResult = class {
9180
9191
  text: "",
9181
9192
  providerMetadata: part.providerMetadata
9182
9193
  };
9183
- recordedContent.push(activeReasoningContent[part.id]);
9194
+ if (retention.collectContent) recordedContent.push(activeReasoningContent[part.id]);
9184
9195
  }
9185
9196
  if (part.type === "reasoning-delta") {
9186
9197
  const activeReasoning = activeReasoningContent[part.id];
@@ -9194,7 +9205,7 @@ var DefaultStreamTextResult = class {
9194
9205
  });
9195
9206
  return;
9196
9207
  }
9197
- activeReasoning.text += part.text;
9208
+ if (retention.collectContent) activeReasoning.text += part.text;
9198
9209
  activeReasoning.providerMetadata = part.providerMetadata ?? activeReasoning.providerMetadata;
9199
9210
  }
9200
9211
  if (part.type === "reasoning-end") {
@@ -9212,12 +9223,16 @@ var DefaultStreamTextResult = class {
9212
9223
  activeReasoning.providerMetadata = part.providerMetadata ?? activeReasoning.providerMetadata;
9213
9224
  delete activeReasoningContent[part.id];
9214
9225
  }
9215
- if (part.type === "file" || part.type === "reasoning-file") recordedContent.push({
9216
- type: part.type,
9217
- file: part.file,
9218
- ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
9219
- });
9220
- if (part.type === "tool-result" && !part.preliminary) recordedContent.push(part);
9226
+ if (part.type === "file" || part.type === "reasoning-file") {
9227
+ if (retention.collectContent) recordedContent.push({
9228
+ type: part.type,
9229
+ file: part.file,
9230
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
9231
+ });
9232
+ }
9233
+ if (part.type === "tool-result" && !part.preliminary) {
9234
+ if (retention.collectContent) recordedContent.push(part);
9235
+ }
9221
9236
  if (part.type === "start-step") {
9222
9237
  recordedContent = [];
9223
9238
  activeReasoningContent = createIdMap();
@@ -9284,7 +9299,7 @@ var DefaultStreamTextResult = class {
9284
9299
  self._finishReason.resolve(finishReason);
9285
9300
  self._rawFinishReason.resolve(recordedRawFinishReason);
9286
9301
  self._totalUsage.resolve(totalUsage);
9287
- self._steps.resolve(recordedSteps);
9302
+ self._steps.resolve(retention.replay ? recordedSteps : []);
9288
9303
  if (isAborted) return;
9289
9304
  const finalStep = recordedSteps[recordedSteps.length - 1];
9290
9305
  const content = recordedSteps.flatMap((step) => step.content);
@@ -9298,7 +9313,7 @@ var DefaultStreamTextResult = class {
9298
9313
  const dynamicToolResults = recordedSteps.flatMap((step) => step.dynamicToolResults);
9299
9314
  const warnings = recordedSteps.flatMap((step) => step.warnings ?? []);
9300
9315
  const onEndWithOutput = onEnd == null ? void 0 : async (event) => {
9301
- const parsedOutput = output == null ? void 0 : await self.getOutputPromise().catch(() => void 0);
9316
+ const parsedOutput = output == null ? void 0 : await (retention.replay ? self.getOutputPromise() : self.parseOutput(finalStep)).catch(() => void 0);
9302
9317
  await onEnd({
9303
9318
  ...event,
9304
9319
  ...output != null ? { output: parsedOutput } : {}
@@ -9343,6 +9358,16 @@ var DefaultStreamTextResult = class {
9343
9358
  })]);
9344
9359
  } catch (error) {
9345
9360
  controller.error(error);
9361
+ } finally {
9362
+ if (!retention.replay) {
9363
+ recordedSteps = [];
9364
+ recordedContent = [];
9365
+ recordedRequestMessages = [];
9366
+ currentStepMessages = [];
9367
+ stepMessagesForNextStep = void 0;
9368
+ activeTextContent = createIdMap();
9369
+ activeReasoningContent = createIdMap();
9370
+ }
9346
9371
  }
9347
9372
  }
9348
9373
  });
@@ -9421,7 +9446,7 @@ var DefaultStreamTextResult = class {
9421
9446
  isRunning = false;
9422
9447
  }
9423
9448
  });
9424
- this.baseStream = stream.pipeThrough(createOutputTransformStream(output ?? text())).pipeThrough(eventProcessor);
9449
+ this.baseStream = stream.pipeThrough(createOutputTransformStream(output ?? text(), retention.replay || output != null)).pipeThrough(eventProcessor);
9425
9450
  const { maxRetries } = prepareRetries({
9426
9451
  maxRetries: maxRetriesArg,
9427
9452
  abortSignal
@@ -9765,7 +9790,10 @@ var DefaultStreamTextResult = class {
9765
9790
  callbacks: [onStepStart, telemetryDispatcher.onStepStart]
9766
9791
  });
9767
9792
  },
9768
- _internal: { now },
9793
+ _internal: {
9794
+ now,
9795
+ collectContent: retention.collectContent
9796
+ },
9769
9797
  ...stepCallSettings
9770
9798
  })));
9771
9799
  const initialLanguageModelCall = await callLanguageModel();
@@ -10197,7 +10225,7 @@ var DefaultStreamTextResult = class {
10197
10225
  });
10198
10226
  }
10199
10227
  get steps() {
10200
- this.consumeStream();
10228
+ if (this.retention.replay) this.consumeStream();
10201
10229
  return this._steps.promise;
10202
10230
  }
10203
10231
  get finalStep() {
@@ -10258,15 +10286,15 @@ var DefaultStreamTextResult = class {
10258
10286
  return Promise.all([this._initialResponseMessages.promise, this.steps]).then(([initialResponseMessages, steps]) => [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)]);
10259
10287
  }
10260
10288
  get totalUsage() {
10261
- this.consumeStream();
10289
+ if (this.retention.replay) this.consumeStream();
10262
10290
  return this._totalUsage.promise;
10263
10291
  }
10264
10292
  get finishReason() {
10265
- this.consumeStream();
10293
+ if (this.retention.replay) this.consumeStream();
10266
10294
  return this._finishReason.promise;
10267
10295
  }
10268
10296
  get rawFinishReason() {
10269
- this.consumeStream();
10297
+ if (this.retention.replay) this.consumeStream();
10270
10298
  return this._rawFinishReason.promise;
10271
10299
  }
10272
10300
  /**
@@ -10278,15 +10306,50 @@ var DefaultStreamTextResult = class {
10278
10306
  * However, the LLM results are expected to be small enough to not cause issues.
10279
10307
  */
10280
10308
  teeStream() {
10309
+ if (!this.retention.replay) {
10310
+ if (this.streamClaimed) throw new AISDKError$1({
10311
+ name: "AI_StreamAlreadyConsumedError",
10312
+ message: "This result supports one stream consumer. Choose one stream projection or response helper."
10313
+ });
10314
+ this.streamClaimed = true;
10315
+ const reader = this.baseStream.getReader();
10316
+ const rejectResults = (error) => this.rejectResultPromises(error);
10317
+ return new ReadableStream({
10318
+ async pull(controller) {
10319
+ try {
10320
+ const { done, value } = await reader.read();
10321
+ if (done) {
10322
+ reader.releaseLock();
10323
+ controller.close();
10324
+ } else controller.enqueue(value);
10325
+ } catch (error) {
10326
+ rejectResults(error);
10327
+ reader.releaseLock();
10328
+ controller.error(error);
10329
+ }
10330
+ },
10331
+ async cancel(reason) {
10332
+ rejectResults(reason ?? new DOMException("The stream was cancelled.", "AbortError"));
10333
+ try {
10334
+ await reader.cancel(reason);
10335
+ } finally {
10336
+ reader.releaseLock();
10337
+ }
10338
+ }
10339
+ }, { highWaterMark: 0 });
10340
+ }
10281
10341
  const [stream1, stream2] = this.baseStream.tee();
10282
10342
  this.baseStream = stream2;
10283
10343
  return stream1;
10284
10344
  }
10285
10345
  get textStream() {
10286
- return createAsyncIterableStream(toTextStream({ stream: this.stream }));
10346
+ return this.asIterableStream(toTextStream({ stream: this.stream }));
10347
+ }
10348
+ asIterableStream(stream) {
10349
+ return this.retention.replay ? createAsyncIterableStream(stream) : asAsyncIterableStream(stream);
10287
10350
  }
10288
10351
  get stream() {
10289
- return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {
10352
+ return this.asIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {
10290
10353
  controller.enqueue(part);
10291
10354
  } })));
10292
10355
  }
@@ -10322,9 +10385,10 @@ var DefaultStreamTextResult = class {
10322
10385
  }
10323
10386
  }
10324
10387
  async consumeStream(options) {
10388
+ const stream = this.stream;
10325
10389
  try {
10326
10390
  await consumeStream({
10327
- stream: this.stream,
10391
+ stream,
10328
10392
  onError: (error) => {
10329
10393
  this.rejectResultPromises(error);
10330
10394
  options?.onError?.(error);
@@ -10339,25 +10403,27 @@ var DefaultStreamTextResult = class {
10339
10403
  return this.partialOutputStream;
10340
10404
  }
10341
10405
  get partialOutputStream() {
10342
- return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {
10406
+ if (!this.retention.replay && this.outputSpecification == null) throw new UnsupportedFunctionalityError$1({ functionality: "partialOutputStream without an explicit output specification with experimental_lowMemory enabled" });
10407
+ return this.asIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {
10343
10408
  if (partialOutput !== void 0) controller.enqueue(partialOutput);
10344
10409
  } })));
10345
10410
  }
10346
10411
  get elementStream() {
10347
10412
  const transform = this.outputSpecification?.createElementStreamTransform();
10348
10413
  if (transform == null) throw new UnsupportedFunctionalityError$1({ functionality: `element streams in ${this.outputSpecification?.name ?? "text"} mode` });
10349
- return createAsyncIterableStream(this.teeStream().pipeThrough(transform));
10414
+ return this.asIterableStream(this.teeStream().pipeThrough(transform));
10350
10415
  }
10351
10416
  getOutputPromise() {
10352
- if (this.outputPromise == null) this.outputPromise = this.finalStep.then((step) => {
10353
- return (this.outputSpecification ?? text()).parseCompleteOutput({ text: step.text }, {
10354
- response: step.response,
10355
- usage: step.usage,
10356
- finishReason: step.finishReason
10357
- });
10358
- });
10417
+ if (this.outputPromise == null) this.outputPromise = this.finalStep.then((step) => this.parseOutput(step));
10359
10418
  return this.outputPromise;
10360
10419
  }
10420
+ parseOutput(step) {
10421
+ return (this.outputSpecification ?? text()).parseCompleteOutput({ text: step.text }, {
10422
+ response: step.response,
10423
+ usage: step.usage,
10424
+ finishReason: step.finishReason
10425
+ });
10426
+ }
10361
10427
  get output() {
10362
10428
  return this.getOutputPromise();
10363
10429
  }
@@ -10574,7 +10640,8 @@ var ToolLoopAgent = class {
10574
10640
  return await stream({
10575
10641
  ...preparedCall,
10576
10642
  ...callbackArgs,
10577
- headers: this.agentHeaders(preparedCall)
10643
+ headers: this.agentHeaders(preparedCall),
10644
+ experimental_lowMemory: false
10578
10645
  });
10579
10646
  }
10580
10647
  };
@@ -12937,6 +13004,7 @@ function validateDecisionInput({ state, questions }) {
12937
13004
  for (const [id, question] of Object.entries(questions)) {
12938
13005
  const parameter = `questions.${id}`;
12939
13006
  if (!isRecord$1(question) || !isInput(question.instructions)) invalidInput(parameter, question, "instructions must be a JSON-compatible string, object, or array");
13007
+ if (question.type === "box") continue;
12940
13008
  const criteria = question.criteria;
12941
13009
  switch (question.type) {
12942
13010
  case "choice":
@@ -12949,7 +13017,7 @@ function validateDecisionInput({ state, questions }) {
12949
13017
  if (criteria === void 0) continue;
12950
13018
  if (!isRecord$1(criteria) || Object.keys(criteria).some((key) => key !== "true" && key !== "false")) invalidInput(parameter, question, "boolean criteria may only describe true and false");
12951
13019
  break;
12952
- default: invalidInput(parameter, question, "question type must be choice, score, or boolean");
13020
+ default: invalidInput(parameter, question, "question type must be choice, score, boolean, or box");
12953
13021
  }
12954
13022
  if (!isJSON(criteria) || Object.values(criteria).some((value) => value !== null && !isInput(value))) invalidInput(parameter, question, "criteria descriptions must be JSON-compatible strings, objects, arrays, or null");
12955
13023
  }
@@ -13003,6 +13071,16 @@ function validateDecisionAnswers({ questions, answers, rounding }) {
13003
13071
  if (Math.abs(mean - answer.score) > tolerance + meanRoundingError + scoreError) invalidAnswer(answers, `Question "${id}" score must equal the probability-weighted mean within the declared rounding precision.`);
13004
13072
  }
13005
13073
  break;
13074
+ case "box": {
13075
+ const box = answer.box;
13076
+ if (!isRecord$1(box) || !hasExactKeys(box, [
13077
+ "top",
13078
+ "bottom",
13079
+ "left",
13080
+ "right"
13081
+ ]) || !isProbability(box.left) || !isProbability(box.right) || !isProbability(box.top) || !isProbability(box.bottom) || !(box.left < box.right) || !(box.top < box.bottom)) invalidAnswer(answers, `Question "${id}" must return box edges in [0, 1] with left < right and top < bottom.`);
13082
+ break;
13083
+ }
13006
13084
  case "boolean": if (!isProbability(answer.probability)) invalidAnswer(answers, `Question "${id}" must return P(true) as a finite probability in [0, 1].`);
13007
13085
  }
13008
13086
  }
@@ -19849,7 +19927,10 @@ var DefaultChatTransport = class extends HttpChatTransport {
19849
19927
  //#endregion
19850
19928
  //#region src/ui/chat.ts
19851
19929
  var AbstractChat = class {
19852
- constructor({ generateId = generateId$1, id = generateId(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {
19930
+ get id() {
19931
+ return this._id ??= this.generateId();
19932
+ }
19933
+ constructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {
19853
19934
  this.pendingMessagePreparations = /* @__PURE__ */ new Set();
19854
19935
  this.activeResponse = void 0;
19855
19936
  this.activeResumeRequest = void 0;
@@ -20056,7 +20137,7 @@ var AbstractChat = class {
20056
20137
  await this.stop();
20057
20138
  this.transport.close?.();
20058
20139
  };
20059
- this.id = id;
20140
+ this._id = id;
20060
20141
  this.transport = transport;
20061
20142
  this.generateId = generateId;
20062
20143
  this.messageMetadataSchema = messageMetadataSchema;