ai 7.0.154 → 7.0.155

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
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { GatewayAuthenticationError, GatewayError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
3
3
  import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getWebSocketConstructor, isAbortError, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
4
- import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidArgumentError as InvalidArgumentError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
4
+ import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
5
5
  import { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, string, union, unknown } from "zod/v4";
6
6
  //#region src/error/invalid-argument-error.ts
7
7
  const name$23 = "AI_InvalidArgumentError";
@@ -1175,7 +1175,7 @@ function cloneValue(value) {
1175
1175
  }
1176
1176
  //#endregion
1177
1177
  //#region src/version.ts
1178
- const VERSION = "7.0.154";
1178
+ const VERSION = "7.0.155";
1179
1179
  //#endregion
1180
1180
  //#region src/util/download/download.ts
1181
1181
  /**
@@ -1928,41 +1928,6 @@ function prepareLanguageModelCallOptions({ maxOutputTokens, temperature, topP, t
1928
1928
  message: "maxOutputTokens must be >= 1"
1929
1929
  });
1930
1930
  }
1931
- if (temperature != null) {
1932
- if (typeof temperature !== "number") throw new InvalidArgumentError({
1933
- parameter: "temperature",
1934
- value: temperature,
1935
- message: "temperature must be a number"
1936
- });
1937
- }
1938
- if (topP != null) {
1939
- if (typeof topP !== "number") throw new InvalidArgumentError({
1940
- parameter: "topP",
1941
- value: topP,
1942
- message: "topP must be a number"
1943
- });
1944
- }
1945
- if (topK != null) {
1946
- if (typeof topK !== "number") throw new InvalidArgumentError({
1947
- parameter: "topK",
1948
- value: topK,
1949
- message: "topK must be a number"
1950
- });
1951
- }
1952
- if (presencePenalty != null) {
1953
- if (typeof presencePenalty !== "number") throw new InvalidArgumentError({
1954
- parameter: "presencePenalty",
1955
- value: presencePenalty,
1956
- message: "presencePenalty must be a number"
1957
- });
1958
- }
1959
- if (frequencyPenalty != null) {
1960
- if (typeof frequencyPenalty !== "number") throw new InvalidArgumentError({
1961
- parameter: "frequencyPenalty",
1962
- value: frequencyPenalty,
1963
- message: "frequencyPenalty must be a number"
1964
- });
1965
- }
1966
1931
  if (seed != null) {
1967
1932
  if (!Number.isInteger(seed)) throw new InvalidArgumentError({
1968
1933
  parameter: "seed",
@@ -2105,708 +2070,368 @@ function getToolTimeoutMs(timeout, toolName) {
2105
2070
  return timeout.tools?.[`${toolName}Ms`] ?? timeout.toolMs;
2106
2071
  }
2107
2072
  //#endregion
2108
- //#region src/util/zod.ts
2109
- const z = {
2110
- array,
2111
- boolean,
2112
- custom,
2113
- discriminatedUnion,
2114
- enum: enum$1,
2115
- instanceof: instanceof$1,
2116
- lazy,
2117
- literal,
2118
- looseObject,
2119
- never,
2120
- null: null$1,
2121
- number,
2122
- object,
2123
- record,
2124
- string,
2125
- union,
2126
- unknown
2127
- };
2073
+ //#region src/prompt/standardize-prompt.ts
2074
+ /**
2075
+ * Converts a prompt input into a standardized prompt with model messages.
2076
+ *
2077
+ * @param prompt - The prompt definition to standardize.
2078
+ * Set `allowSystemInMessages` to true to allow system messages in the
2079
+ * `prompt` or `messages` fields. System messages in the `instructions`
2080
+ * option are always allowed.
2081
+ * @returns The standardized prompt.
2082
+ * @throws {InvalidPromptError} When the prompt is invalid.
2083
+ */
2084
+ async function standardizePrompt({ allowSystemInMessages = false, system, instructions = system, prompt, messages }) {
2085
+ messages = prompt == null ? messages : typeof prompt === "string" ? [{
2086
+ role: "user",
2087
+ content: prompt
2088
+ }] : prompt;
2089
+ if (messages.length === 0) throw new InvalidPromptError$1({
2090
+ prompt,
2091
+ message: "messages must not be empty"
2092
+ });
2093
+ if (!allowSystemInMessages && messages.some((message) => message.role === "system")) throw new InvalidPromptError$1({
2094
+ prompt,
2095
+ message: "System messages are not allowed in the prompt or messages fields. Use the instructions option instead."
2096
+ });
2097
+ return {
2098
+ messages,
2099
+ instructions
2100
+ };
2101
+ }
2128
2102
  //#endregion
2129
- //#region src/types/json-value.ts
2130
- const jsonValueSchema = z.lazy(() => z.union([
2131
- z.null(),
2132
- z.string(),
2133
- z.number(),
2134
- z.boolean(),
2135
- z.record(z.string(), jsonValueSchema.optional()),
2136
- z.array(jsonValueSchema)
2137
- ]));
2103
+ //#region src/prompt/wrap-gateway-error.ts
2104
+ function wrapGatewayError(error) {
2105
+ if (!GatewayAuthenticationError.isInstance(error)) return error;
2106
+ const isProductionEnv = process?.env.NODE_ENV === "production";
2107
+ const moreInfoURL = "https://ai-sdk.dev/unauthenticated-ai-gateway";
2108
+ if (isProductionEnv) return new AISDKError$1({
2109
+ name: "GatewayError",
2110
+ message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`
2111
+ });
2112
+ return Object.assign(/* @__PURE__ */ new Error(`\u001b[1m\u001b[31mUnauthenticated request to AI Gateway.\u001b[0m
2113
+
2114
+ To authenticate, set the \u001b[33mAI_GATEWAY_API_KEY\u001b[0m environment variable with your API key.
2115
+
2116
+ Alternatively, you can use a provider module instead of the AI Gateway.
2117
+
2118
+ Learn more: \u001b[34m${moreInfoURL}\u001b[0m
2119
+
2120
+ `), { name: "GatewayAuthenticationError" });
2121
+ }
2138
2122
  //#endregion
2139
- //#region src/types/provider-metadata.ts
2140
- const providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
2123
+ //#region src/types/usage.ts
2124
+ function asLanguageModelUsage(usage) {
2125
+ return {
2126
+ inputTokens: usage.inputTokens.total,
2127
+ inputTokenDetails: {
2128
+ noCacheTokens: usage.inputTokens.noCache,
2129
+ cacheReadTokens: usage.inputTokens.cacheRead,
2130
+ cacheWriteTokens: usage.inputTokens.cacheWrite
2131
+ },
2132
+ outputTokens: usage.outputTokens.total,
2133
+ outputTokenDetails: {
2134
+ textTokens: usage.outputTokens.text,
2135
+ reasoningTokens: usage.outputTokens.reasoning
2136
+ },
2137
+ totalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total),
2138
+ raw: usage.raw
2139
+ };
2140
+ }
2141
+ function createNullLanguageModelUsage() {
2142
+ return {
2143
+ inputTokens: void 0,
2144
+ inputTokenDetails: {
2145
+ noCacheTokens: void 0,
2146
+ cacheReadTokens: void 0,
2147
+ cacheWriteTokens: void 0
2148
+ },
2149
+ outputTokens: void 0,
2150
+ outputTokenDetails: {
2151
+ textTokens: void 0,
2152
+ reasoningTokens: void 0
2153
+ },
2154
+ totalTokens: void 0,
2155
+ raw: void 0
2156
+ };
2157
+ }
2158
+ function addLanguageModelUsage(usage1, usage2) {
2159
+ const raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;
2160
+ return {
2161
+ inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2162
+ inputTokenDetails: {
2163
+ noCacheTokens: addTokenCounts(usage1.inputTokenDetails?.noCacheTokens, usage2.inputTokenDetails?.noCacheTokens),
2164
+ cacheReadTokens: addTokenCounts(usage1.inputTokenDetails?.cacheReadTokens, usage2.inputTokenDetails?.cacheReadTokens),
2165
+ cacheWriteTokens: addTokenCounts(usage1.inputTokenDetails?.cacheWriteTokens, usage2.inputTokenDetails?.cacheWriteTokens)
2166
+ },
2167
+ outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
2168
+ outputTokenDetails: {
2169
+ textTokens: addTokenCounts(usage1.outputTokenDetails?.textTokens, usage2.outputTokenDetails?.textTokens),
2170
+ reasoningTokens: addTokenCounts(usage1.outputTokenDetails?.reasoningTokens, usage2.outputTokenDetails?.reasoningTokens)
2171
+ },
2172
+ totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),
2173
+ ...raw == null ? {} : { raw }
2174
+ };
2175
+ }
2176
+ function isNullLanguageModelUsage(usage) {
2177
+ return usage.inputTokens == null && usage.inputTokenDetails?.noCacheTokens == null && usage.inputTokenDetails?.cacheReadTokens == null && usage.inputTokenDetails?.cacheWriteTokens == null && usage.outputTokens == null && usage.outputTokenDetails?.textTokens == null && usage.outputTokenDetails?.reasoningTokens == null && usage.totalTokens == null && usage.raw == null;
2178
+ }
2179
+ function addTokenCounts(tokenCount1, tokenCount2) {
2180
+ return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);
2181
+ }
2182
+ function addImageModelUsage(usage1, usage2) {
2183
+ return {
2184
+ inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2185
+ outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
2186
+ totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)
2187
+ };
2188
+ }
2141
2189
  //#endregion
2142
- //#region src/prompt/content-part.ts
2143
- const fileInlineDataSchema = z.union([
2144
- z.string(),
2145
- z.instanceof(Uint8Array),
2146
- z.instanceof(ArrayBuffer),
2147
- z.custom(isBuffer, { message: "Must be a Buffer" })
2148
- ]);
2149
- const providerReferenceSchema$1 = z.record(z.string(), z.string());
2150
- /**
2151
- * @internal
2152
- */
2153
- const textPartSchema = z.object({
2154
- type: z.literal("text"),
2155
- text: z.string(),
2156
- providerOptions: providerMetadataSchema.optional()
2157
- });
2190
+ //#region src/util/get-own.ts
2158
2191
  /**
2159
- * @internal
2160
- * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:
2161
- * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
2192
+ * Reads a property by an untrusted key, ignoring inherited prototype members.
2193
+ *
2194
+ * Tool sets, tool contexts, and similar lookup objects are indexed by names
2195
+ * that can come from model output or client-supplied message history. Plain
2196
+ * bracket access (`obj[name]`) resolves names such as `constructor`,
2197
+ * `toString`, or `__proto__` to values on `Object.prototype`, which would slip
2198
+ * past the `== null` / `!value` guards that treat an unknown name as "not
2199
+ * present". This helper returns `undefined` unless `key` is an own property.
2162
2200
  */
2163
- const imagePartSchema = z.object({
2164
- type: z.literal("image"),
2165
- image: z.union([
2166
- fileInlineDataSchema,
2167
- z.instanceof(URL),
2168
- providerReferenceSchema$1
2169
- ]),
2170
- mediaType: z.string().optional(),
2171
- providerOptions: providerMetadataSchema.optional()
2172
- });
2173
- const taggedFileDataSchema = z.discriminatedUnion("type", [
2174
- z.object({
2175
- type: z.literal("data"),
2176
- data: fileInlineDataSchema
2177
- }),
2178
- z.object({
2179
- type: z.literal("url"),
2180
- url: z.instanceof(URL)
2181
- }),
2182
- z.object({
2183
- type: z.literal("reference"),
2184
- reference: providerReferenceSchema$1
2185
- }),
2186
- z.object({
2187
- type: z.literal("text"),
2188
- text: z.string()
2189
- })
2190
- ]);
2191
- const taggedReasoningFileDataSchema = z.discriminatedUnion("type", [z.object({
2192
- type: z.literal("data"),
2193
- data: fileInlineDataSchema
2194
- }), z.object({
2195
- type: z.literal("url"),
2196
- url: z.instanceof(URL)
2197
- })]);
2201
+ function getOwn(obj, key) {
2202
+ return obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;
2203
+ }
2204
+ //#endregion
2205
+ //#region src/util/merge-abort-signals.ts
2198
2206
  /**
2199
- * @internal
2207
+ * Merges multiple abort sources into a single `AbortSignal`.
2208
+ * The returned signal will abort when any input signal aborts or when any
2209
+ * numeric timeout elapses, using the reason from the first source to abort.
2210
+ *
2211
+ * @param signals - Abort signals or timeout durations in milliseconds.
2212
+ * `null` and `undefined` values are ignored.
2213
+ * @returns An `AbortSignal` that aborts when any valid source aborts,
2214
+ * or `undefined` if no valid sources are provided.
2200
2215
  */
2201
- const filePartSchema = z.object({
2202
- type: z.literal("file"),
2203
- data: z.union([
2204
- taggedFileDataSchema,
2205
- fileInlineDataSchema,
2206
- z.instanceof(URL),
2207
- providerReferenceSchema$1
2208
- ]),
2209
- filename: z.string().optional(),
2210
- mediaType: z.string(),
2211
- providerOptions: providerMetadataSchema.optional()
2212
- });
2216
+ function mergeAbortSignals(...signals) {
2217
+ const validSignals = filterNullable(...signals).map((signal) => typeof signal === "number" ? AbortSignal.timeout(signal) : signal);
2218
+ return validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);
2219
+ }
2220
+ //#endregion
2221
+ //#region src/util/now.ts
2222
+ function now() {
2223
+ return globalThis?.performance?.now() ?? Date.now();
2224
+ }
2225
+ //#endregion
2226
+ //#region src/util/notify.ts
2213
2227
  /**
2214
- * @internal
2228
+ * Notifies all provided callbacks with the given event in parallel.
2229
+ * Errors in callbacks do not break the generation flow.
2215
2230
  */
2216
- const reasoningPartSchema = z.object({
2217
- type: z.literal("reasoning"),
2218
- text: z.string(),
2219
- providerOptions: providerMetadataSchema.optional()
2220
- });
2221
- /**
2222
- * @internal
2223
- */
2224
- const customPartSchema = z.object({
2225
- type: z.literal("custom"),
2226
- kind: z.string().transform((value) => value),
2227
- providerOptions: providerMetadataSchema.optional()
2228
- });
2229
- /**
2230
- * @internal
2231
- */
2232
- const reasoningFilePartSchema = z.object({
2233
- type: z.literal("reasoning-file"),
2234
- data: z.union([
2235
- taggedReasoningFileDataSchema,
2236
- fileInlineDataSchema,
2237
- z.instanceof(URL)
2238
- ]),
2239
- mediaType: z.string(),
2240
- providerOptions: providerMetadataSchema.optional()
2241
- });
2242
- /**
2243
- * @internal
2244
- */
2245
- const toolCallPartSchema = z.object({
2246
- type: z.literal("tool-call"),
2247
- toolCallId: z.string(),
2248
- toolName: z.string(),
2249
- input: z.unknown(),
2250
- providerOptions: providerMetadataSchema.optional(),
2251
- providerExecuted: z.boolean().optional()
2252
- });
2231
+ async function notify(options) {
2232
+ await Promise.all(asArray(options.callbacks).map(async (callback) => {
2233
+ try {
2234
+ await callback?.(options.event);
2235
+ } catch {}
2236
+ }));
2237
+ }
2238
+ //#endregion
2239
+ //#region src/util/retry-with-exponential-backoff.ts
2240
+ function getRetryDelayInMs({ error, exponentialBackoffDelay }) {
2241
+ const headers = APICallError$1.isInstance(error) ? error.responseHeaders : APICallError$1.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
2242
+ if (!headers) return exponentialBackoffDelay;
2243
+ let ms;
2244
+ const retryAfterMs = headers["retry-after-ms"];
2245
+ if (retryAfterMs) {
2246
+ const timeoutMs = parseFloat(retryAfterMs);
2247
+ if (!Number.isNaN(timeoutMs)) ms = timeoutMs;
2248
+ }
2249
+ const retryAfter = headers["retry-after"];
2250
+ if (retryAfter && ms === void 0) {
2251
+ const timeoutSeconds = parseFloat(retryAfter);
2252
+ if (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;
2253
+ else ms = Date.parse(retryAfter) - Date.now();
2254
+ }
2255
+ if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;
2256
+ return exponentialBackoffDelay;
2257
+ }
2253
2258
  /**
2254
- * @internal
2259
+ * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,
2260
+ * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).
2261
+ * You can configure the maximum number of retries, the initial delay, and the backoff factor.
2255
2262
  */
2256
- const outputSchema = z.discriminatedUnion("type", [
2257
- z.object({
2258
- type: z.literal("text"),
2259
- value: z.string(),
2260
- providerOptions: providerMetadataSchema.optional()
2261
- }),
2262
- z.object({
2263
- type: z.literal("json"),
2264
- value: jsonValueSchema,
2265
- providerOptions: providerMetadataSchema.optional()
2266
- }),
2267
- z.object({
2268
- type: z.literal("execution-denied"),
2269
- reason: z.string().optional(),
2270
- providerOptions: providerMetadataSchema.optional()
2271
- }),
2272
- z.object({
2273
- type: z.literal("error-text"),
2274
- value: z.string(),
2275
- providerOptions: providerMetadataSchema.optional()
2276
- }),
2277
- z.object({
2278
- type: z.literal("error-json"),
2279
- value: jsonValueSchema,
2280
- providerOptions: providerMetadataSchema.optional()
2263
+ const retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => retryWithExponentialBackoff({
2264
+ maxRetries,
2265
+ initialDelayInMs,
2266
+ backoffFactor,
2267
+ abortSignal,
2268
+ shouldRetry: async (error) => error instanceof Error && (APICallError$1.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || additionalRetryableError != null && await additionalRetryableError(error),
2269
+ getDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs({
2270
+ error,
2271
+ exponentialBackoffDelay
2281
2272
  }),
2282
- z.object({
2283
- type: z.literal("content"),
2284
- value: z.array(z.union([
2285
- z.object({
2286
- type: z.literal("text"),
2287
- text: z.string(),
2288
- providerOptions: providerMetadataSchema.optional()
2289
- }),
2290
- z.object({
2291
- type: z.literal("file"),
2292
- data: taggedFileDataSchema,
2293
- mediaType: z.string(),
2294
- filename: z.string().optional(),
2295
- providerOptions: providerMetadataSchema.optional()
2296
- }),
2297
- z.object({
2298
- type: z.literal("file-data"),
2299
- data: z.string(),
2300
- mediaType: z.string(),
2301
- filename: z.string().optional(),
2302
- providerOptions: providerMetadataSchema.optional()
2303
- }),
2304
- z.object({
2305
- type: z.literal("file-url"),
2306
- url: z.string(),
2307
- mediaType: z.string().optional(),
2308
- providerOptions: providerMetadataSchema.optional()
2309
- }),
2310
- z.object({
2311
- type: z.literal("file-id"),
2312
- fileId: z.union([z.string(), z.record(z.string(), z.string())]),
2313
- providerOptions: providerMetadataSchema.optional()
2314
- }),
2315
- z.object({
2316
- type: z.literal("file-reference"),
2317
- providerReference: z.record(z.string(), z.string()),
2318
- providerOptions: providerMetadataSchema.optional()
2319
- }),
2320
- z.object({
2321
- type: z.literal("image-data"),
2322
- data: z.string(),
2323
- mediaType: z.string(),
2324
- providerOptions: providerMetadataSchema.optional()
2325
- }),
2326
- z.object({
2327
- type: z.literal("image-url"),
2328
- url: z.string(),
2329
- providerOptions: providerMetadataSchema.optional()
2330
- }),
2331
- z.object({
2332
- type: z.literal("image-file-id"),
2333
- fileId: z.union([z.string(), z.record(z.string(), z.string())]),
2334
- providerOptions: providerMetadataSchema.optional()
2335
- }),
2336
- z.object({
2337
- type: z.literal("image-file-reference"),
2338
- providerReference: z.record(z.string(), z.string()),
2339
- providerOptions: providerMetadataSchema.optional()
2340
- }),
2341
- z.object({
2342
- type: z.literal("custom"),
2343
- providerOptions: providerMetadataSchema.optional()
2344
- })
2345
- ]))
2273
+ createRetryError: ({ message, reason, errors }) => new RetryError({
2274
+ message,
2275
+ reason,
2276
+ errors
2346
2277
  })
2347
- ]);
2278
+ });
2279
+ //#endregion
2280
+ //#region src/util/prepare-retries.ts
2348
2281
  /**
2349
- * @internal
2282
+ * Validate and prepare retries.
2350
2283
  */
2351
- const toolResultPartSchema = z.object({
2352
- type: z.literal("tool-result"),
2353
- toolCallId: z.string(),
2354
- toolName: z.string(),
2355
- output: outputSchema,
2356
- providerOptions: providerMetadataSchema.optional()
2357
- });
2284
+ function prepareRetries({ maxRetries, abortSignal, additionalRetryableError, parameter = "maxRetries", defaultMaxRetries = 2 }) {
2285
+ if (maxRetries != null) {
2286
+ if (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({
2287
+ parameter,
2288
+ value: maxRetries,
2289
+ message: `${parameter} must be an integer`
2290
+ });
2291
+ if (maxRetries < 0) throw new InvalidArgumentError({
2292
+ parameter,
2293
+ value: maxRetries,
2294
+ message: `${parameter} must be >= 0`
2295
+ });
2296
+ }
2297
+ const maxRetriesResult = maxRetries ?? defaultMaxRetries;
2298
+ return {
2299
+ maxRetries: maxRetriesResult,
2300
+ retry: retryWithExponentialBackoffRespectingRetryHeaders({
2301
+ maxRetries: maxRetriesResult,
2302
+ abortSignal,
2303
+ additionalRetryableError
2304
+ })
2305
+ };
2306
+ }
2307
+ //#endregion
2308
+ //#region src/util/set-abort-timeout.ts
2358
2309
  /**
2359
- * @internal
2310
+ * Schedules a timeout that aborts the given controller with a `TimeoutError`
2311
+ * `DOMException`, matching the reason produced by `AbortSignal.timeout(ms)`.
2312
+ *
2313
+ * @param abortController - The controller to abort when the timeout elapses.
2314
+ * If undefined, no timeout is scheduled.
2315
+ * @param label - Human-readable label included in the error message
2316
+ * (e.g. "Step", "Chunk").
2317
+ * @param timeoutMs - Duration in milliseconds before the controller is aborted.
2318
+ * If undefined, no timeout is scheduled.
2319
+ * @returns The timeout id (suitable for passing to `clearTimeout`), or
2320
+ * `undefined` if no timeout was scheduled.
2360
2321
  */
2361
- const toolApprovalRequestSchema = z.object({
2362
- type: z.literal("tool-approval-request"),
2363
- approvalId: z.string(),
2364
- toolCallId: z.string(),
2365
- reason: z.string().optional(),
2366
- isAutomatic: z.boolean().optional(),
2367
- signature: z.string().optional(),
2368
- inputSchemaInput: z.unknown().optional()
2369
- });
2322
+ function setAbortTimeout({ abortController, label, timeoutMs }) {
2323
+ if (abortController == null || timeoutMs == null) return;
2324
+ return setTimeout(() => abortController.abort(new DOMException(`${label} timeout of ${timeoutMs}ms exceeded`, "TimeoutError")), timeoutMs);
2325
+ }
2326
+ //#endregion
2327
+ //#region src/generate-text/calculate-tokens-per-second.ts
2370
2328
  /**
2371
- * @internal
2329
+ * Calculates a token rate in tokens per second.
2330
+ *
2331
+ * Returns 0 when the token count is unknown, the duration is unknown or 0, or
2332
+ * the computed rate cannot be represented as a finite JSON-safe number.
2372
2333
  */
2373
- const toolApprovalResponseSchema = z.object({
2374
- type: z.literal("tool-approval-response"),
2375
- approvalId: z.string(),
2376
- approved: z.boolean(),
2377
- reason: z.string().optional()
2378
- });
2334
+ function calculateTokensPerSecond({ tokens, durationMs }) {
2335
+ const tokenRate = 1e3 * (tokens ?? 0) / (durationMs ?? 0);
2336
+ return Number.isFinite(tokenRate) ? tokenRate : 0;
2337
+ }
2379
2338
  //#endregion
2380
- //#region src/prompt/message.ts
2381
- const systemModelMessageSchema = z.object({
2382
- role: z.literal("system"),
2383
- content: z.string(),
2384
- providerOptions: providerMetadataSchema.optional()
2385
- });
2386
- const userModelMessageSchema = z.object({
2387
- role: z.literal("user"),
2388
- content: z.union([z.string(), z.array(z.union([
2389
- textPartSchema,
2390
- imagePartSchema,
2391
- filePartSchema
2392
- ]))]),
2393
- providerOptions: providerMetadataSchema.optional()
2394
- });
2395
- const assistantModelMessageSchema = z.object({
2396
- role: z.literal("assistant"),
2397
- content: z.union([z.string(), z.array(z.union([
2398
- textPartSchema,
2399
- customPartSchema,
2400
- filePartSchema,
2401
- reasoningPartSchema,
2402
- reasoningFilePartSchema,
2403
- toolCallPartSchema,
2404
- toolResultPartSchema,
2405
- toolApprovalRequestSchema
2406
- ]))]),
2407
- providerOptions: providerMetadataSchema.optional()
2408
- });
2409
- const toolModelMessageSchema = z.object({
2410
- role: z.literal("tool"),
2411
- content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),
2412
- providerOptions: providerMetadataSchema.optional()
2413
- });
2414
- const modelMessageSchema = z.union([
2415
- systemModelMessageSchema,
2416
- userModelMessageSchema,
2417
- assistantModelMessageSchema,
2418
- toolModelMessageSchema
2419
- ]);
2420
- //#endregion
2421
- //#region src/prompt/standardize-prompt.ts
2339
+ //#region src/generate-text/collect-tool-approvals.ts
2422
2340
  /**
2423
- * Converts a prompt input into a standardized prompt with validated model
2424
- * messages.
2425
- *
2426
- * @param prompt - The prompt definition to standardize.
2427
- * Set `allowSystemInMessages` to true to allow system messages in the
2428
- * `prompt` or `messages` fields. System messages in the `instructions`
2429
- * option are always allowed.
2430
- * @returns The standardized prompt.
2431
- * @throws {InvalidPromptError} When the prompt is invalid.
2341
+ * If the last message is a tool message, this function collects all tool approvals
2342
+ * from that message.
2432
2343
  */
2433
- async function standardizePrompt({ allowSystemInMessages = false, system, instructions = system, prompt, messages }) {
2434
- if (prompt == null && messages == null) throw new InvalidPromptError$1({
2435
- prompt,
2436
- message: "prompt or messages must be defined"
2437
- });
2438
- if (prompt != null && messages != null) throw new InvalidPromptError$1({
2439
- prompt,
2440
- message: "prompt and messages cannot be defined at the same time"
2441
- });
2442
- if (typeof instructions !== "string" && !asArray(instructions).every((message) => message.role === "system")) throw new InvalidPromptError$1({
2443
- prompt,
2444
- message: "instructions must be a string, SystemModelMessage, or array of SystemModelMessage"
2445
- });
2446
- if (prompt != null && typeof prompt === "string") messages = [{
2447
- role: "user",
2448
- content: prompt
2449
- }];
2450
- else if (prompt != null && Array.isArray(prompt)) messages = prompt;
2451
- else if (messages == null) throw new InvalidPromptError$1({
2452
- prompt,
2453
- message: "prompt or messages must be defined"
2454
- });
2455
- if (messages.length === 0) throw new InvalidPromptError$1({
2456
- prompt,
2457
- message: "messages must not be empty"
2458
- });
2459
- if (!allowSystemInMessages && messages.some((message) => message.role === "system")) throw new InvalidPromptError$1({
2460
- prompt,
2461
- message: "System messages are not allowed in the prompt or messages fields. Use the instructions option instead."
2462
- });
2463
- const validationResult = await safeValidateTypes({
2464
- value: messages,
2465
- schema: z.array(modelMessageSchema)
2466
- });
2467
- if (!validationResult.success) throw new InvalidPromptError$1({
2468
- prompt,
2469
- message: "The messages do not match the ModelMessage[] schema.",
2470
- cause: validationResult.error
2471
- });
2472
- return {
2473
- messages,
2474
- instructions
2475
- };
2476
- }
2477
- //#endregion
2478
- //#region src/prompt/wrap-gateway-error.ts
2479
- function wrapGatewayError(error) {
2480
- if (!GatewayAuthenticationError.isInstance(error)) return error;
2481
- const isProductionEnv = process?.env.NODE_ENV === "production";
2482
- const moreInfoURL = "https://ai-sdk.dev/unauthenticated-ai-gateway";
2483
- if (isProductionEnv) return new AISDKError$1({
2484
- name: "GatewayError",
2485
- message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`
2486
- });
2487
- return Object.assign(/* @__PURE__ */ new Error(`\u001b[1m\u001b[31mUnauthenticated request to AI Gateway.\u001b[0m
2488
-
2489
- To authenticate, set the \u001b[33mAI_GATEWAY_API_KEY\u001b[0m environment variable with your API key.
2490
-
2491
- Alternatively, you can use a provider module instead of the AI Gateway.
2492
-
2493
- Learn more: \u001b[34m${moreInfoURL}\u001b[0m
2494
-
2495
- `), { name: "GatewayAuthenticationError" });
2496
- }
2497
- //#endregion
2498
- //#region src/types/usage.ts
2499
- function asLanguageModelUsage(usage) {
2500
- return {
2501
- inputTokens: usage.inputTokens.total,
2502
- inputTokenDetails: {
2503
- noCacheTokens: usage.inputTokens.noCache,
2504
- cacheReadTokens: usage.inputTokens.cacheRead,
2505
- cacheWriteTokens: usage.inputTokens.cacheWrite
2506
- },
2507
- outputTokens: usage.outputTokens.total,
2508
- outputTokenDetails: {
2509
- textTokens: usage.outputTokens.text,
2510
- reasoningTokens: usage.outputTokens.reasoning
2511
- },
2512
- totalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total),
2513
- raw: usage.raw
2514
- };
2515
- }
2516
- function createNullLanguageModelUsage() {
2517
- return {
2518
- inputTokens: void 0,
2519
- inputTokenDetails: {
2520
- noCacheTokens: void 0,
2521
- cacheReadTokens: void 0,
2522
- cacheWriteTokens: void 0
2523
- },
2524
- outputTokens: void 0,
2525
- outputTokenDetails: {
2526
- textTokens: void 0,
2527
- reasoningTokens: void 0
2528
- },
2529
- totalTokens: void 0,
2530
- raw: void 0
2531
- };
2532
- }
2533
- function addLanguageModelUsage(usage1, usage2) {
2534
- const raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;
2535
- return {
2536
- inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2537
- inputTokenDetails: {
2538
- noCacheTokens: addTokenCounts(usage1.inputTokenDetails?.noCacheTokens, usage2.inputTokenDetails?.noCacheTokens),
2539
- cacheReadTokens: addTokenCounts(usage1.inputTokenDetails?.cacheReadTokens, usage2.inputTokenDetails?.cacheReadTokens),
2540
- cacheWriteTokens: addTokenCounts(usage1.inputTokenDetails?.cacheWriteTokens, usage2.inputTokenDetails?.cacheWriteTokens)
2541
- },
2542
- outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
2543
- outputTokenDetails: {
2544
- textTokens: addTokenCounts(usage1.outputTokenDetails?.textTokens, usage2.outputTokenDetails?.textTokens),
2545
- reasoningTokens: addTokenCounts(usage1.outputTokenDetails?.reasoningTokens, usage2.outputTokenDetails?.reasoningTokens)
2546
- },
2547
- totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),
2548
- ...raw == null ? {} : { raw }
2344
+ function collectToolApprovals({ messages }) {
2345
+ const lastMessage = messages.at(-1);
2346
+ if (lastMessage?.role != "tool") return {
2347
+ approvedToolApprovals: [],
2348
+ deniedToolApprovals: []
2549
2349
  };
2550
- }
2551
- function isNullLanguageModelUsage(usage) {
2552
- return usage.inputTokens == null && usage.inputTokenDetails?.noCacheTokens == null && usage.inputTokenDetails?.cacheReadTokens == null && usage.inputTokenDetails?.cacheWriteTokens == null && usage.outputTokens == null && usage.outputTokenDetails?.textTokens == null && usage.outputTokenDetails?.reasoningTokens == null && usage.totalTokens == null && usage.raw == null;
2553
- }
2554
- function addTokenCounts(tokenCount1, tokenCount2) {
2555
- return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);
2556
- }
2557
- function addImageModelUsage(usage1, usage2) {
2350
+ const toolCallsByToolCallId = Object.create(null);
2351
+ const toolCallOrder = Object.create(null);
2352
+ let nextToolCallIndex = 0;
2353
+ for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
2354
+ const content = message.content;
2355
+ for (const part of content) if (part.type === "tool-call") {
2356
+ toolCallsByToolCallId[part.toolCallId] = part;
2357
+ toolCallOrder[part.toolCallId] = nextToolCallIndex++;
2358
+ }
2359
+ }
2360
+ const toolApprovalRequestsByApprovalId = Object.create(null);
2361
+ for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
2362
+ const content = message.content;
2363
+ for (const part of content) if (part.type === "tool-approval-request") toolApprovalRequestsByApprovalId[part.approvalId] = part;
2364
+ }
2365
+ const toolResults = Object.create(null);
2366
+ for (const part of lastMessage.content) if (part.type === "tool-result") toolResults[part.toolCallId] = part;
2367
+ const approvedToolApprovals = [];
2368
+ const deniedToolApprovals = [];
2369
+ const collectedToolCallIds = /* @__PURE__ */ new Set();
2370
+ const approvalResponses = lastMessage.content.filter((part) => part.type === "tool-approval-response");
2371
+ for (const approvalResponse of approvalResponses) {
2372
+ const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];
2373
+ if (approvalRequest == null) throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId });
2374
+ const existingToolResult = toolResults[approvalRequest.toolCallId];
2375
+ if (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== "execution-denied")) continue;
2376
+ const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
2377
+ if (toolCall == null) throw new ToolCallNotFoundForApprovalError({
2378
+ toolCallId: approvalRequest.toolCallId,
2379
+ approvalId: approvalRequest.approvalId
2380
+ });
2381
+ if (collectedToolCallIds.has(toolCall.toolCallId)) continue;
2382
+ collectedToolCallIds.add(toolCall.toolCallId);
2383
+ const approval = {
2384
+ approvalRequest,
2385
+ approvalResponse,
2386
+ toolCall,
2387
+ ...existingToolResult != null ? { existingToolResult } : {}
2388
+ };
2389
+ if (approvalResponse.approved) approvedToolApprovals.push(approval);
2390
+ else deniedToolApprovals.push(approval);
2391
+ }
2392
+ approvedToolApprovals.sort((a, b) => toolCallOrder[a.toolCall.toolCallId] - toolCallOrder[b.toolCall.toolCallId]);
2558
2393
  return {
2559
- inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2560
- outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
2561
- totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)
2394
+ approvedToolApprovals,
2395
+ deniedToolApprovals
2562
2396
  };
2563
2397
  }
