'use strict'; var chunkBVWXTWXP_cjs = require('./chunk-BVWXTWXP.cjs'); var z4 = require('zod/v4'); var v3 = require('zod/v3'); var spec_star = require('@standard-schema/spec'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var z4__namespace = /*#__PURE__*/_interopNamespace(z4); var spec_star__namespace = /*#__PURE__*/_interopNamespace(spec_star); // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/2.0.3/baf9ca0bc6c1e850f5a9c142d47d3731e6921106a5f2b12483df7e7922a48657/node_modules/@ai-sdk/provider/dist/index.mjs var marker = "vercel.ai.error"; var symbol = Symbol.for(marker); var _a; var _b; var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name142, message, cause }) { super(message); this[_a] = true; this.name = name142; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error) { return _AISDKError.hasMarker(error, marker); } static hasMarker(error, marker152) { const markerSymbol = Symbol.for(marker152); return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; } }; var name = "AI_APICallError"; var marker2 = `vercel.ai.error.${name}`; var symbol2 = Symbol.for(marker2); var _a2; var _b2; var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) { constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name, message, cause }); this[_a2] = true; this.url = url; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker2); } }; var name2 = "AI_EmptyResponseBodyError"; var marker3 = `vercel.ai.error.${name2}`; var symbol3 = Symbol.for(marker3); var _a3; var _b3; var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name2, message }); this[_a3] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker3); } }; function getErrorMessage(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } var name3 = "AI_InvalidArgumentError"; var marker4 = `vercel.ai.error.${name3}`; var symbol4 = Symbol.for(marker4); var _a4; var _b4; var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) { constructor({ message, cause, argument }) { super({ name: name3, message, cause }); this[_a4] = true; this.argument = argument; } static isInstance(error) { return AISDKError.hasMarker(error, marker4); } }; var name4 = "AI_InvalidPromptError"; var marker5 = `vercel.ai.error.${name4}`; var symbol5 = Symbol.for(marker5); var _a5; var _b5; var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) { constructor({ prompt, message, cause }) { super({ name: name4, message: `Invalid prompt: ${message}`, cause }); this[_a5] = true; this.prompt = prompt; } static isInstance(error) { return AISDKError.hasMarker(error, marker5); } }; var name5 = "AI_InvalidResponseDataError"; var marker6 = `vercel.ai.error.${name5}`; var symbol6 = Symbol.for(marker6); var _a6; var _b6; var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) { constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) { super({ name: name5, message }); this[_a6] = true; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker6); } }; var name6 = "AI_JSONParseError"; var marker7 = `vercel.ai.error.${name6}`; var symbol7 = Symbol.for(marker7); var _a7; var _b7; var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) { constructor({ text, cause }) { super({ name: name6, message: `JSON parsing failed: Text: ${text}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a7] = true; this.text = text; } static isInstance(error) { return AISDKError.hasMarker(error, marker7); } }; var name7 = "AI_LoadAPIKeyError"; var marker8 = `vercel.ai.error.${name7}`; var symbol8 = Symbol.for(marker8); var _a8; var _b8; var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) { // used in isInstance constructor({ message }) { super({ name: name7, message }); this[_a8] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker8); } }; var name8 = "AI_LoadSettingError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var _b9; var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) { // used in isInstance constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker9); } }; var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var _b11; var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) { constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) { super({ name: errorName, message }); this[_a11] = true; this.modelId = modelId; this.modelType = modelType; } static isInstance(error) { return AISDKError.hasMarker(error, marker11); } }; var name11 = "AI_TooManyEmbeddingValuesForCallError"; var marker12 = `vercel.ai.error.${name11}`; var symbol12 = Symbol.for(marker12); var _a12; var _b12; var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) { constructor(options) { super({ name: name11, message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` }); this[_a12] = true; this.provider = options.provider; this.modelId = options.modelId; this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; this.values = options.values; } static isInstance(error) { return AISDKError.hasMarker(error, marker12); } }; var name12 = "AI_TypeValidationError"; var marker13 = `vercel.ai.error.${name12}`; var symbol13 = Symbol.for(marker13); var _a13; var _b13; var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) { constructor({ value, cause }) { super({ name: name12, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a13] = true; this.value = value; } static isInstance(error) { return AISDKError.hasMarker(error, marker13); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause }); } }; var name13 = "AI_UnsupportedFunctionalityError"; var marker14 = `vercel.ai.error.${name13}`; var symbol14 = Symbol.for(marker14); var _a14; var _b14; var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name13, message }); this[_a14] = true; this.functionality = functionality; } static isInstance(error) { return AISDKError.hasMarker(error, marker14); } }; // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/3.0.25/8850a22427892148bad3177fddb9b16cacd9df1673e18e8f590fecb805b79a5c/node_modules/@ai-sdk/provider-utils/dist/index.mjs var dist_exports = {}; chunkBVWXTWXP_cjs.__export(dist_exports, { DEFAULT_MAX_DOWNLOAD_SIZE: () => DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise: () => DelayedPromise, DownloadError: () => DownloadError, EventSourceParserStream: () => EventSourceParserStream, VERSION: () => VERSION, asSchema: () => asSchema, asValidator: () => asValidator, combineHeaders: () => combineHeaders, convertAsyncIteratorToReadableStream: () => convertAsyncIteratorToReadableStream, convertBase64ToUint8Array: () => convertBase64ToUint8Array, convertToBase64: () => convertToBase64, convertUint8ArrayToBase64: () => convertUint8ArrayToBase64, createBinaryResponseHandler: () => createBinaryResponseHandler, createEventSourceResponseHandler: () => createEventSourceResponseHandler, createIdGenerator: () => createIdGenerator, createJsonErrorResponseHandler: () => createJsonErrorResponseHandler, createJsonResponseHandler: () => createJsonResponseHandler, createJsonStreamResponseHandler: () => createJsonStreamResponseHandler, createProviderDefinedToolFactory: () => createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema: () => createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler, delay: () => delay, dynamicTool: () => dynamicTool, executeTool: () => executeTool, extractResponseHeaders: () => extractResponseHeaders, generateId: () => generateId, getErrorMessage: () => getErrorMessage2, getFromApi: () => getFromApi, getRuntimeEnvironmentUserAgent: () => getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages: () => injectJsonInstructionIntoMessages, isAbortError: () => isAbortError, isParsableJson: () => isParsableJson, isUrlSupported: () => isUrlSupported, isValidator: () => isValidator, jsonSchema: () => jsonSchema, lazySchema: () => lazySchema, lazyValidator: () => lazyValidator, loadApiKey: () => loadApiKey, loadOptionalSetting: () => loadOptionalSetting, loadSetting: () => loadSetting, mediaTypeToExtension: () => mediaTypeToExtension, normalizeHeaders: () => normalizeHeaders, parseJSON: () => parseJSON, parseJsonEventStream: () => parseJsonEventStream, parseProviderOptions: () => parseProviderOptions, postFormDataToApi: () => postFormDataToApi, postJsonToApi: () => postJsonToApi, postToApi: () => postToApi, readResponseWithSizeLimit: () => readResponseWithSizeLimit, removeUndefinedEntries: () => removeUndefinedEntries, resolve: () => resolve, safeParseJSON: () => safeParseJSON, safeValidateTypes: () => safeValidateTypes, standardSchemaValidator: () => standardSchemaValidator, tool: () => tool, validateDownloadUrl: () => validateDownloadUrl, validateTypes: () => validateTypes, validator: () => validator, withUserAgentSuffix: () => withUserAgentSuffix, withoutTrailingSlash: () => withoutTrailingSlash, zodSchema: () => zodSchema }); // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/index.js var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; var LF = 10; var CR = 13; var SPACE = 32; function noop(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = []; let isFirstChunk = true, id, data = "", dataLines = 0, eventType; function feed(chunk) { if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { const trailing2 = processLines(chunk); trailing2 !== "" && pendingFragments.push(trailing2); return; } if (chunk.indexOf(` `) === -1 && chunk.indexOf("\r") === -1) { pendingFragments.push(chunk); return; } pendingFragments.push(chunk); const input = pendingFragments.join(""); pendingFragments.length = 0; const trailing = processLines(input); trailing !== "" && pendingFragments.push(trailing); } function processLines(chunk) { let searchIndex = 0; if (chunk.indexOf("\r") === -1) { let lfIndex = chunk.indexOf(` `, searchIndex); for (; lfIndex !== -1; ) { if (searchIndex === lfIndex) { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); continue; } const firstCharCode = chunk.charCodeAt(searchIndex); if (isDataPrefix(chunk, searchIndex, firstCharCode)) { const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) { onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` `, searchIndex); continue; } data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice( chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex ) || void 0 : parseLine(chunk, searchIndex, lfIndex); searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); } return chunk.slice(searchIndex); } for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++; } return chunk.slice(searchIndex); } function parseLine(chunk, start, end) { if (start === end) { dispatchEvent(); return; } const firstCharCode = chunk.charCodeAt(start); if (isDataPrefix(chunk, start, firstCharCode)) { const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); data = dataLines === 0 ? value2 : `${data} ${value2}`, dataLines++; return; } if (isEventPrefix(chunk, start, firstCharCode)) { eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0; return; } if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end); id = value2.includes("\0") ? void 0 : value2; return; } if (firstCharCode === 58) { if (onComment) { const line2 = chunk.slice(start, end); onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1)); } return; } const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex === -1) { processField(line, "", line); return; } const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); } function processField(field, value, line) { switch (field) { case "event": eventType = value || void 0; break; case "data": data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0; } function reset(options = {}) { if (options.consume && pendingFragments.length > 0) { const incompleteLine = pendingFragments.join(""); parseLine(incompleteLine, 0, incompleteLine.length); } isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0; } return { feed, reset }; } function isDataPrefix(chunk, i, firstCharCode) { return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58; } function isEventPrefix(chunk, i, firstCharCode) { return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58; } // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/stream.js var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error) { onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/3.0.25/8850a22427892148bad3177fddb9b16cacd9df1673e18e8f590fecb805b79a5c/node_modules/@ai-sdk/provider-utils/dist/index.mjs chunkBVWXTWXP_cjs.__reExport(dist_exports, spec_star__namespace); function combineHeaders(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } function convertAsyncIteratorToReadableStream(iterator) { let cancelled = false; return new ReadableStream({ /** * Called when the consumer wants to pull more data from the stream. * * @param {ReadableStreamDefaultController} controller - The controller to enqueue data into the stream. * @returns {Promise} */ async pull(controller) { if (cancelled) return; try { const { value, done } = await iterator.next(); if (done) { controller.close(); } else { controller.enqueue(value); } } catch (error) { controller.error(error); } }, /** * Called when the consumer cancels the stream. */ async cancel(reason) { cancelled = true; if (iterator.return) { try { await iterator.return(reason); } catch (e) { } } } }); } async function delay(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError() { return new DOMException("Delay was aborted", "AbortError"); } var DelayedPromise = class { constructor() { this.status = { type: "pending" }; this._resolve = void 0; this._reject = void 0; } get promise() { if (this._promise) { return this._promise; } this._promise = new Promise((resolve22, reject) => { if (this.status.type === "resolved") { resolve22(this.status.value); } else if (this.status.type === "rejected") { reject(this.status.error); } this._resolve = resolve22; this._reject = reject; }); return this._promise; } resolve(value) { var _a23; this.status = { type: "resolved", value }; if (this._promise) { (_a23 = this._resolve) == null ? void 0 : _a23.call(this, value); } } reject(error) { var _a23; this.status = { type: "rejected", error }; if (this._promise) { (_a23 = this._reject) == null ? void 0 : _a23.call(this, error); } } isResolved() { return this.status.type === "resolved"; } isRejected() { return this.status.type === "rejected"; } isPending() { return this.status.type === "pending"; } }; function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } var name14 = "AI_DownloadError"; var marker15 = `vercel.ai.error.${name14}`; var symbol15 = Symbol.for(marker15); var _a15; var _b15; var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) { constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) { super({ name: name14, message, cause }); this[_a15] = true; this.url = url; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error) { return AISDKError.hasMarker(error, marker15); } }; var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024; async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) { const contentLength = response.headers.get("content-length"); if (contentLength != null) { const length = parseInt(contentLength, 10); if (!isNaN(length) && length > maxBytes) { throw new DownloadError({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).` }); } } const body = response.body; if (body == null) { return new Uint8Array(0); } const reader = body.getReader(); const chunks = []; let totalBytes = 0; try { while (true) { const { done, value } = await reader.read(); if (done) { break; } totalBytes += value.length; if (totalBytes > maxBytes) { throw new DownloadError({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.` }); } chunks.push(value); } } finally { try { await reader.cancel(); } finally { reader.releaseLock(); } } const result = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; var generateId = createIdGenerator(); function getErrorMessage2(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } function isAbortError(error) { return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js error.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"]; function handleFetchError({ error, url, requestBodyValues }) { if (isAbortError(error)) { return error; } if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) { const cause = error.cause; if (cause != null) { return new APICallError({ message: `Cannot connect to API: ${cause.message}`, cause, url, requestBodyValues, isRetryable: true // retry when network error }); } } return error; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a23, _b23, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a23 = globalThisAny.navigator) == null ? void 0 : _a23.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION = "3.0.25" ; var getOriginalFetch = () => globalThis.fetch; var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch() }) => { try { const response = await fetch2(url, { method: "GET", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: {} }); } catch (error) { if (isAbortError(error) || APICallError.isInstance(error)) { throw error; } throw new APICallError({ message: "Failed to process error response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: {} }); } catch (error) { if (error instanceof Error) { if (isAbortError(error) || APICallError.isInstance(error)) { throw error; } } throw new APICallError({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: {} }); } } catch (error) { throw handleFetchError({ error, url, requestBodyValues: {} }); } }; var DEFAULT_SCHEMA_PREFIX = "JSON schema:"; var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above."; var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON."; function injectJsonInstruction({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX }) { return [ prompt != null && prompt.length > 0 ? prompt : void 0, prompt != null && prompt.length > 0 ? "" : void 0, // add a newline if prompt is not null schemaPrefix, schema != null ? JSON.stringify(schema) : void 0, schemaSuffix ].filter((line) => line != null).join("\n"); } function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix }) { var _a23, _b23; const systemMessage = ((_a23 = messages[0]) == null ? void 0 : _a23.role) === "system" ? { ...messages[0] } : { role: "system", content: "" }; systemMessage.content = injectJsonInstruction({ prompt: systemMessage.content, schema, schemaPrefix, schemaSuffix }); return [ systemMessage, ...((_b23 = messages[0]) == null ? void 0 : _b23.role) === "system" ? messages.slice(1) : messages ]; } function isUrlSupported({ mediaType, url, supportedUrls }) { url = url.toLowerCase(); mediaType = mediaType.toLowerCase(); return Object.entries(supportedUrls).map(([key, value]) => { const mediaType2 = key.toLowerCase(); return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value }; }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url)); } function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { if (typeof apiKey === "string") { return apiKey; } if (apiKey != null) { throw new LoadAPIKeyError({ message: `${description} API key must be a string.` }); } if (typeof process === "undefined") { throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.` }); } apiKey = process.env[environmentVariableName]; if (apiKey == null) { throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` }); } if (typeof apiKey !== "string") { throw new LoadAPIKeyError({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); } return apiKey; } function loadOptionalSetting({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } function loadSetting({ settingValue, environmentVariableName, settingName, description }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null) { throw new LoadSettingError({ message: `${description} setting must be a string.` }); } if (typeof process === "undefined") { throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.` }); } settingValue = process.env[environmentVariableName]; if (settingValue == null) { throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.` }); } if (typeof settingValue !== "string") { throw new LoadSettingError({ message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); } return settingValue; } function mediaTypeToExtension(mediaType) { var _a23; const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); return (_a23 = { mpeg: "mp3", "x-wav": "wav", opus: "ogg", mp4: "m4a", "x-m4a": "m4a" }[subtype]) != null ? _a23 : subtype; } var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse(text) { const obj = JSON.parse(text); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) { return obj; } return filter(obj); } function filter(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse(text) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e) { return _parse(text); } try { return _parse(text); } finally { Error.stackTraceLimit = stackTraceLimit; } } var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator"); function validator(validate) { return { [validatorSymbol]: true, validate }; } function isValidator(value) { return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value; } function lazyValidator(createValidator) { let validator2; return () => { if (validator2 == null) { validator2 = createValidator(); } return validator2; }; } function asValidator(value) { return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value); } function standardSchemaValidator(standardSchema2) { return validator(async (value) => { const result = await standardSchema2["~standard"].validate(value); return result.issues == null ? { success: true, value: result.value } : { success: false, error: new TypeValidationError({ value, cause: result.issues }) }; }); } async function validateTypes({ value, schema }) { const result = await safeValidateTypes({ value, schema }); if (!result.success) { throw TypeValidationError.wrap({ value, cause: result.error }); } return result.value; } async function safeValidateTypes({ value, schema }) { const validator2 = asValidator(schema); try { if (validator2.validate == null) { return { success: true, value, rawValue: value }; } const result = await validator2.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError.wrap({ value, cause: result.error }), rawValue: value }; } catch (error) { return { success: false, error: TypeValidationError.wrap({ value, cause: error }), rawValue: value }; } } async function parseJSON({ text, schema }) { try { const value = secureJsonParse(text); if (schema == null) { return value; } return validateTypes({ value, schema }); } catch (error) { if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) { throw error; } throw new JSONParseError({ text, cause: error }); } } async function safeParseJSON({ text, schema }) { try { const value = secureJsonParse(text); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes({ value, schema }); } catch (error) { return { success: false, error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }), rawValue: void 0 }; } } function isParsableJson(input) { try { secureJsonParse(input); return true; } catch (e) { return false; } } function parseJsonEventStream({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON({ text: data, schema })); } }) ); } async function parseProviderOptions({ provider, providerOptions, schema }) { if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) { return void 0; } const parsedProviderOptions = await safeValidateTypes({ value: providerOptions[provider], schema }); if (!parsedProviderOptions.success) { throw new InvalidArgumentError({ argument: "providerOptions", message: `invalid ${provider} provider options`, cause: parsedProviderOptions.error }); } return parsedProviderOptions.value; } var getOriginalFetch2 = () => globalThis.fetch; var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({ url, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({ url, headers, body: { content: formData, values: Object.fromEntries(formData.entries()) }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => { try { const response = await fetch2(url, { method: "POST", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent() ), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (isAbortError(error) || APICallError.isInstance(error)) { throw error; } throw new APICallError({ message: "Failed to process error response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (error instanceof Error) { if (isAbortError(error) || APICallError.isInstance(error)) { throw error; } } throw new APICallError({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } } catch (error) { throw handleFetchError({ error, url, requestBodyValues: body.values }); } }; function tool(tool22) { return tool22; } function dynamicTool(tool22) { return { ...tool22, type: "dynamic" }; } function createProviderDefinedToolFactory({ id, name: name23, inputSchema }) { return ({ execute, outputSchema, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name23, args, inputSchema, outputSchema, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name23, inputSchema, outputSchema }) { return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name23, args, inputSchema, outputSchema, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function removeUndefinedEntries(record) { return Object.fromEntries( Object.entries(record).filter(([_key, value]) => value != null) ); } async function resolve(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); const responseHeaders = extractResponseHeaders(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError({ message: errorToMessage(parsedError), url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler = (chunkSchema2) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } return { responseHeaders, value: parseJsonEventStream({ stream: response.body, schema: chunkSchema2 }) }; }; var createJsonStreamResponseHandler = (chunkSchema2) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } let buffer = ""; return { responseHeaders, value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough( new TransformStream({ async transform(chunkText, controller) { if (chunkText.endsWith("\n")) { controller.enqueue( await safeParseJSON({ text: buffer + chunkText, schema: chunkSchema2 }) ); buffer = ""; } else { buffer += chunkText; } } }) ) }; }; var createJsonResponseHandler = (responseSchema2) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON({ text: responseBody, schema: responseSchema2 }); const responseHeaders = extractResponseHeaders(response); if (!parsedResult.success) { throw new APICallError({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders(response); if (!response.body) { throw new APICallError({ message: "Response body is empty", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0 }); } try { const buffer = await response.arrayBuffer(); return { responseHeaders, value: new Uint8Array(buffer) }; } catch (error) { throw new APICallError({ message: "Failed to read response as array buffer", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0, cause: error }); } }; var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders(response); const responseBody = await response.text(); return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody }) }; }; var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema(jsonSchema22, { validate } = {}) { return { [schemaSymbol]: true, _type: void 0, // should never be used directly [validatorSymbol]: true, get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function addAdditionalPropertiesToJsonSchema(jsonSchema22) { if (jsonSchema22.type === "object") { jsonSchema22.additionalProperties = false; const properties = jsonSchema22.properties; if (properties != null) { for (const property in properties) { properties[property] = addAdditionalPropertiesToJsonSchema( properties[property] ); } } } if (jsonSchema22.type === "array" && jsonSchema22.items != null) { if (Array.isArray(jsonSchema22.items)) { jsonSchema22.items = jsonSchema22.items.map( (item) => addAdditionalPropertiesToJsonSchema(item) ); } else { jsonSchema22.items = addAdditionalPropertiesToJsonSchema( jsonSchema22.items ); } } return jsonSchema22; } var ignoreOverride = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; function parseAnyDef() { return {}; } function parseArrayDef(def, refs) { var _a23, _b23, _c; const res = { type: "array" }; if (((_a23 = def.type) == null ? void 0 : _a23._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseBooleanDef() { return { type: "boolean" }; } function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def); } } var integerDateParser = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check of def.checks) { switch (check.kind) { case "min": res.minimum = check.value; break; case "max": res.maximum = check.value; break; } } return res; }; function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(); } function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef(def) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } var emojiRegex = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex === void 0) { emojiRegex = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs); break; } break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex, check.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check.message, refs); break; case "startsWith": addPattern( res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs ); break; case "endsWith": addPattern( res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs ); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "date": addFormat(res, "date", check.message, refs); break; case "time": addFormat(res, "time", check.message, refs); break; case "duration": addFormat(res, "duration", check.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "includes": { addPattern( res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs ); break; } case "ip": { if (check.version !== "v6") { addFormat(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat(res, "ipv6", check.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check.message, refs); break; case "cidr": { if (check.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); } if (check.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check.message, refs); } } } } return res; } function escapeLiteralCheckValue(literal, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; } var ALPHA_NUMERIC = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat(schema, value, message, refs) { var _a23; if (schema.format || ((_a23 = schema.anyOf) == null ? void 0 : _a23.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern(schema, regex, message, refs) { var _a23; if (schema.pattern || ((_a23 = schema.allOf) == null ? void 0 : _a23.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push({ pattern: stringifyRegExpWithFlags(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { schema.pattern = stringifyRegExpWithFlags(regex, refs); } } function stringifyRegExpWithFlags(regex, refs) { var _a23; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? void 0 : _a23.match(/[a-z]/))) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } function parseRecordDef(def, refs) { var _a23, _b23, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a23 = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a23 : refs.allowedAdditionalProperties }; if (((_b23 = def.keyType) == null ? void 0 : _b23._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type, ...keyType } = parseBrandedDef( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef(); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from( new Set(actualValues.map((values) => typeof values)) ); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } function parseNeverDef() { return { not: parseAnyDef() }; } function parseNullDef() { return { type: "null" }; } var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce( (acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, [] ); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce( (acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, [] ) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce( (acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf(def, refs); } var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] }) ).filter( (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0) ); return anyOf.length ? { anyOf } : void 0; }; function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings[def.innerType._def.typeName], "null" ] }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; break; case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseObjectDef(def, refs) { const result = { type: "object", properties: {} }; const required = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional(propDef); const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required.push(propName); } } if (required.length) { result.required = required; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch (e) { return true; } } var parseOptionalDef = (def, refs) => { var _a23; if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? void 0 : _a23.toString())) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef(); }; var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if (def.maxSize) { schema.maxItems = def.maxSize.value; } return schema; } function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map( (x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map( (x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ) }; } } function parseUndefinedDef() { return { not: parseAnyDef() }; } function parseUnknownDef() { return parseAnyDef(); } var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; var selectParser = (def, typeName, refs) => { switch (typeName) { case v3.ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def); case v3.ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def); case v3.ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); case v3.ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(); case v3.ZodFirstPartyTypeKind.ZodNull: return parseNullDef(); case v3.ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodUnion: case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def); case v3.ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); case v3.ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); case v3.ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case v3.ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodNaN: case v3.ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(); case v3.ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(); case v3.ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(); case v3.ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); case v3.ZodFirstPartyTypeKind.ZodFunction: case v3.ZodFirstPartyTypeKind.ZodVoid: case v3.ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; var getRelativePath = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; function parseDef(def, refs, forceResolution = false) { var _a23; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a23 = refs.override) == null ? void 0 : _a23.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn( `Recursive reference detected at ${refs.currentPath.join( "/" )}! Defaulting to any` ); return parseAnyDef(); } return refs.$refStrategy === "seen" ? parseAnyDef() : void 0; } } }; var addMeta = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; } return jsonSchema22; }; var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name23, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name23], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zodToJsonSchema = (schema, options) => { var _a23; const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name33, schema2]) => { var _a33; return { ...acc, [name33]: (_a33 = parseDef( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name33] }, true )) != null ? _a33 : parseAnyDef() }; }, {} ) : void 0; const name23 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a23 = parseDef( schema._def, name23 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name23] }, false )) != null ? _a23 : parseAnyDef(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name23 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name23 ].join("/"), [refs.definitionPath]: { ...definitions, [name23]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var zod_to_json_schema_default = zodToJsonSchema; function zod3Schema(zodSchema22, options) { var _a23; const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false; return jsonSchema( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod_to_json_schema_default(zodSchema22, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema22.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema(zodSchema22, options) { var _a23; const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false; return jsonSchema( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema( z4__namespace.toJSONSchema(zodSchema22, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await z4__namespace.safeParseAsync(zodSchema22, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema(zodSchema22) { return "_zod" in zodSchema22; } function zodSchema(zodSchema22, options) { if (isZod4Schema(zodSchema22)) { return zod4Schema(zodSchema22, options); } else { return zod3Schema(zodSchema22, options); } } function isSchema(value) { return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value; } function asSchema(schema) { return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema); } var { btoa, atob } = globalThis; function convertBase64ToUint8Array(base64String) { const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/"); const latin1string = atob(base64Url); return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0)); } function convertUint8ArrayToBase64(array) { let latin1string = ""; for (let i = 0; i < array.length; i++) { latin1string += String.fromCodePoint(array[i]); } return btoa(latin1string); } function convertToBase64(value) { return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value; } function validateDownloadUrl(url) { let parsed; try { parsed = new URL(url); } catch (e) { throw new DownloadError({ url, message: `Invalid URL: ${url}` }); } if (parsed.protocol === "data:") { return; } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new DownloadError({ url, message: `URL scheme must be http, https, or data, got ${parsed.protocol}` }); } const hostname = parsed.hostname; if (!hostname) { throw new DownloadError({ url, message: `URL must have a hostname` }); } if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost")) { throw new DownloadError({ url, message: `URL with hostname ${hostname} is not allowed` }); } if (hostname.startsWith("[") && hostname.endsWith("]")) { const ipv6 = hostname.slice(1, -1); if (isPrivateIPv6(ipv6)) { throw new DownloadError({ url, message: `URL with IPv6 address ${hostname} is not allowed` }); } return; } if (isIPv4(hostname)) { if (isPrivateIPv4(hostname)) { throw new DownloadError({ url, message: `URL with IP address ${hostname} is not allowed` }); } return; } } function isIPv4(hostname) { const parts = hostname.split("."); if (parts.length !== 4) return false; return parts.every((part) => { const num = Number(part); return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part; }); } function isPrivateIPv4(ip) { const parts = ip.split(".").map(Number); const [a, b] = parts; if (a === 0) return true; if (a === 10) return true; if (a === 127) return true; if (a === 169 && b === 254) return true; if (a === 172 && b >= 16 && b <= 31) return true; if (a === 192 && b === 168) return true; return false; } function isPrivateIPv6(ip) { const normalized = ip.toLowerCase(); if (normalized === "::1") return true; if (normalized === "::") return true; if (normalized.startsWith("::ffff:")) { const mappedPart = normalized.slice(7); if (isIPv4(mappedPart)) { return isPrivateIPv4(mappedPart); } const hexParts = mappedPart.split(":"); if (hexParts.length === 2) { const high = parseInt(hexParts[0], 16); const low = parseInt(hexParts[1], 16); if (!isNaN(high) && !isNaN(low)) { const a = high >> 8 & 255; const b = high & 255; const c = low >> 8 & 255; const d = low & 255; return isPrivateIPv4(`${a}.${b}.${c}.${d}`); } } } if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true; if (normalized.startsWith("fe80")) return true; return false; } function withoutTrailingSlash(url) { return url == null ? void 0 : url.replace(/\/$/, ""); } function isAsyncIterable(obj) { return obj != null && typeof obj[Symbol.asyncIterator] === "function"; } async function* executeTool({ execute, input, options }) { const result = execute(input, options); if (isAsyncIterable(result)) { let lastOutput; for await (const output of result) { lastOutput = output; yield { type: "preliminary", output }; } yield { type: "final", output: lastOutput }; } else { yield { type: "final", output: await result }; } } function getOpenAIMetadata(message) { var _a18, _b18; return (_b18 = (_a18 = message == null ? void 0 : message.providerOptions) == null ? void 0 : _a18.openaiCompatible) != null ? _b18 : {}; } function convertToOpenAICompatibleChatMessages(prompt) { const messages = []; for (const { role, content, ...message } of prompt) { const metadata = getOpenAIMetadata({ ...message }); switch (role) { case "system": { messages.push({ role: "system", content, ...metadata }); break; } case "user": { if (content.length === 1 && content[0].type === "text") { messages.push({ role: "user", content: content[0].text, ...getOpenAIMetadata(content[0]) }); break; } messages.push({ role: "user", content: content.map((part) => { const partMetadata = getOpenAIMetadata(part); switch (part.type) { case "text": { return { type: "text", text: part.text, ...partMetadata }; } case "file": { if (part.mediaType.startsWith("image/")) { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; return { type: "image_url", image_url: { url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}` }, ...partMetadata }; } else { throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` }); } } } }), ...metadata }); break; } case "assistant": { let text = ""; let reasoning = ""; const toolCalls = []; for (const part of content) { const partMetadata = getOpenAIMetadata(part); switch (part.type) { case "text": { text += part.text; break; } case "reasoning": { reasoning += part.text; break; } case "tool-call": { toolCalls.push({ id: part.toolCallId, type: "function", function: { name: part.toolName, arguments: JSON.stringify(part.input) }, ...partMetadata }); break; } } } messages.push({ role: "assistant", content: text, ...reasoning.length > 0 ? { reasoning_content: reasoning } : {}, tool_calls: toolCalls.length > 0 ? toolCalls : void 0, ...metadata }); break; } case "tool": { for (const toolResponse of content) { const output = toolResponse.output; let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "content": case "json": case "error-json": contentValue = JSON.stringify(output.value); break; } const toolResponseMetadata = getOpenAIMetadata(toolResponse); messages.push({ role: "tool", tool_call_id: toolResponse.toolCallId, content: contentValue, ...toolResponseMetadata }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return messages; } function getResponseMetadata({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : void 0 }; } function mapOpenAICompatibleFinishReason(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "unknown"; } } var openaiCompatibleProviderOptions = z4.z.object({ /** * A unique identifier representing your end-user, which can help the provider to * monitor and detect abuse. */ user: z4.z.string().optional(), /** * Reasoning effort for reasoning models. Defaults to `medium`. */ reasoningEffort: z4.z.string().optional(), /** * Controls the verbosity of the generated text. Defaults to `medium`. */ textVerbosity: z4.z.string().optional() }); var openaiCompatibleErrorDataSchema = z4.z.object({ error: z4.z.object({ message: z4.z.string(), // The additional information below is handled loosely to support // OpenAI-compatible providers that have slightly different error // responses: type: z4.z.string().nullish(), param: z4.z.any().nullish(), code: z4.z.union([z4.z.string(), z4.z.number()]).nullish() }) }); var defaultOpenAICompatibleErrorStructure = { errorSchema: openaiCompatibleErrorDataSchema, errorToMessage: (data) => data.error.message }; function prepareTools({ tools, toolChoice }) { tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiCompatTools = []; for (const tool3 of tools) { if (tool3.type === "provider-defined") { toolWarnings.push({ type: "unsupported-tool", tool: tool3 }); } else { openaiCompatTools.push({ type: "function", function: { name: tool3.name, description: tool3.description, parameters: tool3.inputSchema } }); } } if (toolChoice == null) { return { tools: openaiCompatTools, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": case "required": return { tools: openaiCompatTools, toolChoice: type, toolWarnings }; case "tool": return { tools: openaiCompatTools, toolChoice: { type: "function", function: { name: toolChoice.toolName } }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } var OpenAICompatibleChatLanguageModel = class { // type inferred via constructor constructor(modelId, config) { this.specificationVersion = "v2"; var _a18, _b18; this.modelId = modelId; this.config = config; const errorStructure = (_a18 = config.errorStructure) != null ? _a18 : defaultOpenAICompatibleErrorStructure; this.chunkSchema = createOpenAICompatibleChatChunkSchema( errorStructure.errorSchema ); this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure); this.supportsStructuredOutputs = (_b18 = config.supportsStructuredOutputs) != null ? _b18 : false; } get provider() { return this.config.provider; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } get supportedUrls() { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).supportedUrls) == null ? void 0 : _b18.call(_a18)) != null ? _c : {}; } transformRequestBody(args) { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).transformRequestBody) == null ? void 0 : _b18.call(_a18, args)) != null ? _c : args; } convertUsage(usage) { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).convertUsage) == null ? void 0 : _b18.call(_a18, usage)) != null ? _c : convertOpenAICompatibleChatUsage(usage); } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, providerOptions, stopSequences, responseFormat, seed, toolChoice, tools }) { var _a18, _b18, _c, _d; const warnings = []; const compatibleOptions = Object.assign( (_a18 = await parseProviderOptions({ provider: "openai-compatible", providerOptions, schema: openaiCompatibleProviderOptions })) != null ? _a18 : {}, (_b18 = await parseProviderOptions({ provider: this.providerOptionsName, providerOptions, schema: openaiCompatibleProviderOptions })) != null ? _b18 : {} ); if (topK != null) { warnings.push({ type: "unsupported-setting", setting: "topK" }); } if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) { warnings.push({ type: "unsupported-setting", setting: "responseFormat", details: "JSON response format schema is only supported with structuredOutputs" }); } const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareTools({ tools, toolChoice }); return { args: { // model id: model: this.modelId, // model specific settings: user: compatibleOptions.user, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? { type: "json_schema", json_schema: { schema: responseFormat.schema, name: (_c = responseFormat.name) != null ? _c : "response", description: responseFormat.description } } : { type: "json_object" } : void 0, stop: stopSequences, seed, ...Object.fromEntries( Object.entries( (_d = providerOptions == null ? void 0 : providerOptions[this.providerOptionsName]) != null ? _d : {} ).filter( ([key]) => !Object.keys(openaiCompatibleProviderOptions.shape).includes(key) ) ), reasoning_effort: compatibleOptions.reasoningEffort, verbosity: compatibleOptions.textVerbosity, // messages: messages: convertToOpenAICompatibleChatMessages(prompt), // tools: tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e; const { args, warnings } = await this.getArgs({ ...options }); const transformedArgs = this.transformRequestBody(args); const body = JSON.stringify(transformedArgs); const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), options.headers), body: transformedArgs, failedResponseHandler: this.failedResponseHandler, successfulResponseHandler: createJsonResponseHandler( OpenAICompatibleChatResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = responseBody.choices[0]; const content = []; const text = choice.message.content; if (text != null && text.length > 0) { content.push({ type: "text", text }); } const reasoning = (_a18 = choice.message.reasoning_content) != null ? _a18 : choice.message.reasoning; if (reasoning != null && reasoning.length > 0) { content.push({ type: "reasoning", text: reasoning }); } if (choice.message.tool_calls != null) { for (const toolCall of choice.message.tool_calls) { content.push({ type: "tool-call", toolCallId: (_b18 = toolCall.id) != null ? _b18 : generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); } } const providerMetadata = { [this.providerOptionsName]: {}, ...await ((_d = (_c = this.config.metadataExtractor) == null ? void 0 : _c.extractMetadata) == null ? void 0 : _d.call(_c, { parsedBody: rawResponse })) }; const completionTokenDetails = (_e = responseBody.usage) == null ? void 0 : _e.completion_tokens_details; if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; } if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; } return { content, finishReason: mapOpenAICompatibleFinishReason(choice.finish_reason), usage: this.convertUsage(responseBody.usage), providerMetadata, request: { body }, response: { ...getResponseMetadata(responseBody), headers: responseHeaders, body: rawResponse }, warnings }; } async doStream(options) { var _a18; const { args, warnings } = await this.getArgs({ ...options }); const body = this.transformRequestBody({ ...args, stream: true, // only include stream_options when in strict compatibility mode: stream_options: this.config.includeUsage ? { include_usage: true } : void 0 }); const metadataExtractor = (_a18 = this.config.metadataExtractor) == null ? void 0 : _a18.createStreamExtractor(); const { responseHeaders, value: response } = await postJsonToApi({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: this.failedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( this.chunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const toolCalls = []; let finishReason = "unknown"; const usage = { completionTokens: void 0, completionTokensDetails: { reasoningTokens: void 0, acceptedPredictionTokens: void 0, rejectedPredictionTokens: void 0 }, promptTokens: void 0, promptTokensDetails: { cachedTokens: void 0 }, totalTokens: void 0 }; let lastUsage = void 0; let isFirstChunk = true; const providerOptionsName = this.providerOptionsName; let isActiveReasoning = false; let isActiveText = false; const convertUsage = (usage2) => this.convertUsage(usage2); return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, // TODO we lost type safety on Chunk, most likely due to the error schema. MUST FIX transform(chunk, controller) { var _a23, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = "error"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; metadataExtractor == null ? void 0 : metadataExtractor.processChunk(chunk.rawValue); if ("error" in value) { finishReason = "error"; controller.enqueue({ type: "error", error: value.error.message }); return; } if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata(value) }); } if (value.usage != null) { lastUsage = value.usage; const { prompt_tokens, completion_tokens, total_tokens, prompt_tokens_details, completion_tokens_details } = value.usage; usage.promptTokens = prompt_tokens != null ? prompt_tokens : void 0; usage.completionTokens = completion_tokens != null ? completion_tokens : void 0; usage.totalTokens = total_tokens != null ? total_tokens : void 0; if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) { usage.completionTokensDetails.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens; } if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) { usage.completionTokensDetails.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens; } if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) { usage.completionTokensDetails.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens; } if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) { usage.promptTokensDetails.cachedTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens; } } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = mapOpenAICompatibleFinishReason( choice.finish_reason ); } if ((choice == null ? void 0 : choice.delta) == null) { return; } const delta = choice.delta; const reasoningContent = (_a23 = delta.reasoning_content) != null ? _a23 : delta.reasoning; if (reasoningContent) { if (!isActiveReasoning) { controller.enqueue({ type: "reasoning-start", id: "reasoning-0" }); isActiveReasoning = true; } controller.enqueue({ type: "reasoning-delta", id: "reasoning-0", delta: reasoningContent }); } if (delta.content) { if (!isActiveText) { controller.enqueue({ type: "text-start", id: "txt-0" }); isActiveText = true; } controller.enqueue({ type: "text-delta", id: "txt-0", delta: delta.content }); } if (delta.tool_calls != null) { for (const toolCallDelta of delta.tool_calls) { const index = toolCallDelta.index; if (toolCalls[index] == null) { if (toolCallDelta.id == null) { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'id' to be a string.` }); } if (((_b18 = toolCallDelta.function) == null ? void 0 : _b18.name) == null) { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function.name' to be a string.` }); } controller.enqueue({ type: "tool-input-start", id: toolCallDelta.id, toolName: toolCallDelta.function.name }); toolCalls[index] = { id: toolCallDelta.id, type: "function", function: { name: toolCallDelta.function.name, arguments: (_c = toolCallDelta.function.arguments) != null ? _c : "" }, hasFinished: false }; const toolCall2 = toolCalls[index]; if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null) { if (toolCall2.function.arguments.length > 0) { controller.enqueue({ type: "tool-input-delta", id: toolCall2.id, delta: toolCall2.function.arguments }); } if (isParsableJson(toolCall2.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall2.id }); controller.enqueue({ type: "tool-call", toolCallId: (_f = toolCall2.id) != null ? _f : generateId(), toolName: toolCall2.function.name, input: toolCall2.function.arguments }); toolCall2.hasFinished = true; } } continue; } const toolCall = toolCalls[index]; if (toolCall.hasFinished) { continue; } if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) { toolCall.function.arguments += (_i = (_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null ? _i : ""; } controller.enqueue({ type: "tool-input-delta", id: toolCall.id, delta: (_j = toolCallDelta.function.arguments) != null ? _j : "" }); if (((_k = toolCall.function) == null ? void 0 : _k.name) != null && ((_l = toolCall.function) == null ? void 0 : _l.arguments) != null && isParsableJson(toolCall.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall.id }); controller.enqueue({ type: "tool-call", toolCallId: (_m = toolCall.id) != null ? _m : generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); toolCall.hasFinished = true; } } } }, flush(controller) { var _a23; if (isActiveReasoning) { controller.enqueue({ type: "reasoning-end", id: "reasoning-0" }); } if (isActiveText) { controller.enqueue({ type: "text-end", id: "txt-0" }); } for (const toolCall of toolCalls.filter( (toolCall2) => !toolCall2.hasFinished )) { controller.enqueue({ type: "tool-input-end", id: toolCall.id }); controller.enqueue({ type: "tool-call", toolCallId: (_a23 = toolCall.id) != null ? _a23 : generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); } const providerMetadata = { [providerOptionsName]: {}, ...metadataExtractor == null ? void 0 : metadataExtractor.buildMetadata() }; if (usage.completionTokensDetails.acceptedPredictionTokens != null) { providerMetadata[providerOptionsName].acceptedPredictionTokens = usage.completionTokensDetails.acceptedPredictionTokens; } if (usage.completionTokensDetails.rejectedPredictionTokens != null) { providerMetadata[providerOptionsName].rejectedPredictionTokens = usage.completionTokensDetails.rejectedPredictionTokens; } controller.enqueue({ type: "finish", finishReason, usage: convertUsage(lastUsage), providerMetadata }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; var openaiCompatibleTokenUsageSchema = z4.z.object({ prompt_tokens: z4.z.number().nullish(), completion_tokens: z4.z.number().nullish(), total_tokens: z4.z.number().nullish(), prompt_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), completion_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish(), accepted_prediction_tokens: z4.z.number().nullish(), rejected_prediction_tokens: z4.z.number().nullish() }).nullish() }).nullish(); function convertOpenAICompatibleChatUsage(usage) { var _a18, _b18, _c, _d, _e, _f, _g; return { inputTokens: (_a18 = usage == null ? void 0 : usage.prompt_tokens) != null ? _a18 : void 0, outputTokens: (_b18 = usage == null ? void 0 : usage.completion_tokens) != null ? _b18 : void 0, totalTokens: (_c = usage == null ? void 0 : usage.total_tokens) != null ? _c : void 0, reasoningTokens: (_e = (_d = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : void 0, cachedInputTokens: (_g = (_f = usage == null ? void 0 : usage.prompt_tokens_details) == null ? void 0 : _f.cached_tokens) != null ? _g : void 0 }; } var OpenAICompatibleChatResponseSchema = z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ message: z4.z.object({ role: z4.z.literal("assistant").nullish(), content: z4.z.string().nullish(), reasoning_content: z4.z.string().nullish(), reasoning: z4.z.string().nullish(), tool_calls: z4.z.array( z4.z.object({ id: z4.z.string().nullish(), function: z4.z.object({ name: z4.z.string(), arguments: z4.z.string() }) }) ).nullish() }), finish_reason: z4.z.string().nullish() }) ), usage: openaiCompatibleTokenUsageSchema }); var createOpenAICompatibleChatChunkSchema = (errorSchema) => z4.z.union([ z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ delta: z4.z.object({ role: z4.z.enum(["assistant"]).nullish(), content: z4.z.string().nullish(), // Most openai-compatible models set `reasoning_content`, but some // providers serving `gpt-oss` set `reasoning`. See #7866 reasoning_content: z4.z.string().nullish(), reasoning: z4.z.string().nullish(), tool_calls: z4.z.array( z4.z.object({ index: z4.z.number(), id: z4.z.string().nullish(), function: z4.z.object({ name: z4.z.string().nullish(), arguments: z4.z.string().nullish() }) }) ).nullish() }).nullish(), finish_reason: z4.z.string().nullish() }) ), usage: openaiCompatibleTokenUsageSchema }), errorSchema ]); function convertToOpenAICompatibleCompletionPrompt({ prompt, user = "user", assistant = "assistant" }) { let text = ""; if (prompt[0].role === "system") { text += `${prompt[0].content} `; prompt = prompt.slice(1); } for (const { role, content } of prompt) { switch (role) { case "system": { throw new InvalidPromptError({ message: "Unexpected system message in prompt: ${content}", prompt }); } case "user": { const userMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } } }).filter(Boolean).join(""); text += `${user}: ${userMessage} `; break; } case "assistant": { const assistantMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } case "tool-call": { throw new UnsupportedFunctionalityError({ functionality: "tool-call messages" }); } } }).join(""); text += `${assistant}: ${assistantMessage} `; break; } case "tool": { throw new UnsupportedFunctionalityError({ functionality: "tool messages" }); } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } text += `${assistant}: `; return { prompt: text, stopSequences: [` ${user}:`] }; } function getResponseMetadata2({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : void 0 }; } function mapOpenAICompatibleFinishReason2(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "unknown"; } } var openaiCompatibleCompletionProviderOptions = z4.z.object({ /** * Echo back the prompt in addition to the completion. */ echo: z4.z.boolean().optional(), /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. */ logitBias: z4.z.record(z4.z.string(), z4.z.number()).optional(), /** * The suffix that comes after a completion of inserted text. */ suffix: z4.z.string().optional(), /** * A unique identifier representing your end-user, which can help providers to * monitor and detect abuse. */ user: z4.z.string().optional() }); var OpenAICompatibleCompletionLanguageModel = class { // type inferred via constructor constructor(modelId, config) { this.specificationVersion = "v2"; var _a18; this.modelId = modelId; this.config = config; const errorStructure = (_a18 = config.errorStructure) != null ? _a18 : defaultOpenAICompatibleErrorStructure; this.chunkSchema = createOpenAICompatibleCompletionChunkSchema( errorStructure.errorSchema ); this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure); } get provider() { return this.config.provider; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } get supportedUrls() { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).supportedUrls) == null ? void 0 : _b18.call(_a18)) != null ? _c : {}; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) { var _a18; const warnings = []; const completionOptions = (_a18 = await parseProviderOptions({ provider: this.providerOptionsName, providerOptions, schema: openaiCompatibleCompletionProviderOptions })) != null ? _a18 : {}; if (topK != null) { warnings.push({ type: "unsupported-setting", setting: "topK" }); } if (tools == null ? void 0 : tools.length) { warnings.push({ type: "unsupported-setting", setting: "tools" }); } if (toolChoice != null) { warnings.push({ type: "unsupported-setting", setting: "toolChoice" }); } if (responseFormat != null && responseFormat.type !== "text") { warnings.push({ type: "unsupported-setting", setting: "responseFormat", details: "JSON response format is not supported." }); } const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt }); const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; return { args: { // model id: model: this.modelId, // model specific settings: echo: completionOptions.echo, logit_bias: completionOptions.logitBias, suffix: completionOptions.suffix, user: completionOptions.user, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, seed, ...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName], // prompt: prompt: completionPrompt, // stop sequences: stop: stop.length > 0 ? stop : void 0 }, warnings }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f; const { args, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), options.headers), body: args, failedResponseHandler: this.failedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiCompatibleCompletionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const content = []; if (choice.text != null && choice.text.length > 0) { content.push({ type: "text", text: choice.text }); } return { content, usage: { inputTokens: (_b18 = (_a18 = response.usage) == null ? void 0 : _a18.prompt_tokens) != null ? _b18 : void 0, outputTokens: (_d = (_c = response.usage) == null ? void 0 : _c.completion_tokens) != null ? _d : void 0, totalTokens: (_f = (_e = response.usage) == null ? void 0 : _e.total_tokens) != null ? _f : void 0 }, finishReason: mapOpenAICompatibleFinishReason2(choice.finish_reason), request: { body: args }, response: { ...getResponseMetadata2(response), headers: responseHeaders, body: rawResponse }, warnings }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, // only include stream_options when in strict compatibility mode: stream_options: this.config.includeUsage ? { include_usage: true } : void 0 }; const { responseHeaders, value: response } = await postJsonToApi({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: this.failedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( this.chunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = "unknown"; const usage = { inputTokens: void 0, outputTokens: void 0, totalTokens: void 0 }; let isFirstChunk = true; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a18, _b18, _c; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = "error"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if ("error" in value) { finishReason = "error"; controller.enqueue({ type: "error", error: value.error }); return; } if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata2(value) }); controller.enqueue({ type: "text-start", id: "0" }); } if (value.usage != null) { usage.inputTokens = (_a18 = value.usage.prompt_tokens) != null ? _a18 : void 0; usage.outputTokens = (_b18 = value.usage.completion_tokens) != null ? _b18 : void 0; usage.totalTokens = (_c = value.usage.total_tokens) != null ? _c : void 0; } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = mapOpenAICompatibleFinishReason2( choice.finish_reason ); } if ((choice == null ? void 0 : choice.text) != null) { controller.enqueue({ type: "text-delta", id: "0", delta: choice.text }); } }, flush(controller) { if (!isFirstChunk) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, usage }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; var usageSchema = z4.z.object({ prompt_tokens: z4.z.number(), completion_tokens: z4.z.number(), total_tokens: z4.z.number() }); var openaiCompatibleCompletionResponseSchema = z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ text: z4.z.string(), finish_reason: z4.z.string() }) ), usage: usageSchema.nullish() }); var createOpenAICompatibleCompletionChunkSchema = (errorSchema) => z4.z.union([ z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ text: z4.z.string(), finish_reason: z4.z.string().nullish(), index: z4.z.number() }) ), usage: usageSchema.nullish() }), errorSchema ]); var openaiCompatibleEmbeddingProviderOptions = z4.z.object({ /** * The number of dimensions the resulting output embeddings should have. * Only supported in text-embedding-3 and later models. */ dimensions: z4.z.number().optional(), /** * A unique identifier representing your end-user, which can help providers to * monitor and detect abuse. */ user: z4.z.string().optional() }); var OpenAICompatibleEmbeddingModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } get maxEmbeddingsPerCall() { var _a18; return (_a18 = this.config.maxEmbeddingsPerCall) != null ? _a18 : 2048; } get supportsParallelCalls() { var _a18; return (_a18 = this.config.supportsParallelCalls) != null ? _a18 : true; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a18, _b18, _c; const compatibleOptions = Object.assign( (_a18 = await parseProviderOptions({ provider: "openai-compatible", providerOptions, schema: openaiCompatibleEmbeddingProviderOptions })) != null ? _a18 : {}, (_b18 = await parseProviderOptions({ provider: this.providerOptionsName, providerOptions, schema: openaiCompatibleEmbeddingProviderOptions })) != null ? _b18 : {} ); if (values.length > this.maxEmbeddingsPerCall) { throw new TooManyEmbeddingValuesForCallError({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const { responseHeaders, value: response, rawValue } = await postJsonToApi({ url: this.config.url({ path: "/embeddings", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), headers), body: { model: this.modelId, input: values, encoding_format: "float", dimensions: compatibleOptions.dimensions, user: compatibleOptions.user }, failedResponseHandler: createJsonErrorResponseHandler( (_c = this.config.errorStructure) != null ? _c : defaultOpenAICompatibleErrorStructure ), successfulResponseHandler: createJsonResponseHandler( openaiTextEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { embeddings: response.data.map((item) => item.embedding), usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, providerMetadata: response.providerMetadata, response: { headers: responseHeaders, body: rawValue } }; } }; var openaiTextEmbeddingResponseSchema = z4.z.object({ data: z4.z.array(z4.z.object({ embedding: z4.z.array(z4.z.number()) })), usage: z4.z.object({ prompt_tokens: z4.z.number() }).nullish(), providerMetadata: z4.z.record(z4.z.string(), z4.z.record(z4.z.string(), z4.z.any())).optional() }); var OpenAICompatibleImageModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v2"; this.maxImagesPerCall = 10; } get provider() { return this.config.provider; } /** * The provider options key used to extract provider-specific options. */ get providerOptionsKey() { return this.config.provider.split(".")[0].trim(); } async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a18, _b18, _c, _d; const warnings = []; if (aspectRatio != null) { warnings.push({ type: "unsupported-setting", setting: "aspectRatio", details: "This model does not support aspect ratio. Use `size` instead." }); } if (seed != null) { warnings.push({ type: "unsupported-setting", setting: "seed" }); } const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); const { value: response, responseHeaders } = await postJsonToApi({ url: this.config.url({ path: "/images/generations", modelId: this.modelId }), headers: combineHeaders(this.config.headers(), headers), body: { model: this.modelId, prompt, n, size, ...providerOptions[this.providerOptionsKey], response_format: "b64_json" }, failedResponseHandler: createJsonErrorResponseHandler( (_d = this.config.errorStructure) != null ? _d : defaultOpenAICompatibleErrorStructure ), successfulResponseHandler: createJsonResponseHandler( openaiCompatibleImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response.data.map((item) => item.b64_json), warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders } }; } }; var openaiCompatibleImageResponseSchema = z4.z.object({ data: z4.z.array(z4.z.object({ b64_json: z4.z.string() })) }); var VERSION2 = "1.0.39" ; function createOpenAICompatible(options) { const baseURL = withoutTrailingSlash(options.baseURL); const providerName = options.name; const headers = { ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` }, ...options.headers }; const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION2}`); const getCommonModelConfig = (modelType) => ({ provider: `${providerName}.${modelType}`, url: ({ path }) => { const url = new URL(`${baseURL}${path}`); if (options.queryParams) { url.search = new URLSearchParams(options.queryParams).toString(); } return url.toString(); }, headers: getHeaders, fetch: options.fetch }); const createLanguageModel = (modelId) => createChatModel(modelId); const createChatModel = (modelId) => new OpenAICompatibleChatLanguageModel(modelId, { ...getCommonModelConfig("chat"), includeUsage: options.includeUsage, supportsStructuredOutputs: options.supportsStructuredOutputs, supportedUrls: options.supportedUrls, transformRequestBody: options.transformRequestBody, metadataExtractor: options.metadataExtractor, convertUsage: options.convertUsage }); const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, { ...getCommonModelConfig("completion"), includeUsage: options.includeUsage }); const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, { ...getCommonModelConfig("embedding") }); const createImageModel = (modelId) => new OpenAICompatibleImageModel(modelId, getCommonModelConfig("image")); const provider = (modelId) => createLanguageModel(modelId); provider.languageModel = createLanguageModel; provider.chatModel = createChatModel; provider.completionModel = createCompletionModel; provider.textEmbeddingModel = createEmbeddingModel; provider.imageModel = createImageModel; return provider; } // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/3.0.10/0a7346fe2d918129694b7a3854f60556297703876a7eb06af86e8f8dfed8a65f/node_modules/@ai-sdk/provider/dist/index.mjs var marker16 = "vercel.ai.error"; var symbol16 = Symbol.for(marker16); var _a16; var _b16; var AISDKError2 = class _AISDKError2 extends (_b16 = Error, _a16 = symbol16, _b16) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name142, message, cause }) { super(message); this[_a16] = true; this.name = name142; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error) { return _AISDKError2.hasMarker(error, marker16); } static hasMarker(error, marker152) { const markerSymbol = Symbol.for(marker152); return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; } }; var name15 = "AI_APICallError"; var marker22 = `vercel.ai.error.${name15}`; var symbol22 = Symbol.for(marker22); var _a22; var _b22; var APICallError2 = class extends (_b22 = AISDKError2, _a22 = symbol22, _b22) { constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name: name15, message, cause }); this[_a22] = true; this.url = url; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error) { return AISDKError2.hasMarker(error, marker22); } }; var name22 = "AI_EmptyResponseBodyError"; var marker32 = `vercel.ai.error.${name22}`; var symbol32 = Symbol.for(marker32); var _a32; var _b32; var EmptyResponseBodyError2 = class extends (_b32 = AISDKError2, _a32 = symbol32, _b32) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name22, message }); this[_a32] = true; } static isInstance(error) { return AISDKError2.hasMarker(error, marker32); } }; function getErrorMessage3(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } var name32 = "AI_InvalidArgumentError"; var marker42 = `vercel.ai.error.${name32}`; var symbol42 = Symbol.for(marker42); var _a42; var _b42; var InvalidArgumentError2 = class extends (_b42 = AISDKError2, _a42 = symbol42, _b42) { constructor({ message, cause, argument }) { super({ name: name32, message, cause }); this[_a42] = true; this.argument = argument; } static isInstance(error) { return AISDKError2.hasMarker(error, marker42); } }; var name42 = "AI_InvalidPromptError"; var marker52 = `vercel.ai.error.${name42}`; var symbol52 = Symbol.for(marker52); var _a52; var _b52; var InvalidPromptError2 = class extends (_b52 = AISDKError2, _a52 = symbol52, _b52) { constructor({ prompt, message, cause }) { super({ name: name42, message: `Invalid prompt: ${message}`, cause }); this[_a52] = true; this.prompt = prompt; } static isInstance(error) { return AISDKError2.hasMarker(error, marker52); } }; var name52 = "AI_InvalidResponseDataError"; var marker62 = `vercel.ai.error.${name52}`; var symbol62 = Symbol.for(marker62); var _a62; var _b62; var InvalidResponseDataError2 = class extends (_b62 = AISDKError2, _a62 = symbol62, _b62) { constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) { super({ name: name52, message }); this[_a62] = true; this.data = data; } static isInstance(error) { return AISDKError2.hasMarker(error, marker62); } }; var name62 = "AI_JSONParseError"; var marker72 = `vercel.ai.error.${name62}`; var symbol72 = Symbol.for(marker72); var _a72; var _b72; var JSONParseError2 = class extends (_b72 = AISDKError2, _a72 = symbol72, _b72) { constructor({ text, cause }) { super({ name: name62, message: `JSON parsing failed: Text: ${text}. Error message: ${getErrorMessage3(cause)}`, cause }); this[_a72] = true; this.text = text; } static isInstance(error) { return AISDKError2.hasMarker(error, marker72); } }; var name72 = "AI_LoadAPIKeyError"; var marker82 = `vercel.ai.error.${name72}`; var symbol82 = Symbol.for(marker82); var _a82; var _b82; var LoadAPIKeyError2 = class extends (_b82 = AISDKError2, _a82 = symbol82, _b82) { // used in isInstance constructor({ message }) { super({ name: name72, message }); this[_a82] = true; } static isInstance(error) { return AISDKError2.hasMarker(error, marker82); } }; var name102 = "AI_NoSuchModelError"; var marker112 = `vercel.ai.error.${name102}`; var symbol112 = Symbol.for(marker112); var _a112; var _b112; var NoSuchModelError2 = class extends (_b112 = AISDKError2, _a112 = symbol112, _b112) { constructor({ errorName = name102, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) { super({ name: errorName, message }); this[_a112] = true; this.modelId = modelId; this.modelType = modelType; } static isInstance(error) { return AISDKError2.hasMarker(error, marker112); } }; var name112 = "AI_TooManyEmbeddingValuesForCallError"; var marker122 = `vercel.ai.error.${name112}`; var symbol122 = Symbol.for(marker122); var _a122; var _b122; var TooManyEmbeddingValuesForCallError2 = class extends (_b122 = AISDKError2, _a122 = symbol122, _b122) { constructor(options) { super({ name: name112, message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` }); this[_a122] = true; this.provider = options.provider; this.modelId = options.modelId; this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; this.values = options.values; } static isInstance(error) { return AISDKError2.hasMarker(error, marker122); } }; var name122 = "AI_TypeValidationError"; var marker132 = `vercel.ai.error.${name122}`; var symbol132 = Symbol.for(marker132); var _a132; var _b132; var TypeValidationError2 = class _TypeValidationError2 extends (_b132 = AISDKError2, _a132 = symbol132, _b132) { constructor({ value, cause, context }) { let contextPrefix = "Type validation failed"; if (context == null ? void 0 : context.field) { contextPrefix += ` for ${context.field}`; } if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) { contextPrefix += " ("; const parts = []; if (context.entityName) { parts.push(context.entityName); } if (context.entityId) { parts.push(`id: "${context.entityId}"`); } contextPrefix += parts.join(", "); contextPrefix += ")"; } super({ name: name122, message: `${contextPrefix}: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage3(cause)}`, cause }); this[_a132] = true; this.value = value; this.context = context; } static isInstance(error) { return AISDKError2.hasMarker(error, marker132); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value and context, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @param {TypeValidationContext} params.context - Optional context about what is being validated. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause, context }) { var _a152, _b152, _c; if (_TypeValidationError2.isInstance(cause) && cause.value === value && ((_a152 = cause.context) == null ? void 0 : _a152.field) === (context == null ? void 0 : context.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) { return cause; } return new _TypeValidationError2({ value, cause, context }); } }; var name132 = "AI_UnsupportedFunctionalityError"; var marker142 = `vercel.ai.error.${name132}`; var symbol142 = Symbol.for(marker142); var _a142; var _b142; var UnsupportedFunctionalityError2 = class extends (_b142 = AISDKError2, _a142 = symbol142, _b142) { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name132, message }); this[_a142] = true; this.functionality = functionality; } static isInstance(error) { return AISDKError2.hasMarker(error, marker142); } }; function combineHeaders2(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } function createToolNameMapping({ tools = [], providerToolNames, resolveProviderToolName }) { var _a23; const customToolNameToProviderToolName = {}; const providerToolNameToCustomToolName = {}; for (const tool22 of tools) { if (tool22.type === "provider") { const providerToolName = (_a23 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool22)) != null ? _a23 : tool22.id in providerToolNames ? providerToolNames[tool22.id] : void 0; if (providerToolName == null) { continue; } customToolNameToProviderToolName[tool22.name] = providerToolName; providerToolNameToCustomToolName[providerToolName] = tool22.name; } } return { toProviderToolName: (customToolName) => { var _a33; return (_a33 = customToolNameToProviderToolName[customToolName]) != null ? _a33 : customToolName; }, toCustomToolName: (providerToolName) => { var _a33; return (_a33 = providerToolNameToCustomToolName[providerToolName]) != null ? _a33 : providerToolName; } }; } async function delay2(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError2()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError2()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError2() { return new DOMException("Delay was aborted", "AbortError"); } function extractResponseHeaders2(response) { return Object.fromEntries([...response.headers]); } var { btoa: btoa2, atob: atob2 } = globalThis; function convertBase64ToUint8Array2(base64String) { const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/"); const latin1string = atob2(base64Url); return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0)); } function convertUint8ArrayToBase642(array) { let latin1string = ""; for (let i = 0; i < array.length; i++) { latin1string += String.fromCodePoint(array[i]); } return btoa2(latin1string); } function convertToBase642(value) { return value instanceof Uint8Array ? convertUint8ArrayToBase642(value) : value; } function convertImageModelFileToDataUri(file) { if (file.type === "url") return file.url; return `data:${file.mediaType};base64,${typeof file.data === "string" ? file.data : convertUint8ArrayToBase642(file.data)}`; } function convertToFormData(input, options = {}) { const { useArrayBrackets = true } = options; const formData = new FormData(); for (const [key, value] of Object.entries(input)) { if (value == null) { continue; } if (Array.isArray(value)) { if (value.length === 1) { formData.append(key, value[0]); continue; } const arrayKey = useArrayBrackets ? `${key}[]` : key; for (const item of value) { formData.append(arrayKey, item); } continue; } formData.append(key, value); } return formData; } var name16 = "AI_DownloadError"; var marker17 = `vercel.ai.error.${name16}`; var symbol17 = Symbol.for(marker17); var _a17; var _b17; var DownloadError2 = class extends (_b17 = AISDKError2, _a17 = symbol17, _b17) { constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) { super({ name: name16, message, cause }); this[_a17] = true; this.url = url; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error) { return AISDKError2.hasMarker(error, marker17); } }; var DEFAULT_MAX_DOWNLOAD_SIZE2 = 2 * 1024 * 1024 * 1024; async function readResponseWithSizeLimit2({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE2 }) { const contentLength = response.headers.get("content-length"); if (contentLength != null) { const length = parseInt(contentLength, 10); if (!isNaN(length) && length > maxBytes) { throw new DownloadError2({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).` }); } } const body = response.body; if (body == null) { return new Uint8Array(0); } const reader = body.getReader(); const chunks = []; let totalBytes = 0; try { while (true) { const { done, value } = await reader.read(); if (done) { break; } totalBytes += value.length; if (totalBytes > maxBytes) { throw new DownloadError2({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.` }); } chunks.push(value); } } finally { try { await reader.cancel(); } finally { reader.releaseLock(); } } const result = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } function validateDownloadUrl2(url) { let parsed; try { parsed = new URL(url); } catch (e) { throw new DownloadError2({ url, message: `Invalid URL: ${url}` }); } if (parsed.protocol === "data:") { return; } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new DownloadError2({ url, message: `URL scheme must be http, https, or data, got ${parsed.protocol}` }); } const hostname = parsed.hostname; if (!hostname) { throw new DownloadError2({ url, message: `URL must have a hostname` }); } if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost")) { throw new DownloadError2({ url, message: `URL with hostname ${hostname} is not allowed` }); } if (hostname.startsWith("[") && hostname.endsWith("]")) { const ipv6 = hostname.slice(1, -1); if (isPrivateIPv62(ipv6)) { throw new DownloadError2({ url, message: `URL with IPv6 address ${hostname} is not allowed` }); } return; } if (isIPv42(hostname)) { if (isPrivateIPv42(hostname)) { throw new DownloadError2({ url, message: `URL with IP address ${hostname} is not allowed` }); } return; } } function isIPv42(hostname) { const parts = hostname.split("."); if (parts.length !== 4) return false; return parts.every((part) => { const num = Number(part); return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part; }); } function isPrivateIPv42(ip) { const parts = ip.split(".").map(Number); const [a, b] = parts; if (a === 0) return true; if (a === 10) return true; if (a === 127) return true; if (a === 169 && b === 254) return true; if (a === 172 && b >= 16 && b <= 31) return true; if (a === 192 && b === 168) return true; return false; } function isPrivateIPv62(ip) { const normalized = ip.toLowerCase(); if (normalized === "::1") return true; if (normalized === "::") return true; if (normalized.startsWith("::ffff:")) { const mappedPart = normalized.slice(7); if (isIPv42(mappedPart)) { return isPrivateIPv42(mappedPart); } const hexParts = mappedPart.split(":"); if (hexParts.length === 2) { const high = parseInt(hexParts[0], 16); const low = parseInt(hexParts[1], 16); if (!isNaN(high) && !isNaN(low)) { const a = high >> 8 & 255; const b = high & 255; const c = low >> 8 & 255; const d = low & 255; return isPrivateIPv42(`${a}.${b}.${c}.${d}`); } } } if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true; if (normalized.startsWith("fe80")) return true; return false; } async function downloadBlob(url, options) { var _a23, _b23; validateDownloadUrl2(url); try { const response = await fetch(url, { signal: void 0 }); if (response.redirected) { validateDownloadUrl2(response.url); } if (!response.ok) { throw new DownloadError2({ url, statusCode: response.status, statusText: response.statusText }); } const data = await readResponseWithSizeLimit2({ response, url, maxBytes: (_a23 = void 0 ) != null ? _a23 : DEFAULT_MAX_DOWNLOAD_SIZE2 }); const contentType = (_b23 = response.headers.get("content-type")) != null ? _b23 : void 0; return new Blob([data], contentType ? { type: contentType } : void 0); } catch (error) { if (DownloadError2.isInstance(error)) { throw error; } throw new DownloadError2({ url, cause: error }); } } var createIdGenerator2 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError2({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; var generateId2 = createIdGenerator2(); function isAbortError2(error) { return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js error.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES2 = ["fetch failed", "failed to fetch"]; var BUN_ERROR_CODES = [ "ConnectionRefused", "ConnectionClosed", "FailedToOpenSocket", "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE" ]; function isBunNetworkError(error) { if (!(error instanceof Error)) { return false; } const code = error.code; if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) { return true; } return false; } function handleFetchError2({ error, url, requestBodyValues }) { if (isAbortError2(error)) { return error; } if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error.message.toLowerCase())) { const cause = error.cause; if (cause != null) { return new APICallError2({ message: `Cannot connect to API: ${cause.message}`, cause, url, requestBodyValues, isRetryable: true // retry when network error }); } } if (isBunNetworkError(error)) { return new APICallError2({ message: `Cannot connect to API: ${error.message}`, cause: error, url, requestBodyValues, isRetryable: true }); } return error; } function getRuntimeEnvironmentUserAgent2(globalThisAny = globalThis) { var _a23, _b23, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a23 = globalThisAny.navigator) == null ? void 0 : _a23.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders2(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix2(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders2(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION3 = "4.0.27" ; var getOriginalFetch3 = () => globalThis.fetch; var getFromApi2 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch3() }) => { try { const response = await fetch2(url, { method: "GET", headers: withUserAgentSuffix2( headers, `ai-sdk/provider-utils/${VERSION3}`, getRuntimeEnvironmentUserAgent2() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders2(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: {} }); } catch (error) { if (isAbortError2(error) || APICallError2.isInstance(error)) { throw error; } throw new APICallError2({ message: "Failed to process error response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: {} }); } catch (error) { if (error instanceof Error) { if (isAbortError2(error) || APICallError2.isInstance(error)) { throw error; } } throw new APICallError2({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: {} }); } } catch (error) { throw handleFetchError2({ error, url, requestBodyValues: {} }); } }; var DEFAULT_SCHEMA_PREFIX2 = "JSON schema:"; var DEFAULT_SCHEMA_SUFFIX2 = "You MUST answer with a JSON object that matches the JSON schema above."; var DEFAULT_GENERIC_SUFFIX2 = "You MUST answer with JSON."; function injectJsonInstruction2({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX2 : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX2 : DEFAULT_GENERIC_SUFFIX2 }) { return [ prompt != null && prompt.length > 0 ? prompt : void 0, prompt != null && prompt.length > 0 ? "" : void 0, // add a newline if prompt is not null schemaPrefix, schema != null ? JSON.stringify(schema) : void 0, schemaSuffix ].filter((line) => line != null).join("\n"); } function injectJsonInstructionIntoMessages2({ messages, schema, schemaPrefix, schemaSuffix }) { var _a23, _b23; const systemMessage = ((_a23 = messages[0]) == null ? void 0 : _a23.role) === "system" ? { ...messages[0] } : { role: "system", content: "" }; systemMessage.content = injectJsonInstruction2({ prompt: systemMessage.content, schema, schemaPrefix, schemaSuffix }); return [ systemMessage, ...((_b23 = messages[0]) == null ? void 0 : _b23.role) === "system" ? messages.slice(1) : messages ]; } function isNonNullable(value) { return value != null; } function loadApiKey2({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { if (typeof apiKey === "string") { return apiKey; } if (apiKey != null) { throw new LoadAPIKeyError2({ message: `${description} API key must be a string.` }); } if (typeof process === "undefined") { throw new LoadAPIKeyError2({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` }); } apiKey = process.env[environmentVariableName]; if (apiKey == null) { throw new LoadAPIKeyError2({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` }); } if (typeof apiKey !== "string") { throw new LoadAPIKeyError2({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); } return apiKey; } function loadOptionalSetting2({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } function mediaTypeToExtension2(mediaType) { var _a23; const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); return (_a23 = { mpeg: "mp3", "x-wav": "wav", opus: "ogg", mp4: "m4a", "x-m4a": "m4a" }[subtype]) != null ? _a23 : subtype; } var suspectProtoRx2 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx2 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse2(text) { const obj = JSON.parse(text); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx2.test(text) === false && suspectConstructorRx2.test(text) === false) { return obj; } return filter2(obj); } function filter2(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse2(text) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e) { return _parse2(text); } try { return _parse2(text); } finally { Error.stackTraceLimit = stackTraceLimit; } } function addAdditionalPropertiesToJsonSchema2(jsonSchema22) { if (jsonSchema22.type === "object" || Array.isArray(jsonSchema22.type) && jsonSchema22.type.includes("object")) { jsonSchema22.additionalProperties = false; const { properties } = jsonSchema22; if (properties != null) { for (const key of Object.keys(properties)) { properties[key] = visit(properties[key]); } } } if (jsonSchema22.items != null) { jsonSchema22.items = Array.isArray(jsonSchema22.items) ? jsonSchema22.items.map(visit) : visit(jsonSchema22.items); } if (jsonSchema22.anyOf != null) { jsonSchema22.anyOf = jsonSchema22.anyOf.map(visit); } if (jsonSchema22.allOf != null) { jsonSchema22.allOf = jsonSchema22.allOf.map(visit); } if (jsonSchema22.oneOf != null) { jsonSchema22.oneOf = jsonSchema22.oneOf.map(visit); } const { definitions } = jsonSchema22; if (definitions != null) { for (const key of Object.keys(definitions)) { definitions[key] = visit(definitions[key]); } } return jsonSchema22; } function visit(def) { if (typeof def === "boolean") return def; return addAdditionalPropertiesToJsonSchema2(def); } var ignoreOverride2 = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions2 = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions2 = (options) => typeof options === "string" ? { ...defaultOptions2, name: options } : { ...defaultOptions2, ...options }; function parseAnyDef2() { return {}; } function parseArrayDef2(def, refs) { var _a23, _b23, _c; const res = { type: "array" }; if (((_a23 = def.type) == null ? void 0 : _a23._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef2(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef2(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseBooleanDef2() { return { type: "boolean" }; } function parseBrandedDef2(_def, refs) { return parseDef2(_def.type._def, refs); } var parseCatchDef2 = (def, refs) => { return parseDef2(def.innerType._def, refs); }; function parseDateDef2(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef2(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser2(def); } } var integerDateParser2 = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check of def.checks) { switch (check.kind) { case "min": res.minimum = check.value; break; case "max": res.maximum = check.value; break; } } return res; }; function parseDefaultDef2(_def, refs) { return { ...parseDef2(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef2(_def, refs) { return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs) : parseAnyDef2(); } function parseEnumDef2(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType2 = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef2(def, refs) { const allOf = [ parseDef2(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef2(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType2(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef2(def) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } var emojiRegex2 = void 0; var zodPatterns2 = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex2 === void 0) { emojiRegex2 = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex2; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef2(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat2(res, "email", check.message, refs); break; case "format:idn-email": addFormat2(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern2(res, zodPatterns2.email, check.message, refs); break; } break; case "url": addFormat2(res, "uri", check.message, refs); break; case "uuid": addFormat2(res, "uuid", check.message, refs); break; case "regex": addPattern2(res, check.regex, check.message, refs); break; case "cuid": addPattern2(res, zodPatterns2.cuid, check.message, refs); break; case "cuid2": addPattern2(res, zodPatterns2.cuid2, check.message, refs); break; case "startsWith": addPattern2( res, RegExp(`^${escapeLiteralCheckValue2(check.value, refs)}`), check.message, refs ); break; case "endsWith": addPattern2( res, RegExp(`${escapeLiteralCheckValue2(check.value, refs)}$`), check.message, refs ); break; case "datetime": addFormat2(res, "date-time", check.message, refs); break; case "date": addFormat2(res, "date", check.message, refs); break; case "time": addFormat2(res, "time", check.message, refs); break; case "duration": addFormat2(res, "duration", check.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "includes": { addPattern2( res, RegExp(escapeLiteralCheckValue2(check.value, refs)), check.message, refs ); break; } case "ip": { if (check.version !== "v6") { addFormat2(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat2(res, "ipv6", check.message, refs); } break; } case "base64url": addPattern2(res, zodPatterns2.base64url, check.message, refs); break; case "jwt": addPattern2(res, zodPatterns2.jwt, check.message, refs); break; case "cidr": { if (check.version !== "v6") { addPattern2(res, zodPatterns2.ipv4Cidr, check.message, refs); } if (check.version !== "v4") { addPattern2(res, zodPatterns2.ipv6Cidr, check.message, refs); } break; } case "emoji": addPattern2(res, zodPatterns2.emoji(), check.message, refs); break; case "ulid": { addPattern2(res, zodPatterns2.ulid, check.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat2(res, "binary", check.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern2(res, zodPatterns2.base64, check.message, refs); break; } } break; } case "nanoid": { addPattern2(res, zodPatterns2.nanoid, check.message, refs); } } } } return res; } function escapeLiteralCheckValue2(literal, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal) : literal; } var ALPHA_NUMERIC2 = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric2(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC2.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat2(schema, value, message, refs) { var _a23; if (schema.format || ((_a23 = schema.anyOf) == null ? void 0 : _a23.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern2(schema, regex, message, refs) { var _a23; if (schema.pattern || ((_a23 = schema.allOf) == null ? void 0 : _a23.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push({ pattern: stringifyRegExpWithFlags2(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { schema.pattern = stringifyRegExpWithFlags2(regex, refs); } } function stringifyRegExpWithFlags2(regex, refs) { var _a23; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? void 0 : _a23.match(/[a-z]/))) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } function parseRecordDef2(def, refs) { var _a23, _b23, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a23 = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a23 : refs.allowedAdditionalProperties }; if (((_b23 = def.keyType) == null ? void 0 : _b23._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type, ...keyType } = parseStringDef2(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type, ...keyType } = parseBrandedDef2( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef2(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef2(def, refs); } const keys = parseDef2(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef2(); const values = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef2(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef2(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from( new Set(actualValues.map((values) => typeof values)) ); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } function parseNeverDef2() { return { not: parseAnyDef2() }; } function parseNullDef2() { return { type: "null" }; } var primitiveMappings2 = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef2(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings2 && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings2[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce( (acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, [] ); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce( (acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, [] ) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce( (acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf2(def, refs); } var asAnyOf2 = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef2(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] }) ).filter( (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0) ); return anyOf.length ? { anyOf } : void 0; }; function parseNullableDef2(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings2[def.innerType._def.typeName], "null" ] }; } const base = parseDef2(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef2(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; break; case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseObjectDef2(def, refs) { const result = { type: "object", properties: {} }; const required = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional2(propDef); const parsedDef = parseDef2(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required.push(propName); } } if (required.length) { result.required = required; } const additionalProperties = decideAdditionalProperties2(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties2(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef2(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional2(schema) { try { return schema.isOptional(); } catch (e) { return true; } } var parseOptionalDef2 = (def, refs) => { var _a23; if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? void 0 : _a23.toString())) { return parseDef2(def.innerType._def, refs); } const innerSchema = parseDef2(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef2() }, innerSchema] } : parseAnyDef2(); }; var parsePipelineDef2 = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef2(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef2(def.out._def, refs); } const a = parseDef2(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef2(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef2(def, refs) { return parseDef2(def.type._def, refs); } function parseSetDef2(def, refs) { const items = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if (def.maxSize) { schema.maxItems = def.maxSize.value; } return schema; } function parseTupleDef2(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map( (x, i) => parseDef2(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ), additionalItems: parseDef2(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map( (x, i) => parseDef2(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ) }; } } function parseUndefinedDef2() { return { not: parseAnyDef2() }; } function parseUnknownDef2() { return parseAnyDef2(); } var parseReadonlyDef2 = (def, refs) => { return parseDef2(def.innerType._def, refs); }; var selectParser2 = (def, typeName, refs) => { switch (typeName) { case v3.ZodFirstPartyTypeKind.ZodString: return parseStringDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef2(def); case v3.ZodFirstPartyTypeKind.ZodObject: return parseObjectDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef2(def); case v3.ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef2(); case v3.ZodFirstPartyTypeKind.ZodDate: return parseDateDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef2(); case v3.ZodFirstPartyTypeKind.ZodNull: return parseNullDef2(); case v3.ZodFirstPartyTypeKind.ZodArray: return parseArrayDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodUnion: case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef2(def); case v3.ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef2(def); case v3.ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef2(def); case v3.ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodMap: return parseMapDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodSet: return parseSetDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case v3.ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodNaN: case v3.ZodFirstPartyTypeKind.ZodNever: return parseNeverDef2(); case v3.ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodAny: return parseAnyDef2(); case v3.ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef2(); case v3.ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef2(def, refs); case v3.ZodFirstPartyTypeKind.ZodFunction: case v3.ZodFirstPartyTypeKind.ZodVoid: case v3.ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; var getRelativePath2 = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; function parseDef2(def, refs, forceResolution = false) { var _a23; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a23 = refs.override) == null ? void 0 : _a23.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride2) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref2(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser2(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta2(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var get$ref2 = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath2(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn( `Recursive reference detected at ${refs.currentPath.join( "/" )}! Defaulting to any` ); return parseAnyDef2(); } return refs.$refStrategy === "seen" ? parseAnyDef2() : void 0; } } }; var addMeta2 = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; } return jsonSchema22; }; var getRefs2 = (options) => { const _options = getDefaultOptions2(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name23, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name23], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zod3ToJsonSchema = (schema, options) => { var _a23; const refs = getRefs2(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name33, schema2]) => { var _a33; return { ...acc, [name33]: (_a33 = parseDef2( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name33] }, true )) != null ? _a33 : parseAnyDef2() }; }, {} ) : void 0; const name23 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a23 = parseDef2( schema._def, name23 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name23] }, false )) != null ? _a23 : parseAnyDef2(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name23 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name23 ].join("/"), [refs.definitionPath]: { ...definitions, [name23]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var schemaSymbol2 = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema2(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema2(jsonSchema22, { validate } = {}) { return { [schemaSymbol2]: true, _type: void 0, // should never be used directly get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function isSchema2(value) { return typeof value === "object" && value !== null && schemaSymbol2 in value && value[schemaSymbol2] === true && "jsonSchema" in value && "validate" in value; } function asSchema2(schema) { return schema == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema2(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema2(schema) : standardSchema(schema) : schema(); } function standardSchema(standardSchema2) { return jsonSchema2( () => addAdditionalPropertiesToJsonSchema2( standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }) ), { validate: async (value) => { const result = await standardSchema2["~standard"].validate(value); return "value" in result ? { success: true, value: result.value } : { success: false, error: new TypeValidationError2({ value, cause: result.issues }) }; } } ); } function zod3Schema2(zodSchema22, options) { var _a23; const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false; return jsonSchema2( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod3ToJsonSchema(zodSchema22, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema22.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema2(zodSchema22, options) { var _a23; const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false; return jsonSchema2( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema2( z4__namespace.toJSONSchema(zodSchema22, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await z4__namespace.safeParseAsync(zodSchema22, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema2(zodSchema22) { return "_zod" in zodSchema22; } function zodSchema2(zodSchema22, options) { if (isZod4Schema2(zodSchema22)) { return zod4Schema2(zodSchema22, options); } else { return zod3Schema2(zodSchema22, options); } } async function validateTypes2({ value, schema, context }) { const result = await safeValidateTypes2({ value, schema, context }); if (!result.success) { throw TypeValidationError2.wrap({ value, cause: result.error, context }); } return result.value; } async function safeValidateTypes2({ value, schema, context }) { const actualSchema = asSchema2(schema); try { if (actualSchema.validate == null) { return { success: true, value, rawValue: value }; } const result = await actualSchema.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError2.wrap({ value, cause: result.error, context }), rawValue: value }; } catch (error) { return { success: false, error: TypeValidationError2.wrap({ value, cause: error, context }), rawValue: value }; } } async function parseJSON2({ text, schema }) { try { const value = secureJsonParse2(text); if (schema == null) { return value; } return validateTypes2({ value, schema }); } catch (error) { if (JSONParseError2.isInstance(error) || TypeValidationError2.isInstance(error)) { throw error; } throw new JSONParseError2({ text, cause: error }); } } async function safeParseJSON2({ text, schema }) { try { const value = secureJsonParse2(text); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes2({ value, schema }); } catch (error) { return { success: false, error: JSONParseError2.isInstance(error) ? error : new JSONParseError2({ text, cause: error }), rawValue: void 0 }; } } function isParsableJson2(input) { try { secureJsonParse2(input); return true; } catch (e) { return false; } } function parseJsonEventStream2({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON2({ text: data, schema })); } }) ); } async function parseProviderOptions2({ provider, providerOptions, schema }) { if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) { return void 0; } const parsedProviderOptions = await safeValidateTypes2({ value: providerOptions[provider], schema }); if (!parsedProviderOptions.success) { throw new InvalidArgumentError2({ argument: "providerOptions", message: `invalid ${provider} provider options`, cause: parsedProviderOptions.error }); } return parsedProviderOptions.value; } var getOriginalFetch22 = () => globalThis.fetch; var postJsonToApi2 = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi2({ url, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postFormDataToApi2 = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi2({ url, headers, body: { content: formData, values: Object.fromEntries(formData.entries()) }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi2 = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch22() }) => { try { const response = await fetch2(url, { method: "POST", headers: withUserAgentSuffix2( headers, `ai-sdk/provider-utils/${VERSION3}`, getRuntimeEnvironmentUserAgent2() ), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders2(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (isAbortError2(error) || APICallError2.isInstance(error)) { throw error; } throw new APICallError2({ message: "Failed to process error response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (error instanceof Error) { if (isAbortError2(error) || APICallError2.isInstance(error)) { throw error; } } throw new APICallError2({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } } catch (error) { throw handleFetchError2({ error, url, requestBodyValues: body.values }); } }; function tool2(tool22) { return tool22; } function createProviderToolFactory({ id, inputSchema }) { return ({ execute, outputSchema, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool2({ type: "provider", id, args, inputSchema, outputSchema, execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema, supportsDeferredResults }) { return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool2({ type: "provider", id, args, inputSchema, outputSchema, execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, supportsDeferredResults }); } async function resolve2(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler2 = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); const responseHeaders = extractResponseHeaders2(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError2({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON2({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError2({ message: errorToMessage(parsedError), url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError2({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler2 = (chunkSchema2) => async ({ response }) => { const responseHeaders = extractResponseHeaders2(response); if (response.body == null) { throw new EmptyResponseBodyError2({}); } return { responseHeaders, value: parseJsonEventStream2({ stream: response.body, schema: chunkSchema2 }) }; }; var createJsonResponseHandler2 = (responseSchema2) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON2({ text: responseBody, schema: responseSchema2 }); const responseHeaders = extractResponseHeaders2(response); if (!parsedResult.success) { throw new APICallError2({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var createBinaryResponseHandler2 = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders2(response); if (!response.body) { throw new APICallError2({ message: "Response body is empty", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0 }); } try { const buffer = await response.arrayBuffer(); return { responseHeaders, value: new Uint8Array(buffer) }; } catch (error) { throw new APICallError2({ message: "Failed to read response as array buffer", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0, cause: error }); } }; var createStatusCodeErrorResponseHandler2 = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders2(response); const responseBody = await response.text(); return { responseHeaders, value: new APICallError2({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody }) }; }; function withoutTrailingSlash2(url) { return url == null ? void 0 : url.replace(/\/$/, ""); } var openaiErrorDataSchema = z4.z.object({ error: z4.z.object({ message: z4.z.string(), // The additional information below is handled loosely to support // OpenAI-compatible providers that have slightly different error // responses: type: z4.z.string().nullish(), param: z4.z.any().nullish(), code: z4.z.union([z4.z.string(), z4.z.number()]).nullish() }) }); var openaiFailedResponseHandler = createJsonErrorResponseHandler2({ errorSchema: openaiErrorDataSchema, errorToMessage: (data) => data.error.message }); function getOpenAILanguageModelCapabilities(modelId) { const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"); const supportsPriorityProcessing = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") && !modelId.startsWith("gpt-5.4-nano") || modelId.startsWith("o3") || modelId.startsWith("o4-mini"); const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"); const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2") || modelId.startsWith("gpt-5.3") || modelId.startsWith("gpt-5.4") || modelId.startsWith("gpt-5.5"); const systemMessageMode = isReasoningModel ? "developer" : "system"; return { supportsFlexProcessing, supportsPriorityProcessing, isReasoningModel, systemMessageMode, supportsNonReasoningParameters }; } function convertOpenAIChatUsage(usage) { var _a18, _b18, _c, _d, _e, _f; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const promptTokens = (_a18 = usage.prompt_tokens) != null ? _a18 : 0; const completionTokens = (_b18 = usage.completion_tokens) != null ? _b18 : 0; const cachedTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0; const reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0; return { inputTokens: { total: promptTokens, noCache: promptTokens - cachedTokens, cacheRead: cachedTokens, cacheWrite: void 0 }, outputTokens: { total: completionTokens, text: completionTokens - reasoningTokens, reasoning: reasoningTokens }, raw: usage }; } function serializeToolCallArguments(input) { return JSON.stringify(input === void 0 ? {} : input); } function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) { var _a18; const messages = []; const warnings = []; for (const { role, content } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { messages.push({ role: "system", content }); break; } case "developer": { messages.push({ role: "developer", content }); break; } case "remove": { warnings.push({ type: "other", message: "system messages are removed for this model" }); break; } default: { const _exhaustiveCheck = systemMessageMode; throw new Error( `Unsupported system message mode: ${_exhaustiveCheck}` ); } } break; } case "user": { if (content.length === 1 && content[0].type === "text") { messages.push({ role: "user", content: content[0].text }); break; } messages.push({ role: "user", content: content.map((part, index) => { var _a23, _b18, _c; switch (part.type) { case "text": { return { type: "text", text: part.text }; } case "file": { if (part.mediaType.startsWith("image/")) { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; return { type: "image_url", image_url: { url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase642(part.data)}`, // OpenAI specific extension: image detail detail: (_b18 = (_a23 = part.providerOptions) == null ? void 0 : _a23.openai) == null ? void 0 : _b18.imageDetail } }; } else if (part.mediaType.startsWith("audio/")) { if (part.data instanceof URL) { throw new UnsupportedFunctionalityError2({ functionality: "audio file parts with URLs" }); } switch (part.mediaType) { case "audio/wav": { return { type: "input_audio", input_audio: { data: convertToBase642(part.data), format: "wav" } }; } case "audio/mp3": case "audio/mpeg": { return { type: "input_audio", input_audio: { data: convertToBase642(part.data), format: "mp3" } }; } default: { throw new UnsupportedFunctionalityError2({ functionality: `audio content parts with media type ${part.mediaType}` }); } } } else if (part.mediaType === "application/pdf") { if (part.data instanceof URL) { throw new UnsupportedFunctionalityError2({ functionality: "PDF file parts with URLs" }); } return { type: "file", file: typeof part.data === "string" && part.data.startsWith("file-") ? { file_id: part.data } : { filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`, file_data: `data:application/pdf;base64,${convertToBase642(part.data)}` } }; } else { throw new UnsupportedFunctionalityError2({ functionality: `file part media type ${part.mediaType}` }); } } } }) }); break; } case "assistant": { let text = ""; const toolCalls = []; for (const part of content) { switch (part.type) { case "text": { text += part.text; break; } case "tool-call": { toolCalls.push({ id: part.toolCallId, type: "function", function: { name: part.toolName, arguments: serializeToolCallArguments(part.input) } }); break; } } } messages.push({ role: "assistant", content: toolCalls.length > 0 ? text || null : text, tool_calls: toolCalls.length > 0 ? toolCalls : void 0 }); break; } case "tool": { for (const toolResponse of content) { if (toolResponse.type === "tool-approval-response") { continue; } const output = toolResponse.output; let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "execution-denied": contentValue = (_a18 = output.reason) != null ? _a18 : "Tool execution denied."; break; case "content": case "json": case "error-json": contentValue = JSON.stringify(output.value); break; } messages.push({ role: "tool", tool_call_id: toolResponse.toolCallId, content: contentValue }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return { messages, warnings }; } function getResponseMetadata3({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created ? new Date(created * 1e3) : void 0 }; } function mapOpenAIFinishReason(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "other"; } } var openaiChatResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ message: z4.z.object({ role: z4.z.literal("assistant").nullish(), content: z4.z.string().nullish(), tool_calls: z4.z.array( z4.z.object({ id: z4.z.string().nullish(), type: z4.z.literal("function"), function: z4.z.object({ name: z4.z.string(), arguments: z4.z.string() }) }) ).nullish(), annotations: z4.z.array( z4.z.object({ type: z4.z.literal("url_citation"), url_citation: z4.z.object({ start_index: z4.z.number(), end_index: z4.z.number(), url: z4.z.string(), title: z4.z.string() }) }) ).nullish() }), index: z4.z.number(), logprobs: z4.z.object({ content: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number(), top_logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number() }) ) }) ).nullish() }).nullish(), finish_reason: z4.z.string().nullish() }) ), usage: z4.z.object({ prompt_tokens: z4.z.number().nullish(), completion_tokens: z4.z.number().nullish(), total_tokens: z4.z.number().nullish(), prompt_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), completion_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish(), accepted_prediction_tokens: z4.z.number().nullish(), rejected_prediction_tokens: z4.z.number().nullish() }).nullish() }).nullish() }) ) ); var openaiChatChunkSchema = lazySchema2( () => zodSchema2( z4.z.union([ z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ delta: z4.z.object({ role: z4.z.enum(["assistant"]).nullish(), content: z4.z.string().nullish(), tool_calls: z4.z.array( z4.z.object({ index: z4.z.number(), id: z4.z.string().nullish(), type: z4.z.literal("function").nullish(), function: z4.z.object({ name: z4.z.string().nullish(), arguments: z4.z.string().nullish() }) }) ).nullish(), annotations: z4.z.array( z4.z.object({ type: z4.z.literal("url_citation"), url_citation: z4.z.object({ start_index: z4.z.number(), end_index: z4.z.number(), url: z4.z.string(), title: z4.z.string() }) }) ).nullish() }).nullish(), logprobs: z4.z.object({ content: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number(), top_logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number() }) ) }) ).nullish() }).nullish(), finish_reason: z4.z.string().nullish(), index: z4.z.number() }) ), usage: z4.z.object({ prompt_tokens: z4.z.number().nullish(), completion_tokens: z4.z.number().nullish(), total_tokens: z4.z.number().nullish(), prompt_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), completion_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish(), accepted_prediction_tokens: z4.z.number().nullish(), rejected_prediction_tokens: z4.z.number().nullish() }).nullish() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiLanguageModelChatOptions = lazySchema2( () => zodSchema2( z4.z.object({ /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. */ logitBias: z4.z.record(z4.z.coerce.number(), z4.z.number()).optional(), /** * Return the log probabilities of the tokens. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. */ logprobs: z4.z.union([z4.z.boolean(), z4.z.number()]).optional(), /** * Whether to enable parallel function calling during tool use. Default to true. */ parallelToolCalls: z4.z.boolean().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. */ user: z4.z.string().optional(), /** * Reasoning effort for reasoning models. Defaults to `medium`. */ reasoningEffort: z4.z.enum(["none", "minimal", "low", "medium", "high", "xhigh"]).optional(), /** * Maximum number of completion tokens to generate. Useful for reasoning models. */ maxCompletionTokens: z4.z.number().optional(), /** * Whether to enable persistence in responses API. */ store: z4.z.boolean().optional(), /** * Metadata to associate with the request. */ metadata: z4.z.record(z4.z.string().max(64), z4.z.string().max(512)).optional(), /** * Parameters for prediction mode. */ prediction: z4.z.record(z4.z.string(), z4.z.any()).optional(), /** * Service tier for the request. * - 'auto': Default service tier. The request will be processed with the service tier configured in the * Project settings. Unless otherwise configured, the Project will use 'default'. * - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models. * - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers. * - 'default': The request will be processed with the standard pricing and performance for the selected model. * * @default 'auto' */ serviceTier: z4.z.enum(["auto", "flex", "priority", "default"]).optional(), /** * Whether to use strict JSON schema validation. * * @default true */ strictJsonSchema: z4.z.boolean().optional(), /** * Controls the verbosity of the model's responses. * Lower values will result in more concise responses, while higher values will result in more verbose responses. */ textVerbosity: z4.z.enum(["low", "medium", "high"]).optional(), /** * A cache key for prompt caching. Allows manual control over prompt caching behavior. * Useful for improving cache hit rates and working around automatic caching issues. */ promptCacheKey: z4.z.string().optional(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Currently only available for 5.1 series models. * * @default 'in_memory' */ promptCacheRetention: z4.z.enum(["in_memory", "24h"]).optional(), /** * A stable identifier used to help detect users of your application * that may be violating OpenAI's usage policies. The IDs should be a * string that uniquely identifies each user. We recommend hashing their * username or email address, in order to avoid sending us any identifying * information. */ safetyIdentifier: z4.z.string().optional(), /** * Override the system message mode for this model. * - 'system': Use the 'system' role for system messages (default for most models) * - 'developer': Use the 'developer' role for system messages (used by reasoning models) * - 'remove': Remove system messages entirely * * If not specified, the mode is automatically determined based on the model. */ systemMessageMode: z4.z.enum(["system", "developer", "remove"]).optional(), /** * Force treating this model as a reasoning model. * * This is useful for "stealth" reasoning models (e.g. via a custom baseURL) * where the model ID is not recognized by the SDK's allowlist. * * When enabled, the SDK applies reasoning-model parameter compatibility rules * and defaults `systemMessageMode` to `developer` unless overridden. */ forceReasoning: z4.z.boolean().optional() }) ) ); function prepareChatTools({ tools, toolChoice }) { tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; for (const tool3 of tools) { switch (tool3.type) { case "function": openaiTools2.push({ type: "function", function: { name: tool3.name, description: tool3.description, parameters: tool3.inputSchema, ...tool3.strict != null ? { strict: tool3.strict } : {} } }); break; default: toolWarnings.push({ type: "unsupported", feature: `tool type: ${tool3.type}` }); break; } } if (toolChoice == null) { return { tools: openaiTools2, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": case "required": return { tools: openaiTools2, toolChoice: type, toolWarnings }; case "tool": return { tools: openaiTools2, toolChoice: { type: "function", function: { name: toolChoice.toolName } }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError2({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } var OpenAIChatLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) { var _a18, _b18, _c, _d, _e; const warnings = []; const openaiOptions = (_a18 = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiLanguageModelChatOptions })) != null ? _a18 : {}; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); const isReasoningModel = (_b18 = openaiOptions.forceReasoning) != null ? _b18 : modelCapabilities.isReasoningModel; if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages( { prompt, systemMessageMode: (_c = openaiOptions.systemMessageMode) != null ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode } ); warnings.push(...messageWarnings); const strictJsonSchema = (_d = openaiOptions.strictJsonSchema) != null ? _d : true; const baseArgs = { // model id: model: this.modelId, // model specific settings: logit_bias: openaiOptions.logitBias, logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0, top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0, user: openaiOptions.user, parallel_tool_calls: openaiOptions.parallelToolCalls, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? { type: "json_schema", json_schema: { schema: responseFormat.schema, strict: strictJsonSchema, name: (_e = responseFormat.name) != null ? _e : "response", description: responseFormat.description } } : { type: "json_object" } : void 0, stop: stopSequences, seed, verbosity: openaiOptions.textVerbosity, // openai specific settings: // TODO AI SDK 6: remove, we auto-map maxOutputTokens now max_completion_tokens: openaiOptions.maxCompletionTokens, store: openaiOptions.store, metadata: openaiOptions.metadata, prediction: openaiOptions.prediction, reasoning_effort: openaiOptions.reasoningEffort, service_tier: openaiOptions.serviceTier, prompt_cache_key: openaiOptions.promptCacheKey, prompt_cache_retention: openaiOptions.promptCacheRetention, safety_identifier: openaiOptions.safetyIdentifier, // messages: messages }; if (isReasoningModel) { if (openaiOptions.reasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported", feature: "topP", details: "topP is not supported for reasoning models" }); } if (baseArgs.logprobs != null) { baseArgs.logprobs = void 0; warnings.push({ type: "other", message: "logprobs is not supported for reasoning models" }); } } if (baseArgs.frequency_penalty != null) { baseArgs.frequency_penalty = void 0; warnings.push({ type: "unsupported", feature: "frequencyPenalty", details: "frequencyPenalty is not supported for reasoning models" }); } if (baseArgs.presence_penalty != null) { baseArgs.presence_penalty = void 0; warnings.push({ type: "unsupported", feature: "presencePenalty", details: "presencePenalty is not supported for reasoning models" }); } if (baseArgs.logit_bias != null) { baseArgs.logit_bias = void 0; warnings.push({ type: "other", message: "logitBias is not supported for reasoning models" }); } if (baseArgs.top_logprobs != null) { baseArgs.top_logprobs = void 0; warnings.push({ type: "other", message: "topLogprobs is not supported for reasoning models" }); } if (baseArgs.max_tokens != null) { if (baseArgs.max_completion_tokens == null) { baseArgs.max_completion_tokens = baseArgs.max_tokens; } baseArgs.max_tokens = void 0; } } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported for the search preview models and has been removed." }); } } if (openaiOptions.serviceTier === "flex" && !modelCapabilities.supportsFlexProcessing) { warnings.push({ type: "unsupported", feature: "serviceTier", details: "flex processing is only available for o3, o4-mini, and gpt-5 models" }); baseArgs.service_tier = void 0; } if (openaiOptions.serviceTier === "priority" && !modelCapabilities.supportsPriorityProcessing) { warnings.push({ type: "unsupported", feature: "serviceTier", details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" }); baseArgs.service_tier = void 0; } const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({ tools, toolChoice }); return { args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a18, _b18, _c, _d, _f, _g; const { args: body, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi2({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiChatResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const content = []; const text = choice.message.content; if (text != null && text.length > 0) { content.push({ type: "text", text }); } for (const toolCall of (_a18 = choice.message.tool_calls) != null ? _a18 : []) { content.push({ type: "tool-call", toolCallId: (_b18 = toolCall.id) != null ? _b18 : generateId2(), toolName: toolCall.function.name, input: toolCall.function.arguments }); } for (const annotation of (_c = choice.message.annotations) != null ? _c : []) { content.push({ type: "source", sourceType: "url", id: generateId2(), url: annotation.url_citation.url, title: annotation.url_citation.title }); } const completionTokenDetails = (_d = response.usage) == null ? void 0 : _d.completion_tokens_details; const providerMetadata = { openai: {} }; if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; } if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; } if (((_f = choice.logprobs) == null ? void 0 : _f.content) != null) { providerMetadata.openai.logprobs = choice.logprobs.content; } return { content, finishReason: { unified: mapOpenAIFinishReason(choice.finish_reason), raw: (_g = choice.finish_reason) != null ? _g : void 0 }, usage: convertOpenAIChatUsage(response.usage), request: { body }, response: { ...getResponseMetadata3(response), headers: responseHeaders, body: rawResponse }, warnings, providerMetadata }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const { responseHeaders, value: response } = await postJsonToApi2({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2( openaiChatChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const toolCalls = []; let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; let metadataExtracted = false; let isActiveText = false; const providerMetadata = { openai: {} }; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if ("error" in value) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: value.error }); return; } if (!metadataExtracted) { const metadata = getResponseMetadata3(value); if (Object.values(metadata).some(Boolean)) { metadataExtracted = true; controller.enqueue({ type: "response-metadata", ...getResponseMetadata3(value) }); } } if (value.usage != null) { usage = value.usage; if (((_a18 = value.usage.completion_tokens_details) == null ? void 0 : _a18.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = (_b18 = value.usage.completion_tokens_details) == null ? void 0 : _b18.accepted_prediction_tokens; } if (((_c = value.usage.completion_tokens_details) == null ? void 0 : _c.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens; } } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = { unified: mapOpenAIFinishReason(choice.finish_reason), raw: choice.finish_reason }; } if (((_e = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _e.content) != null) { providerMetadata.openai.logprobs = choice.logprobs.content; } if ((choice == null ? void 0 : choice.delta) == null) { return; } const delta = choice.delta; if (delta.content != null) { if (!isActiveText) { controller.enqueue({ type: "text-start", id: "0" }); isActiveText = true; } controller.enqueue({ type: "text-delta", id: "0", delta: delta.content }); } if (delta.tool_calls != null) { for (const toolCallDelta of delta.tool_calls) { const index = toolCallDelta.index; if (toolCalls[index] == null) { if (toolCallDelta.type != null && toolCallDelta.type !== "function") { throw new InvalidResponseDataError2({ data: toolCallDelta, message: `Expected 'function' type.` }); } if (toolCallDelta.id == null) { throw new InvalidResponseDataError2({ data: toolCallDelta, message: `Expected 'id' to be a string.` }); } if (((_f = toolCallDelta.function) == null ? void 0 : _f.name) == null) { throw new InvalidResponseDataError2({ data: toolCallDelta, message: `Expected 'function.name' to be a string.` }); } controller.enqueue({ type: "tool-input-start", id: toolCallDelta.id, toolName: toolCallDelta.function.name }); toolCalls[index] = { id: toolCallDelta.id, type: "function", function: { name: toolCallDelta.function.name, arguments: (_g = toolCallDelta.function.arguments) != null ? _g : "" }, hasFinished: false }; const toolCall2 = toolCalls[index]; if (((_h = toolCall2.function) == null ? void 0 : _h.name) != null && ((_i = toolCall2.function) == null ? void 0 : _i.arguments) != null) { if (toolCall2.function.arguments.length > 0) { controller.enqueue({ type: "tool-input-delta", id: toolCall2.id, delta: toolCall2.function.arguments }); } if (isParsableJson2(toolCall2.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall2.id }); controller.enqueue({ type: "tool-call", toolCallId: (_j = toolCall2.id) != null ? _j : generateId2(), toolName: toolCall2.function.name, input: toolCall2.function.arguments }); toolCall2.hasFinished = true; } } continue; } const toolCall = toolCalls[index]; if (toolCall.hasFinished) { continue; } if (((_k = toolCallDelta.function) == null ? void 0 : _k.arguments) != null) { toolCall.function.arguments += (_m = (_l = toolCallDelta.function) == null ? void 0 : _l.arguments) != null ? _m : ""; } controller.enqueue({ type: "tool-input-delta", id: toolCall.id, delta: (_n = toolCallDelta.function.arguments) != null ? _n : "" }); if (((_o = toolCall.function) == null ? void 0 : _o.name) != null && ((_p = toolCall.function) == null ? void 0 : _p.arguments) != null && isParsableJson2(toolCall.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall.id }); controller.enqueue({ type: "tool-call", toolCallId: (_q = toolCall.id) != null ? _q : generateId2(), toolName: toolCall.function.name, input: toolCall.function.arguments }); toolCall.hasFinished = true; } } } if (delta.annotations != null) { for (const annotation of delta.annotations) { controller.enqueue({ type: "source", sourceType: "url", id: generateId2(), url: annotation.url_citation.url, title: annotation.url_citation.title }); } } }, flush(controller) { if (isActiveText) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, usage: convertOpenAIChatUsage(usage), ...providerMetadata != null ? { providerMetadata } : {} }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; function convertOpenAICompletionUsage(usage) { var _a18, _b18, _c, _d; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const promptTokens = (_a18 = usage.prompt_tokens) != null ? _a18 : 0; const completionTokens = (_b18 = usage.completion_tokens) != null ? _b18 : 0; return { inputTokens: { total: (_c = usage.prompt_tokens) != null ? _c : void 0, noCache: promptTokens, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: (_d = usage.completion_tokens) != null ? _d : void 0, text: completionTokens, reasoning: void 0 }, raw: usage }; } function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) { let text = ""; if (prompt[0].role === "system") { text += `${prompt[0].content} `; prompt = prompt.slice(1); } for (const { role, content } of prompt) { switch (role) { case "system": { throw new InvalidPromptError2({ message: "Unexpected system message in prompt: ${content}", prompt }); } case "user": { const userMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } } }).filter(Boolean).join(""); text += `${user}: ${userMessage} `; break; } case "assistant": { const assistantMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } case "tool-call": { throw new UnsupportedFunctionalityError2({ functionality: "tool-call messages" }); } } }).join(""); text += `${assistant}: ${assistantMessage} `; break; } case "tool": { throw new UnsupportedFunctionalityError2({ functionality: "tool messages" }); } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } text += `${assistant}: `; return { prompt: text, stopSequences: [` ${user}:`] }; } function getResponseMetadata22({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : void 0 }; } function mapOpenAIFinishReason2(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "other"; } } var openaiCompletionResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ text: z4.z.string(), finish_reason: z4.z.string(), logprobs: z4.z.object({ tokens: z4.z.array(z4.z.string()), token_logprobs: z4.z.array(z4.z.number()), top_logprobs: z4.z.array(z4.z.record(z4.z.string(), z4.z.number())).nullish() }).nullish() }) ), usage: z4.z.object({ prompt_tokens: z4.z.number(), completion_tokens: z4.z.number(), total_tokens: z4.z.number() }).nullish() }) ) ); var openaiCompletionChunkSchema = lazySchema2( () => zodSchema2( z4.z.union([ z4.z.object({ id: z4.z.string().nullish(), created: z4.z.number().nullish(), model: z4.z.string().nullish(), choices: z4.z.array( z4.z.object({ text: z4.z.string(), finish_reason: z4.z.string().nullish(), index: z4.z.number(), logprobs: z4.z.object({ tokens: z4.z.array(z4.z.string()), token_logprobs: z4.z.array(z4.z.number()), top_logprobs: z4.z.array(z4.z.record(z4.z.string(), z4.z.number())).nullish() }).nullish() }) ), usage: z4.z.object({ prompt_tokens: z4.z.number(), completion_tokens: z4.z.number(), total_tokens: z4.z.number() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiLanguageModelCompletionOptions = lazySchema2( () => zodSchema2( z4.z.object({ /** * Echo back the prompt in addition to the completion. */ echo: z4.z.boolean().optional(), /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. You * can use this tokenizer tool to convert text to token IDs. Mathematically, * the bias is added to the logits generated by the model prior to sampling. * The exact effect will vary per model, but values between -1 and 1 should * decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. * * As an example, you can pass {"50256": -100} to prevent the <|endoftext|> * token from being generated. */ logitBias: z4.z.record(z4.z.string(), z4.z.number()).optional(), /** * The suffix that comes after a completion of inserted text. */ suffix: z4.z.string().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. Learn more. */ user: z4.z.string().optional(), /** * Return the log probabilities of the tokens. Including logprobs will increase * the response size and can slow down response times. However, it can * be useful to better understand how the model is behaving. * Setting to true will return the log probabilities of the tokens that * were generated. * Setting to a number will return the log probabilities of the top n * tokens that were generated. */ logprobs: z4.z.union([z4.z.boolean(), z4.z.number()]).optional() }) ) ); var OpenAICompletionLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; this.supportedUrls = { // No URLs are supported for completion models. }; this.modelId = modelId; this.config = config; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools, toolChoice, seed, providerOptions }) { const warnings = []; const openaiOptions = { ...await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiLanguageModelCompletionOptions }), ...await parseProviderOptions2({ provider: this.providerOptionsName, providerOptions, schema: openaiLanguageModelCompletionOptions }) }; if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } if (tools == null ? void 0 : tools.length) { warnings.push({ type: "unsupported", feature: "tools" }); } if (toolChoice != null) { warnings.push({ type: "unsupported", feature: "toolChoice" }); } if (responseFormat != null && responseFormat.type !== "text") { warnings.push({ type: "unsupported", feature: "responseFormat", details: "JSON response format is not supported." }); } const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt }); const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; return { args: { // model id: model: this.modelId, // model specific settings: echo: openaiOptions.echo, logit_bias: openaiOptions.logitBias, logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs, suffix: openaiOptions.suffix, user: openaiOptions.user, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, seed, // prompt: prompt: completionPrompt, // stop sequences: stop: stop.length > 0 ? stop : void 0 }, warnings }; } async doGenerate(options) { var _a18; const { args, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi2({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body: args, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiCompletionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const providerMetadata = { openai: {} }; if (choice.logprobs != null) { providerMetadata.openai.logprobs = choice.logprobs; } return { content: [{ type: "text", text: choice.text }], usage: convertOpenAICompletionUsage(response.usage), finishReason: { unified: mapOpenAIFinishReason2(choice.finish_reason), raw: (_a18 = choice.finish_reason) != null ? _a18 : void 0 }, request: { body: args }, response: { ...getResponseMetadata22(response), headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const { responseHeaders, value: response } = await postJsonToApi2({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2( openaiCompletionChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = { unified: "other", raw: void 0 }; const providerMetadata = { openai: {} }; let usage = void 0; let isFirstChunk = true; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if ("error" in value) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: value.error }); return; } if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata22(value) }); controller.enqueue({ type: "text-start", id: "0" }); } if (value.usage != null) { usage = value.usage; } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = { unified: mapOpenAIFinishReason2(choice.finish_reason), raw: choice.finish_reason }; } if ((choice == null ? void 0 : choice.logprobs) != null) { providerMetadata.openai.logprobs = choice.logprobs; } if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) { controller.enqueue({ type: "text-delta", id: "0", delta: choice.text }); } }, flush(controller) { if (!isFirstChunk) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, providerMetadata, usage: convertOpenAICompletionUsage(usage) }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; var openaiEmbeddingModelOptions = lazySchema2( () => zodSchema2( z4.z.object({ /** * The number of dimensions the resulting output embeddings should have. * Only supported in text-embedding-3 and later models. */ dimensions: z4.z.number().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. Learn more. */ user: z4.z.string().optional() }) ) ); var openaiTextEmbeddingResponseSchema2 = lazySchema2( () => zodSchema2( z4.z.object({ data: z4.z.array(z4.z.object({ embedding: z4.z.array(z4.z.number()) })), usage: z4.z.object({ prompt_tokens: z4.z.number() }).nullish() }) ) ); var OpenAIEmbeddingModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a18; if (values.length > this.maxEmbeddingsPerCall) { throw new TooManyEmbeddingValuesForCallError2({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const openaiOptions = (_a18 = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiEmbeddingModelOptions })) != null ? _a18 : {}; const { responseHeaders, value: response, rawValue } = await postJsonToApi2({ url: this.config.url({ path: "/embeddings", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), headers), body: { model: this.modelId, input: values, encoding_format: "float", dimensions: openaiOptions.dimensions, user: openaiOptions.user }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiTextEmbeddingResponseSchema2 ), abortSignal, fetch: this.config.fetch }); return { warnings: [], embeddings: response.data.map((item) => item.embedding), usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, response: { headers: responseHeaders, body: rawValue } }; } }; var openaiImageResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ created: z4.z.number().nullish(), data: z4.z.array( z4.z.object({ b64_json: z4.z.string(), revised_prompt: z4.z.string().nullish() }) ), background: z4.z.string().nullish(), output_format: z4.z.string().nullish(), size: z4.z.string().nullish(), quality: z4.z.string().nullish(), usage: z4.z.object({ input_tokens: z4.z.number().nullish(), output_tokens: z4.z.number().nullish(), total_tokens: z4.z.number().nullish(), input_tokens_details: z4.z.object({ image_tokens: z4.z.number().nullish(), text_tokens: z4.z.number().nullish() }).nullish() }).nullish() }) ) ); var modelMaxImagesPerCall = { "dall-e-3": 1, "dall-e-2": 10, "gpt-image-1": 10, "gpt-image-1-mini": 10, "gpt-image-1.5": 10, "gpt-image-2": 10, "chatgpt-image-latest": 10 }; var defaultResponseFormatPrefixes = [ "chatgpt-image-", "gpt-image-1-mini", "gpt-image-1.5", "gpt-image-1", "gpt-image-2" ]; function hasDefaultResponseFormat(modelId) { return defaultResponseFormatPrefixes.some( (prefix) => modelId.startsWith(prefix) ); } var baseImageModelOptionsObject = z4.z.object({ /** * Quality of the generated image(s). * * Valid values: `standard`, `hd`, `low`, `medium`, `high`, `auto`. */ quality: z4.z.enum(["standard", "hd", "low", "medium", "high", "auto"]).optional(), /** * Background behavior for the generated image(s). * * If `transparent`, the output format must support transparency * (i.e. `png` or `webp`). */ background: z4.z.enum(["transparent", "opaque", "auto"]).optional(), /** * Format in which the generated image(s) are returned. */ outputFormat: z4.z.enum(["png", "jpeg", "webp"]).optional(), /** * Compression level (0-100) for the generated image(s). Applies to the * `jpeg` and `webp` output formats. */ outputCompression: z4.z.number().int().min(0).max(100).optional(), /** * A unique identifier representing your end-user, which can help OpenAI * to monitor and detect abuse. */ user: z4.z.string().optional() }); var openaiImageModelGenerationOptions = lazySchema2( () => zodSchema2( baseImageModelOptionsObject.extend({ /** * Style of the generated image. `vivid` produces hyper-real and * dramatic images; `natural` produces more subdued, less hyper-real * looking images. */ style: z4.z.enum(["vivid", "natural"]).optional(), /** * Content moderation level for the generated image(s). `low` applies * less restrictive filtering. */ moderation: z4.z.enum(["auto", "low"]).optional() }) ) ); var openaiImageModelEditOptions = lazySchema2( () => zodSchema2( baseImageModelOptionsObject.extend({ /** * Fidelity of the output image(s) to the input image(s). */ inputFidelity: z4.z.enum(["high", "low"]).optional() }) ) ); var OpenAIImageModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v3"; } get maxImagesPerCall() { var _a18; return (_a18 = modelMaxImagesPerCall[this.modelId]) != null ? _a18 : 1; } get provider() { return this.config.provider; } async doGenerate({ prompt, files, mask, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k; const warnings = []; if (aspectRatio != null) { warnings.push({ type: "unsupported", feature: "aspectRatio", details: "This model does not support aspect ratio. Use `size` instead." }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed" }); } const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); if (files != null) { const openaiOptions2 = (_d = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiImageModelEditOptions })) != null ? _d : {}; const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi2({ url: this.config.url({ path: "/images/edits", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), headers), formData: convertToFormData({ model: this.modelId, prompt, image: await Promise.all( files.map( (file) => file.type === "file" ? new Blob( [ file.data instanceof Uint8Array ? new Blob([file.data], { type: file.mediaType }) : new Blob([convertBase64ToUint8Array2(file.data)], { type: file.mediaType }) ], { type: file.mediaType } ) : downloadBlob(file.url) ) ), mask: mask != null ? await fileToBlob(mask) : void 0, n, size, quality: openaiOptions2.quality, background: openaiOptions2.background, output_format: openaiOptions2.outputFormat, output_compression: openaiOptions2.outputCompression, input_fidelity: openaiOptions2.inputFidelity, user: openaiOptions2.user }), failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response2.data.map((item) => item.b64_json), warnings, usage: response2.usage != null ? { inputTokens: (_e = response2.usage.input_tokens) != null ? _e : void 0, outputTokens: (_f = response2.usage.output_tokens) != null ? _f : void 0, totalTokens: (_g = response2.usage.total_tokens) != null ? _g : void 0 } : void 0, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders2 }, providerMetadata: { openai: { images: response2.data.map((item, index) => { var _a23, _b23, _c2, _d2, _e2, _f2; return { ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}, created: (_a23 = response2.created) != null ? _a23 : void 0, size: (_b23 = response2.size) != null ? _b23 : void 0, quality: (_c2 = response2.quality) != null ? _c2 : void 0, background: (_d2 = response2.background) != null ? _d2 : void 0, outputFormat: (_e2 = response2.output_format) != null ? _e2 : void 0, ...distributeTokenDetails( (_f2 = response2.usage) == null ? void 0 : _f2.input_tokens_details, index, response2.data.length ) }; }) } } }; } const openaiOptions = (_h = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiImageModelGenerationOptions })) != null ? _h : {}; const { value: response, responseHeaders } = await postJsonToApi2({ url: this.config.url({ path: "/images/generations", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), headers), body: { model: this.modelId, prompt, n, size, quality: openaiOptions.quality, style: openaiOptions.style, background: openaiOptions.background, moderation: openaiOptions.moderation, output_format: openaiOptions.outputFormat, output_compression: openaiOptions.outputCompression, user: openaiOptions.user, ...!hasDefaultResponseFormat(this.modelId) ? { response_format: "b64_json" } : {} }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response.data.map((item) => item.b64_json), warnings, usage: response.usage != null ? { inputTokens: (_i = response.usage.input_tokens) != null ? _i : void 0, outputTokens: (_j = response.usage.output_tokens) != null ? _j : void 0, totalTokens: (_k = response.usage.total_tokens) != null ? _k : void 0 } : void 0, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders }, providerMetadata: { openai: { images: response.data.map((item, index) => { var _a23, _b23, _c2, _d2, _e2, _f2; return { ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}, created: (_a23 = response.created) != null ? _a23 : void 0, size: (_b23 = response.size) != null ? _b23 : void 0, quality: (_c2 = response.quality) != null ? _c2 : void 0, background: (_d2 = response.background) != null ? _d2 : void 0, outputFormat: (_e2 = response.output_format) != null ? _e2 : void 0, ...distributeTokenDetails( (_f2 = response.usage) == null ? void 0 : _f2.input_tokens_details, index, response.data.length ) }; }) } } }; } }; function distributeTokenDetails(details, index, total) { if (details == null) { return {}; } const result = {}; if (details.image_tokens != null) { const base = Math.floor(details.image_tokens / total); const remainder = details.image_tokens - base * (total - 1); result.imageTokens = index === total - 1 ? remainder : base; } if (details.text_tokens != null) { const base = Math.floor(details.text_tokens / total); const remainder = details.text_tokens - base * (total - 1); result.textTokens = index === total - 1 ? remainder : base; } return result; } async function fileToBlob(file) { if (!file) return void 0; if (file.type === "url") { return downloadBlob(file.url); } const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array2(file.data); return new Blob([data], { type: file.mediaType }); } var applyPatchInputSchema = lazySchema2( () => zodSchema2( z4.z.object({ callId: z4.z.string(), operation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("create_file"), path: z4.z.string(), diff: z4.z.string() }), z4.z.object({ type: z4.z.literal("delete_file"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("update_file"), path: z4.z.string(), diff: z4.z.string() }) ]) }) ) ); var applyPatchOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ status: z4.z.enum(["completed", "failed"]), output: z4.z.string().optional() }) ) ); var applyPatchToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.apply_patch", inputSchema: applyPatchInputSchema, outputSchema: applyPatchOutputSchema }); var applyPatch = applyPatchToolFactory; var codeInterpreterInputSchema = lazySchema2( () => zodSchema2( z4.z.object({ code: z4.z.string().nullish(), containerId: z4.z.string() }) ) ); var codeInterpreterOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ outputs: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("logs"), logs: z4.z.string() }), z4.z.object({ type: z4.z.literal("image"), url: z4.z.string() }) ]) ).nullish() }) ) ); var codeInterpreterArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ container: z4.z.union([ z4.z.string(), z4.z.object({ fileIds: z4.z.array(z4.z.string()).optional() }) ]).optional() }) ) ); var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.code_interpreter", inputSchema: codeInterpreterInputSchema, outputSchema: codeInterpreterOutputSchema }); var codeInterpreter = (args = {}) => { return codeInterpreterToolFactory(args); }; var customArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ name: z4.z.string(), description: z4.z.string().optional(), format: z4.z.union([ z4.z.object({ type: z4.z.literal("grammar"), syntax: z4.z.enum(["regex", "lark"]), definition: z4.z.string() }), z4.z.object({ type: z4.z.literal("text") }) ]).optional() }) ) ); var customInputSchema = lazySchema2(() => zodSchema2(z4.z.string())); var customToolFactory = createProviderToolFactory({ id: "openai.custom", inputSchema: customInputSchema }); var customTool = (args) => customToolFactory(args); var comparisonFilterSchema = z4.z.object({ key: z4.z.string(), type: z4.z.enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]), value: z4.z.union([z4.z.string(), z4.z.number(), z4.z.boolean(), z4.z.array(z4.z.string())]) }); var compoundFilterSchema = z4.z.object({ type: z4.z.enum(["and", "or"]), filters: z4.z.array( z4.z.union([comparisonFilterSchema, z4.z.lazy(() => compoundFilterSchema)]) ) }); var fileSearchArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ vectorStoreIds: z4.z.array(z4.z.string()), maxNumResults: z4.z.number().optional(), ranking: z4.z.object({ ranker: z4.z.string().optional(), scoreThreshold: z4.z.number().optional() }).optional(), filters: z4.z.union([comparisonFilterSchema, compoundFilterSchema]).optional() }) ) ); var fileSearchOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ queries: z4.z.array(z4.z.string()), results: z4.z.array( z4.z.object({ attributes: z4.z.record(z4.z.string(), z4.z.unknown()), fileId: z4.z.string(), filename: z4.z.string(), score: z4.z.number(), text: z4.z.string() }) ).nullable() }) ) ); var fileSearch = createProviderToolFactoryWithOutputSchema({ id: "openai.file_search", inputSchema: z4.z.object({}), outputSchema: fileSearchOutputSchema }); var imageGenerationArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ background: z4.z.enum(["auto", "opaque", "transparent"]).optional(), inputFidelity: z4.z.enum(["low", "high"]).optional(), inputImageMask: z4.z.object({ fileId: z4.z.string().optional(), imageUrl: z4.z.string().optional() }).optional(), model: z4.z.string().optional(), moderation: z4.z.enum(["auto"]).optional(), outputCompression: z4.z.number().int().min(0).max(100).optional(), outputFormat: z4.z.enum(["png", "jpeg", "webp"]).optional(), partialImages: z4.z.number().int().min(0).max(3).optional(), quality: z4.z.enum(["auto", "low", "medium", "high"]).optional(), size: z4.z.enum(["1024x1024", "1024x1536", "1536x1024", "auto"]).optional() }).strict() ) ); var imageGenerationInputSchema = lazySchema2(() => zodSchema2(z4.z.object({}))); var imageGenerationOutputSchema = lazySchema2( () => zodSchema2(z4.z.object({ result: z4.z.string() })) ); var imageGenerationToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.image_generation", inputSchema: imageGenerationInputSchema, outputSchema: imageGenerationOutputSchema }); var imageGeneration = (args = {}) => { return imageGenerationToolFactory(args); }; var localShellInputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.object({ type: z4.z.literal("exec"), command: z4.z.array(z4.z.string()), timeoutMs: z4.z.number().optional(), user: z4.z.string().optional(), workingDirectory: z4.z.string().optional(), env: z4.z.record(z4.z.string(), z4.z.string()).optional() }) }) ) ); var localShellOutputSchema = lazySchema2( () => zodSchema2(z4.z.object({ output: z4.z.string() })) ); var localShell = createProviderToolFactoryWithOutputSchema({ id: "openai.local_shell", inputSchema: localShellInputSchema, outputSchema: localShellOutputSchema }); var shellInputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.object({ commands: z4.z.array(z4.z.string()), timeoutMs: z4.z.number().optional(), maxOutputLength: z4.z.number().optional() }) }) ) ); var shellOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ output: z4.z.array( z4.z.object({ stdout: z4.z.string(), stderr: z4.z.string(), outcome: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("timeout") }), z4.z.object({ type: z4.z.literal("exit"), exitCode: z4.z.number() }) ]) }) ) }) ) ); var shellSkillsSchema = z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("skillReference"), skillId: z4.z.string(), version: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("inline"), name: z4.z.string(), description: z4.z.string(), source: z4.z.object({ type: z4.z.literal("base64"), mediaType: z4.z.literal("application/zip"), data: z4.z.string() }) }) ]) ).optional(); var shellArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ environment: z4.z.union([ z4.z.object({ type: z4.z.literal("containerAuto"), fileIds: z4.z.array(z4.z.string()).optional(), memoryLimit: z4.z.enum(["1g", "4g", "16g", "64g"]).optional(), networkPolicy: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("disabled") }), z4.z.object({ type: z4.z.literal("allowlist"), allowedDomains: z4.z.array(z4.z.string()), domainSecrets: z4.z.array( z4.z.object({ domain: z4.z.string(), name: z4.z.string(), value: z4.z.string() }) ).optional() }) ]).optional(), skills: shellSkillsSchema }), z4.z.object({ type: z4.z.literal("containerReference"), containerId: z4.z.string() }), z4.z.object({ type: z4.z.literal("local").optional(), skills: z4.z.array( z4.z.object({ name: z4.z.string(), description: z4.z.string(), path: z4.z.string() }) ).optional() }) ]).optional() }) ) ); var shell = createProviderToolFactoryWithOutputSchema({ id: "openai.shell", inputSchema: shellInputSchema, outputSchema: shellOutputSchema }); var toolSearchArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ execution: z4.z.enum(["server", "client"]).optional(), description: z4.z.string().optional(), parameters: z4.z.record(z4.z.string(), z4.z.unknown()).optional() }) ) ); var toolSearchInputSchema = lazySchema2( () => zodSchema2( z4.z.object({ arguments: z4.z.unknown().optional(), call_id: z4.z.string().nullish() }) ) ); var toolSearchOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ tools: z4.z.array(z4.z.record(z4.z.string(), z4.z.unknown())) }) ) ); var toolSearchToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.tool_search", inputSchema: toolSearchInputSchema, outputSchema: toolSearchOutputSchema }); var toolSearch = (args = {}) => toolSearchToolFactory(args); var webSearchArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ externalWebAccess: z4.z.boolean().optional(), filters: z4.z.object({ allowedDomains: z4.z.array(z4.z.string()).optional() }).optional(), searchContextSize: z4.z.enum(["low", "medium", "high"]).optional(), userLocation: z4.z.object({ type: z4.z.literal("approximate"), country: z4.z.string().optional(), city: z4.z.string().optional(), region: z4.z.string().optional(), timezone: z4.z.string().optional() }).optional() }) ) ); var webSearchInputSchema = lazySchema2(() => zodSchema2(z4.z.object({}))); var webSearchOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("search"), query: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("openPage"), url: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("findInPage"), url: z4.z.string().nullish(), pattern: z4.z.string().nullish() }) ]).optional(), sources: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("url"), url: z4.z.string() }), z4.z.object({ type: z4.z.literal("api"), name: z4.z.string() }) ]) ).optional() }) ) ); var webSearchToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.web_search", inputSchema: webSearchInputSchema, outputSchema: webSearchOutputSchema }); var webSearch = (args = {}) => webSearchToolFactory(args); var webSearchPreviewArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ searchContextSize: z4.z.enum(["low", "medium", "high"]).optional(), userLocation: z4.z.object({ type: z4.z.literal("approximate"), country: z4.z.string().optional(), city: z4.z.string().optional(), region: z4.z.string().optional(), timezone: z4.z.string().optional() }).optional() }) ) ); var webSearchPreviewInputSchema = lazySchema2( () => zodSchema2(z4.z.object({})) ); var webSearchPreviewOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("search"), query: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("openPage"), url: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("findInPage"), url: z4.z.string().nullish(), pattern: z4.z.string().nullish() }) ]).optional() }) ) ); var webSearchPreview = createProviderToolFactoryWithOutputSchema({ id: "openai.web_search_preview", inputSchema: webSearchPreviewInputSchema, outputSchema: webSearchPreviewOutputSchema }); var jsonValueSchema = z4.z.lazy( () => z4.z.union([ z4.z.string(), z4.z.number(), z4.z.boolean(), z4.z.null(), z4.z.array(jsonValueSchema), z4.z.record(z4.z.string(), jsonValueSchema) ]) ); var mcpArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ serverLabel: z4.z.string(), allowedTools: z4.z.union([ z4.z.array(z4.z.string()), z4.z.object({ readOnly: z4.z.boolean().optional(), toolNames: z4.z.array(z4.z.string()).optional() }) ]).optional(), authorization: z4.z.string().optional(), connectorId: z4.z.string().optional(), headers: z4.z.record(z4.z.string(), z4.z.string()).optional(), requireApproval: z4.z.union([ z4.z.enum(["always", "never"]), z4.z.object({ never: z4.z.object({ toolNames: z4.z.array(z4.z.string()).optional() }).optional() }) ]).optional(), serverDescription: z4.z.string().optional(), serverUrl: z4.z.string().optional() }).refine( (v) => v.serverUrl != null || v.connectorId != null, "One of serverUrl or connectorId must be provided." ) ) ); var mcpInputSchema = lazySchema2(() => zodSchema2(z4.z.object({}))); var mcpOutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("call"), serverLabel: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), output: z4.z.string().nullish(), error: z4.z.union([z4.z.string(), jsonValueSchema]).optional() }) ) ); var mcpToolFactory = createProviderToolFactoryWithOutputSchema({ id: "openai.mcp", inputSchema: mcpInputSchema, outputSchema: mcpOutputSchema }); var mcp = (args) => mcpToolFactory(args); var openaiTools = { /** * The apply_patch tool lets GPT-5.1 create, update, and delete files in your * codebase using structured diffs. Instead of just suggesting edits, the model * emits patch operations that your application applies and then reports back on, * enabling iterative, multi-step code editing workflows. * */ applyPatch, /** * Custom tools let callers constrain model output to a grammar (regex or * Lark syntax). The model returns a `custom_tool_call` output item whose * `input` field is a string matching the specified grammar. * * @param name - The name of the custom tool. * @param description - An optional description of the tool. * @param format - The output format constraint (grammar type, syntax, and definition). */ customTool, /** * The Code Interpreter tool allows models to write and run Python code in a * sandboxed environment to solve complex problems in domains like data analysis, * coding, and math. * * @param container - The container to use for the code interpreter. */ codeInterpreter, /** * File search is a tool available in the Responses API. It enables models to * retrieve information in a knowledge base of previously uploaded files through * semantic and keyword search. * * @param vectorStoreIds - The vector store IDs to use for the file search. * @param maxNumResults - The maximum number of results to return. * @param ranking - The ranking options to use for the file search. * @param filters - The filters to use for the file search. */ fileSearch, /** * The image generation tool allows you to generate images using a text prompt, * and optionally image inputs. It leverages the GPT Image model, * and automatically optimizes text inputs for improved performance. * * @param background - Background type for the generated image. One of 'auto', 'opaque', or 'transparent'. * @param inputFidelity - Input fidelity for the generated image. One of 'low' or 'high'. * @param inputImageMask - Optional mask for inpainting. Contains fileId and/or imageUrl. * @param model - The image generation model to use. Default: gpt-image-1. * @param moderation - Moderation level for the generated image. Default: 'auto'. * @param outputCompression - Compression level for the output image (0-100). * @param outputFormat - The output format of the generated image. One of 'png', 'jpeg', or 'webp'. * @param partialImages - Number of partial images to generate in streaming mode (0-3). * @param quality - The quality of the generated image. One of 'auto', 'low', 'medium', or 'high'. * @param size - The size of the generated image. One of 'auto', '1024x1024', '1024x1536', or '1536x1024'. */ imageGeneration, /** * Local shell is a tool that allows agents to run shell commands locally * on a machine you or the user provides. * * Supported models: `gpt-5-codex` */ localShell, /** * The shell tool allows the model to interact with your local computer through * a controlled command-line interface. The model proposes shell commands; your * integration executes them and returns the outputs. * * Available through the Responses API for use with GPT-5.1. * * WARNING: Running arbitrary shell commands can be dangerous. Always sandbox * execution or add strict allow-/deny-lists before forwarding a command to * the system shell. */ shell, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. */ webSearchPreview, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * @param filters - The filters to use for the web search. * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. */ webSearch, /** * MCP (Model Context Protocol) allows models to call tools exposed by * remote MCP servers or service connectors. * * @param serverLabel - Label to identify the MCP server. * @param allowedTools - Allowed tool names or filter object. * @param authorization - OAuth access token for the MCP server/connector. * @param connectorId - Identifier for a service connector. * @param headers - Optional headers to include in MCP requests. * // param requireApproval - Approval policy ('always'|'never'|filter object). (Removed - always 'never') * @param serverDescription - Optional description of the server. * @param serverUrl - URL for the MCP server. */ mcp, /** * Tool search allows the model to dynamically search for and load deferred * tools into the model's context as needed. This helps reduce overall token * usage, cost, and latency by only loading tools when the model needs them. * * To use tool search, mark functions or namespaces with `defer_loading: true` * in the tools array. The model will use tool search to load these tools * when it determines they are needed. */ toolSearch }; function convertOpenAIResponsesUsage(usage) { var _a18, _b18, _c, _d; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const inputTokens = usage.input_tokens; const outputTokens = usage.output_tokens; const cachedTokens = (_b18 = (_a18 = usage.input_tokens_details) == null ? void 0 : _a18.cached_tokens) != null ? _b18 : 0; const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0; return { inputTokens: { total: inputTokens, noCache: inputTokens - cachedTokens, cacheRead: cachedTokens, cacheWrite: void 0 }, outputTokens: { total: outputTokens, text: outputTokens - reasoningTokens, reasoning: reasoningTokens }, raw: usage }; } function serializeToolCallArguments2(input) { return JSON.stringify(input === void 0 ? {} : input); } function isFileId(data, prefixes) { if (!prefixes) return false; return prefixes.some((prefix) => data.startsWith(prefix)); } async function convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode, providerOptionsName, fileIdPrefixes, store, hasConversation = false, hasLocalShellTool = false, hasShellTool = false, hasApplyPatchTool = false, customProviderToolNames }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; let input = []; const warnings = []; const processedApprovalIds = /* @__PURE__ */ new Set(); for (const { role, content } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { input.push({ role: "system", content }); break; } case "developer": { input.push({ role: "developer", content }); break; } case "remove": { warnings.push({ type: "other", message: "system messages are removed for this model" }); break; } default: { const _exhaustiveCheck = systemMessageMode; throw new Error( `Unsupported system message mode: ${_exhaustiveCheck}` ); } } break; } case "user": { input.push({ role: "user", content: content.map((part, index) => { var _a23, _b23, _c2; switch (part.type) { case "text": { return { type: "input_text", text: part.text }; } case "file": { if (part.mediaType.startsWith("image/")) { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; return { type: "input_image", ...part.data instanceof URL ? { image_url: part.data.toString() } : typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { image_url: `data:${mediaType};base64,${convertToBase642(part.data)}` }, detail: (_b23 = (_a23 = part.providerOptions) == null ? void 0 : _a23[providerOptionsName]) == null ? void 0 : _b23.imageDetail }; } else if (part.mediaType === "application/pdf") { if (part.data instanceof URL) { return { type: "input_file", file_url: part.data.toString() }; } return { type: "input_file", ...typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { filename: (_c2 = part.filename) != null ? _c2 : `part-${index}.pdf`, file_data: `data:application/pdf;base64,${convertToBase642(part.data)}` } }; } else { throw new UnsupportedFunctionalityError2({ functionality: `file part media type ${part.mediaType}` }); } } } }) }); break; } case "assistant": { const reasoningMessages = {}; for (const part of content) { switch (part.type) { case "text": { const providerOpts = (_a18 = part.providerOptions) == null ? void 0 : _a18[providerOptionsName]; const id = providerOpts == null ? void 0 : providerOpts.itemId; const phase = providerOpts == null ? void 0 : providerOpts.phase; if (hasConversation && id != null) { break; } if (store && id != null) { input.push({ type: "item_reference", id }); break; } input.push({ role: "assistant", content: [{ type: "output_text", text: part.text }], id, ...phase != null && { phase } }); break; } case "tool-call": { const id = (_f = (_c = (_b18 = part.providerOptions) == null ? void 0 : _b18[providerOptionsName]) == null ? void 0 : _c.itemId) != null ? _f : (_e = (_d = part.providerMetadata) == null ? void 0 : _d[providerOptionsName]) == null ? void 0 : _e.itemId; if (hasConversation && id != null) { break; } const resolvedToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedToolName === "tool_search") { if (store && id != null) { input.push({ type: "item_reference", id }); break; } const parsedInput = typeof part.input === "string" ? await parseJSON2({ text: part.input, schema: toolSearchInputSchema }) : await validateTypes2({ value: part.input, schema: toolSearchInputSchema }); const execution = parsedInput.call_id != null ? "client" : "server"; input.push({ type: "tool_search_call", id: id != null ? id : part.toolCallId, execution, call_id: (_g = parsedInput.call_id) != null ? _g : null, status: "completed", arguments: parsedInput.arguments }); break; } if (part.providerExecuted) { if (store && id != null) { input.push({ type: "item_reference", id }); } break; } if (store && id != null) { input.push({ type: "item_reference", id }); break; } if (hasLocalShellTool && resolvedToolName === "local_shell") { const parsedInput = await validateTypes2({ value: part.input, schema: localShellInputSchema }); input.push({ type: "local_shell_call", call_id: part.toolCallId, id, action: { type: "exec", command: parsedInput.action.command, timeout_ms: parsedInput.action.timeoutMs, user: parsedInput.action.user, working_directory: parsedInput.action.workingDirectory, env: parsedInput.action.env } }); break; } if (hasShellTool && resolvedToolName === "shell") { const parsedInput = await validateTypes2({ value: part.input, schema: shellInputSchema }); input.push({ type: "shell_call", call_id: part.toolCallId, id, status: "completed", action: { commands: parsedInput.action.commands, timeout_ms: parsedInput.action.timeoutMs, max_output_length: parsedInput.action.maxOutputLength } }); break; } if (hasApplyPatchTool && resolvedToolName === "apply_patch") { const parsedInput = await validateTypes2({ value: part.input, schema: applyPatchInputSchema }); input.push({ type: "apply_patch_call", call_id: parsedInput.callId, id, status: "completed", operation: parsedInput.operation }); break; } if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) { input.push({ type: "custom_tool_call", call_id: part.toolCallId, name: resolvedToolName, input: typeof part.input === "string" ? part.input : JSON.stringify(part.input), id }); break; } input.push({ type: "function_call", call_id: part.toolCallId, name: resolvedToolName, arguments: serializeToolCallArguments2(part.input), id }); break; } // assistant tool result parts are from provider-executed tools: case "tool-result": { if (part.output.type === "execution-denied" || part.output.type === "json" && typeof part.output.value === "object" && part.output.value != null && "type" in part.output.value && part.output.value.type === "execution-denied") { break; } if (hasConversation) { break; } const resolvedResultToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedResultToolName === "tool_search") { const itemId = (_j = (_i = (_h = part.providerOptions) == null ? void 0 : _h[providerOptionsName]) == null ? void 0 : _i.itemId) != null ? _j : part.toolCallId; if (store) { input.push({ type: "item_reference", id: itemId }); } else if (part.output.type === "json") { const parsedOutput = await validateTypes2({ value: part.output.value, schema: toolSearchOutputSchema }); input.push({ type: "tool_search_output", id: itemId, execution: "server", call_id: null, status: "completed", tools: parsedOutput.tools }); } break; } if (hasShellTool && resolvedResultToolName === "shell") { if (part.output.type === "json") { const parsedOutput = await validateTypes2({ value: part.output.value, schema: shellOutputSchema }); input.push({ type: "shell_call_output", call_id: part.toolCallId, output: parsedOutput.output.map((item) => ({ stdout: item.stdout, stderr: item.stderr, outcome: item.outcome.type === "timeout" ? { type: "timeout" } : { type: "exit", exit_code: item.outcome.exitCode } })) }); } break; } if (store) { const itemId = (_m = (_l = (_k = part.providerOptions) == null ? void 0 : _k[providerOptionsName]) == null ? void 0 : _l.itemId) != null ? _m : part.toolCallId; input.push({ type: "item_reference", id: itemId }); } else { warnings.push({ type: "other", message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false` }); } break; } case "reasoning": { const providerOptions = await parseProviderOptions2({ provider: providerOptionsName, providerOptions: part.providerOptions, schema: openaiResponsesReasoningProviderOptionsSchema }); const reasoningId = providerOptions == null ? void 0 : providerOptions.itemId; if (hasConversation && reasoningId != null) { break; } if (reasoningId != null) { const reasoningMessage = reasoningMessages[reasoningId]; if (store) { if (reasoningMessage === void 0) { input.push({ type: "item_reference", id: reasoningId }); reasoningMessages[reasoningId] = { type: "reasoning", id: reasoningId, summary: [] }; } } else { const summaryParts = []; if (part.text.length > 0) { summaryParts.push({ type: "summary_text", text: part.text }); } else if (reasoningMessage !== void 0) { warnings.push({ type: "other", message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.` }); } if (reasoningMessage === void 0) { reasoningMessages[reasoningId] = { type: "reasoning", id: reasoningId, encrypted_content: providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent, summary: summaryParts }; input.push(reasoningMessages[reasoningId]); } else { reasoningMessage.summary.push(...summaryParts); if ((providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent) != null) { reasoningMessage.encrypted_content = providerOptions.reasoningEncryptedContent; } } } } else { const encryptedContent = providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent; if (encryptedContent != null) { const summaryParts = []; if (part.text.length > 0) { summaryParts.push({ type: "summary_text", text: part.text }); } input.push({ type: "reasoning", encrypted_content: encryptedContent, summary: summaryParts }); } else { warnings.push({ type: "other", message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.` }); } } break; } } } break; } case "tool": { for (const part of content) { if (part.type === "tool-approval-response") { const approvalResponse = part; if (processedApprovalIds.has(approvalResponse.approvalId)) { continue; } processedApprovalIds.add(approvalResponse.approvalId); if (store) { input.push({ type: "item_reference", id: approvalResponse.approvalId }); } input.push({ type: "mcp_approval_response", approval_request_id: approvalResponse.approvalId, approve: approvalResponse.approved }); continue; } const output = part.output; if (output.type === "execution-denied") { const approvalId = (_o = (_n = output.providerOptions) == null ? void 0 : _n.openai) == null ? void 0 : _o.approvalId; if (approvalId) { continue; } } const resolvedToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedToolName === "tool_search" && output.type === "json") { const parsedOutput = await validateTypes2({ value: output.value, schema: toolSearchOutputSchema }); input.push({ type: "tool_search_output", execution: "client", call_id: part.toolCallId, status: "completed", tools: parsedOutput.tools }); continue; } if (hasLocalShellTool && resolvedToolName === "local_shell" && output.type === "json") { const parsedOutput = await validateTypes2({ value: output.value, schema: localShellOutputSchema }); input.push({ type: "local_shell_call_output", call_id: part.toolCallId, output: parsedOutput.output }); continue; } if (hasShellTool && resolvedToolName === "shell" && output.type === "json") { const parsedOutput = await validateTypes2({ value: output.value, schema: shellOutputSchema }); input.push({ type: "shell_call_output", call_id: part.toolCallId, output: parsedOutput.output.map((item) => ({ stdout: item.stdout, stderr: item.stderr, outcome: item.outcome.type === "timeout" ? { type: "timeout" } : { type: "exit", exit_code: item.outcome.exitCode } })) }); continue; } if (hasApplyPatchTool && part.toolName === "apply_patch" && output.type === "json") { const parsedOutput = await validateTypes2({ value: output.value, schema: applyPatchOutputSchema }); input.push({ type: "apply_patch_call_output", call_id: part.toolCallId, status: parsedOutput.status, output: parsedOutput.output }); continue; } if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) { let outputValue; switch (output.type) { case "text": case "error-text": outputValue = output.value; break; case "execution-denied": outputValue = (_p = output.reason) != null ? _p : "Tool execution denied."; break; case "json": case "error-json": outputValue = JSON.stringify(output.value); break; case "content": outputValue = output.value.map((item) => { var _a23, _b23, _c2, _d2, _e2; switch (item.type) { case "text": return { type: "input_text", text: item.text }; case "image-data": return { type: "input_image", image_url: `data:${item.mediaType};base64,${item.data}`, detail: (_b23 = (_a23 = item.providerOptions) == null ? void 0 : _a23[providerOptionsName]) == null ? void 0 : _b23.imageDetail }; case "image-url": return { type: "input_image", image_url: item.url, detail: (_d2 = (_c2 = item.providerOptions) == null ? void 0 : _c2[providerOptionsName]) == null ? void 0 : _d2.imageDetail }; case "file-data": return { type: "input_file", filename: (_e2 = item.filename) != null ? _e2 : "data", file_data: `data:${item.mediaType};base64,${item.data}` }; case "file-url": return { type: "input_file", file_url: item.url }; default: warnings.push({ type: "other", message: `unsupported custom tool content part type: ${item.type}` }); return void 0; } }).filter(isNonNullable); break; default: outputValue = ""; } input.push({ type: "custom_tool_call_output", call_id: part.toolCallId, output: outputValue }); continue; } let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "execution-denied": contentValue = (_q = output.reason) != null ? _q : "Tool execution denied."; break; case "json": case "error-json": contentValue = JSON.stringify(output.value); break; case "content": contentValue = output.value.map((item) => { var _a23, _b23, _c2, _d2, _e2; switch (item.type) { case "text": { return { type: "input_text", text: item.text }; } case "image-data": { return { type: "input_image", image_url: `data:${item.mediaType};base64,${item.data}`, detail: (_b23 = (_a23 = item.providerOptions) == null ? void 0 : _a23[providerOptionsName]) == null ? void 0 : _b23.imageDetail }; } case "image-url": { return { type: "input_image", image_url: item.url, detail: (_d2 = (_c2 = item.providerOptions) == null ? void 0 : _c2[providerOptionsName]) == null ? void 0 : _d2.imageDetail }; } case "file-data": { return { type: "input_file", filename: (_e2 = item.filename) != null ? _e2 : "data", file_data: `data:${item.mediaType};base64,${item.data}` }; } case "file-url": { return { type: "input_file", file_url: item.url }; } default: { warnings.push({ type: "other", message: `unsupported tool content part type: ${item.type}` }); return void 0; } } }).filter(isNonNullable); break; } input.push({ type: "function_call_output", call_id: part.toolCallId, output: contentValue }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } if (!store && input.some( (item) => "type" in item && item.type === "reasoning" && item.encrypted_content == null )) { warnings.push({ type: "other", message: "Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts." }); input = input.filter( (item) => !("type" in item) || item.type !== "reasoning" || item.encrypted_content != null ); } return { input, warnings }; } var openaiResponsesReasoningProviderOptionsSchema = z4.z.object({ itemId: z4.z.string().nullish(), reasoningEncryptedContent: z4.z.string().nullish() }); function mapOpenAIResponseFinishReason({ finishReason, hasFunctionCall }) { switch (finishReason) { case void 0: case null: return hasFunctionCall ? "tool-calls" : "stop"; case "max_output_tokens": return "length"; case "content_filter": return "content-filter"; default: return hasFunctionCall ? "tool-calls" : "other"; } } var jsonValueSchema2 = z4.z.lazy( () => z4.z.union([ z4.z.string(), z4.z.number(), z4.z.boolean(), z4.z.null(), z4.z.array(jsonValueSchema2), z4.z.record(z4.z.string(), jsonValueSchema2.optional()) ]) ); var openaiResponsesChunkSchema = lazySchema2( () => zodSchema2( z4.z.union([ z4.z.object({ type: z4.z.literal("response.output_text.delta"), item_id: z4.z.string(), delta: z4.z.string(), logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number(), top_logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number() }) ) }) ).nullish() }), z4.z.object({ type: z4.z.enum(["response.completed", "response.incomplete"]), response: z4.z.object({ incomplete_details: z4.z.object({ reason: z4.z.string() }).nullish(), usage: z4.z.object({ input_tokens: z4.z.number(), input_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), output_tokens: z4.z.number(), output_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish() }).nullish() }), service_tier: z4.z.string().nullish() }) }), z4.z.object({ type: z4.z.literal("response.failed"), response: z4.z.object({ error: z4.z.object({ code: z4.z.string().nullish(), message: z4.z.string() }).nullish(), incomplete_details: z4.z.object({ reason: z4.z.string() }).nullish(), usage: z4.z.object({ input_tokens: z4.z.number(), input_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), output_tokens: z4.z.number(), output_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish() }).nullish() }).nullish(), service_tier: z4.z.string().nullish() }) }), z4.z.object({ type: z4.z.literal("response.created"), response: z4.z.object({ id: z4.z.string(), created_at: z4.z.number(), model: z4.z.string(), service_tier: z4.z.string().nullish() }) }), z4.z.object({ type: z4.z.literal("response.output_item.added"), output_index: z4.z.number(), item: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("message"), id: z4.z.string(), phase: z4.z.enum(["commentary", "final_answer"]).nullish() }), z4.z.object({ type: z4.z.literal("reasoning"), id: z4.z.string(), encrypted_content: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("function_call"), id: z4.z.string(), call_id: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), namespace: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("web_search_call"), id: z4.z.string(), status: z4.z.string() }), z4.z.object({ type: z4.z.literal("computer_call"), id: z4.z.string(), status: z4.z.string() }), z4.z.object({ type: z4.z.literal("file_search_call"), id: z4.z.string() }), z4.z.object({ type: z4.z.literal("image_generation_call"), id: z4.z.string() }), z4.z.object({ type: z4.z.literal("code_interpreter_call"), id: z4.z.string(), container_id: z4.z.string(), code: z4.z.string().nullable(), outputs: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("logs"), logs: z4.z.string() }), z4.z.object({ type: z4.z.literal("image"), url: z4.z.string() }) ]) ).nullable(), status: z4.z.string() }), z4.z.object({ type: z4.z.literal("mcp_call"), id: z4.z.string(), status: z4.z.string(), approval_request_id: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("mcp_list_tools"), id: z4.z.string() }), z4.z.object({ type: z4.z.literal("mcp_approval_request"), id: z4.z.string() }), z4.z.object({ type: z4.z.literal("apply_patch_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed"]), operation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("create_file"), path: z4.z.string(), diff: z4.z.string() }), z4.z.object({ type: z4.z.literal("delete_file"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("update_file"), path: z4.z.string(), diff: z4.z.string() }) ]) }), z4.z.object({ type: z4.z.literal("custom_tool_call"), id: z4.z.string(), call_id: z4.z.string(), name: z4.z.string(), input: z4.z.string() }), z4.z.object({ type: z4.z.literal("shell_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), action: z4.z.object({ commands: z4.z.array(z4.z.string()) }) }), z4.z.object({ type: z4.z.literal("shell_call_output"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), output: z4.z.array( z4.z.object({ stdout: z4.z.string(), stderr: z4.z.string(), outcome: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("timeout") }), z4.z.object({ type: z4.z.literal("exit"), exit_code: z4.z.number() }) ]) }) ) }), z4.z.object({ type: z4.z.literal("tool_search_call"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), arguments: z4.z.unknown() }), z4.z.object({ type: z4.z.literal("tool_search_output"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), tools: z4.z.array(z4.z.record(z4.z.string(), jsonValueSchema2.optional())) }) ]) }), z4.z.object({ type: z4.z.literal("response.output_item.done"), output_index: z4.z.number(), item: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("message"), id: z4.z.string(), phase: z4.z.enum(["commentary", "final_answer"]).nullish() }), z4.z.object({ type: z4.z.literal("reasoning"), id: z4.z.string(), encrypted_content: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("function_call"), id: z4.z.string(), call_id: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), status: z4.z.literal("completed"), namespace: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("custom_tool_call"), id: z4.z.string(), call_id: z4.z.string(), name: z4.z.string(), input: z4.z.string(), status: z4.z.literal("completed") }), z4.z.object({ type: z4.z.literal("code_interpreter_call"), id: z4.z.string(), code: z4.z.string().nullable(), container_id: z4.z.string(), outputs: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("logs"), logs: z4.z.string() }), z4.z.object({ type: z4.z.literal("image"), url: z4.z.string() }) ]) ).nullable() }), z4.z.object({ type: z4.z.literal("image_generation_call"), id: z4.z.string(), result: z4.z.string() }), z4.z.object({ type: z4.z.literal("web_search_call"), id: z4.z.string(), status: z4.z.string(), action: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("search"), query: z4.z.string().nullish(), sources: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("url"), url: z4.z.string() }), z4.z.object({ type: z4.z.literal("api"), name: z4.z.string() }) ]) ).nullish() }), z4.z.object({ type: z4.z.literal("open_page"), url: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("find_in_page"), url: z4.z.string().nullish(), pattern: z4.z.string().nullish() }) ]).nullish() }), z4.z.object({ type: z4.z.literal("file_search_call"), id: z4.z.string(), queries: z4.z.array(z4.z.string()), results: z4.z.array( z4.z.object({ attributes: z4.z.record( z4.z.string(), z4.z.union([z4.z.string(), z4.z.number(), z4.z.boolean()]) ), file_id: z4.z.string(), filename: z4.z.string(), score: z4.z.number(), text: z4.z.string() }) ).nullish() }), z4.z.object({ type: z4.z.literal("local_shell_call"), id: z4.z.string(), call_id: z4.z.string(), action: z4.z.object({ type: z4.z.literal("exec"), command: z4.z.array(z4.z.string()), timeout_ms: z4.z.number().optional(), user: z4.z.string().optional(), working_directory: z4.z.string().optional(), env: z4.z.record(z4.z.string(), z4.z.string()).optional() }) }), z4.z.object({ type: z4.z.literal("computer_call"), id: z4.z.string(), status: z4.z.literal("completed") }), z4.z.object({ type: z4.z.literal("mcp_call"), id: z4.z.string(), status: z4.z.string(), arguments: z4.z.string(), name: z4.z.string(), server_label: z4.z.string(), output: z4.z.string().nullish(), error: z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.string().optional(), code: z4.z.union([z4.z.number(), z4.z.string()]).optional(), message: z4.z.string().optional() }).loose() ]).nullish(), approval_request_id: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("mcp_list_tools"), id: z4.z.string(), server_label: z4.z.string(), tools: z4.z.array( z4.z.object({ name: z4.z.string(), description: z4.z.string().optional(), input_schema: z4.z.any(), annotations: z4.z.record(z4.z.string(), z4.z.unknown()).optional() }) ), error: z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.string().optional(), code: z4.z.union([z4.z.number(), z4.z.string()]).optional(), message: z4.z.string().optional() }).loose() ]).optional() }), z4.z.object({ type: z4.z.literal("mcp_approval_request"), id: z4.z.string(), server_label: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), approval_request_id: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("apply_patch_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed"]), operation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("create_file"), path: z4.z.string(), diff: z4.z.string() }), z4.z.object({ type: z4.z.literal("delete_file"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("update_file"), path: z4.z.string(), diff: z4.z.string() }) ]) }), z4.z.object({ type: z4.z.literal("shell_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), action: z4.z.object({ commands: z4.z.array(z4.z.string()) }) }), z4.z.object({ type: z4.z.literal("shell_call_output"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), output: z4.z.array( z4.z.object({ stdout: z4.z.string(), stderr: z4.z.string(), outcome: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("timeout") }), z4.z.object({ type: z4.z.literal("exit"), exit_code: z4.z.number() }) ]) }) ) }), z4.z.object({ type: z4.z.literal("tool_search_call"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), arguments: z4.z.unknown() }), z4.z.object({ type: z4.z.literal("tool_search_output"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), tools: z4.z.array(z4.z.record(z4.z.string(), jsonValueSchema2.optional())) }) ]) }), z4.z.object({ type: z4.z.literal("response.function_call_arguments.delta"), item_id: z4.z.string(), output_index: z4.z.number(), delta: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.custom_tool_call_input.delta"), item_id: z4.z.string(), output_index: z4.z.number(), delta: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.image_generation_call.partial_image"), item_id: z4.z.string(), output_index: z4.z.number(), partial_image_b64: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.code_interpreter_call_code.delta"), item_id: z4.z.string(), output_index: z4.z.number(), delta: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.code_interpreter_call_code.done"), item_id: z4.z.string(), output_index: z4.z.number(), code: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.output_text.annotation.added"), annotation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("url_citation"), start_index: z4.z.number(), end_index: z4.z.number(), url: z4.z.string(), title: z4.z.string() }), z4.z.object({ type: z4.z.literal("file_citation"), file_id: z4.z.string(), filename: z4.z.string(), index: z4.z.number() }), z4.z.object({ type: z4.z.literal("container_file_citation"), container_id: z4.z.string(), file_id: z4.z.string(), filename: z4.z.string(), start_index: z4.z.number(), end_index: z4.z.number() }), z4.z.object({ type: z4.z.literal("file_path"), file_id: z4.z.string(), index: z4.z.number() }) ]) }), z4.z.object({ type: z4.z.literal("response.reasoning_summary_part.added"), item_id: z4.z.string(), summary_index: z4.z.number() }), z4.z.object({ type: z4.z.literal("response.reasoning_summary_text.delta"), item_id: z4.z.string(), summary_index: z4.z.number(), delta: z4.z.string() }), z4.z.object({ type: z4.z.literal("response.reasoning_summary_part.done"), item_id: z4.z.string(), summary_index: z4.z.number() }), z4.z.object({ type: z4.z.literal("response.apply_patch_call_operation_diff.delta"), item_id: z4.z.string(), output_index: z4.z.number(), delta: z4.z.string(), obfuscation: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("response.apply_patch_call_operation_diff.done"), item_id: z4.z.string(), output_index: z4.z.number(), diff: z4.z.string() }), z4.z.object({ type: z4.z.literal("error"), sequence_number: z4.z.number(), error: z4.z.object({ type: z4.z.string(), code: z4.z.string(), message: z4.z.string(), param: z4.z.string().nullish() }) }), z4.z.object({ type: z4.z.string() }).loose().transform((value) => ({ type: "unknown_chunk", message: value.type })) // fallback for unknown chunks ]) ) ); var openaiResponsesResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ id: z4.z.string().optional(), created_at: z4.z.number().optional(), error: z4.z.object({ message: z4.z.string(), type: z4.z.string(), param: z4.z.string().nullish(), code: z4.z.string() }).nullish(), model: z4.z.string().optional(), output: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("message"), role: z4.z.literal("assistant"), id: z4.z.string(), phase: z4.z.enum(["commentary", "final_answer"]).nullish(), content: z4.z.array( z4.z.object({ type: z4.z.literal("output_text"), text: z4.z.string(), logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number(), top_logprobs: z4.z.array( z4.z.object({ token: z4.z.string(), logprob: z4.z.number() }) ) }) ).nullish(), annotations: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("url_citation"), start_index: z4.z.number(), end_index: z4.z.number(), url: z4.z.string(), title: z4.z.string() }), z4.z.object({ type: z4.z.literal("file_citation"), file_id: z4.z.string(), filename: z4.z.string(), index: z4.z.number() }), z4.z.object({ type: z4.z.literal("container_file_citation"), container_id: z4.z.string(), file_id: z4.z.string(), filename: z4.z.string(), start_index: z4.z.number(), end_index: z4.z.number() }), z4.z.object({ type: z4.z.literal("file_path"), file_id: z4.z.string(), index: z4.z.number() }) ]) ) }) ) }), z4.z.object({ type: z4.z.literal("web_search_call"), id: z4.z.string(), status: z4.z.string(), action: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("search"), query: z4.z.string().nullish(), sources: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("url"), url: z4.z.string() }), z4.z.object({ type: z4.z.literal("api"), name: z4.z.string() }) ]) ).nullish() }), z4.z.object({ type: z4.z.literal("open_page"), url: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("find_in_page"), url: z4.z.string().nullish(), pattern: z4.z.string().nullish() }) ]).nullish() }), z4.z.object({ type: z4.z.literal("file_search_call"), id: z4.z.string(), queries: z4.z.array(z4.z.string()), results: z4.z.array( z4.z.object({ attributes: z4.z.record( z4.z.string(), z4.z.union([z4.z.string(), z4.z.number(), z4.z.boolean()]) ), file_id: z4.z.string(), filename: z4.z.string(), score: z4.z.number(), text: z4.z.string() }) ).nullish() }), z4.z.object({ type: z4.z.literal("code_interpreter_call"), id: z4.z.string(), code: z4.z.string().nullable(), container_id: z4.z.string(), outputs: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("logs"), logs: z4.z.string() }), z4.z.object({ type: z4.z.literal("image"), url: z4.z.string() }) ]) ).nullable() }), z4.z.object({ type: z4.z.literal("image_generation_call"), id: z4.z.string(), result: z4.z.string() }), z4.z.object({ type: z4.z.literal("local_shell_call"), id: z4.z.string(), call_id: z4.z.string(), action: z4.z.object({ type: z4.z.literal("exec"), command: z4.z.array(z4.z.string()), timeout_ms: z4.z.number().optional(), user: z4.z.string().optional(), working_directory: z4.z.string().optional(), env: z4.z.record(z4.z.string(), z4.z.string()).optional() }) }), z4.z.object({ type: z4.z.literal("function_call"), call_id: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), id: z4.z.string(), namespace: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("custom_tool_call"), call_id: z4.z.string(), name: z4.z.string(), input: z4.z.string(), id: z4.z.string() }), z4.z.object({ type: z4.z.literal("computer_call"), id: z4.z.string(), status: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("reasoning"), id: z4.z.string(), encrypted_content: z4.z.string().nullish(), summary: z4.z.array( z4.z.object({ type: z4.z.literal("summary_text"), text: z4.z.string() }) ) }), z4.z.object({ type: z4.z.literal("mcp_call"), id: z4.z.string(), status: z4.z.string(), arguments: z4.z.string(), name: z4.z.string(), server_label: z4.z.string(), output: z4.z.string().nullish(), error: z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.string().optional(), code: z4.z.union([z4.z.number(), z4.z.string()]).optional(), message: z4.z.string().optional() }).loose() ]).nullish(), approval_request_id: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("mcp_list_tools"), id: z4.z.string(), server_label: z4.z.string(), tools: z4.z.array( z4.z.object({ name: z4.z.string(), description: z4.z.string().optional(), input_schema: z4.z.any(), annotations: z4.z.record(z4.z.string(), z4.z.unknown()).optional() }) ), error: z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.string().optional(), code: z4.z.union([z4.z.number(), z4.z.string()]).optional(), message: z4.z.string().optional() }).loose() ]).optional() }), z4.z.object({ type: z4.z.literal("mcp_approval_request"), id: z4.z.string(), server_label: z4.z.string(), name: z4.z.string(), arguments: z4.z.string(), approval_request_id: z4.z.string().optional() }), z4.z.object({ type: z4.z.literal("apply_patch_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed"]), operation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("create_file"), path: z4.z.string(), diff: z4.z.string() }), z4.z.object({ type: z4.z.literal("delete_file"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("update_file"), path: z4.z.string(), diff: z4.z.string() }) ]) }), z4.z.object({ type: z4.z.literal("shell_call"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), action: z4.z.object({ commands: z4.z.array(z4.z.string()) }) }), z4.z.object({ type: z4.z.literal("shell_call_output"), id: z4.z.string(), call_id: z4.z.string(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), output: z4.z.array( z4.z.object({ stdout: z4.z.string(), stderr: z4.z.string(), outcome: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("timeout") }), z4.z.object({ type: z4.z.literal("exit"), exit_code: z4.z.number() }) ]) }) ) }), z4.z.object({ type: z4.z.literal("tool_search_call"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), arguments: z4.z.unknown() }), z4.z.object({ type: z4.z.literal("tool_search_output"), id: z4.z.string(), execution: z4.z.enum(["server", "client"]), call_id: z4.z.string().nullable(), status: z4.z.enum(["in_progress", "completed", "incomplete"]), tools: z4.z.array(z4.z.record(z4.z.string(), jsonValueSchema2.optional())) }) ]) ).optional(), service_tier: z4.z.string().nullish(), incomplete_details: z4.z.object({ reason: z4.z.string() }).nullish(), usage: z4.z.object({ input_tokens: z4.z.number(), input_tokens_details: z4.z.object({ cached_tokens: z4.z.number().nullish() }).nullish(), output_tokens: z4.z.number(), output_tokens_details: z4.z.object({ reasoning_tokens: z4.z.number().nullish() }).nullish() }).optional() }) ) ); var TOP_LOGPROBS_MAX = 20; var openaiLanguageModelResponsesOptionsSchema = lazySchema2( () => zodSchema2( z4.z.object({ /** * The ID of the OpenAI Conversation to continue. * You must create a conversation first via the OpenAI API. * Cannot be used in conjunction with `previousResponseId`. * Defaults to `undefined`. * @see https://platform.openai.com/docs/api-reference/conversations/create */ conversation: z4.z.string().nullish(), /** * The set of extra fields to include in the response (advanced, usually not needed). * Example values: 'reasoning.encrypted_content', 'file_search_call.results', 'message.output_text.logprobs'. */ include: z4.z.array( z4.z.enum([ "reasoning.encrypted_content", // handled internally by default, only needed for unknown reasoning models "file_search_call.results", "message.output_text.logprobs" ]) ).nullish(), /** * Instructions for the model. * They can be used to change the system or developer message when continuing a conversation using the `previousResponseId` option. * Defaults to `undefined`. */ instructions: z4.z.string().nullish(), /** * Return the log probabilities of the tokens. Including logprobs will increase * the response size and can slow down response times. However, it can * be useful to better understand how the model is behaving. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. * * @see https://platform.openai.com/docs/api-reference/responses/create * @see https://cookbook.openai.com/examples/using_logprobs */ logprobs: z4.z.union([z4.z.boolean(), z4.z.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(), /** * The maximum number of total calls to built-in tools that can be processed in a response. * This maximum number applies across all built-in tool calls, not per individual tool. * Any further attempts to call a tool by the model will be ignored. */ maxToolCalls: z4.z.number().nullish(), /** * Additional metadata to store with the generation. */ metadata: z4.z.any().nullish(), /** * Whether to use parallel tool calls. Defaults to `true`. */ parallelToolCalls: z4.z.boolean().nullish(), /** * The ID of the previous response. You can use it to continue a conversation. * Defaults to `undefined`. */ previousResponseId: z4.z.string().nullish(), /** * Sets a cache key to tie this prompt to cached prefixes for better caching performance. */ promptCacheKey: z4.z.string().nullish(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Currently only available for 5.1 series models. * * @default 'in_memory' */ promptCacheRetention: z4.z.enum(["in_memory", "24h"]).nullish(), /** * Reasoning effort for reasoning models. Defaults to `medium`. If you use * `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored. * Valid values: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' * * The 'none' type for `reasoningEffort` is only available for OpenAI's GPT-5.1 * models. Also, the 'xhigh' type for `reasoningEffort` is only available for * OpenAI's GPT-5.1-Codex-Max model. Setting `reasoningEffort` to 'none' or 'xhigh' with unsupported models will result in * an error. */ reasoningEffort: z4.z.string().nullish(), /** * Controls reasoning summary output from the model. * Set to "auto" to automatically receive the richest level available, * or "detailed" for comprehensive summaries. */ reasoningSummary: z4.z.string().nullish(), /** * The identifier for safety monitoring and tracking. */ safetyIdentifier: z4.z.string().nullish(), /** * Service tier for the request. * Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models). * Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported). * * Defaults to 'auto'. */ serviceTier: z4.z.enum(["auto", "flex", "priority", "default"]).nullish(), /** * Whether to store the generation. Defaults to `true`. */ store: z4.z.boolean().nullish(), /** * Whether to use strict JSON schema validation. * Defaults to `true`. */ strictJsonSchema: z4.z.boolean().nullish(), /** * Controls the verbosity of the model's responses. Lower values ('low') will result * in more concise responses, while higher values ('high') will result in more verbose responses. * Valid values: 'low', 'medium', 'high'. */ textVerbosity: z4.z.enum(["low", "medium", "high"]).nullish(), /** * Controls output truncation. 'auto' (default) performs truncation automatically; * 'disabled' turns truncation off. */ truncation: z4.z.enum(["auto", "disabled"]).nullish(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. * Defaults to `undefined`. * @see https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids */ user: z4.z.string().nullish(), /** * Override the system message mode for this model. * - 'system': Use the 'system' role for system messages (default for most models) * - 'developer': Use the 'developer' role for system messages (used by reasoning models) * - 'remove': Remove system messages entirely * * If not specified, the mode is automatically determined based on the model. */ systemMessageMode: z4.z.enum(["system", "developer", "remove"]).optional(), /** * Force treating this model as a reasoning model. * * This is useful for "stealth" reasoning models (e.g. via a custom baseURL) * where the model ID is not recognized by the SDK's allowlist. * * When enabled, the SDK applies reasoning-model parameter compatibility rules * and defaults `systemMessageMode` to `developer` unless overridden. */ forceReasoning: z4.z.boolean().optional(), /** * Restrict the callable tools to a subset while keeping the full tools * list intact, so prompt caching is preserved across requests with * different allowlists. * * When set, this overrides the request-level `toolChoice` and emits * `tool_choice: { type: "allowed_tools", mode, tools }` on the wire. * * @see https://developers.openai.com/api/reference/resources/responses/methods/create#(resource)%20responses%20%3E%20(model)%20tool_choice_allowed%20%3E%20(schema) */ allowedTools: z4.z.object({ toolNames: z4.z.array(z4.z.string()).min(1), mode: z4.z.enum(["auto", "required"]).optional() }).optional() }) ) ); async function prepareResponsesTools({ tools, toolChoice, allowedTools, toolNameMapping, customProviderToolNames }) { var _a18, _b18, _c; tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set(); for (const tool3 of tools) { switch (tool3.type) { case "function": { const openaiOptions = (_a18 = tool3.providerOptions) == null ? void 0 : _a18.openai; const deferLoading = openaiOptions == null ? void 0 : openaiOptions.deferLoading; openaiTools2.push({ type: "function", name: tool3.name, description: tool3.description, parameters: tool3.inputSchema, ...tool3.strict != null ? { strict: tool3.strict } : {}, ...deferLoading != null ? { defer_loading: deferLoading } : {} }); break; } case "provider": { switch (tool3.id) { case "openai.file_search": { const args = await validateTypes2({ value: tool3.args, schema: fileSearchArgsSchema }); openaiTools2.push({ type: "file_search", vector_store_ids: args.vectorStoreIds, max_num_results: args.maxNumResults, ranking_options: args.ranking ? { ranker: args.ranking.ranker, score_threshold: args.ranking.scoreThreshold } : void 0, filters: args.filters }); break; } case "openai.local_shell": { openaiTools2.push({ type: "local_shell" }); break; } case "openai.shell": { const args = await validateTypes2({ value: tool3.args, schema: shellArgsSchema }); openaiTools2.push({ type: "shell", ...args.environment && { environment: mapShellEnvironment(args.environment) } }); break; } case "openai.apply_patch": { openaiTools2.push({ type: "apply_patch" }); break; } case "openai.web_search_preview": { const args = await validateTypes2({ value: tool3.args, schema: webSearchPreviewArgsSchema }); openaiTools2.push({ type: "web_search_preview", search_context_size: args.searchContextSize, user_location: args.userLocation }); break; } case "openai.web_search": { const args = await validateTypes2({ value: tool3.args, schema: webSearchArgsSchema }); openaiTools2.push({ type: "web_search", filters: args.filters != null ? { allowed_domains: args.filters.allowedDomains } : void 0, external_web_access: args.externalWebAccess, search_context_size: args.searchContextSize, user_location: args.userLocation }); break; } case "openai.code_interpreter": { const args = await validateTypes2({ value: tool3.args, schema: codeInterpreterArgsSchema }); openaiTools2.push({ type: "code_interpreter", container: args.container == null ? { type: "auto", file_ids: void 0 } : typeof args.container === "string" ? args.container : { type: "auto", file_ids: args.container.fileIds } }); break; } case "openai.image_generation": { const args = await validateTypes2({ value: tool3.args, schema: imageGenerationArgsSchema }); openaiTools2.push({ type: "image_generation", background: args.background, input_fidelity: args.inputFidelity, input_image_mask: args.inputImageMask ? { file_id: args.inputImageMask.fileId, image_url: args.inputImageMask.imageUrl } : void 0, model: args.model, moderation: args.moderation, partial_images: args.partialImages, quality: args.quality, output_compression: args.outputCompression, output_format: args.outputFormat, size: args.size }); break; } case "openai.mcp": { const args = await validateTypes2({ value: tool3.args, schema: mcpArgsSchema }); const mapApprovalFilter = (filter3) => ({ tool_names: filter3.toolNames }); const requireApproval = args.requireApproval; const requireApprovalParam = requireApproval == null ? void 0 : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { never: mapApprovalFilter(requireApproval.never) } : void 0; openaiTools2.push({ type: "mcp", server_label: args.serverLabel, allowed_tools: Array.isArray(args.allowedTools) ? args.allowedTools : args.allowedTools ? { read_only: args.allowedTools.readOnly, tool_names: args.allowedTools.toolNames } : void 0, authorization: args.authorization, connector_id: args.connectorId, headers: args.headers, require_approval: requireApprovalParam != null ? requireApprovalParam : "never", server_description: args.serverDescription, server_url: args.serverUrl }); break; } case "openai.custom": { const args = await validateTypes2({ value: tool3.args, schema: customArgsSchema }); openaiTools2.push({ type: "custom", name: args.name, description: args.description, format: args.format }); resolvedCustomProviderToolNames.add(args.name); break; } case "openai.tool_search": { const args = await validateTypes2({ value: tool3.args, schema: toolSearchArgsSchema }); openaiTools2.push({ type: "tool_search", ...args.execution != null ? { execution: args.execution } : {}, ...args.description != null ? { description: args.description } : {}, ...args.parameters != null ? { parameters: args.parameters } : {} }); break; } } break; } default: toolWarnings.push({ type: "unsupported", feature: `function tool ${tool3}` }); break; } } if (allowedTools != null) { return { tools: openaiTools2, toolChoice: { type: "allowed_tools", mode: (_b18 = allowedTools.mode) != null ? _b18 : "auto", tools: allowedTools.toolNames.map((name17) => { var _a23; return { type: "function", name: (_a23 = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(name17)) != null ? _a23 : name17 }; }) }, toolWarnings }; } if (toolChoice == null) { return { tools: openaiTools2, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": case "required": return { tools: openaiTools2, toolChoice: type, toolWarnings }; case "tool": { const resolvedToolName = (_c = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _c : toolChoice.toolName; return { tools: openaiTools2, toolChoice: resolvedToolName === "code_interpreter" || resolvedToolName === "file_search" || resolvedToolName === "image_generation" || resolvedToolName === "web_search_preview" || resolvedToolName === "web_search" || resolvedToolName === "mcp" || resolvedToolName === "apply_patch" ? { type: resolvedToolName } : resolvedCustomProviderToolNames.has(resolvedToolName) ? { type: "custom", name: resolvedToolName } : { type: "function", name: resolvedToolName }, toolWarnings }; } default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError2({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } function mapShellEnvironment(environment) { if (environment.type === "containerReference") { const env2 = environment; return { type: "container_reference", container_id: env2.containerId }; } if (environment.type === "containerAuto") { const env2 = environment; return { type: "container_auto", file_ids: env2.fileIds, memory_limit: env2.memoryLimit, network_policy: env2.networkPolicy == null ? void 0 : env2.networkPolicy.type === "disabled" ? { type: "disabled" } : { type: "allowlist", allowed_domains: env2.networkPolicy.allowedDomains, domain_secrets: env2.networkPolicy.domainSecrets }, skills: mapShellSkills(env2.skills) }; } const env = environment; return { type: "local", skills: env.skills }; } function mapShellSkills(skills) { return skills == null ? void 0 : skills.map( (skill) => skill.type === "skillReference" ? { type: "skill_reference", skill_id: skill.skillId, version: skill.version } : { type: "inline", name: skill.name, description: skill.description, source: { type: "base64", media_type: skill.source.mediaType, data: skill.source.data } } ); } function extractApprovalRequestIdToToolCallIdMapping(prompt) { var _a18, _b18; const mapping = {}; for (const message of prompt) { if (message.role !== "assistant") continue; for (const part of message.content) { if (part.type !== "tool-call") continue; const approvalRequestId = (_b18 = (_a18 = part.providerOptions) == null ? void 0 : _a18.openai) == null ? void 0 : _b18.approvalRequestId; if (approvalRequestId != null) { mapping[approvalRequestId] = part.toolCallId; } } } return mapping; } var OpenAIResponsesLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/], "application/pdf": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, providerOptions, tools, toolChoice, responseFormat }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j; const warnings = []; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed" }); } if (presencePenalty != null) { warnings.push({ type: "unsupported", feature: "presencePenalty" }); } if (frequencyPenalty != null) { warnings.push({ type: "unsupported", feature: "frequencyPenalty" }); } if (stopSequences != null) { warnings.push({ type: "unsupported", feature: "stopSequences" }); } const providerOptionsName = this.config.provider.includes("azure") ? "azure" : "openai"; let openaiOptions = await parseProviderOptions2({ provider: providerOptionsName, providerOptions, schema: openaiLanguageModelResponsesOptionsSchema }); if (openaiOptions == null && providerOptionsName !== "openai") { openaiOptions = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiLanguageModelResponsesOptionsSchema }); } const isReasoningModel = (_a18 = openaiOptions == null ? void 0 : openaiOptions.forceReasoning) != null ? _a18 : modelCapabilities.isReasoningModel; if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) { warnings.push({ type: "unsupported", feature: "conversation", details: "conversation and previousResponseId cannot be used together" }); } const toolNameMapping = createToolNameMapping({ tools, providerToolNames: { "openai.code_interpreter": "code_interpreter", "openai.file_search": "file_search", "openai.image_generation": "image_generation", "openai.local_shell": "local_shell", "openai.shell": "shell", "openai.web_search": "web_search", "openai.web_search_preview": "web_search_preview", "openai.mcp": "mcp", "openai.apply_patch": "apply_patch", "openai.tool_search": "tool_search" }, resolveProviderToolName: (tool3) => tool3.id === "openai.custom" ? tool3.args.name : void 0 }); const customProviderToolNames = /* @__PURE__ */ new Set(); const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({ tools, toolChoice, allowedTools: (_b18 = openaiOptions == null ? void 0 : openaiOptions.allowedTools) != null ? _b18 : void 0, toolNameMapping, customProviderToolNames }); const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode: (_c = openaiOptions == null ? void 0 : openaiOptions.systemMessageMode) != null ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode, providerOptionsName, fileIdPrefixes: this.config.fileIdPrefixes, store: (_d = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _d : true, hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null, hasLocalShellTool: hasOpenAITool("openai.local_shell"), hasShellTool: hasOpenAITool("openai.shell"), hasApplyPatchTool: hasOpenAITool("openai.apply_patch"), customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0 }); warnings.push(...inputWarnings); const strictJsonSchema = (_e = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _e : true; let include = openaiOptions == null ? void 0 : openaiOptions.include; function addInclude(key) { if (include == null) { include = [key]; } else if (!include.includes(key)) { include = [...include, key]; } } function hasOpenAITool(id) { return (tools == null ? void 0 : tools.find((tool3) => tool3.type === "provider" && tool3.id === id)) != null; } const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0; if (topLogprobs) { addInclude("message.output_text.logprobs"); } const webSearchToolName = (_f = tools == null ? void 0 : tools.find( (tool3) => tool3.type === "provider" && (tool3.id === "openai.web_search" || tool3.id === "openai.web_search_preview") )) == null ? void 0 : _f.name; if (webSearchToolName) { addInclude("web_search_call.action.sources"); } if (hasOpenAITool("openai.code_interpreter")) { addInclude("code_interpreter_call.outputs"); } const store = openaiOptions == null ? void 0 : openaiOptions.store; if (store === false && isReasoningModel) { addInclude("reasoning.encrypted_content"); } const baseArgs = { model: this.modelId, input, temperature, top_p: topP, max_output_tokens: maxOutputTokens, ...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && { text: { ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && { format: responseFormat.schema != null ? { type: "json_schema", strict: strictJsonSchema, name: (_g = responseFormat.name) != null ? _g : "response", description: responseFormat.description, schema: responseFormat.schema } : { type: "json_object" } }, ...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity } } }, // provider options: conversation: openaiOptions == null ? void 0 : openaiOptions.conversation, max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls, metadata: openaiOptions == null ? void 0 : openaiOptions.metadata, parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls, previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId, store, user: openaiOptions == null ? void 0 : openaiOptions.user, instructions: openaiOptions == null ? void 0 : openaiOptions.instructions, service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier, include, prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey, prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention, safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier, top_logprobs: topLogprobs, truncation: openaiOptions == null ? void 0 : openaiOptions.truncation, // model-specific settings: ...isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && { reasoning: { ...(openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && { effort: openaiOptions.reasoningEffort }, ...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { summary: openaiOptions.reasoningSummary } } } }; if (isReasoningModel) { if (!((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported", feature: "topP", details: "topP is not supported for reasoning models" }); } } } else { if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) { warnings.push({ type: "unsupported", feature: "reasoningEffort", details: "reasoningEffort is not supported for non-reasoning models" }); } if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) { warnings.push({ type: "unsupported", feature: "reasoningSummary", details: "reasoningSummary is not supported for non-reasoning models" }); } } if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) { warnings.push({ type: "unsupported", feature: "serviceTier", details: "flex processing is only available for o3, o4-mini, and gpt-5 models" }); delete baseArgs.service_tier; } if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "priority" && !modelCapabilities.supportsPriorityProcessing) { warnings.push({ type: "unsupported", feature: "serviceTier", details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" }); delete baseArgs.service_tier; } const shellToolEnvType = (_j = (_i = (_h = tools == null ? void 0 : tools.find( (tool3) => tool3.type === "provider" && tool3.id === "openai.shell" )) == null ? void 0 : _h.args) == null ? void 0 : _i.environment) == null ? void 0 : _j.type; const isShellProviderExecuted = shellToolEnvType === "containerAuto" || shellToolEnvType === "containerReference"; return { webSearchToolName, args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings], store, toolNameMapping, providerOptionsName, isShellProviderExecuted }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B; const { args: body, warnings, webSearchToolName, toolNameMapping, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options); const url = this.config.url({ path: "/responses", modelId: this.modelId }); const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi2({ url, headers: combineHeaders2(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiResponsesResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); if (response.error) { throw new APICallError2({ message: response.error.message, url, requestBodyValues: body, statusCode: 400, responseHeaders, responseBody: rawResponse, isRetryable: false }); } const content = []; const logprobs = []; let hasFunctionCall = false; const hostedToolSearchCallIds = []; for (const part of response.output) { switch (part.type) { case "reasoning": { if (part.summary.length === 0) { part.summary.push({ type: "summary_text", text: "" }); } for (const summary of part.summary) { content.push({ type: "reasoning", text: summary.text, providerMetadata: { [providerOptionsName]: { itemId: part.id, reasoningEncryptedContent: (_a18 = part.encrypted_content) != null ? _a18 : null } } }); } break; } case "image_generation_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("image_generation"), input: "{}", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("image_generation"), result: { result: part.result } }); break; } case "tool_search_call": { const toolCallId = (_b18 = part.call_id) != null ? _b18 : part.id; const isHosted = part.execution === "server"; if (isHosted) { hostedToolSearchCallIds.push(toolCallId); } content.push({ type: "tool-call", toolCallId, toolName: toolNameMapping.toCustomToolName("tool_search"), input: JSON.stringify({ arguments: part.arguments, call_id: part.call_id }), ...isHosted ? { providerExecuted: true } : {}, providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "tool_search_output": { const toolCallId = (_d = (_c = part.call_id) != null ? _c : hostedToolSearchCallIds.shift()) != null ? _d : part.id; content.push({ type: "tool-result", toolCallId, toolName: toolNameMapping.toCustomToolName("tool_search"), result: { tools: part.tools }, providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "local_shell_call": { content.push({ type: "tool-call", toolCallId: part.call_id, toolName: toolNameMapping.toCustomToolName("local_shell"), input: JSON.stringify({ action: part.action }), providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "shell_call": { content.push({ type: "tool-call", toolCallId: part.call_id, toolName: toolNameMapping.toCustomToolName("shell"), input: JSON.stringify({ action: { commands: part.action.commands } }), ...isShellProviderExecuted && { providerExecuted: true }, providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "shell_call_output": { content.push({ type: "tool-result", toolCallId: part.call_id, toolName: toolNameMapping.toCustomToolName("shell"), result: { output: part.output.map((item) => ({ stdout: item.stdout, stderr: item.stderr, outcome: item.outcome.type === "exit" ? { type: "exit", exitCode: item.outcome.exit_code } : { type: "timeout" } })) } }); break; } case "message": { for (const contentPart of part.content) { if (((_f = (_e = options.providerOptions) == null ? void 0 : _e[providerOptionsName]) == null ? void 0 : _f.logprobs) && contentPart.logprobs) { logprobs.push(contentPart.logprobs); } const providerMetadata2 = { itemId: part.id, ...part.phase != null && { phase: part.phase }, ...contentPart.annotations.length > 0 && { annotations: contentPart.annotations } }; content.push({ type: "text", text: contentPart.text, providerMetadata: { [providerOptionsName]: providerMetadata2 } }); for (const annotation of contentPart.annotations) { if (annotation.type === "url_citation") { content.push({ type: "source", sourceType: "url", id: (_i = (_h = (_g = this.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId2(), url: annotation.url, title: annotation.title }); } else if (annotation.type === "file_citation") { content.push({ type: "source", sourceType: "document", id: (_l = (_k = (_j = this.config).generateId) == null ? void 0 : _k.call(_j)) != null ? _l : generateId2(), mediaType: "text/plain", title: annotation.filename, filename: annotation.filename, providerMetadata: { [providerOptionsName]: { type: annotation.type, fileId: annotation.file_id, index: annotation.index } } }); } else if (annotation.type === "container_file_citation") { content.push({ type: "source", sourceType: "document", id: (_o = (_n = (_m = this.config).generateId) == null ? void 0 : _n.call(_m)) != null ? _o : generateId2(), mediaType: "text/plain", title: annotation.filename, filename: annotation.filename, providerMetadata: { [providerOptionsName]: { type: annotation.type, fileId: annotation.file_id, containerId: annotation.container_id } } }); } else if (annotation.type === "file_path") { content.push({ type: "source", sourceType: "document", id: (_r = (_q = (_p = this.config).generateId) == null ? void 0 : _q.call(_p)) != null ? _r : generateId2(), mediaType: "application/octet-stream", title: annotation.file_id, filename: annotation.file_id, providerMetadata: { [providerOptionsName]: { type: annotation.type, fileId: annotation.file_id, index: annotation.index } } }); } } } break; } case "function_call": { hasFunctionCall = true; content.push({ type: "tool-call", toolCallId: part.call_id, toolName: part.name, input: part.arguments, providerMetadata: { [providerOptionsName]: { itemId: part.id, ...part.namespace != null && { namespace: part.namespace } } } }); break; } case "custom_tool_call": { hasFunctionCall = true; const toolName = toolNameMapping.toCustomToolName(part.name); content.push({ type: "tool-call", toolCallId: part.call_id, toolName, input: JSON.stringify(part.input), providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "web_search_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), input: JSON.stringify({}), providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), result: mapWebSearchOutput(part.action) }); break; } case "mcp_call": { const toolCallId = part.approval_request_id != null ? (_s = approvalRequestIdToDummyToolCallIdFromPrompt[part.approval_request_id]) != null ? _s : part.id : part.id; const toolName = `mcp.${part.name}`; content.push({ type: "tool-call", toolCallId, toolName, input: part.arguments, providerExecuted: true, dynamic: true }); content.push({ type: "tool-result", toolCallId, toolName, result: { type: "call", serverLabel: part.server_label, name: part.name, arguments: part.arguments, ...part.output != null ? { output: part.output } : {}, ...part.error != null ? { error: part.error } : {} }, providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "mcp_list_tools": { break; } case "mcp_approval_request": { const approvalRequestId = (_t = part.approval_request_id) != null ? _t : part.id; const dummyToolCallId = (_w = (_v = (_u = this.config).generateId) == null ? void 0 : _v.call(_u)) != null ? _w : generateId2(); const toolName = `mcp.${part.name}`; content.push({ type: "tool-call", toolCallId: dummyToolCallId, toolName, input: part.arguments, providerExecuted: true, dynamic: true }); content.push({ type: "tool-approval-request", approvalId: approvalRequestId, toolCallId: dummyToolCallId }); break; } case "computer_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("computer_use"), input: "", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("computer_use"), result: { type: "computer_use_tool_result", status: part.status || "completed" } }); break; } case "file_search_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("file_search"), input: "{}", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("file_search"), result: { queries: part.queries, results: (_y = (_x = part.results) == null ? void 0 : _x.map((result) => ({ attributes: result.attributes, fileId: result.file_id, filename: result.filename, score: result.score, text: result.text }))) != null ? _y : null } }); break; } case "code_interpreter_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), input: JSON.stringify({ code: part.code, containerId: part.container_id }), providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), result: { outputs: part.outputs } }); break; } case "apply_patch_call": { content.push({ type: "tool-call", toolCallId: part.call_id, toolName: toolNameMapping.toCustomToolName("apply_patch"), input: JSON.stringify({ callId: part.call_id, operation: part.operation }), providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } } } const providerMetadata = { [providerOptionsName]: { responseId: response.id, ...logprobs.length > 0 ? { logprobs } : {}, ...typeof response.service_tier === "string" ? { serviceTier: response.service_tier } : {} } }; const usage = response.usage; return { content, finishReason: { unified: mapOpenAIResponseFinishReason({ finishReason: (_z = response.incomplete_details) == null ? void 0 : _z.reason, hasFunctionCall }), raw: (_B = (_A = response.incomplete_details) == null ? void 0 : _A.reason) != null ? _B : void 0 }, usage: convertOpenAIResponsesUsage(usage), request: { body }, response: { id: response.id, timestamp: new Date(response.created_at * 1e3), modelId: response.model, headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { const { args: body, warnings, webSearchToolName, toolNameMapping, store, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options); const { responseHeaders, value: response } = await postJsonToApi2({ url: this.config.url({ path: "/responses", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body: { ...body, stream: true }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2( openaiResponsesChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const self = this; const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt); const approvalRequestIdToDummyToolCallIdFromStream = /* @__PURE__ */ new Map(); let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; const logprobs = []; let responseId = null; const ongoingToolCalls = {}; const ongoingAnnotations = []; let activeMessagePhase; let hasFunctionCall = false; const activeReasoning = {}; let serviceTier; const hostedToolSearchCallIds = []; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if (isResponseOutputItemAddedChunk(value)) { if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = { toolName: value.item.name, toolCallId: value.item.call_id }; controller.enqueue({ type: "tool-input-start", id: value.item.call_id, toolName: value.item.name }); } else if (value.item.type === "custom_tool_call") { const toolName = toolNameMapping.toCustomToolName( value.item.name ); ongoingToolCalls[value.output_index] = { toolName, toolCallId: value.item.call_id }; controller.enqueue({ type: "tool-input-start", id: value.item.call_id, toolName }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), toolCallId: value.item.id }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), providerExecuted: true }); controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), input: JSON.stringify({}), providerExecuted: true }); } else if (value.item.type === "computer_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("computer_use"), toolCallId: value.item.id }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: toolNameMapping.toCustomToolName("computer_use"), providerExecuted: true }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("code_interpreter"), toolCallId: value.item.id, codeInterpreter: { containerId: value.item.container_id } }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), providerExecuted: true }); controller.enqueue({ type: "tool-input-delta", id: value.item.id, delta: `{"containerId":"${value.item.container_id}","code":"` }); } else if (value.item.type === "file_search_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("file_search"), input: "{}", providerExecuted: true }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("image_generation"), input: "{}", providerExecuted: true }); } else if (value.item.type === "tool_search_call") { const toolCallId = value.item.id; const toolName = toolNameMapping.toCustomToolName("tool_search"); const isHosted = value.item.execution === "server"; ongoingToolCalls[value.output_index] = { toolName, toolCallId, toolSearchExecution: (_a18 = value.item.execution) != null ? _a18 : "server" }; if (isHosted) { controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName, providerExecuted: true }); } } else if (value.item.type === "tool_search_output") ; else if (value.item.type === "mcp_call" || value.item.type === "mcp_list_tools" || value.item.type === "mcp_approval_request") ; else if (value.item.type === "apply_patch_call") { const { call_id: callId, operation } = value.item; ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("apply_patch"), toolCallId: callId, applyPatch: { // delete_file doesn't have diff hasDiff: operation.type === "delete_file", endEmitted: operation.type === "delete_file" } }; controller.enqueue({ type: "tool-input-start", id: callId, toolName: toolNameMapping.toCustomToolName("apply_patch") }); if (operation.type === "delete_file") { const inputString = JSON.stringify({ callId, operation }); controller.enqueue({ type: "tool-input-delta", id: callId, delta: inputString }); controller.enqueue({ type: "tool-input-end", id: callId }); } else { controller.enqueue({ type: "tool-input-delta", id: callId, delta: `{"callId":"${escapeJSONDelta(callId)}","operation":{"type":"${escapeJSONDelta(operation.type)}","path":"${escapeJSONDelta(operation.path)}","diff":"` }); } } else if (value.item.type === "shell_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("shell"), toolCallId: value.item.call_id }; } else if (value.item.type === "shell_call_output") ; else if (value.item.type === "message") { ongoingAnnotations.splice(0, ongoingAnnotations.length); activeMessagePhase = (_b18 = value.item.phase) != null ? _b18 : void 0; controller.enqueue({ type: "text-start", id: value.item.id, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...value.item.phase != null && { phase: value.item.phase } } } }); } else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") { activeReasoning[value.item.id] = { encryptedContent: value.item.encrypted_content, summaryParts: { 0: "active" } }; controller.enqueue({ type: "reasoning-start", id: `${value.item.id}:0`, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, reasoningEncryptedContent: (_c = value.item.encrypted_content) != null ? _c : null } } }); } } else if (isResponseOutputItemDoneChunk(value)) { if (value.item.type === "message") { const phase = (_d = value.item.phase) != null ? _d : activeMessagePhase; activeMessagePhase = void 0; controller.enqueue({ type: "text-end", id: value.item.id, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...phase != null && { phase }, ...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations } } } }); } else if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = void 0; hasFunctionCall = true; controller.enqueue({ type: "tool-input-end", id: value.item.call_id, ...value.item.namespace != null && { providerMetadata: { [providerOptionsName]: { namespace: value.item.namespace } } } }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: value.item.name, input: value.item.arguments, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...value.item.namespace != null && { namespace: value.item.namespace } } } }); } else if (value.item.type === "custom_tool_call") { ongoingToolCalls[value.output_index] = void 0; hasFunctionCall = true; const toolName = toolNameMapping.toCustomToolName( value.item.name ); controller.enqueue({ type: "tool-input-end", id: value.item.call_id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName, input: JSON.stringify(value.item.input), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), result: mapWebSearchOutput(value.item.action) }); } else if (value.item.type === "computer_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("computer_use"), input: "", providerExecuted: true }); controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("computer_use"), result: { type: "computer_use_tool_result", status: value.item.status || "completed" } }); } else if (value.item.type === "file_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("file_search"), result: { queries: value.item.queries, results: (_f = (_e = value.item.results) == null ? void 0 : _e.map((result) => ({ attributes: result.attributes, fileId: result.file_id, filename: result.filename, score: result.score, text: result.text }))) != null ? _f : null } }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), result: { outputs: value.item.outputs } }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("image_generation"), result: { result: value.item.result } }); } else if (value.item.type === "tool_search_call") { const toolCall = ongoingToolCalls[value.output_index]; const isHosted = value.item.execution === "server"; if (toolCall != null) { const toolCallId = isHosted ? toolCall.toolCallId : (_g = value.item.call_id) != null ? _g : value.item.id; if (isHosted) { hostedToolSearchCallIds.push(toolCallId); } else { controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName: toolCall.toolName }); } controller.enqueue({ type: "tool-input-end", id: toolCallId }); controller.enqueue({ type: "tool-call", toolCallId, toolName: toolCall.toolName, input: JSON.stringify({ arguments: value.item.arguments, call_id: isHosted ? null : toolCallId }), ...isHosted ? { providerExecuted: true } : {}, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "tool_search_output") { const toolCallId = (_i = (_h = value.item.call_id) != null ? _h : hostedToolSearchCallIds.shift()) != null ? _i : value.item.id; controller.enqueue({ type: "tool-result", toolCallId, toolName: toolNameMapping.toCustomToolName("tool_search"), result: { tools: value.item.tools }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "mcp_call") { ongoingToolCalls[value.output_index] = void 0; const approvalRequestId = (_j = value.item.approval_request_id) != null ? _j : void 0; const aliasedToolCallId = approvalRequestId != null ? (_l = (_k = approvalRequestIdToDummyToolCallIdFromStream.get( approvalRequestId )) != null ? _k : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _l : value.item.id : value.item.id; const toolName = `mcp.${value.item.name}`; controller.enqueue({ type: "tool-call", toolCallId: aliasedToolCallId, toolName, input: value.item.arguments, providerExecuted: true, dynamic: true }); controller.enqueue({ type: "tool-result", toolCallId: aliasedToolCallId, toolName, result: { type: "call", serverLabel: value.item.server_label, name: value.item.name, arguments: value.item.arguments, ...value.item.output != null ? { output: value.item.output } : {}, ...value.item.error != null ? { error: value.item.error } : {} }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "mcp_list_tools") { ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "apply_patch_call") { const toolCall = ongoingToolCalls[value.output_index]; if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted && value.item.operation.type !== "delete_file") { if (!toolCall.applyPatch.hasDiff) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.item.operation.diff) }); } controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: '"}}' }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId }); toolCall.applyPatch.endEmitted = true; } if (toolCall && value.item.status === "completed") { controller.enqueue({ type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolNameMapping.toCustomToolName("apply_patch"), input: JSON.stringify({ callId: value.item.call_id, operation: value.item.operation }), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "mcp_approval_request") { ongoingToolCalls[value.output_index] = void 0; const dummyToolCallId = (_o = (_n = (_m = self.config).generateId) == null ? void 0 : _n.call(_m)) != null ? _o : generateId2(); const approvalRequestId = (_p = value.item.approval_request_id) != null ? _p : value.item.id; approvalRequestIdToDummyToolCallIdFromStream.set( approvalRequestId, dummyToolCallId ); const toolName = `mcp.${value.item.name}`; controller.enqueue({ type: "tool-call", toolCallId: dummyToolCallId, toolName, input: value.item.arguments, providerExecuted: true, dynamic: true }); controller.enqueue({ type: "tool-approval-request", approvalId: approvalRequestId, toolCallId: dummyToolCallId }); } else if (value.item.type === "local_shell_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("local_shell"), input: JSON.stringify({ action: { type: "exec", command: value.item.action.command, timeoutMs: value.item.action.timeout_ms, user: value.item.action.user, workingDirectory: value.item.action.working_directory, env: value.item.action.env } }), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "shell_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("shell"), input: JSON.stringify({ action: { commands: value.item.action.commands } }), ...isShellProviderExecuted && { providerExecuted: true }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "shell_call_output") { controller.enqueue({ type: "tool-result", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("shell"), result: { output: value.item.output.map( (item) => ({ stdout: item.stdout, stderr: item.stderr, outcome: item.outcome.type === "exit" ? { type: "exit", exitCode: item.outcome.exit_code } : { type: "timeout" } }) ) } }); } else if (value.item.type === "reasoning") { const activeReasoningPart = activeReasoning[value.item.id]; const summaryPartIndices = Object.entries( activeReasoningPart.summaryParts ).filter( ([_, status]) => status === "active" || status === "can-conclude" ).map(([summaryIndex]) => summaryIndex); for (const summaryIndex of summaryPartIndices) { controller.enqueue({ type: "reasoning-end", id: `${value.item.id}:${summaryIndex}`, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, reasoningEncryptedContent: (_q = value.item.encrypted_content) != null ? _q : null } } }); } delete activeReasoning[value.item.id]; } } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: value.delta }); } } else if (isResponseCustomToolCallInputDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: value.delta }); } } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall == null ? void 0 : toolCall.applyPatch) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.delta) }); toolCall.applyPatch.hasDiff = true; } } else if (isResponseApplyPatchCallOperationDiffDoneChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted) { if (!toolCall.applyPatch.hasDiff) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.diff) }); toolCall.applyPatch.hasDiff = true; } controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: '"}}' }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId }); toolCall.applyPatch.endEmitted = true; } } else if (isResponseImageGenerationCallPartialImageChunk(value)) { controller.enqueue({ type: "tool-result", toolCallId: value.item_id, toolName: toolNameMapping.toCustomToolName("image_generation"), result: { result: value.partial_image_b64 }, preliminary: true }); } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.delta) }); } } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: '"}' }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId }); controller.enqueue({ type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolNameMapping.toCustomToolName("code_interpreter"), input: JSON.stringify({ code: value.code, containerId: toolCall.codeInterpreter.containerId }), providerExecuted: true }); } } else if (isResponseCreatedChunk(value)) { responseId = value.response.id; controller.enqueue({ type: "response-metadata", id: value.response.id, timestamp: new Date(value.response.created_at * 1e3), modelId: value.response.model }); } else if (isTextDeltaChunk(value)) { controller.enqueue({ type: "text-delta", id: value.item_id, delta: value.delta }); if (((_s = (_r = options.providerOptions) == null ? void 0 : _r[providerOptionsName]) == null ? void 0 : _s.logprobs) && value.logprobs) { logprobs.push(value.logprobs); } } else if (value.type === "response.reasoning_summary_part.added") { if (value.summary_index > 0) { const activeReasoningPart = activeReasoning[value.item_id]; activeReasoningPart.summaryParts[value.summary_index] = "active"; for (const summaryIndex of Object.keys( activeReasoningPart.summaryParts )) { if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${summaryIndex}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); activeReasoningPart.summaryParts[summaryIndex] = "concluded"; } } controller.enqueue({ type: "reasoning-start", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id, reasoningEncryptedContent: (_u = (_t = activeReasoning[value.item_id]) == null ? void 0 : _t.encryptedContent) != null ? _u : null } } }); } } else if (value.type === "response.reasoning_summary_text.delta") { controller.enqueue({ type: "reasoning-delta", id: `${value.item_id}:${value.summary_index}`, delta: value.delta, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); } else if (value.type === "response.reasoning_summary_part.done") { if (store) { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded"; } else { activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude"; } } else if (isResponseFinishedChunk(value)) { finishReason = { unified: mapOpenAIResponseFinishReason({ finishReason: (_v = value.response.incomplete_details) == null ? void 0 : _v.reason, hasFunctionCall }), raw: (_x = (_w = value.response.incomplete_details) == null ? void 0 : _w.reason) != null ? _x : void 0 }; usage = value.response.usage; if (typeof value.response.service_tier === "string") { serviceTier = value.response.service_tier; } } else if (isResponseFailedChunk(value)) { const incompleteReason = (_y = value.response.incomplete_details) == null ? void 0 : _y.reason; finishReason = { unified: incompleteReason ? mapOpenAIResponseFinishReason({ finishReason: incompleteReason, hasFunctionCall }) : "error", raw: incompleteReason != null ? incompleteReason : "error" }; usage = (_z = value.response.usage) != null ? _z : void 0; } else if (isResponseAnnotationAddedChunk(value)) { ongoingAnnotations.push(value.annotation); if (value.annotation.type === "url_citation") { controller.enqueue({ type: "source", sourceType: "url", id: (_C = (_B = (_A = self.config).generateId) == null ? void 0 : _B.call(_A)) != null ? _C : generateId2(), url: value.annotation.url, title: value.annotation.title }); } else if (value.annotation.type === "file_citation") { controller.enqueue({ type: "source", sourceType: "document", id: (_F = (_E = (_D = self.config).generateId) == null ? void 0 : _E.call(_D)) != null ? _F : generateId2(), mediaType: "text/plain", title: value.annotation.filename, filename: value.annotation.filename, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, index: value.annotation.index } } }); } else if (value.annotation.type === "container_file_citation") { controller.enqueue({ type: "source", sourceType: "document", id: (_I = (_H = (_G = self.config).generateId) == null ? void 0 : _H.call(_G)) != null ? _I : generateId2(), mediaType: "text/plain", title: value.annotation.filename, filename: value.annotation.filename, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, containerId: value.annotation.container_id } } }); } else if (value.annotation.type === "file_path") { controller.enqueue({ type: "source", sourceType: "document", id: (_L = (_K = (_J = self.config).generateId) == null ? void 0 : _K.call(_J)) != null ? _L : generateId2(), mediaType: "application/octet-stream", title: value.annotation.file_id, filename: value.annotation.file_id, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, index: value.annotation.index } } }); } } else if (isErrorChunk(value)) { controller.enqueue({ type: "error", error: value }); } }, flush(controller) { const providerMetadata = { [providerOptionsName]: { responseId, ...logprobs.length > 0 ? { logprobs } : {}, ...serviceTier !== void 0 ? { serviceTier } : {} } }; controller.enqueue({ type: "finish", finishReason, usage: convertOpenAIResponsesUsage(usage), providerMetadata }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; function isTextDeltaChunk(chunk) { return chunk.type === "response.output_text.delta"; } function isResponseOutputItemDoneChunk(chunk) { return chunk.type === "response.output_item.done"; } function isResponseFinishedChunk(chunk) { return chunk.type === "response.completed" || chunk.type === "response.incomplete"; } function isResponseFailedChunk(chunk) { return chunk.type === "response.failed"; } function isResponseCreatedChunk(chunk) { return chunk.type === "response.created"; } function isResponseFunctionCallArgumentsDeltaChunk(chunk) { return chunk.type === "response.function_call_arguments.delta"; } function isResponseCustomToolCallInputDeltaChunk(chunk) { return chunk.type === "response.custom_tool_call_input.delta"; } function isResponseImageGenerationCallPartialImageChunk(chunk) { return chunk.type === "response.image_generation_call.partial_image"; } function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.delta"; } function isResponseCodeInterpreterCallCodeDoneChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.done"; } function isResponseApplyPatchCallOperationDiffDeltaChunk(chunk) { return chunk.type === "response.apply_patch_call_operation_diff.delta"; } function isResponseApplyPatchCallOperationDiffDoneChunk(chunk) { return chunk.type === "response.apply_patch_call_operation_diff.done"; } function isResponseOutputItemAddedChunk(chunk) { return chunk.type === "response.output_item.added"; } function isResponseAnnotationAddedChunk(chunk) { return chunk.type === "response.output_text.annotation.added"; } function isErrorChunk(chunk) { return chunk.type === "error"; } function mapWebSearchOutput(action) { var _a18; if (action == null) { return {}; } switch (action.type) { case "search": return { action: { type: "search", query: (_a18 = action.query) != null ? _a18 : void 0 }, // include sources when provided by the Responses API (behind include flag) ...action.sources != null && { sources: action.sources } }; case "open_page": return { action: { type: "openPage", url: action.url } }; case "find_in_page": return { action: { type: "findInPage", url: action.url, pattern: action.pattern } }; } } function escapeJSONDelta(delta) { return JSON.stringify(delta).slice(1, -1); } var openaiSpeechModelOptionsSchema = lazySchema2( () => zodSchema2( z4.z.object({ instructions: z4.z.string().nullish(), speed: z4.z.number().min(0.25).max(4).default(1).nullish() }) ) ); var OpenAISpeechModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v3"; } get provider() { return this.config.provider; } async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) { const warnings = []; const openAIOptions = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openaiSpeechModelOptionsSchema }); const requestBody = { model: this.modelId, input: text, voice, response_format: "mp3", speed, instructions }; if (outputFormat) { if (["mp3", "opus", "aac", "flac", "wav", "pcm"].includes(outputFormat)) { requestBody.response_format = outputFormat; } else { warnings.push({ type: "unsupported", feature: "outputFormat", details: `Unsupported output format: ${outputFormat}. Using mp3 instead.` }); } } if (openAIOptions) { const speechModelOptions = {}; for (const key in speechModelOptions) { const value = speechModelOptions[key]; if (value !== void 0) { requestBody[key] = value; } } } if (language) { warnings.push({ type: "unsupported", feature: "language", details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.` }); } return { requestBody, warnings }; } async doGenerate(options) { var _a18, _b18, _c; const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); const { requestBody, warnings } = await this.getArgs(options); const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi2({ url: this.config.url({ path: "/audio/speech", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), body: requestBody, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createBinaryResponseHandler2(), abortSignal: options.abortSignal, fetch: this.config.fetch }); return { audio, warnings, request: { body: JSON.stringify(requestBody) }, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } }; var openaiTranscriptionResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ text: z4.z.string(), language: z4.z.string().nullish(), duration: z4.z.number().nullish(), words: z4.z.array( z4.z.object({ word: z4.z.string(), start: z4.z.number(), end: z4.z.number() }) ).nullish(), segments: z4.z.array( z4.z.object({ id: z4.z.number(), seek: z4.z.number(), start: z4.z.number(), end: z4.z.number(), text: z4.z.string(), tokens: z4.z.array(z4.z.number()), temperature: z4.z.number(), avg_logprob: z4.z.number(), compression_ratio: z4.z.number(), no_speech_prob: z4.z.number() }) ).nullish() }) ) ); var openAITranscriptionModelOptions = lazySchema2( () => zodSchema2( z4.z.object({ /** * Additional information to include in the transcription response. */ include: z4.z.array(z4.z.string()).optional(), /** * The language of the input audio in ISO-639-1 format. */ language: z4.z.string().optional(), /** * An optional text to guide the model's style or continue a previous audio segment. */ prompt: z4.z.string().optional(), /** * The sampling temperature, between 0 and 1. * @default 0 */ temperature: z4.z.number().min(0).max(1).default(0).optional(), /** * The timestamp granularities to populate for this transcription. * @default ['segment'] */ timestampGranularities: z4.z.array(z4.z.enum(["word", "segment"])).default(["segment"]).optional() }) ) ); var languageMap = { afrikaans: "af", arabic: "ar", armenian: "hy", azerbaijani: "az", belarusian: "be", bosnian: "bs", bulgarian: "bg", catalan: "ca", chinese: "zh", croatian: "hr", czech: "cs", danish: "da", dutch: "nl", english: "en", estonian: "et", finnish: "fi", french: "fr", galician: "gl", german: "de", greek: "el", hebrew: "he", hindi: "hi", hungarian: "hu", icelandic: "is", indonesian: "id", italian: "it", japanese: "ja", kannada: "kn", kazakh: "kk", korean: "ko", latvian: "lv", lithuanian: "lt", macedonian: "mk", malay: "ms", marathi: "mr", maori: "mi", nepali: "ne", norwegian: "no", persian: "fa", polish: "pl", portuguese: "pt", romanian: "ro", russian: "ru", serbian: "sr", slovak: "sk", slovenian: "sl", spanish: "es", swahili: "sw", swedish: "sv", tagalog: "tl", tamil: "ta", thai: "th", turkish: "tr", ukrainian: "uk", urdu: "ur", vietnamese: "vi", welsh: "cy" }; var OpenAITranscriptionModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v3"; } get provider() { return this.config.provider; } async getArgs({ audio, mediaType, providerOptions }) { const warnings = []; const openAIOptions = await parseProviderOptions2({ provider: "openai", providerOptions, schema: openAITranscriptionModelOptions }); const formData = new FormData(); const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array2(audio)]); formData.append("model", this.modelId); const fileExtension = mediaTypeToExtension2(mediaType); formData.append( "file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}` ); if (openAIOptions) { const transcriptionModelOptions = { include: openAIOptions.include, language: openAIOptions.language, prompt: openAIOptions.prompt, // https://platform.openai.com/docs/api-reference/audio/createTranscription#audio_createtranscription-response_format // prefer verbose_json to get segments for models that support it response_format: [ "gpt-4o-transcribe", "gpt-4o-mini-transcribe" ].includes(this.modelId) ? "json" : "verbose_json", temperature: openAIOptions.temperature, timestamp_granularities: openAIOptions.timestampGranularities }; for (const [key, value] of Object.entries(transcriptionModelOptions)) { if (value != null) { if (Array.isArray(value)) { for (const item of value) { formData.append(`${key}[]`, String(item)); } } else { formData.append(key, String(value)); } } } } return { formData, warnings }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h; const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); const { formData, warnings } = await this.getArgs(options); const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi2({ url: this.config.url({ path: "/audio/transcriptions", modelId: this.modelId }), headers: combineHeaders2(this.config.headers(), options.headers), formData, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( openaiTranscriptionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0; return { text: response.text, segments: (_g = (_f = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({ text: segment.text, startSecond: segment.start, endSecond: segment.end }))) != null ? _f : (_e = response.words) == null ? void 0 : _e.map((word) => ({ text: word.word, startSecond: word.start, endSecond: word.end }))) != null ? _g : [], language, durationInSeconds: (_h = response.duration) != null ? _h : void 0, warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } }; var VERSION4 = "3.0.63" ; function createOpenAI(options = {}) { var _a18, _b18; const baseURL = (_a18 = withoutTrailingSlash2( loadOptionalSetting2({ settingValue: options.baseURL, environmentVariableName: "OPENAI_BASE_URL" }) )) != null ? _a18 : "https://api.openai.com/v1"; const providerName = (_b18 = options.name) != null ? _b18 : "openai"; const getHeaders = () => withUserAgentSuffix2( { Authorization: `Bearer ${loadApiKey2({ apiKey: options.apiKey, environmentVariableName: "OPENAI_API_KEY", description: "OpenAI" })}`, "OpenAI-Organization": options.organization, "OpenAI-Project": options.project, ...options.headers }, `ai-sdk/openai/${VERSION4}` ); const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, { provider: `${providerName}.chat`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, { provider: `${providerName}.completion`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, { provider: `${providerName}.embedding`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createImageModel = (modelId) => new OpenAIImageModel(modelId, { provider: `${providerName}.image`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, { provider: `${providerName}.transcription`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, { provider: `${providerName}.speech`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createLanguageModel = (modelId) => { if (new.target) { throw new Error( "The OpenAI model function cannot be called with the new keyword." ); } return createResponsesModel(modelId); }; const createResponsesModel = (modelId) => { return new OpenAIResponsesLanguageModel(modelId, { provider: `${providerName}.responses`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch, fileIdPrefixes: ["file-"] }); }; const provider = function(modelId) { return createLanguageModel(modelId); }; provider.specificationVersion = "v3"; provider.languageModel = createLanguageModel; provider.chat = createChatModel; provider.completion = createCompletionModel; provider.responses = createResponsesModel; provider.embedding = createEmbeddingModel; provider.embeddingModel = createEmbeddingModel; provider.textEmbedding = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.image = createImageModel; provider.imageModel = createImageModel; provider.transcription = createTranscriptionModel; provider.transcriptionModel = createTranscriptionModel; provider.speech = createSpeechModel; provider.speechModel = createSpeechModel; provider.tools = openaiTools; return provider; } createOpenAI(); // src/llm/model/gateways/base.ts var MASTRA_GATEWAY_STREAM_TRANSPORT = /* @__PURE__ */ Symbol.for("@mastra/core.gatewayStreamTransport"); var MastraModelGateway = class { getId() { return this.id; } shouldEnable() { return true; } serializeForSpan() { return { id: this.id, name: this.name }; } }; // src/llm/model/gateways/constants.ts var MASTRA_USER_AGENT = `mastra/${"1.45.0"}` ; var PROVIDERS_WITH_INSTALLED_PACKAGES = [ "anthropic", "cerebras", "deepinfra", "deepseek", "google", "groq", "mistral", "openai", "openrouter", "perplexity", "togetherai", "vercel", "xai" ]; var EXCLUDED_PROVIDERS = ["github-copilot"]; var GATEWAY_AUTH_HEADER = "X-Memory-Gateway-Authorization"; var VERSION5 = "3.0.82" ; var anthropicErrorDataSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("error"), error: z4.z.object({ type: z4.z.string(), message: z4.z.string() }) }) ) ); var anthropicFailedResponseHandler = createJsonErrorResponseHandler2({ errorSchema: anthropicErrorDataSchema, errorToMessage: (data) => data.error.message }); var anthropicStopDetailsSchema = z4.z.object({ type: z4.z.string(), category: z4.z.string().nullish(), explanation: z4.z.string().nullish(), recommended_model: z4.z.string().nullish() }); var anthropicMessagesResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("message"), id: z4.z.string().nullish(), model: z4.z.string().nullish(), content: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("text"), text: z4.z.string(), citations: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("web_search_result_location"), cited_text: z4.z.string(), url: z4.z.string(), title: z4.z.string(), encrypted_index: z4.z.string() }), z4.z.object({ type: z4.z.literal("page_location"), cited_text: z4.z.string(), document_index: z4.z.number(), document_title: z4.z.string().nullable(), start_page_number: z4.z.number(), end_page_number: z4.z.number() }), z4.z.object({ type: z4.z.literal("char_location"), cited_text: z4.z.string(), document_index: z4.z.number(), document_title: z4.z.string().nullable(), start_char_index: z4.z.number(), end_char_index: z4.z.number() }) ]) ).optional() }), z4.z.object({ type: z4.z.literal("thinking"), thinking: z4.z.string(), signature: z4.z.string() }), z4.z.object({ type: z4.z.literal("redacted_thinking"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("compaction"), content: z4.z.string() }), z4.z.object({ type: z4.z.literal("tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.unknown(), // Programmatic tool calling: caller info when triggered from code execution caller: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_20250825"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("code_execution_20260120"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("direct") }) ]).optional() }), z4.z.object({ type: z4.z.literal("server_tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), caller: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_20260120"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("direct") }) ]).optional() }), z4.z.object({ type: z4.z.literal("mcp_tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.unknown(), server_name: z4.z.string() }), z4.z.object({ type: z4.z.literal("mcp_tool_result"), tool_use_id: z4.z.string(), is_error: z4.z.boolean(), content: z4.z.array( z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.literal("text"), text: z4.z.string() }) ]) ) }), z4.z.object({ type: z4.z.literal("web_fetch_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("web_fetch_result"), url: z4.z.string(), retrieved_at: z4.z.string(), content: z4.z.object({ type: z4.z.literal("document"), title: z4.z.string().nullable(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), source: z4.z.union([ z4.z.object({ type: z4.z.literal("base64"), media_type: z4.z.literal("application/pdf"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("text"), media_type: z4.z.literal("text/plain"), data: z4.z.string() }) ]) }) }), z4.z.object({ type: z4.z.literal("web_fetch_tool_result_error"), error_code: z4.z.string() }) ]) }), z4.z.object({ type: z4.z.literal("web_search_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.array( z4.z.object({ type: z4.z.literal("web_search_result"), url: z4.z.string(), title: z4.z.string(), encrypted_content: z4.z.string(), page_age: z4.z.string().nullish() }) ), z4.z.object({ type: z4.z.literal("web_search_tool_result_error"), error_code: z4.z.string() }) ]) }), // code execution results for code_execution_20250522 tool: z4.z.object({ type: z4.z.literal("code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_result"), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("encrypted_code_execution_result"), encrypted_stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("code_execution_tool_result_error"), error_code: z4.z.string() }) ]) }), // bash code execution results for code_execution_20250825 tool: z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("bash_code_execution_result"), content: z4.z.array( z4.z.object({ type: z4.z.literal("bash_code_execution_output"), file_id: z4.z.string() }) ), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number() }), z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result_error"), error_code: z4.z.string() }) ]) }), // text editor code execution results for code_execution_20250825 tool: z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_view_result"), content: z4.z.string(), file_type: z4.z.string(), num_lines: z4.z.number().nullable(), start_line: z4.z.number().nullable(), total_lines: z4.z.number().nullable() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_create_result"), is_file_update: z4.z.boolean() }), z4.z.object({ type: z4.z.literal( "text_editor_code_execution_str_replace_result" ), lines: z4.z.array(z4.z.string()).nullable(), new_lines: z4.z.number().nullable(), new_start: z4.z.number().nullable(), old_lines: z4.z.number().nullable(), old_start: z4.z.number().nullable() }) ]) }), // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119: z4.z.object({ type: z4.z.literal("tool_search_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("tool_search_tool_search_result"), tool_references: z4.z.array( z4.z.object({ type: z4.z.literal("tool_reference"), tool_name: z4.z.string() }) ) }), z4.z.object({ type: z4.z.literal("tool_search_tool_result_error"), error_code: z4.z.string() }) ]) }), // advisor results for advisor_20260301: z4.z.object({ type: z4.z.literal("advisor_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("advisor_result"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_redacted_result"), encrypted_content: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_tool_result_error"), error_code: z4.z.string() }) ]) }), // Server-side fallback marker. Parsed so the response validates, but // dropped from the content output (the AI SDK has no model-hop // primitive). The hop remains observable via usage.iterations. z4.z.object({ type: z4.z.literal("fallback") }) ]) ), stop_reason: z4.z.string().nullish(), stop_sequence: z4.z.string().nullish(), stop_details: anthropicStopDetailsSchema.nullish(), usage: z4.z.looseObject({ input_tokens: z4.z.number(), output_tokens: z4.z.number(), cache_creation_input_tokens: z4.z.number().nullish(), cache_read_input_tokens: z4.z.number().nullish(), iterations: z4.z.array( z4.z.object({ type: z4.z.union([ z4.z.literal("compaction"), z4.z.literal("message"), z4.z.literal("advisor_message"), z4.z.literal("fallback_message") ]), model: z4.z.string().nullish(), input_tokens: z4.z.number(), output_tokens: z4.z.number(), cache_creation_input_tokens: z4.z.number().nullish(), cache_read_input_tokens: z4.z.number().nullish() }) ).nullish() }), container: z4.z.object({ expires_at: z4.z.string(), id: z4.z.string(), skills: z4.z.array( z4.z.object({ type: z4.z.union([z4.z.literal("anthropic"), z4.z.literal("custom")]), skill_id: z4.z.string(), version: z4.z.string() }) ).nullish() }).nullish(), context_management: z4.z.object({ applied_edits: z4.z.array( z4.z.union([ z4.z.object({ type: z4.z.literal("clear_tool_uses_20250919"), cleared_tool_uses: z4.z.number(), cleared_input_tokens: z4.z.number() }), z4.z.object({ type: z4.z.literal("clear_thinking_20251015"), cleared_thinking_turns: z4.z.number(), cleared_input_tokens: z4.z.number() }), z4.z.object({ type: z4.z.literal("compact_20260112") }) ]) ) }).nullish() }) ) ); var anthropicMessagesChunkSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("message_start"), message: z4.z.object({ id: z4.z.string().nullish(), model: z4.z.string().nullish(), role: z4.z.string().nullish(), usage: z4.z.looseObject({ input_tokens: z4.z.number(), cache_creation_input_tokens: z4.z.number().nullish(), cache_read_input_tokens: z4.z.number().nullish() }), // Programmatic tool calling: content may be pre-populated for deferred tool calls content: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.unknown(), caller: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_20250825"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("code_execution_20260120"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("direct") }) ]).optional() }) ]) ).nullish(), stop_reason: z4.z.string().nullish(), container: z4.z.object({ expires_at: z4.z.string(), id: z4.z.string() }).nullish() }) }), z4.z.object({ type: z4.z.literal("content_block_start"), index: z4.z.number(), content_block: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("text"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("thinking"), thinking: z4.z.string() }), z4.z.object({ type: z4.z.literal("tool_use"), id: z4.z.string(), name: z4.z.string(), // Programmatic tool calling: input may be present directly for deferred tool calls input: z4.z.record(z4.z.string(), z4.z.unknown()).optional(), // Programmatic tool calling: caller info when triggered from code execution caller: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_20250825"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("code_execution_20260120"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("direct") }) ]).optional() }), z4.z.object({ type: z4.z.literal("redacted_thinking"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("compaction"), content: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("server_tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), caller: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_20260120"), tool_id: z4.z.string() }), z4.z.object({ type: z4.z.literal("direct") }) ]).optional() }), z4.z.object({ type: z4.z.literal("mcp_tool_use"), id: z4.z.string(), name: z4.z.string(), input: z4.z.unknown(), server_name: z4.z.string() }), z4.z.object({ type: z4.z.literal("mcp_tool_result"), tool_use_id: z4.z.string(), is_error: z4.z.boolean(), content: z4.z.array( z4.z.union([ z4.z.string(), z4.z.object({ type: z4.z.literal("text"), text: z4.z.string() }) ]) ) }), z4.z.object({ type: z4.z.literal("web_fetch_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("web_fetch_result"), url: z4.z.string(), retrieved_at: z4.z.string(), content: z4.z.object({ type: z4.z.literal("document"), title: z4.z.string().nullable(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), source: z4.z.union([ z4.z.object({ type: z4.z.literal("base64"), media_type: z4.z.literal("application/pdf"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("text"), media_type: z4.z.literal("text/plain"), data: z4.z.string() }) ]) }) }), z4.z.object({ type: z4.z.literal("web_fetch_tool_result_error"), error_code: z4.z.string() }) ]) }), z4.z.object({ type: z4.z.literal("web_search_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.array( z4.z.object({ type: z4.z.literal("web_search_result"), url: z4.z.string(), title: z4.z.string(), encrypted_content: z4.z.string(), page_age: z4.z.string().nullish() }) ), z4.z.object({ type: z4.z.literal("web_search_tool_result_error"), error_code: z4.z.string() }) ]) }), // code execution results for code_execution_20250522 tool: z4.z.object({ type: z4.z.literal("code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("code_execution_result"), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("encrypted_code_execution_result"), encrypted_stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("code_execution_tool_result_error"), error_code: z4.z.string() }) ]) }), // bash code execution results for code_execution_20250825 tool: z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("bash_code_execution_result"), content: z4.z.array( z4.z.object({ type: z4.z.literal("bash_code_execution_output"), file_id: z4.z.string() }) ), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number() }), z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result_error"), error_code: z4.z.string() }) ]) }), // text editor code execution results for code_execution_20250825 tool: z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_view_result"), content: z4.z.string(), file_type: z4.z.string(), num_lines: z4.z.number().nullable(), start_line: z4.z.number().nullable(), total_lines: z4.z.number().nullable() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_create_result"), is_file_update: z4.z.boolean() }), z4.z.object({ type: z4.z.literal( "text_editor_code_execution_str_replace_result" ), lines: z4.z.array(z4.z.string()).nullable(), new_lines: z4.z.number().nullable(), new_start: z4.z.number().nullable(), old_lines: z4.z.number().nullable(), old_start: z4.z.number().nullable() }) ]) }), // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119: z4.z.object({ type: z4.z.literal("tool_search_tool_result"), tool_use_id: z4.z.string(), content: z4.z.union([ z4.z.object({ type: z4.z.literal("tool_search_tool_search_result"), tool_references: z4.z.array( z4.z.object({ type: z4.z.literal("tool_reference"), tool_name: z4.z.string() }) ) }), z4.z.object({ type: z4.z.literal("tool_search_tool_result_error"), error_code: z4.z.string() }) ]) }), // advisor results for advisor_20260301: z4.z.object({ type: z4.z.literal("advisor_tool_result"), tool_use_id: z4.z.string(), content: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("advisor_result"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_redacted_result"), encrypted_content: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_tool_result_error"), error_code: z4.z.string() }) ]) }), // Server-side fallback marker; dropped from content output (see the // response schema). The hop remains observable via usage.iterations. z4.z.object({ type: z4.z.literal("fallback") }) ]) }), z4.z.object({ type: z4.z.literal("content_block_delta"), index: z4.z.number(), delta: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("input_json_delta"), partial_json: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_delta"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("thinking_delta"), thinking: z4.z.string() }), z4.z.object({ type: z4.z.literal("signature_delta"), signature: z4.z.string() }), z4.z.object({ type: z4.z.literal("compaction_delta"), content: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("citations_delta"), citation: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("web_search_result_location"), cited_text: z4.z.string(), url: z4.z.string(), title: z4.z.string(), encrypted_index: z4.z.string() }), z4.z.object({ type: z4.z.literal("page_location"), cited_text: z4.z.string(), document_index: z4.z.number(), document_title: z4.z.string().nullable(), start_page_number: z4.z.number(), end_page_number: z4.z.number() }), z4.z.object({ type: z4.z.literal("char_location"), cited_text: z4.z.string(), document_index: z4.z.number(), document_title: z4.z.string().nullable(), start_char_index: z4.z.number(), end_char_index: z4.z.number() }) ]) }) ]) }), z4.z.object({ type: z4.z.literal("content_block_stop"), index: z4.z.number() }), z4.z.object({ type: z4.z.literal("error"), error: z4.z.object({ type: z4.z.string(), message: z4.z.string() }) }), z4.z.object({ type: z4.z.literal("message_delta"), delta: z4.z.object({ stop_reason: z4.z.string().nullish(), stop_sequence: z4.z.string().nullish(), stop_details: anthropicStopDetailsSchema.nullish(), container: z4.z.object({ expires_at: z4.z.string(), id: z4.z.string(), skills: z4.z.array( z4.z.object({ type: z4.z.union([ z4.z.literal("anthropic"), z4.z.literal("custom") ]), skill_id: z4.z.string(), version: z4.z.string() }) ).nullish() }).nullish() }), usage: z4.z.looseObject({ input_tokens: z4.z.number().nullish(), output_tokens: z4.z.number(), cache_creation_input_tokens: z4.z.number().nullish(), cache_read_input_tokens: z4.z.number().nullish(), iterations: z4.z.array( z4.z.object({ type: z4.z.union([ z4.z.literal("compaction"), z4.z.literal("message"), z4.z.literal("advisor_message"), z4.z.literal("fallback_message") ]), model: z4.z.string().nullish(), input_tokens: z4.z.number(), output_tokens: z4.z.number(), cache_creation_input_tokens: z4.z.number().nullish(), cache_read_input_tokens: z4.z.number().nullish() }) ).nullish() }), context_management: z4.z.object({ applied_edits: z4.z.array( z4.z.union([ z4.z.object({ type: z4.z.literal("clear_tool_uses_20250919"), cleared_tool_uses: z4.z.number(), cleared_input_tokens: z4.z.number() }), z4.z.object({ type: z4.z.literal("clear_thinking_20251015"), cleared_thinking_turns: z4.z.number(), cleared_input_tokens: z4.z.number() }), z4.z.object({ type: z4.z.literal("compact_20260112") }) ]) ) }).nullish() }), z4.z.object({ type: z4.z.literal("message_stop") }), z4.z.object({ type: z4.z.literal("ping") }) ]) ) ); var anthropicReasoningMetadataSchema = lazySchema2( () => zodSchema2( z4.z.object({ signature: z4.z.string().optional(), redactedData: z4.z.string().optional() }) ) ); var anthropicFilePartProviderOptions = z4.z.object({ /** * Citation configuration for this document. * When enabled, this document will generate citations in the response. */ citations: z4.z.object({ /** * Enable citations for this document */ enabled: z4.z.boolean() }).optional(), /** * Custom title for the document. * If not provided, the filename will be used. */ title: z4.z.string().optional(), /** * Context about the document that will be passed to the model * but not used towards cited content. * Useful for storing document metadata as text or stringified JSON. */ context: z4.z.string().optional() }); var anthropicLanguageModelOptions = z4.z.object({ /** * Whether to send reasoning to the model. * * This allows you to deactivate reasoning inputs for models that do not support them. */ sendReasoning: z4.z.boolean().optional(), /** * Determines how structured outputs are generated. * * - `outputFormat`: Use the `output_config.format` parameter to specify the structured output format. * - `jsonTool`: Use a special 'json' tool to specify the structured output format. * - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool' (default). */ structuredOutputMode: z4.z.enum(["outputFormat", "jsonTool", "auto"]).optional(), /** * Configuration for enabling Claude's extended thinking. * * When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer. * Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit. */ thinking: z4.z.discriminatedUnion("type", [ z4.z.object({ /** for Sonnet 4.6, Opus 4.6, and newer models */ type: z4.z.literal("adaptive"), /** * Controls whether thinking content is included in the response. * - `"omitted"`: Thinking blocks are present but text is empty (default for Opus 4.7+). * - `"summarized"`: Thinking content is returned. Required to see reasoning output. */ display: z4.z.enum(["omitted", "summarized"]).optional() }), z4.z.object({ /** for models before Opus 4.6, except Sonnet 4.6 still supports it */ type: z4.z.literal("enabled"), budgetTokens: z4.z.number().optional() }), z4.z.object({ type: z4.z.literal("disabled") }) ]).optional(), /** * Whether to disable parallel function calling during tool use. Default is false. * When set to true, Claude will use at most one tool per response. */ disableParallelToolUse: z4.z.boolean().optional(), /** * Cache control settings for this message. * See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching */ cacheControl: z4.z.object({ type: z4.z.literal("ephemeral"), ttl: z4.z.union([z4.z.literal("5m"), z4.z.literal("1h")]).optional() }).optional(), /** * Metadata to include with the request. * * See https://platform.claude.com/docs/en/api/messages/create for details. */ metadata: z4.z.object({ /** * An external identifier for the user associated with the request. * * Should be a UUID, hash value, or other opaque identifier. * Must not contain PII (name, email, phone number, etc.). */ userId: z4.z.string().optional() }).optional(), /** * MCP servers to be utilized in this request. */ mcpServers: z4.z.array( z4.z.object({ type: z4.z.literal("url"), name: z4.z.string(), url: z4.z.string(), authorizationToken: z4.z.string().nullish(), toolConfiguration: z4.z.object({ enabled: z4.z.boolean().nullish(), allowedTools: z4.z.array(z4.z.string()).nullish() }).nullish() }) ).optional(), /** * Agent Skills configuration. Skills enable Claude to perform specialized tasks * like document processing (PPTX, DOCX, PDF, XLSX) and data analysis. * Requires code execution tool to be enabled. */ container: z4.z.object({ id: z4.z.string().optional(), skills: z4.z.array( z4.z.object({ type: z4.z.union([z4.z.literal("anthropic"), z4.z.literal("custom")]), skillId: z4.z.string(), version: z4.z.string().optional() }) ).optional() }).optional(), /** * Whether to enable fine-grained (eager) streaming of tool call inputs * and structured outputs for every function tool in the request. When * true (the default), each function tool receives a default of * `eager_input_streaming: true` unless it explicitly sets * `providerOptions.anthropic.eagerInputStreaming`. * * @default true */ toolStreaming: z4.z.boolean().optional(), /** * @default 'high' */ effort: z4.z.enum(["low", "medium", "high", "xhigh", "max"]).optional(), /** * Task budget for agentic turns. Informs the model of the total token budget * available for the current task, allowing it to prioritize work and wind down * gracefully as the budget is consumed. * * Advisory only — does not enforce a hard token limit. */ taskBudget: z4.z.object({ type: z4.z.literal("tokens"), total: z4.z.number().int().min(2e4), remaining: z4.z.number().int().min(0).optional() }).optional(), /** * Enable fast mode for faster inference (2.5x faster output token speeds). * Only supported with claude-opus-4-6. */ speed: z4.z.enum(["fast", "standard"]).optional(), /** * Controls where model inference runs for this request. * * - `"global"`: Inference may run in any available geography (default). * - `"us"`: Inference runs only in US-based infrastructure. * * See https://platform.claude.com/docs/en/build-with-claude/data-residency */ inferenceGeo: z4.z.enum(["us", "global"]).optional(), /** * Server-side fallback chain. * * When the primary model's safety classifiers block a turn, the API * automatically retries it on the next model in the chain, server-side. A * `content-filter` finish reason means the entire chain refused. * * Each entry is merged into the request as a direct request to that entry's * model, so it must be formatted accordingly: `model` is required, and an * entry may additionally override `max_tokens`, `thinking`, `output_config`, * and `speed` for that attempt only (`speed` additionally requires the speed * beta). The value is passed through to the API as-is. * * The required `server-side-fallback-2026-06-01` beta is added automatically * when this option is set. */ fallbacks: z4.z.array( z4.z.object({ model: z4.z.string(), max_tokens: z4.z.number().int().optional(), thinking: z4.z.record(z4.z.string(), z4.z.unknown()).optional(), output_config: z4.z.record(z4.z.string(), z4.z.unknown()).optional(), speed: z4.z.enum(["fast", "standard"]).optional() }) ).optional(), /** * A set of beta features to enable. * Allow a provider to receive the full `betas` set if it needs it. */ anthropicBeta: z4.z.array(z4.z.string()).optional(), contextManagement: z4.z.object({ edits: z4.z.array( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("clear_tool_uses_20250919"), trigger: z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("input_tokens"), value: z4.z.number() }), z4.z.object({ type: z4.z.literal("tool_uses"), value: z4.z.number() }) ]).optional(), keep: z4.z.object({ type: z4.z.literal("tool_uses"), value: z4.z.number() }).optional(), clearAtLeast: z4.z.object({ type: z4.z.literal("input_tokens"), value: z4.z.number() }).optional(), clearToolInputs: z4.z.boolean().optional(), excludeTools: z4.z.array(z4.z.string()).optional() }), z4.z.object({ type: z4.z.literal("clear_thinking_20251015"), keep: z4.z.union([ z4.z.literal("all"), z4.z.object({ type: z4.z.literal("thinking_turns"), value: z4.z.number() }) ]).optional() }), z4.z.object({ type: z4.z.literal("compact_20260112"), trigger: z4.z.object({ type: z4.z.literal("input_tokens"), value: z4.z.number() }).optional(), pauseAfterCompaction: z4.z.boolean().optional(), instructions: z4.z.string().optional() }) ]) ) }).optional() }); var MAX_CACHE_BREAKPOINTS = 4; function getCacheControl(providerMetadata) { var _a18; const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic; const cacheControlValue = (_a18 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a18 : anthropic2 == null ? void 0 : anthropic2.cache_control; return cacheControlValue; } var CacheControlValidator = class { constructor() { this.breakpointCount = 0; this.warnings = []; } getCacheControl(providerMetadata, context) { const cacheControlValue = getCacheControl(providerMetadata); if (!cacheControlValue) { return void 0; } if (!context.canCache) { this.warnings.push({ type: "unsupported", feature: "cache_control on non-cacheable context", details: `cache_control cannot be set on ${context.type}. It will be ignored.` }); return void 0; } this.breakpointCount++; if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) { this.warnings.push({ type: "unsupported", feature: "cacheControl breakpoint limit", details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.` }); return void 0; } return cacheControlValue; } getWarnings() { return this.warnings; } }; var advisor_20260301ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ model: z4.z.string(), maxUses: z4.z.number().optional(), caching: z4.z.object({ type: z4.z.literal("ephemeral"), ttl: z4.z.union([z4.z.literal("5m"), z4.z.literal("1h")]) }).optional() }) ) ); var advisor_20260301OutputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("advisor_result"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_redacted_result"), encryptedContent: z4.z.string() }), z4.z.object({ type: z4.z.literal("advisor_tool_result_error"), errorCode: z4.z.string() }) ]) ) ); var advisor_20260301InputSchema = lazySchema2( () => zodSchema2(z4.z.object({}).strict()) ); var factory = createProviderToolFactoryWithOutputSchema({ id: "anthropic.advisor_20260301", inputSchema: advisor_20260301InputSchema, outputSchema: advisor_20260301OutputSchema, supportsDeferredResults: true }); var advisor_20260301 = (args) => { return factory(args); }; var textEditor_20250728ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ maxCharacters: z4.z.number().optional() }) ) ); var textEditor_20250728InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.enum(["view", "create", "str_replace", "insert"]), path: z4.z.string(), file_text: z4.z.string().optional(), insert_line: z4.z.number().int().optional(), new_str: z4.z.string().optional(), insert_text: z4.z.string().optional(), old_str: z4.z.string().optional(), view_range: z4.z.array(z4.z.number().int()).optional() }) ) ); var factory2 = createProviderToolFactory({ id: "anthropic.text_editor_20250728", inputSchema: textEditor_20250728InputSchema }); var textEditor_20250728 = (args = {}) => { return factory2(args); }; var webSearch_20260209ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ maxUses: z4.z.number().optional(), allowedDomains: z4.z.array(z4.z.string()).optional(), blockedDomains: z4.z.array(z4.z.string()).optional(), userLocation: z4.z.object({ type: z4.z.literal("approximate"), city: z4.z.string().optional(), region: z4.z.string().optional(), country: z4.z.string().optional(), timezone: z4.z.string().optional() }).optional() }) ) ); var webSearch_20260209OutputSchema = lazySchema2( () => zodSchema2( z4.z.array( z4.z.object({ url: z4.z.string(), title: z4.z.string().nullable(), pageAge: z4.z.string().nullable(), encryptedContent: z4.z.string(), type: z4.z.literal("web_search_result") }) ) ) ); var webSearch_20260209InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ query: z4.z.string() }) ) ); var factory3 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.web_search_20260209", inputSchema: webSearch_20260209InputSchema, outputSchema: webSearch_20260209OutputSchema, supportsDeferredResults: true }); var webSearch_20260209 = (args = {}) => { return factory3(args); }; var webSearch_20250305ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ maxUses: z4.z.number().optional(), allowedDomains: z4.z.array(z4.z.string()).optional(), blockedDomains: z4.z.array(z4.z.string()).optional(), userLocation: z4.z.object({ type: z4.z.literal("approximate"), city: z4.z.string().optional(), region: z4.z.string().optional(), country: z4.z.string().optional(), timezone: z4.z.string().optional() }).optional() }) ) ); var webSearch_20250305OutputSchema = lazySchema2( () => zodSchema2( z4.z.array( z4.z.object({ url: z4.z.string(), title: z4.z.string().nullable(), pageAge: z4.z.string().nullable(), encryptedContent: z4.z.string(), type: z4.z.literal("web_search_result") }) ) ) ); var webSearch_20250305InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ query: z4.z.string() }) ) ); var factory4 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.web_search_20250305", inputSchema: webSearch_20250305InputSchema, outputSchema: webSearch_20250305OutputSchema, supportsDeferredResults: true }); var webSearch_20250305 = (args = {}) => { return factory4(args); }; var webFetch_20260209ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ maxUses: z4.z.number().optional(), allowedDomains: z4.z.array(z4.z.string()).optional(), blockedDomains: z4.z.array(z4.z.string()).optional(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), maxContentTokens: z4.z.number().optional() }) ) ); var webFetch_20260209OutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("web_fetch_result"), url: z4.z.string(), content: z4.z.object({ type: z4.z.literal("document"), title: z4.z.string().nullable(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), source: z4.z.union([ z4.z.object({ type: z4.z.literal("base64"), mediaType: z4.z.literal("application/pdf"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("text"), mediaType: z4.z.literal("text/plain"), data: z4.z.string() }) ]) }), retrievedAt: z4.z.string().nullable() }) ) ); var webFetch_20260209InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ url: z4.z.string() }) ) ); var factory5 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.web_fetch_20260209", inputSchema: webFetch_20260209InputSchema, outputSchema: webFetch_20260209OutputSchema, supportsDeferredResults: true }); var webFetch_20260209 = (args = {}) => { return factory5(args); }; var webFetch_20250910ArgsSchema = lazySchema2( () => zodSchema2( z4.z.object({ maxUses: z4.z.number().optional(), allowedDomains: z4.z.array(z4.z.string()).optional(), blockedDomains: z4.z.array(z4.z.string()).optional(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), maxContentTokens: z4.z.number().optional() }) ) ); var webFetch_20250910OutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("web_fetch_result"), url: z4.z.string(), content: z4.z.object({ type: z4.z.literal("document"), title: z4.z.string().nullable(), citations: z4.z.object({ enabled: z4.z.boolean() }).optional(), source: z4.z.union([ z4.z.object({ type: z4.z.literal("base64"), mediaType: z4.z.literal("application/pdf"), data: z4.z.string() }), z4.z.object({ type: z4.z.literal("text"), mediaType: z4.z.literal("text/plain"), data: z4.z.string() }) ]) }), retrievedAt: z4.z.string().nullable() }) ) ); var webFetch_20250910InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ url: z4.z.string() }) ) ); var factory6 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.web_fetch_20250910", inputSchema: webFetch_20250910InputSchema, outputSchema: webFetch_20250910OutputSchema, supportsDeferredResults: true }); var webFetch_20250910 = (args = {}) => { return factory6(args); }; async function prepareTools2({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false }) { var _a18, _b18; tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; const betas = /* @__PURE__ */ new Set(); const validator2 = cacheControlValidator || new CacheControlValidator(); if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings, betas }; } const anthropicTools2 = []; for (const tool3 of tools) { switch (tool3.type) { case "function": { const cacheControl = validator2.getCacheControl(tool3.providerOptions, { type: "tool definition", canCache: true }); const anthropicOptions = (_a18 = tool3.providerOptions) == null ? void 0 : _a18.anthropic; const eagerInputStreaming = (_b18 = anthropicOptions == null ? void 0 : anthropicOptions.eagerInputStreaming) != null ? _b18 : defaultEagerInputStreaming; const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading; const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers; if (!supportsStrictTools && tool3.strict != null) { toolWarnings.push({ type: "unsupported", feature: "strict", details: `Tool '${tool3.name}' has strict: ${tool3.strict}, but strict mode is not supported by this provider. The strict property will be ignored.` }); } anthropicTools2.push({ name: tool3.name, description: tool3.description, input_schema: tool3.inputSchema, cache_control: cacheControl, ...eagerInputStreaming ? { eager_input_streaming: true } : {}, ...supportsStrictTools === true && tool3.strict != null ? { strict: tool3.strict } : {}, ...deferLoading != null ? { defer_loading: deferLoading } : {}, ...allowedCallers != null ? { allowed_callers: allowedCallers } : {}, ...tool3.inputExamples != null ? { input_examples: tool3.inputExamples.map( (example) => example.input ) } : {} }); if (supportsStructuredOutput === true) { betas.add("structured-outputs-2025-11-13"); } if (tool3.inputExamples != null || allowedCallers != null) { betas.add("advanced-tool-use-2025-11-20"); } break; } case "provider": { switch (tool3.id) { case "anthropic.code_execution_20250522": { betas.add("code-execution-2025-05-22"); anthropicTools2.push({ type: "code_execution_20250522", name: "code_execution", cache_control: void 0 }); break; } case "anthropic.code_execution_20250825": { betas.add("code-execution-2025-08-25"); anthropicTools2.push({ type: "code_execution_20250825", name: "code_execution" }); break; } case "anthropic.code_execution_20260120": { anthropicTools2.push({ type: "code_execution_20260120", name: "code_execution" }); break; } case "anthropic.computer_20250124": { betas.add("computer-use-2025-01-24"); anthropicTools2.push({ name: "computer", type: "computer_20250124", display_width_px: tool3.args.displayWidthPx, display_height_px: tool3.args.displayHeightPx, display_number: tool3.args.displayNumber, cache_control: void 0 }); break; } case "anthropic.computer_20251124": { betas.add("computer-use-2025-11-24"); anthropicTools2.push({ name: "computer", type: "computer_20251124", display_width_px: tool3.args.displayWidthPx, display_height_px: tool3.args.displayHeightPx, display_number: tool3.args.displayNumber, enable_zoom: tool3.args.enableZoom, cache_control: void 0 }); break; } case "anthropic.computer_20241022": { betas.add("computer-use-2024-10-22"); anthropicTools2.push({ name: "computer", type: "computer_20241022", display_width_px: tool3.args.displayWidthPx, display_height_px: tool3.args.displayHeightPx, display_number: tool3.args.displayNumber, cache_control: void 0 }); break; } case "anthropic.text_editor_20250124": { betas.add("computer-use-2025-01-24"); anthropicTools2.push({ name: "str_replace_editor", type: "text_editor_20250124", cache_control: void 0 }); break; } case "anthropic.text_editor_20241022": { betas.add("computer-use-2024-10-22"); anthropicTools2.push({ name: "str_replace_editor", type: "text_editor_20241022", cache_control: void 0 }); break; } case "anthropic.text_editor_20250429": { betas.add("computer-use-2025-01-24"); anthropicTools2.push({ name: "str_replace_based_edit_tool", type: "text_editor_20250429", cache_control: void 0 }); break; } case "anthropic.text_editor_20250728": { const args = await validateTypes2({ value: tool3.args, schema: textEditor_20250728ArgsSchema }); anthropicTools2.push({ name: "str_replace_based_edit_tool", type: "text_editor_20250728", max_characters: args.maxCharacters, cache_control: void 0 }); break; } case "anthropic.bash_20250124": { betas.add("computer-use-2025-01-24"); anthropicTools2.push({ name: "bash", type: "bash_20250124", cache_control: void 0 }); break; } case "anthropic.bash_20241022": { betas.add("computer-use-2024-10-22"); anthropicTools2.push({ name: "bash", type: "bash_20241022", cache_control: void 0 }); break; } case "anthropic.memory_20250818": { betas.add("context-management-2025-06-27"); anthropicTools2.push({ name: "memory", type: "memory_20250818" }); break; } case "anthropic.web_fetch_20250910": { betas.add("web-fetch-2025-09-10"); const args = await validateTypes2({ value: tool3.args, schema: webFetch_20250910ArgsSchema }); anthropicTools2.push({ type: "web_fetch_20250910", name: "web_fetch", max_uses: args.maxUses, allowed_domains: args.allowedDomains, blocked_domains: args.blockedDomains, citations: args.citations, max_content_tokens: args.maxContentTokens, cache_control: void 0 }); break; } case "anthropic.web_fetch_20260209": { betas.add("code-execution-web-tools-2026-02-09"); const args = await validateTypes2({ value: tool3.args, schema: webFetch_20260209ArgsSchema }); anthropicTools2.push({ type: "web_fetch_20260209", name: "web_fetch", max_uses: args.maxUses, allowed_domains: args.allowedDomains, blocked_domains: args.blockedDomains, citations: args.citations, max_content_tokens: args.maxContentTokens, cache_control: void 0 }); break; } case "anthropic.web_search_20250305": { const args = await validateTypes2({ value: tool3.args, schema: webSearch_20250305ArgsSchema }); anthropicTools2.push({ type: "web_search_20250305", name: "web_search", max_uses: args.maxUses, allowed_domains: args.allowedDomains, blocked_domains: args.blockedDomains, user_location: args.userLocation, cache_control: void 0 }); break; } case "anthropic.web_search_20260209": { betas.add("code-execution-web-tools-2026-02-09"); const args = await validateTypes2({ value: tool3.args, schema: webSearch_20260209ArgsSchema }); anthropicTools2.push({ type: "web_search_20260209", name: "web_search", max_uses: args.maxUses, allowed_domains: args.allowedDomains, blocked_domains: args.blockedDomains, user_location: args.userLocation, cache_control: void 0 }); break; } case "anthropic.tool_search_regex_20251119": { anthropicTools2.push({ type: "tool_search_tool_regex_20251119", name: "tool_search_tool_regex" }); break; } case "anthropic.tool_search_bm25_20251119": { anthropicTools2.push({ type: "tool_search_tool_bm25_20251119", name: "tool_search_tool_bm25" }); break; } case "anthropic.advisor_20260301": { betas.add("advisor-tool-2026-03-01"); const args = await validateTypes2({ value: tool3.args, schema: advisor_20260301ArgsSchema }); anthropicTools2.push({ type: "advisor_20260301", name: "advisor", model: args.model, ...args.maxUses !== void 0 && { max_uses: args.maxUses }, ...args.caching !== void 0 && { caching: args.caching } }); break; } default: { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}` }); break; } } break; } default: { toolWarnings.push({ type: "unsupported", feature: `tool ${tool3}` }); break; } } } if (toolChoice == null) { return { tools: anthropicTools2, toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0, toolWarnings, betas }; } const type = toolChoice.type; switch (type) { case "auto": return { tools: anthropicTools2, toolChoice: { type: "auto", disable_parallel_tool_use: disableParallelToolUse }, toolWarnings, betas }; case "required": return { tools: anthropicTools2, toolChoice: { type: "any", disable_parallel_tool_use: disableParallelToolUse }, toolWarnings, betas }; case "none": return { tools: void 0, toolChoice: void 0, toolWarnings, betas }; case "tool": return { tools: anthropicTools2, toolChoice: { type: "tool", name: toolChoice.toolName, disable_parallel_tool_use: disableParallelToolUse }, toolWarnings, betas }; default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError2({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } function convertAnthropicMessagesUsage({ usage, rawUsage }) { var _a18, _b18, _c; const cacheCreationTokens = (_a18 = usage.cache_creation_input_tokens) != null ? _a18 : 0; const cacheReadTokens = (_b18 = usage.cache_read_input_tokens) != null ? _b18 : 0; let inputTokens; let outputTokens; const servedByFallback = (_c = usage.iterations) == null ? void 0 : _c.some( (iter) => iter.type === "fallback_message" ); if (usage.iterations && usage.iterations.length > 0 && !servedByFallback) { const executorIterations = usage.iterations.filter( (iter) => iter.type === "compaction" || iter.type === "message" ); if (executorIterations.length > 0) { const totals = executorIterations.reduce( (acc, iter) => ({ input: acc.input + iter.input_tokens, output: acc.output + iter.output_tokens }), { input: 0, output: 0 } ); inputTokens = totals.input; outputTokens = totals.output; } else { inputTokens = usage.input_tokens; outputTokens = usage.output_tokens; } } else { inputTokens = usage.input_tokens; outputTokens = usage.output_tokens; } return { inputTokens: { total: inputTokens + cacheCreationTokens + cacheReadTokens, noCache: inputTokens, cacheRead: cacheReadTokens, cacheWrite: cacheCreationTokens }, outputTokens: { total: outputTokens, text: void 0, reasoning: void 0 }, raw: rawUsage != null ? rawUsage : usage }; } var codeExecution_20250522OutputSchema = lazySchema2( () => zodSchema2( z4.z.object({ type: z4.z.literal("code_execution_result"), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }) ) ); var codeExecution_20250522InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ code: z4.z.string() }) ) ); var factory7 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.code_execution_20250522", inputSchema: codeExecution_20250522InputSchema, outputSchema: codeExecution_20250522OutputSchema }); var codeExecution_20250522 = (args = {}) => { return factory7(args); }; var codeExecution_20250825OutputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("code_execution_result"), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("bash_code_execution_result"), content: z4.z.array( z4.z.object({ type: z4.z.literal("bash_code_execution_output"), file_id: z4.z.string() }) ), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number() }), z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_view_result"), content: z4.z.string(), file_type: z4.z.string(), num_lines: z4.z.number().nullable(), start_line: z4.z.number().nullable(), total_lines: z4.z.number().nullable() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_create_result"), is_file_update: z4.z.boolean() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_str_replace_result"), lines: z4.z.array(z4.z.string()).nullable(), new_lines: z4.z.number().nullable(), new_start: z4.z.number().nullable(), old_lines: z4.z.number().nullable(), old_start: z4.z.number().nullable() }) ]) ) ); var codeExecution_20250825InputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ // Programmatic tool calling format (mapped from { code } by AI SDK) z4.z.object({ type: z4.z.literal("programmatic-tool-call"), code: z4.z.string() }), z4.z.object({ type: z4.z.literal("bash_code_execution"), command: z4.z.string() }), z4.z.discriminatedUnion("command", [ z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("view"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("create"), path: z4.z.string(), file_text: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("str_replace"), path: z4.z.string(), old_str: z4.z.string(), new_str: z4.z.string() }) ]) ]) ) ); var factory8 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.code_execution_20250825", inputSchema: codeExecution_20250825InputSchema, outputSchema: codeExecution_20250825OutputSchema, // Programmatic tool calling: tool results may be deferred to a later turn // when code execution triggers a client-executed tool that needs to be // resolved before the code execution result can be returned. supportsDeferredResults: true }); var codeExecution_20250825 = (args = {}) => { return factory8(args); }; var codeExecution_20260120OutputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("code_execution_result"), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("encrypted_code_execution_result"), encrypted_stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number(), content: z4.z.array( z4.z.object({ type: z4.z.literal("code_execution_output"), file_id: z4.z.string() }) ).optional().default([]) }), z4.z.object({ type: z4.z.literal("bash_code_execution_result"), content: z4.z.array( z4.z.object({ type: z4.z.literal("bash_code_execution_output"), file_id: z4.z.string() }) ), stdout: z4.z.string(), stderr: z4.z.string(), return_code: z4.z.number() }), z4.z.object({ type: z4.z.literal("bash_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_tool_result_error"), error_code: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_view_result"), content: z4.z.string(), file_type: z4.z.string(), num_lines: z4.z.number().nullable(), start_line: z4.z.number().nullable(), total_lines: z4.z.number().nullable() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_create_result"), is_file_update: z4.z.boolean() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution_str_replace_result"), lines: z4.z.array(z4.z.string()).nullable(), new_lines: z4.z.number().nullable(), new_start: z4.z.number().nullable(), old_lines: z4.z.number().nullable(), old_start: z4.z.number().nullable() }) ]) ) ); var codeExecution_20260120InputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("programmatic-tool-call"), code: z4.z.string() }), z4.z.object({ type: z4.z.literal("bash_code_execution"), command: z4.z.string() }), z4.z.discriminatedUnion("command", [ z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("view"), path: z4.z.string() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("create"), path: z4.z.string(), file_text: z4.z.string().nullish() }), z4.z.object({ type: z4.z.literal("text_editor_code_execution"), command: z4.z.literal("str_replace"), path: z4.z.string(), old_str: z4.z.string(), new_str: z4.z.string() }) ]) ]) ) ); var factory9 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.code_execution_20260120", inputSchema: codeExecution_20260120InputSchema, outputSchema: codeExecution_20260120OutputSchema, supportsDeferredResults: true }); var codeExecution_20260120 = (args = {}) => { return factory9(args); }; var toolSearchRegex_20251119OutputSchema = lazySchema2( () => zodSchema2( z4.z.array( z4.z.object({ type: z4.z.literal("tool_reference"), toolName: z4.z.string() }) ) ) ); var toolSearchRegex_20251119InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ /** * A regex pattern to search for tools. * Uses Python re.search() syntax. Maximum 200 characters. * * Examples: * - "weather" - matches tool names/descriptions containing "weather" * - "get_.*_data" - matches tools like get_user_data, get_weather_data * - "database.*query|query.*database" - OR patterns for flexibility * - "(?i)slack" - case-insensitive search */ pattern: z4.z.string(), /** * Maximum number of tools to return. Optional. */ limit: z4.z.number().optional() }) ) ); var factory10 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.tool_search_regex_20251119", inputSchema: toolSearchRegex_20251119InputSchema, outputSchema: toolSearchRegex_20251119OutputSchema, supportsDeferredResults: true }); var toolSearchRegex_20251119 = (args = {}) => { return factory10(args); }; function convertToString(data) { if (typeof data === "string") { return new TextDecoder().decode(convertBase64ToUint8Array2(data)); } if (data instanceof Uint8Array) { return new TextDecoder().decode(data); } if (data instanceof URL) { throw new UnsupportedFunctionalityError2({ functionality: "URL-based text documents are not supported for citations" }); } throw new UnsupportedFunctionalityError2({ functionality: `unsupported data type for text documents: ${typeof data}` }); } function isUrlData(data) { return data instanceof URL || isUrlString(data); } function isUrlString(data) { return typeof data === "string" && /^https?:\/\//i.test(data); } function getUrlString(data) { return data instanceof URL ? data.toString() : data; } async function extractErrorValue(value) { if (typeof value === "string") { const result = await safeParseJSON2({ text: value }); if (result.success && typeof result.value === "object" && result.value !== null) { return result.value; } return { errorCode: "unavailable" }; } if (typeof value === "object" && value !== null) { return value; } return {}; } async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u; const betas = /* @__PURE__ */ new Set(); const blocks = groupIntoBlocks(prompt); const validator2 = cacheControlValidator || new CacheControlValidator(); let system = void 0; const messages = []; async function shouldEnableCitations(providerMetadata) { var _a23, _b23; const anthropicOptions = await parseProviderOptions2({ provider: "anthropic", providerOptions: providerMetadata, schema: anthropicFilePartProviderOptions }); return (_b23 = (_a23 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a23.enabled) != null ? _b23 : false; } async function getDocumentMetadata(providerMetadata) { const anthropicOptions = await parseProviderOptions2({ provider: "anthropic", providerOptions: providerMetadata, schema: anthropicFilePartProviderOptions }); return { title: anthropicOptions == null ? void 0 : anthropicOptions.title, context: anthropicOptions == null ? void 0 : anthropicOptions.context }; } for (let i = 0; i < blocks.length; i++) { const block = blocks[i]; const isLastBlock = i === blocks.length - 1; const type = block.type; switch (type) { case "system": { const content = block.messages.map(({ content: content2, providerOptions }) => ({ type: "text", text: content2, cache_control: validator2.getCacheControl(providerOptions, { type: "system message", canCache: true }) })); if (system == null) { system = content; } else { messages.push({ role: "system", content }); betas.add("mid-conversation-system-2026-04-07"); } break; } case "user": { const anthropicContent = []; for (const message of block.messages) { const { role, content } = message; switch (role) { case "user": { for (let j = 0; j < content.length; j++) { const part = content[j]; const isLastPart = j === content.length - 1; const cacheControl = (_a18 = validator2.getCacheControl(part.providerOptions, { type: "user message part", canCache: true })) != null ? _a18 : isLastPart ? validator2.getCacheControl(message.providerOptions, { type: "user message", canCache: true }) : void 0; switch (part.type) { case "text": { anthropicContent.push({ type: "text", text: part.text, cache_control: cacheControl }); break; } case "file": { if (part.mediaType.startsWith("image/")) { anthropicContent.push({ type: "image", source: isUrlData(part.data) ? { type: "url", url: getUrlString(part.data) } : { type: "base64", media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType, data: convertToBase642(part.data) }, cache_control: cacheControl }); } else if (part.mediaType === "application/pdf") { betas.add("pdfs-2024-09-25"); const enableCitations = await shouldEnableCitations( part.providerOptions ); const metadata = await getDocumentMetadata( part.providerOptions ); anthropicContent.push({ type: "document", source: isUrlData(part.data) ? { type: "url", url: getUrlString(part.data) } : { type: "base64", media_type: "application/pdf", data: convertToBase642(part.data) }, title: (_b18 = metadata.title) != null ? _b18 : part.filename, ...metadata.context && { context: metadata.context }, ...enableCitations && { citations: { enabled: true } }, cache_control: cacheControl }); } else if (part.mediaType === "text/plain") { const enableCitations = await shouldEnableCitations( part.providerOptions ); const metadata = await getDocumentMetadata( part.providerOptions ); anthropicContent.push({ type: "document", source: isUrlData(part.data) ? { type: "url", url: getUrlString(part.data) } : { type: "text", media_type: "text/plain", data: convertToString(part.data) }, title: (_c = metadata.title) != null ? _c : part.filename, ...metadata.context && { context: metadata.context }, ...enableCitations && { citations: { enabled: true } }, cache_control: cacheControl }); } else { throw new UnsupportedFunctionalityError2({ functionality: `media type: ${part.mediaType}` }); } break; } } } break; } case "tool": { for (let i2 = 0; i2 < content.length; i2++) { const part = content[i2]; if (part.type === "tool-approval-response") { continue; } const output = part.output; const outputProviderOptions = "providerOptions" in output ? output.providerOptions : output.type === "content" ? (_d = output.value.find( (contentPart) => contentPart.providerOptions != null )) == null ? void 0 : _d.providerOptions : void 0; const isLastPart = i2 === content.length - 1; const cacheControl = (_f = (_e = validator2.getCacheControl(part.providerOptions, { type: "tool result part", canCache: true })) != null ? _e : validator2.getCacheControl(outputProviderOptions, { type: "tool result output", canCache: true })) != null ? _f : isLastPart ? validator2.getCacheControl(message.providerOptions, { type: "tool result message", canCache: true }) : void 0; let contentValue; switch (output.type) { case "content": contentValue = output.value.map((contentPart) => { var _a23; switch (contentPart.type) { case "text": return { type: "text", text: contentPart.text }; case "image-data": { return { type: "image", source: { type: "base64", media_type: contentPart.mediaType, data: contentPart.data } }; } case "image-url": { return { type: "image", source: { type: "url", url: contentPart.url } }; } case "file-url": { return { type: "document", source: { type: "url", url: contentPart.url } }; } case "file-data": { if (contentPart.mediaType === "application/pdf") { betas.add("pdfs-2024-09-25"); return { type: "document", source: { type: "base64", media_type: contentPart.mediaType, data: contentPart.data } }; } warnings.push({ type: "other", message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}` }); return void 0; } case "custom": { const anthropicOptions = (_a23 = contentPart.providerOptions) == null ? void 0 : _a23.anthropic; if ((anthropicOptions == null ? void 0 : anthropicOptions.type) === "tool-reference") { return { type: "tool_reference", tool_name: anthropicOptions.toolName }; } warnings.push({ type: "other", message: `unsupported custom tool content part` }); return void 0; } default: { warnings.push({ type: "other", message: `unsupported tool content part type: ${contentPart.type}` }); return void 0; } } }).filter(isNonNullable); break; case "text": case "error-text": contentValue = output.value; break; case "execution-denied": contentValue = (_g = output.reason) != null ? _g : "Tool execution denied."; break; case "json": case "error-json": default: contentValue = JSON.stringify(output.value); break; } anthropicContent.push({ type: "tool_result", tool_use_id: part.toolCallId, content: contentValue, is_error: output.type === "error-text" || output.type === "error-json" ? true : void 0, cache_control: cacheControl }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } messages.push({ role: "user", content: anthropicContent }); break; } case "assistant": { const anthropicContent = []; const mcpToolUseIds = /* @__PURE__ */ new Set(); for (let j = 0; j < block.messages.length; j++) { const message = block.messages[j]; const isLastMessage = j === block.messages.length - 1; const { content } = message; for (let k = 0; k < content.length; k++) { const part = content[k]; const isLastContentPart = k === content.length - 1; const cacheControl = (_h = validator2.getCacheControl(part.providerOptions, { type: "assistant message part", canCache: true })) != null ? _h : isLastContentPart ? validator2.getCacheControl(message.providerOptions, { type: "assistant message", canCache: true }) : void 0; switch (part.type) { case "text": { const textMetadata = (_i = part.providerOptions) == null ? void 0 : _i.anthropic; if ((textMetadata == null ? void 0 : textMetadata.type) === "compaction") { anthropicContent.push({ type: "compaction", content: part.text, cache_control: cacheControl }); } else { anthropicContent.push({ type: "text", text: ( // trim the last text part if it's the last message in the block // because Anthropic does not allow trailing whitespace // in pre-filled assistant responses isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text ), cache_control: cacheControl }); } break; } case "reasoning": { if (sendReasoning) { const reasoningMetadata = await parseProviderOptions2({ provider: "anthropic", providerOptions: part.providerOptions, schema: anthropicReasoningMetadataSchema }); if (reasoningMetadata != null) { if (reasoningMetadata.signature != null) { validator2.getCacheControl(part.providerOptions, { type: "thinking block", canCache: false }); anthropicContent.push({ type: "thinking", thinking: part.text, signature: reasoningMetadata.signature }); } else if (reasoningMetadata.redactedData != null) { validator2.getCacheControl(part.providerOptions, { type: "redacted thinking block", canCache: false }); anthropicContent.push({ type: "redacted_thinking", data: reasoningMetadata.redactedData }); } else { warnings.push({ type: "other", message: "unsupported reasoning metadata" }); } } else { warnings.push({ type: "other", message: "unsupported reasoning metadata" }); } } else { warnings.push({ type: "other", message: "sending reasoning content is disabled for this model" }); } break; } case "tool-call": { if (part.providerExecuted) { const providerToolName = toolNameMapping.toProviderToolName( part.toolName ); const isMcpToolUse = ((_k = (_j = part.providerOptions) == null ? void 0 : _j.anthropic) == null ? void 0 : _k.type) === "mcp-tool-use"; if (isMcpToolUse) { mcpToolUseIds.add(part.toolCallId); const serverName = (_m = (_l = part.providerOptions) == null ? void 0 : _l.anthropic) == null ? void 0 : _m.serverName; if (serverName == null || typeof serverName !== "string") { warnings.push({ type: "other", message: "mcp tool use server name is required and must be a string" }); break; } anthropicContent.push({ type: "mcp_tool_use", id: part.toolCallId, name: part.toolName, input: part.input, server_name: serverName, cache_control: cacheControl }); } else if ( // code execution 20250825: providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && typeof part.input.type === "string" && (part.input.type === "bash_code_execution" || part.input.type === "text_editor_code_execution") ) { anthropicContent.push({ type: "server_tool_use", id: part.toolCallId, name: part.input.type, // map back to subtool name input: part.input, cache_control: cacheControl }); } else if ( // code execution 20250825 programmatic tool calling: // Strip the fake 'programmatic-tool-call' type before sending to Anthropic providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && part.input.type === "programmatic-tool-call" ) { const { type: _, ...inputWithoutType } = part.input; anthropicContent.push({ type: "server_tool_use", id: part.toolCallId, name: "code_execution", input: inputWithoutType, cache_control: cacheControl }); } else { if (providerToolName === "code_execution" || // code execution 20250522 providerToolName === "web_fetch" || providerToolName === "web_search") { anthropicContent.push({ type: "server_tool_use", id: part.toolCallId, name: providerToolName, input: part.input, cache_control: cacheControl }); } else if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") { anthropicContent.push({ type: "server_tool_use", id: part.toolCallId, name: providerToolName, input: part.input, cache_control: cacheControl }); } else if (providerToolName === "advisor") { anthropicContent.push({ type: "server_tool_use", id: part.toolCallId, name: "advisor", input: {}, cache_control: cacheControl }); } else { warnings.push({ type: "other", message: `provider executed tool call for tool ${part.toolName} is not supported` }); } } break; } const callerOptions = (_n = part.providerOptions) == null ? void 0 : _n.anthropic; const caller = (callerOptions == null ? void 0 : callerOptions.caller) ? (callerOptions.caller.type === "code_execution_20250825" || callerOptions.caller.type === "code_execution_20260120") && callerOptions.caller.toolId ? { type: callerOptions.caller.type, tool_id: callerOptions.caller.toolId } : callerOptions.caller.type === "direct" ? { type: "direct" } : void 0 : void 0; anthropicContent.push({ type: "tool_use", id: part.toolCallId, name: part.toolName, input: part.input, ...caller && { caller }, cache_control: cacheControl }); break; } case "tool-result": { const providerToolName = toolNameMapping.toProviderToolName( part.toolName ); if (mcpToolUseIds.has(part.toolCallId)) { const output = part.output; if (output.type !== "json" && output.type !== "error-json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } anthropicContent.push({ type: "mcp_tool_result", tool_use_id: part.toolCallId, is_error: output.type === "error-json", content: output.value, cache_control: cacheControl }); } else if (providerToolName === "code_execution") { const output = part.output; if (output.type === "error-text" || output.type === "error-json") { let errorInfo = {}; try { if (typeof output.value === "string") { errorInfo = JSON.parse(output.value); } else if (typeof output.value === "object" && output.value !== null) { errorInfo = output.value; } } catch (e) { } if (errorInfo.type === "code_execution_tool_result_error") { anthropicContent.push({ type: "code_execution_tool_result", tool_use_id: part.toolCallId, content: { type: "code_execution_tool_result_error", error_code: (_o = errorInfo.errorCode) != null ? _o : "unknown" }, cache_control: cacheControl }); } else { anthropicContent.push({ type: "bash_code_execution_tool_result", tool_use_id: part.toolCallId, cache_control: cacheControl, content: { type: "bash_code_execution_tool_result_error", error_code: (_p = errorInfo.errorCode) != null ? _p : "unknown" } }); } break; } if (output.type !== "json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } if (output.value == null || typeof output.value !== "object" || !("type" in output.value) || typeof output.value.type !== "string") { warnings.push({ type: "other", message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}` }); break; } if (output.value.type === "code_execution_result") { const codeExecutionOutput = await validateTypes2({ value: output.value, schema: codeExecution_20250522OutputSchema }); anthropicContent.push({ type: "code_execution_tool_result", tool_use_id: part.toolCallId, content: { type: codeExecutionOutput.type, stdout: codeExecutionOutput.stdout, stderr: codeExecutionOutput.stderr, return_code: codeExecutionOutput.return_code, content: (_q = codeExecutionOutput.content) != null ? _q : [] }, cache_control: cacheControl }); } else if (output.value.type === "encrypted_code_execution_result") { const codeExecutionOutput = await validateTypes2({ value: output.value, schema: codeExecution_20260120OutputSchema }); if (codeExecutionOutput.type === "encrypted_code_execution_result") { anthropicContent.push({ type: "code_execution_tool_result", tool_use_id: part.toolCallId, content: { type: codeExecutionOutput.type, encrypted_stdout: codeExecutionOutput.encrypted_stdout, stderr: codeExecutionOutput.stderr, return_code: codeExecutionOutput.return_code, content: (_r = codeExecutionOutput.content) != null ? _r : [] }, cache_control: cacheControl }); } } else { const codeExecutionOutput = await validateTypes2({ value: output.value, schema: codeExecution_20250825OutputSchema }); if (codeExecutionOutput.type === "code_execution_result") { anthropicContent.push({ type: "code_execution_tool_result", tool_use_id: part.toolCallId, content: { type: codeExecutionOutput.type, stdout: codeExecutionOutput.stdout, stderr: codeExecutionOutput.stderr, return_code: codeExecutionOutput.return_code, content: (_s = codeExecutionOutput.content) != null ? _s : [] }, cache_control: cacheControl }); } else if (codeExecutionOutput.type === "bash_code_execution_result" || codeExecutionOutput.type === "bash_code_execution_tool_result_error") { anthropicContent.push({ type: "bash_code_execution_tool_result", tool_use_id: part.toolCallId, cache_control: cacheControl, content: codeExecutionOutput }); } else { anthropicContent.push({ type: "text_editor_code_execution_tool_result", tool_use_id: part.toolCallId, cache_control: cacheControl, content: codeExecutionOutput }); } } break; } if (providerToolName === "web_fetch") { const output = part.output; if (output.type === "error-json") { anthropicContent.push({ type: "web_fetch_tool_result", tool_use_id: part.toolCallId, content: { type: "web_fetch_tool_result_error", error_code: (_t = (await extractErrorValue(output.value)).errorCode) != null ? _t : "unavailable" }, cache_control: cacheControl }); break; } if (output.type !== "json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } const webFetchOutput = await validateTypes2({ value: output.value, schema: webFetch_20250910OutputSchema }); anthropicContent.push({ type: "web_fetch_tool_result", tool_use_id: part.toolCallId, content: { type: "web_fetch_result", url: webFetchOutput.url, retrieved_at: webFetchOutput.retrievedAt, content: { type: "document", title: webFetchOutput.content.title, citations: webFetchOutput.content.citations, source: { type: webFetchOutput.content.source.type, media_type: webFetchOutput.content.source.mediaType, data: webFetchOutput.content.source.data } } }, cache_control: cacheControl }); break; } if (providerToolName === "web_search") { const output = part.output; if (output.type === "error-json") { anthropicContent.push({ type: "web_search_tool_result", tool_use_id: part.toolCallId, content: { type: "web_search_tool_result_error", error_code: (_u = (await extractErrorValue(output.value)).errorCode) != null ? _u : "unavailable" }, cache_control: cacheControl }); break; } if (output.type !== "json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } const webSearchOutput = await validateTypes2({ value: output.value, schema: webSearch_20250305OutputSchema }); anthropicContent.push({ type: "web_search_tool_result", tool_use_id: part.toolCallId, content: webSearchOutput.map((result) => ({ url: result.url, title: result.title, page_age: result.pageAge, encrypted_content: result.encryptedContent, type: result.type })), cache_control: cacheControl }); break; } if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") { const output = part.output; if (output.type !== "json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } const toolSearchOutput = await validateTypes2({ value: output.value, schema: toolSearchRegex_20251119OutputSchema }); const toolReferences = toolSearchOutput.map((ref) => ({ type: "tool_reference", tool_name: ref.toolName })); anthropicContent.push({ type: "tool_search_tool_result", tool_use_id: part.toolCallId, content: { type: "tool_search_tool_search_result", tool_references: toolReferences }, cache_control: cacheControl }); break; } if (providerToolName === "advisor") { const output = part.output; if (output.type !== "json" && output.type !== "error-json") { warnings.push({ type: "other", message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` }); break; } const advisorOutput = await validateTypes2({ value: output.value, schema: advisor_20260301OutputSchema }); if (advisorOutput.type === "advisor_result") { anthropicContent.push({ type: "advisor_tool_result", tool_use_id: part.toolCallId, content: { type: "advisor_result", text: advisorOutput.text }, cache_control: cacheControl }); } else if (advisorOutput.type === "advisor_redacted_result") { anthropicContent.push({ type: "advisor_tool_result", tool_use_id: part.toolCallId, content: { type: "advisor_redacted_result", encrypted_content: advisorOutput.encryptedContent }, cache_control: cacheControl }); } else { anthropicContent.push({ type: "advisor_tool_result", tool_use_id: part.toolCallId, content: { type: "advisor_tool_result_error", error_code: advisorOutput.errorCode }, cache_control: cacheControl }); } break; } warnings.push({ type: "other", message: `provider executed tool result for tool ${part.toolName} is not supported` }); break; } } } } messages.push({ role: "assistant", content: anthropicContent }); break; } default: { const _exhaustiveCheck = type; throw new Error(`content type: ${_exhaustiveCheck}`); } } } return { prompt: { system, messages }, betas }; } function groupIntoBlocks(prompt) { const blocks = []; let currentBlock = void 0; for (const message of prompt) { const { role } = message; switch (role) { case "system": { if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") { currentBlock = { type: "system", messages: [] }; blocks.push(currentBlock); } currentBlock.messages.push(message); break; } case "assistant": { if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") { currentBlock = { type: "assistant", messages: [] }; blocks.push(currentBlock); } currentBlock.messages.push(message); break; } case "user": { if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") { currentBlock = { type: "user", messages: [] }; blocks.push(currentBlock); } currentBlock.messages.push(message); break; } case "tool": { if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") { currentBlock = { type: "user", messages: [] }; blocks.push(currentBlock); } currentBlock.messages.push(message); break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return blocks; } function mapAnthropicStopReason({ finishReason, isJsonResponseFromTool }) { switch (finishReason) { case "pause_turn": case "end_turn": case "stop_sequence": return "stop"; case "refusal": return "content-filter"; case "tool_use": return isJsonResponseFromTool ? "stop" : "tool-calls"; case "max_tokens": case "model_context_window_exceeded": return "length"; case "compaction": return "other"; default: return "other"; } } var SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([ "date-time", "time", "date", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid" ]); var DESCRIPTION_CONSTRAINT_KEYS = [ "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minLength", "maxLength", "pattern", "minItems", "maxItems", "uniqueItems", "minProperties", "maxProperties", "not" ]; function sanitizeJsonSchema(schema) { return sanitizeSchema(schema); } function sanitizeDefinition(definition) { if (typeof definition === "boolean" || !isPlainObject(definition)) { return definition; } return sanitizeSchema(definition); } function sanitizeSchema(schema) { const result = {}; const schemaWithDefs = schema; if (schema.$ref != null) { return { $ref: schema.$ref }; } if (schema.$schema != null) { result.$schema = schema.$schema; } if (schema.$id != null) { result.$id = schema.$id; } if (schema.title != null) { result.title = schema.title; } if (schema.description != null) { result.description = schema.description; } if (schema.default !== void 0) { result.default = schema.default; } if (schema.const !== void 0) { result.const = schema.const; } if (schema.enum != null) { result.enum = schema.enum; } if (schema.type != null) { result.type = schema.type; } if (schema.anyOf != null) { result.anyOf = schema.anyOf.map(sanitizeDefinition); } else if (schema.oneOf != null) { result.anyOf = schema.oneOf.map(sanitizeDefinition); } if (schema.allOf != null) { result.allOf = schema.allOf.map(sanitizeDefinition); } if (schema.definitions != null) { result.definitions = Object.fromEntries( Object.entries(schema.definitions).map(([name17, definition]) => [ name17, sanitizeDefinition(definition) ]) ); } if (schemaWithDefs.$defs != null) { const resultWithDefs = result; resultWithDefs.$defs = Object.fromEntries( Object.entries(schemaWithDefs.$defs).map(([name17, definition]) => [ name17, sanitizeDefinition(definition) ]) ); } if (schema.type === "object" || schema.properties != null) { if (schema.properties != null) { result.properties = Object.fromEntries( Object.entries(schema.properties).map(([name17, definition]) => [ name17, sanitizeDefinition(definition) ]) ); } result.additionalProperties = false; if (schema.required != null) { result.required = schema.required; } } if (schema.items != null) { result.items = Array.isArray(schema.items) ? schema.items.map(sanitizeDefinition) : sanitizeDefinition(schema.items); } if (typeof schema.format === "string" && SUPPORTED_STRING_FORMATS.has(schema.format)) { result.format = schema.format; } const constraintDescription = getConstraintDescription(schema); if (constraintDescription != null) { result.description = result.description == null ? constraintDescription : `${result.description} ${constraintDescription}`; } return result; } function getConstraintDescription(schema) { const descriptions = DESCRIPTION_CONSTRAINT_KEYS.flatMap((key) => { const value = schema[key]; if (value == null || value === false) { return []; } return `${formatConstraintName(key)}: ${formatConstraintValue(value)}`; }); if (typeof schema.format === "string" && !SUPPORTED_STRING_FORMATS.has(schema.format)) { descriptions.push(`format: ${schema.format}`); } return descriptions.length === 0 ? void 0 : `${descriptions.join("; ")}.`; } function formatConstraintName(key) { return key.replace(/[A-Z]/g, (match) => ` ${match.toLowerCase()}`); } function formatConstraintValue(value) { if (typeof value === "string") { return value; } return JSON.stringify(value); } function isPlainObject(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function createCitationSource(citation, citationDocuments, generateId3) { var _a18; if (citation.type === "web_search_result_location") { return { type: "source", sourceType: "url", id: generateId3(), url: citation.url, title: citation.title, providerMetadata: { anthropic: { citedText: citation.cited_text, encryptedIndex: citation.encrypted_index } } }; } if (citation.type !== "page_location" && citation.type !== "char_location") { return; } const documentInfo = citationDocuments[citation.document_index]; if (!documentInfo) { return; } return { type: "source", sourceType: "document", id: generateId3(), mediaType: documentInfo.mediaType, title: (_a18 = citation.document_title) != null ? _a18 : documentInfo.title, filename: documentInfo.filename, providerMetadata: { anthropic: citation.type === "page_location" ? { citedText: citation.cited_text, startPageNumber: citation.start_page_number, endPageNumber: citation.end_page_number } : { citedText: citation.cited_text, startCharIndex: citation.start_char_index, endCharIndex: citation.end_char_index } } }; } var AnthropicMessagesLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; var _a18; this.modelId = modelId; this.config = config; this.generateId = (_a18 = config.generateId) != null ? _a18 : generateId2; } supportsUrl(url) { return url.protocol === "https:"; } get provider() { return this.config.provider; } /** * Extracts the dynamic provider name from the config.provider string. * e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic' */ get providerOptionsName() { const provider = this.config.provider; const dotIndex = provider.indexOf("."); return dotIndex === -1 ? provider : provider.substring(0, dotIndex); } get supportedUrls() { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).supportedUrls) == null ? void 0 : _b18.call(_a18)) != null ? _c : {}; } async getArgs({ userSuppliedBetas, prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions, stream }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j; const warnings = []; if (frequencyPenalty != null) { warnings.push({ type: "unsupported", feature: "frequencyPenalty" }); } if (presencePenalty != null) { warnings.push({ type: "unsupported", feature: "presencePenalty" }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed" }); } if (temperature != null && temperature > 1) { warnings.push({ type: "unsupported", feature: "temperature", details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0` }); temperature = 1; } else if (temperature != null && temperature < 0) { warnings.push({ type: "unsupported", feature: "temperature", details: `${temperature} is below anthropic minimum of 0. clamped to 0` }); temperature = 0; } if ((responseFormat == null ? void 0 : responseFormat.type) === "json") { if (responseFormat.schema == null) { warnings.push({ type: "unsupported", feature: "responseFormat", details: "JSON response format requires a schema. The response format is ignored." }); } } const providerOptionsName = this.providerOptionsName; const canonicalOptions = await parseProviderOptions2({ provider: "anthropic", providerOptions, schema: anthropicLanguageModelOptions }); const customProviderOptions = providerOptionsName !== "anthropic" ? await parseProviderOptions2({ provider: providerOptionsName, providerOptions, schema: anthropicLanguageModelOptions }) : null; const usedCustomProviderKey = customProviderOptions != null; const anthropicOptions = Object.assign( {}, canonicalOptions != null ? canonicalOptions : {}, customProviderOptions != null ? customProviderOptions : {} ); const { maxOutputTokens: maxOutputTokensForModel, supportsStructuredOutput: modelSupportsStructuredOutput, rejectsSamplingParameters, isKnownModel } = getModelCapabilities(this.modelId); if (rejectsSamplingParameters) { if (temperature != null) { warnings.push({ type: "unsupported", feature: "temperature", details: `temperature is not supported by ${this.modelId} and will be ignored` }); temperature = void 0; } if (topK != null) { warnings.push({ type: "unsupported", feature: "topK", details: `topK is not supported by ${this.modelId} and will be ignored` }); topK = void 0; } if (topP != null) { warnings.push({ type: "unsupported", feature: "topP", details: `topP is not supported by ${this.modelId} and will be ignored` }); topP = void 0; } } const isAnthropicModel = isKnownModel || this.modelId.startsWith("claude-"); const supportsStructuredOutput = ((_a18 = this.config.supportsNativeStructuredOutput) != null ? _a18 : true) && modelSupportsStructuredOutput; const supportsStrictTools = ((_b18 = this.config.supportsStrictTools) != null ? _b18 : true) && modelSupportsStructuredOutput; const structureOutputMode = (_c = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _c : "auto"; const useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput; const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useStructuredOutput ? { type: "function", name: "json", description: "Respond with a JSON object.", inputSchema: responseFormat.schema } : void 0; const contextManagement = anthropicOptions == null ? void 0 : anthropicOptions.contextManagement; const cacheControlValidator = new CacheControlValidator(); const toolNameMapping = createToolNameMapping({ tools, providerToolNames: { "anthropic.code_execution_20250522": "code_execution", "anthropic.code_execution_20250825": "code_execution", "anthropic.code_execution_20260120": "code_execution", "anthropic.computer_20241022": "computer", "anthropic.computer_20250124": "computer", "anthropic.text_editor_20241022": "str_replace_editor", "anthropic.text_editor_20250124": "str_replace_editor", "anthropic.text_editor_20250429": "str_replace_based_edit_tool", "anthropic.text_editor_20250728": "str_replace_based_edit_tool", "anthropic.bash_20241022": "bash", "anthropic.bash_20250124": "bash", "anthropic.memory_20250818": "memory", "anthropic.web_search_20250305": "web_search", "anthropic.web_search_20260209": "web_search", "anthropic.web_fetch_20250910": "web_fetch", "anthropic.web_fetch_20260209": "web_fetch", "anthropic.tool_search_regex_20251119": "tool_search_tool_regex", "anthropic.tool_search_bm25_20251119": "tool_search_tool_bm25", "anthropic.advisor_20260301": "advisor" } }); const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({ prompt, sendReasoning: (_d = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _d : true, warnings, cacheControlValidator, toolNameMapping }); const thinkingType = (_e = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _e.type; const isThinking = thinkingType === "enabled" || thinkingType === "adaptive"; let thinkingBudget = thinkingType === "enabled" ? (_f = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _f.budgetTokens : void 0; const thinkingDisplay = thinkingType === "adaptive" ? (_g = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _g.display : void 0; const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel; const baseArgs = { // model id: model: this.modelId, // standardized settings: max_tokens: maxTokens, temperature, top_k: topK, top_p: topP, stop_sequences: stopSequences, // provider specific settings: ...isThinking && { thinking: { type: thinkingType, ...thinkingBudget != null && { budget_tokens: thinkingBudget }, ...thinkingDisplay != null && { display: thinkingDisplay } } }, ...((anthropicOptions == null ? void 0 : anthropicOptions.effort) || (anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) || useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) && { output_config: { ...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && { effort: anthropicOptions.effort }, ...(anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) && { task_budget: { type: anthropicOptions.taskBudget.type, total: anthropicOptions.taskBudget.total, ...anthropicOptions.taskBudget.remaining != null && { remaining: anthropicOptions.taskBudget.remaining } } }, ...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && { format: { type: "json_schema", schema: sanitizeJsonSchema(responseFormat.schema) } } } }, ...(anthropicOptions == null ? void 0 : anthropicOptions.speed) && { speed: anthropicOptions.speed }, ...(anthropicOptions == null ? void 0 : anthropicOptions.inferenceGeo) && { inference_geo: anthropicOptions.inferenceGeo }, ...(anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0 && { fallbacks: anthropicOptions.fallbacks }, ...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && { cache_control: anthropicOptions.cacheControl }, ...((_h = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _h.userId) != null && { metadata: { user_id: anthropicOptions.metadata.userId } }, // mcp servers: ...(anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && { mcp_servers: anthropicOptions.mcpServers.map((server) => ({ type: server.type, name: server.name, url: server.url, authorization_token: server.authorizationToken, tool_configuration: server.toolConfiguration ? { allowed_tools: server.toolConfiguration.allowedTools, enabled: server.toolConfiguration.enabled } : void 0 })) }, // container: For programmatic tool calling (just an ID string) or agent skills (object with id and skills) ...(anthropicOptions == null ? void 0 : anthropicOptions.container) && { container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? ( // Object format when skills are provided (agent skills feature) { id: anthropicOptions.container.id, skills: anthropicOptions.container.skills.map((skill) => ({ type: skill.type, skill_id: skill.skillId, version: skill.version })) } ) : ( // String format for container ID only (programmatic tool calling) anthropicOptions.container.id ) }, // prompt: system: messagesPrompt.system, messages: messagesPrompt.messages, ...contextManagement && { context_management: { edits: contextManagement.edits.map((edit) => { const strategy = edit.type; switch (strategy) { case "clear_tool_uses_20250919": return { type: edit.type, ...edit.trigger !== void 0 && { trigger: edit.trigger }, ...edit.keep !== void 0 && { keep: edit.keep }, ...edit.clearAtLeast !== void 0 && { clear_at_least: edit.clearAtLeast }, ...edit.clearToolInputs !== void 0 && { clear_tool_inputs: edit.clearToolInputs }, ...edit.excludeTools !== void 0 && { exclude_tools: edit.excludeTools } }; case "clear_thinking_20251015": return { type: edit.type, ...edit.keep !== void 0 && { keep: edit.keep } }; case "compact_20260112": return { type: edit.type, ...edit.trigger !== void 0 && { trigger: edit.trigger }, ...edit.pauseAfterCompaction !== void 0 && { pause_after_compaction: edit.pauseAfterCompaction }, ...edit.instructions !== void 0 && { instructions: edit.instructions } }; default: warnings.push({ type: "other", message: `Unknown context management strategy: ${strategy}` }); return void 0; } }).filter((edit) => edit !== void 0) } } }; if (isThinking) { if (thinkingType === "enabled" && thinkingBudget == null) { warnings.push({ type: "compatibility", feature: "extended thinking", details: "thinking budget is required when thinking is enabled. using default budget of 1024 tokens." }); baseArgs.thinking = { type: "enabled", budget_tokens: 1024 }; thinkingBudget = 1024; } if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported when thinking is enabled" }); } if (topK != null) { baseArgs.top_k = void 0; warnings.push({ type: "unsupported", feature: "topK", details: "topK is not supported when thinking is enabled" }); } if (topP != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported", feature: "topP", details: "topP is not supported when thinking is enabled" }); } baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0); } else { if (isAnthropicModel && topP != null && temperature != null) { warnings.push({ type: "unsupported", feature: "topP", details: `topP is not supported when temperature is set. topP is ignored.` }); baseArgs.top_p = void 0; } } if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) { if (maxOutputTokens != null) { warnings.push({ type: "unsupported", feature: "maxOutputTokens", details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.` }); } baseArgs.max_tokens = maxOutputTokensForModel; } if ((anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) { betas.add("mcp-client-2025-04-04"); } if (contextManagement) { betas.add("context-management-2025-06-27"); if (contextManagement.edits.some((e) => e.type === "compact_20260112")) { betas.add("compact-2026-01-12"); } } if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) { betas.add("code-execution-2025-08-25"); betas.add("skills-2025-10-02"); betas.add("files-api-2025-04-14"); if (!(tools == null ? void 0 : tools.some( (tool3) => tool3.type === "provider" && (tool3.id === "anthropic.code_execution_20250825" || tool3.id === "anthropic.code_execution_20260120") ))) { warnings.push({ type: "other", message: "code execution tool is required when using skills" }); } } if (anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) { betas.add("task-budgets-2026-03-13"); } if ((anthropicOptions == null ? void 0 : anthropicOptions.speed) === "fast") { betas.add("fast-mode-2026-02-01"); } if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) { betas.add("server-side-fallback-2026-06-01"); } const defaultEagerInputStreaming = stream && ((_i = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _i : true); const { tools: anthropicTools2, toolChoice: anthropicToolChoice, toolWarnings, betas: toolsBetas } = await prepareTools2( jsonResponseTool != null ? { tools: [...tools != null ? tools : [], jsonResponseTool], toolChoice: { type: "required" }, disableParallelToolUse: true, cacheControlValidator, supportsStructuredOutput: false, supportsStrictTools, defaultEagerInputStreaming } : { tools: tools != null ? tools : [], toolChoice, disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming } ); const cacheWarnings = cacheControlValidator.getWarnings(); return { args: { ...baseArgs, tools: anthropicTools2, tool_choice: anthropicToolChoice, stream: stream === true ? true : void 0 // do not send when not streaming }, warnings: [...warnings, ...toolWarnings, ...cacheWarnings], betas: /* @__PURE__ */ new Set([ ...betas, ...toolsBetas, ...userSuppliedBetas, ...(_j = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _j : [] ]), usesJsonResponseTool: jsonResponseTool != null, toolNameMapping, providerOptionsName, usedCustomProviderKey }; } async getHeaders({ betas, headers }) { return combineHeaders2( await resolve2(this.config.headers), headers, betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {} ); } async getBetasFromHeaders(requestHeaders) { var _a18, _b18; const configHeaders = await resolve2(this.config.headers); const configBetaHeader = (_a18 = configHeaders["anthropic-beta"]) != null ? _a18 : ""; const requestBetaHeader = (_b18 = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b18 : ""; return new Set( [ ...configBetaHeader.toLowerCase().split(","), ...requestBetaHeader.toLowerCase().split(",") ].map((beta) => beta.trim()).filter((beta) => beta !== "") ); } buildRequestUrl(isStreaming) { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).buildRequestUrl) == null ? void 0 : _b18.call(_a18, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`; } transformRequestBody(args, betas) { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).transformRequestBody) == null ? void 0 : _b18.call(_a18, args, betas)) != null ? _c : args; } extractCitationDocuments(prompt) { const isCitationPart = (part) => { var _a18, _b18; if (part.type !== "file") { return false; } if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") { return false; } const anthropic2 = (_a18 = part.providerOptions) == null ? void 0 : _a18.anthropic; const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations; return (_b18 = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b18 : false; }; return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => { var _a18; const filePart = part; return { title: (_a18 = filePart.filename) != null ? _a18 : "Untitled Document", filename: filePart.filename, mediaType: filePart.mediaType }; }); } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f, _g; const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({ ...options, stream: false, userSuppliedBetas: await this.getBetasFromHeaders(options.headers) }); const citationDocuments = [ ...this.extractCitationDocuments(options.prompt) ]; const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution( args.tools ); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi2({ url: this.buildRequestUrl(false), headers: await this.getHeaders({ betas, headers: options.headers }), body: this.transformRequestBody(args, betas), failedResponseHandler: anthropicFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( anthropicMessagesResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const content = []; const mcpToolCalls = {}; const serverToolCalls = {}; let isJsonResponseFromTool = false; for (const part of response.content) { switch (part.type) { case "text": { if (!usesJsonResponseTool) { content.push({ type: "text", text: part.text }); if (part.citations) { for (const citation of part.citations) { const source = createCitationSource( citation, citationDocuments, this.generateId ); if (source) { content.push(source); } } } } break; } case "thinking": { content.push({ type: "reasoning", text: part.thinking, providerMetadata: { anthropic: { signature: part.signature } } }); break; } case "redacted_thinking": { content.push({ type: "reasoning", text: "", providerMetadata: { anthropic: { redactedData: part.data } } }); break; } case "compaction": { content.push({ type: "text", text: part.content, providerMetadata: { anthropic: { type: "compaction" } } }); break; } case "tool_use": { const isJsonResponseTool = usesJsonResponseTool && part.name === "json"; if (isJsonResponseTool) { isJsonResponseFromTool = true; content.push({ type: "text", text: JSON.stringify(part.input) }); } else { const caller = part.caller; const callerInfo = caller ? { type: caller.type, toolId: "tool_id" in caller ? caller.tool_id : void 0 } : void 0; content.push({ type: "tool-call", toolCallId: part.id, toolName: part.name, input: JSON.stringify(part.input), ...callerInfo && { providerMetadata: { anthropic: { caller: callerInfo } } } }); } break; } case "server_tool_use": { if (part.name === "text_editor_code_execution" || part.name === "bash_code_execution") { const providerToolName = "code_execution"; content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("code_execution"), input: JSON.stringify({ type: part.name, ...part.input }), providerExecuted: true, // Specific 'web_fetch' or 'web_search' tools may need code execution, which the Anthropic API // implicitly allows. In this scenario, we need to allow 'code_execution' tool calls even if the // tool was not explicitly provided. We therefore bypass the general validation by marking the // tool as dynamic. ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {} }); } else if (part.name === "web_search" || part.name === "code_execution" || part.name === "web_fetch") { const inputToSerialize = part.name === "code_execution" && part.input != null && typeof part.input === "object" && "code" in part.input && !("type" in part.input) ? { type: "programmatic-tool-call", ...part.input } : part.input; content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName(part.name), input: JSON.stringify(inputToSerialize), providerExecuted: true, // Specific 'web_fetch' or 'web_search' tools may need code execution, which the Anthropic API // implicitly allows. In this scenario, we need to allow 'code_execution' tool calls even if the // tool was not explicitly provided. We therefore bypass the general validation by marking the // tool as dynamic. ...markCodeExecutionDynamic && part.name === "code_execution" ? { dynamic: true } : {} }); } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") { serverToolCalls[part.id] = part.name; content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName(part.name), input: JSON.stringify(part.input), providerExecuted: true }); } else if (part.name === "advisor") { content.push({ type: "tool-call", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName("advisor"), input: JSON.stringify(part.input), providerExecuted: true }); } break; } case "mcp_tool_use": { mcpToolCalls[part.id] = { type: "tool-call", toolCallId: part.id, toolName: part.name, input: JSON.stringify(part.input), providerExecuted: true, dynamic: true, providerMetadata: { anthropic: { type: "mcp-tool-use", serverName: part.server_name } } }; content.push(mcpToolCalls[part.id]); break; } case "mcp_tool_result": { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: mcpToolCalls[part.tool_use_id].toolName, isError: part.is_error, result: part.content, dynamic: true, providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata }); break; } case "web_fetch_tool_result": { if (part.content.type === "web_fetch_result") { citationDocuments.push({ title: (_a18 = part.content.content.title) != null ? _a18 : part.content.url, mediaType: part.content.content.source.media_type }); content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_fetch"), result: { type: "web_fetch_result", url: part.content.url, retrievedAt: part.content.retrieved_at, content: { type: part.content.content.type, title: part.content.content.title, citations: part.content.content.citations, source: { type: part.content.content.source.type, mediaType: part.content.content.source.media_type, data: part.content.content.source.data } } } }); } else if (part.content.type === "web_fetch_tool_result_error") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_fetch"), isError: true, result: { type: "web_fetch_tool_result_error", errorCode: part.content.error_code } }); } break; } case "web_search_tool_result": { if (Array.isArray(part.content)) { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_search"), result: part.content.map((result) => { var _a23; return { url: result.url, title: result.title, pageAge: (_a23 = result.page_age) != null ? _a23 : null, encryptedContent: result.encrypted_content, type: result.type }; }) }); for (const result of part.content) { content.push({ type: "source", sourceType: "url", id: this.generateId(), url: result.url, title: result.title, providerMetadata: { anthropic: { pageAge: (_b18 = result.page_age) != null ? _b18 : null } } }); } } else { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_search"), isError: true, result: { type: "web_search_tool_result_error", errorCode: part.content.error_code } }); } break; } // code execution 20250522: case "code_execution_tool_result": { if (part.content.type === "code_execution_result") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: { type: part.content.type, stdout: part.content.stdout, stderr: part.content.stderr, return_code: part.content.return_code, content: (_c = part.content.content) != null ? _c : [] } }); } else if (part.content.type === "encrypted_code_execution_result") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: { type: part.content.type, encrypted_stdout: part.content.encrypted_stdout, stderr: part.content.stderr, return_code: part.content.return_code, content: (_d = part.content.content) != null ? _d : [] } }); } else if (part.content.type === "code_execution_tool_result_error") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), isError: true, result: { type: "code_execution_tool_result_error", errorCode: part.content.error_code } }); } break; } // code execution 20250825: case "bash_code_execution_tool_result": case "text_editor_code_execution_tool_result": { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: part.content }); break; } // tool search tool results: case "tool_search_tool_result": { let providerToolName = serverToolCalls[part.tool_use_id]; if (providerToolName == null) { const bm25CustomName = toolNameMapping.toCustomToolName( "tool_search_tool_bm25" ); const regexCustomName = toolNameMapping.toCustomToolName( "tool_search_tool_regex" ); if (bm25CustomName !== "tool_search_tool_bm25") { providerToolName = "tool_search_tool_bm25"; } else if (regexCustomName !== "tool_search_tool_regex") { providerToolName = "tool_search_tool_regex"; } else { providerToolName = "tool_search_tool_regex"; } } if (part.content.type === "tool_search_tool_search_result") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName(providerToolName), result: part.content.tool_references.map((ref) => ({ type: ref.type, toolName: ref.tool_name })) }); } else { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName(providerToolName), isError: true, result: { type: "tool_search_tool_result_error", errorCode: part.content.error_code } }); } break; } // advisor results for advisor_20260301: case "advisor_tool_result": { const advisorToolName = toolNameMapping.toCustomToolName("advisor"); if (part.content.type === "advisor_result") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, result: { type: "advisor_result", text: part.content.text } }); } else if (part.content.type === "advisor_redacted_result") { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, result: { type: "advisor_redacted_result", encryptedContent: part.content.encrypted_content } }); } else { content.push({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, isError: true, result: { type: "advisor_tool_result_error", errorCode: part.content.error_code } }); } break; } } } return { content, finishReason: { unified: mapAnthropicStopReason({ finishReason: response.stop_reason, isJsonResponseFromTool }), raw: (_e = response.stop_reason) != null ? _e : void 0 }, usage: convertAnthropicMessagesUsage({ usage: response.usage }), request: { body: args }, response: { id: (_f = response.id) != null ? _f : void 0, modelId: (_g = response.model) != null ? _g : void 0, headers: responseHeaders, body: rawResponse }, warnings, providerMetadata: (() => { var _a23, _b23, _c2, _d2, _e2; const stopDetails = mapAnthropicStopDetails(response.stop_details); const anthropicMetadata = { usage: response.usage, cacheCreationInputTokens: (_a23 = response.usage.cache_creation_input_tokens) != null ? _a23 : null, stopSequence: (_b23 = response.stop_sequence) != null ? _b23 : null, ...stopDetails != null ? { stopDetails } : {}, iterations: response.usage.iterations ? response.usage.iterations.map( (iter) => ({ type: iter.type, ...iter.model != null ? { model: iter.model } : {}, inputTokens: iter.input_tokens, outputTokens: iter.output_tokens, ...iter.cache_creation_input_tokens ? { cacheCreationInputTokens: iter.cache_creation_input_tokens } : {}, ...iter.cache_read_input_tokens ? { cacheReadInputTokens: iter.cache_read_input_tokens } : {} }) ) : null, container: response.container ? { expiresAt: response.container.expires_at, id: response.container.id, skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({ type: skill.type, skillId: skill.skill_id, version: skill.version }))) != null ? _d2 : null } : null, contextManagement: (_e2 = mapAnthropicResponseContextManagement( response.context_management )) != null ? _e2 : null }; const providerMetadata = { anthropic: anthropicMetadata }; if (usedCustomProviderKey && providerOptionsName !== "anthropic") { providerMetadata[providerOptionsName] = anthropicMetadata; } return providerMetadata; })() }; } async doStream(options) { var _a18, _b18; const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({ ...options, stream: true, userSuppliedBetas: await this.getBetasFromHeaders(options.headers) }); const citationDocuments = [ ...this.extractCitationDocuments(options.prompt) ]; const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution( body.tools ); const url = this.buildRequestUrl(true); const { responseHeaders, value: response } = await postJsonToApi2({ url, headers: await this.getHeaders({ betas, headers: options.headers }), body: this.transformRequestBody(body, betas), failedResponseHandler: anthropicFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2( anthropicMessagesChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = { unified: "other", raw: void 0 }; const usage = { input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, iterations: null }; const contentBlocks = {}; const mcpToolCalls = {}; const serverToolCalls = {}; let contextManagement = null; let rawUsage = void 0; let cacheCreationInputTokens = null; let stopSequence = null; let stopDetails = void 0; let container = null; let isJsonResponseFromTool = false; let blockType = void 0; const generateId3 = this.generateId; const transformedStream = response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a23, _b23, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; switch (value.type) { case "ping": { return; } case "content_block_start": { const part = value.content_block; const contentBlockType = part.type; if (contentBlockType === "fallback") { return; } blockType = contentBlockType; switch (contentBlockType) { case "text": { if (usesJsonResponseTool) { return; } contentBlocks[value.index] = { type: "text" }; controller.enqueue({ type: "text-start", id: String(value.index) }); return; } case "thinking": { contentBlocks[value.index] = { type: "reasoning" }; controller.enqueue({ type: "reasoning-start", id: String(value.index) }); return; } case "redacted_thinking": { contentBlocks[value.index] = { type: "reasoning" }; controller.enqueue({ type: "reasoning-start", id: String(value.index), providerMetadata: { anthropic: { redactedData: part.data } } }); return; } case "compaction": { contentBlocks[value.index] = { type: "text" }; controller.enqueue({ type: "text-start", id: String(value.index), providerMetadata: { anthropic: { type: "compaction" } } }); return; } case "tool_use": { const isJsonResponseTool = usesJsonResponseTool && part.name === "json"; if (isJsonResponseTool) { isJsonResponseFromTool = true; contentBlocks[value.index] = { type: "text" }; controller.enqueue({ type: "text-start", id: String(value.index) }); } else { const caller = part.caller; const callerInfo = caller ? { type: caller.type, toolId: "tool_id" in caller ? caller.tool_id : void 0 } : void 0; const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0; const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : ""; contentBlocks[value.index] = { type: "tool-call", toolCallId: part.id, toolName: part.name, input: initialInput, firstDelta: initialInput.length === 0, ...callerInfo && { caller: callerInfo } }; controller.enqueue({ type: "tool-input-start", id: part.id, toolName: part.name }); } return; } case "server_tool_use": { if ([ "web_fetch", "web_search", // code execution 20250825: "code_execution", // code execution 20250825 text editor: "text_editor_code_execution", // code execution 20250825 bash: "bash_code_execution" ].includes(part.name)) { const providerToolName = part.name === "text_editor_code_execution" || part.name === "bash_code_execution" ? "code_execution" : part.name; const customToolName = toolNameMapping.toCustomToolName(providerToolName); const finalInput = part.input != null && typeof part.input === "object" && Object.keys(part.input).length > 0 ? JSON.stringify(part.input) : ""; contentBlocks[value.index] = { type: "tool-call", toolCallId: part.id, toolName: customToolName, input: finalInput, providerExecuted: true, // Specific 'web_fetch' or 'web_search' tools may need code execution, which the Anthropic API // implicitly allows. In this scenario, we need to allow 'code_execution' tool calls even if the // tool was not explicitly provided. We therefore bypass the general validation by marking the // tool as dynamic. ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {}, firstDelta: true, providerToolName }; controller.enqueue({ type: "tool-input-start", id: part.id, toolName: customToolName, providerExecuted: true, // Specific 'web_fetch' or 'web_search' tools may need code execution, which the Anthropic API // implicitly allows. In this scenario, we need to allow 'code_execution' tool calls even if the // tool was not explicitly provided. We therefore bypass the general validation by marking the // tool as dynamic. ...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {} }); } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") { serverToolCalls[part.id] = part.name; const customToolName = toolNameMapping.toCustomToolName( part.name ); contentBlocks[value.index] = { type: "tool-call", toolCallId: part.id, toolName: customToolName, input: "", providerExecuted: true, firstDelta: true, providerToolName: part.name }; controller.enqueue({ type: "tool-input-start", id: part.id, toolName: customToolName, providerExecuted: true }); } else if (part.name === "advisor") { const customToolName = toolNameMapping.toCustomToolName("advisor"); contentBlocks[value.index] = { type: "tool-call", toolCallId: part.id, toolName: customToolName, input: "{}", providerExecuted: true, firstDelta: true, providerToolName: part.name }; controller.enqueue({ type: "tool-input-start", id: part.id, toolName: customToolName, providerExecuted: true }); } return; } case "web_fetch_tool_result": { if (part.content.type === "web_fetch_result") { citationDocuments.push({ title: (_a23 = part.content.content.title) != null ? _a23 : part.content.url, mediaType: part.content.content.source.media_type }); controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_fetch"), result: { type: "web_fetch_result", url: part.content.url, retrievedAt: part.content.retrieved_at, content: { type: part.content.content.type, title: part.content.content.title, citations: part.content.content.citations, source: { type: part.content.content.source.type, mediaType: part.content.content.source.media_type, data: part.content.content.source.data } } } }); } else if (part.content.type === "web_fetch_tool_result_error") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_fetch"), isError: true, result: { type: "web_fetch_tool_result_error", errorCode: part.content.error_code } }); } return; } case "web_search_tool_result": { if (Array.isArray(part.content)) { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_search"), result: part.content.map((result) => { var _a33; return { url: result.url, title: result.title, pageAge: (_a33 = result.page_age) != null ? _a33 : null, encryptedContent: result.encrypted_content, type: result.type }; }) }); for (const result of part.content) { controller.enqueue({ type: "source", sourceType: "url", id: generateId3(), url: result.url, title: result.title, providerMetadata: { anthropic: { pageAge: (_b23 = result.page_age) != null ? _b23 : null } } }); } } else { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("web_search"), isError: true, result: { type: "web_search_tool_result_error", errorCode: part.content.error_code } }); } return; } // code execution 20250522: case "code_execution_tool_result": { if (part.content.type === "code_execution_result") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: { type: part.content.type, stdout: part.content.stdout, stderr: part.content.stderr, return_code: part.content.return_code, content: (_c = part.content.content) != null ? _c : [] } }); } else if (part.content.type === "encrypted_code_execution_result") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: { type: part.content.type, encrypted_stdout: part.content.encrypted_stdout, stderr: part.content.stderr, return_code: part.content.return_code, content: (_d = part.content.content) != null ? _d : [] } }); } else if (part.content.type === "code_execution_tool_result_error") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), isError: true, result: { type: "code_execution_tool_result_error", errorCode: part.content.error_code } }); } return; } // code execution 20250825: case "bash_code_execution_tool_result": case "text_editor_code_execution_tool_result": { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName("code_execution"), result: part.content }); return; } // tool search tool results: case "tool_search_tool_result": { let providerToolName = serverToolCalls[part.tool_use_id]; if (providerToolName == null) { const bm25CustomName = toolNameMapping.toCustomToolName( "tool_search_tool_bm25" ); const regexCustomName = toolNameMapping.toCustomToolName( "tool_search_tool_regex" ); if (bm25CustomName !== "tool_search_tool_bm25") { providerToolName = "tool_search_tool_bm25"; } else if (regexCustomName !== "tool_search_tool_regex") { providerToolName = "tool_search_tool_regex"; } else { providerToolName = "tool_search_tool_regex"; } } if (part.content.type === "tool_search_tool_search_result") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName(providerToolName), result: part.content.tool_references.map((ref) => ({ type: ref.type, toolName: ref.tool_name })) }); } else { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: toolNameMapping.toCustomToolName(providerToolName), isError: true, result: { type: "tool_search_tool_result_error", errorCode: part.content.error_code } }); } return; } // advisor results for advisor_20260301: // arrives fully formed in a single content_block_start (no deltas). case "advisor_tool_result": { const advisorToolName = toolNameMapping.toCustomToolName("advisor"); if (part.content.type === "advisor_result") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, result: { type: "advisor_result", text: part.content.text } }); } else if (part.content.type === "advisor_redacted_result") { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, result: { type: "advisor_redacted_result", encryptedContent: part.content.encrypted_content } }); } else { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: advisorToolName, isError: true, result: { type: "advisor_tool_result_error", errorCode: part.content.error_code } }); } return; } case "mcp_tool_use": { mcpToolCalls[part.id] = { type: "tool-call", toolCallId: part.id, toolName: part.name, input: JSON.stringify(part.input), providerExecuted: true, dynamic: true, providerMetadata: { anthropic: { type: "mcp-tool-use", serverName: part.server_name } } }; controller.enqueue(mcpToolCalls[part.id]); return; } case "mcp_tool_result": { controller.enqueue({ type: "tool-result", toolCallId: part.tool_use_id, toolName: mcpToolCalls[part.tool_use_id].toolName, isError: part.is_error, result: part.content, dynamic: true, providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata }); return; } default: { const _exhaustiveCheck = contentBlockType; throw new Error( `Unsupported content block type: ${_exhaustiveCheck}` ); } } } case "content_block_stop": { if (contentBlocks[value.index] != null) { const contentBlock = contentBlocks[value.index]; switch (contentBlock.type) { case "text": { controller.enqueue({ type: "text-end", id: String(value.index) }); break; } case "reasoning": { controller.enqueue({ type: "reasoning-end", id: String(value.index) }); break; } case "tool-call": const isJsonResponseTool = usesJsonResponseTool && contentBlock.toolName === "json"; if (!isJsonResponseTool) { controller.enqueue({ type: "tool-input-end", id: contentBlock.toolCallId }); let finalInput = contentBlock.input === "" ? "{}" : contentBlock.input; if (contentBlock.providerToolName === "code_execution") { try { const parsed = JSON.parse(finalInput); if (parsed != null && typeof parsed === "object" && "code" in parsed && !("type" in parsed)) { finalInput = JSON.stringify({ type: "programmatic-tool-call", ...parsed }); } } catch (e) { } } controller.enqueue({ type: "tool-call", toolCallId: contentBlock.toolCallId, toolName: contentBlock.toolName, input: finalInput, providerExecuted: contentBlock.providerExecuted, // Specific 'web_fetch' or 'web_search' tools may need code execution, which the Anthropic API // implicitly allows. In this scenario, we need to allow 'code_execution' tool calls even if the // tool was not explicitly provided. We therefore bypass the general validation by marking the // tool as dynamic. ...markCodeExecutionDynamic && contentBlock.providerToolName === "code_execution" ? { dynamic: true } : {}, ...contentBlock.caller && { providerMetadata: { anthropic: { caller: contentBlock.caller } } } }); } break; } delete contentBlocks[value.index]; } blockType = void 0; return; } case "content_block_delta": { const deltaType = value.delta.type; switch (deltaType) { case "text_delta": { if (usesJsonResponseTool) { return; } controller.enqueue({ type: "text-delta", id: String(value.index), delta: value.delta.text }); return; } case "thinking_delta": { controller.enqueue({ type: "reasoning-delta", id: String(value.index), delta: value.delta.thinking }); return; } case "signature_delta": { if (blockType === "thinking") { controller.enqueue({ type: "reasoning-delta", id: String(value.index), delta: "", providerMetadata: { anthropic: { signature: value.delta.signature } } }); } return; } case "compaction_delta": { if (value.delta.content != null) { controller.enqueue({ type: "text-delta", id: String(value.index), delta: value.delta.content }); } return; } case "input_json_delta": { const contentBlock = contentBlocks[value.index]; let delta = value.delta.partial_json; if (delta.length === 0) { return; } if (isJsonResponseFromTool) { if ((contentBlock == null ? void 0 : contentBlock.type) !== "text") { return; } controller.enqueue({ type: "text-delta", id: String(value.index), delta }); } else { if ((contentBlock == null ? void 0 : contentBlock.type) !== "tool-call") { return; } if (contentBlock.firstDelta && contentBlock.providerToolName === "code_execution") { delta = `{"type": "programmatic-tool-call",${delta.substring(1)}`; } controller.enqueue({ type: "tool-input-delta", id: contentBlock.toolCallId, delta }); contentBlock.input += delta; contentBlock.firstDelta = false; } return; } case "citations_delta": { const citation = value.delta.citation; const source = createCitationSource( citation, citationDocuments, generateId3 ); if (source) { controller.enqueue(source); } return; } default: { const _exhaustiveCheck = deltaType; throw new Error( `Unsupported delta type: ${_exhaustiveCheck}` ); } } } case "message_start": { usage.input_tokens = value.message.usage.input_tokens; usage.cache_read_input_tokens = (_e = value.message.usage.cache_read_input_tokens) != null ? _e : 0; usage.cache_creation_input_tokens = (_f = value.message.usage.cache_creation_input_tokens) != null ? _f : 0; rawUsage = { ...value.message.usage }; cacheCreationInputTokens = (_g = value.message.usage.cache_creation_input_tokens) != null ? _g : null; if (value.message.container != null) { container = { expiresAt: value.message.container.expires_at, id: value.message.container.id, skills: null }; } if (value.message.stop_reason != null) { finishReason = { unified: mapAnthropicStopReason({ finishReason: value.message.stop_reason, isJsonResponseFromTool }), raw: value.message.stop_reason }; } controller.enqueue({ type: "response-metadata", id: (_h = value.message.id) != null ? _h : void 0, modelId: (_i = value.message.model) != null ? _i : void 0 }); if (value.message.content != null) { for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) { const part = value.message.content[contentIndex]; if (part.type === "tool_use") { const caller = part.caller; const callerInfo = caller ? { type: caller.type, toolId: "tool_id" in caller ? caller.tool_id : void 0 } : void 0; controller.enqueue({ type: "tool-input-start", id: part.id, toolName: part.name }); const inputStr = JSON.stringify((_j = part.input) != null ? _j : {}); controller.enqueue({ type: "tool-input-delta", id: part.id, delta: inputStr }); controller.enqueue({ type: "tool-input-end", id: part.id }); controller.enqueue({ type: "tool-call", toolCallId: part.id, toolName: part.name, input: inputStr, ...callerInfo && { providerMetadata: { anthropic: { caller: callerInfo } } } }); } } } return; } case "message_delta": { if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) { usage.input_tokens = value.usage.input_tokens; } usage.output_tokens = value.usage.output_tokens; if (value.usage.cache_read_input_tokens != null) { usage.cache_read_input_tokens = value.usage.cache_read_input_tokens; } if (value.usage.cache_creation_input_tokens != null) { usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens; cacheCreationInputTokens = value.usage.cache_creation_input_tokens; } if (value.usage.iterations != null) { usage.iterations = value.usage.iterations; } finishReason = { unified: mapAnthropicStopReason({ finishReason: value.delta.stop_reason, isJsonResponseFromTool }), raw: (_k = value.delta.stop_reason) != null ? _k : void 0 }; stopSequence = (_l = value.delta.stop_sequence) != null ? _l : null; stopDetails = mapAnthropicStopDetails(value.delta.stop_details); container = value.delta.container != null ? { expiresAt: value.delta.container.expires_at, id: value.delta.container.id, skills: (_n = (_m = value.delta.container.skills) == null ? void 0 : _m.map((skill) => ({ type: skill.type, skillId: skill.skill_id, version: skill.version }))) != null ? _n : null } : null; if (value.context_management) { contextManagement = mapAnthropicResponseContextManagement( value.context_management ); } rawUsage = { ...rawUsage, ...value.usage }; return; } case "message_stop": { const anthropicMetadata = { usage: rawUsage != null ? rawUsage : null, cacheCreationInputTokens, stopSequence, ...stopDetails != null ? { stopDetails } : {}, iterations: usage.iterations ? usage.iterations.map( (iter) => ({ type: iter.type, ...iter.model != null ? { model: iter.model } : {}, inputTokens: iter.input_tokens, outputTokens: iter.output_tokens, ...iter.cache_creation_input_tokens ? { cacheCreationInputTokens: iter.cache_creation_input_tokens } : {}, ...iter.cache_read_input_tokens ? { cacheReadInputTokens: iter.cache_read_input_tokens } : {} }) ) : null, container, contextManagement }; const providerMetadata = { anthropic: anthropicMetadata }; if (usedCustomProviderKey && providerOptionsName !== "anthropic") { providerMetadata[providerOptionsName] = anthropicMetadata; } controller.enqueue({ type: "finish", finishReason, usage: convertAnthropicMessagesUsage({ usage, rawUsage }), providerMetadata }); return; } case "error": { controller.enqueue({ type: "error", error: value.error }); return; } default: { const _exhaustiveCheck = value; throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`); } } } }) ); const [streamForFirstChunk, streamForConsumer] = transformedStream.tee(); const firstChunkReader = streamForFirstChunk.getReader(); try { await firstChunkReader.read(); let result = await firstChunkReader.read(); if (((_a18 = result.value) == null ? void 0 : _a18.type) === "raw") { result = await firstChunkReader.read(); } if (((_b18 = result.value) == null ? void 0 : _b18.type) === "error") { const error = result.value.error; throw new APICallError2({ message: error.message, url, requestBodyValues: body, statusCode: error.type === "overloaded_error" ? 529 : 500, responseHeaders, responseBody: JSON.stringify(error), isRetryable: error.type === "overloaded_error" }); } } finally { firstChunkReader.cancel().catch(() => { }); firstChunkReader.releaseLock(); } return { stream: streamForConsumer, request: { body }, response: { headers: responseHeaders } }; } }; function getModelCapabilities(modelId) { if (modelId.includes("claude-opus-4-8") || modelId.includes("claude-opus-4-7") || modelId.includes("claude-fable-5")) { return { maxOutputTokens: 128e3, supportsStructuredOutput: true, rejectsSamplingParameters: true, isKnownModel: true }; } else if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) { return { maxOutputTokens: 128e3, supportsStructuredOutput: true, rejectsSamplingParameters: false, isKnownModel: true }; } else if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) { return { maxOutputTokens: 64e3, supportsStructuredOutput: true, rejectsSamplingParameters: false, isKnownModel: true }; } else if (modelId.includes("claude-opus-4-1")) { return { maxOutputTokens: 32e3, supportsStructuredOutput: true, rejectsSamplingParameters: false, isKnownModel: true }; } else if (modelId.includes("claude-sonnet-4-")) { return { maxOutputTokens: 64e3, supportsStructuredOutput: false, rejectsSamplingParameters: false, isKnownModel: true }; } else if (modelId.includes("claude-opus-4-")) { return { maxOutputTokens: 32e3, supportsStructuredOutput: false, rejectsSamplingParameters: false, isKnownModel: true }; } else if (modelId.includes("claude-3-haiku")) { return { maxOutputTokens: 4096, supportsStructuredOutput: false, rejectsSamplingParameters: false, isKnownModel: true }; } else { return { maxOutputTokens: 4096, supportsStructuredOutput: false, rejectsSamplingParameters: false, isKnownModel: false }; } } function hasWebTool20260209WithoutCodeExecution(tools) { if (!tools) { return false; } let hasWebTool20260209 = false; let hasCodeExecutionTool = false; for (const tool3 of tools) { if ("type" in tool3 && (tool3.type === "web_fetch_20260209" || tool3.type === "web_search_20260209")) { hasWebTool20260209 = true; continue; } if (tool3.name === "code_execution") { hasCodeExecutionTool = true; break; } } return hasWebTool20260209 && !hasCodeExecutionTool; } function mapAnthropicResponseContextManagement(contextManagement) { return contextManagement ? { appliedEdits: contextManagement.applied_edits.map((edit) => { const strategy = edit.type; switch (strategy) { case "clear_tool_uses_20250919": return { type: edit.type, clearedToolUses: edit.cleared_tool_uses, clearedInputTokens: edit.cleared_input_tokens }; case "clear_thinking_20251015": return { type: edit.type, clearedThinkingTurns: edit.cleared_thinking_turns, clearedInputTokens: edit.cleared_input_tokens }; case "compact_20260112": return { type: edit.type }; } }).filter((edit) => edit !== void 0) } : null; } function mapAnthropicStopDetails(stopDetails) { if (stopDetails == null) { return void 0; } return { type: stopDetails.type, ...stopDetails.category != null ? { category: stopDetails.category } : {}, ...stopDetails.explanation != null ? { explanation: stopDetails.explanation } : {}, ...stopDetails.recommended_model != null ? { recommendedModel: stopDetails.recommended_model } : {} }; } var bash_20241022InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.string(), restart: z4.z.boolean().optional() }) ) ); var bash_20241022 = createProviderToolFactory({ id: "anthropic.bash_20241022", inputSchema: bash_20241022InputSchema }); var bash_20250124InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.string(), restart: z4.z.boolean().optional() }) ) ); var bash_20250124 = createProviderToolFactory({ id: "anthropic.bash_20250124", inputSchema: bash_20250124InputSchema }); var computer_20241022InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.enum([ "key", "type", "mouse_move", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "screenshot", "cursor_position" ]), coordinate: z4.z.array(z4.z.number().int()).optional(), text: z4.z.string().optional() }) ) ); var computer_20241022 = createProviderToolFactory({ id: "anthropic.computer_20241022", inputSchema: computer_20241022InputSchema }); var computer_20250124InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.enum([ "key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot" ]), coordinate: z4.z.tuple([z4.z.number().int(), z4.z.number().int()]).optional(), duration: z4.z.number().optional(), scroll_amount: z4.z.number().optional(), scroll_direction: z4.z.enum(["up", "down", "left", "right"]).optional(), start_coordinate: z4.z.tuple([z4.z.number().int(), z4.z.number().int()]).optional(), text: z4.z.string().optional() }) ) ); var computer_20250124 = createProviderToolFactory({ id: "anthropic.computer_20250124", inputSchema: computer_20250124InputSchema }); var computer_20251124InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ action: z4.z.enum([ "key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot", "zoom" ]), coordinate: z4.z.tuple([z4.z.number().int(), z4.z.number().int()]).optional(), duration: z4.z.number().optional(), region: z4.z.tuple([ z4.z.number().int(), z4.z.number().int(), z4.z.number().int(), z4.z.number().int() ]).optional(), scroll_amount: z4.z.number().optional(), scroll_direction: z4.z.enum(["up", "down", "left", "right"]).optional(), start_coordinate: z4.z.tuple([z4.z.number().int(), z4.z.number().int()]).optional(), text: z4.z.string().optional() }) ) ); var computer_20251124 = createProviderToolFactory({ id: "anthropic.computer_20251124", inputSchema: computer_20251124InputSchema }); var memory_20250818InputSchema = lazySchema2( () => zodSchema2( z4.z.discriminatedUnion("command", [ z4.z.object({ command: z4.z.literal("view"), path: z4.z.string(), view_range: z4.z.tuple([z4.z.number(), z4.z.number()]).optional() }), z4.z.object({ command: z4.z.literal("create"), path: z4.z.string(), file_text: z4.z.string() }), z4.z.object({ command: z4.z.literal("str_replace"), path: z4.z.string(), old_str: z4.z.string(), new_str: z4.z.string() }), z4.z.object({ command: z4.z.literal("insert"), path: z4.z.string(), insert_line: z4.z.number(), insert_text: z4.z.string() }), z4.z.object({ command: z4.z.literal("delete"), path: z4.z.string() }), z4.z.object({ command: z4.z.literal("rename"), old_path: z4.z.string(), new_path: z4.z.string() }) ]) ) ); var memory_20250818 = createProviderToolFactory({ id: "anthropic.memory_20250818", inputSchema: memory_20250818InputSchema }); var textEditor_20241022InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.enum(["view", "create", "str_replace", "insert", "undo_edit"]), path: z4.z.string(), file_text: z4.z.string().optional(), insert_line: z4.z.number().int().optional(), new_str: z4.z.string().optional(), insert_text: z4.z.string().optional(), old_str: z4.z.string().optional(), view_range: z4.z.array(z4.z.number().int()).optional() }) ) ); var textEditor_20241022 = createProviderToolFactory({ id: "anthropic.text_editor_20241022", inputSchema: textEditor_20241022InputSchema }); var textEditor_20250124InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.enum(["view", "create", "str_replace", "insert", "undo_edit"]), path: z4.z.string(), file_text: z4.z.string().optional(), insert_line: z4.z.number().int().optional(), new_str: z4.z.string().optional(), insert_text: z4.z.string().optional(), old_str: z4.z.string().optional(), view_range: z4.z.array(z4.z.number().int()).optional() }) ) ); var textEditor_20250124 = createProviderToolFactory({ id: "anthropic.text_editor_20250124", inputSchema: textEditor_20250124InputSchema }); var textEditor_20250429InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ command: z4.z.enum(["view", "create", "str_replace", "insert"]), path: z4.z.string(), file_text: z4.z.string().optional(), insert_line: z4.z.number().int().optional(), new_str: z4.z.string().optional(), insert_text: z4.z.string().optional(), old_str: z4.z.string().optional(), view_range: z4.z.array(z4.z.number().int()).optional() }) ) ); var textEditor_20250429 = createProviderToolFactory({ id: "anthropic.text_editor_20250429", inputSchema: textEditor_20250429InputSchema }); var toolSearchBm25_20251119OutputSchema = lazySchema2( () => zodSchema2( z4.z.array( z4.z.object({ type: z4.z.literal("tool_reference"), toolName: z4.z.string() }) ) ) ); var toolSearchBm25_20251119InputSchema = lazySchema2( () => zodSchema2( z4.z.object({ /** * A natural language query to search for tools. * Claude will use BM25 text search to find relevant tools. */ query: z4.z.string(), /** * Maximum number of tools to return. Optional. */ limit: z4.z.number().optional() }) ) ); var factory11 = createProviderToolFactoryWithOutputSchema({ id: "anthropic.tool_search_bm25_20251119", inputSchema: toolSearchBm25_20251119InputSchema, outputSchema: toolSearchBm25_20251119OutputSchema, supportsDeferredResults: true }); var toolSearchBm25_20251119 = (args = {}) => { return factory11(args); }; var anthropicTools = { /** * Pairs a faster executor model with a higher-intelligence advisor model * that provides strategic guidance mid-generation. * * The advisor lets a faster, lower-cost executor model consult a * higher-intelligence advisor model server-side. The advisor reads the * executor's full transcript and produces a plan or course correction; * the executor continues with the task, informed by the advice. All of * this happens inside a single `/v1/messages` request. * * Beta header `advisor-tool-2026-03-01` is added automatically when this * tool is included. * * Multi-turn conversations: pass the full assistant content (including * `advisor_tool_result` blocks) back to the API on subsequent turns. If * you omit the advisor tool from `tools` on a follow-up turn while the * message history still contains `advisor_tool_result` blocks, the API * returns a `400 invalid_request_error`. * * Supported executor models: Claude Haiku 4.5, Sonnet 4.6, Opus 4.6, * Opus 4.7. The advisor must be at least as capable as the executor. * * @param model - The advisor model ID (required), e.g. `"claude-opus-4-8"`. * @param maxUses - Maximum advisor calls per request (per-request cap). * @param caching - Enables prompt caching for the advisor's transcript * across calls within a conversation. Worthwhile from ~3 advisor calls * per conversation. */ advisor_20260301, /** * The bash tool enables Claude to execute shell commands in a persistent bash session, * allowing system operations, script execution, and command-line automation. * * Image results are supported. */ bash_20241022, /** * The bash tool enables Claude to execute shell commands in a persistent bash session, * allowing system operations, script execution, and command-line automation. * * Image results are supported. */ bash_20250124, /** * Claude can analyze data, create visualizations, perform complex calculations, * run system commands, create and edit files, and process uploaded files directly within * the API conversation. * * The code execution tool allows Claude to run Bash commands and manipulate files, * including writing code, in a secure, sandboxed environment. */ codeExecution_20250522, /** * Claude can analyze data, create visualizations, perform complex calculations, * run system commands, create and edit files, and process uploaded files directly within * the API conversation. * * The code execution tool allows Claude to run both Python and Bash commands and manipulate files, * including writing code, in a secure, sandboxed environment. * * This is the latest version with enhanced Bash support and file operations. */ codeExecution_20250825, /** * Claude can analyze data, create visualizations, perform complex calculations, * run system commands, create and edit files, and process uploaded files directly within * the API conversation. * * The code execution tool allows Claude to run both Python and Bash commands and manipulate files, * including writing code, in a secure, sandboxed environment. * * This is the recommended version. Does not require a beta header. * * Supported models: Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, Opus 4.5 */ codeExecution_20260120, /** * Claude can interact with computer environments through the computer use tool, which * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction. * * Image results are supported. * * @param displayWidthPx - The width of the display being controlled by the model in pixels. * @param displayHeightPx - The height of the display being controlled by the model in pixels. * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition. */ computer_20241022, /** * Claude can interact with computer environments through the computer use tool, which * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction. * * Image results are supported. * * @param displayWidthPx - The width of the display being controlled by the model in pixels. * @param displayHeightPx - The height of the display being controlled by the model in pixels. * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition. */ computer_20250124, /** * Claude can interact with computer environments through the computer use tool, which * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction. * * This version adds the zoom action for detailed screen region inspection. * * Image results are supported. * * Supported models: Claude Opus 4.5 * * @param displayWidthPx - The width of the display being controlled by the model in pixels. * @param displayHeightPx - The height of the display being controlled by the model in pixels. * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition. * @param enableZoom - Enable zoom action. Set to true to allow Claude to zoom into specific screen regions. Default: false. */ computer_20251124, /** * The memory tool enables Claude to store and retrieve information across conversations through a memory file directory. * Claude can create, read, update, and delete files that persist between sessions, * allowing it to build knowledge over time without keeping everything in the context window. * The memory tool operates client-side—you control where and how the data is stored through your own infrastructure. * * Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4. */ memory_20250818, /** * Claude can use an Anthropic-defined text editor tool to view and modify text files, * helping you debug, fix, and improve your code or other text documents. This allows Claude * to directly interact with your files, providing hands-on assistance rather than just suggesting changes. * * Supported models: Claude Sonnet 3.5 */ textEditor_20241022, /** * Claude can use an Anthropic-defined text editor tool to view and modify text files, * helping you debug, fix, and improve your code or other text documents. This allows Claude * to directly interact with your files, providing hands-on assistance rather than just suggesting changes. * * Supported models: Claude Sonnet 3.7 */ textEditor_20250124, /** * Claude can use an Anthropic-defined text editor tool to view and modify text files, * helping you debug, fix, and improve your code or other text documents. This allows Claude * to directly interact with your files, providing hands-on assistance rather than just suggesting changes. * * Note: This version does not support the "undo_edit" command. * * @deprecated Use textEditor_20250728 instead */ textEditor_20250429, /** * Claude can use an Anthropic-defined text editor tool to view and modify text files, * helping you debug, fix, and improve your code or other text documents. This allows Claude * to directly interact with your files, providing hands-on assistance rather than just suggesting changes. * * Note: This version does not support the "undo_edit" command and adds optional max_characters parameter. * * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1 * * @param maxCharacters - Optional maximum number of characters to view in the file */ textEditor_20250728, /** * Creates a web fetch tool that gives Claude direct access to real-time web content. * * @param maxUses - The max_uses parameter limits the number of web fetches performed * @param allowedDomains - Only fetch from these domains * @param blockedDomains - Never fetch from these domains * @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set "citations": {"enabled": true} to enable Claude to cite specific passages from fetched documents. * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context. */ webFetch_20250910, /** * Creates a web fetch tool that gives Claude direct access to real-time web content. * * @param maxUses - The max_uses parameter limits the number of web fetches performed * @param allowedDomains - Only fetch from these domains * @param blockedDomains - Never fetch from these domains * @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set "citations": {"enabled": true} to enable Claude to cite specific passages from fetched documents. * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context. */ webFetch_20260209, /** * Creates a web search tool that gives Claude direct access to real-time web content. * * @param maxUses - Maximum number of web searches Claude can perform during the conversation. * @param allowedDomains - Optional list of domains that Claude is allowed to search. * @param blockedDomains - Optional list of domains that Claude should avoid when searching. * @param userLocation - Optional user location information to provide geographically relevant search results. */ webSearch_20250305, /** * Creates a web search tool that gives Claude direct access to real-time web content. * * @param maxUses - Maximum number of web searches Claude can perform during the conversation. * @param allowedDomains - Optional list of domains that Claude is allowed to search. * @param blockedDomains - Optional list of domains that Claude should avoid when searching. * @param userLocation - Optional user location information to provide geographically relevant search results. */ webSearch_20260209, /** * Creates a tool search tool that uses regex patterns to find tools. * * The tool search tool enables Claude to work with hundreds or thousands of tools * by dynamically discovering and loading them on-demand. Instead of loading all * tool definitions into the context window upfront, Claude searches your tool * catalog and loads only the tools it needs. * * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools * to mark them for deferred loading. * * Supported models: Claude Opus 4.5, Claude Sonnet 4.5 */ toolSearchRegex_20251119, /** * Creates a tool search tool that uses BM25 (natural language) to find tools. * * The tool search tool enables Claude to work with hundreds or thousands of tools * by dynamically discovering and loading them on-demand. Instead of loading all * tool definitions into the context window upfront, Claude searches your tool * catalog and loads only the tools it needs. * * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools * to mark them for deferred loading. * * Supported models: Claude Opus 4.5, Claude Sonnet 4.5 */ toolSearchBm25_20251119 }; function createAnthropic(options = {}) { var _a18, _b18; const baseURL = (_a18 = withoutTrailingSlash2( loadOptionalSetting2({ settingValue: options.baseURL, environmentVariableName: "ANTHROPIC_BASE_URL" }) )) != null ? _a18 : "https://api.anthropic.com/v1"; const providerName = (_b18 = options.name) != null ? _b18 : "anthropic.messages"; if (options.apiKey && options.authToken) { throw new InvalidArgumentError2({ argument: "apiKey/authToken", message: "Both apiKey and authToken were provided. Please use only one authentication method." }); } const getHeaders = () => { const authHeaders = options.authToken ? { Authorization: `Bearer ${options.authToken}` } : { "x-api-key": loadApiKey2({ apiKey: options.apiKey, environmentVariableName: "ANTHROPIC_API_KEY", description: "Anthropic" }) }; return withUserAgentSuffix2( { "anthropic-version": "2023-06-01", ...authHeaders, ...options.headers }, `ai-sdk/anthropic/${VERSION5}` ); }; const createChatModel = (modelId) => { var _a23; return new AnthropicMessagesLanguageModel(modelId, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch, generateId: (_a23 = options.generateId) != null ? _a23 : generateId2, supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/], "application/pdf": [/^https?:\/\/.*$/] }) }); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Anthropic model function cannot be called with the new keyword." ); } return createChatModel(modelId); }; provider.specificationVersion = "v3"; provider.languageModel = createChatModel; provider.chat = createChatModel; provider.messages = createChatModel; provider.embeddingModel = (modelId) => { throw new NoSuchModelError2({ modelId, modelType: "embeddingModel" }); }; provider.textEmbeddingModel = provider.embeddingModel; provider.imageModel = (modelId) => { throw new NoSuchModelError2({ modelId, modelType: "imageModel" }); }; provider.tools = anthropicTools; return provider; } createAnthropic(); var VERSION6 = "3.0.70" ; var googleErrorDataSchema = lazySchema2( () => zodSchema2( z4.z.object({ error: z4.z.object({ code: z4.z.number().nullable(), message: z4.z.string(), status: z4.z.string() }) }) ) ); var googleFailedResponseHandler = createJsonErrorResponseHandler2({ errorSchema: googleErrorDataSchema, errorToMessage: (data) => data.error.message }); var googleEmbeddingContentPartSchema = z4.z.union([ z4.z.object({ text: z4.z.string() }), z4.z.object({ inlineData: z4.z.object({ mimeType: z4.z.string(), data: z4.z.string() }) }) ]); var googleEmbeddingModelOptions = lazySchema2( () => zodSchema2( z4.z.object({ /** * Optional. Optional reduced dimension for the output embedding. * If set, excessive values in the output embedding are truncated from the end. */ outputDimensionality: z4.z.number().optional(), /** * Optional. Specifies the task type for generating embeddings. * Supported task types: * - SEMANTIC_SIMILARITY: Optimized for text similarity. * - CLASSIFICATION: Optimized for text classification. * - CLUSTERING: Optimized for clustering texts based on similarity. * - RETRIEVAL_DOCUMENT: Optimized for document retrieval. * - RETRIEVAL_QUERY: Optimized for query-based retrieval. * - QUESTION_ANSWERING: Optimized for answering questions. * - FACT_VERIFICATION: Optimized for verifying factual information. * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries. */ taskType: z4.z.enum([ "SEMANTIC_SIMILARITY", "CLASSIFICATION", "CLUSTERING", "RETRIEVAL_DOCUMENT", "RETRIEVAL_QUERY", "QUESTION_ANSWERING", "FACT_VERIFICATION", "CODE_RETRIEVAL_QUERY" ]).optional(), /** * Optional. Per-value multimodal content parts for embedding non-text * content (images, video, PDF, audio). Each entry corresponds to the * embedding value at the same index and its parts are merged with the * text value in the request. Use `null` for entries that are text-only. * * The array length must match the number of values being embedded. In * the case of a single embedding, the array length must be 1. */ content: z4.z.array(z4.z.array(googleEmbeddingContentPartSchema).min(1).nullable()).optional() }) ) ); var GoogleGenerativeAIEmbeddingModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { const googleOptions = await parseProviderOptions2({ provider: "google", providerOptions, schema: googleEmbeddingModelOptions }); if (values.length > this.maxEmbeddingsPerCall) { throw new TooManyEmbeddingValuesForCallError2({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const mergedHeaders = combineHeaders2( await resolve2(this.config.headers), headers ); const multimodalContent = googleOptions == null ? void 0 : googleOptions.content; if (multimodalContent != null && multimodalContent.length !== values.length) { throw new Error( `The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).` ); } if (values.length === 1) { const valueParts = multimodalContent == null ? void 0 : multimodalContent[0]; const textPart = values[0] ? [{ text: values[0] }] : []; const parts = valueParts != null ? [...textPart, ...valueParts] : [{ text: values[0] }]; const { responseHeaders: responseHeaders2, value: response2, rawValue: rawValue2 } = await postJsonToApi2({ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`, headers: mergedHeaders, body: { model: `models/${this.modelId}`, content: { parts }, outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality, taskType: googleOptions == null ? void 0 : googleOptions.taskType }, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleGenerativeAISingleEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { warnings: [], embeddings: [response2.embedding.values], usage: void 0, response: { headers: responseHeaders2, body: rawValue2 } }; } const { responseHeaders, value: response, rawValue } = await postJsonToApi2({ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`, headers: mergedHeaders, body: { requests: values.map((value, index) => { const valueParts = multimodalContent == null ? void 0 : multimodalContent[index]; const textPart = value ? [{ text: value }] : []; return { model: `models/${this.modelId}`, content: { role: "user", parts: valueParts != null ? [...textPart, ...valueParts] : [{ text: value }] }, outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality, taskType: googleOptions == null ? void 0 : googleOptions.taskType }; }) }, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleGenerativeAITextEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { warnings: [], embeddings: response.embeddings.map((item) => item.values), usage: void 0, response: { headers: responseHeaders, body: rawValue } }; } }; var googleGenerativeAITextEmbeddingResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ embeddings: z4.z.array(z4.z.object({ values: z4.z.array(z4.z.number()) })) }) ) ); var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ embedding: z4.z.object({ values: z4.z.array(z4.z.number()) }) }) ) ); function convertGoogleGenerativeAIUsage(usage) { var _a18, _b18, _c, _d; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const promptTokens = (_a18 = usage.promptTokenCount) != null ? _a18 : 0; const candidatesTokens = (_b18 = usage.candidatesTokenCount) != null ? _b18 : 0; const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0; const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0; return { inputTokens: { total: promptTokens, noCache: promptTokens - cachedContentTokens, cacheRead: cachedContentTokens, cacheWrite: void 0 }, outputTokens: { total: candidatesTokens + thoughtsTokens, text: candidatesTokens, reasoning: thoughtsTokens }, raw: usage }; } function convertJSONSchemaToOpenAPISchema(jsonSchema3, isRoot = true) { if (jsonSchema3 == null) { return void 0; } if (isEmptyObjectSchema(jsonSchema3)) { if (isRoot) { return void 0; } if (typeof jsonSchema3 === "object" && jsonSchema3.description) { return { type: "object", description: jsonSchema3.description }; } return { type: "object" }; } if (typeof jsonSchema3 === "boolean") { return { type: "boolean", properties: {} }; } const { type, description, required, properties, items, allOf, anyOf, oneOf, format, const: constValue, minLength, enum: enumValues } = jsonSchema3; const result = {}; if (description) result.description = description; if (required) result.required = required; if (format) result.format = format; if (constValue !== void 0) { result.enum = [constValue]; } if (type) { if (Array.isArray(type)) { const hasNull = type.includes("null"); const nonNullTypes = type.filter((t) => t !== "null"); if (nonNullTypes.length === 0) { result.type = "null"; } else { result.anyOf = nonNullTypes.map((t) => ({ type: t })); if (hasNull) { result.nullable = true; } } } else { result.type = type; } } if (enumValues !== void 0) { result.enum = enumValues; } if (properties != null) { result.properties = Object.entries(properties).reduce( (acc, [key, value]) => { acc[key] = convertJSONSchemaToOpenAPISchema(value, false); return acc; }, {} ); } if (items) { result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false); } if (allOf) { result.allOf = allOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } if (anyOf) { if (anyOf.some( (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null" )) { const nonNullSchemas = anyOf.filter( (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null") ); if (nonNullSchemas.length === 1) { const converted = convertJSONSchemaToOpenAPISchema( nonNullSchemas[0], false ); if (typeof converted === "object") { result.nullable = true; Object.assign(result, converted); } } else { result.anyOf = nonNullSchemas.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); result.nullable = true; } } else { result.anyOf = anyOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } } if (oneOf) { result.oneOf = oneOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } if (minLength !== void 0) { result.minLength = minLength; } return result; } function isEmptyObjectSchema(jsonSchema3) { return jsonSchema3 != null && typeof jsonSchema3 === "object" && jsonSchema3.type === "object" && (jsonSchema3.properties == null || Object.keys(jsonSchema3.properties).length === 0) && !jsonSchema3.additionalProperties; } var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s; function parseBase64DataUrl(value) { const match = dataUrlRegex.exec(value); if (match == null) { return void 0; } return { mediaType: match[1], data: match[2] }; } function convertUrlToolResultPart(url) { const parsedDataUrl = parseBase64DataUrl(url); if (parsedDataUrl == null) { return void 0; } return { inlineData: { mimeType: parsedDataUrl.mediaType, data: parsedDataUrl.data } }; } function appendToolResultParts(parts, toolName, outputValue) { const functionResponseParts = []; const responseTextParts = []; for (const contentPart of outputValue) { switch (contentPart.type) { case "text": { responseTextParts.push(contentPart.text); break; } case "image-data": case "file-data": { functionResponseParts.push({ inlineData: { mimeType: contentPart.mediaType, data: contentPart.data } }); break; } case "image-url": case "file-url": { const functionResponsePart = convertUrlToolResultPart( contentPart.url ); if (functionResponsePart != null) { functionResponseParts.push(functionResponsePart); } else { responseTextParts.push(JSON.stringify(contentPart)); } break; } default: { responseTextParts.push(JSON.stringify(contentPart)); break; } } } parts.push({ functionResponse: { name: toolName, response: { name: toolName, content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully." }, ...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {} } }); } function appendLegacyToolResultParts(parts, toolName, outputValue) { for (const contentPart of outputValue) { switch (contentPart.type) { case "text": parts.push({ functionResponse: { name: toolName, response: { name: toolName, content: contentPart.text } } }); break; case "image-data": parts.push( { inlineData: { mimeType: String(contentPart.mediaType), data: String(contentPart.data) } }, { text: "Tool executed successfully and returned this image as a response" } ); break; default: parts.push({ text: JSON.stringify(contentPart) }); break; } } } function convertToGoogleGenerativeAIMessages(prompt, options) { var _a18, _b18, _c, _d, _e, _f, _g, _h; const systemInstructionParts = []; const contents = []; let systemMessagesAllowed = true; const isGemmaModel = (_a18 = options == null ? void 0 : options.isGemmaModel) != null ? _a18 : false; const providerOptionsName = (_b18 = options == null ? void 0 : options.providerOptionsName) != null ? _b18 : "google"; const supportsFunctionResponseParts = (_c = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _c : true; for (const { role, content } of prompt) { switch (role) { case "system": { if (!systemMessagesAllowed) { throw new UnsupportedFunctionalityError2({ functionality: "system messages are only supported at the beginning of the conversation" }); } systemInstructionParts.push({ text: content }); break; } case "user": { systemMessagesAllowed = false; const parts = []; for (const part of content) { switch (part.type) { case "text": { parts.push({ text: part.text }); break; } case "file": { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; parts.push( part.data instanceof URL ? { fileData: { mimeType: mediaType, fileUri: part.data.toString() } } : { inlineData: { mimeType: mediaType, data: convertToBase642(part.data) } } ); break; } } } contents.push({ role: "user", parts }); break; } case "assistant": { systemMessagesAllowed = false; contents.push({ role: "model", parts: content.map((part) => { var _a23, _b23, _c2, _d2; const providerOpts = (_d2 = (_a23 = part.providerOptions) == null ? void 0 : _a23[providerOptionsName]) != null ? _d2 : providerOptionsName !== "google" ? (_b23 = part.providerOptions) == null ? void 0 : _b23.google : (_c2 = part.providerOptions) == null ? void 0 : _c2.vertex; const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0; switch (part.type) { case "text": { return part.text.length === 0 ? void 0 : { text: part.text, thoughtSignature }; } case "reasoning": { return part.text.length === 0 ? void 0 : { text: part.text, thought: true, thoughtSignature }; } case "file": { if (part.data instanceof URL) { throw new UnsupportedFunctionalityError2({ functionality: "File data URLs in assistant messages are not supported" }); } return { inlineData: { mimeType: part.mediaType, data: convertToBase642(part.data) }, ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {}, thoughtSignature }; } case "tool-call": { const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0; const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0; if (serverToolCallId && serverToolType) { return { toolCall: { toolType: serverToolType, args: typeof part.input === "string" ? JSON.parse(part.input) : part.input, id: serverToolCallId }, thoughtSignature }; } return { functionCall: { name: part.toolName, args: part.input }, thoughtSignature }; } case "tool-result": { const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0; const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0; if (serverToolCallId && serverToolType) { return { toolResponse: { toolType: serverToolType, response: part.output.type === "json" ? part.output.value : {}, id: serverToolCallId }, thoughtSignature }; } return void 0; } } }).filter((part) => part !== void 0) }); break; } case "tool": { systemMessagesAllowed = false; const parts = []; for (const part of content) { if (part.type === "tool-approval-response") { continue; } const partProviderOpts = (_g = (_d = part.providerOptions) == null ? void 0 : _d[providerOptionsName]) != null ? _g : providerOptionsName !== "google" ? (_e = part.providerOptions) == null ? void 0 : _e.google : (_f = part.providerOptions) == null ? void 0 : _f.vertex; const serverToolCallId = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0; const serverToolType = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0; if (serverToolCallId && serverToolType) { const serverThoughtSignature = (partProviderOpts == null ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0; if (contents.length > 0) { const lastContent = contents[contents.length - 1]; if (lastContent.role === "model") { lastContent.parts.push({ toolResponse: { toolType: serverToolType, response: part.output.type === "json" ? part.output.value : {}, id: serverToolCallId }, thoughtSignature: serverThoughtSignature }); continue; } } } const output = part.output; if (output.type === "content") { if (supportsFunctionResponseParts) { appendToolResultParts(parts, part.toolName, output.value); } else { appendLegacyToolResultParts(parts, part.toolName, output.value); } } else { parts.push({ functionResponse: { name: part.toolName, response: { name: part.toolName, content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool execution denied." : output.value } } }); } } contents.push({ role: "user", parts }); break; } } } if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") { const systemText = systemInstructionParts.map((part) => part.text).join("\n\n"); contents[0].parts.unshift({ text: systemText + "\n\n" }); } return { systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0, contents }; } function getModelPath(modelId) { return modelId.includes("/") ? modelId : `models/${modelId}`; } var googleLanguageModelOptions = lazySchema2( () => zodSchema2( z4.z.object({ responseModalities: z4.z.array(z4.z.enum(["TEXT", "IMAGE"])).optional(), thinkingConfig: z4.z.object({ thinkingBudget: z4.z.number().optional(), includeThoughts: z4.z.boolean().optional(), // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level thinkingLevel: z4.z.enum(["minimal", "low", "medium", "high"]).optional() }).optional(), /** * Optional. * The name of the cached content used as context to serve the prediction. * Format: cachedContents/{cachedContent} */ cachedContent: z4.z.string().optional(), /** * Optional. Enable structured output. Default is true. * * This is useful when the JSON Schema contains elements that are * not supported by the OpenAPI schema version that * Google Generative AI uses. You can use this to disable * structured outputs if you need to. */ structuredOutputs: z4.z.boolean().optional(), /** * Optional. A list of unique safety settings for blocking unsafe content. */ safetySettings: z4.z.array( z4.z.object({ category: z4.z.enum([ "HARM_CATEGORY_UNSPECIFIED", "HARM_CATEGORY_HATE_SPEECH", "HARM_CATEGORY_DANGEROUS_CONTENT", "HARM_CATEGORY_HARASSMENT", "HARM_CATEGORY_SEXUALLY_EXPLICIT", "HARM_CATEGORY_CIVIC_INTEGRITY" ]), threshold: z4.z.enum([ "HARM_BLOCK_THRESHOLD_UNSPECIFIED", "BLOCK_LOW_AND_ABOVE", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_ONLY_HIGH", "BLOCK_NONE", "OFF" ]) }) ).optional(), threshold: z4.z.enum([ "HARM_BLOCK_THRESHOLD_UNSPECIFIED", "BLOCK_LOW_AND_ABOVE", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_ONLY_HIGH", "BLOCK_NONE", "OFF" ]).optional(), /** * Optional. Enables timestamp understanding for audio-only files. * * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding */ audioTimestamp: z4.z.boolean().optional(), /** * Optional. Defines labels used in billing reports. Available on Vertex AI only. * * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls */ labels: z4.z.record(z4.z.string(), z4.z.string()).optional(), /** * Optional. If specified, the media resolution specified will be used. * * https://ai.google.dev/api/generate-content#MediaResolution */ mediaResolution: z4.z.enum([ "MEDIA_RESOLUTION_UNSPECIFIED", "MEDIA_RESOLUTION_LOW", "MEDIA_RESOLUTION_MEDIUM", "MEDIA_RESOLUTION_HIGH" ]).optional(), /** * Optional. Configures the image generation aspect ratio for Gemini models. * * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios */ imageConfig: z4.z.object({ aspectRatio: z4.z.enum([ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:8", "8:1", "1:4", "4:1" ]).optional(), imageSize: z4.z.enum(["1K", "2K", "4K", "512"]).optional() }).optional(), /** * Optional. Configuration for grounding retrieval. * Used to provide location context for Google Maps and Google Search grounding. * * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps */ retrievalConfig: z4.z.object({ latLng: z4.z.object({ latitude: z4.z.number(), longitude: z4.z.number() }).optional() }).optional(), /** * Optional. When set to true, function call arguments will be streamed * incrementally via partialArgs in streaming responses. Only supported * on the Vertex AI API (not the Gemini API) and only for Gemini 3+ * models. * * @default false * * https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc */ streamFunctionCallArguments: z4.z.boolean().optional(), /** * Optional. The service tier to use for the request. */ serviceTier: z4.z.enum(["standard", "flex", "priority"]).optional() }) ) ); var VertexServiceTierMap = { standard: "SERVICE_TIER_STANDARD", flex: "SERVICE_TIER_FLEX", priority: "SERVICE_TIER_PRIORITY" }; function prepareTools3({ tools, toolChoice, modelId, isVertexProvider = false }) { var _a18, _b18; tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; const isLatest = [ "gemini-flash-latest", "gemini-flash-lite-latest", "gemini-pro-latest" ].some((id) => id === modelId); const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest; const isGemini3orNewer = modelId.includes("gemini-3"); const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3"); if (tools == null) { return { tools: void 0, toolConfig: void 0, toolWarnings }; } const hasFunctionTools = tools.some((tool3) => tool3.type === "function"); const hasProviderTools = tools.some((tool3) => tool3.type === "provider"); if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) { toolWarnings.push({ type: "unsupported", feature: `combination of function and provider-defined tools` }); } if (hasProviderTools) { const googleTools2 = []; const ProviderTools = tools.filter((tool3) => tool3.type === "provider"); ProviderTools.forEach((tool3) => { switch (tool3.id) { case "google.google_search": if (isGemini2orNewer) { googleTools2.push({ googleSearch: { ...tool3.args } }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "Google Search requires Gemini 2.0 or newer." }); } break; case "google.enterprise_web_search": if (isGemini2orNewer) { googleTools2.push({ enterpriseWebSearch: {} }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "Enterprise Web Search requires Gemini 2.0 or newer." }); } break; case "google.url_context": if (isGemini2orNewer) { googleTools2.push({ urlContext: {} }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "The URL context tool is not supported with other Gemini models than Gemini 2." }); } break; case "google.code_execution": if (isGemini2orNewer) { googleTools2.push({ codeExecution: {} }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "The code execution tool is not supported with other Gemini models than Gemini 2." }); } break; case "google.file_search": if (supportsFileSearch) { googleTools2.push({ fileSearch: { ...tool3.args } }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models." }); } break; case "google.vertex_rag_store": if (isGemini2orNewer) { googleTools2.push({ retrieval: { vertex_rag_store: { rag_resources: { rag_corpus: tool3.args.ragCorpus }, similarity_top_k: tool3.args.topK } } }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "The RAG store tool is not supported with other Gemini models than Gemini 2." }); } break; case "google.google_maps": if (isGemini2orNewer) { googleTools2.push({ googleMaps: {} }); } else { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer." }); } break; default: toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}` }); break; } }); if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) { const functionDeclarations2 = []; for (const tool3 of tools) { if (tool3.type === "function") { functionDeclarations2.push({ name: tool3.name, description: (_a18 = tool3.description) != null ? _a18 : "", parameters: convertJSONSchemaToOpenAPISchema(tool3.inputSchema) }); } } const combinedToolConfig = { functionCallingConfig: { mode: "VALIDATED" }, ...!isVertexProvider && { includeServerSideToolInvocations: true } }; if (toolChoice != null) { switch (toolChoice.type) { case "auto": break; case "none": combinedToolConfig.functionCallingConfig = { mode: "NONE" }; break; case "required": combinedToolConfig.functionCallingConfig = { mode: "ANY" }; break; case "tool": combinedToolConfig.functionCallingConfig = { mode: "ANY", allowedFunctionNames: [toolChoice.toolName] }; break; } } return { tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }], toolConfig: combinedToolConfig, toolWarnings }; } return { tools: googleTools2.length > 0 ? googleTools2 : void 0, toolConfig: void 0, toolWarnings }; } const functionDeclarations = []; let hasStrictTools = false; for (const tool3 of tools) { switch (tool3.type) { case "function": functionDeclarations.push({ name: tool3.name, description: (_b18 = tool3.description) != null ? _b18 : "", parameters: convertJSONSchemaToOpenAPISchema(tool3.inputSchema) }); if (tool3.strict === true) { hasStrictTools = true; } break; default: toolWarnings.push({ type: "unsupported", feature: `function tool ${tool3.name}` }); break; } } if (toolChoice == null) { return { tools: [{ functionDeclarations }], toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "AUTO" } }, toolWarnings }; case "none": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: "NONE" } }, toolWarnings }; case "required": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "ANY" } }, toolWarnings }; case "tool": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "ANY", allowedFunctionNames: [toolChoice.toolName] } }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError2({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } var GoogleJSONAccumulator = class { constructor() { this.accumulatedArgs = {}; this.jsonText = ""; this.pathStack = []; this.stringOpen = false; } /** * Input: [{jsonPath:"$.brightness",numberValue:50}] * Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' } */ processPartialArgs(partialArgs) { let delta = ""; for (const arg of partialArgs) { const rawPath = arg.jsonPath.replace(/^\$\./, ""); if (!rawPath) continue; const segments = parsePath(rawPath); const existingValue = getNestedValue(this.accumulatedArgs, segments); const isStringContinuation = arg.stringValue != null && existingValue !== void 0; if (isStringContinuation) { const escaped = JSON.stringify(arg.stringValue).slice(1, -1); setNestedValue( this.accumulatedArgs, segments, existingValue + arg.stringValue ); delta += escaped; continue; } const resolved = resolvePartialArgValue(arg); if (resolved == null) continue; setNestedValue(this.accumulatedArgs, segments, resolved.value); delta += this.emitNavigationTo(segments, arg, resolved.json); } this.jsonText += delta; return { currentJSON: this.accumulatedArgs, textDelta: delta }; } /** * Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50} * Output: { finalJSON:'{"brightness":50}', closingDelta:'}' } */ finalize() { const finalArgs = JSON.stringify(this.accumulatedArgs); const closingDelta = finalArgs.slice(this.jsonText.length); return { finalJSON: finalArgs, closingDelta }; } /** * Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls) * Output: '{' (first call) or '' (subsequent calls) */ ensureRoot() { if (this.pathStack.length === 0) { this.pathStack.push({ segment: "", isArray: false, childCount: 0 }); return "{"; } return ""; } /** * Emits the JSON text fragment needed to navigate from the current open * path to the new leaf at `targetSegments`, then writes the value. * * Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"' * Output: '{"recipe":{"name":"Lasagna"' */ emitNavigationTo(targetSegments, arg, valueJson) { let fragment = ""; if (this.stringOpen) { fragment += '"'; this.stringOpen = false; } fragment += this.ensureRoot(); const targetContainerSegments = targetSegments.slice(0, -1); const leafSegment = targetSegments[targetSegments.length - 1]; const commonDepth = this.findCommonStackDepth(targetContainerSegments); fragment += this.closeDownTo(commonDepth); fragment += this.openDownTo(targetContainerSegments, leafSegment); fragment += this.emitLeaf(leafSegment, arg, valueJson); return fragment; } /** * Returns the stack depth to preserve when navigating to a new target * container path. Always >= 1 (the root is never popped). * * Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1] * Output: 3 (keep root+"recipe"+"ingredients") */ findCommonStackDepth(targetContainer) { const maxDepth = Math.min( this.pathStack.length - 1, targetContainer.length ); let common = 0; for (let i = 0; i < maxDepth; i++) { if (this.pathStack[i + 1].segment === targetContainer[i]) { common++; } else { break; } } return common + 1; } /** * Closes containers from the current stack depth back down to `targetDepth`. * * Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3 * Output: '}' */ closeDownTo(targetDepth) { let fragment = ""; while (this.pathStack.length > targetDepth) { const entry = this.pathStack.pop(); fragment += entry.isArray ? "]" : "}"; } return fragment; } /** * Opens containers from the current stack depth down to the full target * container path, emitting opening `{`, `[`, keys, and commas as needed. * `leafSegment` is used to determine if the innermost container is an array. * * Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0 * Output: '"recipe":{"ingredients":[' */ openDownTo(targetContainer, leafSegment) { let fragment = ""; const startIdx = this.pathStack.length - 1; for (let i = startIdx; i < targetContainer.length; i++) { const seg = targetContainer[i]; const parentEntry = this.pathStack[this.pathStack.length - 1]; if (parentEntry.childCount > 0) { fragment += ","; } parentEntry.childCount++; if (typeof seg === "string") { fragment += `${JSON.stringify(seg)}:`; } const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment; const isArray = typeof childSeg === "number"; fragment += isArray ? "[" : "{"; this.pathStack.push({ segment: seg, isArray, childCount: 0 }); } return fragment; } /** * Emits the comma, key, and value for a leaf entry in the current container. * * Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"' * Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0) */ emitLeaf(leafSegment, arg, valueJson) { let fragment = ""; const container = this.pathStack[this.pathStack.length - 1]; if (container.childCount > 0) { fragment += ","; } container.childCount++; if (typeof leafSegment === "string") { fragment += `${JSON.stringify(leafSegment)}:`; } if (arg.stringValue != null && arg.willContinue) { fragment += valueJson.slice(0, -1); this.stringOpen = true; } else { fragment += valueJson; } return fragment; } }; function parsePath(rawPath) { const segments = []; for (const part of rawPath.split(".")) { const bracketIdx = part.indexOf("["); if (bracketIdx === -1) { segments.push(part); } else { if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx)); for (const m of part.matchAll(/\[(\d+)\]/g)) { segments.push(parseInt(m[1], 10)); } } } return segments; } function getNestedValue(obj, segments) { let current = obj; for (const seg of segments) { if (current == null || typeof current !== "object") return void 0; current = current[seg]; } return current; } function setNestedValue(obj, segments, value) { let current = obj; for (let i = 0; i < segments.length - 1; i++) { const seg = segments[i]; const nextSeg = segments[i + 1]; if (current[seg] == null) { current[seg] = typeof nextSeg === "number" ? [] : {}; } current = current[seg]; } current[segments[segments.length - 1]] = value; } function resolvePartialArgValue(arg) { var _a18, _b18; const value = (_b18 = (_a18 = arg.stringValue) != null ? _a18 : arg.numberValue) != null ? _b18 : arg.boolValue; if (value != null) return { value, json: JSON.stringify(value) }; if ("nullValue" in arg) return { value: null, json: "null" }; return void 0; } function mapGoogleGenerativeAIFinishReason({ finishReason, hasToolCalls }) { switch (finishReason) { case "STOP": return hasToolCalls ? "tool-calls" : "stop"; case "MAX_TOKENS": return "length"; case "IMAGE_SAFETY": case "RECITATION": case "SAFETY": case "BLOCKLIST": case "PROHIBITED_CONTENT": case "SPII": return "content-filter"; case "MALFORMED_FUNCTION_CALL": return "error"; case "FINISH_REASON_UNSPECIFIED": case "OTHER": default: return "other"; } } var GoogleGenerativeAILanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v3"; var _a18; this.modelId = modelId; this.config = config; this.generateId = (_a18 = config.generateId) != null ? _a18 : generateId2; } get provider() { return this.config.provider; } get supportedUrls() { var _a18, _b18, _c; return (_c = (_b18 = (_a18 = this.config).supportedUrls) == null ? void 0 : _b18.call(_a18)) != null ? _c : {}; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }, { isStreaming = false } = {}) { var _a18, _b18; const warnings = []; const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google"; let googleOptions = await parseProviderOptions2({ provider: providerOptionsName, providerOptions, schema: googleLanguageModelOptions }); if (googleOptions == null && providerOptionsName !== "google") { googleOptions = await parseProviderOptions2({ provider: "google", providerOptions, schema: googleLanguageModelOptions }); } const isVertexProvider = this.config.provider.startsWith("google.vertex."); if ((tools == null ? void 0 : tools.some( (tool3) => tool3.type === "provider" && tool3.id === "google.vertex_rag_store" )) && !isVertexProvider) { warnings.push({ type: "other", message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).` }); } if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) { warnings.push({ type: "other", message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc` }); } let sanitizedServiceTier = googleOptions == null ? void 0 : googleOptions.serviceTier; if ((googleOptions == null ? void 0 : googleOptions.serviceTier) && isVertexProvider) { sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier]; } const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-"); const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3"); const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages( prompt, { isGemmaModel, providerOptionsName, supportsFunctionResponseParts } ); const { tools: googleTools2, toolConfig: googleToolConfig, toolWarnings } = prepareTools3({ tools, toolChoice, modelId: this.modelId, isVertexProvider }); const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a18 = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a18 : false : void 0; const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? { ...googleToolConfig, ...streamFunctionCallArguments && { functionCallingConfig: { ...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig, streamFunctionCallArguments: true } }, ...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && { retrievalConfig: googleOptions.retrievalConfig } } : void 0; return { args: { generationConfig: { // standardized settings: maxOutputTokens, temperature, topK, topP, frequencyPenalty, presencePenalty, stopSequences, seed, // response format: responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0, responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features, // so this is needed as an escape hatch: // TODO convert into provider option ((_b18 = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b18 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0, ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && { audioTimestamp: googleOptions.audioTimestamp }, // provider options: responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities, thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig, ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && { mediaResolution: googleOptions.mediaResolution }, ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && { imageConfig: googleOptions.imageConfig } }, contents, systemInstruction: isGemmaModel ? void 0 : systemInstruction, safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings, tools: googleTools2, toolConfig, cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent, labels: googleOptions == null ? void 0 : googleOptions.labels, serviceTier: sanitizedServiceTier }, warnings: [...warnings, ...toolWarnings], providerOptionsName }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; const { args, warnings, providerOptionsName } = await this.getArgs(options); const mergedHeaders = combineHeaders2( await resolve2(this.config.headers), options.headers ); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi2({ url: `${this.config.baseURL}/${getModelPath( this.modelId )}:generateContent`, headers: mergedHeaders, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2(responseSchema), abortSignal: options.abortSignal, fetch: this.config.fetch }); const candidate = response.candidates[0]; const content = []; const parts = (_b18 = (_a18 = candidate.content) == null ? void 0 : _a18.parts) != null ? _b18 : []; const usageMetadata = response.usageMetadata; let lastCodeExecutionToolCallId; let lastServerToolCallId; for (const part of parts) { if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) { const toolCallId = this.config.generateId(); lastCodeExecutionToolCallId = toolCallId; content.push({ type: "tool-call", toolCallId, toolName: "code_execution", input: JSON.stringify(part.executableCode), providerExecuted: true }); } else if ("codeExecutionResult" in part && part.codeExecutionResult) { content.push({ type: "tool-result", // Assumes a result directly follows its corresponding call part. toolCallId: lastCodeExecutionToolCallId, toolName: "code_execution", result: { outcome: part.codeExecutionResult.outcome, output: (_d = part.codeExecutionResult.output) != null ? _d : "" } }); lastCodeExecutionToolCallId = void 0; } else if ("text" in part && part.text != null) { const thoughtSignatureMetadata = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0; if (part.text.length === 0) { if (thoughtSignatureMetadata != null && content.length > 0) { const lastContent = content[content.length - 1]; lastContent.providerMetadata = thoughtSignatureMetadata; } } else { content.push({ type: part.thought === true ? "reasoning" : "text", text: part.text, providerMetadata: thoughtSignatureMetadata }); } } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) { content.push({ type: "tool-call", toolCallId: this.config.generateId(), toolName: part.functionCall.name, input: JSON.stringify(part.functionCall.args), providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0 }); } else if ("inlineData" in part) { const hasThought = part.thought === true; const hasThoughtSignature = !!part.thoughtSignature; content.push({ type: "file", data: part.inlineData.data, mediaType: part.inlineData.mimeType, providerMetadata: hasThought || hasThoughtSignature ? { [providerOptionsName]: { ...hasThought ? { thought: true } : {}, ...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {} } } : void 0 }); } else if ("toolCall" in part && part.toolCall) { const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId(); lastServerToolCallId = toolCallId; content.push({ type: "tool-call", toolCallId, toolName: `server:${part.toolCall.toolType}`, input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}), providerExecuted: true, dynamic: true, providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature, serverToolCallId: toolCallId, serverToolType: part.toolCall.toolType } } : { [providerOptionsName]: { serverToolCallId: toolCallId, serverToolType: part.toolCall.toolType } } }); } else if ("toolResponse" in part && part.toolResponse) { const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId(); content.push({ type: "tool-result", toolCallId: responseToolCallId, toolName: `server:${part.toolResponse.toolType}`, result: (_h = part.toolResponse.response) != null ? _h : {}, providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature, serverToolCallId: responseToolCallId, serverToolType: part.toolResponse.toolType } } : { [providerOptionsName]: { serverToolCallId: responseToolCallId, serverToolType: part.toolResponse.toolType } } }); lastServerToolCallId = void 0; } } const sources = (_i = extractSources({ groundingMetadata: candidate.groundingMetadata, generateId: this.config.generateId })) != null ? _i : []; for (const source of sources) { content.push(source); } return { content, finishReason: { unified: mapGoogleGenerativeAIFinishReason({ finishReason: candidate.finishReason, // Only count client-executed tool calls for finish reason determination. hasToolCalls: content.some( (part) => part.type === "tool-call" && !part.providerExecuted ) }), raw: (_j = candidate.finishReason) != null ? _j : void 0 }, usage: convertGoogleGenerativeAIUsage(usageMetadata), warnings, providerMetadata: { [providerOptionsName]: { promptFeedback: (_k = response.promptFeedback) != null ? _k : null, groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null, urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null, safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null, usageMetadata: usageMetadata != null ? usageMetadata : null, finishMessage: (_o = candidate.finishMessage) != null ? _o : null, serviceTier: (_p = response.serviceTier) != null ? _p : null } }, request: { body: args }, response: { // TODO timestamp, model id, id headers: responseHeaders, body: rawResponse } }; } async doStream(options) { const { args, warnings, providerOptionsName } = await this.getArgs( options, { isStreaming: true } ); const headers = combineHeaders2( await resolve2(this.config.headers), options.headers ); const { responseHeaders, value: response } = await postJsonToApi2({ url: `${this.config.baseURL}/${getModelPath( this.modelId )}:streamGenerateContent?alt=sse`, headers, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2(chunkSchema), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; let providerMetadata = void 0; let lastGroundingMetadata = null; let lastUrlContextMetadata = null; let serviceTier = null; const generateId3 = this.config.generateId; let hasToolCalls = false; let currentTextBlockId = null; let currentReasoningBlockId = null; let blockCounter = 0; const emittedSourceUrls = /* @__PURE__ */ new Set(); let lastCodeExecutionToolCallId; let lastServerToolCallId; const activeStreamingToolCalls = []; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; const usageMetadata = value.usageMetadata; if (usageMetadata != null) { usage = usageMetadata; } if (value.serviceTier != null) { serviceTier = value.serviceTier; } const candidate = (_a18 = value.candidates) == null ? void 0 : _a18[0]; if (candidate == null) { return; } const content = candidate.content; if (candidate.groundingMetadata != null) { lastGroundingMetadata = candidate.groundingMetadata; } if (candidate.urlContextMetadata != null) { lastUrlContextMetadata = candidate.urlContextMetadata; } const sources = extractSources({ groundingMetadata: candidate.groundingMetadata, generateId: generateId3 }); if (sources != null) { for (const source of sources) { if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) { emittedSourceUrls.add(source.url); controller.enqueue(source); } } } if (content != null) { const parts = (_b18 = content.parts) != null ? _b18 : []; for (const part of parts) { if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) { const toolCallId = generateId3(); lastCodeExecutionToolCallId = toolCallId; controller.enqueue({ type: "tool-call", toolCallId, toolName: "code_execution", input: JSON.stringify(part.executableCode), providerExecuted: true }); } else if ("codeExecutionResult" in part && part.codeExecutionResult) { const toolCallId = lastCodeExecutionToolCallId; if (toolCallId) { controller.enqueue({ type: "tool-result", toolCallId, toolName: "code_execution", result: { outcome: part.codeExecutionResult.outcome, output: (_d = part.codeExecutionResult.output) != null ? _d : "" } }); lastCodeExecutionToolCallId = void 0; } } else if ("text" in part && part.text != null) { const thoughtSignatureMetadata = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0; if (part.text.length === 0) { if (thoughtSignatureMetadata != null && currentTextBlockId !== null) { controller.enqueue({ type: "text-delta", id: currentTextBlockId, delta: "", providerMetadata: thoughtSignatureMetadata }); } } else if (part.thought === true) { if (currentTextBlockId !== null) { controller.enqueue({ type: "text-end", id: currentTextBlockId }); currentTextBlockId = null; } if (currentReasoningBlockId === null) { currentReasoningBlockId = String(blockCounter++); controller.enqueue({ type: "reasoning-start", id: currentReasoningBlockId, providerMetadata: thoughtSignatureMetadata }); } controller.enqueue({ type: "reasoning-delta", id: currentReasoningBlockId, delta: part.text, providerMetadata: thoughtSignatureMetadata }); } else { if (currentReasoningBlockId !== null) { controller.enqueue({ type: "reasoning-end", id: currentReasoningBlockId }); currentReasoningBlockId = null; } if (currentTextBlockId === null) { currentTextBlockId = String(blockCounter++); controller.enqueue({ type: "text-start", id: currentTextBlockId, providerMetadata: thoughtSignatureMetadata }); } controller.enqueue({ type: "text-delta", id: currentTextBlockId, delta: part.text, providerMetadata: thoughtSignatureMetadata }); } } else if ("inlineData" in part) { if (currentTextBlockId !== null) { controller.enqueue({ type: "text-end", id: currentTextBlockId }); currentTextBlockId = null; } if (currentReasoningBlockId !== null) { controller.enqueue({ type: "reasoning-end", id: currentReasoningBlockId }); currentReasoningBlockId = null; } const hasThought = part.thought === true; const hasThoughtSignature = !!part.thoughtSignature; const fileMeta = hasThought || hasThoughtSignature ? { [providerOptionsName]: { ...hasThought ? { thought: true } : {}, ...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {} } } : void 0; controller.enqueue({ type: "file", mediaType: part.inlineData.mimeType, data: part.inlineData.data, providerMetadata: fileMeta }); } else if ("toolCall" in part && part.toolCall) { const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId3(); lastServerToolCallId = toolCallId; const serverMeta = { [providerOptionsName]: { ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}, serverToolCallId: toolCallId, serverToolType: part.toolCall.toolType } }; controller.enqueue({ type: "tool-call", toolCallId, toolName: `server:${part.toolCall.toolType}`, input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}), providerExecuted: true, dynamic: true, providerMetadata: serverMeta }); } else if ("toolResponse" in part && part.toolResponse) { const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId3(); const serverMeta = { [providerOptionsName]: { ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}, serverToolCallId: responseToolCallId, serverToolType: part.toolResponse.toolType } }; controller.enqueue({ type: "tool-result", toolCallId: responseToolCallId, toolName: `server:${part.toolResponse.toolType}`, result: (_h = part.toolResponse.response) != null ? _h : {}, providerMetadata: serverMeta }); lastServerToolCallId = void 0; } } for (const part of parts) { if (!("functionCall" in part)) continue; const providerMeta = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0; const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true; const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null; const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null; if (isStreamingChunk) { if (part.functionCall.name != null && part.functionCall.willContinue === true) { const toolCallId = generateId3(); const accumulator = new GoogleJSONAccumulator(); activeStreamingToolCalls.push({ toolCallId, toolName: part.functionCall.name, accumulator, providerMetadata: providerMeta }); controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName: part.functionCall.name, providerMetadata: providerMeta }); if (part.functionCall.partialArgs != null) { const { textDelta } = accumulator.processPartialArgs( part.functionCall.partialArgs ); if (textDelta.length > 0) { controller.enqueue({ type: "tool-input-delta", id: toolCallId, delta: textDelta, providerMetadata: providerMeta }); } } } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) { const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1]; const { textDelta } = active.accumulator.processPartialArgs( part.functionCall.partialArgs ); if (textDelta.length > 0) { controller.enqueue({ type: "tool-input-delta", id: active.toolCallId, delta: textDelta, providerMetadata: providerMeta }); } } } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) { const active = activeStreamingToolCalls.pop(); const { finalJSON, closingDelta } = active.accumulator.finalize(); if (closingDelta.length > 0) { controller.enqueue({ type: "tool-input-delta", id: active.toolCallId, delta: closingDelta, providerMetadata: active.providerMetadata }); } controller.enqueue({ type: "tool-input-end", id: active.toolCallId, providerMetadata: active.providerMetadata }); controller.enqueue({ type: "tool-call", toolCallId: active.toolCallId, toolName: active.toolName, input: finalJSON, providerMetadata: active.providerMetadata }); hasToolCalls = true; } else if (isCompleteCall) { const toolCallId = generateId3(); const toolName = part.functionCall.name; const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {}); controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName, providerMetadata: providerMeta }); controller.enqueue({ type: "tool-input-delta", id: toolCallId, delta: args2, providerMetadata: providerMeta }); controller.enqueue({ type: "tool-input-end", id: toolCallId, providerMetadata: providerMeta }); controller.enqueue({ type: "tool-call", toolCallId, toolName, input: args2, providerMetadata: providerMeta }); hasToolCalls = true; } } } if (candidate.finishReason != null) { finishReason = { unified: mapGoogleGenerativeAIFinishReason({ finishReason: candidate.finishReason, hasToolCalls }), raw: candidate.finishReason }; providerMetadata = { [providerOptionsName]: { promptFeedback: (_j = value.promptFeedback) != null ? _j : null, groundingMetadata: lastGroundingMetadata, urlContextMetadata: lastUrlContextMetadata, safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null, usageMetadata: usageMetadata != null ? usageMetadata : null, finishMessage: (_l = candidate.finishMessage) != null ? _l : null, serviceTier } }; } }, flush(controller) { if (currentTextBlockId !== null) { controller.enqueue({ type: "text-end", id: currentTextBlockId }); } if (currentReasoningBlockId !== null) { controller.enqueue({ type: "reasoning-end", id: currentReasoningBlockId }); } controller.enqueue({ type: "finish", finishReason, usage: convertGoogleGenerativeAIUsage(usage), providerMetadata }); } }) ), response: { headers: responseHeaders }, request: { body: args } }; } }; function extractSources({ groundingMetadata, generateId: generateId3 }) { var _a18, _b18, _c, _d, _e, _f; if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) { return void 0; } const sources = []; for (const chunk of groundingMetadata.groundingChunks) { if (chunk.web != null) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: chunk.web.uri, title: (_a18 = chunk.web.title) != null ? _a18 : void 0 }); } else if (chunk.image != null) { sources.push({ type: "source", sourceType: "url", id: generateId3(), // Google requires attribution to the source URI, not the actual image URI. // TODO: add another type in v7 to allow both the image and source URL to be included separately url: chunk.image.sourceUri, title: (_b18 = chunk.image.title) != null ? _b18 : void 0 }); } else if (chunk.retrievedContext != null) { const uri = chunk.retrievedContext.uri; const fileSearchStore = chunk.retrievedContext.fileSearchStore; if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: uri, title: (_c = chunk.retrievedContext.title) != null ? _c : void 0 }); } else if (uri) { const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document"; let mediaType = "application/octet-stream"; let filename = void 0; if (uri.endsWith(".pdf")) { mediaType = "application/pdf"; filename = uri.split("/").pop(); } else if (uri.endsWith(".txt")) { mediaType = "text/plain"; filename = uri.split("/").pop(); } else if (uri.endsWith(".docx")) { mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; filename = uri.split("/").pop(); } else if (uri.endsWith(".doc")) { mediaType = "application/msword"; filename = uri.split("/").pop(); } else if (uri.match(/\.(md|markdown)$/)) { mediaType = "text/markdown"; filename = uri.split("/").pop(); } else { filename = uri.split("/").pop(); } sources.push({ type: "source", sourceType: "document", id: generateId3(), mediaType, title, filename }); } else if (fileSearchStore) { const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document"; sources.push({ type: "source", sourceType: "document", id: generateId3(), mediaType: "application/octet-stream", title, filename: fileSearchStore.split("/").pop() }); } } else if (chunk.maps != null) { if (chunk.maps.uri) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: chunk.maps.uri, title: (_f = chunk.maps.title) != null ? _f : void 0 }); } } } return sources.length > 0 ? sources : void 0; } var getGroundingMetadataSchema = () => z4.z.object({ webSearchQueries: z4.z.array(z4.z.string()).nullish(), imageSearchQueries: z4.z.array(z4.z.string()).nullish(), retrievalQueries: z4.z.array(z4.z.string()).nullish(), searchEntryPoint: z4.z.object({ renderedContent: z4.z.string() }).nullish(), groundingChunks: z4.z.array( z4.z.object({ web: z4.z.object({ uri: z4.z.string(), title: z4.z.string().nullish() }).nullish(), image: z4.z.object({ sourceUri: z4.z.string(), imageUri: z4.z.string(), title: z4.z.string().nullish(), domain: z4.z.string().nullish() }).nullish(), retrievedContext: z4.z.object({ uri: z4.z.string().nullish(), title: z4.z.string().nullish(), text: z4.z.string().nullish(), fileSearchStore: z4.z.string().nullish() }).nullish(), maps: z4.z.object({ uri: z4.z.string().nullish(), title: z4.z.string().nullish(), text: z4.z.string().nullish(), placeId: z4.z.string().nullish() }).nullish() }) ).nullish(), groundingSupports: z4.z.array( z4.z.object({ segment: z4.z.object({ startIndex: z4.z.number().nullish(), endIndex: z4.z.number().nullish(), text: z4.z.string().nullish() }).nullish(), segment_text: z4.z.string().nullish(), groundingChunkIndices: z4.z.array(z4.z.number()).nullish(), supportChunkIndices: z4.z.array(z4.z.number()).nullish(), confidenceScores: z4.z.array(z4.z.number()).nullish(), confidenceScore: z4.z.array(z4.z.number()).nullish() }) ).nullish(), retrievalMetadata: z4.z.union([ z4.z.object({ webDynamicRetrievalScore: z4.z.number() }), z4.z.object({}) ]).nullish() }); var partialArgSchema = z4.z.object({ jsonPath: z4.z.string(), stringValue: z4.z.string().nullish(), numberValue: z4.z.number().nullish(), boolValue: z4.z.boolean().nullish(), nullValue: z4.z.unknown().nullish(), willContinue: z4.z.boolean().nullish() }); var getContentSchema = () => z4.z.object({ parts: z4.z.array( z4.z.union([ // note: order matters since text can be fully empty z4.z.object({ functionCall: z4.z.object({ name: z4.z.string().nullish(), args: z4.z.unknown().nullish(), partialArgs: z4.z.array(partialArgSchema).nullish(), willContinue: z4.z.boolean().nullish() }), thoughtSignature: z4.z.string().nullish() }), z4.z.object({ inlineData: z4.z.object({ mimeType: z4.z.string(), data: z4.z.string() }), thought: z4.z.boolean().nullish(), thoughtSignature: z4.z.string().nullish() }), z4.z.object({ toolCall: z4.z.object({ toolType: z4.z.string(), args: z4.z.unknown().nullish(), id: z4.z.string() }), thoughtSignature: z4.z.string().nullish() }), z4.z.object({ toolResponse: z4.z.object({ toolType: z4.z.string(), response: z4.z.unknown().nullish(), id: z4.z.string() }), thoughtSignature: z4.z.string().nullish() }), z4.z.object({ executableCode: z4.z.object({ language: z4.z.string(), code: z4.z.string() }).nullish(), codeExecutionResult: z4.z.object({ outcome: z4.z.string(), output: z4.z.string().nullish() }).nullish(), text: z4.z.string().nullish(), thought: z4.z.boolean().nullish(), thoughtSignature: z4.z.string().nullish() }) ]) ).nullish() }); var getSafetyRatingSchema = () => z4.z.object({ category: z4.z.string().nullish(), probability: z4.z.string().nullish(), probabilityScore: z4.z.number().nullish(), severity: z4.z.string().nullish(), severityScore: z4.z.number().nullish(), blocked: z4.z.boolean().nullish() }); var tokenDetailsSchema = z4.z.array( z4.z.object({ modality: z4.z.string(), tokenCount: z4.z.number() }) ).nullish(); var usageSchema2 = z4.z.object({ cachedContentTokenCount: z4.z.number().nullish(), thoughtsTokenCount: z4.z.number().nullish(), promptTokenCount: z4.z.number().nullish(), candidatesTokenCount: z4.z.number().nullish(), totalTokenCount: z4.z.number().nullish(), // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType trafficType: z4.z.string().nullish(), // https://ai.google.dev/api/generate-content#Modality promptTokensDetails: tokenDetailsSchema, candidatesTokensDetails: tokenDetailsSchema }); var getUrlContextMetadataSchema = () => z4.z.object({ urlMetadata: z4.z.array( z4.z.object({ retrievedUrl: z4.z.string(), urlRetrievalStatus: z4.z.string() }) ).nullish() }); var responseSchema = lazySchema2( () => zodSchema2( z4.z.object({ candidates: z4.z.array( z4.z.object({ content: getContentSchema().nullish().or(z4.z.object({}).strict()), finishReason: z4.z.string().nullish(), finishMessage: z4.z.string().nullish(), safetyRatings: z4.z.array(getSafetyRatingSchema()).nullish(), groundingMetadata: getGroundingMetadataSchema().nullish(), urlContextMetadata: getUrlContextMetadataSchema().nullish() }) ), usageMetadata: usageSchema2.nullish(), promptFeedback: z4.z.object({ blockReason: z4.z.string().nullish(), safetyRatings: z4.z.array(getSafetyRatingSchema()).nullish() }).nullish(), serviceTier: z4.z.string().nullish() }) ) ); var chunkSchema = lazySchema2( () => zodSchema2( z4.z.object({ candidates: z4.z.array( z4.z.object({ content: getContentSchema().nullish(), finishReason: z4.z.string().nullish(), finishMessage: z4.z.string().nullish(), safetyRatings: z4.z.array(getSafetyRatingSchema()).nullish(), groundingMetadata: getGroundingMetadataSchema().nullish(), urlContextMetadata: getUrlContextMetadataSchema().nullish() }) ).nullish(), usageMetadata: usageSchema2.nullish(), promptFeedback: z4.z.object({ blockReason: z4.z.string().nullish(), safetyRatings: z4.z.array(getSafetyRatingSchema()).nullish() }).nullish(), serviceTier: z4.z.string().nullish() }) ) ); var codeExecution = createProviderToolFactoryWithOutputSchema({ id: "google.code_execution", inputSchema: z4.z.object({ language: z4.z.string().describe("The programming language of the code."), code: z4.z.string().describe("The code to be executed.") }), outputSchema: z4.z.object({ outcome: z4.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'), output: z4.z.string().describe("The output from the code execution.") }) }); var enterpriseWebSearch = createProviderToolFactory({ id: "google.enterprise_web_search", inputSchema: lazySchema2(() => zodSchema2(z4.z.object({}))) }); var fileSearchArgsBaseSchema = z4.z.object({ /** The names of the file_search_stores to retrieve from. * Example: `fileSearchStores/my-file-search-store-123` */ fileSearchStoreNames: z4.z.array(z4.z.string()).describe( "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`" ), /** The number of file search retrieval chunks to retrieve. */ topK: z4.z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(), /** Metadata filter to apply to the file search retrieval documents. * See https://google.aip.dev/160 for the syntax of the filter expression. */ metadataFilter: z4.z.string().describe( "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression." ).optional() }).passthrough(); var fileSearchArgsSchema2 = lazySchema2( () => zodSchema2(fileSearchArgsBaseSchema) ); var fileSearch2 = createProviderToolFactory({ id: "google.file_search", inputSchema: fileSearchArgsSchema2 }); var googleMaps = createProviderToolFactory({ id: "google.google_maps", inputSchema: lazySchema2(() => zodSchema2(z4.z.object({}))) }); var googleSearchToolArgsBaseSchema = z4.z.object({ searchTypes: z4.z.object({ webSearch: z4.z.object({}).optional(), imageSearch: z4.z.object({}).optional() }).optional(), timeRangeFilter: z4.z.object({ startTime: z4.z.string(), endTime: z4.z.string() }).optional() }).passthrough(); var googleSearchToolArgsSchema = lazySchema2( () => zodSchema2(googleSearchToolArgsBaseSchema) ); var googleSearch = createProviderToolFactory( { id: "google.google_search", inputSchema: googleSearchToolArgsSchema } ); var urlContext = createProviderToolFactory({ id: "google.url_context", inputSchema: lazySchema2(() => zodSchema2(z4.z.object({}))) }); var vertexRagStore = createProviderToolFactory({ id: "google.vertex_rag_store", inputSchema: z4.z.object({ ragCorpus: z4.z.string(), topK: z4.z.number().optional() }) }); var googleTools = { /** * Creates a Google search tool that gives Google direct access to real-time web content. * Must have name "google_search". */ googleSearch, /** * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index. * Designed for highly-regulated industries (finance, healthcare, public sector). * Does not log customer data and supports VPC service controls. * Must have name "enterprise_web_search". * * @note Only available on Vertex AI. Requires Gemini 2.0 or newer. * * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise */ enterpriseWebSearch, /** * Creates a Google Maps grounding tool that gives the model access to Google Maps data. * Must have name "google_maps". * * @see https://ai.google.dev/gemini-api/docs/maps-grounding * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps */ googleMaps, /** * Creates a URL context tool that gives Google direct access to real-time web content. * Must have name "url_context". */ urlContext, /** * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool. * Must have name "file_search". * * @param fileSearchStoreNames - Fully-qualified File Search store resource names. * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved. * @param topK - Optional result limit for the number of chunks returned from File Search. * * @see https://ai.google.dev/gemini-api/docs/file-search */ fileSearch: fileSearch2, /** * A tool that enables the model to generate and run Python code. * Must have name "code_execution". * * @note Ensure the selected model supports Code Execution. * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models. * * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI) * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI) */ codeExecution, /** * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store. * Must have name "vertex_rag_store". */ vertexRagStore }; var GoogleGenerativeAIImageModel = class { constructor(modelId, settings, config) { this.modelId = modelId; this.settings = settings; this.config = config; this.specificationVersion = "v3"; } get maxImagesPerCall() { if (this.settings.maxImagesPerCall != null) { return this.settings.maxImagesPerCall; } if (isGeminiModel(this.modelId)) { return 10; } return 4; } get provider() { return this.config.provider; } async doGenerate(options) { if (isGeminiModel(this.modelId)) { return this.doGenerateGemini(options); } return this.doGenerateImagen(options); } async doGenerateImagen(options) { var _a18, _b18, _c; const { prompt, n = 1, size, aspectRatio = "1:1", seed, providerOptions, headers, abortSignal, files, mask } = options; const warnings = []; if (files != null && files.length > 0) { throw new Error( "Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities." ); } if (mask != null) { throw new Error( "Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities." ); } if (size != null) { warnings.push({ type: "unsupported", feature: "size", details: "This model does not support the `size` option. Use `aspectRatio` instead." }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed", details: "This model does not support the `seed` option through this provider." }); } const googleOptions = await parseProviderOptions2({ provider: "google", providerOptions, schema: googleImageModelOptionsSchema }); const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); const parameters = { sampleCount: n }; if (aspectRatio != null) { parameters.aspectRatio = aspectRatio; } if (googleOptions) { Object.assign(parameters, googleOptions); } const body = { instances: [{ prompt }], parameters }; const { responseHeaders, value: response } = await postJsonToApi2({ url: `${this.config.baseURL}/models/${this.modelId}:predict`, headers: combineHeaders2(await resolve2(this.config.headers), headers), body, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response.predictions.map( (p) => p.bytesBase64Encoded ), warnings, providerMetadata: { google: { images: response.predictions.map(() => ({ // Add any prediction-specific metadata here })) } }, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders } }; } async doGenerateGemini(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i; const { prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask } = options; const warnings = []; if (mask != null) { throw new Error( "Gemini image models do not support mask-based image editing." ); } if (n != null && n > 1) { throw new Error( "Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter." ); } if (size != null) { warnings.push({ type: "unsupported", feature: "size", details: "This model does not support the `size` option. Use `aspectRatio` instead." }); } const userContent = []; if (prompt != null) { userContent.push({ type: "text", text: prompt }); } if (files != null && files.length > 0) { for (const file of files) { if (file.type === "url") { userContent.push({ type: "file", data: new URL(file.url), mediaType: "image/*" }); } else { userContent.push({ type: "file", data: typeof file.data === "string" ? file.data : new Uint8Array(file.data), mediaType: file.mediaType }); } } } const languageModelPrompt = [ { role: "user", content: userContent } ]; const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, { provider: this.config.provider, baseURL: this.config.baseURL, headers: (_a18 = this.config.headers) != null ? _a18 : {}, fetch: this.config.fetch, generateId: (_b18 = this.config.generateId) != null ? _b18 : generateId2 }); const result = await languageModel.doGenerate({ prompt: languageModelPrompt, seed, providerOptions: { google: { responseModalities: ["IMAGE"], imageConfig: aspectRatio ? { aspectRatio } : void 0, ...(_c = providerOptions == null ? void 0 : providerOptions.google) != null ? _c : {} } }, headers, abortSignal }); const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date(); const images = []; for (const part of result.content) { if (part.type === "file" && part.mediaType.startsWith("image/")) { images.push(convertToBase642(part.data)); } } return { images, warnings, providerMetadata: { google: { images: images.map(() => ({})) } }, response: { timestamp: currentDate, modelId: this.modelId, headers: (_g = result.response) == null ? void 0 : _g.headers }, usage: result.usage ? { inputTokens: result.usage.inputTokens.total, outputTokens: result.usage.outputTokens.total, totalTokens: ((_h = result.usage.inputTokens.total) != null ? _h : 0) + ((_i = result.usage.outputTokens.total) != null ? _i : 0) } : void 0 }; } }; function isGeminiModel(modelId) { return modelId.startsWith("gemini-"); } var googleImageResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ predictions: z4.z.array(z4.z.object({ bytesBase64Encoded: z4.z.string() })).default([]) }) ) ); var googleImageModelOptionsSchema = lazySchema2( () => zodSchema2( z4.z.object({ personGeneration: z4.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(), aspectRatio: z4.z.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish() }) ) ); var GoogleGenerativeAIVideoModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v3"; } get provider() { return this.config.provider; } get maxVideosPerCall() { return 4; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h; const currentDate = (_c = (_b18 = (_a18 = this.config._internal) == null ? void 0 : _a18.currentDate) == null ? void 0 : _b18.call(_a18)) != null ? _c : /* @__PURE__ */ new Date(); const warnings = []; const googleOptions = await parseProviderOptions2({ provider: "google", providerOptions: options.providerOptions, schema: googleVideoModelOptionsSchema }); const instances = [{}]; const instance = instances[0]; if (options.prompt != null) { instance.prompt = options.prompt; } if (options.image != null) { if (options.image.type === "url") { warnings.push({ type: "unsupported", feature: "URL-based image input", details: "Google Generative AI video models require base64-encoded images. URL will be ignored." }); } else { const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase642(options.image.data); instance.image = { inlineData: { mimeType: options.image.mediaType || "image/png", data: base64Data } }; } } if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) { instance.referenceImages = googleOptions.referenceImages.map((refImg) => { if (refImg.bytesBase64Encoded) { return { inlineData: { mimeType: "image/png", data: refImg.bytesBase64Encoded } }; } else if (refImg.gcsUri) { return { gcsUri: refImg.gcsUri }; } return refImg; }); } const parameters = { sampleCount: options.n }; if (options.aspectRatio) { parameters.aspectRatio = options.aspectRatio; } if (options.resolution) { const resolutionMap = { "1280x720": "720p", "1920x1080": "1080p", "3840x2160": "4k" }; parameters.resolution = resolutionMap[options.resolution] || options.resolution; } if (options.duration) { parameters.durationSeconds = options.duration; } if (options.seed) { parameters.seed = options.seed; } if (googleOptions != null) { const opts = googleOptions; if (opts.personGeneration !== void 0 && opts.personGeneration !== null) { parameters.personGeneration = opts.personGeneration; } if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) { parameters.negativePrompt = opts.negativePrompt; } for (const [key, value] of Object.entries(opts)) { if (![ "pollIntervalMs", "pollTimeoutMs", "personGeneration", "negativePrompt", "referenceImages" ].includes(key)) { parameters[key] = value; } } } const { value: operation } = await postJsonToApi2({ url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`, headers: combineHeaders2( await resolve2(this.config.headers), options.headers ), body: { instances, parameters }, successfulResponseHandler: createJsonResponseHandler2( googleOperationSchema ), failedResponseHandler: googleFailedResponseHandler, abortSignal: options.abortSignal, fetch: this.config.fetch }); const operationName = operation.name; if (!operationName) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_ERROR", message: "No operation name returned from API" }); } const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4; const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5; const startTime = Date.now(); let finalOperation = operation; let responseHeaders; while (!finalOperation.done) { if (Date.now() - startTime > pollTimeoutMs) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_TIMEOUT", message: `Video generation timed out after ${pollTimeoutMs}ms` }); } await delay2(pollIntervalMs); if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_ABORTED", message: "Video generation request was aborted" }); } const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi2({ url: `${this.config.baseURL}/${operationName}`, headers: combineHeaders2( await resolve2(this.config.headers), options.headers ), successfulResponseHandler: createJsonResponseHandler2( googleOperationSchema ), failedResponseHandler: googleFailedResponseHandler, abortSignal: options.abortSignal, fetch: this.config.fetch }); finalOperation = statusOperation; responseHeaders = pollHeaders; } if (finalOperation.error) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_FAILED", message: `Video generation failed: ${finalOperation.error.message}` }); } const response = finalOperation.response; if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_ERROR", message: `No videos in response. Response: ${JSON.stringify(finalOperation)}` }); } const videos = []; const videoMetadata = []; const resolvedHeaders = await resolve2(this.config.headers); const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"]; for (const generatedSample of response.generateVideoResponse.generatedSamples) { if ((_h = generatedSample.video) == null ? void 0 : _h.uri) { const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri; videos.push({ type: "url", url: urlWithAuth, mediaType: "video/mp4" }); videoMetadata.push({ uri: generatedSample.video.uri }); } } if (videos.length === 0) { throw new AISDKError2({ name: "GOOGLE_VIDEO_GENERATION_ERROR", message: "No valid videos in response" }); } return { videos, warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders }, providerMetadata: { google: { videos: videoMetadata } } }; } }; var googleOperationSchema = z4.z.object({ name: z4.z.string().nullish(), done: z4.z.boolean().nullish(), error: z4.z.object({ code: z4.z.number().nullish(), message: z4.z.string(), status: z4.z.string().nullish() }).nullish(), response: z4.z.object({ generateVideoResponse: z4.z.object({ generatedSamples: z4.z.array( z4.z.object({ video: z4.z.object({ uri: z4.z.string().nullish() }).nullish() }) ).nullish() }).nullish() }).nullish() }); var googleVideoModelOptionsSchema = lazySchema2( () => zodSchema2( z4.z.object({ pollIntervalMs: z4.z.number().positive().nullish(), pollTimeoutMs: z4.z.number().positive().nullish(), personGeneration: z4.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(), negativePrompt: z4.z.string().nullish(), referenceImages: z4.z.array( z4.z.object({ bytesBase64Encoded: z4.z.string().nullish(), gcsUri: z4.z.string().nullish() }) ).nullish() }).passthrough() ) ); function convertGoogleInteractionsUsage(usage) { var _a18, _b18, _c, _d, _e, _f, _g, _h; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const totalInput = (_a18 = usage.total_input_tokens) != null ? _a18 : 0; const totalOutput = (_b18 = usage.total_output_tokens) != null ? _b18 : 0; const totalThought = (_c = usage.total_thought_tokens) != null ? _c : 0; const totalCached = (_d = usage.total_cached_tokens) != null ? _d : 0; return { inputTokens: { total: (_e = usage.total_input_tokens) != null ? _e : void 0, noCache: usage.total_input_tokens == null ? void 0 : totalInput - totalCached, cacheRead: (_f = usage.total_cached_tokens) != null ? _f : void 0, cacheWrite: void 0 }, outputTokens: { total: usage.total_output_tokens == null && usage.total_thought_tokens == null ? void 0 : totalOutput + totalThought, text: (_g = usage.total_output_tokens) != null ? _g : void 0, reasoning: (_h = usage.total_thought_tokens) != null ? _h : void 0 }, raw: usage }; } var KNOWN_DOC_EXTENSIONS = { pdf: "application/pdf", txt: "text/plain", md: "text/markdown", markdown: "text/markdown", doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }; function inferDocMediaType(uriOrName) { const lower = uriOrName.toLowerCase(); for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) { if (lower.endsWith(`.${ext}`)) return media; } return "application/octet-stream"; } function basename(uriOrName) { const parts = uriOrName.split("/"); const last = parts[parts.length - 1]; return last && last.length > 0 ? last : void 0; } function annotationToSource({ annotation, generateId: generateId3 }) { var _a18, _b18, _c, _d, _e; switch (annotation.type) { case "url_citation": { const a = annotation; if (a.url == null || a.url.length === 0) return void 0; return { type: "source", sourceType: "url", id: generateId3(), url: a.url, ...a.title != null ? { title: a.title } : {} }; } case "file_citation": { const a = annotation; const uri = (_b18 = (_a18 = a.document_uri) != null ? _a18 : a.source) != null ? _b18 : a.file_name; if (uri == null || uri.length === 0) return void 0; if (uri.startsWith("http://") || uri.startsWith("https://")) { return { type: "source", sourceType: "url", id: generateId3(), url: uri, ...a.file_name != null ? { title: a.file_name } : {} }; } const filename = (_c = a.file_name) != null ? _c : basename(uri); const mediaType = inferDocMediaType(uri); return { type: "source", sourceType: "document", id: generateId3(), mediaType, title: (_e = (_d = a.file_name) != null ? _d : filename) != null ? _e : uri, ...filename != null ? { filename } : {} }; } case "place_citation": { const a = annotation; if (a.url == null || a.url.length === 0) return void 0; return { type: "source", sourceType: "url", id: generateId3(), url: a.url, ...a.name != null ? { title: a.name } : {} }; } default: return void 0; } } function builtinToolResultToSources({ block, generateId: generateId3 }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k; const sources = []; switch (block.type) { case "url_context_result": { const result = (_a18 = block.result) != null ? _a18 : []; for (const entry of result) { if ((entry == null ? void 0 : entry.url) == null || entry.url.length === 0) continue; if (entry.status != null && entry.status !== "success") continue; sources.push({ type: "source", sourceType: "url", id: generateId3(), url: entry.url }); } break; } case "google_search_result": { const result = (_b18 = block.result) != null ? _b18 : []; for (const entry of result) { const url = entry == null ? void 0 : entry.url; if (url == null || url.length === 0) continue; sources.push({ type: "source", sourceType: "url", id: generateId3(), url, ...entry.title != null ? { title: entry.title } : {} }); } break; } case "google_maps_result": { const result = (_c = block.result) != null ? _c : []; for (const entry of result) { for (const place of (_d = entry.places) != null ? _d : []) { if (place.url == null || place.url.length === 0) continue; sources.push({ type: "source", sourceType: "url", id: generateId3(), url: place.url, ...place.name != null ? { title: place.name } : {} }); } } break; } case "file_search_result": { const result = (_e = block.result) != null ? _e : []; for (const raw of result) { if (raw == null || typeof raw !== "object") continue; const entry = raw; const uri = (_g = (_f = entry.document_uri) != null ? _f : entry.source) != null ? _g : entry.file_name; if (uri == null || uri.length === 0) continue; if (uri.startsWith("http://") || uri.startsWith("https://")) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: uri, ...entry.title != null ? { title: entry.title } : {} }); continue; } const filename = (_h = entry.file_name) != null ? _h : basename(uri); const mediaType = inferDocMediaType(uri); sources.push({ type: "source", sourceType: "document", id: generateId3(), mediaType, title: (_k = (_j = (_i = entry.title) != null ? _i : entry.file_name) != null ? _j : filename) != null ? _k : uri, ...filename != null ? { filename } : {} }); } break; } } return sources; } function annotationsToSources({ annotations, generateId: generateId3 }) { var _a18; if (annotations == null) return []; const seen = /* @__PURE__ */ new Set(); const sources = []; for (const annotation of annotations) { const source = annotationToSource({ annotation, generateId: generateId3 }); if (source == null) continue; const key = source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a18 = source.filename) != null ? _a18 : source.title}`; if (seen.has(key)) continue; seen.add(key); sources.push(source); } return sources; } function mapGoogleInteractionsFinishReason({ status, hasFunctionCall }) { switch (status) { case "completed": return hasFunctionCall ? "tool-calls" : "stop"; case "requires_action": return "tool-calls"; case "failed": return "error"; case "incomplete": return "length"; case "cancelled": return "other"; case "in_progress": default: return "other"; } } var BUILTIN_TOOL_CALL_TYPES = /* @__PURE__ */ new Set([ "google_search_call", "code_execution_call", "url_context_call", "file_search_call", "google_maps_call", "mcp_server_tool_call" ]); var BUILTIN_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([ "google_search_result", "code_execution_result", "url_context_result", "file_search_result", "google_maps_result", "mcp_server_tool_result" ]); function builtinToolNameFromCallType(type) { return type.replace(/_call$/, ""); } function builtinToolNameFromResultType(type) { return type.replace(/_result$/, ""); } function buildGoogleInteractionsStreamTransform({ warnings, generateId: generateId3, includeRawChunks, serviceTier: headerServiceTier }) { let interactionId; let usage; let serviceTier = headerServiceTier; let finishStatus; let hasFunctionCall = false; const openBlocks = /* @__PURE__ */ new Map(); const emittedSourceKeys = /* @__PURE__ */ new Set(); function sourceKey(source) { var _a18; return source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a18 = source.filename) != null ? _a18 : source.title}`; } return new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; if (includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishStatus = "failed"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; const eventType = value.event_type; switch (eventType) { case "interaction.start": { const event = value; const interaction = event.interaction; interactionId = (interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0 ? interaction.id : void 0; const created = interaction == null ? void 0 : interaction.created; let timestamp; if (typeof created === "string") { const parsed = new Date(created); if (!Number.isNaN(parsed.getTime())) { timestamp = parsed; } } controller.enqueue({ type: "response-metadata", ...interactionId != null ? { id: interactionId } : {}, modelId: interaction == null ? void 0 : interaction.model, ...timestamp ? { timestamp } : {} }); break; } case "content.start": { const event = value; const block = event.content; const index = event.index; const blockId = `${interactionId != null ? interactionId : "interaction"}:${index}`; if ((block == null ? void 0 : block.type) === "text") { openBlocks.set(index, { kind: "text", id: blockId, emittedSourceKeys: /* @__PURE__ */ new Set() }); controller.enqueue({ type: "text-start", id: blockId }); const initialSources = annotationsToSources({ annotations: block.annotations, generateId: generateId3 }); for (const source of initialSources) { const key = sourceKey(source); if (emittedSourceKeys.has(key)) continue; emittedSourceKeys.add(key); controller.enqueue(source); } } else if ((block == null ? void 0 : block.type) === "image") { const img = block; openBlocks.set(index, { kind: "image", id: blockId, ...img.data != null ? { data: img.data } : {}, ...img.mime_type != null ? { mimeType: img.mime_type } : {}, ...img.uri != null ? { uri: img.uri } : {} }); } else if ((block == null ? void 0 : block.type) === "thought") { const signature = block.signature; openBlocks.set(index, { kind: "reasoning", id: blockId, ...signature != null ? { signature } : {} }); controller.enqueue({ type: "reasoning-start", id: blockId }); } else if ((block == null ? void 0 : block.type) === "function_call") { const fc = block; const toolCallId = (_a18 = fc.id) != null ? _a18 : blockId; hasFunctionCall = true; const state = { kind: "function_call", id: blockId, toolCallId, toolName: fc.name, arguments: (_b18 = fc.arguments) != null ? _b18 : {}, ...fc.signature != null ? { signature: fc.signature } : {}, startEmitted: false }; openBlocks.set(index, state); if (state.toolName != null) { controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName: state.toolName }); state.startEmitted = true; } } else if ((block == null ? void 0 : block.type) != null && BUILTIN_TOOL_CALL_TYPES.has(block.type)) { const toolName = block.type === "mcp_server_tool_call" ? (_c = block.name) != null ? _c : "mcp_server_tool" : builtinToolNameFromCallType(block.type); const toolCallId = (_d = block.id) != null ? _d : blockId; const state = { kind: "builtin_tool_call", id: blockId, blockType: block.type, toolCallId, toolName, arguments: (_e = block.arguments) != null ? _e : {}, callEmitted: false }; openBlocks.set(index, state); } else if ((block == null ? void 0 : block.type) != null && BUILTIN_TOOL_RESULT_TYPES.has(block.type)) { const toolName = block.type === "mcp_server_tool_result" ? (_f = block.name) != null ? _f : "mcp_server_tool" : builtinToolNameFromResultType(block.type); const callId = (_g = block.call_id) != null ? _g : blockId; const state = { kind: "builtin_tool_result", id: blockId, blockType: block.type, callId, toolName, result: (_h = block.result) != null ? _h : null, ...block.is_error != null ? { isError: block.is_error } : {}, resultEmitted: false }; openBlocks.set(index, state); } else { openBlocks.set(index, { kind: "unknown", id: blockId }); } break; } case "content.delta": { const event = value; const open = openBlocks.get(event.index); if (open == null) break; const delta = event.delta; if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text") { const text = (_i = delta.text) != null ? _i : ""; if (text.length > 0) { controller.enqueue({ type: "text-delta", id: open.id, delta: text }); } } else if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text_annotation") { const sources = annotationsToSources({ annotations: delta.annotations, generateId: generateId3 }); for (const source of sources) { const key = sourceKey(source); if (emittedSourceKeys.has(key)) continue; emittedSourceKeys.add(key); open.emittedSourceKeys.add(key); controller.enqueue(source); } } else if (open.kind === "image" && (delta == null ? void 0 : delta.type) === "image") { if (delta.data != null) open.data = delta.data; if (delta.mime_type != null) open.mimeType = delta.mime_type; if (delta.uri != null) open.uri = delta.uri; } else if (open.kind === "reasoning") { if ((delta == null ? void 0 : delta.type) === "thought_summary") { const item = delta.content; if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") { controller.enqueue({ type: "reasoning-delta", id: open.id, delta: item.text }); } } else if ((delta == null ? void 0 : delta.type) === "thought_signature") { const signature = delta.signature; if (signature != null) { open.signature = signature; } } } else if (open.kind === "function_call" && (delta == null ? void 0 : delta.type) === "function_call") { if (delta.id != null) { open.toolCallId = delta.id; } if (delta.name != null) { open.toolName = delta.name; } if (delta.arguments != null) { open.arguments = delta.arguments; } if (delta.signature != null) { open.signature = delta.signature; } if (!open.startEmitted && open.toolName != null) { controller.enqueue({ type: "tool-input-start", id: open.toolCallId, toolName: open.toolName }); open.startEmitted = true; } hasFunctionCall = true; } else if (open.kind === "builtin_tool_call" && (delta == null ? void 0 : delta.type) === open.blockType) { if (delta.id != null) open.toolCallId = delta.id; if (delta.arguments != null) open.arguments = delta.arguments; if (delta.name != null && open.blockType === "mcp_server_tool_call") { open.toolName = delta.name; } } else if (open.kind === "builtin_tool_result" && (delta == null ? void 0 : delta.type) === open.blockType) { if (delta.call_id != null) open.callId = delta.call_id; if (delta.result !== void 0) open.result = delta.result; if (delta.is_error != null) open.isError = delta.is_error; if (delta.name != null && open.blockType === "mcp_server_tool_result") { open.toolName = delta.name; } } break; } case "content.stop": { const event = value; const open = openBlocks.get(event.index); if (open == null) break; if (open.kind === "text") { const textProviderMetadata = interactionId != null ? { google: { interactionId } } : void 0; controller.enqueue({ type: "text-end", id: open.id, ...textProviderMetadata ? { providerMetadata: textProviderMetadata } : {} }); } else if (open.kind === "reasoning") { const google2 = {}; if (open.signature != null) google2.signature = open.signature; if (interactionId != null) google2.interactionId = interactionId; const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0; controller.enqueue({ type: "reasoning-end", id: open.id, ...providerMetadata ? { providerMetadata } : {} }); } else if (open.kind === "image") { const google2 = {}; if (interactionId != null) google2.interactionId = interactionId; const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0; if (open.data != null && open.data.length > 0) { controller.enqueue({ type: "file", mediaType: (_j = open.mimeType) != null ? _j : "image/png", data: open.data, ...providerMetadata ? { providerMetadata } : {} }); } else if (open.uri != null && open.uri.length > 0) { const uriProviderMetadata = { google: { ...interactionId != null ? { interactionId } : {}, imageUri: open.uri } }; controller.enqueue({ type: "file", mediaType: (_k = open.mimeType) != null ? _k : "image/png", data: "", providerMetadata: uriProviderMetadata }); } } else if (open.kind === "function_call") { const toolName = (_l = open.toolName) != null ? _l : "unknown"; const argsJson = JSON.stringify((_m = open.arguments) != null ? _m : {}); if (!open.startEmitted) { controller.enqueue({ type: "tool-input-start", id: open.toolCallId, toolName }); } controller.enqueue({ type: "tool-input-delta", id: open.toolCallId, delta: argsJson }); controller.enqueue({ type: "tool-input-end", id: open.toolCallId }); const google2 = {}; if (open.signature != null) google2.signature = open.signature; if (interactionId != null) google2.interactionId = interactionId; const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0; controller.enqueue({ type: "tool-call", toolCallId: open.toolCallId, toolName, input: argsJson, ...providerMetadata ? { providerMetadata } : {} }); } else if (open.kind === "builtin_tool_call" && !open.callEmitted) { controller.enqueue({ type: "tool-call", toolCallId: open.toolCallId, toolName: open.toolName, input: JSON.stringify((_n = open.arguments) != null ? _n : {}), providerExecuted: true }); open.callEmitted = true; } else if (open.kind === "builtin_tool_result" && !open.resultEmitted) { controller.enqueue({ type: "tool-result", toolCallId: open.callId, toolName: open.toolName, result: (_o = open.result) != null ? _o : null }); open.resultEmitted = true; const sources = builtinToolResultToSources({ block: { type: open.blockType, result: open.result }, generateId: generateId3 }); for (const source of sources) { const key = sourceKey(source); if (emittedSourceKeys.has(key)) continue; emittedSourceKeys.add(key); controller.enqueue(source); } } openBlocks.delete(event.index); break; } case "interaction.status_update": { const event = value; finishStatus = event.status; break; } case "interaction.complete": { const event = value; const interaction = event.interaction; if ((interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0) { interactionId = interaction.id; } if ((interaction == null ? void 0 : interaction.status) != null) { finishStatus = interaction.status; } if ((interaction == null ? void 0 : interaction.usage) != null) { usage = interaction.usage; } if ((interaction == null ? void 0 : interaction.service_tier) != null) { serviceTier = interaction.service_tier; } break; } case "error": { const event = value; finishStatus = "failed"; const errorPayload = (_p = event.error) != null ? _p : { message: "Unknown interaction error" }; controller.enqueue({ type: "error", error: errorPayload }); break; } } }, flush(controller) { const finishReason = { unified: mapGoogleInteractionsFinishReason({ status: finishStatus, hasFunctionCall }), raw: finishStatus }; const providerMetadata = { google: { ...interactionId != null ? { interactionId } : {}, ...serviceTier != null ? { serviceTier } : {} } }; controller.enqueue({ type: "finish", finishReason, usage: convertGoogleInteractionsUsage(usage), providerMetadata }); } }); } function getTopLevelMediaType(mediaType) { const slashIndex = mediaType.indexOf("/"); return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex); } function isFullMediaType(mediaType) { const slashIndex = mediaType.indexOf("/"); if (slashIndex === -1) { return false; } const subtype = mediaType.substring(slashIndex + 1); return subtype.length > 0 && subtype !== "*"; } function convertToGoogleInteractionsInput({ prompt, previousInteractionId, store, mediaResolution }) { var _a18, _b18, _c, _d, _e, _f, _g; const warnings = []; const incoherentCombo = previousInteractionId != null && store === false; const shouldCompact = previousInteractionId != null && store !== false; if (incoherentCombo) { warnings.push({ type: "other", message: "google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted." }); } const compactedPrompt = shouldCompact ? compactPromptForPreviousInteraction({ prompt, previousInteractionId }) : prompt; const systemTexts = []; const turns = []; for (const message of compactedPrompt) { switch (message.role) { case "system": { systemTexts.push(message.content); break; } case "user": { const content = []; for (const part of message.content) { if (part.type === "text") { const block = { type: "text", text: part.text }; content.push(block); } else if (part.type === "file") { const fileBlock = convertFilePartToContent({ part, warnings, mediaResolution }); if (fileBlock != null) { content.push(fileBlock); } } } const merged = mergeAdjacentTextContent(content); if (merged.length > 0) { turns.push({ role: "user", content: merged }); } break; } case "assistant": { const content = []; for (const part of message.content) { if (part.type === "text") { content.push({ type: "text", text: part.text }); } else if (part.type === "reasoning") { const signature = (_b18 = (_a18 = part.providerOptions) == null ? void 0 : _a18.google) == null ? void 0 : _b18.signature; content.push({ type: "thought", ...signature != null ? { signature } : {}, summary: part.text.length > 0 ? [{ type: "text", text: part.text }] : void 0 }); } else if (part.type === "file") { const fileBlock = convertFilePartToContent({ part, warnings, mediaResolution }); if (fileBlock != null) { content.push(fileBlock); } } else if (part.type === "tool-call") { const signature = (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.signature; const args = typeof part.input === "string" ? safeParseToolArgs(part.input) : (_e = part.input) != null ? _e : {}; content.push({ type: "function_call", id: part.toolCallId, name: part.toolName, arguments: args, ...signature != null ? { signature } : {} }); } else { warnings.push({ type: "other", message: `google.interactions: unsupported assistant content part type "${part.type}"; part dropped.` }); } } if (content.length > 0) { turns.push({ role: "model", content }); } break; } case "tool": { const content = []; for (const part of message.content) { if (part.type !== "tool-result") { warnings.push({ type: "other", message: `google.interactions: unsupported tool message part type "${part.type}"; part dropped.` }); continue; } const block = convertToolResultPart({ toolCallId: part.toolCallId, toolName: part.toolName, output: part.output, signature: (_g = (_f = part.providerOptions) == null ? void 0 : _f.google) == null ? void 0 : _g.signature, warnings }); content.push(block); } if (content.length > 0) { turns.push({ role: "user", content }); } break; } } } const systemInstruction = systemTexts.length > 0 ? systemTexts.join("\n\n") : void 0; let input; if (turns.length === 0) { input = ""; } else if (turns.length === 1 && turns[0].role === "user" && Array.isArray(turns[0].content)) { input = turns[0].content; } else { input = turns; } return { input, systemInstruction, warnings }; } function convertFilePartToContent({ part, warnings, mediaResolution }) { const topLevel = getTopLevelMediaType(part.mediaType); let kind; switch (topLevel) { case "image": kind = "image"; break; case "audio": kind = "audio"; break; case "video": kind = "video"; break; case "application": kind = "document"; break; default: kind = void 0; } if (kind == null) { warnings.push({ type: "other", message: `google.interactions: unsupported file media type "${part.mediaType}"; part dropped.` }); return void 0; } const resolutionField = mediaResolution != null && (kind === "image" || kind === "video") ? { resolution: mediaResolution } : {}; if (part.data instanceof URL) { return { type: kind, uri: part.data.toString(), ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {}, ...resolutionField }; } if (!isFullMediaType(part.mediaType)) { warnings.push({ type: "other", message: `google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.` }); return void 0; } return { type: kind, data: convertToBase642(part.data), mime_type: part.mediaType, ...resolutionField }; } function compactPromptForPreviousInteraction({ prompt, previousInteractionId }) { const out = []; const droppedToolCallIds = /* @__PURE__ */ new Set(); for (const message of prompt) { if (message.role === "assistant") { const matchesLinkedInteraction = message.content.some((part) => { var _a18, _b18; const partInteractionId = (_b18 = (_a18 = part.providerOptions) == null ? void 0 : _a18.google) == null ? void 0 : _b18.interactionId; return partInteractionId === previousInteractionId; }); if (matchesLinkedInteraction) { for (const part of message.content) { if (part.type === "tool-call") { droppedToolCallIds.add(part.toolCallId); } } continue; } out.push(message); continue; } if (message.role === "tool") { const remaining = message.content.filter((part) => { if (part.type !== "tool-result") { return true; } return !droppedToolCallIds.has(part.toolCallId); }); if (remaining.length === 0) { continue; } out.push({ ...message, content: remaining }); continue; } out.push(message); } return out; } function safeParseToolArgs(input) { try { const parsed = JSON.parse(input); if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) { return parsed; } return { value: parsed }; } catch (e) { return { value: input }; } } function convertToolResultPart({ toolCallId, toolName, output, signature, warnings }) { var _a18; const base = { type: "function_result", call_id: toolCallId, name: toolName, ...signature != null ? { signature } : {} }; switch (output.type) { case "text": return { ...base, result: output.value }; case "json": return { ...base, result: JSON.stringify(output.value) }; case "error-text": return { ...base, is_error: true, result: output.value }; case "error-json": return { ...base, is_error: true, result: JSON.stringify(output.value) }; case "execution-denied": return { ...base, is_error: true, result: (_a18 = output.reason) != null ? _a18 : "Tool execution denied by user." }; case "content": { const blocks = []; for (const item of output.value) { if (item.type === "text") { blocks.push({ type: "text", text: item.text }); } else if (item.type === "image-data") { const imageBlock = filePartToImageBlock({ part: { mediaType: item.mediaType, data: item.data }, warnings }); if (imageBlock != null) { blocks.push(imageBlock); } } else if (item.type === "image-url") { const imageBlock = filePartToImageBlock({ part: { mediaType: "image/*", data: new URL(item.url) }, warnings }); if (imageBlock != null) { blocks.push(imageBlock); } } else if (item.type === "file-data" || item.type === "file-url") { const mediaType = item.type === "file-data" ? item.mediaType : "application/*"; const topLevel = getTopLevelMediaType(mediaType); if (topLevel !== "image") { warnings.push({ type: "other", message: `google.interactions: tool-result file with mediaType "${mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.` }); continue; } const imageBlock = filePartToImageBlock({ part: item.type === "file-data" ? { mediaType: item.mediaType, data: item.data } : { mediaType, data: new URL(item.url) }, warnings }); if (imageBlock != null) { blocks.push(imageBlock); } } else { warnings.push({ type: "other", message: `google.interactions: tool-result content part type "${item.type}" is not supported; part dropped.` }); } } return { ...base, result: blocks }; } } } function filePartToImageBlock({ part, warnings }) { if (part.data instanceof URL) { return { type: "image", uri: part.data.toString(), ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {} }; } if (!isFullMediaType(part.mediaType)) { warnings.push({ type: "other", message: `google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.` }); return void 0; } return { type: "image", data: convertToBase642(part.data), mime_type: part.mediaType }; } function mergeAdjacentTextContent(content) { if (content.length < 2) { return content; } const result = []; for (const block of content) { const last = result[result.length - 1]; if (block.type === "text" && last != null && last.type === "text" && last.annotations == null && block.annotations == null) { const merged = { type: "text", text: `${last.text} ${block.text}` }; result[result.length - 1] = merged; continue; } result.push(block); } return result; } var tokenByModalitySchema = () => z4.z.object({ modality: z4.z.string().nullish(), tokens: z4.z.number().nullish() }).loose(); var usageSchema22 = () => z4.z.object({ total_input_tokens: z4.z.number().nullish(), total_output_tokens: z4.z.number().nullish(), total_thought_tokens: z4.z.number().nullish(), total_cached_tokens: z4.z.number().nullish(), total_tool_use_tokens: z4.z.number().nullish(), total_tokens: z4.z.number().nullish(), input_tokens_by_modality: z4.z.array(tokenByModalitySchema()).nullish(), output_tokens_by_modality: z4.z.array(tokenByModalitySchema()).nullish(), cached_tokens_by_modality: z4.z.array(tokenByModalitySchema()).nullish(), tool_use_tokens_by_modality: z4.z.array(tokenByModalitySchema()).nullish(), grounding_tool_count: z4.z.array( z4.z.object({ type: z4.z.string().nullish(), count: z4.z.number().nullish() }).loose() ).nullish() }).loose(); var interactionStatusSchema = () => z4.z.enum([ "in_progress", "requires_action", "completed", "failed", "cancelled", "incomplete" ]); var annotationSchema = () => { const urlCitation = z4.z.object({ type: z4.z.literal("url_citation"), url: z4.z.string().nullish(), title: z4.z.string().nullish(), start_index: z4.z.number().nullish(), end_index: z4.z.number().nullish() }).loose(); const fileCitation = z4.z.object({ type: z4.z.literal("file_citation"), file_name: z4.z.string().nullish(), document_uri: z4.z.string().nullish(), source: z4.z.string().nullish(), page_number: z4.z.number().nullish(), media_id: z4.z.string().nullish(), start_index: z4.z.number().nullish(), end_index: z4.z.number().nullish(), custom_metadata: z4.z.record(z4.z.string(), z4.z.unknown()).nullish() }).loose(); const placeCitation = z4.z.object({ type: z4.z.literal("place_citation"), name: z4.z.string().nullish(), url: z4.z.string().nullish(), place_id: z4.z.string().nullish(), start_index: z4.z.number().nullish(), end_index: z4.z.number().nullish() }).loose(); return z4.z.union([ urlCitation, fileCitation, placeCitation, z4.z.object({ type: z4.z.string() }).loose() ]); }; var thoughtSummaryItemSchema = () => z4.z.object({ type: z4.z.string(), text: z4.z.string().nullish(), data: z4.z.string().nullish(), mime_type: z4.z.string().nullish() }).loose(); var contentBlockSchema = () => { const textContent = z4.z.object({ type: z4.z.literal("text"), text: z4.z.string(), annotations: z4.z.array(annotationSchema()).nullish() }).loose(); const thoughtContent = z4.z.object({ type: z4.z.literal("thought"), signature: z4.z.string().nullish(), summary: z4.z.array(thoughtSummaryItemSchema()).nullish() }).loose(); const functionCallContent = z4.z.object({ type: z4.z.literal("function_call"), id: z4.z.string(), name: z4.z.string(), arguments: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), signature: z4.z.string().nullish() }).loose(); const imageContent = z4.z.object({ type: z4.z.literal("image"), data: z4.z.string().nullish(), mime_type: z4.z.string().nullish(), resolution: z4.z.enum(["low", "medium", "high", "ultra_high"]).nullish(), uri: z4.z.string().nullish() }).loose(); const builtinToolCall = z4.z.object({ type: z4.z.enum([ "google_search_call", "code_execution_call", "url_context_call", "file_search_call", "google_maps_call", "mcp_server_tool_call" ]), id: z4.z.string(), arguments: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), name: z4.z.string().nullish(), server_name: z4.z.string().nullish(), search_type: z4.z.string().nullish(), signature: z4.z.string().nullish() }).loose(); const builtinToolResult = z4.z.object({ type: z4.z.enum([ "google_search_result", "code_execution_result", "url_context_result", "file_search_result", "google_maps_result", "mcp_server_tool_result" ]), call_id: z4.z.string(), result: z4.z.unknown().nullish(), is_error: z4.z.boolean().nullish(), name: z4.z.string().nullish(), server_name: z4.z.string().nullish(), signature: z4.z.string().nullish() }).loose(); return z4.z.union([ textContent, imageContent, thoughtContent, functionCallContent, builtinToolCall, builtinToolResult, z4.z.object({ type: z4.z.string() }).loose() ]); }; var googleInteractionsResponseSchema = lazySchema2( () => zodSchema2( z4.z.object({ /* * `id` is omitted from the response body when `store: false` (fully * stateless mode) — there is no server-side interaction record for the * client to reference. `nullish` lets the schema accept that shape. */ id: z4.z.string().nullish(), created: z4.z.string().nullish(), updated: z4.z.string().nullish(), status: interactionStatusSchema(), model: z4.z.string().nullish(), agent: z4.z.string().nullish(), outputs: z4.z.array(contentBlockSchema()).nullish(), usage: usageSchema22().nullish(), service_tier: z4.z.string().nullish(), previous_interaction_id: z4.z.string().nullish(), response_modalities: z4.z.array(z4.z.string()).nullish() }).loose() ) ); var googleInteractionsEventSchema = lazySchema2( () => zodSchema2( (() => { const status = interactionStatusSchema(); const annotation = annotationSchema(); const thoughtSummaryItem = thoughtSummaryItemSchema(); const interactionStartEvent = z4.z.object({ event_type: z4.z.literal("interaction.start"), event_id: z4.z.string().nullish(), interaction: z4.z.object({ /* * `id` is omitted when `store: false` (fully stateless mode); * see the matching note on `googleInteractionsResponseSchema.id`. */ id: z4.z.string().nullish(), created: z4.z.string().nullish(), model: z4.z.string().nullish(), agent: z4.z.string().nullish(), status: status.nullish() }).loose() }).loose(); const contentStartEvent = z4.z.object({ event_type: z4.z.literal("content.start"), event_id: z4.z.string().nullish(), index: z4.z.number(), content: contentBlockSchema() }).loose(); const contentDeltaText = z4.z.object({ type: z4.z.literal("text"), text: z4.z.string() }).loose(); const contentDeltaThoughtSummary = z4.z.object({ type: z4.z.literal("thought_summary"), content: thoughtSummaryItem.nullish() }).loose(); const contentDeltaThoughtSignature = z4.z.object({ type: z4.z.literal("thought_signature"), signature: z4.z.string().nullish() }).loose(); const contentDeltaFunctionCall = z4.z.object({ type: z4.z.literal("function_call"), id: z4.z.string(), name: z4.z.string(), arguments: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), signature: z4.z.string().nullish() }).loose(); const contentDeltaTextAnnotation = z4.z.object({ type: z4.z.literal("text_annotation"), annotations: z4.z.array(annotation).nullish() }).loose(); const contentDeltaImage = z4.z.object({ type: z4.z.literal("image"), data: z4.z.string().nullish(), mime_type: z4.z.string().nullish(), resolution: z4.z.enum(["low", "medium", "high", "ultra_high"]).nullish(), uri: z4.z.string().nullish() }).loose(); const contentDeltaBuiltinToolCall = z4.z.object({ type: z4.z.enum([ "google_search_call", "code_execution_call", "url_context_call", "file_search_call", "google_maps_call", "mcp_server_tool_call" ]), id: z4.z.string(), arguments: z4.z.record(z4.z.string(), z4.z.unknown()).nullish(), name: z4.z.string().nullish(), server_name: z4.z.string().nullish(), search_type: z4.z.string().nullish(), signature: z4.z.string().nullish() }).loose(); const contentDeltaBuiltinToolResult = z4.z.object({ type: z4.z.enum([ "google_search_result", "code_execution_result", "url_context_result", "file_search_result", "google_maps_result", "mcp_server_tool_result" ]), call_id: z4.z.string(), result: z4.z.unknown().nullish(), is_error: z4.z.boolean().nullish(), name: z4.z.string().nullish(), server_name: z4.z.string().nullish(), signature: z4.z.string().nullish() }).loose(); const contentDeltaUnknown = z4.z.object({ type: z4.z.string() }).loose(); const contentDeltaUnion = z4.z.union([ contentDeltaText, contentDeltaImage, contentDeltaThoughtSummary, contentDeltaThoughtSignature, contentDeltaFunctionCall, contentDeltaTextAnnotation, contentDeltaBuiltinToolCall, contentDeltaBuiltinToolResult, contentDeltaUnknown ]); const contentDeltaEvent = z4.z.object({ event_type: z4.z.literal("content.delta"), event_id: z4.z.string().nullish(), index: z4.z.number(), delta: contentDeltaUnion }).loose(); const contentStopEvent = z4.z.object({ event_type: z4.z.literal("content.stop"), event_id: z4.z.string().nullish(), index: z4.z.number() }).loose(); const interactionStatusUpdateEvent = z4.z.object({ event_type: z4.z.literal("interaction.status_update"), event_id: z4.z.string().nullish(), interaction_id: z4.z.string().nullish(), status }).loose(); const interactionCompleteEvent = z4.z.object({ event_type: z4.z.literal("interaction.complete"), event_id: z4.z.string().nullish(), interaction: z4.z.object({ id: z4.z.string().nullish(), status: status.nullish(), usage: usageSchema22().nullish(), service_tier: z4.z.string().nullish() }).loose() }).loose(); const errorEvent = z4.z.object({ event_type: z4.z.literal("error"), event_id: z4.z.string().nullish(), error: z4.z.object({ code: z4.z.string().nullish(), message: z4.z.string().nullish() }).loose().nullish() }).loose(); const unknownEvent = z4.z.object({ event_type: z4.z.string() }).loose(); return z4.z.union([ interactionStartEvent, contentStartEvent, contentDeltaEvent, contentStopEvent, interactionStatusUpdateEvent, interactionCompleteEvent, errorEvent, unknownEvent ]); })() ) ); var googleInteractionsLanguageModelOptions = lazySchema2( () => zodSchema2( z4.z.object({ previousInteractionId: z4.z.string().nullish(), store: z4.z.boolean().nullish(), agent: z4.z.string().nullish(), agentConfig: z4.z.union([ z4.z.object({ type: z4.z.literal("dynamic") }).loose(), z4.z.object({ type: z4.z.literal("deep-research"), thinkingSummaries: z4.z.enum(["auto", "none"]).nullish(), visualization: z4.z.enum(["off", "auto"]).nullish(), collaborativePlanning: z4.z.boolean().nullish() }) ]).nullish(), thinkingLevel: z4.z.enum(["minimal", "low", "medium", "high"]).nullish(), thinkingSummaries: z4.z.enum(["auto", "none"]).nullish(), imageConfig: z4.z.object({ aspectRatio: z4.z.enum([ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:8", "8:1", "1:4", "4:1" ]).nullish(), imageSize: z4.z.enum(["1K", "2K", "4K", "512"]).nullish() }).nullish(), mediaResolution: z4.z.enum(["low", "medium", "high", "ultra_high"]).nullish(), responseModalities: z4.z.array(z4.z.enum(["text", "image", "audio", "video", "document"])).nullish(), serviceTier: z4.z.enum(["flex", "standard", "priority"]).nullish(), /** * Alternative to AI SDK `system` message. If both are set, the AI SDK * `system` message wins and a warning is emitted. */ systemInstruction: z4.z.string().nullish(), /** * Per-block signature for round-tripping `thought.signature` and * `function_call.signature` blocks. Set by the SDK on output reasoning / * tool-call parts; passed back unchanged on input parts so the API * accepts the prior turn. */ signature: z4.z.string().nullish(), /** * Set by the SDK on output assistant messages. The converter uses it to * decide which messages to drop when compacting under * `previousInteractionId`. */ interactionId: z4.z.string().nullish(), /** * Maximum time, in milliseconds, to poll a background interaction (agent * call) before giving up. Defaults to 30 minutes. Long-running agents * such as deep research can take tens of minutes — increase if needed. */ pollingTimeoutMs: z4.z.number().int().positive().nullish() }) ) ); function googleProviderMetadata({ signature, interactionId }) { const google2 = {}; if (signature != null) { google2.signature = signature; } if (interactionId != null) { google2.interactionId = interactionId; } return Object.keys(google2).length > 0 ? { providerMetadata: { google: google2 } } : {}; } var BUILTIN_TOOL_CALL_TYPES2 = /* @__PURE__ */ new Set([ "google_search_call", "code_execution_call", "url_context_call", "file_search_call", "google_maps_call", "mcp_server_tool_call" ]); var BUILTIN_TOOL_RESULT_TYPES2 = /* @__PURE__ */ new Set([ "google_search_result", "code_execution_result", "url_context_result", "file_search_result", "google_maps_result", "mcp_server_tool_result" ]); function builtinToolNameFromCallType2(type) { return type.replace(/_call$/, ""); } function builtinToolNameFromResultType2(type) { return type.replace(/_result$/, ""); } function parseGoogleInteractionsOutputs({ outputs, generateId: generateId3, interactionId }) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j; const content = []; let hasFunctionCall = false; if (outputs == null) { return { content, hasFunctionCall }; } for (const block of outputs) { if (block == null || typeof block !== "object") continue; const type = block.type; if (typeof type !== "string") continue; switch (type) { case "text": { const text = (_a18 = block.text) != null ? _a18 : ""; const annotations = block.annotations; content.push({ type: "text", text, ...googleProviderMetadata({ interactionId }) }); const sources = annotationsToSources({ annotations, generateId: generateId3 }); for (const source of sources) { content.push(source); } break; } case "thought": { const thought = block; const summary = Array.isArray(thought.summary) ? thought.summary : []; const text = summary.filter( (item) => (item == null ? void 0 : item.type) === "text" && typeof item.text === "string" ).map((item) => item.text).join("\n"); content.push({ type: "reasoning", text, ...googleProviderMetadata({ signature: thought.signature, interactionId }) }); break; } case "image": { const image = block; if (image.data != null && image.data.length > 0) { content.push({ type: "file", mediaType: (_b18 = image.mime_type) != null ? _b18 : "image/png", data: image.data, ...googleProviderMetadata({ interactionId }) }); } else if (image.uri != null && image.uri.length > 0) { content.push({ type: "file", mediaType: (_c = image.mime_type) != null ? _c : "image/png", data: "", providerMetadata: { google: { ...interactionId != null ? { interactionId } : {}, imageUri: image.uri } } }); } break; } case "function_call": { hasFunctionCall = true; const call = block; content.push({ type: "tool-call", toolCallId: call.id, toolName: call.name, input: JSON.stringify((_d = call.arguments) != null ? _d : {}), ...googleProviderMetadata({ signature: call.signature, interactionId }) }); break; } default: { if (BUILTIN_TOOL_CALL_TYPES2.has(type)) { const call = block; const toolName = type === "mcp_server_tool_call" ? (_e = call.name) != null ? _e : "mcp_server_tool" : builtinToolNameFromCallType2(type); const input = JSON.stringify((_f = call.arguments) != null ? _f : {}); content.push({ type: "tool-call", toolCallId: (_g = call.id) != null ? _g : generateId3(), toolName, input, providerExecuted: true }); } else if (BUILTIN_TOOL_RESULT_TYPES2.has(type)) { const result = block; const toolName = type === "mcp_server_tool_result" ? (_h = result.name) != null ? _h : "mcp_server_tool" : builtinToolNameFromResultType2(type); content.push({ type: "tool-result", toolCallId: (_i = result.call_id) != null ? _i : generateId3(), toolName, result: (_j = result.result) != null ? _j : null }); const sources = builtinToolResultToSources({ block, generateId: generateId3 }); for (const source of sources) { content.push(source); } } break; } } } return { content, hasFunctionCall }; } var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]); function isTerminalStatus(status) { return status != null && TERMINAL_STATUSES.has(status); } var DEFAULT_INITIAL_DELAY_MS = 1e3; var DEFAULT_MAX_DELAY_MS = 1e4; var DEFAULT_TIMEOUT_MS = 30 * 60 * 1e3; async function pollGoogleInteractionUntilTerminal({ baseURL, interactionId, headers, fetch: fetch2, abortSignal, initialDelayMs = DEFAULT_INITIAL_DELAY_MS, maxDelayMs = DEFAULT_MAX_DELAY_MS, timeoutMs = DEFAULT_TIMEOUT_MS }) { if (interactionId == null || interactionId.length === 0) { throw new Error( "google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id." ); } const startedAt = Date.now(); let nextDelayMs = initialDelayMs; const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`; while (true) { if (abortSignal == null ? void 0 : abortSignal.aborted) { throw new DOMException("Polling was aborted", "AbortError"); } if (Date.now() - startedAt > timeoutMs) { throw new Error( `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.` ); } await delay2(nextDelayMs, { abortSignal }); const { value: response, rawValue: rawResponse, responseHeaders } = await getFromApi2({ url, headers, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleInteractionsResponseSchema ), abortSignal, fetch: fetch2 }); if (isTerminalStatus(response.status)) { return { response, rawResponse, responseHeaders }; } nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs); } } function prepareGoogleInteractionsTools({ tools, toolChoice }) { var _a18, _b18, _c, _d; const toolWarnings = []; const normalized = (tools == null ? void 0 : tools.length) ? tools : void 0; if (normalized == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const interactionsTools = []; for (const tool3 of normalized) { if (tool3.type === "function") { interactionsTools.push({ type: "function", name: tool3.name, description: (_a18 = tool3.description) != null ? _a18 : "", parameters: tool3.inputSchema }); continue; } if (tool3.type === "provider") { const args = (_b18 = tool3.args) != null ? _b18 : {}; switch (tool3.id) { case "google.google_search": { const searchTypesArg = args.searchTypes; let search_types; if (searchTypesArg != null && typeof searchTypesArg === "object") { const list = []; if (searchTypesArg.webSearch != null) list.push("web_search"); if (searchTypesArg.imageSearch != null) list.push("image_search"); if (list.length > 0) { search_types = list; } } interactionsTools.push({ type: "google_search", ...search_types != null ? { search_types } : {} }); break; } case "google.code_execution": { interactionsTools.push({ type: "code_execution" }); break; } case "google.url_context": { interactionsTools.push({ type: "url_context" }); break; } case "google.file_search": { interactionsTools.push({ type: "file_search", ...args.fileSearchStoreNames != null ? { file_search_store_names: args.fileSearchStoreNames } : {}, ...args.topK != null ? { top_k: args.topK } : {}, ...args.metadataFilter != null ? { metadata_filter: args.metadataFilter } : {} }); break; } case "google.google_maps": { interactionsTools.push({ type: "google_maps", ...args.latitude != null ? { latitude: args.latitude } : {}, ...args.longitude != null ? { longitude: args.longitude } : {}, ...args.enableWidget != null ? { enable_widget: args.enableWidget } : {} }); break; } case "google.computer_use": { interactionsTools.push({ type: "computer_use", environment: (_c = args.environment) != null ? _c : "browser", ...args.excludedPredefinedFunctions != null ? { excludedPredefinedFunctions: args.excludedPredefinedFunctions } : {} }); break; } case "google.mcp_server": { interactionsTools.push({ type: "mcp_server", ...args.name != null ? { name: args.name } : {}, ...args.url != null ? { url: args.url } : {}, ...args.headers != null ? { headers: args.headers } : {}, ...args.allowedTools != null ? { allowed_tools: args.allowedTools } : {} }); break; } case "google.retrieval": { const vertexAiSearchConfig = (_d = args.vertexAiSearchConfig) != null ? _d : void 0; interactionsTools.push({ type: "retrieval", ...args.retrievalTypes != null ? { retrieval_types: args.retrievalTypes } : { retrieval_types: ["vertex_ai_search"] }, ...vertexAiSearchConfig != null ? { vertex_ai_search_config: vertexAiSearchConfig } : {} }); break; } default: { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool3.id}`, details: `provider-defined tool ${tool3.id} is not supported by google.interactions; tool dropped.` }); break; } } continue; } toolWarnings.push({ type: "unsupported", feature: `tool of type ${tool3.type}`, details: "Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped." }); } const hasFunctionTool = interactionsTools.some((t) => t.type === "function"); let mappedToolChoice; if (toolChoice != null && hasFunctionTool) { switch (toolChoice.type) { case "auto": mappedToolChoice = "auto"; break; case "required": mappedToolChoice = "any"; break; case "none": mappedToolChoice = "none"; break; case "tool": mappedToolChoice = { allowed_tools: { mode: "validated", tools: [toolChoice.toolName] } }; break; } } return { tools: interactionsTools.length > 0 ? interactionsTools : void 0, toolChoice: mappedToolChoice, toolWarnings }; } function synthesizeGoogleInteractionsAgentStream({ response, warnings, generateId: generateId3, includeRawChunks, headerServiceTier }) { return new ReadableStream({ start(controller) { var _a18, _b18, _c; controller.enqueue({ type: "stream-start", warnings }); const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0; let timestamp; const created = response.created; if (typeof created === "string") { const parsed = new Date(created); if (!Number.isNaN(parsed.getTime())) { timestamp = parsed; } } controller.enqueue({ type: "response-metadata", ...interactionId != null ? { id: interactionId } : {}, modelId: (_a18 = response.model) != null ? _a18 : void 0, ...timestamp ? { timestamp } : {} }); if (includeRawChunks) { controller.enqueue({ type: "raw", rawValue: response }); } const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({ outputs: (_b18 = response.outputs) != null ? _b18 : null, generateId: generateId3, interactionId }); let blockCounter = 0; const nextBlockId = () => `${interactionId != null ? interactionId : "agent"}:${blockCounter++}`; for (const part of content) { switch (part.type) { case "text": { const id = nextBlockId(); const providerMetadata2 = part.providerMetadata; controller.enqueue({ type: "text-start", id }); if (part.text.length > 0) { controller.enqueue({ type: "text-delta", id, delta: part.text }); } controller.enqueue({ type: "text-end", id, ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {} }); break; } case "reasoning": { const id = nextBlockId(); const providerMetadata2 = part.providerMetadata; controller.enqueue({ type: "reasoning-start", id }); if (part.text.length > 0) { controller.enqueue({ type: "reasoning-delta", id, delta: part.text }); } controller.enqueue({ type: "reasoning-end", id, ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {} }); break; } case "tool-call": { const providerMetadata2 = part.providerMetadata; controller.enqueue({ type: "tool-input-start", id: part.toolCallId, toolName: part.toolName, ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {} }); controller.enqueue({ type: "tool-input-delta", id: part.toolCallId, delta: part.input }); controller.enqueue({ type: "tool-input-end", id: part.toolCallId }); controller.enqueue({ type: "tool-call", toolCallId: part.toolCallId, toolName: part.toolName, input: part.input, ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {}, ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {} }); break; } case "tool-result": { controller.enqueue({ type: "tool-result", toolCallId: part.toolCallId, toolName: part.toolName, result: part.result }); break; } case "source": case "file": { controller.enqueue(part); break; } } } const serviceTier = (_c = response.service_tier) != null ? _c : headerServiceTier; const finishReason = { unified: mapGoogleInteractionsFinishReason({ status: response.status, hasFunctionCall }), raw: response.status }; const providerMetadata = { google: { ...interactionId != null ? { interactionId } : {}, ...serviceTier != null ? { serviceTier } : {} } }; controller.enqueue({ type: "finish", finishReason, usage: convertGoogleInteractionsUsage(response.usage), providerMetadata }); controller.close(); } }); } var GoogleInteractionsLanguageModel = class { constructor(modelOrAgent, config) { this.specificationVersion = "v3"; if (typeof modelOrAgent === "string") { this.modelId = modelOrAgent; this.agent = void 0; } else { this.modelId = modelOrAgent.agent; this.agent = modelOrAgent.agent; } this.config = config; } get provider() { return this.config.provider; } get supportedUrls() { if (this.config.supportedUrls) { return this.config.supportedUrls(); } return { "image/*": [/^https?:\/\/.+/], "application/pdf": [/^https?:\/\/.+/], "audio/*": [/^https?:\/\/.+/], "video/*": [ /^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/, /^https?:\/\/youtu\.be\/.+/, /^gs:\/\/.+/ ] }; } async getArgs(options) { var _a18, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t; const warnings = []; const opts = await parseProviderOptions2({ provider: "google", providerOptions: options.providerOptions, schema: googleInteractionsLanguageModelOptions }); const isAgent = this.agent != null; const hasTools = options.tools != null && options.tools.length > 0; let toolsForBody; let toolChoiceForBody; if (hasTools && isAgent) { warnings.push({ type: "other", message: "google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body." }); } else if (hasTools) { const prepared = prepareGoogleInteractionsTools({ tools: options.tools, toolChoice: options.toolChoice }); toolsForBody = prepared.tools; toolChoiceForBody = prepared.toolChoice; warnings.push(...prepared.toolWarnings); } let responseMimeType; let responseFormat; if (((_a18 = options.responseFormat) == null ? void 0 : _a18.type) === "json") { if (isAgent) { warnings.push({ type: "other", message: "google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored." }); } else { responseMimeType = "application/json"; if (options.responseFormat.schema != null) { responseFormat = options.responseFormat.schema; } } } const { input, systemInstruction: convertedSystemInstruction, warnings: convWarnings } = convertToGoogleInteractionsInput({ prompt: options.prompt, previousInteractionId: (_b18 = opts == null ? void 0 : opts.previousInteractionId) != null ? _b18 : void 0, store: (_c = opts == null ? void 0 : opts.store) != null ? _c : void 0, mediaResolution: (_d = opts == null ? void 0 : opts.mediaResolution) != null ? _d : void 0 }); warnings.push(...convWarnings); let systemInstruction = convertedSystemInstruction; const optionSystemInstruction = (_e = opts == null ? void 0 : opts.systemInstruction) != null ? _e : void 0; if (systemInstruction != null && optionSystemInstruction != null) { warnings.push({ type: "other", message: "google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message." }); } else if (systemInstruction == null && optionSystemInstruction != null) { systemInstruction = optionSystemInstruction; } let generationConfig; if (isAgent) { const droppedFields = []; if (options.temperature != null) droppedFields.push("temperature"); if (options.topP != null) droppedFields.push("topP"); if (options.seed != null) droppedFields.push("seed"); if (options.stopSequences != null && options.stopSequences.length > 0) { droppedFields.push("stopSequences"); } if (options.maxOutputTokens != null) droppedFields.push("maxOutputTokens"); if ((opts == null ? void 0 : opts.thinkingLevel) != null) droppedFields.push("thinkingLevel"); if ((opts == null ? void 0 : opts.thinkingSummaries) != null) { droppedFields.push("thinkingSummaries"); } if ((opts == null ? void 0 : opts.imageConfig) != null) droppedFields.push("imageConfig"); if (droppedFields.length > 0) { warnings.push({ type: "other", message: `google.interactions: ${droppedFields.join(", ")} ${droppedFields.length === 1 ? "is" : "are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.` }); } generationConfig = void 0; } else { generationConfig = pruneUndefined({ temperature: (_f = options.temperature) != null ? _f : void 0, top_p: (_g = options.topP) != null ? _g : void 0, seed: (_h = options.seed) != null ? _h : void 0, stop_sequences: options.stopSequences != null && options.stopSequences.length > 0 ? options.stopSequences : void 0, max_output_tokens: (_i = options.maxOutputTokens) != null ? _i : void 0, thinking_level: (_j = opts == null ? void 0 : opts.thinkingLevel) != null ? _j : void 0, thinking_summaries: (_k = opts == null ? void 0 : opts.thinkingSummaries) != null ? _k : void 0, image_config: (opts == null ? void 0 : opts.imageConfig) != null ? pruneUndefined({ aspect_ratio: (_l = opts.imageConfig.aspectRatio) != null ? _l : void 0, image_size: (_m = opts.imageConfig.imageSize) != null ? _m : void 0 }) : void 0, tool_choice: toolChoiceForBody }); } let agentConfig; if (isAgent && (opts == null ? void 0 : opts.agentConfig) != null) { const ac = opts.agentConfig; if (ac.type === "deep-research") { agentConfig = pruneUndefined({ type: "deep-research", thinking_summaries: (_n = ac.thinkingSummaries) != null ? _n : void 0, visualization: (_o = ac.visualization) != null ? _o : void 0, collaborative_planning: (_p = ac.collaborativePlanning) != null ? _p : void 0 }); } else if (ac.type === "dynamic") { agentConfig = { type: "dynamic" }; } } const args = pruneUndefined({ ...isAgent ? { agent: this.agent } : { model: this.modelId }, input, system_instruction: systemInstruction, tools: toolsForBody, response_format: responseFormat, response_mime_type: responseMimeType, response_modalities: (opts == null ? void 0 : opts.responseModalities) != null ? opts.responseModalities : void 0, previous_interaction_id: (_q = opts == null ? void 0 : opts.previousInteractionId) != null ? _q : void 0, service_tier: (_r = opts == null ? void 0 : opts.serviceTier) != null ? _r : void 0, store: (_s = opts == null ? void 0 : opts.store) != null ? _s : void 0, generation_config: generationConfig != null && Object.keys(generationConfig).length > 0 ? generationConfig : void 0, agent_config: agentConfig, ...isAgent ? { background: true } : {} }); return { args, warnings, isAgent, pollingTimeoutMs: (_t = opts == null ? void 0 : opts.pollingTimeoutMs) != null ? _t : void 0 }; } async doGenerate(options) { var _a18, _b18, _c, _d, _e, _f; const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options); const url = `${this.config.baseURL}/interactions`; const mergedHeaders = combineHeaders2( this.config.headers ? await resolve2(this.config.headers) : void 0, options.headers ); const postResult = await postJsonToApi2({ url, headers: mergedHeaders, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleInteractionsResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let { responseHeaders, value: response, rawValue: rawResponse } = postResult; if (isAgent && !isTerminalStatus(response.status)) { const polled = await pollGoogleInteractionUntilTerminal({ baseURL: this.config.baseURL, interactionId: response.id, headers: mergedHeaders, fetch: this.config.fetch, abortSignal: options.abortSignal, timeoutMs: pollingTimeoutMs }); response = polled.response; rawResponse = polled.rawResponse; responseHeaders = (_a18 = polled.responseHeaders) != null ? _a18 : responseHeaders; } const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0; const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({ outputs: (_b18 = response.outputs) != null ? _b18 : null, generateId: (_c = this.config.generateId) != null ? _c : generateId2, interactionId }); const finishReason = { unified: mapGoogleInteractionsFinishReason({ status: response.status, hasFunctionCall }), raw: response.status }; const serviceTier = (_e = (_d = response.service_tier) != null ? _d : responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]) != null ? _e : void 0; const providerMetadata = { google: { ...interactionId != null ? { interactionId } : {}, ...serviceTier != null ? { serviceTier } : {} } }; let timestamp; if (typeof response.created === "string") { const parsed = new Date(response.created); if (!Number.isNaN(parsed.getTime())) { timestamp = parsed; } } return { content, finishReason, usage: convertGoogleInteractionsUsage(response.usage), warnings, providerMetadata, request: { body: args }, response: { headers: responseHeaders, body: rawResponse, ...interactionId != null ? { id: interactionId } : {}, ...timestamp ? { timestamp } : {}, modelId: (_f = response.model) != null ? _f : void 0 } }; } async doStream(options) { var _a18; const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options); const url = `${this.config.baseURL}/interactions`; const mergedHeaders = combineHeaders2( this.config.headers ? await resolve2(this.config.headers) : void 0, options.headers ); if (isAgent) { return this.doStreamAgent({ args, warnings, url, mergedHeaders, options, pollingTimeoutMs }); } const body = { ...args, stream: true }; const { responseHeaders, value: response } = await postJsonToApi2({ url, headers: mergedHeaders, body, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler2( googleInteractionsEventSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]; const transform = buildGoogleInteractionsStreamTransform({ warnings, generateId: (_a18 = this.config.generateId) != null ? _a18 : generateId2, includeRawChunks: options.includeRawChunks, serviceTier: headerServiceTier }); return { stream: response.pipeThrough(transform), request: { body }, response: { headers: responseHeaders } }; } /* * Drive the streaming surface for agent calls. Agent calls require * `background: true`, which is incompatible with `stream: true` on POST. * * In principle the API also exposes `GET /interactions/{id}?stream=true` * to replay events as the agent runs. In practice the connection is * idle for long stretches while the agent thinks (deep-research can run * for a minute or more between SSE events), and undici's default body * timeout terminates the request mid-flight with `UND_ERR_BODY_TIMEOUT`. * Tuning the timeout per-call would require the caller to thread an * `undici.Agent` through `fetch`, which contradicts the AI SDK's * pluggable-fetch contract. * * We therefore drive `doStream` exactly like `doGenerate` for agents: * POST with `background: true`, poll `GET /interactions/{id}` until * terminal, then synthesize the stream from the final outputs. The * user-facing surface stays identical -- text-start / text-delta / * text-end / finish parts arrive in the same order as a true SSE * response, just buffered until the agent completes. */ async doStreamAgent({ args, warnings, url, mergedHeaders, options, pollingTimeoutMs }) { var _a18, _b18; const postResult = await postJsonToApi2({ url, headers: mergedHeaders, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( googleInteractionsResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let { responseHeaders: postHeaders, value: postResponse } = postResult; const interactionId = postResponse.id; if (interactionId == null || interactionId.length === 0) { throw new Error( "google.interactions: agent POST response did not include an interaction id; cannot poll for the agent result." ); } if (!isTerminalStatus(postResponse.status)) { const polled = await pollGoogleInteractionUntilTerminal({ baseURL: this.config.baseURL, interactionId, headers: mergedHeaders, fetch: this.config.fetch, abortSignal: options.abortSignal, timeoutMs: pollingTimeoutMs }); postResponse = polled.response; postHeaders = (_a18 = polled.responseHeaders) != null ? _a18 : postHeaders; } const stream = synthesizeGoogleInteractionsAgentStream({ response: postResponse, warnings, generateId: (_b18 = this.config.generateId) != null ? _b18 : generateId2, includeRawChunks: options.includeRawChunks, headerServiceTier: postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"] }); return { stream, request: { body: args }, response: { headers: postHeaders } }; } }; function pruneUndefined(obj) { const result = {}; for (const [key, value] of Object.entries(obj)) { if (value === void 0) continue; result[key] = value; } return result; } function createGoogleGenerativeAI(options = {}) { var _a18, _b18; const baseURL = (_a18 = withoutTrailingSlash2(options.baseURL)) != null ? _a18 : "https://generativelanguage.googleapis.com/v1beta"; const providerName = (_b18 = options.name) != null ? _b18 : "google.generative-ai"; const getHeaders = () => withUserAgentSuffix2( { "x-goog-api-key": loadApiKey2({ apiKey: options.apiKey, environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY", description: "Google Generative AI" }), ...options.headers }, `ai-sdk/google/${VERSION6}` ); const createChatModel = (modelId) => { var _a23; return new GoogleGenerativeAILanguageModel(modelId, { provider: providerName, baseURL, headers: getHeaders, generateId: (_a23 = options.generateId) != null ? _a23 : generateId2, supportedUrls: () => ({ "*": [ // Google Generative Language "files" endpoint // e.g. https://generativelanguage.googleapis.com/v1beta/files/... new RegExp(`^${baseURL}/files/.*$`), // YouTube URLs (public or unlisted videos) new RegExp( `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$` ), new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`) ] }), fetch: options.fetch }); }; const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch }); const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch }); const createVideoModel = (modelId) => { var _a23; return new GoogleGenerativeAIVideoModel(modelId, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch, generateId: (_a23 = options.generateId) != null ? _a23 : generateId2 }); }; const createInteractionsModel = (modelIdOrAgent) => { var _a23; return new GoogleInteractionsLanguageModel( modelIdOrAgent, { provider: `${providerName}.interactions`, baseURL, headers: getHeaders, generateId: (_a23 = options.generateId) != null ? _a23 : generateId2, fetch: options.fetch } ); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Google Generative AI model function cannot be called with the new keyword." ); } return createChatModel(modelId); }; provider.specificationVersion = "v3"; provider.languageModel = createChatModel; provider.chat = createChatModel; provider.generativeAI = createChatModel; provider.embedding = createEmbeddingModel; provider.embeddingModel = createEmbeddingModel; provider.textEmbedding = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.image = createImageModel; provider.imageModel = createImageModel; provider.video = createVideoModel; provider.videoModel = createVideoModel; provider.interactions = createInteractionsModel; provider.tools = googleTools; return provider; } createGoogleGenerativeAI(); exports.AISDKError = AISDKError2; exports.APICallError = APICallError; exports.APICallError2 = APICallError2; exports.EXCLUDED_PROVIDERS = EXCLUDED_PROVIDERS; exports.GATEWAY_AUTH_HEADER = GATEWAY_AUTH_HEADER; exports.InvalidPromptError = InvalidPromptError; exports.InvalidResponseDataError = InvalidResponseDataError; exports.InvalidResponseDataError2 = InvalidResponseDataError2; exports.MASTRA_GATEWAY_STREAM_TRANSPORT = MASTRA_GATEWAY_STREAM_TRANSPORT; exports.MASTRA_USER_AGENT = MASTRA_USER_AGENT; exports.MastraModelGateway = MastraModelGateway; exports.NoSuchModelError = NoSuchModelError; exports.NoSuchModelError2 = NoSuchModelError2; exports.OpenAICompatibleChatLanguageModel = OpenAICompatibleChatLanguageModel; exports.OpenAICompatibleCompletionLanguageModel = OpenAICompatibleCompletionLanguageModel; exports.OpenAICompatibleEmbeddingModel = OpenAICompatibleEmbeddingModel; exports.PROVIDERS_WITH_INSTALLED_PACKAGES = PROVIDERS_WITH_INSTALLED_PACKAGES; exports.TooManyEmbeddingValuesForCallError = TooManyEmbeddingValuesForCallError; exports.TooManyEmbeddingValuesForCallError2 = TooManyEmbeddingValuesForCallError2; exports.UnsupportedFunctionalityError = UnsupportedFunctionalityError; exports.UnsupportedFunctionalityError2 = UnsupportedFunctionalityError2; exports.combineHeaders = combineHeaders; exports.combineHeaders2 = combineHeaders2; exports.convertBase64ToUint8Array = convertBase64ToUint8Array; exports.convertBase64ToUint8Array2 = convertBase64ToUint8Array2; exports.convertImageModelFileToDataUri = convertImageModelFileToDataUri; exports.convertToBase64 = convertToBase64; exports.convertToBase642 = convertToBase642; exports.convertUint8ArrayToBase64 = convertUint8ArrayToBase64; exports.convertUint8ArrayToBase642 = convertUint8ArrayToBase642; exports.createAnthropic = createAnthropic; exports.createBinaryResponseHandler = createBinaryResponseHandler; exports.createBinaryResponseHandler2 = createBinaryResponseHandler2; exports.createEventSourceResponseHandler = createEventSourceResponseHandler; exports.createEventSourceResponseHandler2 = createEventSourceResponseHandler2; exports.createGoogleGenerativeAI = createGoogleGenerativeAI; exports.createJsonErrorResponseHandler = createJsonErrorResponseHandler; exports.createJsonErrorResponseHandler2 = createJsonErrorResponseHandler2; exports.createJsonResponseHandler = createJsonResponseHandler; exports.createJsonResponseHandler2 = createJsonResponseHandler2; exports.createOpenAI = createOpenAI; exports.createOpenAICompatible = createOpenAICompatible; exports.createProviderDefinedToolFactory = createProviderDefinedToolFactory; exports.createProviderDefinedToolFactoryWithOutputSchema = createProviderDefinedToolFactoryWithOutputSchema; exports.createProviderToolFactory = createProviderToolFactory; exports.createProviderToolFactoryWithOutputSchema = createProviderToolFactoryWithOutputSchema; exports.createStatusCodeErrorResponseHandler = createStatusCodeErrorResponseHandler2; exports.delay = delay2; exports.dist_exports = dist_exports; exports.extractResponseHeaders = extractResponseHeaders2; exports.generateId = generateId; exports.generateId2 = generateId2; exports.getFromApi = getFromApi2; exports.injectJsonInstructionIntoMessages = injectJsonInstructionIntoMessages2; exports.isParsableJson = isParsableJson; exports.isParsableJson2 = isParsableJson2; exports.lazySchema = lazySchema; exports.lazySchema2 = lazySchema2; exports.lazyValidator = lazyValidator; exports.loadApiKey = loadApiKey; exports.loadApiKey2 = loadApiKey2; exports.loadOptionalSetting = loadOptionalSetting; exports.loadSetting = loadSetting; exports.mediaTypeToExtension = mediaTypeToExtension; exports.mediaTypeToExtension2 = mediaTypeToExtension2; exports.parseProviderOptions = parseProviderOptions; exports.parseProviderOptions2 = parseProviderOptions2; exports.postFormDataToApi = postFormDataToApi; exports.postFormDataToApi2 = postFormDataToApi2; exports.postJsonToApi = postJsonToApi; exports.postJsonToApi2 = postJsonToApi2; exports.resolve = resolve; exports.resolve2 = resolve2; exports.safeParseJSON = safeParseJSON2; exports.validateTypes = validateTypes; exports.validateTypes2 = validateTypes2; exports.withUserAgentSuffix = withUserAgentSuffix; exports.withUserAgentSuffix2 = withUserAgentSuffix2; exports.withoutTrailingSlash = withoutTrailingSlash; exports.withoutTrailingSlash2 = withoutTrailingSlash2; exports.zodSchema = zodSchema; exports.zodSchema2 = zodSchema2; //# sourceMappingURL=chunk-OCS2GTEN.cjs.map //# sourceMappingURL=chunk-OCS2GTEN.cjs.map