UNPKG

@mastra/core

Version:
9,493 lines • 333 kB
import { _ as MASTRA_GATEWAY_STREAM_TRANSPORT, a as interpolateUrlTemplate, b as createOpenAICompatible, f as findGatewayForModel, h as shouldEnableGateway, l as MASTRA_USER_AGENT, m as hasAuthCredentials, o as parseModelRouterId, p as getGatewayId, r as ModelsDevGateway, s as createGoogleGenerativeAI, t as NetlifyGateway, v as MastraModelGateway, x as EventSourceParserStream, y as createOpenAI } from "./netlify-WYnWTeMp.js";
import { n as prepareAzureStrictToolSchemas, r as createStreamFromGenerateResult, t as AISDKV5LanguageModel } from "./model-DS-b2R-R.js";
import { i as aiV5PromptToAIV7Prompt, r as aiV5PromptToAIV6Prompt } from "./to-prompt-BsDtVXrf.js";
import { t as convertToDataContent } from "./content-CFBIylxS.js";
import { f as MastraGateway, l as modelSupportsTemperature, n as PROVIDER_REGISTRY, p as gatewayServesObservationalMemory, t as GatewayRegistry } from "./provider-registry-DBfyKz2x.js";
import { i as MastraError, n as ErrorDomain, t as ErrorCategory } from "./error-oh2DLsP2.js";
import { u as RequestContext } from "./request-context-COnZHt2-.js";
import { n as resolveDynamicArgument } from "./dynamic-argument-BzPK3qPN.js";
import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
import * as z4 from "zod/v4";
import { z } from "zod/v4";
import { ZodFirstPartyTypeKind } from "zod/v3";
import { createHmac } from "crypto";
import WebSocket from "ws";
// src/stream/types.ts
let ChunkFrom = /* @__PURE__ */ function(ChunkFrom) {
	ChunkFrom["AGENT"] = "AGENT";
	ChunkFrom["USER"] = "USER";
	ChunkFrom["SYSTEM"] = "SYSTEM";
	ChunkFrom["WORKFLOW"] = "WORKFLOW";
	ChunkFrom["NETWORK"] = "NETWORK";
	return ChunkFrom;
}({});
const MASTRA_MODEL_STREAM_TRANSPORT = Symbol.for("@mastra/core.modelStreamTransport");
function attachModelStreamTransport(target, transport) {
	if (!transport) return;
	Object.defineProperty(target, MASTRA_MODEL_STREAM_TRANSPORT, {
		configurable: true,
		value: transport
	});
}
function readModelStreamTransport(target) {
	return target?.[MASTRA_MODEL_STREAM_TRANSPORT];
}
/**
* Whether a stream chunk or message part is a custom `data-*` chunk (e.g. written via `writer.custom()`).
* The `data-` type prefix is the discriminant for these chunks, shared with the AI SDK.
*/
function isDataChunk(value) {
	const type = value?.type;
	return typeof type === "string" && type.startsWith("data-");
}
// src/llm/model/aisdk/v6/model.ts
/**
* Remaps tool types from V2 format ('provider-defined') to V3 format ('provider').
* Tools may arrive in V2 format when prepared upstream (e.g., by ToolBuilder or
* prepareToolsAndToolChoice) without knowing the final model version. This ensures
* provider tools (like openai.tools.webSearch()) work correctly with V3 models.
*/
function remapToolsToV3(options) {
	if (!options.tools?.length) return options;
	const remappedTools = options.tools.map((tool) => {
		if (tool.type === "provider-defined") return {
			...tool,
			type: "provider"
		};
		return tool;
	});
	return {
		...options,
		tools: remappedTools
	};
}
/**
* ModelRouter exposes a V2 interface, so prompts prepared upstream may contain
* V2 tool-result media parts even when the resolved provider implements V3.
*/
function remapToolResultMediaPartsToV3(options) {
	return {
		...options,
		prompt: aiV5PromptToAIV6Prompt(options.prompt)
	};
}
function remapCallOptionsToV3(options) {
	return remapToolsToV3(remapToolResultMediaPartsToV3(options));
}
/**
* Wrapper class for AI SDK V6 (LanguageModelV3) that converts doGenerate to return
* a stream format for consistency with Mastra's streaming architecture.
*/
var AISDKV6LanguageModel = class {
	/**
	* The language model must specify which language model interface version it implements.
	*/
	specificationVersion = "v3";
	/**
	* Name of the provider for logging purposes.
	*/
	provider;
	/**
	* Provider-specific model ID for logging purposes.
	*/
	modelId;
	/** Full `provider/model` ID this model was resolved from, when known. */
	id;
	/**
	* Supported URL patterns by media type for the provider.
	*
	* The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`).
	* and the values are arrays of regular expressions that match the URL paths.
	* The matching should be against lower-case URLs.
	* Matched URLs are supported natively by the model and are not downloaded.
	* @returns A map of supported URL patterns by media type (as a promise or a plain object).
	*/
	supportedUrls;
	/**
	* Whether the wrapped provider model sends native structured output (for example
	* `@ai-sdk/openai-compatible` models created with `supportsStructuredOutputs: true`).
	*/
	supportsStructuredOutputs;
	#model;
	constructor(config) {
		this.#model = config;
		this.provider = this.#model.provider;
		this.modelId = this.#model.modelId;
		this.supportedUrls = this.#model.supportedUrls;
		const supportsStructuredOutputs = config.supportsStructuredOutputs;
		if (typeof supportsStructuredOutputs === "boolean") this.supportsStructuredOutputs = supportsStructuredOutputs;
	}
	async doGenerate(options) {
		const result = await this.#model.doGenerate(remapCallOptionsToV3(options));
		return {
			...result,
			request: result.request,
			response: result.response,
			stream: createStreamFromGenerateResult(result)
		};
	}
	async doStream(options) {
		return await this.#model.doStream(remapCallOptionsToV3(options));
	}
	/**
	* Custom serialization for tracing/observability spans.
	* `#model` is already a true JS private field and not enumerable, so
	* the wrapped provider SDK client can't leak. This method makes the
	* safe shape explicit and avoids walking `supportedUrls` (a
	* PromiseLike / regex map that isn't useful in spans).
	*/
	serializeForSpan() {
		return {
			specificationVersion: this.specificationVersion,
			modelId: this.modelId,
			provider: this.provider
		};
	}
};
// src/llm/model/aisdk/v7/model.ts
/**
* Remaps tool types from V2 format ('provider-defined') to V4 format ('provider').
* Tools may arrive in V2 format when prepared upstream (e.g., by ToolBuilder or
* prepareToolsAndToolChoice) without knowing the final model version. This ensures
* provider tools (like openai.tools.webSearch()) work correctly with V4 models.
*
* V4 shares the V3 convention ('provider'), so the same remap applies.
*/
function remapToolsToV4(options) {
	if (!options.tools?.length) return options;
	const remappedTools = options.tools.map((tool) => {
		if (tool.type === "provider-defined") return {
			...tool,
			type: "provider"
		};
		return tool;
	});
	return {
		...options,
		tools: remappedTools
	};
}
function isTaggedV4FileData(data) {
	if (typeof data !== "object" || data === null || !("type" in data)) return false;
	const type = data.type;
	return type === "data" || type === "url" || type === "reference" || type === "text";
}
/**
* The Agent loop calls V4 providers directly, bypassing AI SDK v7's prompt
* conversion. Agent prompts may therefore still contain V2/V3 flat file data.
* Convert that legacy shape while preserving already-normalized V4 data.
*/
function normalizeFileDataForV4(data) {
	if (isTaggedV4FileData(data)) return { data };
	const { data: convertedData, mediaType } = convertToDataContent(data);
	return {
		data: convertedData instanceof URL ? {
			type: "url",
			url: convertedData
		} : {
			type: "data",
			data: convertedData
		},
		mediaType
	};
}
function remapFilePartsToV4(options) {
	let promptModified = false;
	const prompt = options.prompt.map((message) => {
		if (message.role !== "user" && message.role !== "assistant") return message;
		let contentModified = false;
		const content = message.content.map((part) => {
			if (part.type !== "file") return part;
			const { data, mediaType } = normalizeFileDataForV4(part.data);
			if (data === part.data && mediaType == null) return part;
			contentModified = true;
			return {
				...part,
				data,
				mediaType: mediaType ?? part.mediaType
			};
		});
		if (!contentModified) return message;
		promptModified = true;
		return {
			...message,
			content
		};
	});
	return promptModified ? {
		...options,
		prompt
	} : options;
}
/**
* ModelRouter exposes a V2 interface, so prompts prepared upstream may contain
* V2 tool-result media parts even when the resolved provider implements V4.
*/
function remapToolResultMediaPartsToV4(options) {
	return {
		...options,
		prompt: aiV5PromptToAIV7Prompt(options.prompt)
	};
}
function remapCallOptionsToV4(options) {
	return remapToolsToV4(remapFilePartsToV4(remapToolResultMediaPartsToV4(options)));
}
/**
* V4 responses tag generated file data ({type: 'data' | 'url'}), but Mastra's
* shared response pipeline (chunk transforms, file buffering, message
* persistence) expects the flat V2/V3 shape (base64 string | Uint8Array).
* Untag before handing results to the shared pipeline so file chunks and
* persisted message history keep the flat contract. This applies to both
* 'file' and 'reasoning-file' parts, which carry the same tagged data shape.
*
* Response file data is typed as the 'data' | 'url' variants only, so this
* guard is exhaustive for well-formed responses. Other tagged variants
* ('reference' | 'text') have no flat equivalent and pass through untouched.
*/
function isUntaggableV4ResponseFileData(data) {
	if (typeof data !== "object" || data === null || !("type" in data)) return false;
	return data.type === "data" || data.type === "url";
}
function untagV4ResponseFileData(data) {
	return data.type === "url" ? data.url.toString() : data.data;
}
function isFilePartType(type) {
	return type === "file" || type === "reasoning-file";
}
function untagResponseFileContent(content) {
	let contentModified = false;
	const untagged = content.map((part) => {
		if (!isFilePartType(part.type) || !("data" in part) || !isUntaggableV4ResponseFileData(part.data)) return part;
		contentModified = true;
		return {
			...part,
			data: untagV4ResponseFileData(part.data)
		};
	});
	return contentModified ? untagged : content;
}
function untagFileStreamParts(stream) {
	return stream.pipeThrough(new TransformStream({ transform(part, controller) {
		if (isFilePartType(part.type) && "data" in part && isUntaggableV4ResponseFileData(part.data)) controller.enqueue({
			...part,
			data: untagV4ResponseFileData(part.data)
		});
		else controller.enqueue(part);
	} }));
}
/**
* Wrapper class for AI SDK V7 (LanguageModelV4) that converts doGenerate to return
* a stream format for consistency with Mastra's streaming architecture.
*/
var AISDKV7LanguageModel = class {
	/**
	* The language model must specify which language model interface version it implements.
	*/
	specificationVersion = "v4";
	/**
	* Name of the provider for logging purposes.
	*/
	provider;
	/**
	* Provider-specific model ID for logging purposes.
	*/
	modelId;
	/** Full `provider/model` ID this model was resolved from, when known. */
	id;
	/**
	* Supported URL patterns by media type for the provider.
	*
	* The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`).
	* and the values are arrays of regular expressions that match the URL paths.
	* The matching should be against lower-case URLs.
	* Matched URLs are supported natively by the model and are not downloaded.
	* @returns A map of supported URL patterns by media type (as a promise or a plain object).
	*/
	supportedUrls;
	/**
	* Whether the wrapped provider model sends native structured output (for example
	* `@ai-sdk/openai-compatible` models created with `supportsStructuredOutputs: true`).
	*/
	supportsStructuredOutputs;
	#model;
	constructor(config) {
		this.#model = config;
		this.provider = this.#model.provider;
		this.modelId = this.#model.modelId;
		this.supportedUrls = this.#model.supportedUrls;
		const supportsStructuredOutputs = config.supportsStructuredOutputs;
		if (typeof supportsStructuredOutputs === "boolean") this.supportsStructuredOutputs = supportsStructuredOutputs;
	}
	async doGenerate(options) {
		const result = await this.#model.doGenerate(remapCallOptionsToV4(options));
		const content = untagResponseFileContent(result.content);
		const untaggedResult = content === result.content ? result : {
			...result,
			content
		};
		return {
			...untaggedResult,
			request: result.request,
			response: result.response,
			stream: createStreamFromGenerateResult(untaggedResult)
		};
	}
	async doStream(options) {
		const result = await this.#model.doStream(remapCallOptionsToV4(options));
		return {
			...result,
			stream: untagFileStreamParts(result.stream)
		};
	}
	/**
	* Custom serialization for tracing/observability spans.
	* `#model` is already a true JS private field and not enumerable, so
	* the wrapped provider SDK client can't leak. This method makes the
	* safe shape explicit and avoids walking `supportedUrls` (a
	* PromiseLike / regex map that isn't useful in spans).
	*/
	serializeForSpan() {
		return {
			specificationVersion: this.specificationVersion,
			modelId: this.modelId,
			provider: this.provider
		};
	}
};
// src/llm/model/gateways/defaults.ts
function getStaticProvidersByGateway(name) {
	return Object.fromEntries(Object.entries(PROVIDER_REGISTRY).filter(([_provider, config]) => config.gateway === name));
}
const defaultGateways = [
	new NetlifyGateway(),
	new MastraGateway(),
	new ModelsDevGateway(getStaticProvidersByGateway(`models.dev`))
];
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/2.0.5/2c8283d13e9eb4f0e5a1ac47681372d3f46a500d1f90320b75e3c03a424c2390/node_modules/@ai-sdk/provider/dist/index.mjs
var marker$1 = "vercel.ai.error";
var symbol$1 = Symbol.for(marker$1);
var _a$2;
var _b$1;
var AISDKError = class _AISDKError extends (_b$1 = Error, _a$2 = symbol$1, _b$1) {
	/**
	* 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: name14, message, cause }) {
		super(message);
		this[_a$2] = true;
		this.name = name14;
		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$1);
	}
	static hasMarker(error, marker15) {
		const markerSymbol = Symbol.for(marker15);
		return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
	}
};
var name$1 = "AI_APICallError";
var marker2 = `vercel.ai.error.${name$1}`;
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 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
		super({
			name: name$1,
			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) {
	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) {
	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) {
	constructor({ message }) {
		super({
			name: name8,
			message
		});
		this[_a9] = true;
	}
	static isInstance(error) {
		return AISDKError.hasMarker(error, marker9);
	}
};
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.46/eff05af98696c14b937414704a02dc999b9465fb8cc88f9bbfa08ad4317bb4a0/node_modules/@ai-sdk/provider-utils/dist/index.mjs
function combineHeaders(...headers) {
	return headers.reduce((combinedHeaders, currentHeaders) => ({
		...combinedHeaders,
		...currentHeaders
	}), {});
}
function extractResponseHeaders(response) {
	return Object.fromEntries([...response.headers]);
}
var name = "AI_DownloadError";
var marker = `vercel.ai.error.${name}`;
var symbol = Symbol.for(marker);
var _a$1;
var _b;
var DownloadError = class extends (_b = AISDKError, _a$1 = symbol, _b) {
	constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
		super({
			name,
			message,
			cause
		});
		this[_a$1] = true;
		this.url = url;
		this.statusCode = statusCode;
		this.statusText = statusText;
	}
	static isInstance(error) {
		return AISDKError.hasMarker(error, marker);
	}
};
var EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = /* @__PURE__ */ Symbol.for("vercel.ai.embeddingModel.maxInputBytesPerCall");
async function cancelResponseBody(response) {
	var _a2;
	try {
		await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
	} catch (e) {}
}
var DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648;
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) {
			await cancelResponseBody(response);
			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 /* @__PURE__ */ 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();
		} catch (e) {} 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 isAbortError(error) {
	return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
	"ConnectionRefused",
	"ConnectionClosed",
	"FailedToOpenSocket",
	"ECONNRESET",
	"ECONNREFUSED",
	"ETIMEDOUT",
	"EPIPE",
	"UND_ERR_SOCKET",
	"UND_ERR_HEADERS_TIMEOUT",
	"UND_ERR_BODY_TIMEOUT",
	"UND_ERR_CONNECT_TIMEOUT"
]);
function findNetworkError(error) {
	const visited = /* @__PURE__ */ new Set();
	let current = error;
	while (current instanceof Error && !visited.has(current)) {
		visited.add(current);
		const errorWithCode = current;
		if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) return errorWithCode;
		current = current.cause;
	}
}
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
		});
	}
	const networkError = findNetworkError(error);
	if (networkError != null) {
		if (APICallError.isInstance(error)) return new APICallError({
			message: error.message,
			cause: error.cause,
			url: error.url,
			requestBodyValues: error.requestBodyValues,
			statusCode: error.statusCode,
			responseHeaders: error.responseHeaders,
			responseBody: error.responseBody,
			data: error.data,
			isRetryable: true
		});
		return new APICallError({
			message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
			cause: error,
			url,
			requestBodyValues,
			isRetryable: true
		});
	}
	return error;
}
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
	var _a2, _b2, _c;
	if (globalThisAny.window) return `runtime/browser`;
	if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
	if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.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$1(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$1(headers));
	const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
	normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
	return Object.fromEntries(normalizedHeaders.entries());
}
var VERSION$1 = "3.0.46";
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 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 _a2;
	const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
	return (_a2 = {
		mpeg: "mp3",
		"x-wav": "wav",
		opus: "ogg",
		mp4: "m4a",
		"x-m4a": "m4a"
	}[subtype]) != null ? _a2 : 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 : "~standard" in value ? standardSchemaValidator(value) : value();
}
function standardSchemaValidator(standardSchema) {
	return validator(async (value) => {
		const result = await standardSchema["~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;
	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 }) => postToApi({
	url,
	headers: {
		"Content-Type": "application/json",
		...headers
	},
	body: {
		content: JSON.stringify(body),
		values: body
	},
	failedResponseHandler,
	successfulResponseHandler,
	abortSignal,
	fetch
});
var postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({
	url,
	headers,
	body: {
		content: formData,
		values: Object.fromEntries(formData.entries())
	},
	failedResponseHandler,
	successfulResponseHandler,
	abortSignal,
	fetch
});
var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {
	try {
		const response = await fetch(url, {
			method: "POST",
			headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$1}`, 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(tool2) {
	return tool2;
}
function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) {
	return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
		type: "provider-defined",
		id,
		name: name2,
		args,
		inputSchema,
		outputSchema,
		execute,
		toModelOutput,
		onInputStart,
		onInputDelta,
		onInputAvailable
	});
}
var textDecoder = new TextDecoder();
function wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
	const reader = stream.getReader();
	let readerReleased = false;
	const releaseReader = () => {
		if (!readerReleased) {
			reader.releaseLock();
			readerReleased = true;
		}
	};
	return new ReadableStream({
		async pull(controller) {
			try {
				const { done, value } = await reader.read();
				if (done) {
					releaseReader();
					controller.close();
				} else controller.enqueue(value);
			} catch (error) {
				releaseReader();
				if (isAbortError(error)) {
					controller.error(error);
					return;
				}
				controller.error(handleFetchError({
					error: new APICallError({
						message: "Failed to process successful response",
						cause: error,
						statusCode,
						url,
						responseHeaders,
						requestBodyValues
					}),
					url,
					requestBodyValues
				}));
			}
		},
		async cancel(reason) {
			try {
				await reader.cancel(reason);
			} finally {
				releaseReader();
			}
		}
	});
}
async function readResponseBodyAsText({ response, url }) {
	return textDecoder.decode(await readResponseWithSizeLimit({
		response,
		url
	}));
}
var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
	const responseBody = await readResponseBodyAsText({
		response,
		url
	});
	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 = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
	const responseHeaders = extractResponseHeaders(response);
	if (response.body == null) throw new EmptyResponseBodyError({});
	return {
		responseHeaders,
		value: parseJsonEventStream({
			stream: wrapResponseBodyStream({
				stream: response.body,
				url,
				requestBodyValues,
				statusCode: response.status,
				responseHeaders
			}),
			schema: chunkSchema
		})
	};
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
	const responseBody = await readResponseBodyAsText({
		response,
		url
	});
	const parsedResult = await safeParseJSON({
		text: responseBody,
		schema: responseSchema
	});
	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 schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
function lazySchema(createSchema) {
	let schema;
	return () => {
		if (schema == null) schema = createSchema();
		return schema;
	};
}
function jsonSchema(jsonSchema2, { validate } = {}) {
	return {
		[schemaSymbol]: true,
		_type: void 0,
		[validatorSymbol]: true,
		get jsonSchema() {
			if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
			return jsonSchema2;
		},
		validate
	};
}
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
	if (jsonSchema2.type === "object") {
		const { additionalProperties } = jsonSchema2;
		jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? addAdditionalPropertiesToJsonSchema(additionalProperties) : false;
		const properties = jsonSchema2.properties;
		if (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);
	}
	if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
		if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));
		else jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);
	}
	return jsonSchema2;
}
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 _a2, _b2, _c;
	const res = { type: "array" };
	if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== 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;
	}
	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;
	}
	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;
		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;
		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 = /* @__PURE__ */ 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 _a2;
	if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.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 _a2;
	if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.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 _a2;
	if (!refs.applyRegexFlags || !regex.flags) return regex.source;
	const flags = {
		i: regex.flags.includes("i"),
		m: regex.flags.includes("m"),
		s: regex.flags.includes("s")
	};
	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] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.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;
	}
	try {
		new RegExp(pattern);
	} catch (e) {
		console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
		return regex.source;
	}
	return pattern;
}
function parseRecordDef(def, refs) {
	var _a2, _b2, _c, _d, _e, _f;
	const schema = {
		type: "object",
		additionalProperties: (_a2 = parseDef(def.valueType._def, {
			...refs,
			currentPath: [...refs.currentPath, "additionalProperties"]
		})) != null ? _a2 : refs.allowedAdditionalProperties
	};
	if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === 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) === ZodFirstPartyTypeKind.ZodEnum) return {
		...schema,
		propertyNames: { enum: def.keyType._def.values }
	};
	else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === 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);
	return {
		type: "array",
		maxItems: 125,
		items: {
			type: "array",
			items: [parseDef(def.keyType._def, {
				...refs,
				currentPath: [
					...refs.currentPath,
					"items",
					"items",
					"0"
				]
			}) || parseAnyDef(), parseDef(def.valueType._def, {
				...refs,
				currentPath: [
					...refs.currentPath,
					"items",
					"items",
					"1"
				]
			}) || parseAnyDef()],
			minItems: 2,
			maxItems: 2
		}
	};
}
function parseNativeEnumDef(def) {
	const object = def.values;
	const actualValues = Object.keys(def.values).filter((key) => {
		return typeof object[object[key]] !== "number";
	}).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"];
				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;
	}
	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 _a2;
	if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.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"
		]
	});
	return { allOf: [a, parseDef(def.out._def, {
		...refs,
		currentPath: [
			...refs.currentPath,
			"allOf",
			a ? "1" : "0"
		]
	})].filter((x) => x !== void 0) };
};
function parsePromiseDef(def, refs) {
	return parseDef(def.type._def, refs);
}
function parseSetDef(def, refs) {
	const schema = {
		type: "array",
		uniqueItems: true,
		items: parseDef(def.valueType._def, {
			...refs,
			currentPath: [...refs.currentPath, "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 ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
		case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);
		case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
		case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);
		case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
		case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
		case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
		case ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
		case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
		case ZodFirstPartyTypeKind.ZodUnion:
		case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
		case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
		case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
		case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
		case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);
		case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
		case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
		case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
		case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
		case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
		case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
		case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
		case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
		case ZodFirstPartyTypeKind.ZodNaN:
		case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
		case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
		case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
		case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
		case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
		case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
		case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
		case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
		case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
		case ZodFirstPartyTypeKind.ZodFunction:
		case ZodFirstPartyTypeKind.ZodVoid:
		case ZodFirstPartyTypeKind.ZodSymbol: return;
		default: return /* @__PURE__ */ ((_) => void 0)(typeName);
	}
};
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 _a2;
	const seenItem = refs.seen.get(def);
	if (refs.override) {
		const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.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 jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
	if (jsonSchema2) addMeta(def, refs, jsonSchema2);
	if (refs.postProcess) {
		const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
		newItem.jsonSchema = jsonSchema2;
		return postProcessResult;
	}
	newItem.jsonSchema = jsonSchema2;
	return jsonSchema2;
}
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, jsonSchema2) => {
	if (def.description) jsonSchema2.description = def.description;
	return jsonSchema2;
};
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(([name2, def]) => [def._def, {
			def: def._def,
			path: [
				..._options.basePath,
				_options.definitionPath,
				name2
			],
			jsonSchema: void 0
		}]))
	};
};
var zodToJsonSchema = (schema, options) => {
	var _a2;
	const refs = getRefs(options);
	let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {
		var _a3;
		return {
			...acc,
			[name3]: (_a3 = parseDef(schema2._def, {
				...refs,
				currentPath: [
					...refs.basePath,
					refs.definitionPath,
					name3
				]
			}, true)) != null ? _a3 : parseAnyDef()
		};
	}, {}) : void 0;
	const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
	const main = (_a2 = parseDef(schema._def, name2 === void 0 ? refs : {
		...refs,
		currentPath: [
			...refs.basePath,
			refs.definitionPath,
			name2
		]
	}, false)) != null ? _a2 : 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 = name2 === void 0 ? definitions ? {
		...main,
		[refs.definitionPath]: definitions
	} : main : {
		$ref: [
			...refs.$refStrategy === "relative" ? [] : refs.basePath,
			refs.definitionPath,
			name2
		].join("/"),
		[refs.definitionPath]: {
			...definitions,
			[name2]: main
		}
	};
	combined.$schema = "http://json-schema.org/draft-07/schema#";
	return combined;
};
var zod_to_json_schema_default = zodToJsonSchema;
function zod3Schema(zodSchema2, options) {
	var _a2;
	const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
	return jsonSchema(() => zod_to_json_schema_default(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
		const result = await zodSchema2.safeParseAsync(value);
		return result.success ? {
			success: true,
			value: result.data
		} : {
			success: false,
			error: result.error
		};
	} });
}
function zod4Schema(zodSchema2, options) {
	var _a2;
	const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
	return jsonSchema(() => addAdditionalPropertiesToJsonSchema(z4.toJSONSchema(zodSchema2, {
		target: "draft-7",
		io: "input",
		reused: useReferences ? "ref" : "inline"
	})), { validate: async (value) => {
		const result = await z4.safeParseAsync(zodSchema2, value);
		return result.success ? {
			success: true,
			value: result.data
		} : {
			success: false,
			error: result.error
		};
	} });
}
function isZod4Schema(zodSchema2) {
	return "_zod" in zodSchema2;
}
function zodSchema(zodSchema2, options) {
	if (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);
	else return zod3Schema(zodSchema2, options);
}
function startsWithStructuredValue(value) {
	if (typeof value !== "string") return false;
	const firstCharacter = value.trimStart()[0];
	return firstCharacter === "{" || firstCharacter === "[";
}
var StreamingToolCallArgumentState = class {
	constructor(initialValue = "") {
		this.structure = { kind: "undetermined" };
		this.append(initialValue);
	}
	get hasCompleteStructuredValue() {
		return this.structure.kind === "structured" && this.structure.complete === true;
	}
	append(delta) {
		let nextStructure = this.structure;
		for (const character of delta) {
			if (nextStructure.kind === "undetermined") {
				if (/\s/.test(character)) continue;
				if (character !== "{" && character !== "[") {
					nextStructure = { kind: "other" };
					continue;
				}
				nextStructure = {
					kind: "structured",
					stack: [character],
					inString: false,
					escaped: false,
					complete: false
				};
				continue;
			}
			if (nextStructure.kind !== "structured" || nextStructure.complete) continue;
			if (nextStructure.inString) {
				if (nextStructure.escaped) nextStructure.escaped = false;
				else if (character === "\\") nextStructure.escaped = true;
				else if (character === "\"") nextStructure.inString = false;
				continue;
			}
			if (character === "\"") nextStructure.inString = true;
			else if (character === "{" || character === "[") nextStructure.stack.push(character);
			else if (character === "}" || character === "]") {
				const expectedOpening = character === "}" ? "{" : "[";
				if (nextStructure.stack[nextStructure.stack.length - 1] !== expectedOpening) {
					nextStructure = { kind: "other" };
					continue;
				}
				nextStructure.stack.pop();
				if (nextStructure.stack.length === 0) nextStructure.complete = true;
			}
		}
		this.structure = nextStructure;
	}
};
var StreamingToolCallTracker = class {
	constructor(controller, options = {}) {
		this.toolCalls = [];
		this.toolCallsById = /* @__PURE__ */ new Map();
		this.toolCallsByIndex = /* @__PURE__ */ new Map();
		this.usedToolCallIds = /* @__PURE__ */ new Set();
		this.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();
		var _a2, _b2;
		this.controller = controller;
		this._generateId = (_a2 = options.generateId) != null ? _a2 : generateId;
		this.typeValidation = (_b2 = options.typeValidation) != null ? _b2 : "none";
		this.extractMetadata = options.extractMetadata;
		this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
	}
	processDelta(toolCallDelta) {
		var _a2, _b2;
		const wireName = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.name;
		const hasBlankName = typeof wireName === "string" && wireName.trim().length === 0;
		const wireId = this.getNonBlankString(toolCallDelta.id);
		const name2 = this.getNonBlankString(wireName);
		const { index } = toolCallDelta;
		const resolution = this.resolveToolCall({
			wireId,
			index,
			name: name2,
			hasExplicitCallStart: name2 != null && startsWithStructuredValue((_b2 = toolCallDelta.function) == null ? void 0 : _b2.arguments)
		});
		if (resolution.kind === "ambiguous") return;
		let toolCall;
		if (resolution.kind === "new") {
			if (hasBlankName) return;
			toolCall = this.processNewToolCall(toolCallDelta, {
				wireId,
				index,
				name: name2
			});
		} else {
			toolCall = resolution.toolCall;
			if (wireId != null) this.associateWireId(toolCall, wireId);
			this.processExistingToolCall(toolCall, toolCallDelta);
		}
		if (index != null) this.associateIndex(toolCall, index);
	}
	flush() {
		const toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort((a, b) => a.index - b.index || a.sequence - b.sequence) : this.toolCalls;
		for (const toolCall of toolCalls) if (!toolCall.hasFinished) this.finishToolCall(toolCall);
	}
	resolveToolCall({ wireId, index, name: name2, hasExplicitCallStart }) {
		const indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0;
		const matchingIndexedToolCalls = this.filterToolCallsByName(indexedToolCalls, name2);
		if (wireId != null) {
			const toolCallsWithId = this.toolCallsById.get(wireId);
			if (toolCallsWithId != null) {
				if (index != null) {
					const matchingToolCalls = matchingIndexedToolCalls.filter((toolCall) => toolCallsWithId.has(toolCall));
					const matchingToolCall = this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
					if (matchingToolCall.kind !== "new") return matchingToolCall;
					if (name2 != null) return { kind: "new" };
					if (indexedToolCalls != null) return { kind: "ambiguous" };
					return this.resolveMatchingToolCall([...toolCallsWithId], false);
				}
				if (name2 != null) {
					const matchingToolCalls = [...toolCallsWithId].filter((toolCall) => toolCall.function.name === name2);
					return this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
				}
				return this.resolveMatchingToolCall([...toolCallsWithId], false);
			}
			if (matchingIndexedToolCalls.length > 0) return hasExplicitCallStart ? { kind: "new" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, false);
			return { kind: "new" };
		}
		if (indexedToolCalls != null) return this.resolveMatchingToolCall(matchingIndexedToolCalls, hasExplicitCallStart);
		if (name2 != null) return { kind: "new" };
		const unfinishedToolCalls = this.toolCalls.filter((toolCall) => !toolCall.hasFinished);
		if (unfinishedToolCalls.length === 1) return {
			kind: "existing",
			toolCall: unfinishedToolCalls[0]
		};
		return unfinishedToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
	}
	filterToolCallsByName(toolCalls, name2) {
		if (toolCalls == null) return [];
		return [...toolCalls].filter((toolCall) => name2 == null || toolCall.function.name === name2);
	}
	resolveMatchingToolCall(toolCalls, hasExplicitCallStart) {
		if (toolCalls.length === 0) return { kind: "new" };
		if (!hasExplicitCallStart) return toolCalls.length === 1 ? {
			kind: "existing",
			toolCall: toolCalls[0]
		} : { kind: "ambiguous" };
		const continuableToolCalls = toolCalls.filter((toolCall) => !toolCall.argumentState.hasCompleteStructuredValue);
		if (continuableToolCalls.length === 1) return {
			kind: "existing",
			toolCall: continuableToolCalls[0]
		};
		return continuableToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
	}
	processNewToolCall(toolCallDelta, { wireId, index, name: name2 }) {
		var _a2, _b2, _c, _d, _e;
		if (this.typeValidation === "required") {
			if (toolCallDelta.type !== "function") throw new InvalidResponseDataError({
				data: toolCallDelta,
				message: `Expected 'function' type.`
			});
		} else if (this.typeValidation === "if-present") {
			if (toolCallDelta.type != null && toolCallDelta.type !== "function") throw new InvalidResponseDataError({
				data: toolCallDelta,
				message: `Expected 'function' type.`
			});
		}
		if (name2 == null) throw new InvalidResponseDataError({
			data: toolCallDelta,
			message: `Expected 'function.name' to be a string.`
		});
		const id = this.createToolCallId(wireId);
		this.controller.enqueue({
			type: "tool-input-start",
			id,
			toolName: name2
		});
		const toolCall = {
			id,
			index: index != null ? index : void 0,
			sequence: this.toolCalls.length,
			type: "function",
			function: {
				name: name2,
				arguments: (_b2 = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null ? _b2 : ""
			},
			argumentState: new StreamingToolCallArgumentState((_d = (_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null ? _d : ""),
			hasFinished: false,
			metadata: (_e = this.extractMetadata) == null ? void 0 : _e.call(this, toolCallDelta)
		};
		this.toolCalls.push(toolCall);
		if (wireId != null) this.associateWireId(toolCall, wireId);
		if (toolCall.function.arguments.length > 0) this.controller.enqueue({
			type: "tool-input-delta",
			id: toolCall.id,
			delta: toolCall.function.arguments
		});
		return toolCall;
	}
	associateWireId(toolCall, wireId) {
		let toolCallsWithId = this.toolCallsById.get(wireId);
		if (toolCallsWithId == null) {
			toolCallsWithId = /* @__PURE__ */ new Set();
			this.toolCallsById.set(wireId, toolCallsWithId);
		}
		toolCallsWithId.add(toolCall);
	}
	associateIndex(toolCall, index) {
		let toolCallsWithIndex = this.toolCallsByIndex.get(index);
		if (toolCallsWithIndex == null) {
			toolCallsWithIndex = /* @__PURE__ */ new Set();
			this.toolCallsByIndex.set(index, toolCallsWithIndex);
		}
		toolCallsWithIndex.add(toolCall);
	}
	createToolCallId(wireId) {
		var _a2, _b2;
		if (wireId != null && !this.usedToolCallIds.has(wireId)) {
			this.usedToolCallIds.add(wireId);
			return wireId;
		}
		const generatedId = (_a2 = this.getNonBlankString(this._generateId())) != null ? _a2 : "tool-call";
		if (!this.usedToolCallIds.has(generatedId)) {
			this.usedToolCallIds.add(generatedId);
			return generatedId;
		}
		const initialSuffix = (_b2 = this.nextGeneratedIdSuffixes.get(generatedId)) != null ? _b2 : 1;
		const maximumSuffix = initialSuffix + this.usedToolCallIds.size;
		for (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {
			const suffixedId = `${generatedId}-${suffix}`;
			if (!this.usedToolCallIds.has(suffixedId)) {
				this.usedToolCallIds.add(suffixedId);
				this.nextGeneratedIdSuffixes.set(generatedId, suffix + 1);
				return suffixedId;
			}
		}
		throw new Error("Failed to create a unique tool call ID.");
	}
	getNonBlankString(value) {
		return value != null && value.trim().length > 0 ? value : void 0;
	}
	processExistingToolCall(toolCall, toolCallDelta) {
		var _a2;
		if (!toolCall.hasFinished && ((_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null) {
			toolCall.argumentState.append(toolCallDelta.function.arguments);
			toolCall.function.arguments += toolCallDelta.function.arguments;
			this.controller.enqueue({
				type: "tool-input-delta",
				id: toolCall.id,
				delta: toolCallDelta.function.arguments
			});
		}
	}
	finishToolCall(toolCall) {
		var _a2;
		this.controller.enqueue({
			type: "tool-input-end",
			id: toolCall.id
		});
		const providerMetadata = (_a2 = this.buildToolCallProviderMetadata) == null ? void 0 : _a2.call(this, toolCall.metadata);
		this.controller.enqueue({
			type: "tool-call",
			toolCallId: toolCall.id,
			toolName: toolCall.function.name,
			input: toolCall.function.arguments,
			...providerMetadata ? { providerMetadata } : {}
		});
		toolCall.hasFinished = true;
	}
};
var { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
	const latin1string = atob(base64String.replace(/-/g, "+").replace(/_/g, "/"));
	const bytes = new Uint8Array(latin1string.length);
	for (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);
	return bytes;
}
function convertUint8ArrayToBase64(array) {
	var _a2;
	if (typeof ((_a2 = globalThis.Buffer) == null ? void 0 : _a2.from) === "function") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("base64");
	const chunks = [];
	const chunkSize = 4096;
	for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
	return btoa(chunks.join(""));
}
var typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
function isUint8Array(value) {
	return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
}
function convertToBase64(value) {
	return isUint8Array(value) ? convertUint8ArrayToBase64(value) : value;
}
function withoutTrailingSlash(url) {
	return url == null ? void 0 : url.replace(/\/$/, "");
}
function stringifyWithBigIntAndCycles(value) {
	const ancestors = [];
	return JSON.stringify(value, function(_key, value2) {
		if (typeof value2 === "bigint") return value2.toString();
		if (typeof value2 !== "object" || value2 === null) return value2;
		while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
		if (ancestors.includes(value2)) return "[Circular]";
		ancestors.push(value2);
		return value2;
	});
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai/2.0.140/8fd565967bdbe014b81c7f3b28a2442228305bd7edc39d9c0dbc397608e2d0b8/node_modules/@ai-sdk/openai/dist/internal/index.mjs
var openaiErrorDataSchema = () => z.object({ error: z.object({
	message: z.string(),
	type: z.string().nullish(),
	param: z.any().nullish(),
	code: z.union([z.string(), z.number()]).nullish()
}) });
var openaiFailedResponseHandler = createJsonErrorResponseHandler({
	errorSchema: lazySchema(() => zodSchema(openaiErrorDataSchema())),
	errorToMessage: (data) => data.error.message
});
function getOpenAILanguageModelCapabilities(modelId) {
	var _a2, _b, _c, _d, _e;
	const oSeriesVersion = getOSeriesVersion(modelId);
	const gptVersion = getGptVersion(modelId);
	const isGptChatModel = (gptVersion == null ? void 0 : gptVersion.minor) == null && ((_b = (_a2 = gptVersion == null ? void 0 : gptVersion.variant) == null ? void 0 : _a2.startsWith("chat")) != null ? _b : false);
	const isGptNanoModel = (_d = (_c = gptVersion == null ? void 0 : gptVersion.variant) == null ? void 0 : _c.startsWith("nano")) != null ? _d : false;
	const isGpt6OrLaterModel = gptVersion != null && gptVersion.major >= 6;
	const isGpt6SolOrLuna = modelId === "gpt-6-sol" || modelId === "gpt-6-luna";
	const supportsFlexProcessing = oSeriesVersion != null && oSeriesVersion >= 3 || gptVersion != null && gptVersion.major >= 5 && !isGptChatModel;
	const supportsPriorityProcessing = modelId.startsWith("gpt-4") || gptVersion != null && gptVersion.major >= 5 && !isGptNanoModel && !isGptChatModel || oSeriesVersion != null && oSeriesVersion >= 3;
	const isReasoningModel = oSeriesVersion != null || gptVersion != null && gptVersion.major >= 5 && !isGptChatModel || modelId === "codex-mini-latest" || modelId === "computer-use-preview";
	const supportsNonReasoningParameters = !isGpt6OrLaterModel && gptVersion != null && (gptVersion.major > 5 || gptVersion.major === 5 && ((_e = gptVersion.minor) != null ? _e : 0) >= 1);
	return {
		supportsFlexProcessing,
		supportsPriorityProcessing,
		supportsConfigurationUpdate: isGpt6OrLaterModel,
		supportsAsyncToolCalling: isGpt6OrLaterModel,
		supportedReasoningEfforts: isGpt6SolOrLuna ? [
			"none",
			"low",
			"medium",
			"high",
			"xhigh",
			"max"
		] : isGpt6OrLaterModel ? [
			"low",
			"medium",
			"high",
			"xhigh",
			"max"
		] : void 0,
		isReasoningModel,
		systemMessageMode: isReasoningModel ? "developer" : "system",
		supportsNonReasoningParameters
	};
}
function getOSeriesVersion(modelId) {
	const match = /^o(\d+)(?:-|$)/.exec(modelId);
	return match == null ? void 0 : Number(match[1]);
}
function getGptVersion(modelId) {
	const match = /^gpt-(\d+)(?:\.(\d+))?(?:-(.+))?$/.exec(modelId);
	if (match == null) return;
	return {
		major: Number(match[1]),
		minor: match[2] == null ? void 0 : Number(match[2]),
		variant: match[3]
	};
}
function serializeToolCallArguments(input) {
	if (typeof input === "string") try {
		const parsed = secureJsonParse(input);
		if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "{}";
		return input;
	} catch (e) {
		return "{}";
	}
	return stringifyWithBigIntAndCycles(typeof input === "object" && input !== null && !Array.isArray(input) ? input : {});
}
function getPromptCacheBreakpoint(providerOptions) {
	var _a2;
	return (_a2 = providerOptions == null ? void 0 : providerOptions.openai) == null ? void 0 : _a2.promptCacheBreakpoint;
}
function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) {
	const messages = [];
	const warnings = [];
	for (const { role, content, providerOptions } of prompt) switch (role) {
		case "system":
			switch (systemMessageMode) {
				case "system": {
					const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions);
					messages.push({
						role: "system",
						content: promptCacheBreakpoint == null ? content : [{
							type: "text",
							text: content,
							prompt_cache_breakpoint: promptCacheBreakpoint
						}]
					});
					break;
				}
				case "developer": {
					const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions);
					messages.push({
						role: "developer",
						content: promptCacheBreakpoint == null ? content : [{
							type: "text",
							text: content,
							prompt_cache_breakpoint: promptCacheBreakpoint
						}]
					});
					break;
				}
				case "remove":
					warnings.push({
						type: "other",
						message: "system messages are removed for this model"
					});
					break;
				default: throw new Error(`Unsupported system message mode: ${systemMessageMode}`);
			}
			break;
		case "user":
			if (content.length === 1 && content[0].type === "text" && getPromptCacheBreakpoint(content[0].providerOptions) == null) {
				messages.push({
					role: "user",
					content: content[0].text
				});
				break;
			}
			messages.push({
				role: "user",
				content: content.map((part, index) => {
					var _a2, _b, _c;
					switch (part.type) {
						case "text": {
							const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
							return {
								type: "text",
								text: part.text,
								...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
							};
						}
						case "file": {
							const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
							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)}`,
										detail: (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b.imageDetail
									},
									...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
								};
							} else if (part.mediaType.startsWith("audio/")) {
								if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ functionality: "audio file parts with URLs" });
								switch (part.mediaType) {
									case "audio/wav": return {
										type: "input_audio",
										input_audio: {
											data: convertToBase64(part.data),
											format: "wav"
										},
										...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
									};
									case "audio/mp3":
									case "audio/mpeg": return {
										type: "input_audio",
										input_audio: {
											data: convertToBase64(part.data),
											format: "mp3"
										},
										...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
									};
									default: throw new UnsupportedFunctionalityError({ functionality: `audio content parts with media type ${part.mediaType}` });
								}
							} else if (part.mediaType === "application/pdf") {
								if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ 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,${convertToBase64(part.data)}`
									},
									...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
								};
							} else throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` });
						}
					}
				})
			});
			break;
		case "assistant": {
			let text = "";
			const textParts = [];
			let hasPromptCacheBreakpoint = false;
			const toolCalls = [];
			for (const part of content) switch (part.type) {
				case "text": {
					const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
					text += part.text;
					textParts.push({
						type: "text",
						text: part.text,
						...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
					});
					hasPromptCacheBreakpoint || (hasPromptCacheBreakpoint = promptCacheBreakpoint != null);
					break;
				}
				case "tool-call": toolCalls.push({
					id: part.toolCallId,
					type: "function",
					function: {
						name: part.toolName,
						arguments: serializeToolCallArguments(part.input)
					}
				});
			}
			messages.push({
				role: "assistant",
				content: hasPromptCacheBreakpoint ? textParts : toolCalls.length > 0 ? text || null : text,
				tool_calls: toolCalls.length > 0 ? toolCalls : void 0
			});
			break;
		}
		case "tool":
			for (const toolResponse of content) {
				const output = toolResponse.output;
				const promptCacheBreakpoint = getPromptCacheBreakpoint(toolResponse.providerOptions);
				let contentValue;
				switch (output.type) {
					case "text":
					case "error-text":
						contentValue = output.value;
						break;
					case "content":
					case "json":
					case "error-json": contentValue = stringifyWithBigIntAndCycles(output.value);
				}
				messages.push({
					role: "tool",
					tool_call_id: toolResponse.toolCallId,
					content: promptCacheBreakpoint == null ? contentValue : [{
						type: "text",
						text: contentValue,
						prompt_cache_breakpoint: promptCacheBreakpoint
					}]
				});
			}
			break;
		default: throw new Error(`Unsupported role: ${role}`);
	}
	return {
		messages,
		warnings
	};
}
function getResponseMetadata$1({ id, model, created }) {
	return {
		id: id != null ? id : void 0,
		modelId: model != null ? model : void 0,
		timestamp: created ? /* @__PURE__ */ 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 "unknown";
	}
}
var openaiChatResponseSchema = lazyValidator(() => zodSchema(z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	choices: z.array(z.object({
		message: z.object({
			role: z.literal("assistant").nullish(),
			content: z.string().nullish(),
			audio: z.object({ transcript: z.string().nullish() }).nullish(),
			tool_calls: z.array(z.object({
				id: z.string().nullish(),
				type: z.literal("function"),
				function: z.object({
					name: z.string(),
					arguments: z.string()
				})
			})).nullish(),
			annotations: z.array(z.object({
				type: z.literal("url_citation"),
				url_citation: z.object({
					start_index: z.number(),
					end_index: z.number(),
					url: z.string(),
					title: z.string()
				})
			})).nullish()
		}),
		index: z.number(),
		logprobs: z.object({ content: z.array(z.object({
			token: z.string(),
			logprob: z.number(),
			top_logprobs: z.array(z.object({
				token: z.string(),
				logprob: z.number()
			}))
		})).nullish() }).nullish(),
		finish_reason: z.string().nullish()
	})),
	usage: z.object({
		prompt_tokens: z.number().nullish(),
		completion_tokens: z.number().nullish(),
		total_tokens: z.number().nullish(),
		prompt_tokens_details: z.object({
			cached_tokens: z.number().nullish(),
			cache_write_tokens: z.number().nullish()
		}).nullish(),
		completion_tokens_details: z.object({
			reasoning_tokens: z.number().nullish(),
			accepted_prediction_tokens: z.number().nullish(),
			rejected_prediction_tokens: z.number().nullish()
		}).nullish()
	}).nullish()
})));
var openaiChatChunkSchema = lazyValidator(() => zodSchema(z.union([z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	choices: z.array(z.object({
		delta: z.object({
			role: z.enum(["assistant"]).nullish(),
			content: z.string().nullish(),
			tool_calls: z.array(z.object({
				index: z.number(),
				id: z.string().nullish(),
				type: z.literal("function").nullish(),
				function: z.object({
					name: z.string().nullish(),
					arguments: z.string().nullish()
				})
			})).nullish(),
			annotations: z.array(z.object({
				type: z.literal("url_citation"),
				url_citation: z.object({
					start_index: z.number(),
					end_index: z.number(),
					url: z.string(),
					title: z.string()
				})
			})).nullish()
		}).nullish(),
		logprobs: z.object({ content: z.array(z.object({
			token: z.string(),
			logprob: z.number(),
			top_logprobs: z.array(z.object({
				token: z.string(),
				logprob: z.number()
			}))
		})).nullish() }).nullish(),
		finish_reason: z.string().nullish(),
		index: z.number()
	})),
	usage: z.object({
		prompt_tokens: z.number().nullish(),
		completion_tokens: z.number().nullish(),
		total_tokens: z.number().nullish(),
		prompt_tokens_details: z.object({
			cached_tokens: z.number().nullish(),
			cache_write_tokens: z.number().nullish()
		}).nullish(),
		completion_tokens_details: z.object({
			reasoning_tokens: z.number().nullish(),
			accepted_prediction_tokens: z.number().nullish(),
			rejected_prediction_tokens: z.number().nullish()
		}).nullish()
	}).nullish()
}), openaiErrorDataSchema()])));
var openaiChatLanguageModelOptions = lazyValidator(() => zodSchema(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: z.record(z.coerce.number(), 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: z.union([z.boolean(), z.number()]).optional(),
	/**
	* Whether to enable parallel function calling during tool use. Default to true.
	*/
	parallelToolCalls: z.boolean().optional(),
	/**
	* A unique identifier representing your end-user, which can help OpenAI to
	* monitor and detect abuse.
	*/
	user: z.string().optional(),
	/**
	* Reasoning effort for reasoning models. Defaults to `medium`.
	*/
	reasoningEffort: z.enum([
		"none",
		"minimal",
		"low",
		"medium",
		"high",
		"xhigh",
		"max"
	]).optional(),
	/**
	* Maximum number of completion tokens to generate. Useful for reasoning models.
	*/
	maxCompletionTokens: z.number().optional(),
	/**
	* Whether to enable persistence in responses API.
	*/
	store: z.boolean().optional(),
	/**
	* Metadata to associate with the request.
	*/
	metadata: z.record(z.string().max(64), z.string().max(512)).optional(),
	/**
	* Parameters for prediction mode.
	*/
	prediction: z.record(z.string(), z.any()).optional(),
	/**
	* Whether to use structured outputs.
	*
	* @default true
	*/
	structuredOutputs: z.boolean().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: z.enum([
		"auto",
		"flex",
		"priority",
		"default"
	]).optional(),
	/**
	* Whether to use strict JSON schema validation.
	*
	* @default false
	*/
	strictJsonSchema: 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: 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: z.string().optional(),
	/**
	* Prompt cache behavior for GPT-5.6 and later models.
	* `mode` controls whether OpenAI also places an implicit breakpoint.
	* `ttl` sets the minimum cache lifetime and currently only supports 30 minutes.
	*/
	promptCacheOptions: z.object({
		mode: z.enum(["implicit", "explicit"]).optional(),
		ttl: z.literal("30m").optional()
	}).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.
	*          Available for models before GPT-5.6 that support extended caching.
	*
	* @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`.
	*
	* @default 'in_memory'
	*/
	promptCacheRetention: 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: z.string().optional()
})));
function prepareChatTools({ tools, toolChoice, structuredOutputs, strictJsonSchema }) {
	tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
	const toolWarnings = [];
	if (tools == null) return {
		tools: void 0,
		toolChoice: void 0,
		toolWarnings
	};
	const openaiTools = [];
	for (const tool of tools) switch (tool.type) {
		case "function":
			openaiTools.push({
				type: "function",
				function: {
					name: tool.name,
					description: tool.description,
					parameters: tool.inputSchema,
					strict: structuredOutputs ? strictJsonSchema : void 0
				}
			});
			break;
		default: toolWarnings.push({
			type: "unsupported-tool",
			tool
		});
	}
	if (toolChoice == null) return {
		tools: openaiTools,
		toolChoice: void 0,
		toolWarnings
	};
	const type = toolChoice.type;
	switch (type) {
		case "auto":
		case "none":
		case "required": return {
			tools: openaiTools,
			toolChoice: type,
			toolWarnings
		};
		case "tool": return {
			tools: openaiTools,
			toolChoice: {
				type: "function",
				function: { name: toolChoice.toolName }
			},
			toolWarnings
		};
		default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
	}
}
var OpenAIChatLanguageModel = class {
	constructor(modelId, config) {
		this.specificationVersion = "v2";
		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 _a2, _b, _c, _d;
		const warnings = [];
		const openaiOptions = (_a2 = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openaiChatLanguageModelOptions
		})) != null ? _a2 : {};
		const structuredOutputs = (_b = openaiOptions.structuredOutputs) != null ? _b : true;
		const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
		if (topK != null) warnings.push({
			type: "unsupported-setting",
			setting: "topK"
		});
		if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !structuredOutputs) warnings.push({
			type: "unsupported-setting",
			setting: "responseFormat",
			details: "JSON response format schema is only supported with structuredOutputs"
		});
		const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages({
			prompt,
			systemMessageMode: modelCapabilities.systemMessageMode
		});
		warnings.push(...messageWarnings);
		const strictJsonSchema = (_c = openaiOptions.strictJsonSchema) != null ? _c : false;
		let resolvedReasoningEffort = openaiOptions.reasoningEffort;
		if (resolvedReasoningEffort != null && modelCapabilities.supportedReasoningEfforts != null && !modelCapabilities.supportedReasoningEfforts.includes(resolvedReasoningEffort)) {
			warnings.push({
				type: "unsupported-setting",
				setting: "reasoningEffort",
				details: `${this.modelId} only supports the following reasoning efforts: ${modelCapabilities.supportedReasoningEfforts.join(", ")}`
			});
			resolvedReasoningEffort = void 0;
		}
		const baseArgs = {
			model: this.modelId,
			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,
			max_tokens: maxOutputTokens,
			temperature,
			top_p: topP,
			frequency_penalty: frequencyPenalty,
			presence_penalty: presencePenalty,
			response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && responseFormat.schema != null ? {
				type: "json_schema",
				json_schema: {
					schema: responseFormat.schema,
					strict: strictJsonSchema,
					name: (_d = responseFormat.name) != null ? _d : "response",
					description: responseFormat.description
				}
			} : { type: "json_object" } : void 0,
			stop: stopSequences,
			seed,
			verbosity: openaiOptions.textVerbosity,
			max_completion_tokens: openaiOptions.maxCompletionTokens,
			store: openaiOptions.store,
			metadata: openaiOptions.metadata,
			prediction: openaiOptions.prediction,
			reasoning_effort: resolvedReasoningEffort,
			service_tier: openaiOptions.serviceTier,
			prompt_cache_key: openaiOptions.promptCacheKey,
			prompt_cache_options: openaiOptions.promptCacheOptions,
			prompt_cache_retention: openaiOptions.promptCacheRetention,
			safety_identifier: openaiOptions.safetyIdentifier,
			messages
		};
		if (modelCapabilities.supportedReasoningEfforts != null && baseArgs.prompt_cache_retention != null) {
			baseArgs.prompt_cache_retention = void 0;
			warnings.push({
				type: "unsupported-setting",
				setting: "promptCacheRetention",
				details: "promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"
			});
		}
		if (modelCapabilities.isReasoningModel) {
			if (openaiOptions.reasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) {
				if (baseArgs.temperature != null) {
					baseArgs.temperature = void 0;
					warnings.push({
						type: "unsupported-setting",
						setting: "temperature",
						details: "temperature is not supported for reasoning models"
					});
				}
				if (baseArgs.top_p != null) {
					baseArgs.top_p = void 0;
					warnings.push({
						type: "unsupported-setting",
						setting: "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-setting",
					setting: "frequencyPenalty",
					details: "frequencyPenalty is not supported for reasoning models"
				});
			}
			if (baseArgs.presence_penalty != null) {
				baseArgs.presence_penalty = void 0;
				warnings.push({
					type: "unsupported-setting",
					setting: "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-setting",
					setting: "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-setting",
				setting: "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-setting",
				setting: "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: openaiTools, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({
			tools,
			toolChoice,
			structuredOutputs,
			strictJsonSchema
		});
		return {
			args: {
				...baseArgs,
				tools: openaiTools,
				tool_choice: openaiToolChoice
			},
			warnings: [...warnings, ...toolWarnings]
		};
	}
	async doGenerate(options) {
		var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
		const { args: body, warnings } = await this.getArgs(options);
		const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
			url: this.config.url({
				path: "/chat/completions",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createJsonResponseHandler(openaiChatResponseSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		const choice = response.choices[0];
		if (choice == null) throw new InvalidResponseDataError({
			data: rawResponse,
			message: "Response did not contain any choices."
		});
		const content = [];
		const text = choice.message.content != null && choice.message.content.length > 0 ? choice.message.content : (_a2 = choice.message.audio) == null ? void 0 : _a2.transcript;
		if (text != null && text.length > 0) content.push({
			type: "text",
			text
		});
		for (const toolCall of (_b = choice.message.tool_calls) != null ? _b : []) content.push({
			type: "tool-call",
			toolCallId: (_c = toolCall.id) != null ? _c : generateId(),
			toolName: toolCall.function.name,
			input: toolCall.function.arguments
		});
		for (const annotation of (_d = choice.message.annotations) != null ? _d : []) content.push({
			type: "source",
			sourceType: "url",
			id: generateId(),
			url: annotation.url_citation.url,
			title: annotation.url_citation.title
		});
		const completionTokenDetails = (_e = response.usage) == null ? void 0 : _e.completion_tokens_details;
		const promptTokenDetails = (_f = response.usage) == null ? void 0 : _f.prompt_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 ((promptTokenDetails == null ? void 0 : promptTokenDetails.cache_write_tokens) != null) providerMetadata.openai.usage = { cacheWriteTokens: promptTokenDetails.cache_write_tokens };
		if (((_g = choice.logprobs) == null ? void 0 : _g.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content;
		return {
			content,
			finishReason: mapOpenAIFinishReason(choice.finish_reason),
			usage: {
				inputTokens: (_i = (_h = response.usage) == null ? void 0 : _h.prompt_tokens) != null ? _i : void 0,
				outputTokens: (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens) != null ? _k : void 0,
				totalTokens: (_m = (_l = response.usage) == null ? void 0 : _l.total_tokens) != null ? _m : void 0,
				reasoningTokens: (_n = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null ? _n : void 0,
				cachedInputTokens: (_o = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null ? _o : void 0
			},
			request: { body },
			response: {
				...getResponseMetadata$1(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 postJsonToApi({
			url: this.config.url({
				path: "/chat/completions",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createEventSourceResponseHandler(openaiChatChunkSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		let toolCallTracker;
		let finishReason = "unknown";
		const usage = {
			inputTokens: void 0,
			outputTokens: void 0,
			totalTokens: void 0
		};
		let metadataExtracted = false;
		let isActiveText = false;
		const providerMetadata = { openai: {} };
		return {
			stream: response.pipeThrough(new TransformStream({
				start(controller) {
					toolCallTracker = new StreamingToolCallTracker(controller, {
						generateId,
						typeValidation: "if-present"
					});
					controller.enqueue({
						type: "stream-start",
						warnings
					});
				},
				transform(chunk, controller) {
					var _a2, _b, _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;
					if ("error" in value) {
						finishReason = "error";
						controller.enqueue({
							type: "error",
							error: value.error
						});
						return;
					}
					if (!metadataExtracted) {
						const metadata = getResponseMetadata$1(value);
						if (Object.values(metadata).some(Boolean)) {
							metadataExtracted = true;
							controller.enqueue({
								type: "response-metadata",
								...getResponseMetadata$1(value)
							});
						}
					}
					if (value.usage != null) {
						usage.inputTokens = (_a2 = value.usage.prompt_tokens) != null ? _a2 : void 0;
						usage.outputTokens = (_b = value.usage.completion_tokens) != null ? _b : void 0;
						usage.totalTokens = (_c = value.usage.total_tokens) != null ? _c : void 0;
						usage.reasoningTokens = (_e = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : void 0;
						usage.cachedInputTokens = (_g = (_f = value.usage.prompt_tokens_details) == null ? void 0 : _f.cached_tokens) != null ? _g : void 0;
						if (((_h = value.usage.prompt_tokens_details) == null ? void 0 : _h.cache_write_tokens) != null) providerMetadata.openai.usage = { cacheWriteTokens: value.usage.prompt_tokens_details.cache_write_tokens };
						if (((_i = value.usage.completion_tokens_details) == null ? void 0 : _i.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = (_j = value.usage.completion_tokens_details) == null ? void 0 : _j.accepted_prediction_tokens;
						if (((_k = value.usage.completion_tokens_details) == null ? void 0 : _k.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = (_l = value.usage.completion_tokens_details) == null ? void 0 : _l.rejected_prediction_tokens;
					}
					const choice = value.choices[0];
					if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = mapOpenAIFinishReason(choice.finish_reason);
					if (((_m = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _m.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) toolCallTracker.processDelta(toolCallDelta);
					if (delta.annotations != null) for (const annotation of delta.annotations) controller.enqueue({
						type: "source",
						sourceType: "url",
						id: generateId(),
						url: annotation.url_citation.url,
						title: annotation.url_citation.title
					});
				},
				flush(controller) {
					if (isActiveText) controller.enqueue({
						type: "text-end",
						id: "0"
					});
					toolCallTracker.flush();
					controller.enqueue({
						type: "finish",
						finishReason,
						usage,
						...providerMetadata != null ? { providerMetadata } : {}
					});
				}
			})),
			request: { body },
			response: { headers: responseHeaders }
		};
	}
};
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 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: throw new Error(`Unsupported role: ${role}`);
	}
	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 ? /* @__PURE__ */ 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 "unknown";
	}
}
var openaiCompletionResponseSchema = lazyValidator(() => zodSchema(z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	choices: z.array(z.object({
		text: z.string(),
		finish_reason: z.string(),
		logprobs: z.object({
			tokens: z.array(z.string()),
			token_logprobs: z.array(z.number()),
			top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
		}).nullish()
	})),
	usage: z.object({
		prompt_tokens: z.number(),
		completion_tokens: z.number(),
		total_tokens: z.number()
	}).nullish()
})));
var openaiCompletionChunkSchema = lazyValidator(() => zodSchema(z.union([z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	choices: z.array(z.object({
		text: z.string(),
		finish_reason: z.string().nullish(),
		index: z.number(),
		logprobs: z.object({
			tokens: z.array(z.string()),
			token_logprobs: z.array(z.number()),
			top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
		}).nullish()
	})),
	usage: z.object({
		prompt_tokens: z.number(),
		completion_tokens: z.number(),
		total_tokens: z.number()
	}).nullish()
}), openaiErrorDataSchema()])));
var openaiCompletionProviderOptions = lazyValidator(() => zodSchema(z.object({
	/**
	Echo back the prompt in addition to the completion.
	*/
	echo: 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: z.record(z.string(), z.number()).optional(),
	/**
	The suffix that comes after a completion of inserted text.
	*/
	suffix: z.string().optional(),
	/**
	A unique identifier representing your end-user, which can help OpenAI to
	monitor and detect abuse. Learn more.
	*/
	user: 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: z.union([z.boolean(), z.number()]).optional()
})));
var OpenAICompletionLanguageModel = class {
	constructor(modelId, config) {
		this.specificationVersion = "v2";
		this.supportedUrls = {};
		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 parseProviderOptions({
				provider: "openai",
				providerOptions,
				schema: openaiCompletionProviderOptions
			}),
			...await parseProviderOptions({
				provider: this.providerOptionsName,
				providerOptions,
				schema: openaiCompletionProviderOptions
			})
		};
		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 } = convertToOpenAICompletionPrompt({ prompt });
		const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
		return {
			args: {
				model: this.modelId,
				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,
				max_tokens: maxOutputTokens,
				temperature,
				top_p: topP,
				frequency_penalty: frequencyPenalty,
				presence_penalty: presencePenalty,
				seed,
				prompt: completionPrompt,
				stop: stop.length > 0 ? stop : void 0
			},
			warnings
		};
	}
	async doGenerate(options) {
		var _a2, _b, _c;
		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: openaiFailedResponseHandler,
			successfulResponseHandler: createJsonResponseHandler(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: {
				inputTokens: (_a2 = response.usage) == null ? void 0 : _a2.prompt_tokens,
				outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
				totalTokens: (_c = response.usage) == null ? void 0 : _c.total_tokens
			},
			finishReason: mapOpenAIFinishReason2(choice.finish_reason),
			request: { body: args },
			response: {
				...getResponseMetadata2(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 postJsonToApi({
			url: this.config.url({
				path: "/completions",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createEventSourceResponseHandler(openaiCompletionChunkSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		let finishReason = "unknown";
		const providerMetadata = { openai: {} };
		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) {
					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 = value.usage.prompt_tokens;
						usage.outputTokens = value.usage.completion_tokens;
						usage.totalTokens = value.usage.total_tokens;
					}
					const choice = value.choices[0];
					if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = mapOpenAIFinishReason2(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
					});
				}
			})),
			request: { body },
			response: { headers: responseHeaders }
		};
	}
};
var openaiEmbeddingProviderOptions = lazyValidator(() => zodSchema(z.object({
	/**
	The number of dimensions the resulting output embeddings should have.
	Only supported in text-embedding-3 and later models.
	*/
	dimensions: z.number().optional(),
	/**
	A unique identifier representing your end-user, which can help OpenAI to
	monitor and detect abuse. Learn more.
	*/
	user: z.string().optional()
})));
var openaiTextEmbeddingResponseSchema = lazyValidator(() => zodSchema(z.object({
	data: z.array(z.object({ embedding: z.array(z.number()) })),
	usage: z.object({ prompt_tokens: z.number() }).nullish()
})));
var _a = EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL;
var OpenAIEmbeddingModel = class {
	constructor(modelId, config) {
		this.specificationVersion = "v2";
		this.maxEmbeddingsPerCall = 2048;
		this[_a] = 3e5;
		this.supportsParallelCalls = true;
		this.modelId = modelId;
		this.config = config;
	}
	get provider() {
		return this.config.provider;
	}
	async doEmbed({ values, headers, abortSignal, providerOptions }) {
		var _a2;
		if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
			provider: this.provider,
			modelId: this.modelId,
			maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
			values
		});
		const openaiOptions = (_a2 = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openaiEmbeddingProviderOptions
		})) != null ? _a2 : {};
		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: openaiOptions.dimensions,
				user: openaiOptions.user
			},
			failedResponseHandler: openaiFailedResponseHandler,
			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,
			response: {
				headers: responseHeaders,
				body: rawValue
			}
		};
	}
};
var openaiImageResponseSchema = lazyValidator(() => zodSchema(z.object({
	created: z.number().nullish(),
	data: z.array(z.object({
		b64_json: z.string(),
		revised_prompt: z.string().nullish()
	})),
	background: z.string().nullish(),
	output_format: z.string().nullish(),
	size: z.string().nullish(),
	quality: z.string().nullish(),
	usage: z.object({
		input_tokens: z.number().nullish(),
		output_tokens: z.number().nullish(),
		total_tokens: z.number().nullish(),
		input_tokens_details: z.object({
			image_tokens: z.number().nullish(),
			text_tokens: 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
};
var defaultResponseFormatPrefixes = ["gpt-image-"];
function hasDefaultResponseFormat(modelId) {
	return defaultResponseFormatPrefixes.some((prefix) => modelId.startsWith(prefix));
}
function getMaxImagesPerCall(modelId) {
	var _a2;
	return (_a2 = modelMaxImagesPerCall[modelId]) != null ? _a2 : modelId.startsWith("gpt-image-") ? 10 : 1;
}
var baseImageModelOptionsObject = () => z.object({
	/**
	* Quality of the generated image(s).
	*
	* Valid values: `standard`, `hd`, `low`, `medium`, `high`, `auto`.
	*/
	quality: 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: z.enum([
		"transparent",
		"opaque",
		"auto"
	]).optional(),
	/**
	* Format in which the generated image(s) are returned.
	*/
	outputFormat: z.enum([
		"png",
		"jpeg",
		"webp"
	]).optional(),
	/**
	* Compression level (0-100) for the generated image(s). Applies to the
	* `jpeg` and `webp` output formats.
	*/
	outputCompression: 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: z.string().optional()
});
var openaiImageModelGenerationOptions = lazyValidator(() => zodSchema(baseImageModelOptionsObject().extend({
	/**
	* Style of the generated image. `vivid` produces hyper-real and
	* dramatic images; `natural` produces more subdued, less hyper-real
	* looking images.
	*/
	style: z.enum(["vivid", "natural"]).optional(),
	/**
	* Content moderation level for the generated image(s). `low` applies
	* less restrictive filtering.
	*/
	moderation: z.enum(["auto", "low"]).optional()
})));
var OpenAIImageModel = class {
	constructor(modelId, config) {
		this.modelId = modelId;
		this.config = config;
		this.specificationVersion = "v2";
	}
	get maxImagesPerCall() {
		return getMaxImagesPerCall(this.modelId);
	}
	get provider() {
		return this.config.provider;
	}
	async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {
		var _a2, _b, _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 = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
		const openaiOptions = (_d = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openaiImageModelGenerationOptions
		})) != null ? _d : {};
		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,
				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: createJsonResponseHandler(openaiImageResponseSchema),
			abortSignal,
			fetch: this.config.fetch
		});
		return {
			images: response.data.map((item) => item.b64_json),
			warnings,
			response: {
				timestamp: currentDate,
				modelId: this.modelId,
				headers: responseHeaders
			},
			providerMetadata: { openai: { images: response.data.map((item, index) => ({
				...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
				...response.created != null ? { created: response.created } : {},
				...response.size != null ? { size: response.size } : {},
				...response.quality != null ? { quality: response.quality } : {},
				...response.background != null ? { background: response.background } : {},
				...response.output_format != null ? { outputFormat: response.output_format } : {},
				...distributeTokenDetails(response.usage, index, response.data.length)
			})) } }
		};
	}
};
function distributeTokenDetails(usage, index, total) {
	if (usage == null) return {};
	const result = {};
	const details = usage.input_tokens_details;
	if ((details == null ? void 0 : 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 == null ? void 0 : 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;
	}
	if (usage.input_tokens != null) {
		const base = Math.floor(usage.input_tokens / total);
		const remainder = usage.input_tokens - base * (total - 1);
		result.inputTokens = index === total - 1 ? remainder : base;
	}
	if (usage.output_tokens != null) {
		const base = Math.floor(usage.output_tokens / total);
		const remainder = usage.output_tokens - base * (total - 1);
		result.outputTokens = index === total - 1 ? remainder : base;
	}
	return result;
}
var openaiTranscriptionResponseSchema = lazyValidator(() => zodSchema(z.object({
	text: z.string(),
	language: z.string().nullish(),
	duration: z.number().nullish(),
	words: z.array(z.object({
		word: z.string(),
		start: z.number(),
		end: z.number()
	})).nullish(),
	segments: z.array(z.object({
		id: z.number(),
		seek: z.number(),
		start: z.number(),
		end: z.number(),
		text: z.string(),
		tokens: z.array(z.number()),
		temperature: z.number(),
		avg_logprob: z.number(),
		compression_ratio: z.number(),
		no_speech_prob: z.number()
	})).nullish(),
	usage: z.object({
		type: z.string().nullish(),
		seconds: z.number().nullish()
	}).nullish().catch(void 0)
})));
var openAITranscriptionProviderOptions = lazyValidator(() => zodSchema(z.object({
	/**
	* Additional information to include in the transcription response.
	*/
	include: z.array(z.string()).optional(),
	/**
	* The language of the input audio in ISO-639-1 format.
	*/
	language: z.string().optional(),
	/**
	* Expected languages for REST transcription, e.g. with gpt-transcribe.
	* Use this instead of language. The API validates model support.
	*/
	languages: z.array(z.string()).optional(),
	/**
	* Vocabulary hints for REST transcription, e.g. names or technical terms.
	* The API validates model support.
	*/
	keywords: z.array(z.string()).optional(),
	/**
	* An optional text to guide the model's style or continue a previous audio segment.
	*/
	prompt: z.string().optional(),
	/**
	* The sampling temperature, between 0 and 1.
	* @default 0
	*/
	temperature: z.number().min(0).max(1).default(0).optional(),
	/**
	* The timestamp granularities to populate for this transcription.
	* @default ['segment']
	*/
	timestampGranularities: z.array(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 = "v2";
	}
	get provider() {
		return this.config.provider;
	}
	async getArgs({ audio, mediaType, providerOptions }) {
		const warnings = [];
		const openAIOptions = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openAITranscriptionProviderOptions
		});
		const formData = new FormData();
		const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
		formData.append("model", this.modelId);
		const fileExtension = mediaTypeToExtension(mediaType);
		formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
		if (openAIOptions) {
			const transcriptionModelOptions = {
				include: openAIOptions.include,
				language: openAIOptions.language,
				languages: openAIOptions.languages,
				keywords: openAIOptions.keywords,
				prompt: openAIOptions.prompt,
				response_format: ["gpt-4o-transcribe", "gpt-4o-mini-transcribe"].includes(this.modelId) || this.modelId.startsWith("gpt-4o-mini-transcribe-") || this.modelId === "gpt-transcribe" || this.modelId.startsWith("gpt-transcribe-") ? "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 _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
		const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
		const { formData, warnings } = await this.getArgs(options);
		const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({
			url: this.config.url({
				path: "/audio/transcriptions",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			formData,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createJsonResponseHandler(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: (_j = response.duration) != null ? _j : ((_h = response.usage) == null ? void 0 : _h.type) === "duration" ? (_i = response.usage.seconds) != null ? _i : void 0 : void 0,
			warnings,
			response: {
				timestamp: currentDate,
				modelId: this.modelId,
				headers: responseHeaders,
				body: rawResponse
			}
		};
	}
};
var openaiSpeechProviderOptionsSchema = lazyValidator(() => zodSchema(z.object({
	instructions: z.string().nullish(),
	speed: z.number().min(.25).max(4).default(1).nullish()
})));
var OpenAISpeechModel = class {
	constructor(modelId, config) {
		this.modelId = modelId;
		this.config = config;
		this.specificationVersion = "v2";
	}
	get provider() {
		return this.config.provider;
	}
	async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) {
		const warnings = [];
		const openAIOptions = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openaiSpeechProviderOptionsSchema
		});
		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-setting",
				setting: "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-setting",
			setting: "language",
			details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.`
		});
		return {
			requestBody,
			warnings
		};
	}
	async doGenerate(options) {
		var _a2, _b, _c;
		const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
		const { requestBody, warnings } = await this.getArgs(options);
		const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi({
			url: this.config.url({
				path: "/audio/speech",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body: requestBody,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createBinaryResponseHandler(),
			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 TOP_LOGPROBS_MAX = 20;
var openaiResponsesProviderOptionsSchema = lazyValidator(() => zodSchema(z.object({
	conversation: z.string().nullish(),
	include: z.array(z.enum([
		"reasoning.encrypted_content",
		"file_search_call.results",
		"message.output_text.logprobs"
	])).nullish(),
	instructions: z.string().nullish(),
	/**
	* 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.
	*
	* @see https://platform.openai.com/docs/api-reference/responses/create
	* @see https://cookbook.openai.com/examples/using_logprobs
	*/
	logprobs: z.union([z.boolean(), 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: z.number().nullish(),
	metadata: z.any().nullish(),
	parallelToolCalls: z.boolean().nullish(),
	previousResponseId: z.string().nullish(),
	promptCacheKey: z.string().nullish(),
	/**
	* Prompt cache behavior for GPT-5.6 and later models.
	* `mode` controls whether OpenAI also places an implicit breakpoint.
	* `ttl` sets the minimum cache lifetime and currently only supports 30 minutes.
	*/
	promptCacheOptions: z.object({
		mode: z.enum(["implicit", "explicit"]).optional(),
		ttl: z.literal("30m").optional()
	}).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.
	*          Available for models before GPT-5.6 that support extended caching.
	*
	* @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`.
	*
	* @default 'in_memory'
	*/
	promptCacheRetention: 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.
	* GPT-5.6 supports 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'.
	* Supported values vary by model.
	*/
	reasoningEffort: z.string().nullish(),
	/**
	* Updates the reasoning effort for GPT-6 and later models starting with this response
	* without changing the request-level reasoning effort. This preserves the
	* request prefix for prompt caching.
	*
	* Only supported by GPT-6 and later models in standard, single-agent mode. Cannot be
	* combined with automatic truncation.
	*/
	reasoningEffortUpdate: z.enum([
		"low",
		"medium",
		"high",
		"xhigh",
		"max"
	]).optional(),
	/**
	* Controls how much model work GPT-5.6 performs before returning a final answer.
	* `standard` is the default. `pro` increases quality, latency, and token usage.
	*/
	reasoningMode: z.enum(["standard", "pro"]).optional(),
	/**
	* Controls which available reasoning items GPT-5.6 can use.
	* `auto` uses the model default, `current_turn` excludes reasoning from earlier
	* turns, and `all_turns` makes compatible earlier reasoning available.
	*/
	reasoningContext: z.enum([
		"auto",
		"current_turn",
		"all_turns"
	]).optional(),
	reasoningSummary: z.string().nullish(),
	safetyIdentifier: z.string().nullish(),
	serviceTier: z.enum([
		"auto",
		"flex",
		"priority",
		"default"
	]).nullish(),
	store: z.boolean().nullish(),
	strictJsonSchema: z.boolean().nullish(),
	textVerbosity: z.enum([
		"low",
		"medium",
		"high"
	]).nullish(),
	truncation: z.enum(["auto", "disabled"]).nullish(),
	user: z.string().nullish()
})));
var openaiResponsesSystemMessageOptionsSchema = lazyValidator(() => zodSchema(z.object({ 
/**
* Emit a configuration update at this position in Responses history.
* Requires empty system message content and the same supported
* configuration as the request-level reasoningEffortUpdate option.
* Unsupported historical updates throw instead of being omitted.
*
* @see https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation
*/
reasoningEffortUpdate: z.enum([
	"low",
	"medium",
	"high",
	"xhigh",
	"max"
]).optional() })));
var localShellInputSchema = lazySchema(() => zodSchema(z.object({ action: z.object({
	type: z.literal("exec"),
	command: z.array(z.string()),
	timeoutMs: z.number().optional(),
	user: z.string().optional(),
	workingDirectory: z.string().optional(),
	env: z.record(z.string(), z.string()).optional()
}) })));
var localShellOutputSchema = lazySchema(() => zodSchema(z.object({ output: z.string() })));
createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.local_shell",
	name: "local_shell",
	inputSchema: localShellInputSchema,
	outputSchema: localShellOutputSchema
});
var webSearchArgsSchema = lazySchema(() => zodSchema(z.object({
	externalWebAccess: z.boolean().optional(),
	filters: z.object({
		allowedDomains: z.array(z.string()).optional(),
		blockedDomains: z.array(z.string()).optional()
	}).optional(),
	searchContextSize: z.enum([
		"low",
		"medium",
		"high"
	]).optional(),
	userLocation: z.object({
		type: z.literal("approximate"),
		country: z.string().optional(),
		city: z.string().optional(),
		region: z.string().optional(),
		timezone: z.string().optional()
	}).optional()
})));
var webSearchInputSchema = lazySchema(() => zodSchema(z.object({})));
var webSearchOutputSchema = lazySchema(() => zodSchema(z.object({
	action: z.discriminatedUnion("type", [
		z.object({
			type: z.literal("search"),
			query: z.string().optional()
		}),
		z.object({
			type: z.literal("openPage"),
			url: z.string().nullish()
		}),
		z.object({
			type: z.literal("findInPage"),
			url: z.string().nullish(),
			pattern: z.string().nullish()
		})
	]).optional(),
	sources: z.array(z.discriminatedUnion("type", [z.object({
		type: z.literal("url"),
		url: z.string()
	}), z.object({
		type: z.literal("api"),
		name: z.string()
	})])).optional()
})));
var webSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.web_search",
	name: "web_search",
	inputSchema: webSearchInputSchema,
	outputSchema: webSearchOutputSchema
});
var webSearch = (args = {}) => webSearchToolFactory(args);
async function convertWebSearchToolResultOutput({ output, id }) {
	if (output.type !== "json") return;
	const validation = await safeValidateTypes({
		value: output.value,
		schema: webSearchOutputSchema
	});
	if (!validation.success || validation.value.action == null) return;
	const { action, sources } = validation.value;
	switch (action.type) {
		case "search": return {
			type: "web_search_call",
			id,
			status: "completed",
			action: {
				type: "search",
				...action.query != null && { query: action.query },
				...sources != null && { sources }
			}
		};
		case "openPage": return {
			type: "web_search_call",
			id,
			status: "completed",
			action: {
				type: "open_page",
				url: action.url
			}
		};
		case "findInPage": return {
			type: "web_search_call",
			id,
			status: "completed",
			action: {
				type: "find_in_page",
				url: action.url,
				pattern: action.pattern
			}
		};
	}
}
function getPromptCacheBreakpoint2(providerOptions) {
	var _a2;
	return (_a2 = providerOptions == null ? void 0 : providerOptions.openai) == null ? void 0 : _a2.promptCacheBreakpoint;
}
function isFileId(data, prefixes) {
	if (!prefixes) return false;
	return prefixes.some((prefix) => data.startsWith(prefix));
}
async function convertToOpenAIResponsesInput({ prompt, systemMessageMode, providerOptionsName = "openai", explicitMessageItemType = false, fileIdPrefixes, store, isReasoningModel = false, configurationUpdateUnsupportedReason, hasLocalShellTool = false, webSearchToolName }) {
	var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
	let input = [];
	const warnings = [];
	for (const { role, content, providerOptions } of prompt) switch (role) {
		case "system": {
			let options = await parseProviderOptions({
				provider: providerOptionsName,
				providerOptions,
				schema: openaiResponsesSystemMessageOptionsSchema
			});
			if (options == null && providerOptionsName !== "openai") options = await parseProviderOptions({
				provider: "openai",
				providerOptions,
				schema: openaiResponsesSystemMessageOptionsSchema
			});
			const effort = options == null ? void 0 : options.reasoningEffortUpdate;
			if (effort != null) {
				const unsupportedReason = content !== "" ? "Message-level reasoningEffortUpdate requires empty system message content." : configurationUpdateUnsupportedReason;
				if (unsupportedReason != null) throw new UnsupportedFunctionalityError({
					functionality: "Message-level reasoningEffortUpdate",
					message: unsupportedReason
				});
				input.push({
					type: "configuration_update",
					reasoning: { effort }
				});
				break;
			}
			switch (systemMessageMode) {
				case "system": {
					const promptCacheBreakpoint = getPromptCacheBreakpoint2(providerOptions);
					input.push({
						...explicitMessageItemType && { type: "message" },
						role: "system",
						content: promptCacheBreakpoint == null ? content : [{
							type: "input_text",
							text: content,
							prompt_cache_breakpoint: promptCacheBreakpoint
						}]
					});
					break;
				}
				case "developer": {
					const promptCacheBreakpoint = getPromptCacheBreakpoint2(providerOptions);
					input.push({
						...explicitMessageItemType && { type: "message" },
						role: "developer",
						content: promptCacheBreakpoint == null ? content : [{
							type: "input_text",
							text: content,
							prompt_cache_breakpoint: promptCacheBreakpoint
						}]
					});
					break;
				}
				case "remove":
					warnings.push({
						type: "other",
						message: "system messages are removed for this model"
					});
					break;
				default: throw new Error(`Unsupported system message mode: ${systemMessageMode}`);
			}
			break;
		}
		case "user":
			input.push({
				...explicitMessageItemType && { type: "message" },
				role: "user",
				content: content.map((part, index) => {
					var _a3, _b2, _c2;
					switch (part.type) {
						case "text": {
							const promptCacheBreakpoint = getPromptCacheBreakpoint2(part.providerOptions);
							return {
								type: "input_text",
								text: part.text,
								...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
							};
						}
						case "file": {
							const promptCacheBreakpoint = getPromptCacheBreakpoint2(part.providerOptions);
							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,${convertToBase64(part.data)}` },
									detail: (_b2 = (_a3 = part.providerOptions) == null ? void 0 : _a3.openai) == null ? void 0 : _b2.imageDetail,
									...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
								};
							} else if (part.mediaType === "application/pdf") {
								if (part.data instanceof URL) return {
									type: "input_file",
									file_url: part.data.toString(),
									...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
								};
								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,${convertToBase64(part.data)}`
									},
									...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
								};
							} else throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` });
						}
					}
				})
			});
			break;
		case "assistant": {
			const reasoningMessages = {};
			const toolCallParts = {};
			let hasPrecedingReasoning = false;
			for (const part of content) switch (part.type) {
				case "text": {
					const id = (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b.itemId;
					const phase = (_d = (_c = part.providerOptions) == null ? void 0 : _c.openai) == null ? void 0 : _d.phase;
					const canUseItemId = id != null && (!isReasoningModel || hasPrecedingReasoning);
					if (store && canUseItemId) {
						input.push({
							type: "item_reference",
							id
						});
						break;
					}
					input.push({
						...explicitMessageItemType && { type: "message" },
						role: "assistant",
						content: [{
							type: "output_text",
							text: part.text
						}],
						id: canUseItemId ? id : void 0,
						...phase != null && { phase }
					});
					break;
				}
				case "tool-call": {
					toolCallParts[part.toolCallId] = part;
					if (part.providerExecuted) break;
					const id = (_f = (_e = part.providerOptions) == null ? void 0 : _e.openai) == null ? void 0 : _f.itemId;
					const isAsync = (_h = (_g = part.providerOptions) == null ? void 0 : _g.openai) == null ? void 0 : _h.async;
					const canUseItemId = id != null && (!isReasoningModel || hasPrecedingReasoning);
					if (store && canUseItemId) {
						input.push({
							type: "item_reference",
							id
						});
						break;
					}
					if (hasLocalShellTool && part.toolName === "local_shell") {
						const parsedInput = await validateTypes({
							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;
					}
					input.push({
						type: "function_call",
						call_id: part.toolCallId,
						name: part.toolName,
						arguments: serializeToolCallArguments2(part.input),
						...isAsync != null && { async: isAsync },
						id: canUseItemId ? id : void 0
					});
					break;
				}
				case "tool-result":
					if (part.toolName === "web_search" || part.toolName === "web_search_preview" || part.toolName === webSearchToolName) {
						const itemId = (_k = (_j = (_i = part.providerOptions) == null ? void 0 : _i[providerOptionsName]) == null ? void 0 : _j.itemId) != null ? _k : part.toolCallId;
						if (store) {
							input.push({
								type: "item_reference",
								id: itemId
							});
							break;
						}
						const webSearchCall = await convertWebSearchToolResultOutput({
							output: part.output,
							id: itemId
						});
						if (webSearchCall != null) {
							input.push(webSearchCall);
							break;
						}
					}
					if (store) input.push({
						type: "item_reference",
						id: part.toolCallId
					});
					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": {
					hasPrecedingReasoning = true;
					const providerOptions2 = await parseProviderOptions({
						provider: "openai",
						providerOptions: part.providerOptions,
						schema: openaiResponsesReasoningProviderOptionsSchema
					});
					const reasoningId = providerOptions2 == null ? void 0 : providerOptions2.itemId;
					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: ${stringifyWithBigIntAndCycles(part)}.`
							});
							if (reasoningMessage === void 0) {
								reasoningMessages[reasoningId] = {
									type: "reasoning",
									id: reasoningId,
									encrypted_content: providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent,
									summary: summaryParts
								};
								input.push(reasoningMessages[reasoningId]);
							} else {
								reasoningMessage.summary.push(...summaryParts);
								if ((providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent) != null) reasoningMessage.encrypted_content = providerOptions2.reasoningEncryptedContent;
							}
						}
					} else warnings.push({
						type: "other",
						message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${stringifyWithBigIntAndCycles(part)}.`
					});
					break;
				}
			}
			break;
		}
		case "tool":
			for (const part of content) {
				const output = part.output;
				const promptCacheBreakpoint = getPromptCacheBreakpoint2(part.providerOptions);
				if (hasLocalShellTool && part.toolName === "local_shell" && output.type === "json") {
					const parsedOutput = await validateTypes({
						value: output.value,
						schema: localShellOutputSchema
					});
					input.push({
						type: "local_shell_call_output",
						call_id: part.toolCallId,
						output: parsedOutput.output
					});
					break;
				}
				let contentValue;
				switch (output.type) {
					case "text":
					case "error-text":
						contentValue = promptCacheBreakpoint == null ? output.value : [{
							type: "input_text",
							text: output.value,
							prompt_cache_breakpoint: promptCacheBreakpoint
						}];
						break;
					case "json":
					case "error-json":
						contentValue = promptCacheBreakpoint == null ? stringifyWithBigIntAndCycles(output.value) : [{
							type: "input_text",
							text: stringifyWithBigIntAndCycles(output.value),
							prompt_cache_breakpoint: promptCacheBreakpoint
						}];
						break;
					case "content": contentValue = output.value.map((item, index) => {
						const isBreakpoint = promptCacheBreakpoint != null && index === output.value.length - 1;
						switch (item.type) {
							case "text": return {
								type: "input_text",
								text: item.text,
								...isBreakpoint && { prompt_cache_breakpoint: promptCacheBreakpoint }
							};
							case "media": return item.mediaType.startsWith("image/") ? {
								type: "input_image",
								image_url: `data:${item.mediaType};base64,${item.data}`,
								...isBreakpoint && { prompt_cache_breakpoint: promptCacheBreakpoint }
							} : {
								type: "input_file",
								filename: "data",
								file_data: `data:${item.mediaType};base64,${item.data}`,
								...isBreakpoint && { prompt_cache_breakpoint: promptCacheBreakpoint }
							};
						}
					});
				}
				input.push({
					type: "function_call_output",
					call_id: part.toolCallId,
					output: contentValue
				});
			}
			break;
		default: throw new Error(`Unsupported role: ${role}`);
	}
	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 = lazySchema(() => zodSchema(z.object({
	itemId: z.string().nullish(),
	reasoningEncryptedContent: z.string().nullish()
})));
function serializeToolCallArguments2(input) {
	if (typeof input === "string") try {
		secureJsonParse(input);
		return input;
	} catch (e) {
		return stringifyWithBigIntAndCycles(input);
	}
	return stringifyWithBigIntAndCycles(input === void 0 ? {} : input);
}
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" : "unknown";
	}
}
var openaiResponsesChunkSchema = lazyValidator(() => zodSchema(z.union([
	z.object({
		type: z.literal("response.output_text.delta"),
		item_id: z.string(),
		delta: z.string(),
		logprobs: z.array(z.object({
			token: z.string(),
			logprob: z.number(),
			top_logprobs: z.array(z.object({
				token: z.string(),
				logprob: z.number()
			}))
		})).nullish()
	}),
	z.object({
		type: z.enum(["response.completed", "response.incomplete"]),
		response: z.object({
			incomplete_details: z.object({ reason: z.string() }).nullish(),
			usage: z.object({
				input_tokens: z.number(),
				input_tokens_details: z.object({
					cached_tokens: z.number().nullish(),
					cache_write_tokens: z.number().nullish(),
					orchestration_input_tokens: z.number().nullish(),
					orchestration_input_cached_tokens: z.number().nullish()
				}).nullish(),
				output_tokens: z.number(),
				output_tokens_details: z.object({
					reasoning_tokens: z.number().nullish(),
					orchestration_output_tokens: z.number().nullish()
				}).nullish()
			}),
			reasoning: z.object({ context: z.string().nullish() }).nullish(),
			service_tier: z.string().nullish()
		})
	}),
	z.object({
		type: z.literal("response.created"),
		response: z.object({
			id: z.string(),
			created_at: z.number(),
			model: z.string(),
			service_tier: z.string().nullish()
		})
	}),
	z.object({
		type: z.literal("response.output_item.added"),
		output_index: z.number(),
		item: z.discriminatedUnion("type", [
			z.object({
				type: z.literal("message"),
				id: z.string(),
				phase: z.enum(["commentary", "final_answer"]).nullish()
			}),
			z.object({
				type: z.literal("reasoning"),
				id: z.string(),
				encrypted_content: z.string().nullish()
			}),
			z.object({
				type: z.literal("function_call"),
				id: z.string(),
				call_id: z.string(),
				name: z.string(),
				arguments: z.string(),
				async: z.boolean().nullish()
			}),
			z.object({
				type: z.literal("web_search_call"),
				id: z.string(),
				status: z.string()
			}),
			z.object({
				type: z.literal("computer_call"),
				id: z.string(),
				status: z.string()
			}),
			z.object({
				type: z.literal("file_search_call"),
				id: z.string()
			}),
			z.object({
				type: z.literal("image_generation_call"),
				id: z.string()
			}),
			z.object({
				type: z.literal("code_interpreter_call"),
				id: z.string(),
				container_id: z.string(),
				code: z.string().nullable(),
				outputs: z.array(z.discriminatedUnion("type", [z.object({
					type: z.literal("logs"),
					logs: z.string()
				}), z.object({
					type: z.literal("image"),
					url: z.string()
				})])).nullable(),
				status: z.string()
			})
		])
	}),
	z.object({
		type: z.literal("response.output_item.done"),
		output_index: z.number(),
		item: z.discriminatedUnion("type", [
			z.object({
				type: z.literal("message"),
				id: z.string(),
				phase: z.enum(["commentary", "final_answer"]).nullish()
			}),
			z.object({
				type: z.literal("reasoning"),
				id: z.string(),
				encrypted_content: z.string().nullish()
			}),
			z.object({
				type: z.literal("function_call"),
				id: z.string(),
				call_id: z.string(),
				name: z.string(),
				arguments: z.string(),
				async: z.boolean().nullish(),
				status: z.enum([
					"in_progress",
					"completed",
					"incomplete"
				])
			}),
			z.object({
				type: z.literal("code_interpreter_call"),
				id: z.string(),
				code: z.string().nullable(),
				container_id: z.string(),
				outputs: z.array(z.discriminatedUnion("type", [z.object({
					type: z.literal("logs"),
					logs: z.string()
				}), z.object({
					type: z.literal("image"),
					url: z.string()
				})])).nullable()
			}),
			z.object({
				type: z.literal("image_generation_call"),
				id: z.string(),
				result: z.string()
			}),
			z.object({
				type: z.literal("web_search_call"),
				id: z.string(),
				status: z.string(),
				action: z.discriminatedUnion("type", [
					z.object({
						type: z.literal("search"),
						query: z.string().nullish(),
						sources: z.array(z.discriminatedUnion("type", [z.object({
							type: z.literal("url"),
							url: z.string()
						}), z.object({
							type: z.literal("api"),
							name: z.string()
						})])).nullish()
					}),
					z.object({
						type: z.literal("open_page"),
						url: z.string().nullish()
					}),
					z.object({
						type: z.literal("find_in_page"),
						url: z.string().nullish(),
						pattern: z.string().nullish()
					})
				]).nullish()
			}),
			z.object({
				type: z.literal("file_search_call"),
				id: z.string(),
				queries: z.array(z.string()),
				results: z.array(z.object({
					attributes: z.record(z.string(), z.unknown()),
					file_id: z.string(),
					filename: z.string(),
					score: z.number(),
					text: z.string()
				})).nullish()
			}),
			z.object({
				type: z.literal("local_shell_call"),
				id: z.string(),
				call_id: z.string(),
				action: z.object({
					type: z.literal("exec"),
					command: z.array(z.string()),
					timeout_ms: z.number().optional(),
					user: z.string().optional(),
					working_directory: z.string().optional(),
					env: z.record(z.string(), z.string()).optional()
				})
			}),
			z.object({
				type: z.literal("computer_call"),
				id: z.string(),
				status: z.literal("completed")
			})
		])
	}),
	z.object({
		type: z.literal("response.function_call_arguments.delta"),
		item_id: z.string(),
		output_index: z.number(),
		delta: z.string()
	}),
	z.object({
		type: z.literal("response.image_generation_call.partial_image"),
		item_id: z.string(),
		output_index: z.number(),
		partial_image_b64: z.string()
	}),
	z.object({
		type: z.literal("response.code_interpreter_call_code.delta"),
		item_id: z.string(),
		output_index: z.number(),
		delta: z.string()
	}),
	z.object({
		type: z.literal("response.code_interpreter_call_code.done"),
		item_id: z.string(),
		output_index: z.number(),
		code: z.string()
	}),
	z.object({
		type: z.literal("response.output_text.annotation.added"),
		annotation: z.discriminatedUnion("type", [z.object({
			type: z.literal("url_citation"),
			start_index: z.number(),
			end_index: z.number(),
			url: z.string(),
			title: z.string()
		}), z.object({
			type: z.literal("file_citation"),
			file_id: z.string(),
			filename: z.string().nullish(),
			index: z.number().nullish(),
			start_index: z.number().nullish(),
			end_index: z.number().nullish(),
			quote: z.string().nullish()
		})])
	}),
	z.object({
		type: z.literal("response.reasoning_summary_part.added"),
		item_id: z.string(),
		summary_index: z.number()
	}),
	z.object({
		type: z.literal("response.reasoning_summary_text.delta"),
		item_id: z.string(),
		summary_index: z.number(),
		delta: z.string()
	}),
	z.object({
		type: z.literal("response.reasoning_summary_part.done"),
		item_id: z.string(),
		summary_index: z.number()
	}),
	z.object({
		type: z.literal("error"),
		sequence_number: z.number(),
		error: z.object({
			type: z.string(),
			code: z.string(),
			message: z.string(),
			param: z.string().nullish()
		})
	}),
	z.object({ type: z.string() }).loose().transform((value) => ({
		type: "unknown_chunk",
		message: value.type
	}))
])));
var openaiResponsesResponseSchema = lazyValidator(() => zodSchema(z.object({
	id: z.string().optional(),
	created_at: z.number().optional(),
	error: z.object({
		message: z.string(),
		type: z.string(),
		param: z.string().nullish(),
		code: z.string()
	}).nullish(),
	model: z.string().optional(),
	output: z.array(z.discriminatedUnion("type", [
		z.object({
			type: z.literal("message"),
			role: z.literal("assistant"),
			id: z.string(),
			phase: z.enum(["commentary", "final_answer"]).nullish(),
			content: z.array(z.object({
				type: z.literal("output_text"),
				text: z.string(),
				logprobs: z.array(z.object({
					token: z.string(),
					logprob: z.number(),
					top_logprobs: z.array(z.object({
						token: z.string(),
						logprob: z.number()
					}))
				})).nullish(),
				annotations: z.array(z.discriminatedUnion("type", [
					z.object({
						type: z.literal("url_citation"),
						start_index: z.number(),
						end_index: z.number(),
						url: z.string(),
						title: z.string()
					}),
					z.object({
						type: z.literal("file_citation"),
						file_id: z.string(),
						filename: z.string().nullish(),
						index: z.number().nullish(),
						start_index: z.number().nullish(),
						end_index: z.number().nullish(),
						quote: z.string().nullish()
					}),
					z.object({
						type: z.literal("container_file_citation"),
						container_id: z.string(),
						file_id: z.string(),
						filename: z.string().nullish(),
						start_index: z.number().nullish(),
						end_index: z.number().nullish(),
						index: z.number().nullish()
					}),
					z.object({
						type: z.literal("file_path"),
						file_id: z.string(),
						index: z.number().nullish()
					})
				]))
			}))
		}),
		z.object({
			type: z.literal("web_search_call"),
			id: z.string(),
			status: z.string(),
			action: z.discriminatedUnion("type", [
				z.object({
					type: z.literal("search"),
					query: z.string().nullish(),
					sources: z.array(z.discriminatedUnion("type", [z.object({
						type: z.literal("url"),
						url: z.string()
					}), z.object({
						type: z.literal("api"),
						name: z.string()
					})])).nullish()
				}),
				z.object({
					type: z.literal("open_page"),
					url: z.string().nullish()
				}),
				z.object({
					type: z.literal("find_in_page"),
					url: z.string().nullish(),
					pattern: z.string().nullish()
				})
			]).nullish()
		}),
		z.object({
			type: z.literal("file_search_call"),
			id: z.string(),
			queries: z.array(z.string()),
			results: z.array(z.object({
				attributes: z.record(z.string(), z.union([
					z.string(),
					z.number(),
					z.boolean()
				])),
				file_id: z.string(),
				filename: z.string(),
				score: z.number(),
				text: z.string()
			})).nullish()
		}),
		z.object({
			type: z.literal("code_interpreter_call"),
			id: z.string(),
			code: z.string().nullable(),
			container_id: z.string(),
			outputs: z.array(z.discriminatedUnion("type", [z.object({
				type: z.literal("logs"),
				logs: z.string()
			}), z.object({
				type: z.literal("image"),
				url: z.string()
			})])).nullable()
		}),
		z.object({
			type: z.literal("image_generation_call"),
			id: z.string(),
			result: z.string()
		}),
		z.object({
			type: z.literal("local_shell_call"),
			id: z.string(),
			call_id: z.string(),
			action: z.object({
				type: z.literal("exec"),
				command: z.array(z.string()),
				timeout_ms: z.number().optional(),
				user: z.string().optional(),
				working_directory: z.string().optional(),
				env: z.record(z.string(), z.string()).optional()
			})
		}),
		z.object({
			type: z.literal("function_call"),
			call_id: z.string(),
			name: z.string(),
			arguments: z.string(),
			id: z.string(),
			async: z.boolean().nullish()
		}),
		z.object({
			type: z.literal("computer_call"),
			id: z.string(),
			status: z.string().optional()
		}),
		z.object({
			type: z.literal("reasoning"),
			id: z.string(),
			encrypted_content: z.string().nullish(),
			summary: z.array(z.object({
				type: z.literal("summary_text"),
				text: z.string()
			}))
		})
	])).optional(),
	service_tier: z.string().nullish(),
	reasoning: z.object({ context: z.string().nullish() }).nullish(),
	incomplete_details: z.object({ reason: z.string() }).nullish(),
	usage: z.object({
		input_tokens: z.number(),
		input_tokens_details: z.object({
			cached_tokens: z.number().nullish(),
			cache_write_tokens: z.number().nullish(),
			orchestration_input_tokens: z.number().nullish(),
			orchestration_input_cached_tokens: z.number().nullish()
		}).nullish(),
		output_tokens: z.number(),
		output_tokens_details: z.object({
			reasoning_tokens: z.number().nullish(),
			orchestration_output_tokens: z.number().nullish()
		}).nullish()
	}).optional()
})));
var codeInterpreterInputSchema = lazySchema(() => zodSchema(z.object({
	code: z.string().nullish(),
	containerId: z.string()
})));
var codeInterpreterOutputSchema = lazySchema(() => zodSchema(z.object({ outputs: z.array(z.discriminatedUnion("type", [z.object({
	type: z.literal("logs"),
	logs: z.string()
}), z.object({
	type: z.literal("image"),
	url: z.string()
})])).nullish() })));
var codeInterpreterArgsSchema = lazySchema(() => zodSchema(z.object({ container: z.union([z.string(), z.object({ fileIds: z.array(z.string()).optional() })]).optional() })));
var codeInterpreterToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.code_interpreter",
	name: "code_interpreter",
	inputSchema: codeInterpreterInputSchema,
	outputSchema: codeInterpreterOutputSchema
});
var codeInterpreter = (args = {}) => {
	return codeInterpreterToolFactory(args);
};
var comparisonFilterSchema = () => z.object({
	key: z.string(),
	type: z.enum([
		"eq",
		"ne",
		"gt",
		"gte",
		"lt",
		"lte",
		"in",
		"nin"
	]),
	value: z.union([
		z.string(),
		z.number(),
		z.boolean(),
		z.array(z.string())
	])
});
var cachedCompoundFilterSchema;
var compoundFilterSchema = () => cachedCompoundFilterSchema != null ? cachedCompoundFilterSchema : cachedCompoundFilterSchema = z.object({
	type: z.enum(["and", "or"]),
	filters: z.array(z.union([comparisonFilterSchema(), z.lazy(() => compoundFilterSchema())]))
});
var fileSearchArgsSchema = lazySchema(() => zodSchema(z.object({
	vectorStoreIds: z.array(z.string()),
	maxNumResults: z.number().optional(),
	ranking: z.object({
		ranker: z.string().optional(),
		scoreThreshold: z.number().optional()
	}).optional(),
	filters: z.union([comparisonFilterSchema(), compoundFilterSchema()]).optional()
})));
var fileSearchOutputSchema = lazySchema(() => zodSchema(z.object({
	queries: z.array(z.string()),
	results: z.array(z.object({
		attributes: z.record(z.string(), z.unknown()),
		fileId: z.string(),
		filename: z.string(),
		score: z.number(),
		text: z.string()
	})).nullable()
})));
var fileSearch = createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.file_search",
	name: "file_search",
	inputSchema: z.object({}),
	outputSchema: fileSearchOutputSchema
});
var webSearchPreviewArgsSchema = lazySchema(() => zodSchema(z.object({
	searchContextSize: z.enum([
		"low",
		"medium",
		"high"
	]).optional(),
	userLocation: z.object({
		type: z.literal("approximate"),
		country: z.string().optional(),
		city: z.string().optional(),
		region: z.string().optional(),
		timezone: z.string().optional()
	}).optional()
})));
var webSearchPreview = createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.web_search_preview",
	name: "web_search_preview",
	inputSchema: lazySchema(() => zodSchema(z.object({}))),
	outputSchema: lazySchema(() => zodSchema(z.object({ action: z.discriminatedUnion("type", [
		z.object({
			type: z.literal("search"),
			query: z.string().optional()
		}),
		z.object({
			type: z.literal("openPage"),
			url: z.string().nullish()
		}),
		z.object({
			type: z.literal("findInPage"),
			url: z.string().nullish(),
			pattern: z.string().nullish()
		})
	]).optional() })))
});
var imageGenerationArgsSchema = lazySchema(() => zodSchema(z.object({
	background: z.enum([
		"auto",
		"opaque",
		"transparent"
	]).optional(),
	inputFidelity: z.enum(["low", "high"]).optional(),
	inputImageMask: z.object({
		fileId: z.string().optional(),
		imageUrl: z.string().optional()
	}).optional(),
	model: z.string().optional(),
	moderation: z.enum(["auto"]).optional(),
	outputCompression: z.number().int().min(0).max(100).optional(),
	outputFormat: z.enum([
		"png",
		"jpeg",
		"webp"
	]).optional(),
	partialImages: z.number().int().min(0).max(3).optional(),
	quality: z.enum([
		"auto",
		"low",
		"medium",
		"high"
	]).optional(),
	size: z.enum([
		"1024x1024",
		"1024x1536",
		"1536x1024",
		"auto"
	]).optional()
}).strict()));
var imageGenerationToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
	id: "openai.image_generation",
	name: "image_generation",
	inputSchema: lazySchema(() => zodSchema(z.object({}))),
	outputSchema: lazySchema(() => zodSchema(z.object({ result: z.string() })))
});
var imageGeneration = (args = {}) => {
	return imageGenerationToolFactory(args);
};
async function prepareResponsesTools({ tools, toolChoice, strictJsonSchema, supportsAsyncToolCalling = true }) {
	var _a2;
	tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
	const toolWarnings = [];
	if (tools == null) return {
		tools: void 0,
		toolChoice: void 0,
		toolWarnings
	};
	const openaiTools = [];
	for (const tool of tools) switch (tool.type) {
		case "function": {
			const openaiOptions = (_a2 = tool.providerOptions) == null ? void 0 : _a2.openai;
			const async = resolveAsyncToolOption({
				value: openaiOptions == null ? void 0 : openaiOptions.async,
				supportsAsyncToolCalling,
				tool,
				toolWarnings
			});
			openaiTools.push({
				type: "function",
				name: tool.name,
				description: tool.description,
				parameters: tool.inputSchema,
				strict: strictJsonSchema,
				...async != null ? { async } : {}
			});
			break;
		}
		case "provider-defined":
			switch (tool.id) {
				case "openai.file_search": {
					const args = await validateTypes({
						value: tool.args,
						schema: fileSearchArgsSchema
					});
					openaiTools.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":
					openaiTools.push({ type: "local_shell" });
					break;
				case "openai.web_search_preview": {
					const args = await validateTypes({
						value: tool.args,
						schema: webSearchPreviewArgsSchema
					});
					openaiTools.push({
						type: "web_search_preview",
						search_context_size: args.searchContextSize,
						user_location: args.userLocation
					});
					break;
				}
				case "openai.web_search": {
					const args = await validateTypes({
						value: tool.args,
						schema: webSearchArgsSchema
					});
					openaiTools.push({
						type: "web_search",
						filters: args.filters != null ? {
							allowed_domains: args.filters.allowedDomains,
							blocked_domains: args.filters.blockedDomains
						} : void 0,
						external_web_access: args.externalWebAccess,
						search_context_size: args.searchContextSize,
						user_location: args.userLocation
					});
					break;
				}
				case "openai.code_interpreter": {
					const args = await validateTypes({
						value: tool.args,
						schema: codeInterpreterArgsSchema
					});
					openaiTools.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 validateTypes({
						value: tool.args,
						schema: imageGenerationArgsSchema
					});
					openaiTools.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,
						size: args.size,
						quality: args.quality,
						moderation: args.moderation,
						output_format: args.outputFormat,
						output_compression: args.outputCompression
					});
					break;
				}
			}
			break;
		default: toolWarnings.push({
			type: "unsupported-tool",
			tool
		});
	}
	if (toolChoice == null) return {
		tools: openaiTools,
		toolChoice: void 0,
		toolWarnings
	};
	const type = toolChoice.type;
	switch (type) {
		case "auto":
		case "none":
		case "required": return {
			tools: openaiTools,
			toolChoice: type,
			toolWarnings
		};
		case "tool": return {
			tools: openaiTools,
			toolChoice: toolChoice.toolName === "code_interpreter" || toolChoice.toolName === "file_search" || toolChoice.toolName === "image_generation" || toolChoice.toolName === "web_search_preview" || toolChoice.toolName === "web_search" ? { type: toolChoice.toolName } : {
				type: "function",
				name: toolChoice.toolName
			},
			toolWarnings
		};
		default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
	}
}
function resolveAsyncToolOption({ value, supportsAsyncToolCalling, tool, toolWarnings }) {
	if (value !== true || supportsAsyncToolCalling) return value;
	toolWarnings.push({
		type: "unsupported-tool",
		tool,
		details: "Async tool calling is only supported by GPT-6 and later models."
	});
}
function getConfigurationUpdateUnsupportedReason({ modelCapabilities, options }) {
	if (!modelCapabilities.supportsConfigurationUpdate) return "reasoningEffortUpdate is only supported by GPT-6 and later models";
	if ((options == null ? void 0 : options.reasoningMode) === "pro" || (options == null ? void 0 : options.truncation) === "auto") return "reasoningEffortUpdate requires standard reasoning mode without automatic truncation";
}
var OpenAIResponsesLanguageModel = class {
	constructor(modelId, config) {
		this.specificationVersion = "v2";
		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 _a2, _b, _c, _d, _e, _f;
		const warnings = [];
		const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
		if (topK != null) warnings.push({
			type: "unsupported-setting",
			setting: "topK"
		});
		if (seed != null) warnings.push({
			type: "unsupported-setting",
			setting: "seed"
		});
		if (presencePenalty != null) warnings.push({
			type: "unsupported-setting",
			setting: "presencePenalty"
		});
		if (frequencyPenalty != null) warnings.push({
			type: "unsupported-setting",
			setting: "frequencyPenalty"
		});
		if (stopSequences != null) warnings.push({
			type: "unsupported-setting",
			setting: "stopSequences"
		});
		const openaiOptions = await parseProviderOptions({
			provider: "openai",
			providerOptions,
			schema: openaiResponsesProviderOptionsSchema
		});
		if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) warnings.push({
			type: "unsupported-setting",
			setting: "conversation",
			details: "conversation and previousResponseId cannot be used together"
		});
		const configurationUpdateUnsupportedReason = getConfigurationUpdateUnsupportedReason({
			modelCapabilities,
			options: openaiOptions
		});
		const webSearchToolName = (_a2 = tools == null ? void 0 : tools.find((tool) => tool.type === "provider-defined" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview"))) == null ? void 0 : _a2.name;
		const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
			prompt,
			configurationUpdateUnsupportedReason,
			providerOptionsName: this.config.provider.includes("azure") ? "azure" : "openai",
			systemMessageMode: modelCapabilities.systemMessageMode,
			explicitMessageItemType: this.config.explicitMessageItemType,
			fileIdPrefixes: this.config.fileIdPrefixes,
			store: (_b = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _b : true,
			isReasoningModel: modelCapabilities.isReasoningModel,
			hasLocalShellTool: hasOpenAITool("openai.local_shell"),
			webSearchToolName
		});
		warnings.push(...inputWarnings);
		let resolvedReasoningEffort = openaiOptions == null ? void 0 : openaiOptions.reasoningEffort;
		if (resolvedReasoningEffort != null && modelCapabilities.supportedReasoningEfforts != null && !modelCapabilities.supportedReasoningEfforts.includes(resolvedReasoningEffort)) {
			warnings.push({
				type: "unsupported-setting",
				setting: "reasoningEffort",
				details: `${this.modelId} only supports the following reasoning efforts: ${modelCapabilities.supportedReasoningEfforts.join(", ")}`
			});
			resolvedReasoningEffort = void 0;
		}
		const reasoningEffortUpdate = openaiOptions == null ? void 0 : openaiOptions.reasoningEffortUpdate;
		if (reasoningEffortUpdate != null && configurationUpdateUnsupportedReason != null) warnings.push({
			type: "unsupported-setting",
			setting: "reasoningEffortUpdate",
			details: configurationUpdateUnsupportedReason
		});
		else if (reasoningEffortUpdate != null) {
			const firstItem = input[0];
			if ((firstItem == null ? void 0 : firstItem.type) !== "configuration_update" || firstItem.reasoning.effort !== reasoningEffortUpdate) input.unshift({
				type: "configuration_update",
				reasoning: { effort: reasoningEffortUpdate }
			});
		}
		for (let i = 1; i < input.length; i++) if (input[i - 1].type === "configuration_update" && input[i].type === "configuration_update") throw new UnsupportedFunctionalityError({ functionality: "Adjacent reasoning effort configuration updates" });
		const strictJsonSchema = (_c = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _c : false;
		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((tool) => tool.type === "provider-defined" && tool.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");
		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 && modelCapabilities.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: (_d = responseFormat.name) != null ? _d : "response",
					description: responseFormat.description,
					schema: responseFormat.schema
				} : { type: "json_object" } },
				...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity }
			} },
			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_options: openaiOptions == null ? void 0 : openaiOptions.promptCacheOptions,
			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,
			...modelCapabilities.isReasoningModel && (resolvedReasoningEffort != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) && { reasoning: {
				...resolvedReasoningEffort != null && { effort: resolvedReasoningEffort },
				...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { summary: openaiOptions.reasoningSummary },
				...(openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null && { mode: openaiOptions.reasoningMode },
				...(openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null && { context: openaiOptions.reasoningContext }
			} }
		};
		if (modelCapabilities.supportsConfigurationUpdate && baseArgs.prompt_cache_retention != null) {
			baseArgs.prompt_cache_retention = void 0;
			warnings.push({
				type: "unsupported-setting",
				setting: "promptCacheRetention",
				details: "promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"
			});
		}
		if (modelCapabilities.isReasoningModel) {
			if (!((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) {
				if (baseArgs.temperature != null) {
					baseArgs.temperature = void 0;
					warnings.push({
						type: "unsupported-setting",
						setting: "temperature",
						details: "temperature is not supported for reasoning models"
					});
				}
				if (baseArgs.top_p != null) {
					baseArgs.top_p = void 0;
					warnings.push({
						type: "unsupported-setting",
						setting: "topP",
						details: "topP is not supported for reasoning models"
					});
				}
				if (modelCapabilities.supportedReasoningEfforts != null && (baseArgs.top_logprobs != null || ((_e = baseArgs.include) == null ? void 0 : _e.includes("message.output_text.logprobs")))) {
					baseArgs.top_logprobs = void 0;
					const filteredInclude = (_f = baseArgs.include) == null ? void 0 : _f.filter((value) => value !== "message.output_text.logprobs");
					baseArgs.include = filteredInclude != null && filteredInclude.length > 0 ? filteredInclude : void 0;
					warnings.push({
						type: "unsupported-setting",
						setting: "logprobs",
						details: "logprobs is not supported for reasoning models"
					});
				}
			}
		} else {
			if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) warnings.push({
				type: "unsupported-setting",
				setting: "reasoningEffort",
				details: "reasoningEffort is not supported for non-reasoning models"
			});
			if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) warnings.push({
				type: "unsupported-setting",
				setting: "reasoningSummary",
				details: "reasoningSummary is not supported for non-reasoning models"
			});
			if ((openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null) warnings.push({
				type: "unsupported-setting",
				setting: "reasoningMode",
				details: "reasoningMode is not supported for non-reasoning models"
			});
			if ((openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) warnings.push({
				type: "unsupported-setting",
				setting: "reasoningContext",
				details: "reasoningContext is not supported for non-reasoning models"
			});
		}
		if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) {
			warnings.push({
				type: "unsupported-setting",
				setting: "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-setting",
				setting: "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 { tools: openaiTools, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({
			tools,
			toolChoice,
			strictJsonSchema,
			supportsAsyncToolCalling: modelCapabilities.supportsAsyncToolCalling
		});
		return {
			webSearchToolName,
			args: {
				...baseArgs,
				tools: openaiTools,
				tool_choice: openaiToolChoice
			},
			warnings: [...warnings, ...toolWarnings],
			store
		};
	}
	async doGenerate(options) {
		var _a2, _b, _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;
		const { args: body, warnings, webSearchToolName } = await this.getArgs(options);
		const url = this.config.url({
			path: "/responses",
			modelId: this.modelId
		});
		const providerKey = this.config.provider.replace(".responses", "");
		const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
			url,
			headers: combineHeaders(this.config.headers(), options.headers),
			body,
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createJsonResponseHandler(openaiResponsesResponseSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		if (response.error) throw new APICallError({
			message: response.error.message,
			url,
			requestBodyValues: body,
			statusCode: 400,
			responseHeaders,
			responseBody: rawResponse,
			isRetryable: false
		});
		const content = [];
		const logprobs = [];
		let hasFunctionCall = false;
		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: { [providerKey]: {
						itemId: part.id,
						reasoningEncryptedContent: (_a2 = part.encrypted_content) != null ? _a2 : null
					} }
				});
				break;
			case "image_generation_call":
				content.push({
					type: "tool-call",
					toolCallId: part.id,
					toolName: "image_generation",
					input: "{}",
					providerExecuted: true
				});
				content.push({
					type: "tool-result",
					toolCallId: part.id,
					toolName: "image_generation",
					result: { result: part.result },
					providerExecuted: true
				});
				break;
			case "local_shell_call":
				content.push({
					type: "tool-call",
					toolCallId: part.call_id,
					toolName: "local_shell",
					input: JSON.stringify({ action: part.action }),
					providerMetadata: { [providerKey]: { itemId: part.id } }
				});
				break;
			case "message":
				for (const contentPart of part.content) {
					if (((_c = (_b = options.providerOptions) == null ? void 0 : _b.openai) == null ? void 0 : _c.logprobs) && contentPart.logprobs) logprobs.push(contentPart.logprobs);
					content.push({
						type: "text",
						text: contentPart.text,
						providerMetadata: { [providerKey]: {
							itemId: part.id,
							...part.phase != null && { phase: part.phase }
						} }
					});
					for (const annotation of contentPart.annotations) if (annotation.type === "url_citation") content.push({
						type: "source",
						sourceType: "url",
						id: (_f = (_e = (_d = this.config).generateId) == null ? void 0 : _e.call(_d)) != null ? _f : generateId(),
						url: annotation.url,
						title: annotation.title
					});
					else if (annotation.type === "file_citation") content.push({
						type: "source",
						sourceType: "document",
						id: (_i = (_h = (_g = this.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId(),
						mediaType: "text/plain",
						title: (_k = (_j = annotation.quote) != null ? _j : annotation.filename) != null ? _k : "Document",
						filename: (_l = annotation.filename) != null ? _l : annotation.file_id,
						...annotation.file_id ? { providerMetadata: { [providerKey]: { fileId: annotation.file_id } } } : {}
					});
					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 : generateId(),
						mediaType: "text/plain",
						title: (_q = (_p = annotation.filename) != null ? _p : annotation.file_id) != null ? _q : "Document",
						filename: (_r = annotation.filename) != null ? _r : annotation.file_id,
						providerMetadata: { [providerKey]: {
							fileId: annotation.file_id,
							containerId: annotation.container_id,
							...annotation.index != null ? { index: annotation.index } : {}
						} }
					});
					else if (annotation.type === "file_path") content.push({
						type: "source",
						sourceType: "document",
						id: (_u = (_t = (_s = this.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : generateId(),
						mediaType: "application/octet-stream",
						title: annotation.file_id,
						filename: annotation.file_id,
						providerMetadata: { [providerKey]: {
							fileId: annotation.file_id,
							...annotation.index != null ? { 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: { [providerKey]: {
						itemId: part.id,
						...part.async != null && { async: part.async }
					} }
				});
				break;
			case "web_search_call":
				content.push({
					type: "tool-call",
					toolCallId: part.id,
					toolName: webSearchToolName != null ? webSearchToolName : "web_search",
					input: JSON.stringify({}),
					providerExecuted: true
				});
				content.push({
					type: "tool-result",
					toolCallId: part.id,
					toolName: webSearchToolName != null ? webSearchToolName : "web_search",
					...mapWebSearchResult(part),
					providerExecuted: true
				});
				break;
			case "computer_call":
				content.push({
					type: "tool-call",
					toolCallId: part.id,
					toolName: "computer_use",
					input: "",
					providerExecuted: true
				});
				content.push({
					type: "tool-result",
					toolCallId: part.id,
					toolName: "computer_use",
					result: {
						type: "computer_use_tool_result",
						status: part.status || "completed"
					},
					providerExecuted: true
				});
				break;
			case "file_search_call":
				content.push({
					type: "tool-call",
					toolCallId: part.id,
					toolName: "file_search",
					input: "{}",
					providerExecuted: true
				});
				content.push({
					type: "tool-result",
					toolCallId: part.id,
					toolName: "file_search",
					result: {
						queries: part.queries,
						results: (_w = (_v = part.results) == null ? void 0 : _v.map((result) => ({
							attributes: result.attributes,
							fileId: result.file_id,
							filename: result.filename,
							score: result.score,
							text: result.text
						}))) != null ? _w : null
					},
					providerExecuted: true
				});
				break;
			case "code_interpreter_call":
				content.push({
					type: "tool-call",
					toolCallId: part.id,
					toolName: "code_interpreter",
					input: JSON.stringify({
						code: part.code,
						containerId: part.container_id
					}),
					providerExecuted: true
				});
				content.push({
					type: "tool-result",
					toolCallId: part.id,
					toolName: "code_interpreter",
					result: { outputs: part.outputs },
					providerExecuted: true
				});
		}
		const providerMetadata = { [providerKey]: { ...response.id != null ? { responseId: response.id } : {} } };
		if (logprobs.length > 0) providerMetadata[providerKey].logprobs = logprobs;
		if (typeof response.service_tier === "string") providerMetadata[providerKey].serviceTier = response.service_tier;
		if (((_x = response.reasoning) == null ? void 0 : _x.context) != null) providerMetadata[providerKey].reasoningContext = response.reasoning.context;
		const usage = response.usage;
		const responsesUsage = getResponsesUsageMetadata(usage);
		if (responsesUsage != null) providerMetadata[providerKey].usage = responsesUsage;
		return {
			content,
			finishReason: mapOpenAIResponseFinishReason({
				finishReason: (_y = response.incomplete_details) == null ? void 0 : _y.reason,
				hasFunctionCall
			}),
			usage: {
				inputTokens: usage.input_tokens,
				outputTokens: usage.output_tokens,
				totalTokens: usage.input_tokens + usage.output_tokens,
				reasoningTokens: (_A = (_z = usage.output_tokens_details) == null ? void 0 : _z.reasoning_tokens) != null ? _A : void 0,
				cachedInputTokens: (_C = (_B = usage.input_tokens_details) == null ? void 0 : _B.cached_tokens) != null ? _C : void 0
			},
			request: { body },
			response: {
				id: response.id,
				timestamp: /* @__PURE__ */ new Date(response.created_at * 1e3),
				modelId: response.model,
				headers: responseHeaders,
				body: rawResponse
			},
			providerMetadata,
			warnings
		};
	}
	async doStream(options) {
		const { args: body, warnings, webSearchToolName, store } = await this.getArgs(options);
		const { responseHeaders, value: response } = await postJsonToApi({
			url: this.config.url({
				path: "/responses",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body: {
				...body,
				stream: true
			},
			failedResponseHandler: openaiFailedResponseHandler,
			successfulResponseHandler: createEventSourceResponseHandler(openaiResponsesChunkSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		const self = this;
		const providerKey = this.config.provider.replace(".responses", "");
		let finishReason = "unknown";
		const usage = {
			inputTokens: void 0,
			outputTokens: void 0,
			totalTokens: void 0
		};
		const logprobs = [];
		let responseId = null;
		const ongoingToolCalls = {};
		const ongoingAnnotations = [];
		let activeMessagePhase;
		let hasFunctionCall = false;
		const activeReasoning = {};
		let serviceTier;
		let reasoningContext;
		let responsesUsage;
		return {
			stream: response.pipeThrough(new TransformStream({
				start(controller) {
					controller.enqueue({
						type: "stream-start",
						warnings
					});
				},
				transform(chunk, controller) {
					var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
					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 (isResponseOutputItemAddedChunk(value)) {
						if (value.item.type === "function_call") {
							ongoingToolCalls[value.output_index] = {
								toolName: value.item.name,
								toolCallId: value.item.call_id,
								async: value.item.async
							};
							controller.enqueue({
								type: "tool-input-start",
								id: value.item.call_id,
								toolName: value.item.name
							});
						} else if (value.item.type === "web_search_call") {
							ongoingToolCalls[value.output_index] = {
								toolName: webSearchToolName != null ? webSearchToolName : "web_search",
								toolCallId: value.item.id
							};
							controller.enqueue({
								type: "tool-input-start",
								id: value.item.id,
								toolName: 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: webSearchToolName != null ? webSearchToolName : "web_search",
								input: JSON.stringify({}),
								providerExecuted: true
							});
						} else if (value.item.type === "computer_call") {
							ongoingToolCalls[value.output_index] = {
								toolName: "computer_use",
								toolCallId: value.item.id
							};
							controller.enqueue({
								type: "tool-input-start",
								id: value.item.id,
								toolName: "computer_use",
								providerExecuted: true
							});
						} else if (value.item.type === "code_interpreter_call") {
							ongoingToolCalls[value.output_index] = {
								toolName: "code_interpreter",
								toolCallId: value.item.id,
								codeInterpreter: { containerId: value.item.container_id }
							};
							controller.enqueue({
								type: "tool-input-start",
								id: value.item.id,
								toolName: "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: "file_search",
							input: "{}",
							providerExecuted: true
						});
						else if (value.item.type === "image_generation_call") controller.enqueue({
							type: "tool-call",
							toolCallId: value.item.id,
							toolName: "image_generation",
							input: "{}",
							providerExecuted: true
						});
						else if (value.item.type === "message") {
							ongoingAnnotations.splice(0);
							activeMessagePhase = (_a2 = value.item.phase) != null ? _a2 : void 0;
							controller.enqueue({
								type: "text-start",
								id: value.item.id,
								providerMetadata: { [providerKey]: {
									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: { [providerKey]: {
									itemId: value.item.id,
									reasoningEncryptedContent: (_b = value.item.encrypted_content) != null ? _b : null
								} }
							});
						}
					} else if (isResponseOutputItemDoneChunk(value)) {
						if (value.item.type === "message") {
							const phase = (_c = value.item.phase) != null ? _c : activeMessagePhase;
							activeMessagePhase = void 0;
							controller.enqueue({
								type: "text-end",
								id: value.item.id,
								providerMetadata: { [providerKey]: {
									itemId: value.item.id,
									...phase != null && { phase },
									...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations }
								} }
							});
						} else if (value.item.type === "function_call") {
							const ongoingToolCall = ongoingToolCalls[value.output_index];
							ongoingToolCalls[value.output_index] = void 0;
							hasFunctionCall = true;
							controller.enqueue({
								type: "tool-input-end",
								id: value.item.call_id
							});
							controller.enqueue({
								type: "tool-call",
								toolCallId: value.item.call_id,
								toolName: value.item.name,
								input: value.item.arguments,
								providerMetadata: { [providerKey]: {
									itemId: value.item.id,
									...value.item.async != null ? { async: value.item.async } : (ongoingToolCall == null ? void 0 : ongoingToolCall.async) != null ? { async: ongoingToolCall.async } : {}
								} }
							});
						} else if (value.item.type === "web_search_call") {
							ongoingToolCalls[value.output_index] = void 0;
							controller.enqueue({
								type: "tool-result",
								toolCallId: value.item.id,
								toolName: webSearchToolName != null ? webSearchToolName : "web_search",
								...mapWebSearchResult(value.item),
								providerExecuted: true
							});
						} 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: "computer_use",
								input: "",
								providerExecuted: true
							});
							controller.enqueue({
								type: "tool-result",
								toolCallId: value.item.id,
								toolName: "computer_use",
								result: {
									type: "computer_use_tool_result",
									status: value.item.status || "completed"
								},
								providerExecuted: true
							});
						} else if (value.item.type === "file_search_call") {
							ongoingToolCalls[value.output_index] = void 0;
							controller.enqueue({
								type: "tool-result",
								toolCallId: value.item.id,
								toolName: "file_search",
								result: {
									queries: value.item.queries,
									results: (_e = (_d = value.item.results) == null ? void 0 : _d.map((result) => ({
										attributes: result.attributes,
										fileId: result.file_id,
										filename: result.filename,
										score: result.score,
										text: result.text
									}))) != null ? _e : null
								},
								providerExecuted: true
							});
						} else if (value.item.type === "code_interpreter_call") {
							ongoingToolCalls[value.output_index] = void 0;
							controller.enqueue({
								type: "tool-result",
								toolCallId: value.item.id,
								toolName: "code_interpreter",
								result: { outputs: value.item.outputs },
								providerExecuted: true
							});
						} else if (value.item.type === "image_generation_call") controller.enqueue({
							type: "tool-result",
							toolCallId: value.item.id,
							toolName: "image_generation",
							result: { result: value.item.result },
							providerExecuted: true
						});
						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: "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: { [providerKey]: { itemId: value.item.id } }
							});
						} 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: { [providerKey]: {
									itemId: value.item.id,
									reasoningEncryptedContent: (_f = value.item.encrypted_content) != null ? _f : 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 (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {
						const toolCall = ongoingToolCalls[value.output_index];
						if (toolCall != null) controller.enqueue({
							type: "tool-input-delta",
							id: toolCall.toolCallId,
							delta: JSON.stringify(value.delta).slice(1, -1)
						});
					} 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: "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: /* @__PURE__ */ 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 (((_h = (_g = options.providerOptions) == null ? void 0 : _g.openai) == null ? void 0 : _h.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: { [providerKey]: { itemId: value.item_id } }
								});
								activeReasoningPart.summaryParts[summaryIndex] = "concluded";
							}
							controller.enqueue({
								type: "reasoning-start",
								id: `${value.item_id}:${value.summary_index}`,
								providerMetadata: { [providerKey]: {
									itemId: value.item_id,
									reasoningEncryptedContent: (_j = (_i = activeReasoning[value.item_id]) == null ? void 0 : _i.encryptedContent) != null ? _j : 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: { [providerKey]: { 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: { [providerKey]: { 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 = mapOpenAIResponseFinishReason({
							finishReason: (_k = value.response.incomplete_details) == null ? void 0 : _k.reason,
							hasFunctionCall
						});
						usage.inputTokens = value.response.usage.input_tokens;
						usage.outputTokens = value.response.usage.output_tokens;
						usage.totalTokens = value.response.usage.input_tokens + value.response.usage.output_tokens;
						usage.reasoningTokens = (_m = (_l = value.response.usage.output_tokens_details) == null ? void 0 : _l.reasoning_tokens) != null ? _m : void 0;
						usage.cachedInputTokens = (_o = (_n = value.response.usage.input_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : void 0;
						if (typeof value.response.service_tier === "string") serviceTier = value.response.service_tier;
						if (((_p = value.response.reasoning) == null ? void 0 : _p.context) != null) reasoningContext = value.response.reasoning.context;
						responsesUsage = getResponsesUsageMetadata(value.response.usage);
					} else if (isResponseAnnotationAddedChunk(value)) {
						ongoingAnnotations.push(value.annotation);
						if (value.annotation.type === "url_citation") controller.enqueue({
							type: "source",
							sourceType: "url",
							id: (_s = (_r = (_q = self.config).generateId) == null ? void 0 : _r.call(_q)) != null ? _s : generateId(),
							url: value.annotation.url,
							title: value.annotation.title
						});
						else if (value.annotation.type === "file_citation") controller.enqueue({
							type: "source",
							sourceType: "document",
							id: (_v = (_u = (_t = self.config).generateId) == null ? void 0 : _u.call(_t)) != null ? _v : generateId(),
							mediaType: "text/plain",
							title: (_x = (_w = value.annotation.quote) != null ? _w : value.annotation.filename) != null ? _x : "Document",
							filename: (_y = value.annotation.filename) != null ? _y : value.annotation.file_id,
							...value.annotation.file_id ? { providerMetadata: { [providerKey]: { fileId: value.annotation.file_id } } } : {}
						});
					} else if (isErrorChunk(value)) controller.enqueue({
						type: "error",
						error: value
					});
				},
				flush(controller) {
					const providerMetadata = { [providerKey]: { responseId } };
					if (logprobs.length > 0) providerMetadata[providerKey].logprobs = logprobs;
					if (serviceTier !== void 0) providerMetadata[providerKey].serviceTier = serviceTier;
					if (reasoningContext !== void 0) providerMetadata[providerKey].reasoningContext = reasoningContext;
					if (responsesUsage != null) providerMetadata[providerKey].usage = responsesUsage;
					controller.enqueue({
						type: "finish",
						finishReason,
						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 isResponseCreatedChunk(chunk) {
	return chunk.type === "response.created";
}
function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
	return chunk.type === "response.function_call_arguments.delta";
}
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 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 mapWebSearchResult({ action, status }) {
	return status === "completed" ? { result: mapWebSearchOutput(action) } : {
		isError: true,
		result: { status }
	};
}
function mapWebSearchOutput(action) {
	var _a2;
	if (action == null) return {};
	switch (action.type) {
		case "search": return {
			action: {
				type: "search",
				query: (_a2 = action.query) != null ? _a2 : void 0
			},
			...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 getResponsesUsageMetadata(usage) {
	var _a2, _b, _c, _d;
	const cacheWriteTokens = (_a2 = usage == null ? void 0 : usage.input_tokens_details) == null ? void 0 : _a2.cache_write_tokens;
	const orchestrationInputTokens = (_b = usage == null ? void 0 : usage.input_tokens_details) == null ? void 0 : _b.orchestration_input_tokens;
	const orchestrationInputCachedTokens = (_c = usage == null ? void 0 : usage.input_tokens_details) == null ? void 0 : _c.orchestration_input_cached_tokens;
	const orchestrationOutputTokens = (_d = usage == null ? void 0 : usage.output_tokens_details) == null ? void 0 : _d.orchestration_output_tokens;
	if (cacheWriteTokens == null && orchestrationInputTokens == null && orchestrationInputCachedTokens == null && orchestrationOutputTokens == null) return;
	return {
		...cacheWriteTokens != null && { cacheWriteTokens },
		...orchestrationInputTokens != null && { orchestrationInputTokens },
		...orchestrationInputCachedTokens != null && { orchestrationInputCachedTokens },
		...orchestrationOutputTokens != null && { orchestrationOutputTokens }
	};
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/deepseek/1.0.66/49f66e6059cc74b7ae074dd68bdf1037fc4ae5b7ff92f2c56e0487a8d0f4f8b5/node_modules/@ai-sdk/deepseek/dist/internal/index.mjs
function createDeepseekChatOptionsSchema() {
	return z.object({
		/**
		* Whether to return log probabilities for generated tokens.
		*/
		logprobs: z.boolean().optional(),
		/**
		* Number of most likely tokens to return at each token position.
		*
		* Setting this option automatically enables `logprobs`.
		*/
		topLogprobs: z.number().int().min(0).max(20).optional(),
		/**
		* An opaque identifier for the end user. DeepSeek uses this identifier for
		* content-safety tracing and request isolation.
		*
		* Must contain only ASCII letters, numbers, underscores, and hyphens, and
		* must be at most 512 characters long.
		*/
		userId: z.string().regex(/^[a-zA-Z0-9_-]+$/, "userId must match /^[a-zA-Z0-9_-]+$/").max(512, "userId must be at most 512 characters long").optional(),
		/**
		* Type of thinking to use. Defaults to `enabled`.
		*/
		thinking: z.object({ type: z.enum([
			"adaptive",
			"enabled",
			"disabled"
		]).optional() }).optional(),
		/**
		* Controls the thinking strength for DeepSeek V4 reasoning models.
		*/
		reasoningEffort: z.enum([
			"low",
			"medium",
			"high",
			"xhigh",
			"max"
		]).optional(),
		/**
		* Whether to use strict JSON schema validation for structured outputs.
		* Only applies when the serving endpoint supports JSON schema response
		* formats (e.g. Azure). Defaults to `true`.
		*/
		strictJsonSchema: z.boolean().optional()
	});
}
var chatOptionsSchema;
function getDeepseekChatOptionsSchema() {
	return chatOptionsSchema != null ? chatOptionsSchema : chatOptionsSchema = createDeepseekChatOptionsSchema();
}
var deepseekChatOptions = lazySchema(() => zodSchema(getDeepseekChatOptionsSchema()));
function createDeepseekMessageOptionsSchema() {
	return z.object({ 
	/**
	* The name of the participant represented by the message.
	*
	* Supported on system, user, and assistant messages.
	*/
name: z.string().optional() });
}
var messageOptionsSchema;
function getDeepseekMessageOptionsSchema() {
	return messageOptionsSchema != null ? messageOptionsSchema : messageOptionsSchema = createDeepseekMessageOptionsSchema();
}
function createDeepseekAssistantMessageOptionsSchema() {
	return getDeepseekMessageOptionsSchema().extend({ 
	/**
	* Whether the assistant message content is a prefix that DeepSeek should
	* continue. This beta feature is only supported on the final assistant
	* message when using a beta base URL.
	*/
prefix: z.literal(true).optional() });
}
var assistantMessageOptionsSchema;
function getDeepseekAssistantMessageOptionsSchema() {
	return assistantMessageOptionsSchema != null ? assistantMessageOptionsSchema : assistantMessageOptionsSchema = createDeepseekAssistantMessageOptionsSchema();
}
var deepseekAssistantMessageProviderOptions = lazySchema(() => zodSchema(getDeepseekAssistantMessageOptionsSchema()));
var deepseekFilePartProviderOptions = lazySchema(() => zodSchema(z.object({
	/**
	* Controls how DeepSeek processes an image sent as an `image_url` part.
	*
	* @see https://api-docs.deepseek.com/api/create-chat-completion/
	*/
	imageDetail: z.enum([
		"low",
		"high",
		"original",
		"auto"
	]).optional(),
	/**
	* Sends inline image data as a DeepSeek `file` part using `file_data`
	* instead of an `image_url` data URL. When set, the file part's filename
	* is preserved.
	*
	* This option only applies to inline image data. It cannot be combined
	* with `imageDetail`.
	*/
	fileData: z.literal(true).optional()
})));
function isDeepSeekV4Model(modelId) {
	return !/(^|[/.])deepseek-(?:chat|reasoner|v[1-3](?:\.\d+)?)(?=[-/:.]|$)/.test(modelId);
}
var supportedImageMediaTypes = /* @__PURE__ */ new Set([
	"image/gif",
	"image/jpeg",
	"image/jpg",
	"image/png",
	"image/webp"
]);
function serializeDeepSeekToolCallArguments(input) {
	if (typeof input === "string") try {
		secureJsonParse(input);
		return input;
	} catch (e) {
		return JSON.stringify(input);
	}
	return stringifyWithBigIntAndCycles(input);
}
async function convertToDeepSeekChatMessages({ prompt, responseFormat, modelId, providerOptionsName = "deepseek", supportsAssistantPrefixCompletion = false, supportsStructuredOutputs = false }) {
	const isDeepSeekV4 = isDeepSeekV4Model(modelId);
	const messages = [];
	const warnings = [];
	if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
		if (responseFormat.schema == null) messages.push({
			role: "system",
			content: "Return JSON."
		});
		else if (!supportsStructuredOutputs) messages.push({
			role: "system",
			content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema)
		});
	}
	let lastUserMessageIndex = -1;
	for (let i = prompt.length - 1; i >= 0; i--) if (prompt[i].role === "user") {
		lastUserMessageIndex = i;
		break;
	}
	let index = -1;
	for (const { role, content, providerOptions } of prompt) {
		index++;
		const deepseekMessageOptions = await parseProviderOptions({
			provider: providerOptionsName,
			providerOptions,
			schema: deepseekAssistantMessageProviderOptions
		});
		if ((deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.prefix) === true && role !== "assistant") throw new InvalidPromptError({
			prompt,
			message: "DeepSeek assistant prefix completion requires `prefix: true` on an assistant message."
		});
		switch (role) {
			case "system":
				messages.push({
					role: "system",
					content,
					...(deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.name) != null && { name: deepseekMessageOptions.name }
				});
				break;
			case "user": {
				if (!content.some((part) => part.type === "file" && (part.mediaType === "image" || part.mediaType.startsWith("image/")))) {
					let userContent2 = "";
					for (const part of content) if (part.type === "text") userContent2 += part.text;
					else warnings.push({
						type: "other",
						message: `Unsupported user message part type: ${part.type}`
					});
					messages.push({
						role: "user",
						content: userContent2,
						...(deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.name) != null && { name: deepseekMessageOptions.name }
					});
					break;
				}
				const userContent = [];
				for (const part of content) if (part.type === "text") userContent.push({
					type: "text",
					text: part.text
				});
				else if (part.type === "file" && (part.mediaType === "image" || part.mediaType.startsWith("image/"))) {
					const filePartOptions = await parseProviderOptions({
						provider: providerOptionsName,
						providerOptions: part.providerOptions,
						schema: deepseekFilePartProviderOptions
					});
					const resolvedMediaType = part.mediaType === "image" || part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
					if (!supportedImageMediaTypes.has(resolvedMediaType)) throw new UnsupportedFunctionalityError({
						functionality: `DeepSeek image media type ${resolvedMediaType}`,
						message: "DeepSeek supports JPEG, PNG, GIF, and WebP image inputs."
					});
					if (part.data instanceof URL) {
						const url = part.data.toString();
						if (url.length > 8192) throw new InvalidPromptError({
							prompt,
							message: "DeepSeek image URLs must not exceed 8192 characters."
						});
						if ((filePartOptions == null ? void 0 : filePartOptions.fileData) === true) throw new InvalidPromptError({
							prompt,
							message: "DeepSeek `fileData` image parts require inline data, not a URL."
						});
						userContent.push({
							type: "image_url",
							image_url: {
								url,
								...(filePartOptions == null ? void 0 : filePartOptions.imageDetail) != null && { detail: filePartOptions.imageDetail }
							}
						});
					} else {
						const dataUrl = `data:${resolvedMediaType === "image/jpg" ? "image/jpeg" : resolvedMediaType};base64,${convertToBase64(part.data)}`;
						if ((filePartOptions == null ? void 0 : filePartOptions.fileData) === true) {
							if (filePartOptions.imageDetail != null) throw new InvalidPromptError({
								prompt,
								message: "DeepSeek `imageDetail` cannot be combined with `fileData`."
							});
							userContent.push({
								type: "file",
								file_data: dataUrl,
								...part.filename != null && { filename: part.filename }
							});
						} else userContent.push({
							type: "image_url",
							image_url: {
								url: dataUrl,
								...(filePartOptions == null ? void 0 : filePartOptions.imageDetail) != null && { detail: filePartOptions.imageDetail }
							}
						});
					}
				} else warnings.push({
					type: "other",
					message: `Unsupported user message part type: ${part.type}`
				});
				messages.push({
					role: "user",
					content: userContent,
					...(deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.name) != null && { name: deepseekMessageOptions.name }
				});
				break;
			}
			case "assistant": {
				if ((deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.prefix) === true) {
					if (index !== prompt.length - 1) throw new InvalidPromptError({
						prompt,
						message: "DeepSeek assistant prefix completion requires the prefixed assistant message to be the final message."
					});
					if (!supportsAssistantPrefixCompletion) throw new UnsupportedFunctionalityError({
						functionality: "DeepSeek assistant prefix completion",
						message: "DeepSeek assistant prefix completion requires a beta base URL ending in `/beta`."
					});
				}
				let text = "";
				let reasoning;
				const toolCalls = [];
				for (const part of content) switch (part.type) {
					case "text":
						text += part.text;
						break;
					case "reasoning":
						if (index <= lastUserMessageIndex && !isDeepSeekV4) break;
						if (reasoning == null) reasoning = part.text;
						else reasoning += part.text;
						break;
					case "tool-call": toolCalls.push({
						id: part.toolCallId,
						type: "function",
						function: {
							name: part.toolName,
							arguments: serializeDeepSeekToolCallArguments(part.input)
						}
					});
				}
				messages.push({
					role: "assistant",
					content: text,
					...(deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.name) != null && { name: deepseekMessageOptions.name },
					...(deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.prefix) === true && { prefix: true },
					reasoning_content: reasoning != null ? reasoning : isDeepSeekV4 ? "" : void 0,
					tool_calls: toolCalls.length > 0 ? toolCalls : void 0
				});
				break;
			}
			case "tool":
				if ((deepseekMessageOptions == null ? void 0 : deepseekMessageOptions.name) != null) warnings.push({
					type: "other",
					message: "DeepSeek does not support message names on tool messages. The name has been omitted."
				});
				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 = stringifyWithBigIntAndCycles(output.value);
					}
					messages.push({
						role: "tool",
						tool_call_id: toolResponse.toolCallId,
						content: contentValue
					});
				}
				break;
			default: warnings.push({
				type: "other",
				message: `Unsupported message role: ${role}`
			});
		}
	}
	return {
		messages,
		warnings
	};
}
function createTokenUsageSchema() {
	return z.object({
		prompt_tokens: z.number().nullish(),
		completion_tokens: z.number().nullish(),
		prompt_cache_hit_tokens: z.number().nullish(),
		prompt_cache_miss_tokens: z.number().nullish(),
		total_tokens: z.number().nullish(),
		prompt_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
		completion_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
	}).nullish();
}
var tokenUsageSchema;
function getTokenUsageSchema() {
	return tokenUsageSchema != null ? tokenUsageSchema : tokenUsageSchema = createTokenUsageSchema();
}
function createDeepSeekErrorSchema() {
	return z.object({ error: z.object({
		message: z.string(),
		type: z.string().nullish(),
		param: z.any().nullish(),
		code: z.union([z.string(), z.number()]).nullish()
	}) });
}
var errorSchema;
function getDeepSeekErrorSchema() {
	return errorSchema != null ? errorSchema : errorSchema = createDeepSeekErrorSchema();
}
var deepSeekErrorSchema = lazySchema(() => zodSchema(getDeepSeekErrorSchema()));
function createDeepseekChatLogprobsSchema() {
	const deepseekChatLogprobSchema = z.object({
		token: z.string(),
		logprob: z.number(),
		bytes: z.array(z.number()).nullable(),
		top_logprobs: z.array(z.object({
			token: z.string(),
			logprob: z.number(),
			bytes: z.array(z.number()).nullable()
		}))
	});
	return z.object({
		content: z.array(deepseekChatLogprobSchema).nullish(),
		reasoning_content: z.array(deepseekChatLogprobSchema).nullish()
	}).nullish();
}
var logprobsSchema;
function getDeepseekChatLogprobsSchema() {
	return logprobsSchema != null ? logprobsSchema : logprobsSchema = createDeepseekChatLogprobsSchema();
}
var deepseekChatResponseSchema = lazySchema(() => zodSchema(z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	object: z.literal("chat.completion").nullish(),
	system_fingerprint: z.string().nullish(),
	choices: z.array(z.object({
		index: z.number().nullish(),
		message: z.object({
			role: z.literal("assistant").nullish(),
			content: z.string().nullish(),
			reasoning_content: z.string().nullish(),
			tool_calls: z.array(z.object({
				id: z.string().nullish(),
				type: z.literal("function").nullish(),
				function: z.object({
					name: z.string(),
					arguments: z.string()
				})
			})).nullish()
		}),
		logprobs: getDeepseekChatLogprobsSchema(),
		finish_reason: z.string().nullish()
	})),
	usage: getTokenUsageSchema()
})));
var deepseekChatChunkSchema = lazySchema(() => zodSchema(z.union([z.object({
	id: z.string().nullish(),
	created: z.number().nullish(),
	model: z.string().nullish(),
	object: z.literal("chat.completion.chunk").nullish(),
	system_fingerprint: z.string().nullish(),
	choices: z.array(z.object({
		index: z.number().nullish(),
		delta: z.object({
			role: z.enum(["assistant"]).nullish(),
			content: z.string().nullish(),
			reasoning_content: z.string().nullish(),
			tool_calls: z.array(z.object({
				index: z.number(),
				id: z.string().nullish(),
				type: z.literal("function").nullish(),
				function: z.object({
					name: z.string().nullish(),
					arguments: z.string().nullish()
				})
			})).nullish()
		}).nullish(),
		logprobs: getDeepseekChatLogprobsSchema(),
		finish_reason: z.string().nullish()
	})),
	usage: getTokenUsageSchema()
}), getDeepSeekErrorSchema()])));
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 deepseekTools = [];
	for (const tool of tools) if (tool.type === "provider-defined") toolWarnings.push({
		type: "unsupported-tool",
		tool
	});
	else deepseekTools.push({
		type: "function",
		function: {
			name: tool.name,
			description: tool.description,
			parameters: tool.inputSchema
		}
	});
	if (toolChoice == null) return {
		tools: deepseekTools,
		toolChoice: void 0,
		toolWarnings
	};
	const type = toolChoice.type;
	switch (type) {
		case "auto":
		case "none":
		case "required": return {
			tools: deepseekTools,
			toolChoice: type,
			toolWarnings
		};
		case "tool": return {
			tools: deepseekTools,
			toolChoice: {
				type: "function",
				function: { name: toolChoice.toolName }
			},
			toolWarnings
		};
		default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
	}
}
function getResponseMetadata({ id, model, created }) {
	return {
		id: id != null ? id : void 0,
		modelId: model != null ? model : void 0,
		timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
	};
}
function mapDeepSeekFinishReason(finishReason) {
	switch (finishReason) {
		case "stop": return "stop";
		case "length": return "length";
		case "content_filter": return "content-filter";
		case "tool_calls": return "tool-calls";
		case "insufficient_system_resource": return "error";
		default: return "unknown";
	}
}
function getDeepSeekCacheReadTokens(usage) {
	var _a, _b, _c;
	return (_c = (_b = usage == null ? void 0 : usage.prompt_cache_hit_tokens) != null ? _b : (_a = usage == null ? void 0 : usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _c : void 0;
}
function mapDeepSeekProviderReasoningEffort({ reasoningEffort, warnings }) {
	const mapped = reasoningEffort === "medium" ? "high" : reasoningEffort === "xhigh" ? "max" : reasoningEffort;
	if (mapped !== reasoningEffort) warnings.push({
		type: "other",
		message: `reasoningEffort "${reasoningEffort}" is not a canonical DeepSeek value. mapped to "${mapped}".`
	});
	return mapped;
}
var DeepSeekChatLanguageModel = class {
	constructor(modelId, config) {
		this.specificationVersion = "v2";
		this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
		this.modelId = modelId;
		this.config = config;
		this.failedResponseHandler = createJsonErrorResponseHandler({
			errorSchema: deepSeekErrorSchema,
			errorToMessage: (error) => error.error.message
		});
	}
	get provider() {
		return this.config.provider;
	}
	get providerOptionsName() {
		return this.config.provider.split(".")[0].trim();
	}
	async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, providerOptions, stopSequences, responseFormat, tools, toolChoice, seed }) {
		var _a, _b, _c, _d;
		const deepseekOptions = (_a = await parseProviderOptions({
			provider: this.providerOptionsName,
			providerOptions,
			schema: deepseekChatOptions
		})) != null ? _a : {};
		const supportsStructuredOutputs = this.config.supportsStructuredOutputs === true;
		const supportsPenaltySampling = this.config.supportsPenaltySampling === true;
		const { messages, warnings } = await convertToDeepSeekChatMessages({
			prompt,
			responseFormat,
			modelId: this.modelId,
			providerOptionsName: this.providerOptionsName,
			supportsAssistantPrefixCompletion: this.config.supportsAssistantPrefixCompletion,
			supportsStructuredOutputs
		});
		const allWarnings = [...warnings];
		if (topK != null) allWarnings.push({
			type: "unsupported-setting",
			setting: "topK"
		});
		if (seed != null) allWarnings.push({
			type: "unsupported-setting",
			setting: "seed"
		});
		if (!supportsPenaltySampling && frequencyPenalty != null) allWarnings.push({
			type: "other",
			message: "frequencyPenalty is deprecated by DeepSeek and has been omitted. Remove frequencyPenalty from the request."
		});
		if (!supportsPenaltySampling && presencePenalty != null) allWarnings.push({
			type: "other",
			message: "presencePenalty is deprecated by DeepSeek and has been omitted. Remove presencePenalty from the request."
		});
		const { tools: deepseekTools, toolChoice: deepseekToolChoices, toolWarnings } = prepareTools({
			tools,
			toolChoice
		});
		allWarnings.push(...toolWarnings);
		const thinkingType = (_b = deepseekOptions.thinking) == null ? void 0 : _b.type;
		if (thinkingType === "adaptive") allWarnings.push({
			type: "other",
			message: "thinking.type \"adaptive\" is not a canonical DeepSeek value. mapped to \"enabled\"."
		});
		const thinking = this.config.supportsThinking === false ? void 0 : thinkingType != null ? { type: thinkingType === "adaptive" ? "enabled" : thinkingType } : void 0;
		const isThinkingEnabled = this.config.supportsThinking !== false && (thinking == null ? void 0 : thinking.type) !== "disabled" && (thinking != null || this.modelId === "deepseek-reasoner" || isDeepSeekV4Model(this.modelId));
		if (isThinkingEnabled && temperature != null) allWarnings.push({
			type: "unsupported-setting",
			setting: "temperature",
			details: "temperature has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use temperature."
		});
		if (isThinkingEnabled && topP != null) allWarnings.push({
			type: "unsupported-setting",
			setting: "topP",
			details: "topP has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use topP."
		});
		const reasoningEffort = deepseekOptions.reasoningEffort != null ? mapDeepSeekProviderReasoningEffort({
			reasoningEffort: deepseekOptions.reasoningEffort,
			warnings: allWarnings
		}) : void 0;
		return {
			args: {
				model: this.modelId,
				...(deepseekOptions.logprobs === true || deepseekOptions.topLogprobs != null) && { logprobs: true },
				...deepseekOptions.topLogprobs != null && { top_logprobs: deepseekOptions.topLogprobs },
				max_tokens: maxOutputTokens,
				temperature: isThinkingEnabled ? void 0 : temperature,
				top_p: isThinkingEnabled ? void 0 : topP,
				frequency_penalty: supportsPenaltySampling ? frequencyPenalty : void 0,
				presence_penalty: supportsPenaltySampling ? presencePenalty : void 0,
				response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? supportsStructuredOutputs && responseFormat.schema != null ? {
					type: "json_schema",
					json_schema: {
						schema: responseFormat.schema,
						strict: (_c = deepseekOptions.strictJsonSchema) != null ? _c : true,
						name: (_d = responseFormat.name) != null ? _d : "response",
						description: responseFormat.description
					}
				} : { type: "json_object" } : void 0,
				stop: stopSequences,
				messages,
				tools: deepseekTools,
				tool_choice: deepseekToolChoices,
				thinking,
				...deepseekOptions.userId != null && { user_id: deepseekOptions.userId },
				...(thinking == null ? void 0 : thinking.type) !== "disabled" && reasoningEffort != null && { reasoning_effort: reasoningEffort }
			},
			warnings: allWarnings
		};
	}
	async doGenerate(options) {
		var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
		const { args, warnings } = await this.getArgs({ ...options });
		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: args,
			failedResponseHandler: this.failedResponseHandler,
			successfulResponseHandler: createJsonResponseHandler(deepseekChatResponseSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		const choice = responseBody.choices[0];
		const content = [];
		const reasoning = choice.message.reasoning_content;
		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: (_a = toolCall.id) != null ? _a : generateId(),
			toolName: toolCall.function.name,
			input: toolCall.function.arguments
		});
		const text = choice.message.content;
		if (text != null && text.length > 0) content.push({
			type: "text",
			text
		});
		const cacheReadTokens = getDeepSeekCacheReadTokens(responseBody.usage);
		return {
			content,
			finishReason: mapDeepSeekFinishReason(choice.finish_reason),
			usage: {
				inputTokens: (_c = (_b = responseBody.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : void 0,
				outputTokens: (_e = (_d = responseBody.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : void 0,
				totalTokens: (_g = (_f = responseBody.usage) == null ? void 0 : _f.total_tokens) != null ? _g : void 0,
				reasoningTokens: (_j = (_i = (_h = responseBody.usage) == null ? void 0 : _h.completion_tokens_details) == null ? void 0 : _i.reasoning_tokens) != null ? _j : void 0,
				cachedInputTokens: cacheReadTokens
			},
			providerMetadata: { [this.providerOptionsName]: {
				promptCacheHitTokens: cacheReadTokens != null ? cacheReadTokens : null,
				promptCacheMissTokens: (_l = (_k = responseBody.usage) == null ? void 0 : _k.prompt_cache_miss_tokens) != null ? _l : null,
				...responseBody.object != null && { responseObject: responseBody.object },
				...choice.index != null && { choiceIndex: choice.index },
				...choice.message.role != null && { messageRole: choice.message.role },
				...choice.message.tool_calls != null && { toolCallTypes: choice.message.tool_calls.map((toolCall) => toolCall.type).filter((type) => type != null) },
				...choice.logprobs != null && { logprobs: choice.logprobs },
				...responseBody.system_fingerprint != null && { systemFingerprint: responseBody.system_fingerprint }
			} },
			request: { body: args },
			response: {
				...getResponseMetadata(responseBody),
				headers: responseHeaders,
				body: rawResponse
			},
			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 postJsonToApi({
			url: this.config.url({
				path: "/chat/completions",
				modelId: this.modelId
			}),
			headers: combineHeaders(this.config.headers(), options.headers),
			body,
			failedResponseHandler: this.failedResponseHandler,
			successfulResponseHandler: createEventSourceResponseHandler(deepseekChatChunkSchema),
			abortSignal: options.abortSignal,
			fetch: this.config.fetch
		});
		const toolCalls = [];
		let finishReason = "unknown";
		let usage = void 0;
		let systemFingerprint = void 0;
		let isFirstChunk = true;
		const providerOptionsName = this.providerOptionsName;
		let isActiveReasoning = false;
		let isActiveText = false;
		let responseObject;
		let choiceIndex;
		let messageRole;
		const toolCallTypes = /* @__PURE__ */ new Map();
		const contentLogprobs = [];
		const reasoningLogprobs = [];
		return {
			stream: response.pipeThrough(new TransformStream({
				start(controller) {
					controller.enqueue({
						type: "stream-start",
						warnings
					});
				},
				transform(chunk, controller) {
					var _a, _b, _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) {
						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.message
						});
						return;
					}
					if (isFirstChunk) {
						isFirstChunk = false;
						controller.enqueue({
							type: "response-metadata",
							...getResponseMetadata(value)
						});
					}
					if (value.usage != null) usage = value.usage;
					if (value.object != null) responseObject = value.object;
					if (value.system_fingerprint != null) systemFingerprint = value.system_fingerprint;
					const choice = value.choices[0];
					if ((choice == null ? void 0 : choice.index) != null) choiceIndex = choice.index;
					if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = mapDeepSeekFinishReason(choice.finish_reason);
					if (((_a = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _a.content) != null) contentLogprobs.push(...choice.logprobs.content);
					if (((_b = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _b.reasoning_content) != null) reasoningLogprobs.push(...choice.logprobs.reasoning_content);
					if ((choice == null ? void 0 : choice.delta) == null) return;
					const delta = choice.delta;
					if (delta.role != null) messageRole = delta.role;
					const reasoningContent = delta.reasoning_content;
					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;
						}
						if (isActiveReasoning) {
							controller.enqueue({
								type: "reasoning-end",
								id: "reasoning-0"
							});
							isActiveReasoning = false;
						}
						controller.enqueue({
							type: "text-delta",
							id: "txt-0",
							delta: delta.content
						});
					}
					if (delta.tool_calls != null && delta.tool_calls.length > 0) {
						if (isActiveReasoning) {
							controller.enqueue({
								type: "reasoning-end",
								id: "reasoning-0"
							});
							isActiveReasoning = false;
						}
						for (const toolCallDelta of delta.tool_calls) {
							if (toolCallDelta.type != null) toolCallTypes.set(toolCallDelta.index, toolCallDelta.type);
							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 (((_c = toolCallDelta.function) == null ? void 0 : _c.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: (_d = toolCallDelta.function.arguments) != null ? _d : ""
									},
									hasFinished: false
								};
								const toolCall2 = toolCalls[index];
								if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.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: (_g = toolCall2.id) != null ? _g : generateId(),
											toolName: toolCall2.function.name,
											input: toolCall2.function.arguments
										});
										toolCall2.hasFinished = true;
									}
								}
								continue;
							}
							const toolCall = toolCalls[index];
							if (toolCall.hasFinished) continue;
							if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
							controller.enqueue({
								type: "tool-input-delta",
								id: toolCall.id,
								delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
							});
							if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
								controller.enqueue({
									type: "tool-input-end",
									id: toolCall.id
								});
								controller.enqueue({
									type: "tool-call",
									toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
									toolName: toolCall.function.name,
									input: toolCall.function.arguments
								});
								toolCall.hasFinished = true;
							}
						}
					}
				},
				flush(controller) {
					var _a, _b, _c, _d, _e, _f, _g;
					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: (_a = toolCall.id) != null ? _a : generateId(),
							toolName: toolCall.function.name,
							input: toolCall.function.arguments
						});
					}
					const cacheReadTokens = getDeepSeekCacheReadTokens(usage);
					controller.enqueue({
						type: "finish",
						finishReason,
						usage: {
							inputTokens: (_b = usage == null ? void 0 : usage.prompt_tokens) != null ? _b : void 0,
							outputTokens: (_c = usage == null ? void 0 : usage.completion_tokens) != null ? _c : void 0,
							totalTokens: (_d = usage == null ? void 0 : usage.total_tokens) != null ? _d : void 0,
							reasoningTokens: (_f = (_e = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : void 0,
							cachedInputTokens: cacheReadTokens
						},
						providerMetadata: { [providerOptionsName]: {
							promptCacheHitTokens: cacheReadTokens != null ? cacheReadTokens : null,
							promptCacheMissTokens: (_g = usage == null ? void 0 : usage.prompt_cache_miss_tokens) != null ? _g : null,
							...responseObject != null && { responseObject },
							...choiceIndex != null && { choiceIndex },
							...messageRole != null && { messageRole },
							...toolCallTypes.size > 0 && { toolCallTypes: [...toolCallTypes.entries()].sort(([left], [right]) => left - right).map(([, type]) => type) },
							...(contentLogprobs.length > 0 || reasoningLogprobs.length > 0) && { logprobs: {
								...contentLogprobs.length > 0 && { content: contentLogprobs },
								...reasoningLogprobs.length > 0 && { reasoning_content: reasoningLogprobs }
							} },
							...systemFingerprint != null && { systemFingerprint }
						} }
					});
				}
			})),
			request: { body },
			response: { headers: responseHeaders }
		};
	}
};
getDeepseekChatOptionsSchema();
getDeepseekMessageOptionsSchema();
getDeepseekAssistantMessageOptionsSchema();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/azure/2.0.147/deac19ac61fda05fd92ca17c51a62787d3596bbeed3bbb32f029004a1fcbf731/node_modules/@ai-sdk/azure/dist/index.mjs
var azureOpenaiTools = {
	codeInterpreter,
	fileSearch,
	imageGeneration,
	webSearch,
	webSearchPreview
};
var VERSION = "2.0.147";
function getAzureOpenAIBaseURLInfo(baseURL) {
	if (baseURL == null) return {
		isAzureOpenAI: true,
		isFoundryProject: false,
		isVersioned: false
	};
	const url = new URL(baseURL);
	const hostname = url.hostname;
	const isAzureOpenAI = hostname.endsWith(".openai.azure.com") || hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
	const pathname = url.pathname.replace(/\/+$/, "");
	return {
		isAzureOpenAI,
		isFoundryProject: hostname.endsWith(".services.ai.azure.com") && pathname.startsWith("/api/projects/"),
		isVersioned: isAzureOpenAI && pathname.toLowerCase().endsWith("/openai/v1")
	};
}
function createAzure(options = {}) {
	var _a;
	const tokenProvider = options.tokenProvider;
	if (options.apiKey && tokenProvider) throw new InvalidArgumentError({
		argument: "apiKey/tokenProvider",
		message: "Both apiKey and tokenProvider were provided. Please use only one authentication method."
	});
	const getHeaders = () => {
		return withUserAgentSuffix({
			...tokenProvider ? {} : { "api-key": loadApiKey({
				apiKey: options.apiKey,
				environmentVariableName: "AZURE_API_KEY",
				description: "Azure OpenAI"
			}) },
			...options.headers
		}, `ai-sdk/azure/${VERSION}`);
	};
	const fetch = tokenProvider ? async (input, init) => {
		var _a2;
		const headers = normalizeHeaders$1(init == null ? void 0 : init.headers);
		if (headers.authorization == null) headers.authorization = `Bearer ${await tokenProvider()}`;
		return ((_a2 = options.fetch) != null ? _a2 : globalThis.fetch)(input, {
			...init,
			headers
		});
	} : options.fetch;
	const getResourceName = () => loadSetting({
		settingValue: options.resourceName,
		settingName: "resourceName",
		environmentVariableName: "AZURE_RESOURCE_NAME",
		description: "Azure OpenAI resource name"
	});
	const apiVersion = (_a = options.apiVersion) != null ? _a : "v1";
	const { isAzureOpenAI, isFoundryProject, isVersioned: isAzureOpenAIVersioned } = getAzureOpenAIBaseURLInfo(options.baseURL);
	const url = ({ path, modelId }) => {
		var _a2;
		const baseUrlPrefix = withoutTrailingSlash((_a2 = options.baseURL) != null ? _a2 : `https://${getResourceName()}.openai.azure.com/openai`);
		let fullUrl;
		if (options.useDeploymentBasedUrls) fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);
		else if (!isAzureOpenAI || isAzureOpenAIVersioned) fullUrl = new URL(`${baseUrlPrefix}${path}`);
		else fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);
		if (options.useDeploymentBasedUrls || isAzureOpenAI && !isAzureOpenAIVersioned && !isFoundryProject) fullUrl.searchParams.set("api-version", apiVersion);
		return fullUrl.toString();
	};
	const createChatModel = (deploymentName) => new OpenAIChatLanguageModel(deploymentName, {
		provider: "azure.chat",
		url,
		headers: getHeaders,
		fetch
	});
	const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
		provider: "azure.completion",
		url,
		headers: getHeaders,
		fetch
	});
	const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
		provider: "azure.embeddings",
		headers: getHeaders,
		url,
		fetch
	});
	const createResponsesModel = (modelId) => new OpenAIResponsesLanguageModel(modelId, {
		provider: "azure.responses",
		url,
		headers: getHeaders,
		fetch,
		explicitMessageItemType: isFoundryProject,
		fileIdPrefixes: ["assistant-"]
	});
	const createDeepSeekModel = (deploymentName) => new DeepSeekChatLanguageModel(deploymentName, {
		provider: "azure.deepseek",
		url,
		headers: getHeaders,
		fetch,
		supportsPenaltySampling: true,
		supportsThinking: false,
		supportsStructuredOutputs: true
	});
	const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
		provider: "azure.image",
		url,
		headers: getHeaders,
		fetch
	});
	const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
		provider: "azure.transcription",
		url,
		headers: getHeaders,
		fetch
	});
	const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
		provider: "azure.speech",
		url,
		headers: getHeaders,
		fetch
	});
	const provider = function(deploymentId) {
		if (new.target) throw new Error("The Azure OpenAI model function cannot be called with the new keyword.");
		return createChatModel(deploymentId);
	};
	provider.languageModel = createChatModel;
	provider.chat = createChatModel;
	provider.deepseek = createDeepSeekModel;
	provider.completion = createCompletionModel;
	provider.embedding = createEmbeddingModel;
	provider.image = createImageModel;
	provider.imageModel = createImageModel;
	provider.textEmbedding = createEmbeddingModel;
	provider.textEmbeddingModel = createEmbeddingModel;
	provider.responses = createResponsesModel;
	provider.transcription = createTranscriptionModel;
	provider.speech = createSpeechModel;
	provider.tools = azureOpenaiTools;
	return provider;
}
createAzure();
// src/llm/model/openai-websocket-fetch.ts
const TERMINAL_RESPONSE_EVENTS = /* @__PURE__ */ new Set([
	"response.completed",
	"response.failed",
	"response.incomplete",
	"error"
]);
/**
* Creates a `fetch` function that routes OpenAI Responses API streaming
* requests through a persistent WebSocket connection instead of HTTP.
*/
function createOpenAIWebSocketFetch(options) {
	const wsUrl = options?.url ?? "wss://api.openai.com/v1/responses";
	const betaHeader = options?.betaHeader === void 0 ? "responses_websockets=2026-02-06" : options.betaHeader;
	const apiKeyQueryParam = options?.apiKeyQueryParam ?? false;
	let ws = null;
	let connecting = null;
	let connectionKey = null;
	let nextQueryCredentialId = 0;
	const queryCredentialIds = /* @__PURE__ */ new Map();
	let busy = false;
	function getQueryCredentialCacheId(value) {
		if (!value) return "";
		const existing = queryCredentialIds.get(value);
		if (existing) return existing;
		const id = String(++nextQueryCredentialId);
		queryCredentialIds.set(value, id);
		return id;
	}
	function getConnection(authorization, headers, signal) {
		if (signal?.aborted) return Promise.reject(getAbortError(signal));
		const normalizedHeaders = {
			...normalizeHeaders(options?.headers),
			...headers
		};
		const apiKey = normalizedHeaders["api-key"];
		delete normalizedHeaders["authorization"];
		delete normalizedHeaders["openai-beta"];
		if (options?.apiKeyAsBearer || apiKeyQueryParam) delete normalizedHeaders["api-key"];
		const nextConnectionKey = buildConnectionKey(authorization, normalizedHeaders, apiKeyQueryParam ? `${apiKeyQueryParam}:${getQueryCredentialCacheId(apiKey)}` : "");
		if (ws?.readyState === WebSocket.OPEN && connectionKey === nextConnectionKey) return Promise.resolve(ws);
		if (ws?.readyState === WebSocket.OPEN && connectionKey !== nextConnectionKey) {
			ws.close();
			ws = null;
			connectionKey = null;
		}
		if (connecting && connectionKey === nextConnectionKey) return connecting;
		connectionKey = nextConnectionKey;
		connecting = new Promise((resolve, reject) => {
			let settled = false;
			const socket = new WebSocket(getWebSocketUrl(wsUrl, apiKeyQueryParam, apiKey), { headers: {
				...normalizedHeaders,
				...authorization ? { Authorization: authorization } : {},
				...betaHeader ? { "OpenAI-Beta": betaHeader } : {}
			} });
			function cleanupAbortListener() {
				signal?.removeEventListener("abort", onAbort);
			}
			function rejectConnection(err, closeSocket = true) {
				if (settled) return;
				settled = true;
				connecting = null;
				connectionKey = null;
				cleanupAbortListener();
				if (closeSocket) socket.close();
				reject(err);
			}
			function onAbort() {
				rejectConnection(getAbortError(signal));
			}
			signal?.addEventListener("abort", onAbort, { once: true });
			socket.on("open", () => {
				if (signal?.aborted) {
					rejectConnection(getAbortError(signal));
					return;
				}
				settled = true;
				ws = socket;
				connecting = null;
				cleanupAbortListener();
				resolve(socket);
			});
			socket.on("error", (err) => {
				rejectConnection(err, false);
			});
			socket.on("close", () => {
				if (settled) return;
				rejectConnection(/* @__PURE__ */ new Error("WebSocket closed before the connection opened"), false);
			});
			socket.on("close", () => {
				if (ws === socket) ws = null;
				if (ws === null) connectionKey = null;
			});
		});
		return connecting;
	}
	async function websocketFetch(input, init) {
		const url = input instanceof URL ? input.toString() : typeof input === "string" ? input : input.url;
		if (init?.method !== "POST" || !isResponsesUrl(url)) return globalThis.fetch(input, init);
		let body;
		try {
			body = JSON.parse(typeof init.body === "string" ? init.body : "");
		} catch {
			return globalThis.fetch(input, init);
		}
		if (!body.stream) return globalThis.fetch(input, init);
		if (busy) {
			if (body.previous_response_id) throw new Error("Cannot start an overlapping WebSocket Responses continuation. Wait for the active stream to finish before sending previous_response_id.");
			return globalThis.fetch(input, init);
		}
		const headers = normalizeHeaders(init.headers);
		const authorization = headers["authorization"] ?? (options?.apiKeyAsBearer && headers["api-key"] ? `Bearer ${headers["api-key"]}` : "");
		busy = true;
		let connection;
		try {
			connection = await getConnection(authorization, headers, init?.signal);
		} catch (err) {
			busy = false;
			throw err;
		}
		const { stream: _stream, background: _background, ...requestBody } = body;
		const encoder = new TextEncoder();
		let cleanupActiveStream;
		const responseStream = new ReadableStream({
			start(controller) {
				let cleanedUp = false;
				let abortHandler;
				function cleanup({ closeSocket = false } = {}) {
					if (cleanedUp) return;
					cleanedUp = true;
					connection.off("message", onMessage);
					connection.off("error", onError);
					connection.off("close", onClose);
					if (abortHandler) {
						init?.signal?.removeEventListener("abort", abortHandler);
						abortHandler = void 0;
					}
					if (closeSocket && ws === connection) {
						connection.close();
						ws = null;
						connectionKey = null;
					}
					busy = false;
					cleanupActiveStream = void 0;
				}
				cleanupActiveStream = cleanup;
				function onMessage(data) {
					const text = data.toString();
					controller.enqueue(encoder.encode(formatSSEData(text)));
					try {
						const event = JSON.parse(text);
						if (isTerminalWebSocketEvent(event)) {
							controller.enqueue(encoder.encode("data: [DONE]\n\n"));
							cleanup({ closeSocket: shouldReconnectAfterEvent(event) });
							controller.close();
						}
					} catch {}
				}
				function onError(err) {
					cleanup();
					controller.error(err);
				}
				function onClose() {
					cleanup();
					try {
						controller.close();
					} catch {}
				}
				connection.on("message", onMessage);
				connection.on("error", onError);
				connection.on("close", onClose);
				const signal = init?.signal;
				if (signal) {
					if (signal.aborted) {
						cleanup({ closeSocket: true });
						controller.error(signal.reason ?? new DOMException("Aborted", "AbortError"));
						return;
					}
					abortHandler = () => {
						cleanup({ closeSocket: true });
						try {
							controller.error(signal.reason ?? new DOMException("Aborted", "AbortError"));
						} catch {}
					};
					signal.addEventListener("abort", abortHandler, { once: true });
				}
				connection.send(JSON.stringify({
					type: "response.create",
					...requestBody
				}));
			},
			cancel() {
				cleanupActiveStream?.({ closeSocket: true });
			}
		});
		return new Response(responseStream, {
			status: 200,
			headers: { "content-type": "text/event-stream" }
		});
	}
	return Object.assign(websocketFetch, { 
	/** Close the underlying WebSocket connection. */
close() {
		if (ws) {
			ws.close();
			ws = null;
		}
		connectionKey = null;
		connecting = null;
	} });
}
function isResponsesUrl(url) {
	try {
		return new URL(url).pathname.endsWith("/responses");
	} catch {
		return url.split("?")[0]?.endsWith("/responses") ?? false;
	}
}
function getWebSocketUrl(url, apiKeyQueryParam, apiKey) {
	if (!apiKeyQueryParam || !apiKey) return url;
	const parsedUrl = new URL(url);
	parsedUrl.searchParams.set(apiKeyQueryParam, apiKey);
	return parsedUrl.toString();
}
function formatSSEData(text) {
	return `${text.split(/\r?\n/).map((line) => `data: ${line}`).join("\n")}\n\n`;
}
function buildConnectionKey(authorization, headers, queryCredential = "") {
	return JSON.stringify({
		authorization,
		queryCredential,
		headers: Object.entries(headers).sort(([a], [b]) => a.localeCompare(b))
	});
}
function isTerminalWebSocketEvent(event) {
	return typeof event === "object" && event !== null && "type" in event && typeof event.type === "string" && TERMINAL_RESPONSE_EVENTS.has(event.type);
}
function shouldReconnectAfterEvent(event) {
	if (typeof event !== "object" || event === null || !("error" in event)) return false;
	const error = event.error;
	return typeof error === "object" && error !== null && "code" in error && error.code === "websocket_connection_limit_reached";
}
function getAbortError(signal) {
	return signal?.reason ?? new DOMException("Aborted", "AbortError");
}
function normalizeHeaders(headers) {
	const result = {};
	if (!headers) return result;
	if (headers instanceof Headers) headers.forEach((value, key) => {
		result[key.toLowerCase()] = value;
	});
	else if (Array.isArray(headers)) for (const [key, value] of headers) result[key.toLowerCase()] = value;
	else for (const [key, value] of Object.entries(headers)) if (value != null) result[key.toLowerCase()] = value;
	return result;
}
// src/llm/model/gateways/azure.ts
function isRecord(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
function mirrorAzureProviderOptionsForOpenAI(providerOptions) {
	if (!isRecord(providerOptions) || !isRecord(providerOptions.azure)) return providerOptions;
	const openai = isRecord(providerOptions.openai) ? providerOptions.openai : {};
	return {
		...providerOptions,
		openai: {
			...openai,
			...providerOptions.azure
		}
	};
}
function mirrorAzureResponseProviderOptions(prompt) {
	let promptModified = false;
	const mirroredPrompt = prompt.map((message) => {
		const messageWithProviderOptions = message;
		const providerOptions = mirrorAzureProviderOptionsForOpenAI(messageWithProviderOptions.providerOptions);
		const providerOptionsModified = providerOptions !== messageWithProviderOptions.providerOptions;
		if (!Array.isArray(message.content)) {
			if (providerOptionsModified) {
				promptModified = true;
				return {
					...message,
					providerOptions
				};
			}
			return message;
		}
		let contentModified = false;
		const content = message.content.map((part) => {
			if (!("providerOptions" in part)) return part;
			const providerOptions = mirrorAzureProviderOptionsForOpenAI(part.providerOptions);
			if (providerOptions === part.providerOptions) return part;
			contentModified = true;
			return {
				...part,
				providerOptions
			};
		});
		if (!contentModified) {
			if (providerOptionsModified) {
				promptModified = true;
				return {
					...message,
					providerOptions
				};
			}
			return message;
		}
		promptModified = true;
		return {
			...message,
			...providerOptionsModified ? { providerOptions } : {},
			content
		};
	});
	return promptModified ? mirroredPrompt : prompt;
}
function withAzureResponsesInputCompatibility(model) {
	return new Proxy(model, { get(target, property, receiver) {
		if (property === "doGenerate") return (options) => target.doGenerate(prepareAzureStrictToolSchemas({
			...options,
			providerOptions: mirrorAzureProviderOptionsForOpenAI(options.providerOptions),
			prompt: mirrorAzureResponseProviderOptions(options.prompt)
		}));
		if (property === "doStream") return (options) => target.doStream(prepareAzureStrictToolSchemas({
			...options,
			providerOptions: mirrorAzureProviderOptionsForOpenAI(options.providerOptions),
			prompt: mirrorAzureResponseProviderOptions(options.prompt)
		}));
		return Reflect.get(target, property, receiver);
	} });
}
var AzureOpenAIGateway = class extends MastraModelGateway {
	config;
	id = "azure-openai";
	name = "azure-openai";
	tokenCache = new InMemoryServerCache();
	entraIdTokenRequests = /* @__PURE__ */ new Map();
	constructor(config) {
		super();
		this.config = config;
		this.validateConfig();
	}
	validateConfig() {
		if (!this.config.resourceName) throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "resourceName is required for Azure OpenAI gateway"
		});
		if (!this.config.apiKey && this.config.authentication?.type !== "entraId") throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "apiKey or Entra ID authentication is required for Azure OpenAI gateway"
		});
		if (this.config.authentication?.type === "entraId" && !this.config.authentication.credential) throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "credential is required for Azure OpenAI Entra ID authentication"
		});
		if (this.config.apiKey && this.config.authentication?.type === "entraId") console.warn("[AzureOpenAIGateway] Both apiKey and Entra ID authentication provided. Using Entra ID authentication and ignoring apiKey.");
		if (this.config.useResponsesAPI && this.config.useDeploymentBasedUrls === true) throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "useResponsesAPI: true cannot be combined with useDeploymentBasedUrls: true. Omit useDeploymentBasedUrls or set it to false."
		});
		if (this.config.useResponsesAPI && this.config.apiVersion && !["v1", "preview"].includes(this.config.apiVersion)) throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "useResponsesAPI: true requires apiVersion: \"v1\" or apiVersion: \"preview\". Omit apiVersion to use \"v1\"."
		});
		if (this.config.useDeploymentBasedUrls === false && this.config.apiVersion && !["v1", "preview"].includes(this.config.apiVersion)) throw new MastraError({
			id: "AZURE_GATEWAY_INVALID_CONFIG",
			domain: "LLM",
			category: "UNKNOWN",
			text: "useDeploymentBasedUrls: false requires apiVersion: \"v1\" or apiVersion: \"preview\". Omit apiVersion to use \"v1\"."
		});
		const hasDeployments = this.config.deployments && this.config.deployments.length > 0;
		const hasManagement = this.config.management !== void 0;
		if (hasDeployments && hasManagement) console.warn("[AzureOpenAIGateway] Both deployments and management credentials provided. Using static deployments list and ignoring management API.");
		if (hasManagement) this.getManagementCredentials(this.config.management);
	}
	async fetchProviders() {
		if (this.config.deployments && this.config.deployments.length > 0) return { "azure-openai": {
			apiKeyEnvVar: [],
			apiKeyHeader: "api-key",
			name: "Azure OpenAI",
			models: this.config.deployments,
			docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
			gateway: "azure-openai"
		} };
		if (!this.config.management) return { "azure-openai": {
			apiKeyEnvVar: [],
			apiKeyHeader: "api-key",
			name: "Azure OpenAI",
			models: [],
			docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
			gateway: "azure-openai"
		} };
		try {
			const credentials = this.getManagementCredentials(this.config.management);
			const token = await this.getAzureADToken({
				tenantId: credentials.tenantId,
				clientId: credentials.clientId,
				clientSecret: credentials.clientSecret
			});
			return { "azure-openai": {
				apiKeyEnvVar: [],
				apiKeyHeader: "api-key",
				name: "Azure OpenAI",
				models: (await this.fetchDeployments(token, {
					subscriptionId: credentials.subscriptionId,
					resourceGroup: credentials.resourceGroup,
					resourceName: this.config.resourceName
				})).map((d) => d.name),
				docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
				gateway: "azure-openai"
			} };
		} catch (error) {
			const errorMsg = error instanceof Error ? error.message : String(error);
			console.warn(`[AzureOpenAIGateway] Deployment discovery failed: ${errorMsg}`, "\nReturning fallback configuration. Azure OpenAI can still be used by manually specifying deployment names.");
			return { "azure-openai": {
				apiKeyEnvVar: [],
				apiKeyHeader: "api-key",
				name: "Azure OpenAI",
				models: [],
				docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
				gateway: "azure-openai"
			} };
		}
	}
	getManagementCredentials(management) {
		const { tenantId, clientId, clientSecret, subscriptionId, resourceGroup } = management;
		const missing = [];
		if (!tenantId) missing.push("tenantId");
		if (!clientId) missing.push("clientId");
		if (!clientSecret) missing.push("clientSecret");
		if (!subscriptionId) missing.push("subscriptionId");
		if (!resourceGroup) missing.push("resourceGroup");
		if (missing.length > 0) throw new MastraError({
			id: "AZURE_MANAGEMENT_CREDENTIALS_MISSING",
			domain: "LLM",
			category: "UNKNOWN",
			text: `Management credentials incomplete. Missing: ${missing.join(", ")}. Required fields: tenantId, clientId, clientSecret, subscriptionId, resourceGroup.`
		});
		return {
			tenantId,
			clientId,
			clientSecret,
			subscriptionId,
			resourceGroup
		};
	}
	async getAzureADToken(credentials) {
		const { tenantId, clientId, clientSecret } = credentials;
		const cacheKey = `azure-mgmt-token:${tenantId}:${clientId}`;
		const cached = await this.tokenCache.get(cacheKey);
		if (cached && cached.expiresAt > Date.now() / 1e3 + 60) return cached.token;
		const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
		const body = new URLSearchParams({
			grant_type: "client_credentials",
			client_id: clientId,
			client_secret: clientSecret,
			scope: "https://management.azure.com/.default"
		});
		const response = await fetch(tokenEndpoint, {
			method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded" },
			body: body.toString()
		});
		if (!response.ok) {
			const error = await response.text();
			throw new MastraError({
				id: "AZURE_AD_TOKEN_ERROR",
				domain: "LLM",
				category: "UNKNOWN",
				text: `Failed to get Azure AD token: ${response.status} ${error}`
			});
		}
		const tokenResponse = await response.json();
		const expiresAt = Math.floor(Date.now() / 1e3) + tokenResponse.expires_in;
		await this.tokenCache.set(cacheKey, {
			token: tokenResponse.access_token,
			expiresAt
		});
		return tokenResponse.access_token;
	}
	async fetchDeployments(token, credentials) {
		const { subscriptionId, resourceGroup, resourceName } = credentials;
		let url = `https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.CognitiveServices/accounts/${resourceName}/deployments?api-version=2024-10-01`;
		const allDeployments = [];
		while (url) {
			const response = await fetch(url, { headers: {
				Authorization: `Bearer ${token}`,
				"Content-Type": "application/json"
			} });
			if (!response.ok) {
				const error = await response.text();
				throw new MastraError({
					id: "AZURE_DEPLOYMENTS_FETCH_ERROR",
					domain: "LLM",
					category: "UNKNOWN",
					text: `Failed to fetch Azure deployments: ${response.status} ${error}`
				});
			}
			const data = await response.json();
			allDeployments.push(...data.value);
			url = data.nextLink;
		}
		return allDeployments.filter((d) => d.properties.provisioningState === "Succeeded");
	}
	buildUrl(_routerId, _envVars) {}
	async getApiKey(_modelId) {
		return this.config.authentication?.type === "entraId" ? "" : this.config.apiKey ?? "";
	}
	async getEntraIdToken() {
		if (this.config.authentication?.type !== "entraId") throw new MastraError({
			id: "AZURE_ENTRA_ID_AUTH_NOT_CONFIGURED",
			domain: "LLM",
			category: "UNKNOWN",
			text: "Entra ID authentication is not configured for Azure OpenAI gateway"
		});
		const scope = this.config.authentication.scope ?? "https://cognitiveservices.azure.com/.default";
		const cacheKey = `azure-openai-token:${scope}`;
		const cached = await this.tokenCache.get(cacheKey);
		if (cached && cached.expiresAt > Date.now() / 1e3 + 60) return cached.token;
		let tokenRequest = this.entraIdTokenRequests.get(cacheKey);
		if (!tokenRequest) {
			tokenRequest = this.fetchEntraIdToken(scope, cacheKey);
			this.entraIdTokenRequests.set(cacheKey, tokenRequest);
		}
		try {
			return (await tokenRequest).token;
		} finally {
			this.entraIdTokenRequests.delete(cacheKey);
		}
	}
	async fetchEntraIdToken(scope, cacheKey) {
		if (this.config.authentication?.type !== "entraId") throw new MastraError({
			id: "AZURE_ENTRA_ID_AUTH_NOT_CONFIGURED",
			domain: "LLM",
			category: "UNKNOWN",
			text: "Entra ID authentication is not configured for Azure OpenAI gateway"
		});
		const accessToken = await this.config.authentication.credential.getToken(scope);
		if (!accessToken?.token) throw new MastraError({
			id: "AZURE_ENTRA_ID_TOKEN_ERROR",
			domain: "LLM",
			category: "UNKNOWN",
			text: "Failed to get Entra ID token for Azure OpenAI gateway"
		});
		const token = {
			token: accessToken.token,
			expiresAt: accessToken.expiresOnTimestamp ? Math.floor(accessToken.expiresOnTimestamp / 1e3) : Math.floor(Date.now() / 1e3) + 300
		};
		await this.tokenCache.set(cacheKey, token);
		return token;
	}
	createEntraIdFetch(innerFetch = fetch) {
		return async (input, init) => {
			const token = await this.getEntraIdToken();
			const headers = new Headers(init?.headers);
			headers.delete("api-key");
			headers.set("Authorization", `Bearer ${token}`);
			return innerFetch(input, {
				...init,
				headers
			});
		};
	}
	createAzureResponsesWebSocketFetch({ useEntraId, responsesWebSocket }) {
		const websocketFetch = createOpenAIWebSocketFetch({
			url: responsesWebSocket?.url ?? `wss://${this.config.resourceName}.openai.azure.com/openai/v1/responses`,
			headers: responsesWebSocket?.headers,
			apiKeyQueryParam: useEntraId ? false : "api-key",
			betaHeader: false
		});
		return useEntraId ? Object.assign(this.createEntraIdFetch(websocketFetch), { close: websocketFetch.close }) : websocketFetch;
	}
	async resolveLanguageModel({ modelId, apiKey, headers, transport, responsesWebSocket }) {
		const useResponsesAPI = this.config.useResponsesAPI ?? false;
		const apiVersion = this.config.apiVersion || (useResponsesAPI || this.config.useDeploymentBasedUrls === false ? "v1" : "2024-04-01-preview");
		const useDeploymentBasedUrls = this.config.useDeploymentBasedUrls ?? !useResponsesAPI;
		const useEntraId = this.config.authentication?.type === "entraId";
		const websocketFetch = useResponsesAPI && transport === "websocket" ? this.createAzureResponsesWebSocketFetch({
			useEntraId,
			responsesWebSocket
		}) : void 0;
		const azureConfig = {
			resourceName: this.config.resourceName,
			apiKey: useEntraId ? "" : apiKey,
			apiVersion,
			useDeploymentBasedUrls,
			headers: {
				"User-Agent": MASTRA_USER_AGENT,
				...headers
			},
			...websocketFetch && !useEntraId ? { fetch: websocketFetch } : {}
		};
		const azureProvider = createAzure(useEntraId ? {
			...azureConfig,
			fetch: websocketFetch ?? this.createEntraIdFetch()
		} : azureConfig);
		if (useResponsesAPI) {
			const model = withAzureResponsesInputCompatibility(azureProvider.responses(modelId));
			if (websocketFetch) Object.defineProperty(model, MASTRA_GATEWAY_STREAM_TRANSPORT, {
				configurable: true,
				value: {
					type: "openai-websocket",
					close: websocketFetch.close
				}
			});
			return model;
		}
		return azureProvider(modelId);
	}
};
// src/llm/model/gateways/gateway-manager.ts
/**
* MastraError IDs that represent expected "auth not available" states —
* missing credentials, missing gateway config, or no matching gateway.
* These are safe to surface as `hasAuth === false` for catalog/UI checks.
*/
const MISSING_AUTH_ERROR_IDS = /* @__PURE__ */ new Set([
	"MODEL_ROUTER_NO_GATEWAY_FOUND",
	"MASTRA_GATEWAY_NO_API_KEY",
	"NETLIFY_GATEWAY_NO_TOKEN",
	"NETLIFY_GATEWAY_NO_SITE_ID",
	"AZURE_ENTRA_ID_AUTH_NOT_CONFIGURED"
]);
/**
* Returns true for errors that represent an expected "auth not available"
* state (no matching gateway, missing credentials/env vars, missing provider
* config). Real gateway failures (token exchange errors, network bugs,
* malformed auth hooks) are not matched here so {@link hasAuth} can re-throw
* them instead of silently hiding them.
*/
function isExpectedMissingAuthError(error) {
	if (error instanceof MastraError) return MISSING_AUTH_ERROR_IDS.has(error.id);
	if (error instanceof Error) {
		const msg = error.message;
		return /Missing [^ ]+ environment variable/i.test(msg) || /Could not find API key/i.test(msg) || /no api key/i.test(msg) || /Could not find config for provider/i.test(msg) || /Could not identify provider/i.test(msg);
	}
	return false;
}
/**
* Centralises the gateway-chain operations shared between
* {@link ModelRouterLanguageModel} and the AgentController: gateway merging, model
* routing, auth resolution, and provider/model listing.
*
* The manager owns the *gateway registry* (which gateway owns a model, auth
* resolution through the chain). Per-instance concerns (explicit config,
* model-instance caching, websocket/transport, doGenerate/doStream) remain in
* the consumers.
*/
var GatewayManager = class GatewayManager {
	gateways;
	constructor(gateways = []) {
		const seen = /* @__PURE__ */ new Set();
		this.gateways = gateways.filter((gateway) => {
			if (!shouldEnableGateway(gateway)) return false;
			const id = getGatewayId(gateway);
			if (seen.has(id)) return false;
			seen.add(id);
			return true;
		});
	}
	/**
	* Returns the gateway prefix used for model-id parsing.
	* `models.dev` is a provider registry and doesn't use a prefix.
	*/
	static getPrefix(gatewayId) {
		return gatewayId === "models.dev" ? void 0 : gatewayId;
	}
	/**
	* Returns the prefix to use when parsing `routerId` for the given gateway.
	* A gateway may claim an unprefixed id (e.g. `handlesModel` matching a bare
	* `anthropic/...` id); in that case the gateway's prefix does not appear in
	* the id, so parse it as an unprefixed `provider/model` id.
	*/
	static getPrefixForId(gatewayId, routerId) {
		const prefix = GatewayManager.getPrefix(gatewayId);
		if (prefix && !routerId.startsWith(`${prefix}/`)) return;
		return prefix;
	}
	/** Find the gateway that handles a given model/router id. */
	findGatewayForModel(routerId) {
		return findGatewayForModel(routerId, this.gateways);
	}
	/**
	* Resolve the gateway and parsed provider/model components for a router id
	* in a single pass. Centralises gateway selection + id parsing so callers
	* (router constructor, doGenerate/doStream, supportedUrls) don't each
	* re-derive the gateway and prefix separately.
	*/
	resolveModelId(routerId) {
		const gateway = this.findGatewayForModel(routerId);
		const gatewayId = getGatewayId(gateway);
		const { providerId, modelId } = parseModelRouterId(routerId, GatewayManager.getPrefixForId(gatewayId, routerId));
		return {
			gateway,
			gatewayId,
			providerId,
			modelId
		};
	}
	/** Parse a router id into its provider/model/gateway components. */
	parseModelId(routerId) {
		const { gatewayId, providerId, modelId } = this.resolveModelId(routerId);
		return {
			providerId,
			modelId,
			gatewayId
		};
	}
	/**
	* Resolve auth through the gateway chain: select the gateway via
	* {@link findGatewayForModel}, try its `resolveAuth()` (OAuth / stored
	* credentials), and fall back to `getApiKey()` (which, for registry /
	* openai-compatible providers, reads the API-key env var).
	*
	* The caller is responsible for merging any explicit headers/credentials
	* from per-instance config on top of the result returned here.
	*/
	async resolveAuth(routerId) {
		const { gateway, gatewayId, providerId, modelId } = this.resolveModelId(routerId);
		const request = {
			gatewayId,
			providerId,
			modelId,
			routerId
		};
		const rawGatewayAuth = await gateway.resolveAuth?.(request);
		const gatewayAuth = rawGatewayAuth?.bearerToken ? {
			...rawGatewayAuth,
			headers: {
				...rawGatewayAuth.headers,
				Authorization: `Bearer ${rawGatewayAuth.bearerToken}`
			}
		} : rawGatewayAuth;
		if (hasAuthCredentials(gatewayAuth)) return {
			...gatewayAuth,
			source: gatewayAuth.source ?? "gateway"
		};
		return {
			apiKey: await gateway.getApiKey(routerId),
			source: "legacy"
		};
	}
	/**
	* Convenience: whether auth is available for a model.
	* Returns `false` for expected missing-auth states (no matching gateway,
	* missing credentials/env vars) but re-throws unexpected errors (token
	* exchange failures, network bugs, malformed auth hooks) so they surface
	* instead of being silently hidden.
	*/
	async hasAuth(routerId) {
		try {
			const auth = await this.resolveAuth(routerId);
			return hasAuthCredentials(auth);
		} catch (error) {
			if (isExpectedMissingAuthError(error)) return false;
			throw error;
		}
	}
	/**
	* Fetch and flatten providers from all gateways, deduped by provider key
	* (configured / earlier gateway wins). Each gateway's `fetchProviders()`
	* is a network call for gateways like models.dev / Netlify.
	*/
	async listProviders() {
		const entries = [];
		for (const gateway of this.gateways) entries.push({
			gateway,
			providers: await this.fetchGatewayProviders(gateway) ?? {}
		});
		return this.mergeProviders(entries);
	}
	/**
	* Fetch one gateway's providers. Returns `undefined` (after logging) when the
	* gateway fails, so callers can tell a failure apart from an empty list.
	*/
	async fetchGatewayProviders(gateway) {
		try {
			return await gateway.fetchProviders();
		} catch (error) {
			console.warn(`Failed to load providers from gateway ${getGatewayId(gateway)}:`, error);
			return;
		}
	}
	/**
	* Flatten per-gateway providers into one registry keyed by catalog provider
	* id. Pass entries in gateway order: the earlier (configured) gateway wins.
	*/
	mergeProviders(entries) {
		const registry = {};
		for (const { gateway, providers } of entries) for (const [providerId, config] of Object.entries(providers)) {
			const key = this.getProviderKey(gateway, providerId);
			if (key in registry) continue;
			registry[key] = {
				...config,
				gateway: getGatewayId(gateway)
			};
		}
		return registry;
	}
	/**
	* Build the model catalog from gateway providers, resolving auth per
	* provider (using the first model). Returns models without use-count.
	*/
	async listAvailableModels() {
		return this.listModelsForProviders(await this.listProviders());
	}
	/**
	* Build catalog entries for an already-fetched provider registry (see
	* {@link mergeProviders}), resolving auth once per provider.
	*/
	async listModelsForProviders(registry) {
		const models = [];
		for (const [provider, providerConfig] of Object.entries(registry)) {
			const apiKeyEnvVar = Array.isArray(providerConfig.apiKeyEnvVar) ? providerConfig.apiKeyEnvVar[0] : providerConfig.apiKeyEnvVar;
			const modelNames = providerConfig.models;
			if (!Array.isArray(modelNames)) continue;
			const hasApiKey = modelNames[0] ? await this.hasAuth(`${provider}/${modelNames[0]}`) : false;
			for (const modelName of modelNames) models.push({
				id: `${provider}/${modelName}`,
				provider,
				modelName,
				releaseDate: providerConfig.modelReleaseDates?.[modelName],
				hasApiKey,
				apiKeyEnvVar: apiKeyEnvVar || void 0
			});
		}
		return models;
	}
	/** Provider key used for catalog ids: prefix with the gateway id unless it's the prefix-less models.dev registry. */
	getProviderKey(gateway, providerId) {
		const gatewayId = getGatewayId(gateway);
		if (gatewayId === "models.dev") return providerId;
		return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;
	}
};
// src/llm/model/mastra-gateway-provider-tools.ts
const OPENROUTER_WEB_SEARCH_TOOL_ID = "openrouter.web_search";
const NATIVE_WEB_SEARCH_TOOL_IDS = {
	"openai.web_search": true,
	"anthropic.web_search_20250305": true,
	"google.google_search": true,
	"xai.web_search": true
};
/** True for the gateway's OpenRouter chat models, false for its native Anthropic OAuth models. */
function isOpenRouterModel(model) {
	return typeof model.provider === "string" && (model.provider === "openrouter" || model.provider.startsWith("openrouter."));
}
/**
* The Mastra gateway's chat endpoint only runs `openrouter:*` server tools. Another provider's
* native tool is rejected with a 400 (OpenAI, xAI models) or dropped without an error (Anthropic,
* Google models), so the model silently loses the tool.
*
* A native web search tool with no arguments is swapped for the gateway's web search, which works
* for every tool-calling model. Any other native tool fails here with an actionable message.
*/
function prepareToolsForMastraGateway(options, routerId) {
	const isProviderTool = (tool) => tool.type === "provider-defined" || tool.type === "provider";
	if (!options.tools?.some(isProviderTool)) return options;
	const tools = options.tools.map((tool) => {
		if (!isProviderTool(tool)) return tool;
		const { id, args } = tool;
		if (id.startsWith("openrouter.")) return tool;
		const isWebSearch = id in NATIVE_WEB_SEARCH_TOOL_IDS;
		if (isWebSearch && Object.keys(args ?? {}).length === 0) return {
			...tool,
			id: OPENROUTER_WEB_SEARCH_TOOL_ID
		};
		throw new MastraError({
			id: "MASTRA_GATEWAY_UNSUPPORTED_PROVIDER_TOOL",
			domain: ErrorDomain.LLM,
			category: ErrorCategory.USER,
			details: {
				toolId: id,
				model: routerId
			},
			text: `The provider tool "${id}" cannot be used with "${routerId}". The Mastra gateway only runs its own server tools. ` + (isWebSearch ? `Its web search does not accept "${id}" options: use webSearchTool from @mastra/core/tools, or call the provider directly to keep them.` : `Call the provider directly to use this tool.`)
		});
	});
	return {
		...options,
		tools
	};
}
// src/llm/model/router.ts
/**
* Type guard to check if a model is a LanguageModelV4 (AI SDK v7)
*/
function isLanguageModelV4(model) {
	return model.specificationVersion === "v4";
}
/**
* Type guard to check if a model is a LanguageModelV3 (AI SDK v6)
*/
function isLanguageModelV3(model) {
	return model.specificationVersion === "v3";
}
const OPENAI_WS_ALLOWLIST = /* @__PURE__ */ new Set(["openai"]);
const OPENAI_API_HOST = "api.openai.com";
let cacheKeyHmacSecret;
function createGatewayModelCache() {
	return {
		modelInstances: /* @__PURE__ */ new Map(),
		webSocketFetches: /* @__PURE__ */ new Map(),
		gatewayStreamTransports: /* @__PURE__ */ new Map()
	};
}
function getOpenAITransport(providerOptions, providerId) {
	const transportOptions = providerId === "azure-openai" ? providerOptions?.azure : providerOptions?.openai;
	return {
		transport: transportOptions?.transport ?? "fetch",
		websocket: transportOptions?.websocket
	};
}
function isOpenAIBaseUrl(baseURL) {
	if (!baseURL) return true;
	try {
		return new URL(baseURL).hostname === OPENAI_API_HOST;
	} catch {
		return false;
	}
}
function stableHeaderKey(headers) {
	if (!headers) return "";
	const entries = Object.entries(headers);
	if (entries.length === 0) return "";
	return JSON.stringify(entries.sort(([a], [b]) => a.localeCompare(b)));
}
function mergeHeaders(baseHeaders, authHeaders) {
	if (!baseHeaders && !authHeaders) return void 0;
	return {
		...baseHeaders,
		...authHeaders
	};
}
var ModelRouterLanguageModel = class ModelRouterLanguageModel {
	specificationVersion = "v2";
	defaultObjectGenerationMode = "json";
	supportsStructuredOutputs = true;
	supportsImageUrls = true;
	/**
	* Supported URL patterns by media type for the provider.
	* This is a lazy promise that resolves the underlying model's supportedUrls.
	* Models like Mistral define which URL patterns they support (e.g., application/pdf for https URLs).
	*
	* @see https://github.com/mastra-ai/mastra/issues/12152
	*/
	supportedUrls;
	modelId;
	provider;
	gatewayId;
	/** Full `provider/model` router ID, when the ID alone resolves this model's route. */
	id;
	config;
	gateway;
	_supportedUrlsPromise = null;
	instanceGatewayCache = createGatewayModelCache();
	hasCustomGateways;
	#lastStreamTransport;
	#manager;
	constructor(config, customGateways) {
		this.hasCustomGateways = Boolean(customGateways?.length);
		let normalizedConfig;
		if (typeof config === "string") normalizedConfig = { id: config };
		else if ("providerId" in config && "modelId" in config) normalizedConfig = {
			id: `${config.providerId}/${config.modelId}`,
			url: config.url,
			apiKey: config.apiKey,
			headers: config.headers,
			api: config.api
		};
		else normalizedConfig = {
			id: config.id,
			url: config.url,
			apiKey: config.apiKey,
			headers: config.headers,
			api: config.api
		};
		const parsedConfig = {
			...normalizedConfig,
			routerId: normalizedConfig.id
		};
		this.#manager = new GatewayManager([...customGateways ?? [], ...defaultGateways]);
		const resolved = this.#manager.resolveModelId(normalizedConfig.id);
		this.gateway = resolved.gateway;
		this.gatewayId = resolved.gatewayId;
		this.provider = resolved.providerId || "openai-compatible";
		if (resolved.providerId && resolved.modelId !== normalizedConfig.id) parsedConfig.id = resolved.modelId;
		this.modelId = parsedConfig.id;
		this.config = parsedConfig;
		if (!this.hasCustomGateways && !parsedConfig.url && !parsedConfig.apiKey && !parsedConfig.headers && !parsedConfig.api) this.id = parsedConfig.routerId;
		const self = this;
		this.supportedUrls = { then(onfulfilled, onrejected) {
			return self._resolveSupportedUrls().then(onfulfilled, onrejected);
		} };
	}
	/**
	* Lazily resolves the underlying model's supportedUrls.
	* This is cached to avoid multiple model resolutions.
	* @internal
	*/
	async _resolveSupportedUrls() {
		if (this._supportedUrlsPromise) return this._supportedUrlsPromise;
		const supportedUrlsPromise = this._fetchSupportedUrls().catch((error) => {
			console.warn(`[ModelRouter] Failed to resolve supportedUrls for "${this.config.routerId}". Retrying on next access.`, error);
			if (this._supportedUrlsPromise === supportedUrlsPromise) this._supportedUrlsPromise = null;
			return {};
		});
		this._supportedUrlsPromise = supportedUrlsPromise;
		return supportedUrlsPromise;
	}
	/**
	* Fetches supportedUrls from the underlying model.
	* @internal
	*/
	async _fetchSupportedUrls() {
		const resolved = this.#manager.resolveModelId(this.config.routerId);
		const auth = await this.resolveAuth(resolved.providerId, resolved.modelId);
		const modelSupportedUrls = (await this.resolveLanguageModel({
			apiKey: auth.apiKey ?? "",
			auth,
			headers: mergeHeaders(this.config.headers, auth.headers),
			...resolved
		})).supportedUrls;
		if (!modelSupportedUrls) return {};
		if (typeof modelSupportedUrls.then === "function") return await modelSupportedUrls ?? {};
		return modelSupportedUrls ?? {};
	}
	/**
	* Resolves the provider id of the model this router calls, e.g. `groq.chat` or `openai.responses`.
	* `provider` only names the gateway's provider (`groq`, `openai`), which doesn't tell a Chat
	* Completions endpoint from a Responses one. Returns `undefined` when the model can't be resolved
	* (e.g. a missing API key); the model call reports that error itself.
	*/
	async resolveApiProviderId() {
		try {
			const resolved = this.#manager.resolveModelId(this.config.routerId);
			const auth = await this.resolveAuth(resolved.providerId, resolved.modelId);
			return (await this.resolveLanguageModel({
				apiKey: auth.apiKey ?? "",
				auth,
				headers: mergeHeaders(this.config.headers, auth.headers),
				trackStreamTransport: false,
				...resolved
			})).provider;
		} catch {
			return;
		}
	}
	/**
	* Whether the Mastra gateway serves Observational Memory for this model's resolved credential.
	*
	* Gateway models do not all get memory from the gateway: only a Gateway project key routes
	* through the memory-aware gateway, while organization keys (`msk-gateway-…`, `mskv2_…`) are
	* served by a gateway without the memory API. Callers that would otherwise skip local memory
	* processing for gateway models (the Observational Memory processor) use this to tell the two
	* apart.
	*
	* Returns `false` for a model that isn't on the Mastra gateway. A credential that cannot be
	* resolved is thrown rather than reported as local memory: the model call resolves its
	* credential through this same path, so answering "local" when the lookup failed is how the
	* gateway and the local store both end up saving the same conversation. That includes a missing
	* credential (`MASTRA_GATEWAY_NO_API_KEY`, an unset environment variable) — the gateway may
	* serve memory as soon as the credential resolves, so the ownership check stops the run instead
	* of guessing.
	*/
	async isGatewayMemoryManaged() {
		if (this.gatewayId !== "mastra") return false;
		const resolved = this.#manager.resolveModelId(this.config.routerId);
		const auth = await this.resolveAuth(resolved.providerId, resolved.modelId);
		return gatewayServesObservationalMemory(auth.apiKey);
	}
	/** @internal */
	_getStreamTransport() {
		return this.#lastStreamTransport;
	}
	/**
	* Custom serialization for tracing/observability spans.
	* Excludes `config` (holds apiKey, headers, url) and `gateway`
	* (may hold proxy credentials or cached tokens) so they cannot leak
	* into telemetry backends.
	*/
	serializeForSpan() {
		return {
			specificationVersion: this.specificationVersion,
			modelId: this.modelId,
			provider: this.provider,
			gatewayId: this.gatewayId
		};
	}
	getGatewayCache() {
		let cache = ModelRouterLanguageModel.gatewayCaches.get(this.gateway);
		if (!cache) {
			cache = createGatewayModelCache();
			ModelRouterLanguageModel.gatewayCaches.set(this.gateway, cache);
		}
		return cache;
	}
	shouldUseInstanceGatewayCache(auth) {
		return this.config.apiKey !== void 0 || auth.source === "explicit" || auth.source === "gateway";
	}
	setStreamTransportHandle({ resolvedTransport, transport, responsesWebSocket }) {
		if (resolvedTransport !== "websocket") {
			this.#lastStreamTransport = void 0;
			return;
		}
		if (!transport) {
			this.#lastStreamTransport = void 0;
			return;
		}
		this.#lastStreamTransport = {
			type: transport.type,
			close: transport.close,
			closeOnFinish: responsesWebSocket?.closeOnFinish ?? true
		};
	}
	async resolveAuth(_providerId, _modelId) {
		if (this.config.url) return {
			apiKey: this.config.apiKey ?? "",
			headers: this.config.headers,
			source: "explicit"
		};
		const explicitHeaders = this.config.headers;
		if (this.config.apiKey) return {
			apiKey: this.config.apiKey,
			headers: explicitHeaders,
			source: "explicit"
		};
		const gatewayAuth = await this.#manager.resolveAuth(this.config.routerId);
		return explicitHeaders ? {
			...gatewayAuth,
			headers: {
				...explicitHeaders,
				...gatewayAuth.headers
			}
		} : gatewayAuth;
	}
	setStreamTransportFromCache({ cache, resolvedTransport, key, responsesWebSocket }) {
		const wsFetch = cache.webSocketFetches.get(key);
		const gatewayTransport = cache.gatewayStreamTransports.get(key);
		const transport = wsFetch ? {
			type: "openai-websocket",
			close: () => wsFetch.close()
		} : gatewayTransport;
		this.setStreamTransportHandle({
			resolvedTransport,
			transport,
			responsesWebSocket
		});
	}
	stripUnsupportedSamplingParams(options) {
		if (modelSupportsTemperature(this.config.routerId) !== false) return options;
		const { temperature, topP, topK, ...rest } = options;
		if (temperature === void 0 && topP === void 0 && topK === void 0) return options;
		return rest;
	}
	async doGenerate(options) {
		const resolved = this.#manager.resolveModelId(this.config.routerId);
		let auth;
		try {
			auth = await this.resolveAuth(resolved.providerId, resolved.modelId);
		} catch (error) {
			return { stream: new ReadableStream({ start(controller) {
				controller.enqueue({
					type: "error",
					error
				});
				controller.close();
			} }) };
		}
		let sanitizedOptions = this.stripUnsupportedSamplingParams(options);
		const model = await this.resolveLanguageModel({
			apiKey: auth.apiKey ?? "",
			auth,
			headers: mergeHeaders(this.config.headers, auth.headers),
			...resolved
		});
		if (this.gatewayId === "mastra" && isOpenRouterModel(model)) sanitizedOptions = prepareToolsForMastraGateway(sanitizedOptions, this.config.routerId);
		if (isLanguageModelV4(model)) return new AISDKV7LanguageModel(model).doGenerate(sanitizedOptions);
		if (isLanguageModelV3(model)) return new AISDKV6LanguageModel(model).doGenerate(sanitizedOptions);
		return new AISDKV5LanguageModel(model).doGenerate(sanitizedOptions);
	}
	async doStream(options) {
		const resolved = this.#manager.resolveModelId(this.config.routerId);
		let auth;
		try {
			auth = await this.resolveAuth(resolved.providerId, resolved.modelId);
		} catch (error) {
			return { stream: new ReadableStream({ start(controller) {
				controller.enqueue({
					type: "error",
					error
				});
				controller.close();
			} }) };
		}
		let sanitizedOptions = this.stripUnsupportedSamplingParams(options);
		const { transport, websocket } = getOpenAITransport(sanitizedOptions.providerOptions, resolved.providerId);
		const resolvedTransport = (transport === "auto" ? "websocket" : transport) === "websocket" && !this.config.url && (this.gatewayId === "models.dev" && OPENAI_WS_ALLOWLIST.has(this.provider) || this.gatewayId === "azure-openai") ? "websocket" : "fetch";
		const model = await this.resolveLanguageModel({
			apiKey: auth.apiKey ?? "",
			auth,
			headers: mergeHeaders(this.config.headers, auth.headers),
			transport: resolvedTransport,
			responsesWebSocket: websocket,
			...resolved
		});
		if (this.gatewayId === "mastra" && isOpenRouterModel(model)) sanitizedOptions = prepareToolsForMastraGateway(sanitizedOptions, this.config.routerId);
		const streamTransport = this.#lastStreamTransport;
		if (isLanguageModelV4(model)) {
			const streamResult = await new AISDKV7LanguageModel(model).doStream(sanitizedOptions);
			attachModelStreamTransport(streamResult, streamTransport);
			return streamResult;
		}
		if (isLanguageModelV3(model)) {
			const streamResult = await new AISDKV6LanguageModel(model).doStream(sanitizedOptions);
			attachModelStreamTransport(streamResult, streamTransport);
			return streamResult;
		}
		const streamResult = await new AISDKV5LanguageModel(model).doStream(sanitizedOptions);
		attachModelStreamTransport(streamResult, streamTransport);
		return streamResult;
	}
	static computeModelCacheKey({ gatewayId, modelId, providerId, url, apiKey, headersKey, resolvedTransport, websocketKey, authScopeKey, api }) {
		cacheKeyHmacSecret ??= Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
		return createHmac("sha256", cacheKeyHmacSecret).update(JSON.stringify([
			gatewayId,
			modelId,
			providerId,
			url,
			apiKey,
			headersKey,
			resolvedTransport,
			websocketKey,
			authScopeKey,
			api
		])).digest("hex");
	}
	async resolveLanguageModel({ modelId, providerId, apiKey, auth, headers, transport, responsesWebSocket, trackStreamTransport = true }) {
		const resolvedTransport = transport ?? "fetch";
		const websocketKey = resolvedTransport === "websocket" ? `${responsesWebSocket?.url ?? ""}:${stableHeaderKey(responsesWebSocket?.headers)}` : "";
		const useInstanceCache = this.shouldUseInstanceGatewayCache(auth);
		const cache = useInstanceCache ? this.instanceGatewayCache : this.getGatewayCache();
		const authScopeKey = useInstanceCache ? `${auth.source ?? ""}` : "";
		const key = ModelRouterLanguageModel.computeModelCacheKey({
			gatewayId: this.gatewayId,
			modelId,
			providerId,
			url: this.config.url || "",
			apiKey,
			headersKey: stableHeaderKey(headers),
			resolvedTransport,
			websocketKey,
			authScopeKey,
			api: this.config.api || "chat"
		});
		if (cache.modelInstances.has(key)) {
			if (trackStreamTransport) this.setStreamTransportFromCache({
				cache,
				resolvedTransport,
				key,
				responsesWebSocket
			});
			return cache.modelInstances.get(key);
		}
		if (this.config.url) {
			const modelInstance = this.config.api === "responses" ? createOpenAI({
				apiKey,
				baseURL: this.config.url,
				headers
			}).responses(modelId) : createOpenAICompatible({
				name: providerId,
				apiKey,
				baseURL: this.config.url,
				headers,
				supportsStructuredOutputs: true
			}).chatModel(modelId);
			cache.modelInstances.set(key, modelInstance);
			if (trackStreamTransport) this.setStreamTransportHandle({
				resolvedTransport,
				responsesWebSocket
			});
			return modelInstance;
		}
		if (resolvedTransport === "websocket" && providerId === "openai" && this.gatewayId === "models.dev") {
			const baseURL = await this.gateway.buildUrl(this.config.routerId, process.env);
			if (isOpenAIBaseUrl(baseURL)) {
				const { modelInstance, wsFetch } = this.resolveOpenAIWebSocketModel({
					modelId,
					apiKey,
					baseURL,
					headers,
					responsesWebSocket
				});
				cache.modelInstances.set(key, modelInstance);
				cache.webSocketFetches.set(key, wsFetch);
				this.setStreamTransportFromCache({
					cache,
					resolvedTransport,
					key,
					responsesWebSocket
				});
				return modelInstance;
			}
		}
		const modelInstance = await this.gateway.resolveLanguageModel({
			modelId,
			providerId,
			apiKey,
			headers,
			transport: resolvedTransport,
			responsesWebSocket
		});
		const gatewayTransport = readGatewayStreamTransport(modelInstance);
		cache.modelInstances.set(key, modelInstance);
		if (gatewayTransport) cache.gatewayStreamTransports.set(key, gatewayTransport);
		if (trackStreamTransport) this.setStreamTransportHandle({
			resolvedTransport,
			transport: gatewayTransport,
			responsesWebSocket
		});
		return modelInstance;
	}
	resolveOpenAIWebSocketModel({ modelId, apiKey, baseURL, headers, responsesWebSocket }) {
		const wsFetch = createOpenAIWebSocketFetch({
			url: responsesWebSocket?.url,
			headers: responsesWebSocket?.headers
		});
		return {
			modelInstance: createOpenAI({
				apiKey,
				baseURL,
				headers,
				fetch: wsFetch
			}).responses(modelId),
			wsFetch
		};
	}
	static _clearCachesForTests() {
		ModelRouterLanguageModel.gatewayCaches = /* @__PURE__ */ new WeakMap();
	}
	static gatewayCaches = /* @__PURE__ */ new WeakMap();
};
function readGatewayStreamTransport(model) {
	return model[MASTRA_GATEWAY_STREAM_TRANSPORT];
}
/**
* Returns the provider id of the API a model sends requests to, e.g. `openai.chat` or
* `anthropic.messages`. Router models resolve the model they will call; other models report
* their own `provider`.
*/
async function resolveApiProviderId(model) {
	if (model instanceof ModelRouterLanguageModel) return model.resolveApiProviderId();
	const provider = model?.provider;
	return typeof provider === "string" && provider.length > 0 ? provider : void 0;
}
// src/llm/model/aisdk/v4/model.ts
/**
* Wrapper class for AI SDK v4 (LanguageModelV1) legacy models.
*
* The wrapped `#model` is held in a true JS private field so the
* underlying SDK client (and any enumerable config it exposes) cannot
* leak into observability spans. `serializeForSpan()` makes the safe
* shape explicit.
*
* This wrapper is applied by `resolveModelConfig` when a raw v4 model
* is passed to Mastra, so callers do not need to construct it directly.
*/
var AISDKV4LegacyLanguageModel = class {
	specificationVersion = "v1";
	provider;
	modelId;
	defaultObjectGenerationMode;
	supportsImageUrls;
	supportsStructuredOutputs;
	#model;
	constructor(config) {
		this.#model = config;
		this.provider = config.provider;
		this.modelId = config.modelId;
		this.defaultObjectGenerationMode = config.defaultObjectGenerationMode;
		this.supportsImageUrls = config.supportsImageUrls;
		this.supportsStructuredOutputs = config.supportsStructuredOutputs;
	}
	supportsUrl(url) {
		return this.#model.supportsUrl?.(url) ?? false;
	}
	doGenerate(options) {
		return this.#model.doGenerate(options);
	}
	doStream(options) {
		return this.#model.doStream(options);
	}
	/**
	* Custom serialization for tracing/observability spans.
	* `#model` is already a true JS private field and not enumerable, so
	* the wrapped provider SDK client can't leak. This method makes the
	* safe shape explicit.
	*/
	serializeForSpan() {
		return {
			specificationVersion: this.specificationVersion,
			modelId: this.modelId,
			provider: this.provider
		};
	}
};
// src/llm/model/resolve-model.ts
/**
* Type guard to check if a model config is an OpenAICompatibleConfig object
* @internal
*/
/** Whether a model config is a `{ model, id }` labeled model. */
function isIdentifiedModelConfig(modelConfig) {
	return modelConfig !== null && typeof modelConfig === "object" && !("specificationVersion" in modelConfig) && "model" in modelConfig && "id" in modelConfig && typeof modelConfig.id === "string" && Boolean(modelConfig.model);
}
function isOpenAICompatibleObjectConfig(modelConfig) {
	if (modelConfig === null || typeof modelConfig !== "object") return false;
	if ("specificationVersion" in modelConfig) return false;
	if (!("model" in modelConfig)) {
		if ("providerId" in modelConfig && "modelId" in modelConfig) return typeof modelConfig.providerId === "string" && typeof modelConfig.modelId === "string";
		if ("id" in modelConfig) return typeof modelConfig.id === "string";
	}
	return false;
}
/**
* Resolves a model configuration to a LanguageModel instance.
* Supports:
* - Magic strings like "openai/gpt-4o"
* - Config objects like { id: "openai/gpt-4o", apiKey: "..." }
* - Direct LanguageModel instances
* - Dynamic functions that return any of the above
*
* @param modelConfig The model configuration
* @param requestContext Optional request context for dynamic resolution
* @param mastra Optional Mastra instance for dynamic resolution
* @returns A resolved LanguageModel instance
*
* @example
* ```typescript
* // String resolution
* const model = await resolveModelConfig("openai/gpt-4o");
*
* // Config object resolution
* const model = await resolveModelConfig({
*   id: "openai/gpt-4o",
*   apiKey: "sk-..."
* });
*
* // Dynamic resolution
* const model = await resolveModelConfig(
*   ({ requestContext }) => requestContext.get("preferredModel")
* );
* ```
*/
async function resolveModelConfig(modelConfig, requestContext = new RequestContext(), mastra) {
	modelConfig = await resolveDynamicArgument(modelConfig, {
		requestContext,
		mastra
	});
	if (isIdentifiedModelConfig(modelConfig)) {
		const resolved = await resolveModelConfig(modelConfig.model, requestContext, mastra);
		if ("specificationVersion" in resolved && resolved.specificationVersion !== "v1") resolved.id = modelConfig.id;
		return resolved;
	}
	if (modelConfig instanceof ModelRouterLanguageModel || modelConfig instanceof AISDKV4LegacyLanguageModel || modelConfig instanceof AISDKV5LanguageModel || modelConfig instanceof AISDKV6LanguageModel || modelConfig instanceof AISDKV7LanguageModel) return modelConfig;
	if (modelConfig !== null && typeof modelConfig === "object" && "specificationVersion" in modelConfig) {
		if (modelConfig.specificationVersion === "v2") return new AISDKV5LanguageModel(modelConfig);
		if (modelConfig.specificationVersion === "v3") return new AISDKV6LanguageModel(modelConfig);
		if (modelConfig.specificationVersion === "v4") return new AISDKV7LanguageModel(modelConfig);
		if (modelConfig.specificationVersion === "v1") return new AISDKV4LegacyLanguageModel(modelConfig);
		if (typeof modelConfig.doStream === "function" && typeof modelConfig.doGenerate === "function") return new AISDKV5LanguageModel(modelConfig);
		return modelConfig;
	}
	const gatewayRecord = mastra?.listGateways();
	const customGateways = gatewayRecord ? Object.values(gatewayRecord) : void 0;
	if (typeof modelConfig === "string" || isOpenAICompatibleObjectConfig(modelConfig)) return new ModelRouterLanguageModel(modelConfig, customGateways);
	throw new Error("Invalid model configuration provided");
}
// src/llm/model/model-auth-resolver.ts
function mergeAuthHeaders(auth) {
	if (!auth?.bearerToken) return auth;
	return {
		...auth,
		headers: {
			...auth.headers,
			Authorization: `Bearer ${auth.bearerToken}`
		}
	};
}
/**
* @deprecated This function is deprecated and will be removed in a future release.
* Auth resolution is now handled internally by {@link ModelRouterLanguageModel}.
* This function is kept for backward compatibility.
*/
async function resolveModelAuth({ gateway, request, explicit }) {
	if (hasAuthCredentials(explicit)) return mergeAuthHeaders({
		...explicit,
		source: "explicit"
	}) ?? { source: "explicit" };
	const gatewayAuth = mergeAuthHeaders(await gateway.resolveAuth?.(request));
	if (hasAuthCredentials(gatewayAuth)) return {
		...gatewayAuth,
		source: gatewayAuth.source ?? "gateway"
	};
	return {
		apiKey: await gateway.getApiKey(request.routerId),
		source: "legacy"
	};
}
// src/llm/model/embedding-router.ts
const MASTRA_GATEWAY_ID = "mastra";
function trimTrailingSlashes(value) {
	let end = value.length;
	while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
	return value.slice(0, end);
}
function getMastraGatewayBaseUrl(raw = process.env["MASTRA_GATEWAY_URL"]) {
	const withoutTrailingSlashes = trimTrailingSlashes(raw?.trim() || "https://gateway-api.mastra.ai");
	return `${withoutTrailingSlashes.endsWith("/v1") ? withoutTrailingSlashes.slice(0, -3) : withoutTrailingSlashes}/v1`;
}
/**
* Hardcoded list of known embedding models
* This is a curated list that provides autocomplete support
*/
const EMBEDDING_MODELS = [
	{
		id: "text-embedding-3-small",
		provider: "openai",
		dimensions: 1536,
		maxInputTokens: 8191,
		description: "OpenAI text-embedding-3-small model"
	},
	{
		id: "text-embedding-3-large",
		provider: "openai",
		dimensions: 3072,
		maxInputTokens: 8191,
		description: "OpenAI text-embedding-3-large model"
	},
	{
		id: "text-embedding-ada-002",
		provider: "openai",
		dimensions: 1536,
		maxInputTokens: 8191,
		description: "OpenAI text-embedding-ada-002 model"
	},
	{
		id: "gemini-embedding-001",
		provider: "google",
		dimensions: 768,
		maxInputTokens: 2048,
		description: "Google gemini-embedding-001 model"
	}
];
/**
* Model router for embedding models that uses the provider/model string format.
* Automatically resolves the correct AI SDK provider and initializes the embedding model.
*
* @example
* ```ts
* const embedder = new ModelRouterEmbeddingModel('openai/text-embedding-3-small');
* const result = await embedder.doEmbed({ values: ['hello world'] });
* ```
*/
var ModelRouterEmbeddingModel = class {
	specificationVersion = "v2";
	modelId;
	provider;
	maxEmbeddingsPerCall = 2048;
	supportsParallelCalls = true;
	providerModel;
	constructor(config) {
		let normalizedConfig;
		if (typeof config === "string") {
			const parts = config.split("/");
			if (parts[0] === MASTRA_GATEWAY_ID) {
				if (parts.length < 3) throw new Error(`Invalid model string format: "${config}". Expected format: "mastra/provider/model"`);
				normalizedConfig = {
					providerId: MASTRA_GATEWAY_ID,
					modelId: parts.slice(1).join("/")
				};
			} else {
				if (parts.length !== 2) throw new Error(`Invalid model string format: "${config}". Expected format: "provider/model"`);
				const [providerId, modelId] = parts;
				normalizedConfig = {
					providerId,
					modelId
				};
			}
		} else if ("providerId" in config && "modelId" in config) normalizedConfig = {
			providerId: config.providerId,
			modelId: config.modelId,
			url: config.url,
			apiKey: config.apiKey,
			headers: config.headers
		};
		else {
			const parts = config.id.split("/");
			if (parts[0] === MASTRA_GATEWAY_ID) {
				if (parts.length < 3) throw new Error(`Invalid model string format: "${config.id}". Expected format: "mastra/provider/model"`);
				normalizedConfig = {
					providerId: MASTRA_GATEWAY_ID,
					modelId: parts.slice(1).join("/"),
					url: config.url,
					apiKey: config.apiKey,
					headers: config.headers
				};
			} else {
				if (parts.length !== 2) throw new Error(`Invalid model string format: "${config.id}". Expected format: "provider/model"`);
				const [providerId, modelId] = parts;
				normalizedConfig = {
					providerId,
					modelId,
					url: config.url,
					apiKey: config.apiKey,
					headers: config.headers
				};
			}
		}
		this.provider = normalizedConfig.providerId;
		this.modelId = normalizedConfig.modelId;
		if (normalizedConfig.providerId === MASTRA_GATEWAY_ID) {
			const apiKey = normalizedConfig.apiKey ?? process.env["MASTRA_GATEWAY_API_KEY"];
			if (!apiKey) throw new Error("API key not found for provider mastra. Set MASTRA_GATEWAY_API_KEY");
			this.providerModel = createOpenAICompatible({
				name: MASTRA_GATEWAY_ID,
				apiKey,
				baseURL: getMastraGatewayBaseUrl(normalizedConfig.url),
				headers: {
					"User-Agent": MASTRA_USER_AGENT,
					...normalizedConfig.headers
				}
			}).embeddingModel(normalizedConfig.modelId);
		} else if (normalizedConfig.url) {
			const apiKey = normalizedConfig.apiKey || "";
			this.providerModel = createOpenAICompatible({
				name: normalizedConfig.providerId,
				apiKey,
				baseURL: normalizedConfig.url,
				headers: normalizedConfig.headers
			}).embeddingModel(normalizedConfig.modelId);
		} else {
			const providerConfig = GatewayRegistry.getInstance().getProviderConfig(normalizedConfig.providerId);
			if (!providerConfig) throw new Error(`Unknown provider: ${normalizedConfig.providerId}`);
			let apiKey = normalizedConfig.apiKey;
			if (!apiKey) {
				const apiKeyEnvVar = providerConfig.apiKeyEnvVar;
				if (Array.isArray(apiKeyEnvVar)) for (const envVar of apiKeyEnvVar) {
					apiKey = process.env[envVar];
					if (apiKey) break;
				}
				else apiKey = process.env[apiKeyEnvVar];
			}
			if (!apiKey) {
				const envVarDisplay = Array.isArray(providerConfig.apiKeyEnvVar) ? providerConfig.apiKeyEnvVar.join(" or ") : providerConfig.apiKeyEnvVar;
				throw new Error(`API key not found for provider ${normalizedConfig.providerId}. Set ${envVarDisplay}`);
			}
			if (normalizedConfig.providerId === "openai") this.providerModel = createOpenAI({ apiKey }).embeddingModel(normalizedConfig.modelId);
			else if (normalizedConfig.providerId === "google") this.providerModel = createGoogleGenerativeAI({ apiKey }).embeddingModel(normalizedConfig.modelId);
			else {
				if (!providerConfig.url) throw new Error(`Provider ${normalizedConfig.providerId} does not have a URL configured`);
				this.providerModel = createOpenAICompatible({
					name: normalizedConfig.providerId,
					apiKey,
					baseURL: interpolateUrlTemplate(providerConfig.url)
				}).embeddingModel(normalizedConfig.modelId);
			}
		}
		if (this.providerModel.maxEmbeddingsPerCall !== void 0) this.maxEmbeddingsPerCall = this.providerModel.maxEmbeddingsPerCall;
		if (this.providerModel.supportsParallelCalls !== void 0) this.supportsParallelCalls = this.providerModel.supportsParallelCalls;
	}
	async doEmbed(args) {
		let headers;
		if (args.headers) headers = Object.fromEntries(Object.entries(args.headers).filter((entry) => entry[1] !== void 0));
		const result = await this.providerModel.doEmbed({
			...args,
			headers
		});
		const warnings = result.warnings ?? [];
		return {
			...result,
			warnings
		};
	}
};
export { ModelRouterLanguageModel as a, AzureOpenAIGateway as c, attachModelStreamTransport as d, isDataChunk as f, resolveModelConfig as i, defaultGateways as l, ModelRouterEmbeddingModel as n, resolveApiProviderId as o, readModelStreamTransport as p, resolveModelAuth as r, GatewayManager as s, EMBEDDING_MODELS as t, ChunkFrom as u };

//# sourceMappingURL=llm-vu4qB_Xw.js.map