2564
2398
  //#endregion
2565
- //#region src/util/get-own.ts
2566
- /**
2567
- * Reads a property by an untrusted key, ignoring inherited prototype members.
2568
- *
2569
- * Tool sets, tool contexts, and similar lookup objects are indexed by names
2570
- * that can come from model output or client-supplied message history. Plain
2571
- * bracket access (`obj[name]`) resolves names such as `constructor`,
2572
- * `toString`, or `__proto__` to values on `Object.prototype`, which would slip
2573
- * past the `== null` / `!value` guards that treat an unknown name as "not
2574
- * present". This helper returns `undefined` unless `key` is an own property.
2575
- */
2576
- function getOwn(obj, key) {
2577
- return obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;
2578
- }
2579
- //#endregion
2580
- //#region src/util/merge-abort-signals.ts
2581
- /**
2582
- * Merges multiple abort sources into a single `AbortSignal`.
2583
- * The returned signal will abort when any input signal aborts or when any
2584
- * numeric timeout elapses, using the reason from the first source to abort.
2585
- *
2586
- * @param signals - Abort signals or timeout durations in milliseconds.
2587
- * `null` and `undefined` values are ignored.
2588
- * @returns An `AbortSignal` that aborts when any valid source aborts,
2589
- * or `undefined` if no valid sources are provided.
2590
- */
2591
- function mergeAbortSignals(...signals) {
2592
- const validSignals = filterNullable(...signals).map((signal) => typeof signal === "number" ? AbortSignal.timeout(signal) : signal);
2593
- return validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);
2594
- }
2595
- //#endregion
2596
- //#region src/util/now.ts
2597
- function now() {
2598
- return globalThis?.performance?.now() ?? Date.now();
2599
- }
2600
- //#endregion
2601
- //#region src/util/notify.ts
2602
- /**
2603
- * Notifies all provided callbacks with the given event in parallel.
2604
- * Errors in callbacks do not break the generation flow.
2605
- */
2606
- async function notify(options) {
2607
- await Promise.all(asArray(options.callbacks).map(async (callback) => {
2608
- try {
2609
- await callback?.(options.event);
2610
- } catch {}
2611
- }));
2612
- }
2613
- //#endregion
2614
- //#region src/util/retry-with-exponential-backoff.ts
2615
- function getRetryDelayInMs({ error, exponentialBackoffDelay }) {
2616
- const headers = APICallError$1.isInstance(error) ? error.responseHeaders : APICallError$1.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
2617
- if (!headers) return exponentialBackoffDelay;
2618
- let ms;
2619
- const retryAfterMs = headers["retry-after-ms"];
2620
- if (retryAfterMs) {
2621
- const timeoutMs = parseFloat(retryAfterMs);
2622
- if (!Number.isNaN(timeoutMs)) ms = timeoutMs;
2623
- }
2624
- const retryAfter = headers["retry-after"];
2625
- if (retryAfter && ms === void 0) {
2626
- const timeoutSeconds = parseFloat(retryAfter);
2627
- if (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;
2628
- else ms = Date.parse(retryAfter) - Date.now();
2629
- }
2630
- if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;
2631
- return exponentialBackoffDelay;
2632
- }
2633
- /**
2634
- * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,
2635
- * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).
2636
- * You can configure the maximum number of retries, the initial delay, and the backoff factor.
2637
- */
2638
- const retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => retryWithExponentialBackoff({
2639
- maxRetries,
2640
- initialDelayInMs,
2641
- backoffFactor,
2642
- abortSignal,
2643
- shouldRetry: async (error) => error instanceof Error && (APICallError$1.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || additionalRetryableError != null && await additionalRetryableError(error),
2644
- getDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs({
2645
- error,
2646
- exponentialBackoffDelay
2647
- }),
2648
- createRetryError: ({ message, reason, errors }) => new RetryError({
2649
- message,
2650
- reason,
2651
- errors
2652
- })
2653
- });
2654
- //#endregion
2655
- //#region src/util/prepare-retries.ts
2656
- /**
2657
- * Validate and prepare retries.
2658
- */
2659
- function prepareRetries({ maxRetries, abortSignal, additionalRetryableError, parameter = "maxRetries", defaultMaxRetries = 2 }) {
2660
- if (maxRetries != null) {
2661
- if (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({
2662
- parameter,
2663
- value: maxRetries,
2664
- message: `${parameter} must be an integer`
2665
- });
2666
- if (maxRetries < 0) throw new InvalidArgumentError({
2667
- parameter,
2668
- value: maxRetries,
2669
- message: `${parameter} must be >= 0`
2670
- });
2671
- }
2672
- const maxRetriesResult = maxRetries ?? defaultMaxRetries;
2673
- return {
2674
- maxRetries: maxRetriesResult,
2675
- retry: retryWithExponentialBackoffRespectingRetryHeaders({
2676
- maxRetries: maxRetriesResult,
2677
- abortSignal,
2678
- additionalRetryableError
2679
- })
2680
- };
2681
- }
2682
- //#endregion
2683
- //#region src/util/set-abort-timeout.ts
2684
- /**
2685
- * Schedules a timeout that aborts the given controller with a `TimeoutError`
2686
- * `DOMException`, matching the reason produced by `AbortSignal.timeout(ms)`.
2687
- *
2688
- * @param abortController - The controller to abort when the timeout elapses.
2689
- * If undefined, no timeout is scheduled.
2690
- * @param label - Human-readable label included in the error message
2691
- * (e.g. "Step", "Chunk").
2692
- * @param timeoutMs - Duration in milliseconds before the controller is aborted.
2693
- * If undefined, no timeout is scheduled.
2694
- * @returns The timeout id (suitable for passing to `clearTimeout`), or
2695
- * `undefined` if no timeout was scheduled.
2696
- */
2697
- function setAbortTimeout({ abortController, label, timeoutMs }) {
2698
- if (abortController == null || timeoutMs == null) return;
2699
- return setTimeout(() => abortController.abort(new DOMException(`${label} timeout of ${timeoutMs}ms exceeded`, "TimeoutError")), timeoutMs);
2700
- }
2701
- //#endregion
2702
- //#region src/generate-text/calculate-tokens-per-second.ts
2703
- /**
2704
- * Calculates a token rate in tokens per second.
2705
- *
2706
- * Returns 0 when the token count is unknown, the duration is unknown or 0, or
2707
- * the computed rate cannot be represented as a finite JSON-safe number.
2708
- */
2709
- function calculateTokensPerSecond({ tokens, durationMs }) {
2710
- const tokenRate = 1e3 * (tokens ?? 0) / (durationMs ?? 0);
2711
- return Number.isFinite(tokenRate) ? tokenRate : 0;
2712
- }
2713
- //#endregion
2714
- //#region src/generate-text/collect-tool-approvals.ts
2715
- /**
2716
- * If the last message is a tool message, this function collects all tool approvals
2717
- * from that message.
2718
- */
2719
- function collectToolApprovals({ messages }) {
2720
- const lastMessage = messages.at(-1);
2721
- if (lastMessage?.role != "tool") return {
2722
- approvedToolApprovals: [],
2723
- deniedToolApprovals: []
2724
- };
2725
- const toolCallsByToolCallId = Object.create(null);
2726
- const toolCallOrder = Object.create(null);
2727
- let nextToolCallIndex = 0;
2728
- for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
2729
- const content = message.content;
2730
- for (const part of content) if (part.type === "tool-call") {
2731
- toolCallsByToolCallId[part.toolCallId] = part;
2732
- toolCallOrder[part.toolCallId] = nextToolCallIndex++;
2733
- }
2734
- }
2735
- const toolApprovalRequestsByApprovalId = Object.create(null);
2736
- for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
2737
- const content = message.content;
2738
- for (const part of content) if (part.type === "tool-approval-request") toolApprovalRequestsByApprovalId[part.approvalId] = part;
2739
- }
2740
- const toolResults = Object.create(null);
2741
- for (const part of lastMessage.content) if (part.type === "tool-result") toolResults[part.toolCallId] = part;
2742
- const approvedToolApprovals = [];
2743
- const deniedToolApprovals = [];
2744
- const collectedToolCallIds = /* @__PURE__ */ new Set();
2745
- const approvalResponses = lastMessage.content.filter((part) => part.type === "tool-approval-response");
2746
- for (const approvalResponse of approvalResponses) {
2747
- const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];
2748
- if (approvalRequest == null) throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId });
2749
- const existingToolResult = toolResults[approvalRequest.toolCallId];
2750
- if (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== "execution-denied")) continue;
2751
- const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
2752
- if (toolCall == null) throw new ToolCallNotFoundForApprovalError({
2753
- toolCallId: approvalRequest.toolCallId,
2754
- approvalId: approvalRequest.approvalId
2755
- });
2756
- if (collectedToolCallIds.has(toolCall.toolCallId)) continue;
2757
- collectedToolCallIds.add(toolCall.toolCallId);
2758
- const approval = {
2759
- approvalRequest,
2760
- approvalResponse,
2761
- toolCall,
2762
- ...existingToolResult != null ? { existingToolResult } : {}
2763
- };
2764
- if (approvalResponse.approved) approvedToolApprovals.push(approval);
2765
- else deniedToolApprovals.push(approval);
2766
- }
2767
- approvedToolApprovals.sort((a, b) => toolCallOrder[a.toolCall.toolCallId] - toolCallOrder[b.toolCall.toolCallId]);
2768
- return {
2769
- approvedToolApprovals,
2770
- deniedToolApprovals
2771
- };
2772
- }
2773
- //#endregion
2774
- //#region src/generate-text/generated-file.ts
2775
- var DefaultGeneratedFile = class {
2776
- constructor({ data, mediaType, providerMetadata }) {
2777
- const isUint8Array = data instanceof Uint8Array;
2778
- this.base64Data = isUint8Array ? void 0 : data;
2779
- this.uint8ArrayData = isUint8Array ? data : void 0;
2780
- this.mediaType = mediaType;
2781
- this.providerMetadata = providerMetadata;
2782
- }
2783
- get base64() {
2784
- if (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
2785
- return this.base64Data;
2786
- }
2787
- get uint8Array() {
2788
- if (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
2789
- return this.uint8ArrayData;
2790
- }
2791
- };
2792
- var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
2793
- constructor(..._args) {
2794
- super(..._args);
2795
- this.type = "file";
2796
- }
2797
- };
2798
- //#endregion
2799
- //#region src/generate-text/resolve-generated-file-data.ts
2800
- async function resolveGeneratedFileData({ data, abortSignal, cache }) {
2801
- if (data.type === "data") return data.data;
2802
- const cachedData = cache?.get(data);
2803
- if (cachedData != null) return cachedData;
2804
- const downloadedData = (await download({
2805
- url: data.url,
2806
- abortSignal
2807
- })).data;
2808
- cache?.set(data, downloadedData);
2809
- return downloadedData;
2399
+ //#region src/generate-text/generated-file.ts
2400
+ var DefaultGeneratedFile = class {
2401
+ constructor({ data, mediaType, providerMetadata }) {
2402
+ const isUint8Array = data instanceof Uint8Array;
2403
+ this.base64Data = isUint8Array ? void 0 : data;
2404
+ this.uint8ArrayData = isUint8Array ? data : void 0;
2405
+ this.mediaType = mediaType;
2406
+ this.providerMetadata = providerMetadata;
2407
+ }
2408
+ get base64() {
2409
+ if (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
2410
+ return this.base64Data;
2411
+ }
2412
+ get uint8Array() {
2413
+ if (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
2414
+ return this.uint8ArrayData;
2415
+ }
2416
+ };
2417
+ var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
2418
+ constructor(..._args) {
2419
+ super(..._args);
2420
+ this.type = "file";
2421
+ }
2422
+ };
2423
+ //#endregion
2424
+ //#region src/generate-text/resolve-generated-file-data.ts
2425
+ async function resolveGeneratedFileData({ data, abortSignal, cache }) {
2426
+ if (data.type === "data") return data.data;
2427
+ const cachedData = cache?.get(data);
2428
+ if (cachedData != null) return cachedData;
2429
+ const downloadedData = (await download({
2430
+ url: data.url,
2431
+ abortSignal
2432
+ })).data;
2433
+ cache?.set(data, downloadedData);
2434
+ return downloadedData;
2810
2435
  }
2811
2436
  //#endregion
2812
2437
  //#region src/generate-text/convert-language-model-content.ts
@@ -2929,20 +2554,7 @@ function resolveToolCallerConfiguration({ tools, toolCallers }) {
2929
2554
  value: toolCallers,
2930
2555
  message: `unknown tool "${toolName}".`
2931
2556
  });
2932
- if (!Array.isArray(callers)) throw new InvalidArgumentError({
2933
- parameter: "experimental_toolCallers",
2934
- value: toolCallers,
2935
- message: `callers for tool "${toolName}" must be an array.`
2936
- });
2937
- resolved[toolName] = callers.map((caller) => {
2938
- if (caller === "AI_SDK_DIRECT_TOOL_CALL") return caller;
2939
- if (typeof caller !== "string" || !Object.prototype.hasOwnProperty.call(tools, caller) || experimental_getToolCaller(tools[caller]) == null) throw new InvalidArgumentError({
2940
- parameter: "experimental_toolCallers",
2941
- value: toolCallers,
2942
- message: `tool "${toolName}" contains an invalid caller.`
2943
- });
2944
- return caller;
2945
- });
2557
+ if (callers != null) resolved[toolName] = callers;
2946
2558
  }
2947
2559
  return resolved;
2948
2560
  }
