UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,030 lines • 69.6 kB
import { t as canAccess } from "./path-existence-Co7-GyVr.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { _ as resolveDefaultAgentId, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { s as normalizeModelFamily } from "./model-catalog-types-DFHCZ2Xr.mjs";
import { t as ModelInferenceCapabilitiesSchema } from "./model-inference-capabilities-LbVoMxIn.mjs";
import { a as isCurrentPluginMetadataSnapshotRuntimeGeneration, i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { t as normalizeOptionalSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { h as runPluginStreamConsumer } from "./plugin-instance-scope-oezVdCr2.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as modelTransportRoutesMatch } from "./model-compat-catalog-bqzqqcXc.mjs";
import { t as planEffectiveModelCatalogRows } from "./model-catalog-BoLMQ4cy.mjs";
import { n as projectConfigOntoRuntimeSourceSnapshot } from "./runtime-source-projection-DTwMWCo9.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { r as normalizeResolvedPricing } from "./usage-cost-0lKLrzHZ.mjs";
import "./src-DFw9QOgs.mjs";
import { p as resolveExplicitProviderNoAuth, s as applyLocalNoAuthHeaders } from "./model-auth-markers-4YSUG71a.mjs";
import { o as normalizeProviderMapKeys, r as mergeProviderModels, t as buildSourceModelFields } from "./models-config.merge-Bn4GN0An.mjs";
import { g as resolveManagedSecretRefRuntimeProviderAuth } from "./loader-runtime-load-Ba16vW6K.mjs";
import { a as hasUsableCustomProviderApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { t as buildEffectiveManifestProviderConfig } from "./provider-catalog-lIjm3m2s.mjs";
import { a as getAuthStorageOAuthProviderRegistry, i as resolveHeadersOrThrow, n as resolveConfigValueOrThrow, r as resolveConfigValueUncached } from "./auth-storage.core-C5ytUL3b.mjs";
import { a as sanitizeModelHeaders } from "./model.inline-provider-hwabigm5.mjs";
import { t as parseModelCatalogJson } from "./model-catalog-json-DfeKlndn.mjs";
import { n as isGeneratedPluginModelCatalog } from "./plugin-model-catalog-repair-B3GKtPvY.mjs";
import { t as materializeConfiguredProviderCatalogModels } from "./models-config.providers.catalog-DmT2uU7_.mjs";
import { t as loadPersistedPluginModelCatalogs } from "./plugin-model-catalog-execution-D-GvxoAv.mjs";
import { n as inspectLegacyPluginModelCatalogs, r as loadPersistedPluginModelCatalogsReadOnly, t as filterGeneratedPluginModelCatalogProviders } from "./plugin-model-catalog-BafTZg7-.mjs";
import { r as bindStreamLlmRuntime } from "./model-runtime-binding-3f0QcVoj.mjs";
import { existsSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
import { Type } from "typebox";
import { Errors, Pointer } from "typebox/schema";
import { createApiRegistry, createLlmRuntime } from "@openclaw/ai";
import { registerBuiltInApiProviders } from "@openclaw/ai/providers";
//#region src/agents/model-discovery-context.ts
/**
* Shared context resolvers for model discovery.
* Keeps callers from reaching into runtime config or plugin metadata snapshot
* plumbing directly.
*/
function resolveModelWorkspaceDir(e, t, n) {
	if (t !== void 0 || !e) return t;
	return resolveAgentWorkspaceDir(e, n ?? resolveDefaultAgentId(e));
}
/**
* Explicit snapshots win for tests and prepared runtimes. Otherwise we prefer
* the current process snapshot, then fall back to resolving from config/env.
*/
function resolveModelPluginMetadataSnapshot(e) {
	if (e.pluginMetadataSnapshot) return e.pluginMetadataSnapshot;
	const t = process.env;
	try {
		if (!e.config) {
			const n = getCurrentPluginMetadataSnapshot({
				allowWorkspaceScopedSnapshot: true,
				allowSynchronousPolicyRead: false,
				env: t,
				...e.workspaceDir ? { workspaceDir: e.workspaceDir } : {}
			});
			if (n && isCurrentPluginMetadataSnapshotRuntimeGeneration(n)) return n;
		}
		const n = e.config ?? readRuntimeConfig();
		return getCurrentPluginMetadataSnapshot({
			allowWorkspaceScopedSnapshot: true,
			env: t,
			config: n,
			...e.workspaceDir ? { workspaceDir: e.workspaceDir } : {}
		}) ?? resolvePluginMetadataSnapshot({
			config: n,
			env: t,
			...e.workspaceDir ? { workspaceDir: e.workspaceDir } : {},
			...e.allowWorkspaceScopedCurrent !== void 0 ? { allowWorkspaceScopedCurrent: e.allowWorkspaceScopedCurrent } : {}
		});
	} catch {
		return;
	}
}
//#endregion
//#region src/agents/sessions/model-registry-request-auth.ts
/** Authored request settings apply only to their captured provider routes. */
function scopeModelProviderRequestConfig(e, t) {
	if (e?.baseUrls && !e.baseUrls.some((e) => modelTransportRoutesMatch({ baseUrl: e }, { baseUrl: t.baseUrl }))) return;
	return e;
}
/** Resolves registry request auth after the registry has scoped the provider to this route. */
async function resolveModelRegistryRequestAuth(e) {
	const { model: t, providerConfig: n, authStorage: r } = e;
	try {
		const i = resolveExplicitProviderNoAuth({
			provider: t.provider,
			providerConfig: { auth: n?.auth },
			modelApi: t.api
		});
		const a = n?.auth === "aws-sdk";
		const o = (i ? i.apiKey : a ? void 0 : await r.getApiKey(t.provider, {
			includeFallback: false,
			baseUrl: t.baseUrl
		})) ?? (!a && n?.apiKey ? await resolveConfigValueOrThrow(n.apiKey, `API key for provider "${t.provider}"`) : void 0);
		const resolveHeaders = (e, t) => resolveHeadersOrThrow(i && e ? Object.fromEntries(Object.entries(e).filter(([e]) => e.toLowerCase() !== "authorization")) : e, t);
		const s = await resolveHeaders(n?.headers, `provider "${t.provider}"`);
		const c = await resolveHeaders(e.modelHeaders, `model "${t.provider}/${t.id}"`);
		let l = t.headers || s || c ? {
			...t.headers,
			...s,
			...c
		} : void 0;
		if (i) l = applyLocalNoAuthHeaders(t.api, i.apiKey, l);
		else if (n?.authHeader) {
			if (!o) return {
				ok: false,
				error: `No API key found for "${t.provider}"`
			};
			l = {
				...l,
				Authorization: `Bearer ${o}`
			};
		}
		return {
			ok: true,
			apiKey: o,
			headers: l && Object.keys(l).length > 0 ? l : void 0
		};
	} catch (e) {
		return {
			ok: false,
			error: e instanceof Error ? e.message : String(e)
		};
	}
}
//#endregion
//#region src/agents/sessions/model-registry-runtime-model.ts
/** Projects one validated registry row into the runtime model the registry publishes. */
function createRegistryRuntimeModel(e, t, n, r, i) {
	const a = normalizeModelFamily(n.family);
	const o = n.inference === void 0 ? void 0 : ModelInferenceCapabilitiesSchema.safeParse(n.inference);
	return {
		id: n.id,
		name: i ? n.name ?? n.id : n.name,
		api: r,
		provider: e,
		baseUrl: i ? i.baseUrl : n.baseUrl ?? t.baseUrl,
		reasoning: i ? n.reasoning ?? false : n.reasoning,
		thinkingLevelMap: n.thinkingLevelMap,
		input: i ? i.input : n.input,
		cost: i ? normalizeResolvedPricing(n.cost ?? {}) : n.cost,
		contextWindow: n.contextWindow ?? Math.max(n.contextTokens ?? 0, 128e3),
		...n.contextWindow === void 0 ? { contextWindowSource: "synthetic" } : {},
		contextTokens: n.contextTokens,
		...n.parameterCount !== void 0 ? { parameterCount: n.parameterCount } : {},
		...a ? { family: a } : {},
		...o ? { inference: o.success ? o.data : { chat: false } } : {},
		contextWindows: n.contextWindows,
		contextWindowDefault: n.contextWindowDefault,
		maxTokens: i ? n.maxTokens ?? 16384 : n.maxTokens,
		...i && n.maxTokens !== void 0 ? { maxTokensSource: n.maxTokensSource } : {},
		params: n.params,
		headers: void 0,
		compat: n.compat
	};
}
//#endregion
//#region src/agents/sessions/model-registry-runtime.ts
const modelRegistryRuntimes = /* @__PURE__ */ new WeakMap();
function resetApiRegistry(e) {
	e.apiRegistry.clearApiProviders();
	registerBuiltInApiProviders(e.apiRegistry);
}
/** Creates the runtime facts owned by one model-registry lifecycle. */
function initializeModelRegistryRuntime(e) {
	const t = createApiRegistry();
	const n = {
		...createLlmRuntime(t),
		runStream: runPluginStreamConsumer
	};
	const r = {
		apiRegistry: t,
		llmRuntime: n
	};
	bindStreamLlmRuntime(n.streamSimple, n);
	resetApiRegistry(r);
	modelRegistryRuntimes.set(e, r);
}
/** Returns the prepared runtime facts for one model-registry lifecycle. */
function getModelRegistryRuntime(e) {
	const t = modelRegistryRuntimes.get(e);
	if (!t) throw new Error("Model registry runtime is not initialized");
	return t;
}
function resetModelRegistryRuntime(e) {
	resetApiRegistry(getModelRegistryRuntime(e));
}
//#endregion
//#region src/agents/sessions/model-registry-schema-definition.ts
const PercentileCutoffsSchema = Type.Object({
	p50: Type.Optional(Type.Number()),
	p75: Type.Optional(Type.Number()),
	p90: Type.Optional(Type.Number()),
	p99: Type.Optional(Type.Number())
});
const OpenRouterRoutingSchema = Type.Object({
	allow_fallbacks: Type.Optional(Type.Boolean()),
	require_parameters: Type.Optional(Type.Boolean()),
	data_collection: Type.Optional(Type.Union([Type.Literal("deny"), Type.Literal("allow")])),
	zdr: Type.Optional(Type.Boolean()),
	enforce_distillable_text: Type.Optional(Type.Boolean()),
	order: Type.Optional(Type.Array(Type.String())),
	only: Type.Optional(Type.Array(Type.String())),
	ignore: Type.Optional(Type.Array(Type.String())),
	quantizations: Type.Optional(Type.Array(Type.String())),
	sort: Type.Optional(Type.Union([Type.String(), Type.Object({
		by: Type.Optional(Type.String()),
		partition: Type.Optional(Type.Union([Type.String(), Type.Null()]))
	})])),
	max_price: Type.Optional(Type.Object({
		prompt: Type.Optional(Type.Union([Type.Number(), Type.String()])),
		completion: Type.Optional(Type.Union([Type.Number(), Type.String()])),
		image: Type.Optional(Type.Union([Type.Number(), Type.String()])),
		audio: Type.Optional(Type.Union([Type.Number(), Type.String()])),
		request: Type.Optional(Type.Union([Type.Number(), Type.String()]))
	})),
	preferred_min_throughput: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),
	preferred_max_latency: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema]))
});
const VercelGatewayRoutingSchema = Type.Object({
	only: Type.Optional(Type.Array(Type.String())),
	order: Type.Optional(Type.Array(Type.String()))
});
const ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]);
const ThinkingLevelMapSchema = Type.Object({
	off: Type.Optional(ThinkingLevelMapValueSchema),
	minimal: Type.Optional(ThinkingLevelMapValueSchema),
	low: Type.Optional(ThinkingLevelMapValueSchema),
	medium: Type.Optional(ThinkingLevelMapValueSchema),
	high: Type.Optional(ThinkingLevelMapValueSchema),
	xhigh: Type.Optional(ThinkingLevelMapValueSchema),
	max: Type.Optional(ThinkingLevelMapValueSchema)
});
const OpenAICompletionsCompatSchema = Type.Object({
	supportsStore: Type.Optional(Type.Boolean()),
	supportsDeveloperRole: Type.Optional(Type.Boolean()),
	supportsReasoningEffort: Type.Optional(Type.Boolean()),
	supportsUsageInStreaming: Type.Optional(Type.Boolean()),
	maxTokensField: Type.Optional(Type.Union([Type.Literal("max_completion_tokens"), Type.Literal("max_tokens")])),
	requiresToolResultName: Type.Optional(Type.Boolean()),
	requiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),
	requiresThinkingAsText: Type.Optional(Type.Boolean()),
	requiresReasoningContentOnAssistantMessages: Type.Optional(Type.Boolean()),
	thinkingFormat: Type.Optional(Type.Union([
		Type.Literal("openai"),
		Type.Literal("openrouter"),
		Type.Literal("together"),
		Type.Literal("deepseek"),
		Type.Literal("zai"),
		Type.Literal("qwen"),
		Type.Literal("qwen-chat-template")
	])),
	cacheControlFormat: Type.Optional(Type.Literal("anthropic")),
	openRouterRouting: Type.Optional(OpenRouterRoutingSchema),
	vercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),
	supportsStrictMode: Type.Optional(Type.Boolean()),
	supportsJsonSchemaResponseFormat: Type.Optional(Type.Boolean()),
	supportsLongCacheRetention: Type.Optional(Type.Boolean())
});
const OpenAIResponsesCompatSchema = Type.Object({
	supportsTemperature: Type.Optional(Type.Boolean()),
	supportsInstructions: Type.Optional(Type.Boolean()),
	sendSessionIdHeader: Type.Optional(Type.Boolean()),
	supportsLongCacheRetention: Type.Optional(Type.Boolean())
});
const AnthropicMessagesCompatSchema = Type.Object({
	supportsEagerToolInputStreaming: Type.Optional(Type.Boolean()),
	supportsLongCacheRetention: Type.Optional(Type.Boolean())
});
const ProviderCompatSchema = Type.Union([
	OpenAICompletionsCompatSchema,
	OpenAIResponsesCompatSchema,
	AnthropicMessagesCompatSchema
]);
const ProviderAuthModeSchema = Type.Union([
	Type.Literal("api-key"),
	Type.Literal("aws-sdk"),
	Type.Literal("oauth"),
	Type.Literal("token"),
	Type.Literal("none")
]);
const ModelDefinitionSchema = Type.Object({
	id: Type.String({ minLength: 1 }),
	name: Type.Optional(Type.String({ minLength: 1 })),
	api: Type.Optional(Type.String({ minLength: 1 })),
	baseUrl: Type.Optional(Type.String({ minLength: 1 })),
	reasoning: Type.Optional(Type.Boolean()),
	thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),
	input: Type.Optional(Type.Array(Type.Union([
		Type.Literal("text"),
		Type.Literal("image"),
		Type.Literal("audio"),
		Type.Literal("video")
	]))),
	cost: Type.Optional(Type.Object({
		input: Type.Number(),
		output: Type.Number(),
		cacheRead: Type.Number(),
		cacheWrite: Type.Number()
	})),
	contextWindow: Type.Optional(Type.Number()),
	contextTokens: Type.Optional(Type.Number()),
	parameterCount: Type.Optional(Type.Integer({ minimum: 1 })),
	family: Type.Optional(Type.String()),
	maxTokens: Type.Optional(Type.Number()),
	params: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
	headers: Type.Optional(Type.Record(Type.String(), Type.String())),
	compat: Type.Optional(ProviderCompatSchema)
});
const ProviderConfigSchema = Type.Object({
	name: Type.Optional(Type.String({ minLength: 1 })),
	baseUrl: Type.Optional(Type.String({ minLength: 1 })),
	apiKey: Type.Optional(Type.String({ minLength: 1 })),
	auth: Type.Optional(ProviderAuthModeSchema),
	api: Type.Optional(Type.String({ minLength: 1 })),
	headers: Type.Optional(Type.Record(Type.String(), Type.String())),
	compat: Type.Optional(ProviderCompatSchema),
	authHeader: Type.Optional(Type.Boolean()),
	models: Type.Optional(Type.Array(ModelDefinitionSchema))
});
const ModelRegistryConfigSchema = Type.Object({
	generatedBy: Type.Optional(Type.String()),
	providers: Type.Record(Type.String(), ProviderConfigSchema)
});
//#endregion
//#region src/agents/sessions/model-registry-validator.generated.js
/*!
TypeBox

The MIT License (MIT)

Copyright (c) 2017-2026 Haydn Paterson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
function CodePointCount(e) {
	let t = 0, n = 0, r = 0;
	for (; n < e.length;) {
		let i = e.charCodeAt(n++) >> 10;
		t += +((r << 8 | i) !== 13879), r = i;
	}
	return t;
}
var isModelsConfig = (() => {
	let e = [
		/^.*$/u,
		/^.*$/u,
		/^.*$/u,
		/^.*$/u
	], check_0 = (t) => typeof t == "object" && t !== null && !Array.isArray(t) && "providers" in t && (t.generatedBy === void 0 || !("generatedBy" in t) || typeof t.generatedBy == "string") && typeof t.providers == "object" && t.providers !== null && !Array.isArray(t.providers) && Object.entries(t.providers).every(([t, n], r) => !e[0].test(t) || typeof n == "object" && n !== null && !Array.isArray(n) && (n.name === void 0 || !("name" in n) || typeof n.name == "string" && (n.name.length >= 2 || n.name.length >= 1 && CodePointCount(n.name) >= 1)) && (n.baseUrl === void 0 || !("baseUrl" in n) || typeof n.baseUrl == "string" && (n.baseUrl.length >= 2 || n.baseUrl.length >= 1 && CodePointCount(n.baseUrl) >= 1)) && (n.apiKey === void 0 || !("apiKey" in n) || typeof n.apiKey == "string" && (n.apiKey.length >= 2 || n.apiKey.length >= 1 && CodePointCount(n.apiKey) >= 1)) && (n.auth === void 0 || !("auth" in n) || typeof n.auth == "string" && n.auth === "api-key" || typeof n.auth == "string" && n.auth === "aws-sdk" || typeof n.auth == "string" && n.auth === "oauth" || typeof n.auth == "string" && n.auth === "token" || typeof n.auth == "string" && n.auth === "none") && (n.api === void 0 || !("api" in n) || typeof n.api == "string" && (n.api.length >= 2 || n.api.length >= 1 && CodePointCount(n.api) >= 1)) && (n.headers === void 0 || !("headers" in n) || typeof n.headers == "object" && n.headers !== null && !Array.isArray(n.headers) && Object.entries(n.headers).every(([t, n], r) => !e[1].test(t) || typeof n == "string")) && (n.compat === void 0 || !("compat" in n) || typeof n.compat == "object" && n.compat !== null && !Array.isArray(n.compat) && (n.compat.supportsStore === void 0 || !("supportsStore" in n.compat) || typeof n.compat.supportsStore == "boolean") && (n.compat.supportsDeveloperRole === void 0 || !("supportsDeveloperRole" in n.compat) || typeof n.compat.supportsDeveloperRole == "boolean") && (n.compat.supportsReasoningEffort === void 0 || !("supportsReasoningEffort" in n.compat) || typeof n.compat.supportsReasoningEffort == "boolean") && (n.compat.supportsUsageInStreaming === void 0 || !("supportsUsageInStreaming" in n.compat) || typeof n.compat.supportsUsageInStreaming == "boolean") && (n.compat.maxTokensField === void 0 || !("maxTokensField" in n.compat) || typeof n.compat.maxTokensField == "string" && n.compat.maxTokensField === "max_completion_tokens" || typeof n.compat.maxTokensField == "string" && n.compat.maxTokensField === "max_tokens") && (n.compat.requiresToolResultName === void 0 || !("requiresToolResultName" in n.compat) || typeof n.compat.requiresToolResultName == "boolean") && (n.compat.requiresAssistantAfterToolResult === void 0 || !("requiresAssistantAfterToolResult" in n.compat) || typeof n.compat.requiresAssistantAfterToolResult == "boolean") && (n.compat.requiresThinkingAsText === void 0 || !("requiresThinkingAsText" in n.compat) || typeof n.compat.requiresThinkingAsText == "boolean") && (n.compat.requiresReasoningContentOnAssistantMessages === void 0 || !("requiresReasoningContentOnAssistantMessages" in n.compat) || typeof n.compat.requiresReasoningContentOnAssistantMessages == "boolean") && (n.compat.thinkingFormat === void 0 || !("thinkingFormat" in n.compat) || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "openai" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "openrouter" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "together" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "deepseek" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "zai" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "qwen" || typeof n.compat.thinkingFormat == "string" && n.compat.thinkingFormat === "qwen-chat-template") && (n.compat.cacheControlFormat === void 0 || !("cacheControlFormat" in n.compat) || typeof n.compat.cacheControlFormat == "string" && n.compat.cacheControlFormat === "anthropic") && (n.compat.openRouterRouting === void 0 || !("openRouterRouting" in n.compat) || typeof n.compat.openRouterRouting == "object" && n.compat.openRouterRouting !== null && !Array.isArray(n.compat.openRouterRouting) && (n.compat.openRouterRouting.allow_fallbacks === void 0 || !("allow_fallbacks" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.allow_fallbacks == "boolean") && (n.compat.openRouterRouting.require_parameters === void 0 || !("require_parameters" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.require_parameters == "boolean") && (n.compat.openRouterRouting.data_collection === void 0 || !("data_collection" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.data_collection == "string" && n.compat.openRouterRouting.data_collection === "deny" || typeof n.compat.openRouterRouting.data_collection == "string" && n.compat.openRouterRouting.data_collection === "allow") && (n.compat.openRouterRouting.zdr === void 0 || !("zdr" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.zdr == "boolean") && (n.compat.openRouterRouting.enforce_distillable_text === void 0 || !("enforce_distillable_text" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.enforce_distillable_text == "boolean") && (n.compat.openRouterRouting.order === void 0 || !("order" in n.compat.openRouterRouting) || Array.isArray(n.compat.openRouterRouting.order) && n.compat.openRouterRouting.order.every((e, t) => typeof e == "string")) && (n.compat.openRouterRouting.only === void 0 || !("only" in n.compat.openRouterRouting) || Array.isArray(n.compat.openRouterRouting.only) && n.compat.openRouterRouting.only.every((e, t) => typeof e == "string")) && (n.compat.openRouterRouting.ignore === void 0 || !("ignore" in n.compat.openRouterRouting) || Array.isArray(n.compat.openRouterRouting.ignore) && n.compat.openRouterRouting.ignore.every((e, t) => typeof e == "string")) && (n.compat.openRouterRouting.quantizations === void 0 || !("quantizations" in n.compat.openRouterRouting) || Array.isArray(n.compat.openRouterRouting.quantizations) && n.compat.openRouterRouting.quantizations.every((e, t) => typeof e == "string")) && (n.compat.openRouterRouting.sort === void 0 || !("sort" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.sort == "string" || typeof n.compat.openRouterRouting.sort == "object" && n.compat.openRouterRouting.sort !== null && !Array.isArray(n.compat.openRouterRouting.sort) && (n.compat.openRouterRouting.sort.by === void 0 || !("by" in n.compat.openRouterRouting.sort) || typeof n.compat.openRouterRouting.sort.by == "string") && (n.compat.openRouterRouting.sort.partition === void 0 || !("partition" in n.compat.openRouterRouting.sort) || typeof n.compat.openRouterRouting.sort.partition == "string" || n.compat.openRouterRouting.sort.partition === null)) && (n.compat.openRouterRouting.max_price === void 0 || !("max_price" in n.compat.openRouterRouting) || typeof n.compat.openRouterRouting.max_price == "object" && n.compat.openRouterRouting.max_price !== null && !Array.isArray(n.compat.openRouterRouting.max_price) && (n.compat.openRouterRouting.max_price.prompt === void 0 || !("prompt" in n.compat.openRouterRouting.max_price) || Number.isFinite(n.compat.openRouterRouting.max_price.prompt) || typeof n.compat.openRouterRouting.max_price.prompt == "string") && (n.compat.openRouterRouting.max_price.completion === void 0 || !("completion" in n.compat.openRouterRouting.max_price) || Number.isFinite(n.compat.openRouterRouting.max_price.completion) || typeof n.compat.openRouterRouting.max_price.completion == "string") && (n.compat.openRouterRouting.max_price.image === void 0 || !("image" in n.compat.openRouterRouting.max_price) || Number.isFinite(n.compat.openRouterRouting.max_price.image) || typeof n.compat.openRouterRouting.max_price.image == "string") && (n.compat.openRouterRouting.max_price.audio === void 0 || !("audio" in n.compat.openRouterRouting.max_price) || Number.isFinite(n.compat.openRouterRouting.max_price.audio) || typeof n.compat.openRouterRouting.max_price.audio == "string") && (n.compat.openRouterRouting.max_price.request === void 0 || !("request" in n.compat.openRouterRouting.max_price) || Number.isFinite(n.compat.openRouterRouting.max_price.request) || typeof n.compat.openRouterRouting.max_price.request == "string")) && (n.compat.openRouterRouting.preferred_min_throughput === void 0 || !("preferred_min_throughput" in n.compat.openRouterRouting) || Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput) || typeof n.compat.openRouterRouting.preferred_min_throughput == "object" && n.compat.openRouterRouting.preferred_min_throughput !== null && !Array.isArray(n.compat.openRouterRouting.preferred_min_throughput) && (n.compat.openRouterRouting.preferred_min_throughput.p50 === void 0 || !("p50" in n.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p50)) && (n.compat.openRouterRouting.preferred_min_throughput.p75 === void 0 || !("p75" in n.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p75)) && (n.compat.openRouterRouting.preferred_min_throughput.p90 === void 0 || !("p90" in n.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p90)) && (n.compat.openRouterRouting.preferred_min_throughput.p99 === void 0 || !("p99" in n.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p99))) && (n.compat.openRouterRouting.preferred_max_latency === void 0 || !("preferred_max_latency" in n.compat.openRouterRouting) || Number.isFinite(n.compat.openRouterRouting.preferred_max_latency) || typeof n.compat.openRouterRouting.preferred_max_latency == "object" && n.compat.openRouterRouting.preferred_max_latency !== null && !Array.isArray(n.compat.openRouterRouting.preferred_max_latency) && (n.compat.openRouterRouting.preferred_max_latency.p50 === void 0 || !("p50" in n.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p50)) && (n.compat.openRouterRouting.preferred_max_latency.p75 === void 0 || !("p75" in n.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p75)) && (n.compat.openRouterRouting.preferred_max_latency.p90 === void 0 || !("p90" in n.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p90)) && (n.compat.openRouterRouting.preferred_max_latency.p99 === void 0 || !("p99" in n.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p99)))) && (n.compat.vercelGatewayRouting === void 0 || !("vercelGatewayRouting" in n.compat) || typeof n.compat.vercelGatewayRouting == "object" && n.compat.vercelGatewayRouting !== null && !Array.isArray(n.compat.vercelGatewayRouting) && (n.compat.vercelGatewayRouting.only === void 0 || !("only" in n.compat.vercelGatewayRouting) || Array.isArray(n.compat.vercelGatewayRouting.only) && n.compat.vercelGatewayRouting.only.every((e, t) => typeof e == "string")) && (n.compat.vercelGatewayRouting.order === void 0 || !("order" in n.compat.vercelGatewayRouting) || Array.isArray(n.compat.vercelGatewayRouting.order) && n.compat.vercelGatewayRouting.order.every((e, t) => typeof e == "string"))) && (n.compat.supportsStrictMode === void 0 || !("supportsStrictMode" in n.compat) || typeof n.compat.supportsStrictMode == "boolean") && (n.compat.supportsJsonSchemaResponseFormat === void 0 || !("supportsJsonSchemaResponseFormat" in n.compat) || typeof n.compat.supportsJsonSchemaResponseFormat == "boolean") && (n.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in n.compat) || typeof n.compat.supportsLongCacheRetention == "boolean") || typeof n.compat == "object" && n.compat !== null && !Array.isArray(n.compat) && (n.compat.supportsTemperature === void 0 || !("supportsTemperature" in n.compat) || typeof n.compat.supportsTemperature == "boolean") && (n.compat.supportsInstructions === void 0 || !("supportsInstructions" in n.compat) || typeof n.compat.supportsInstructions == "boolean") && (n.compat.sendSessionIdHeader === void 0 || !("sendSessionIdHeader" in n.compat) || typeof n.compat.sendSessionIdHeader == "boolean") && (n.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in n.compat) || typeof n.compat.supportsLongCacheRetention == "boolean") || typeof n.compat == "object" && n.compat !== null && !Array.isArray(n.compat) && (n.compat.supportsEagerToolInputStreaming === void 0 || !("supportsEagerToolInputStreaming" in n.compat) || typeof n.compat.supportsEagerToolInputStreaming == "boolean") && (n.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in n.compat) || typeof n.compat.supportsLongCacheRetention == "boolean")) && (n.authHeader === void 0 || !("authHeader" in n) || typeof n.authHeader == "boolean") && (n.models === void 0 || !("models" in n) || Array.isArray(n.models) && n.models.every((t, n) => typeof t == "object" && t !== null && !Array.isArray(t) && "id" in t && typeof t.id == "string" && (t.id.length >= 2 || t.id.length >= 1 && CodePointCount(t.id) >= 1) && (t.name === void 0 || !("name" in t) || typeof t.name == "string" && (t.name.length >= 2 || t.name.length >= 1 && CodePointCount(t.name) >= 1)) && (t.api === void 0 || !("api" in t) || typeof t.api == "string" && (t.api.length >= 2 || t.api.length >= 1 && CodePointCount(t.api) >= 1)) && (t.baseUrl === void 0 || !("baseUrl" in t) || typeof t.baseUrl == "string" && (t.baseUrl.length >= 2 || t.baseUrl.length >= 1 && CodePointCount(t.baseUrl) >= 1)) && (t.reasoning === void 0 || !("reasoning" in t) || typeof t.reasoning == "boolean") && (t.thinkingLevelMap === void 0 || !("thinkingLevelMap" in t) || typeof t.thinkingLevelMap == "object" && t.thinkingLevelMap !== null && !Array.isArray(t.thinkingLevelMap) && (t.thinkingLevelMap.off === void 0 || !("off" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.off == "string" || t.thinkingLevelMap.off === null) && (t.thinkingLevelMap.minimal === void 0 || !("minimal" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.minimal == "string" || t.thinkingLevelMap.minimal === null) && (t.thinkingLevelMap.low === void 0 || !("low" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.low == "string" || t.thinkingLevelMap.low === null) && (t.thinkingLevelMap.medium === void 0 || !("medium" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.medium == "string" || t.thinkingLevelMap.medium === null) && (t.thinkingLevelMap.high === void 0 || !("high" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.high == "string" || t.thinkingLevelMap.high === null) && (t.thinkingLevelMap.xhigh === void 0 || !("xhigh" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.xhigh == "string" || t.thinkingLevelMap.xhigh === null) && (t.thinkingLevelMap.max === void 0 || !("max" in t.thinkingLevelMap) || typeof t.thinkingLevelMap.max == "string" || t.thinkingLevelMap.max === null)) && (t.input === void 0 || !("input" in t) || Array.isArray(t.input) && t.input.every((e, t) => typeof e == "string" && e === "text" || typeof e == "string" && e === "image" || typeof e == "string" && e === "audio" || typeof e == "string" && e === "video")) && (t.cost === void 0 || !("cost" in t) || typeof t.cost == "object" && t.cost !== null && !Array.isArray(t.cost) && "input" in t.cost && "output" in t.cost && "cacheRead" in t.cost && "cacheWrite" in t.cost && Number.isFinite(t.cost.input) && Number.isFinite(t.cost.output) && Number.isFinite(t.cost.cacheRead) && Number.isFinite(t.cost.cacheWrite)) && (t.contextWindow === void 0 || !("contextWindow" in t) || Number.isFinite(t.contextWindow)) && (t.contextTokens === void 0 || !("contextTokens" in t) || Number.isFinite(t.contextTokens)) && (t.parameterCount === void 0 || !("parameterCount" in t) || Number.isInteger(t.parameterCount) && (!(Number.isFinite(t.parameterCount) || typeof t.parameterCount == "bigint") || t.parameterCount >= 1)) && (t.family === void 0 || !("family" in t) || typeof t.family == "string") && (t.maxTokens === void 0 || !("maxTokens" in t) || Number.isFinite(t.maxTokens)) && (t.params === void 0 || !("params" in t) || typeof t.params == "object" && t.params !== null && !Array.isArray(t.params) && Object.entries(t.params).every(([t, n], r) => !e[2].test(t) || !0)) && (t.headers === void 0 || !("headers" in t) || typeof t.headers == "object" && t.headers !== null && !Array.isArray(t.headers) && Object.entries(t.headers).every(([t, n], r) => !e[3].test(t) || typeof n == "string")) && (t.compat === void 0 || !("compat" in t) || typeof t.compat == "object" && t.compat !== null && !Array.isArray(t.compat) && (t.compat.supportsStore === void 0 || !("supportsStore" in t.compat) || typeof t.compat.supportsStore == "boolean") && (t.compat.supportsDeveloperRole === void 0 || !("supportsDeveloperRole" in t.compat) || typeof t.compat.supportsDeveloperRole == "boolean") && (t.compat.supportsReasoningEffort === void 0 || !("supportsReasoningEffort" in t.compat) || typeof t.compat.supportsReasoningEffort == "boolean") && (t.compat.supportsUsageInStreaming === void 0 || !("supportsUsageInStreaming" in t.compat) || typeof t.compat.supportsUsageInStreaming == "boolean") && (t.compat.maxTokensField === void 0 || !("maxTokensField" in t.compat) || typeof t.compat.maxTokensField == "string" && t.compat.maxTokensField === "max_completion_tokens" || typeof t.compat.maxTokensField == "string" && t.compat.maxTokensField === "max_tokens") && (t.compat.requiresToolResultName === void 0 || !("requiresToolResultName" in t.compat) || typeof t.compat.requiresToolResultName == "boolean") && (t.compat.requiresAssistantAfterToolResult === void 0 || !("requiresAssistantAfterToolResult" in t.compat) || typeof t.compat.requiresAssistantAfterToolResult == "boolean") && (t.compat.requiresThinkingAsText === void 0 || !("requiresThinkingAsText" in t.compat) || typeof t.compat.requiresThinkingAsText == "boolean") && (t.compat.requiresReasoningContentOnAssistantMessages === void 0 || !("requiresReasoningContentOnAssistantMessages" in t.compat) || typeof t.compat.requiresReasoningContentOnAssistantMessages == "boolean") && (t.compat.thinkingFormat === void 0 || !("thinkingFormat" in t.compat) || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "openai" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "openrouter" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "together" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "deepseek" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "zai" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "qwen" || typeof t.compat.thinkingFormat == "string" && t.compat.thinkingFormat === "qwen-chat-template") && (t.compat.cacheControlFormat === void 0 || !("cacheControlFormat" in t.compat) || typeof t.compat.cacheControlFormat == "string" && t.compat.cacheControlFormat === "anthropic") && (t.compat.openRouterRouting === void 0 || !("openRouterRouting" in t.compat) || typeof t.compat.openRouterRouting == "object" && t.compat.openRouterRouting !== null && !Array.isArray(t.compat.openRouterRouting) && (t.compat.openRouterRouting.allow_fallbacks === void 0 || !("allow_fallbacks" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.allow_fallbacks == "boolean") && (t.compat.openRouterRouting.require_parameters === void 0 || !("require_parameters" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.require_parameters == "boolean") && (t.compat.openRouterRouting.data_collection === void 0 || !("data_collection" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.data_collection == "string" && t.compat.openRouterRouting.data_collection === "deny" || typeof t.compat.openRouterRouting.data_collection == "string" && t.compat.openRouterRouting.data_collection === "allow") && (t.compat.openRouterRouting.zdr === void 0 || !("zdr" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.zdr == "boolean") && (t.compat.openRouterRouting.enforce_distillable_text === void 0 || !("enforce_distillable_text" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.enforce_distillable_text == "boolean") && (t.compat.openRouterRouting.order === void 0 || !("order" in t.compat.openRouterRouting) || Array.isArray(t.compat.openRouterRouting.order) && t.compat.openRouterRouting.order.every((e, t) => typeof e == "string")) && (t.compat.openRouterRouting.only === void 0 || !("only" in t.compat.openRouterRouting) || Array.isArray(t.compat.openRouterRouting.only) && t.compat.openRouterRouting.only.every((e, t) => typeof e == "string")) && (t.compat.openRouterRouting.ignore === void 0 || !("ignore" in t.compat.openRouterRouting) || Array.isArray(t.compat.openRouterRouting.ignore) && t.compat.openRouterRouting.ignore.every((e, t) => typeof e == "string")) && (t.compat.openRouterRouting.quantizations === void 0 || !("quantizations" in t.compat.openRouterRouting) || Array.isArray(t.compat.openRouterRouting.quantizations) && t.compat.openRouterRouting.quantizations.every((e, t) => typeof e == "string")) && (t.compat.openRouterRouting.sort === void 0 || !("sort" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.sort == "string" || typeof t.compat.openRouterRouting.sort == "object" && t.compat.openRouterRouting.sort !== null && !Array.isArray(t.compat.openRouterRouting.sort) && (t.compat.openRouterRouting.sort.by === void 0 || !("by" in t.compat.openRouterRouting.sort) || typeof t.compat.openRouterRouting.sort.by == "string") && (t.compat.openRouterRouting.sort.partition === void 0 || !("partition" in t.compat.openRouterRouting.sort) || typeof t.compat.openRouterRouting.sort.partition == "string" || t.compat.openRouterRouting.sort.partition === null)) && (t.compat.openRouterRouting.max_price === void 0 || !("max_price" in t.compat.openRouterRouting) || typeof t.compat.openRouterRouting.max_price == "object" && t.compat.openRouterRouting.max_price !== null && !Array.isArray(t.compat.openRouterRouting.max_price) && (t.compat.openRouterRouting.max_price.prompt === void 0 || !("prompt" in t.compat.openRouterRouting.max_price) || Number.isFinite(t.compat.openRouterRouting.max_price.prompt) || typeof t.compat.openRouterRouting.max_price.prompt == "string") && (t.compat.openRouterRouting.max_price.completion === void 0 || !("completion" in t.compat.openRouterRouting.max_price) || Number.isFinite(t.compat.openRouterRouting.max_price.completion) || typeof t.compat.openRouterRouting.max_price.completion == "string") && (t.compat.openRouterRouting.max_price.image === void 0 || !("image" in t.compat.openRouterRouting.max_price) || Number.isFinite(t.compat.openRouterRouting.max_price.image) || typeof t.compat.openRouterRouting.max_price.image == "string") && (t.compat.openRouterRouting.max_price.audio === void 0 || !("audio" in t.compat.openRouterRouting.max_price) || Number.isFinite(t.compat.openRouterRouting.max_price.audio) || typeof t.compat.openRouterRouting.max_price.audio == "string") && (t.compat.openRouterRouting.max_price.request === void 0 || !("request" in t.compat.openRouterRouting.max_price) || Number.isFinite(t.compat.openRouterRouting.max_price.request) || typeof t.compat.openRouterRouting.max_price.request == "string")) && (t.compat.openRouterRouting.preferred_min_throughput === void 0 || !("preferred_min_throughput" in t.compat.openRouterRouting) || Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput) || typeof t.compat.openRouterRouting.preferred_min_throughput == "object" && t.compat.openRouterRouting.preferred_min_throughput !== null && !Array.isArray(t.compat.openRouterRouting.preferred_min_throughput) && (t.compat.openRouterRouting.preferred_min_throughput.p50 === void 0 || !("p50" in t.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p50)) && (t.compat.openRouterRouting.preferred_min_throughput.p75 === void 0 || !("p75" in t.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p75)) && (t.compat.openRouterRouting.preferred_min_throughput.p90 === void 0 || !("p90" in t.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p90)) && (t.compat.openRouterRouting.preferred_min_throughput.p99 === void 0 || !("p99" in t.compat.openRouterRouting.preferred_min_throughput) || Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p99))) && (t.compat.openRouterRouting.preferred_max_latency === void 0 || !("preferred_max_latency" in t.compat.openRouterRouting) || Number.isFinite(t.compat.openRouterRouting.preferred_max_latency) || typeof t.compat.openRouterRouting.preferred_max_latency == "object" && t.compat.openRouterRouting.preferred_max_latency !== null && !Array.isArray(t.compat.openRouterRouting.preferred_max_latency) && (t.compat.openRouterRouting.preferred_max_latency.p50 === void 0 || !("p50" in t.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p50)) && (t.compat.openRouterRouting.preferred_max_latency.p75 === void 0 || !("p75" in t.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p75)) && (t.compat.openRouterRouting.preferred_max_latency.p90 === void 0 || !("p90" in t.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p90)) && (t.compat.openRouterRouting.preferred_max_latency.p99 === void 0 || !("p99" in t.compat.openRouterRouting.preferred_max_latency) || Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p99)))) && (t.compat.vercelGatewayRouting === void 0 || !("vercelGatewayRouting" in t.compat) || typeof t.compat.vercelGatewayRouting == "object" && t.compat.vercelGatewayRouting !== null && !Array.isArray(t.compat.vercelGatewayRouting) && (t.compat.vercelGatewayRouting.only === void 0 || !("only" in t.compat.vercelGatewayRouting) || Array.isArray(t.compat.vercelGatewayRouting.only) && t.compat.vercelGatewayRouting.only.every((e, t) => typeof e == "string")) && (t.compat.vercelGatewayRouting.order === void 0 || !("order" in t.compat.vercelGatewayRouting) || Array.isArray(t.compat.vercelGatewayRouting.order) && t.compat.vercelGatewayRouting.order.every((e, t) => typeof e == "string"))) && (t.compat.supportsStrictMode === void 0 || !("supportsStrictMode" in t.compat) || typeof t.compat.supportsStrictMode == "boolean") && (t.compat.supportsJsonSchemaResponseFormat === void 0 || !("supportsJsonSchemaResponseFormat" in t.compat) || typeof t.compat.supportsJsonSchemaResponseFormat == "boolean") && (t.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in t.compat) || typeof t.compat.supportsLongCacheRetention == "boolean") || typeof t.compat == "object" && t.compat !== null && !Array.isArray(t.compat) && (t.compat.supportsTemperature === void 0 || !("supportsTemperature" in t.compat) || typeof t.compat.supportsTemperature == "boolean") && (t.compat.supportsInstructions === void 0 || !("supportsInstructions" in t.compat) || typeof t.compat.supportsInstructions == "boolean") && (t.compat.sendSessionIdHeader === void 0 || !("sendSessionIdHeader" in t.compat) || typeof t.compat.sendSessionIdHeader == "boolean") && (t.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in t.compat) || typeof t.compat.supportsLongCacheRetention == "boolean") || typeof t.compat == "object" && t.compat !== null && !Array.isArray(t.compat) && (t.compat.supportsEagerToolInputStreaming === void 0 || !("supportsEagerToolInputStreaming" in t.compat) || typeof t.compat.supportsEagerToolInputStreaming == "boolean") && (t.compat.supportsLongCacheRetention === void 0 || !("supportsLongCacheRetention" in t.compat) || typeof t.compat.supportsLongCacheRetention == "boolean")))));
	return (e) => check_0(e);
})();
//#endregion
//#region src/agents/sessions/model-registry-schema.ts
const validateModelsConfig = {
	Check: isModelsConfig,
	Errors: (e) => Errors(ModelRegistryConfigSchema, e)[1]
};
/** Omit malformed pricing, retaining the rows for semantic validation before exclusion. */
function omitInvalidModelCosts(e) {
	const t = /* @__PURE__ */ new Set();
	for (const n of validateModelsConfig.Errors(e)) {
		const e = /^(\/providers\/[^/]+\/models\/\d+)\/cost(?:\/|$)/.exec(n.instancePath);
		if (!e?.[1]) return /* @__PURE__ */ new Set();
		t.add(e[1]);
	}
	const n = /* @__PURE__ */ new Set();
	for (const r of t) {
		n.add(Pointer.Get(e, r));
		Pointer.Delete(e, `${r}/cost`);
	}
	return n;
}
function formatValidationPath(e) {
	const t = Pointer.Indices(e.instancePath).join(".").replace(/\//g, ".");
	if (e.keyword === "required") {
		const n = e.params.requiredProperties[0];
		if (n) return t ? `${t}.${n}` : n;
	}
	return t || "root";
}
function validateProviderModels(e, t, n) {
	const r = t.models ?? [];
	if (r.length > 0 && !t.baseUrl) throw new Error(`Provider ${e}: "baseUrl" is required when defining ${n === "catalog" ? "custom models" : "models"}.`);
	for (const i of r) {
		if (!i.api && !t.api) {
			const t = n === "catalog" ? " Set at provider or model level." : "";
			throw new Error(`Provider ${e}, model ${i.id}: no "api" specified.${t}`);
		}
		if (n === "catalog") {
			for (const t of ["contextWindow", "maxTokens"]) if (i[t] !== void 0 && i[t] <= 0) throw new Error(`Provider ${e}, model ${i.id}: invalid ${t}`);
		}
	}
}
//#endregion
//#region src/agents/sessions/model-registry-sources.ts
function captureProviderSource(...[e, t]) {
	return {
		...t === "authored" ? e : {
			api: e.api,
			baseUrl: e.baseUrl,
			compat: e.compat
		},
		models: e.models?.map((n) => {
			const { headers: r, ...i } = n;
			const a = t === "composed" ? n.maxTokensSource : t === "static" ? "discovered" : "configured";
			return Object.assign(t === "authored" ? n : i, {
				api: n.api ?? e.api,
				baseUrl: n.baseUrl ?? e.baseUrl,
				maxTokensSource: a,
				compat: t === "composed" ? n.compat : mergeCompat(e.compat, n.compat)
			});
		})
	};
}
function cloneMapValues(e) {
	return new Map([...e].map(([e, t]) => [e, { ...t }]));
}
function storeModelHeaders(e, t, n, r) {
	const i = JSON.stringify([t, n]);
	if (!r || Object.keys(r).length === 0) {
		e.delete(i);
		return;
	}
	e.set(i, r);
}
function mergeCompat(e, t) {
	if (!t) return e;
	const n = {
		...e,
		...t
	};
	for (const r of ["openRouterRouting", "vercelGatewayRouting"]) if (e?.[r] || t[r]) n[r] = {
		...e?.[r],
		...t[r]
	};
	return n;
}
async function readModelRegistryPluginCatalogs(e, t) {
	if (t.config?.models?.mode === "replace" || t.modelsJsonContents === null || t.modelsJsonContents === void 0 && !await canAccess(e)) return { catalogs: [] };
	try {
		return { catalogs: await loadPersistedPluginModelCatalogs(dirname(e)) };
	} catch (e) {
		return {
			catalogs: [],
			error: `Failed to load generated plugin model catalogs: ${e instanceof Error ? e.message : String(e)}`
		};
	}
}
function emptyCustomModelsResult(e) {
	return {
		providers: {},
		error: e
	};
}
function mergeProviderSources(...e) {
	const t = {};
	for (const n of e) for (const [e, r] of Object.entries(n)) {
		const n = t[e];
		t[e] = n ? mergeProviderModels(n, r, {
			providerId: e,
			modelIdMatching: "exact"
		}) : r;
	}
	return t;
}
function projectProviderRequestConfig(e) {
	if (!e.apiKey && !e.auth && !e.headers && !e.authHeader) return;
	return {
		baseUrls: e.baseUrl ? [e.baseUrl, ...(e.models ?? []).flatMap((e) => e.baseUrl ?? [])] : void 0,
		apiKey: e.apiKey,
		auth: e.auth,
		headers: e.headers,
		authHeader: e.authHeader
	};
}
/**
* Admits generated providers the catalog plugin still owns, then describes their listed models
* with the effective catalog rows (bundled plus hosted). Read-time only: callers that persist
* generated rows use the plain admission filter so stored rows stay as discovered.
*
* The account listing alone decides which models exist: an unlisted catalog row is never added,
* and a listed ID without a catalog row keeps its discovered values. For a listed ID with a catalog
* row, the catalog owns the metadata field by field. Generated rows carry no marker separating a
* provider-reported value from a discovery default (128k context, a $0 cost placeholder), so this
* applies the rule live discovery already applies to a plugin's own static rows: the catalog value
* wins and a discovered value fills only what the catalog omits. The row keeps its ID, route,
* declared non-chat kind, and explicit account-specific reasoning effort list.
*/
function readGeneratedPluginModelCatalogProviders(e) {
	const t = filterGeneratedPluginModelCatalogProviders(e);
	const n = e.pluginMetadataSnapshot?.manifestRegistry?.plugins.find((t) => t.id === e.catalogPluginId);
	if (!n?.modelCatalog?.providers) return t;
	return Object.fromEntries(Object.entries(t).map(([t, r]) => {
		if (!r.models?.length) return [t, r];
		const i = normalizeProviderId(t);
		const a = planEffectiveModelCatalogRows({
			registry: { plugins: [n] },
			config: e.config ?? {},
			providerFilter: i
		}).rows.filter((e) => e.provider === i);
		const o = new Map(a.map((e) => [e.id, e]));
		const s = new Map(buildEffectiveManifestProviderConfig(a)?.models.map((e) => [e.id, e]));
		const c = r.models.map((e) => {
			const t = o.get(e.id);
			const n = s.get(e.id);
			if (!t || !n) return e;
			const { api: r, baseUrl: i, headers: a, ...c } = n;
			const { inference: l, ...u } = e;
			const d = l?.chat === false ? l : t.inference;
			return {
				...u,
				...c,
				...e.compat?.supportedReasoningEfforts !== void 0 ? { compat: {
					...c.compat ?? e.compat,
					supportedReasoningEfforts: e.compat.supportedReasoningEfforts
				} } : {},
				...t.cost ? {} : { cost: e.cost },
				...d ? { inference: d } : {}
			};
		});
		return [t, {
			...r,
			models: c
		}];
	}));
}
//#endregion
//#region src/agents/sessions/provider-display-names.ts
/**
* Built-in provider labels shown in session/model UI when plugin metadata does
* not supply a display name.
*/
const BUILT_IN_PROVIDER_DISPLAY_NAMES = {
	anthropic: "Anthropic",
	"amazon-bedrock": "Amazon Bedrock",
	"azure-openai-responses": "Azure OpenAI Responses",
	cerebras: "Cerebras",
	"cloudflare-ai-gateway": "Cloudflare AI Gateway",
	"cloudflare-workers-ai": "Cloudflare Workers AI",
	deepseek: "DeepSeek",
	fireworks: "Fireworks",
	google: "Google Gemini",
	"google-vertex": "Google Vertex AI",
	groq: "Groq",
	huggingface: "Hugging Face",
	"kimi-coding": "Kimi For Coding",
	meta: "Meta",
	mistral: "Mistral",
	minimax: "MiniMax",
	"minimax-cn": "MiniMax (China)",
	moonshotai: "Moonshot AI",
	"moonshotai-cn": "Moonshot AI (China)",
	opencode: "OpenCode Zen",
	"opencode-go": "OpenCode Go",
	openai: "OpenAI",
	openrouter: "OpenRouter",
	together: "Together AI",
	"vercel-ai-gateway": "Vercel AI Gateway",
	xai: "xAI",
	zai: "ZAI",
	xiaomi: "Xiaomi MiMo",
	"xiaomi-token-plan-cn": "Xiaomi MiMo Token Plan (China)",
	"xiaomi-token-plan-ams": "Xiaomi MiMo Token Plan (Amsterdam)",
	"xiaomi-token-plan-sgp": "Xiaomi MiMo Token Plan (Singapore)"
};
//#endregion
//#region src/agents/sessions/model-registry.core.ts
const log = createSubsystemLogger("agents/model-registry");
var ModelRegistry = class ModelRegistry {
	constructor(e, t, n = {}, r, i) {
		this.models = [];
		this.providerRequestConfigs = /* @__PURE__ */ new Map();
		this.modelRequestHeaders = /* @__PURE__ */ new Map();
		this.registeredProviders = /* @__PURE__ */ new Map();
		this.loadError = void 0;
		this.includePluginCatalogs = true;
		this.authStorage = e;
		this.config = n.config ?? n.sourceSnapshot?.config;
		this.excludeGeneratedProviderIds = new Set(n.excludeGeneratedProviderIds);
		this.includePluginCatalogs = n.includePluginCatalogs !== false;
		this.reloadPluginCatalogs = this.includePluginCatalogs && n.pluginCatalogs === void 0;
		initializeModelRegistryRuntime(this);
		if (n.sourceSnapshot) {
			const t = n.sourceSnapshot;
			const i = t.baseCatalogSnapshot ?? t.captureCatalogSnapshot();
			const a = r ? {
				...i,
				models: [...i.models.filter((e) => !r.has(e.provider)), ...[...r.values()].flat()]
			} : i;
			this.sourceSnapshot = a;
			this.baseCatalogSnapshot = a;
			this.restoreSourceCatalog(a);
			this.registeredProviders = cloneMapValues(t.registeredProviders);
			getAuthStorageOAuthProviderRegistry(e).reset();
			for (const t of a.oauthProviders) getAuthStorageOAuthProviderRegistry(e).register(t);
			for (const [e, t] of this.registeredProviders.entries()) this.applyProviderConfig(e, t);
			return;
		}
		this.modelsJsonPath = t;
		this.modelsJsonContents = n.modelsJsonContents;
		this.pluginCatalogs = i?.catalogs ?? n.pluginCatalogs;
		this.pluginCatalogReadError = i?.error;
		this.staticProviderConfigs = n.staticProviderConfigs;
		this.pluginMetadataSnapshot = resolveModelPluginMetadataSnapshot({
			config: this.config,
			...n.pluginMetadataSnapshot ? { pluginMetadataSnapshot: n.pluginMetadataSnapshot } : {},
			...n.workspaceDir ? { workspaceDir: n.workspaceDir } : {},
			allowWorkspaceScopedCurrent: true
		});
		this.loadModels();
		this.baseCatalogSnapshot = this.captureCatalogSnapshot();
	}
	captureCatalogSnapshot() {
		return {
			models: structuredClone(this.models),
			providerRequestConfigs: cloneMapValues(this.providerRequestConfigs),
			modelRequestHeaders: cloneMapValues(this.modelRequestHeaders),
			loadError: this.loadError,
			pluginMetadataSnapshot: this.pluginMetadataSnapshot,
			oauthProviders: [...this.authStorage.getOAuthProviders()]
		};
	}
	restoreSourceCatalog(e) {
		this.models = structuredClone(e.models);
		this.providerRequestConfigs = cloneMapValues(e.providerRequestConfigs);
		this.modelRequestHeaders = cloneMapValues(e.modelRequestHeaders);
		this.loadError = e.loadError;
		this.pluginMetadataSnapshot = e.pluginMetadataSnapshot;
	}
	/** @deprecated Use createAsync or fromCapturedSources. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
	static create(e, t, n = {}) {
		if (n.pluginCatalogs === void 0 && n.includePluginCatalogs !== false) ModelRegistry.warnNativeCatalogRead("ModelRegistry.create", "ModelRegistry.createAsync");
		return new ModelRegistry(e, t, n);
	}
	/** Read persisted plugin catalogs through their worker before publishing the registry. */
	static async createAsync(e, t, n = {}) {
		const r = n.pluginCatalogs === void 0 && n.includePluginCatalogs !== false ? await readModelRegistryPluginCatalogs(t, n) : void 0;
		return new ModelRegistry(e, t, n, void 0, r);
	}
	/** Parse owner-prepared catalogs without opening their persistence store. */
	static fromCapturedSources(e, t, n) {
		return new ModelRegistry(e, t, n);
	}
	static warnNativeCatalogRead(e, t) {
		warnPluginSdkDeprecation({
			family: "model-registry-native-read",
			method: e,
			replacement: t
		});
	}
	static inMemory(e) {
		return new ModelRegistry(e, void 0);
	}
	/** Creates a request-isolated registry from this lifecycle-owned catalog snapshot. */
	fork(e, t) {
		return new ModelRegistry(e, void 0, { sourceSnapshot: this }, t);
	}
	/** @deprecated Await refreshAsync for disk-backed catalogs. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
	refresh() {
		if (this.reloadPluginCatalogs && this.modelsJsonPath) ModelRegistry.warnNativeCatalogRead("ModelRegistry.refresh", "ModelRegistry.refreshAsync");
		this.refreshFromStorage();
	}
	refreshFromStorage() {
		if (this.reloadPluginCatalogs && this.modelsJsonPath) {
			this.pluginCatalogs = void 0;
			this.pluginCatalogReadError = void 0;
		}
		this.reload();
	}
	async refreshAsync() {
		if (this.reloadPluginCatalogs && this.modelsJsonPath) {
			const e = await readModelRegistryPluginCatalogs(this.modelsJsonPath, {
				config: this.config,
				modelsJsonContents: this.modelsJsonContents
			});
			this.pluginCatalogs = e.catalogs;
			this.pluginCatalogReadError = e.error;
		}
		this.reload();
	}
	reload() {
		this.providerRequestConfigs.clear();
		this.modelRequestHeaders.clear();
		this.loadError = void 0;
		resetModelRegistryRuntime(this);
		getAuthStorageOAuthProviderRegistry(this.authStorage).reset();
		if (this.sourceSnapshot) {
			this.restoreSourceCatalog(this.sourceSnapshot);
			for (const e of this.sourceSnapshot.oauthProviders) getAuthStorageOAuthProviderRegistry(this.authStorage).register(e);
		} else {
			this.loadModels();
			this.baseCatalogSnapshot = this.captureCatalogSnapshot();
		}
		for (const [e, t] of this.registeredProviders.entries()) this.applyProviderConfig(e, t);
	}
	/** Get any root or generated plugin catalog load error. */
	getError() {
		return this.loadError;
	}
	/** Returns the exact plugin metadata generation captured with this registry. */
	getProviderMetadataOwners() {
		return this.pluginMetadataSnapshot?.owners;
	}
	loadModels() {
		const e = this.config?.models?.mode === "replace";
		const t = !e && this.modelsJsonPath && this.modelsJsonContents !== null ? this.loadCustomModels(this.modelsJsonPath, {
			...this.modelsJsonContents !== void 0 ? { contents: this.modelsJsonContents } : {},
			includePluginCatalogs: this.includePluginCatalogs && this.pluginCatalogs === void 0
		}) : emptyCustomModelsResult();
		const n = !e && this.includePluginCatalogs && this.pluginCatalogs !== void 0 ? this.loadCapturedPluginCatalogs(this.pluginCatalogs) : emptyCustomModelsResult();
		const r = [
			t.error,
			n.error,
			this.pluginCatalogReadError
		].filter((e) => Boolean(e));
		if (!e && this.modelsJsonPath && this.modelsJsonContents === void 0 && this.reloadPluginCatalogs && this.staticProviderConfigs === void 0 && this.includePluginCatalogs) {
			const e = inspectLegacyPluginModelCatalogs(dirname(this.modelsJsonPath));
			const t = [...e.warnings, ...e.catalogs.map(({ pathname: e }) => `Legacy generated provider catalog: ${e}`)];
			if (t.length > 0) r.push(`${t.join("\n")}\nRun openclaw doctor --fix to verify and import legacy provider catalogs.`);
		}
		if (r.length > 0) {
			this.loadError = r.join("\n\n");
			log.warn(`model catalog load issue: ${this.loadError}`);
		}
		const i = mergeProviderSources(e ? {} : Object.fromEntries(Object.entries(this.staticProviderConfigs ?? {}).map(([e, t]) => [e, captureProviderSource(t, "static")])), n.providers, t.providers);
		const a = buildSourceModelFields(materializeConfiguredProviderCatalogModels(this.config && projectConfigOntoRuntimeSourceSnapshot(this.config).models?.providers, { manifestPlugins: this.pluginMetadataSnapshot }));
		for (const [e, t] of Object.entries(normalizeProviderMapKeys(materializeConfiguredProviderCatalogModels(this.config?.models?.providers, { manifestPlugins: this.pluginMetadataSnapshot })))) {
			const n = i[e];
			const r = new Map(n?.models?.map((e) => [e.id, e]));
			const o = {
				api: t.api,
				baseUrl: t.baseUrl,
				models: t.models?.map((e) => ({
					...e,
					api: e.api ?? r.get(e.id)?.api ?? t.api,
					baseUrl: e.baseUrl ?? r.get(e.id)?.baseUrl ?? t.baseUrl,
					maxTokensSource: "configured",
					headers: sanitizeModelHeaders(e.headers)
				}))
			};
			i[e] = n ? mergeProviderModels(captureProviderSource(n, "composed"), o, {
				providerId: e,
				modelIdMatching: "exact",
				sourceModelFields: a
			}) : o;
			this.providerRequestConfigs.delete(e);
			this.storeProviderRequestConfig(e, {
				apiKey: normalizeOptionalSecretInput(t.apiKey),
				auth: t.auth,
				authHeader: t.authHeader,
				headers: sanitizeModelHeaders(t.headers)
			});
		}
		let o = this.parseModels(i);
		for (const e of this.authStorage.getOAuthProviders()) {
			const t = this.authStorage.get(e.id);
			if (t?.type === "oauth" && e.modifyModels) o = e.modifyModels(o, t);
		}
		this.models = o;
	}
	loadCapturedPluginCatalogs(e) {
		let t = {};
		const n = [];
		for (const r of e) {
			const e = this.loadCustomModels(`sqlite:plugin-model-catalog/${r.pluginId}`, {
				catalogPluginId: r.pluginId,
				contents: r.contents,
				includePluginCatalogs: false,
				requireGeneratedCatalog: true
			});
			t = mergeProviderSources(t, e.providers);
			if (e.error) n.push(e.error);
		}
		return {
			providers: t,
			error: n.join("\n\n") || void 0
		};
	}
	loadCustomModels(e, t = { includePluginCatalogs: true }) {
		if (t.contents === void 0 && !existsSync(e)) return emptyCustomModelsResult();
		try {
			const n = t.contents ?? readFileSync(e, "utf-8");
			const r = parseModelCatalogJson(n);
			if (t.requireGeneratedCatalog === true && !isGeneratedPluginModelCatalog(r)) return emptyCustomModelsResult();
			const i = validateModelsConfig.Check(r);
			const a = i ? void 0 : omitInvalidModelCosts(r);
			if (!i && !validateModelsConfig.Check(r)) {
				const t = validateModelsConfig.Errors(r).map((e) => `  - ${formatValidationPath(e)}: ${e.message}`).join("\n") || "Unknown schema error";
				return emptyCustomModelsResult(`Invalid models.json schema:\n${t}\n\nFile: ${e}`);
			}
			const o = t.requireGeneratedCatalog === true ? readGeneratedPluginModelCatalogProviders({
				catalogPluginId: t.catalogPluginId,
				config: this.config,
				isProviderAvailable: (e) => this.authStorage.hasAuth(normalizeProviderId(e)) || hasUsableCustomProviderApiKey(this.config, e) || resolveManagedSecretRefRuntimeProviderAuth({
					cfg: this.config,
					provider: e
				}) !== void 0,
				parsedCatalog: r,
				pluginMetadataSnapshot: this.pluginMetadataSnapshot,
				providers: r.providers
			}) : r.providers;
			if (t.requireGeneratedCatalog === true && Object.keys(o).length === 0) return emptyCustomModelsResult();
			const s = [];
			for (const [n, r] of Object.entries(o)) {
				validateProviderModels(n, r, "catalog");
				if (a?.size && r.models) r.models = r.models.filter((r) => {
					if (!a.has(r)) return true;
					const i = t.requireGeneratedCatalog ? "the provider's catalog source" : e;
					s.push(`Skipped model ${n}/${r.id}: invalid cost. Fix or remove its cost block in ${i}, then refresh the model catalog.`);
					return false;
				});
			}
			const c = t.requireGeneratedCatalog === true;
			let l = {};
			for (const [e, t] of Object.entries(o)) {
				if (c && this.excludeGeneratedProviderIds.has(normalizeProviderId(e))) continue;
				if (!c && (t.models ?? []).length > 0) this.storeProviderRequestConfig(e, t);
				l[e] = c ? captureProviderSource(t, "static") : captureProviderSource(t, "authored");
			}
			const u = s.map((t) => `${t}\nFile: ${e}`);
			if (t.includePluginCatalogs !== false) {
				let t = [];
				try {
					t = loadPersistedPluginModelCatalogsReadOnly(dirname(e));
				} catch (e) {
					u.push(`Failed to load generated plugin model catalogs: ${e instanceof Error ? e.message : String(e)}`);
				}
				const n = this.loadCapturedPluginCatalogs(t);
				l = mergeProviderSources(n.providers, l);
				if (n.error) u.push(`${n.error}\nRun openclaw doctor --fix to repair persisted generated provider catalogs.`);
			}
			return {
				providers: l,
				error: u.join("\n\n") || void 0
			};
		} catch (n) {
			if (n instanceof SyntaxError) {
				if (t.requireGeneratedCatalog === true) return emptyCustomModelsResult();
				return emptyCustomModelsResult(`Failed to parse models.json: ${n.message}\n\nFile: ${e}`);
			}
			return emptyCustomModelsResult(`Failed to load models.json: ${n instanceof Error ? n.message : String(n)}\n\nFile: ${e}`);
		}
	}
	parseModels(e) {
		const t = [];
		for (const [n, r] of Object.entries(e)) for (const e of r.models ?? []) {
			const i = e.api ?? r.api;
			if (!i) continue;
			const a = e.baseUrl ?? r.baseUrl;
			if (!a) continue;
			const o = (e.input ?? ["text"]).filter((e) => e === "text" || e === "image");
			if ((e.input?.length ?? 0) > 0 && o.length === 0) continue;
			storeModelHeaders(this.modelRequestHeaders, n, e.id, e.headers);
			t.push(createRegistryRuntimeModel(n, r, e, i, {
				baseUrl: a,
				input: o
			}));
		}
		return t;
	}
	getAll() {
		return this.models;
	}
	/**
	* Get only models that have auth configured.
	* This is a fast check that doesn't refresh OAuth tokens.
	*/
	getAvailable() {
		return this.models.filter((e) => this.hasConfiguredAuth(e));
	}
	find(e, t) {
		return this.models.find((n) => n.provider === e && n.id === t);
	}
	hasConfiguredAuth(e) {
		const t = this.getModelProviderRequestConfig(e);
		if (t?.auth === "none") return e.api === "openai-completions";
		return this.authStorage.hasAuth(e.provider) || t?.auth === "aws-sdk" || t?.apiKey !== void 0;
	}
	getModelProviderRequestConfig(e) {
		return scopeModelProviderRequestConfig(this.providerRequestConfigs.get(e.provider), e);
	}
	storeProviderRequestConfig(e, t) {
		const n = projectProviderRequestConfig(t);
		if (n) this.providerRequestConfigs.set(e, n);
	}
	async getApiKeyAndHeaders(e) {
		return resolveModelRegistryRequestAuth({
			model: e,
			providerConfig: this.getModelProviderRequestConfig(e),
			modelHeaders: this.modelRequestHeaders.get(JSON.stringify([e.provider, e.id])),
			authStorage: this.authStorage
		});
	}
	/**
	* Return auth status for a provider, including request auth configured in models.json.
	* This intentionally does not execute command-backed config values.
	*/
	getProviderAuthStatus(e) {
		const t = this.providerRequestConfigs.get(e);
		if (t?.auth === "aws-sdk") return {
			configured: true,
			source: "models_json_key",
			label: t.auth
		};
		const n = this.authStorage.getAuthStatus(e);
		if (n.source) return n;
		const r = t?.apiKey;
		if (!r) return n;
		if (r.startsWith("!")) return {
			configured: true,
			source: "models_json_command"
		};
		if (process.env[r]) return {
			configured: true,
			source: "environment",
			label: r
		};
		return {
			configured: true,
			source: "models_json_key"
		};
	}
	getProviderDisplayName(e) {
		const t = this.registeredProviders.get(e);
		const n = this.authStorage.getOAuthProviders().find((t) => t.id === e);
		return t?.name ?? t?.oauth?.name ?? n?.name ?? BUILT_IN_PROVIDER_DISPLAY_NAMES[e] ?? e;
	}
	async getApiKeyForProvider(e) {
		const t = await this.authStorage.getApiKey(e, { includeFallback: false });
		const n = this.providerRequestConfigs.get(e)?.apiKey;
		return t ?? (n ? resolveConfigValueUncached(n) : void 0);
	}
	isUsingOAuth(e) {
		return this.authStorage.get(e.provider)?.type === "oauth";
	}
	/**
	* Register a provider dynamically (from extensions).
	*
	* If provider has models: replaces all existing models for this provider.
	* Provider-level request settings are stored for already-known models but
	* never create implicit model rows.
	* If provider has oauth: registers OAuth provider for /login support.
	*/
	registerProvider(e, t) {
		if (t.streamSimple && !t.api) throw new Error(`Provider ${e}: "api" is required when registering streamSimple.`);
		validateProviderModels(e, t, "registration");
		this.applyProviderConfig(e, t);
		const n = this.registeredProviders.get(e);
		if (!n) {
			this.registeredProviders.set(e, t);
			return;
		}
		for (const e of Object.keys(t)) if (t[e] !== void 0) n[e] = t[e];
	}
	/**
	* Unregister a previously registered provider.
	*
	* Removes the provider from the registry and reloads models from disk.
	* Also resets dynamic OAuth and API stream registrations before reapplying
	* remaining dynamic providers.
	* Has no effect if the provider was never registered.
	* @deprecated Use unregisterProviderAsync for disk-backed registries. Supported through 2026-12-31; removal ships in the first January 2027 stable release.
	*/
	unregisterProvider(e) {
		if (this.reloadPluginCatalogs && this.modelsJsonPath) ModelRegistry.warnNativeCatalogRead("ModelRegistry.unregisterProvider", "ModelRegistry.unregisterProviderAsync");
		if (!this.registeredProviders.delete(e)) return;
		this.refreshFromStorage();
	}
	async unregisterProviderAsync(e) {
		if (!this.registeredProviders.delete(e)) return;
		await this.refreshAsync();
	}
	applyProviderConfig(e, t) {
		if (t.oauth) {
			const n = {
				...t.oauth,
				id: e
			};
			getAuthStorageOAuthProviderRegistry(this.authStorage).register(n);
		}
		if (t.streamSimple) {
			const n = t.streamSimple;
			getModelRegistryRuntime(this).apiRegistry.registerApiProvider({
				api: t.api,
				stream: (e, t, r) => n(e, t, r),
				streamSimple: n
			}, `provider:${e}`);
		}
		this.storeProviderRequestConfig(e, t);
		if (t.models && t.models.length > 0) {
			this.models = this.models.filter((t) => t.provider !== e);
			for (const n of t.models) {
				const r = n.api || t.api;
				storeModelHeaders(this.modelRequestHeaders, e, n.id, n.headers);
				this.models.push(createRegistryRuntimeModel(e, t, n, r));
			}
			if (t.oauth?.modifyModels) {
				const n = this.authStorage.get(e);
				if (n?.type === "oauth") this.models = t.oauth.modifyModels(this.models, n);
			}
		}
	}
};
//#endregion
export { resolveModelWorkspaceDir as i, getModelRegistryRuntime as n, resolveModelPluginMetadataSnapshot as r, ModelRegistry as t };