@@ -4830,11 +4442,6 @@ var DefaultSteering = class {
4830
4442
  role: "user",
4831
4443
  content: message
4832
4444
  } : message;
4833
- if (userMessage.role !== "user") throw new InvalidArgumentError({
4834
- parameter: "message",
4835
- value: message,
4836
- message: "Steering messages must be user messages."
4837
- });
4838
4445
  const outcome = this.state === "ended" ? Promise.resolve({
4839
4446
  type: "not-delivered",
4840
4447
  id,
@@ -6524,28 +6131,62 @@ function getResponseUIMessageId({ originalMessages, responseMessageId }) {
6524
6131
  return lastMessage?.role === "assistant" ? lastMessage.id : typeof responseMessageId === "function" ? responseMessageId() : responseMessageId;
6525
6132
  }
6526
6133
  //#endregion
6527
- //#region src/types/citation.ts
6528
- const citationSchema = z.object({
6529
- source: z.discriminatedUnion("sourceType", [z.object({
6530
- type: z.literal("source"),
6531
- sourceType: z.literal("url"),
6532
- id: z.string(),
6533
- url: z.string(),
6534
- title: z.string().optional(),
6535
- providerMetadata: providerMetadataSchema.optional()
6536
- }), z.object({
6537
- type: z.literal("source"),
6538
- sourceType: z.literal("document"),
6539
- id: z.string(),
6540
- mediaType: z.string(),
6541
- title: z.string(),
6542
- filename: z.string().optional(),
6543
- providerMetadata: providerMetadataSchema.optional()
6544
- })]),
6545
- startIndex: z.number().int().nonnegative().optional(),
6546
- endIndex: z.number().int().nonnegative().optional(),
6547
- citedText: z.string().optional()
6548
- });
6134
+ //#region src/util/zod.ts
6135
+ const z = {
6136
+ array,
6137
+ boolean,
6138
+ custom,
6139
+ discriminatedUnion,
6140
+ enum: enum$1,
6141
+ instanceof: instanceof$1,
6142
+ lazy,
6143
+ literal,
6144
+ looseObject,
6145
+ never,
6146
+ null: null$1,
6147
+ number,
6148
+ object,
6149
+ record,
6150
+ string,
6151
+ union,
6152
+ unknown
6153
+ };
6154
+ //#endregion
6155
+ //#region src/types/json-value.ts
6156
+ const jsonValueSchema = z.lazy(() => z.union([
6157
+ z.null(),
6158
+ z.string(),
6159
+ z.number(),
6160
+ z.boolean(),
6161
+ z.record(z.string(), jsonValueSchema.optional()),
6162
+ z.array(jsonValueSchema)
6163
+ ]));
6164
+ //#endregion
6165
+ //#region src/types/provider-metadata.ts
6166
+ const providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
6167
+ //#endregion
6168
+ //#region src/types/citation.ts
6169
+ const citationSchema = z.object({
6170
+ source: z.discriminatedUnion("sourceType", [z.object({
6171
+ type: z.literal("source"),
6172
+ sourceType: z.literal("url"),
6173
+ id: z.string(),
6174
+ url: z.string(),
6175
+ title: z.string().optional(),
6176
+ providerMetadata: providerMetadataSchema.optional()
6177
+ }), z.object({
6178
+ type: z.literal("source"),
6179
+ sourceType: z.literal("document"),
6180
+ id: z.string(),
6181
+ mediaType: z.string(),
6182
+ title: z.string(),
6183
+ filename: z.string().optional(),
6184
+ providerMetadata: providerMetadataSchema.optional()
6185
+ })]),
6186
+ startIndex: z.number().int().nonnegative().optional(),
6187
+ endIndex: z.number().int().nonnegative().optional(),
6188
+ citedText: z.string().optional()
6189
+ });
6549
6190
  //#endregion
6550
6191
  //#region src/ui-message-stream/ui-message-chunks.ts
6551
6192
  const toolMetadataSchema$1 = z.record(z.string(), jsonValueSchema.optional());
@@ -11495,7 +11136,7 @@ async function convertToModelMessages(messages, options) {
11495
11136
  //#endregion
11496
11137
  //#region src/ui/validate-ui-messages.ts
11497
11138
  const toolMetadataSchema = z.record(z.string(), jsonValueSchema.optional());
11498
- const providerReferenceSchema = z.record(z.string(), z.string());
11139
+ const providerReferenceSchema$1 = z.record(z.string(), z.string());
11499
11140
  function isEmptyObject(value) {
11500
11141
  return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11501
11142
  }
@@ -11575,7 +11216,7 @@ const uiMessagesSchema = lazySchema(() => {
11575
11216
  mediaType: z.string(),
11576
11217
  filename: z.string().optional(),
11577
11218
  url: z.string(),
11578
- providerReference: providerReferenceSchema.optional(),
11219
+ providerReference: providerReferenceSchema$1.optional(),
11579
11220
  providerMetadata: providerMetadataSchema.optional()
11580
11221
  }),
11581
11222
  z.object({
@@ -12642,11 +12283,6 @@ function validateRequests(requests) {
12642
12283
  }
12643
12284
  }
12644
12285
  function validateBatchReference({ batchApi, batch }) {
12645
- if (batch.version !== 2) throw new InvalidArgumentError({
12646
- parameter: "batch",
12647
- value: batch,
12648
- message: "batch must be a supported batch reference"
12649
- });
12650
12286
  if (batch.provider !== batchApi.provider) throw new InvalidArgumentError({
12651
12287
  parameter: "provider",
12652
12288
  value: batchApi,
@@ -13362,19 +12998,20 @@ function isRecord$1(value) {
13362
12998
  const prototype = Object.getPrototypeOf(value);
13363
12999
  return prototype === Object.prototype || prototype === null;
13364
13000
  }
13365
- function isJSON(value, ancestors = /* @__PURE__ */ new Set()) {
13366
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
13001
+ /**
13002
+ * Checks the JSON constraints that types cannot express: finite numbers, no
13003
+ * cycles, and no array holes. These would otherwise be silently changed by
13004
+ * `JSON.stringify` or make it throw.
13005
+ */
13006
+ function isSerializableJSON(value, ancestors = /* @__PURE__ */ new Set()) {
13367
13007
  if (typeof value === "number") return Number.isFinite(value);
13368
- if (typeof value !== "object" || !Array.isArray(value) && !isRecord$1(value)) return false;
13008
+ if (value == null || typeof value !== "object") return true;
13369
13009
  if (ancestors.has(value)) return false;
13370
13010
  ancestors.add(value);
13371
- const valid = Object.getOwnPropertySymbols(value).length === 0 && (Array.isArray(value) ? Array.from(value).every((item) => isJSON(item, ancestors)) : Object.values(value).every((item) => isJSON(item, ancestors)));
13011
+ const valid = Array.isArray(value) ? Array.from(value.keys()).every((index) => index in value && isSerializableJSON(value[index], ancestors)) : Object.values(value).every((item) => isSerializableJSON(item, ancestors));
13372
13012
  ancestors.delete(value);
13373
13013
  return valid;
13374
13014
  }
13375
- function isInput(value) {
13376
- return (typeof value === "string" || Array.isArray(value) || isRecord$1(value)) && isJSON(value);
13377
- }
13378
13015
  function invalidInput(parameter, value, message) {
13379
13016
  throw new InvalidArgumentError({
13380
13017
  parameter,
@@ -13383,36 +13020,26 @@ function invalidInput(parameter, value, message) {
13383
13020
  });
13384
13021
  }
13385
13022
  function validateDecisionInput({ state, questions }) {
13386
- if (!(Array.isArray(state) ? Array.from(state).every((part) => {
13387
- if (!isRecord$1(part)) return false;
13388
- switch (part.type) {
13389
- case "text": return textPartSchema.safeParse(part).success;
13390
- case "file": return filePartSchema.safeParse(part).success;
13391
- case "json": return isJSON(part.value);
13392
- default: return false;
13393
- }
13394
- }) : (typeof state === "string" || isRecord$1(state)) && isJSON(state))) invalidInput("state", state, "must be a string, JSON object, or array of text, file, or json parts");
13395
- if (!isRecord$1(questions) || Object.keys(questions).length === 0) invalidInput("questions", questions, "must be a nonempty question map");
13023
+ if (Array.isArray(state) && Array.from(state.keys()).some((index) => !(index in state))) invalidInput("state", state, "state parts must not contain array holes");
13024
+ if (!isSerializableJSON(Array.isArray(state) ? state.flatMap((part) => part.type === "json" ? [part.value] : []) : state)) invalidInput("state", state, "JSON content must not contain non-finite numbers, cycles, or array holes");
13025
+ if (Object.keys(questions).length === 0) invalidInput("questions", questions, "must be a nonempty question map");
13396
13026
  for (const [id, question] of Object.entries(questions)) {
13397
13027
  const parameter = `questions.${id}`;
13398
- if (!isRecord$1(question) || (question.type === "box" || question.instructions != null) && !isInput(question.instructions)) invalidInput(parameter, question, "instructions must be a JSON-compatible string, object, or array");
13399
- if (question.type === "box") continue;
13400
- const criteria = question.criteria;
13028
+ if (!isSerializableJSON(question.instructions) || "criteria" in question && !isSerializableJSON(question.criteria)) invalidInput(parameter, question, "instructions and criteria must not contain non-finite numbers, cycles, or array holes");
13401
13029
  switch (question.type) {
13402
13030
  case "choice":
13403
- if (!isRecord$1(criteria) || Object.keys(criteria).length === 0) invalidInput(parameter, question, "choice criteria must be a nonempty option map");
13031
+ if (Object.keys(question.criteria).length === 0) invalidInput(parameter, question, "choice criteria must be a nonempty option map");
13404
13032
  break;
13405
13033
  case "score":
13406
- if (!Array.isArray(criteria) || criteria.length === 0) invalidInput(parameter, question, "score criteria must contain at least one ordered level");
13034
+ if (question.criteria.length === 0) invalidInput(parameter, question, "score criteria must contain at least one ordered level");
13407
13035
  break;
13408
- case "boolean":
13409
- if (question.instructions == null && (!isRecord$1(criteria) || !Object.values(criteria).some((value) => value != null))) invalidInput(parameter, question, "boolean questions require instructions or at least one non-null criterion");
13410
- if (criteria === void 0) continue;
13411
- if (!isRecord$1(criteria) || Object.keys(criteria).some((key) => key !== "true" && key !== "false")) invalidInput(parameter, question, "boolean criteria may only describe true and false");
13036
+ case "boolean": {
13037
+ const criteria = question.criteria;
13038
+ if (question.instructions == null && (criteria == null || !Object.values(criteria).some((value) => value != null))) invalidInput(parameter, question, "boolean questions require instructions or at least one non-null criterion");
13039
+ if (criteria != null && Object.keys(criteria).some((key) => key !== "true" && key !== "false")) invalidInput(parameter, question, "boolean criteria may only describe true and false");
13412
13040
  break;
13413
- default: invalidInput(parameter, question, "question type must be choice, score, boolean, or box");
13041
+ }
13414
13042
  }
13415
- 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");
13416
13043
  }
13417
13044
  }
13418
13045
  function invalidAnswer(answers, message) {
@@ -13915,11 +13542,6 @@ async function parseAndValidateObjectResultWithRepair(result, outputStrategy, re
13915
13542
  //#endregion
13916
13543
  //#region src/generate-object/validate-object-generation-input.ts
13917
13544
  function validateObjectGenerationInput({ output, schema, schemaName, schemaDescription, enumValues }) {
13918
- if (output != null && output !== "object" && output !== "array" && output !== "enum" && output !== "no-schema") throw new InvalidArgumentError({
13919
- parameter: "output",
13920
- value: output,
13921
- message: "Invalid output type."
13922
- });
13923
13545
  if (output === "no-schema") {
13924
13546
  if (schema != null) throw new InvalidArgumentError({
13925
13547
  parameter: "schema",
@@ -13943,11 +13565,6 @@ function validateObjectGenerationInput({ output, schema, schemaName, schemaDescr
13943
13565
  });
13944
13566
  }
13945
13567
  if (output === "object") {
13946
- if (schema == null) throw new InvalidArgumentError({
13947
- parameter: "schema",
13948
- value: schema,
13949
- message: "Schema is required for object output."
13950
- });
13951
13568
  if (enumValues != null) throw new InvalidArgumentError({
13952
13569
  parameter: "enumValues",
13953
13570
  value: enumValues,
@@ -13955,11 +13572,6 @@ function validateObjectGenerationInput({ output, schema, schemaName, schemaDescr
13955
13572
  });
13956
13573
  }
13957
13574
  if (output === "array") {
13958
- if (schema == null) throw new InvalidArgumentError({
13959
- parameter: "schema",
13960
- value: schema,
13961
- message: "Element schema is required for array output."
13962
- });
13963
13575
  if (enumValues != null) throw new InvalidArgumentError({
13964
13576
  parameter: "enumValues",
13965
13577
  value: enumValues,
@@ -13982,12 +13594,7 @@ function validateObjectGenerationInput({ output, schema, schemaName, schemaDescr
13982
13594
  value: schemaName,
13983
13595
  message: "Schema name is not supported for enum output."
13984
13596
  });
13985
- if (enumValues == null) throw new InvalidArgumentError({
13986
- parameter: "enumValues",
13987
- value: enumValues,
13988
- message: "Enum values are required for enum output."
13989
- });
13990
- for (const value of enumValues) if (typeof value !== "string") throw new InvalidArgumentError({
13597
+ for (const value of enumValues ?? []) if (typeof value !== "string") throw new InvalidArgumentError({
13991
13598
  parameter: "enumValues",
13992
13599
  value,
13993
13600
  message: "Enum values must be strings."
@@ -15397,17 +15004,10 @@ function toTextStream$1(text) {
15397
15004
  function toSourceStream(text) {
15398
15005
  if (text instanceof ReadableStream) return text;
15399
15006
  if (typeof text?.[Symbol.asyncIterator] === "function") return convertAsyncIteratorToReadableStream(text[Symbol.asyncIterator]());
15400
- if (typeof text?.[Symbol.iterator] === "function") {
15401
- const iterable = text;
15402
- return convertAsyncIteratorToReadableStream((async function* () {
15403
- yield* iterable;
15404
- })());
15405
- }
15406
- throw new InvalidArgumentError({
15407
- parameter: "text",
15408
- value: text,
15409
- message: "Expected a string, an iterable or async iterable, or a ReadableStream of strings or text parts."
15410
- });
15007
+ const iterable = text;
15008
+ return convertAsyncIteratorToReadableStream((async function* () {
15009
+ yield* iterable;
15010
+ })());
15411
15011
  }
15412
15012
  function toTextPart(value) {
15413
15013
  if (typeof value === "string") return {
@@ -15557,11 +15157,7 @@ function smoothStream({ delayInMs = 10, chunking = "word", _internal: { delay: d
15557
15157
  return match;
15558
15158
  };
15559
15159
  else {
15560
- const chunkingRegex = typeof chunking === "string" ? CHUNKING_REGEXPS[chunking] : chunking instanceof RegExp ? chunking : void 0;
15561
- if (chunkingRegex == null) throw new InvalidArgumentError$1({
15562
- argument: "chunking",
15563
- message: `Chunking must be "word", "line", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`
15564
- });
15160
+ const chunkingRegex = typeof chunking === "string" ? CHUNKING_REGEXPS[chunking] : chunking;
15565
15161
  detectChunk = (buffer) => {
15566
15162
  const lastIndex = chunkingRegex.lastIndex;
15567
15163
  chunkingRegex.lastIndex = 0;
@@ -16889,6 +16485,285 @@ function wrapProvider({ provider, languageModelMiddleware, imageModelMiddleware
16889
16485
  };
16890
16486
  }
16891
16487
  //#endregion
16488
+ //#region src/prompt/content-part.ts
16489
+ const fileInlineDataSchema = z.union([
16490
+ z.string(),
16491
+ z.instanceof(Uint8Array),
16492
+ z.instanceof(ArrayBuffer),
16493
+ z.custom(isBuffer, { message: "Must be a Buffer" })
16494
+ ]);
16495
+ const providerReferenceSchema = z.record(z.string(), z.string());
16496
+ /**
16497
+ * @internal
16498
+ */
16499
+ const textPartSchema = z.object({
16500
+ type: z.literal("text"),
16501
+ text: z.string(),
16502
+ providerOptions: providerMetadataSchema.optional()
16503
+ });
16504
+ /**
16505
+ * @internal
16506
+ * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:
16507
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
16508
+ */
16509
+ const imagePartSchema = z.object({
16510
+ type: z.literal("image"),
16511
+ image: z.union([
16512
+ fileInlineDataSchema,
16513
+ z.instanceof(URL),
16514
+ providerReferenceSchema
16515
+ ]),
16516
+ mediaType: z.string().optional(),
16517
+ providerOptions: providerMetadataSchema.optional()
16518
+ });
16519
+ const taggedFileDataSchema = z.discriminatedUnion("type", [
16520
+ z.object({
16521
+ type: z.literal("data"),
16522
+ data: fileInlineDataSchema
16523
+ }),
16524
+ z.object({
16525
+ type: z.literal("url"),
16526
+ url: z.instanceof(URL)
16527
+ }),
16528
+ z.object({
16529
+ type: z.literal("reference"),
16530
+ reference: providerReferenceSchema
16531
+ }),
16532
+ z.object({
16533
+ type: z.literal("text"),
16534
+ text: z.string()
16535
+ })
16536
+ ]);
16537
+ const taggedReasoningFileDataSchema = z.discriminatedUnion("type", [z.object({
16538
+ type: z.literal("data"),
16539
+ data: fileInlineDataSchema
16540
+ }), z.object({
16541
+ type: z.literal("url"),
16542
+ url: z.instanceof(URL)
16543
+ })]);
16544
+ /**
16545
+ * @internal
16546
+ */
16547
+ const filePartSchema = z.object({
16548
+ type: z.literal("file"),
16549
+ data: z.union([
16550
+ taggedFileDataSchema,
16551
+ fileInlineDataSchema,
16552
+ z.instanceof(URL),
16553
+ providerReferenceSchema
16554
+ ]),
16555
+ filename: z.string().optional(),
16556
+ mediaType: z.string(),
16557
+ providerOptions: providerMetadataSchema.optional()
16558
+ });
16559
+ /**
16560
+ * @internal
16561
+ */
16562
+ const reasoningPartSchema = z.object({
16563
+ type: z.literal("reasoning"),
16564
+ text: z.string(),
16565
+ providerOptions: providerMetadataSchema.optional()
16566
+ });
16567
+ /**
16568
+ * @internal
16569
+ */
16570
+ const customPartSchema = z.object({
16571
+ type: z.literal("custom"),
16572
+ kind: z.string().transform((value) => value),
16573
+ providerOptions: providerMetadataSchema.optional()
16574
+ });
16575
+ /**
16576
+ * @internal
16577
+ */
16578
+ const reasoningFilePartSchema = z.object({
16579
+ type: z.literal("reasoning-file"),
16580
+ data: z.union([
16581
+ taggedReasoningFileDataSchema,
16582
+ fileInlineDataSchema,
16583
+ z.instanceof(URL)
16584
+ ]),
16585
+ mediaType: z.string(),
16586
+ providerOptions: providerMetadataSchema.optional()
16587
+ });
16588
+ /**
16589
+ * @internal
16590
+ */
16591
+ const toolCallPartSchema = z.object({
16592
+ type: z.literal("tool-call"),
16593
+ toolCallId: z.string(),
16594
+ toolName: z.string(),
16595
+ input: z.unknown(),
16596
+ providerOptions: providerMetadataSchema.optional(),
16597
+ providerExecuted: z.boolean().optional()
16598
+ });
16599
+ /**
16600
+ * @internal
16601
+ */
16602
+ const outputSchema = z.discriminatedUnion("type", [
16603
+ z.object({
16604
+ type: z.literal("text"),
16605
+ value: z.string(),
16606
+ providerOptions: providerMetadataSchema.optional()
16607
+ }),
16608
+ z.object({
16609
+ type: z.literal("json"),
16610
+ value: jsonValueSchema,
16611
+ providerOptions: providerMetadataSchema.optional()
16612
+ }),
16613
+ z.object({
16614
+ type: z.literal("execution-denied"),
16615
+ reason: z.string().optional(),
16616
+ providerOptions: providerMetadataSchema.optional()
16617
+ }),
16618
+ z.object({
16619
+ type: z.literal("error-text"),
16620
+ value: z.string(),
16621
+ providerOptions: providerMetadataSchema.optional()
16622
+ }),
16623
+ z.object({
16624
+ type: z.literal("error-json"),
16625
+ value: jsonValueSchema,
16626
+ providerOptions: providerMetadataSchema.optional()
16627
+ }),
16628
+ z.object({
16629
+ type: z.literal("content"),
16630
+ value: z.array(z.union([
16631
+ z.object({
16632
+ type: z.literal("text"),
16633
+ text: z.string(),
16634
+ providerOptions: providerMetadataSchema.optional()
16635
+ }),
16636
+ z.object({
16637
+ type: z.literal("file"),
16638
+ data: taggedFileDataSchema,
16639
+ mediaType: z.string(),
16640
+ filename: z.string().optional(),
16641
+ providerOptions: providerMetadataSchema.optional()
16642
+ }),
16643
+ z.object({
16644
+ type: z.literal("file-data"),
16645
+ data: z.string(),
16646
+ mediaType: z.string(),
16647
+ filename: z.string().optional(),
16648
+ providerOptions: providerMetadataSchema.optional()
16649
+ }),
16650
+ z.object({
16651
+ type: z.literal("file-url"),
16652
+ url: z.string(),
16653
+ mediaType: z.string().optional(),
16654
+ providerOptions: providerMetadataSchema.optional()
16655
+ }),
16656
+ z.object({
16657
+ type: z.literal("file-id"),
16658
+ fileId: z.union([z.string(), z.record(z.string(), z.string())]),
16659
+ providerOptions: providerMetadataSchema.optional()
16660
+ }),
16661
+ z.object({
16662
+ type: z.literal("file-reference"),
16663
+ providerReference: z.record(z.string(), z.string()),
16664
+ providerOptions: providerMetadataSchema.optional()
16665
+ }),
16666
+ z.object({
16667
+ type: z.literal("image-data"),
16668
+ data: z.string(),
16669
+ mediaType: z.string(),
16670
+ providerOptions: providerMetadataSchema.optional()
16671
+ }),
16672
+ z.object({
16673
+ type: z.literal("image-url"),
16674
+ url: z.string(),
16675
+ providerOptions: providerMetadataSchema.optional()
16676
+ }),
16677
+ z.object({
16678
+ type: z.literal("image-file-id"),
16679
+ fileId: z.union([z.string(), z.record(z.string(), z.string())]),
16680
+ providerOptions: providerMetadataSchema.optional()
16681
+ }),
16682
+ z.object({
16683
+ type: z.literal("image-file-reference"),
16684
+ providerReference: z.record(z.string(), z.string()),
16685
+ providerOptions: providerMetadataSchema.optional()
16686
+ }),
16687
+ z.object({
16688
+ type: z.literal("custom"),
16689
+ providerOptions: providerMetadataSchema.optional()
16690
+ })
16691
+ ]))
16692
+ })
16693
+ ]);
16694
+ /**
16695
+ * @internal
16696
+ */
16697
+ const toolResultPartSchema = z.object({
16698
+ type: z.literal("tool-result"),
16699
+ toolCallId: z.string(),
16700
+ toolName: z.string(),
16701
+ output: outputSchema,
16702
+ providerOptions: providerMetadataSchema.optional()
16703
+ });
16704
+ /**
16705
+ * @internal
16706
+ */
16707
+ const toolApprovalRequestSchema = z.object({
16708
+ type: z.literal("tool-approval-request"),
16709
+ approvalId: z.string(),
16710
+ toolCallId: z.string(),
16711
+ reason: z.string().optional(),
16712
+ isAutomatic: z.boolean().optional(),
16713
+ signature: z.string().optional(),
16714
+ inputSchemaInput: z.unknown().optional()
16715
+ });
16716
+ /**
16717
+ * @internal
16718
+ */
16719
+ const toolApprovalResponseSchema = z.object({
16720
+ type: z.literal("tool-approval-response"),
16721
+ approvalId: z.string(),
16722
+ approved: z.boolean(),
16723
+ reason: z.string().optional()
16724
+ });
16725
+ //#endregion
16726
+ //#region src/prompt/message.ts
16727
+ const systemModelMessageSchema = z.object({
16728
+ role: z.literal("system"),
16729
+ content: z.string(),
16730
+ providerOptions: providerMetadataSchema.optional()
16731
+ });
16732
+ const userModelMessageSchema = z.object({
16733
+ role: z.literal("user"),
16734
+ content: z.union([z.string(), z.array(z.union([
16735
+ textPartSchema,
16736
+ imagePartSchema,
16737
+ filePartSchema
16738
+ ]))]),
16739
+ providerOptions: providerMetadataSchema.optional()
16740
+ });
16741
+ const assistantModelMessageSchema = z.object({
16742
+ role: z.literal("assistant"),
16743
+ content: z.union([z.string(), z.array(z.union([
16744
+ textPartSchema,
16745
+ customPartSchema,
16746
+ filePartSchema,
16747
+ reasoningPartSchema,
16748
+ reasoningFilePartSchema,
16749
+ toolCallPartSchema,
16750
+ toolResultPartSchema,
16751
+ toolApprovalRequestSchema
16752
+ ]))]),
16753
+ providerOptions: providerMetadataSchema.optional()
16754
+ });
16755
+ const toolModelMessageSchema = z.object({
16756
+ role: z.literal("tool"),
16757
+ content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),
16758
+ providerOptions: providerMetadataSchema.optional()
16759
+ });
16760
+ const modelMessageSchema = z.union([
16761
+ systemModelMessageSchema,
16762
+ userModelMessageSchema,
16763
+ assistantModelMessageSchema,
16764
+ toolModelMessageSchema
16765
+ ]);
16766
+ //#endregion
16892
16767
  //#region src/realtime/audio-utils.ts
16893
16768
  /**
16894
16769
  * Converts Float32 audio samples to a base64-encoded PCM16 string