import { t as createNonExitingRuntime } from "../runtime-CgZZEqw7.js";
import { t as clearRuntimeAuthProfileStoreSnapshots } from "../store-DLavseDR.js";
import { a as providerContractLoadError, c as resolveWebFetchProviderContractEntriesForPluginId, i as pluginRegistrationContractRegistry, l as resolveWebSearchProviderContractEntriesForPluginId, o as requireProviderContractProvider$1, s as resolveProviderContractProvidersForPluginIds } from "../registry-DMvaVAzc.js";
import { a as beforeEach, i as beforeAll, n as vi, o as describe, r as afterEach, s as it, t as globalExpect } from "../test.p_J6dB8a-Dyq-JxSD.js";
import { i as resolveProviderWizardOptions, n as resolveProviderModelPickerEntries, r as resolveProviderPluginChoice, t as buildProviderPluginMethodChoice } from "../provider-wizard-GPrV7lib.js";
import { t as withFetchPreconnect } from "../fetch-mock-EAzg-1iq.js";
import { r as requireRegisteredProvider, t as registerProviderPlugins } from "../plugin-registration-B1l-RleS.js";
import "../contracts-testkit-Dyvcxwml.js";
import { n as requireRegisteredProvider$1, t as registerProviderPlugin } from "../provider-registration--trCn8jN.js";
import path from "node:path";
import os from "node:os";
import fs from "node:fs/promises";
//#region test/helpers/plugins/provider-contract-suites.ts
function resolveLazy(value) {
	return typeof value === "function" ? value() : value;
}
function installProviderPluginContractSuite(params) {
	it("satisfies the base provider plugin contract", () => {
		const provider = resolveLazy(params.provider);
		const authIds = provider.auth.map((method) => method.id);
		const wizardChoiceIds = /* @__PURE__ */ new Set();
		globalExpect(provider.id).toMatch(/^[a-z0-9][a-z0-9-]*$/);
		globalExpect(provider.label.trim()).not.toBe("");
		if (provider.docsPath) globalExpect(provider.docsPath.startsWith("/")).toBe(true);
		if (provider.aliases) globalExpect(provider.aliases).toEqual([...new Set(provider.aliases)]);
		if (provider.envVars) {
			globalExpect(provider.envVars).toEqual([...new Set(provider.envVars)]);
			globalExpect(provider.envVars.every((entry) => entry.trim().length > 0)).toBe(true);
		}
		globalExpect(Array.isArray(provider.auth)).toBe(true);
		globalExpect(authIds).toEqual([...new Set(authIds)]);
		for (const method of provider.auth) {
			globalExpect(method.id.trim()).not.toBe("");
			globalExpect(method.label.trim()).not.toBe("");
			if (method.hint !== void 0) globalExpect(method.hint.trim()).not.toBe("");
			if (method.wizard) {
				if (method.wizard.choiceId) {
					globalExpect(method.wizard.choiceId.trim()).not.toBe("");
					globalExpect(wizardChoiceIds.has(method.wizard.choiceId)).toBe(false);
					wizardChoiceIds.add(method.wizard.choiceId);
				}
				if (method.wizard.methodId) globalExpect(authIds).toContain(method.wizard.methodId);
				if (method.wizard.modelAllowlist?.allowedKeys) globalExpect(method.wizard.modelAllowlist.allowedKeys).toEqual([...new Set(method.wizard.modelAllowlist.allowedKeys)]);
				if (method.wizard.modelAllowlist?.initialSelections) globalExpect(method.wizard.modelAllowlist.initialSelections).toEqual([...new Set(method.wizard.modelAllowlist.initialSelections)]);
			}
			globalExpect(typeof method.run).toBe("function");
		}
		if (provider.wizard?.setup || provider.wizard?.modelPicker) globalExpect(provider.auth.length).toBeGreaterThan(0);
		if (provider.wizard?.setup) {
			if (provider.wizard.setup.choiceId) {
				globalExpect(provider.wizard.setup.choiceId.trim()).not.toBe("");
				globalExpect(wizardChoiceIds.has(provider.wizard.setup.choiceId)).toBe(false);
			}
			if (provider.wizard.setup.methodId) globalExpect(authIds).toContain(provider.wizard.setup.methodId);
			if (provider.wizard.setup.modelAllowlist?.allowedKeys) globalExpect(provider.wizard.setup.modelAllowlist.allowedKeys).toEqual([...new Set(provider.wizard.setup.modelAllowlist.allowedKeys)]);
			if (provider.wizard.setup.modelAllowlist?.initialSelections) globalExpect(provider.wizard.setup.modelAllowlist.initialSelections).toEqual([...new Set(provider.wizard.setup.modelAllowlist.initialSelections)]);
		}
		if (provider.wizard?.modelPicker?.methodId) globalExpect(authIds).toContain(provider.wizard.modelPicker.methodId);
	});
}
function installWebSearchProviderContractSuite(params) {
	it("satisfies the base web search provider contract", () => {
		const provider = resolveLazy(params.provider);
		const credentialValue = resolveLazy(params.credentialValue);
		globalExpect(provider.id).toMatch(/^[a-z0-9][a-z0-9-]*$/);
		globalExpect(provider.label.trim()).not.toBe("");
		globalExpect(provider.hint.trim()).not.toBe("");
		globalExpect(provider.placeholder.trim()).not.toBe("");
		globalExpect(provider.signupUrl.startsWith("https://")).toBe(true);
		if (provider.docsUrl) globalExpect(provider.docsUrl.startsWith("http")).toBe(true);
		globalExpect(provider.envVars).toEqual([...new Set(provider.envVars)]);
		globalExpect(provider.envVars.every((entry) => entry.trim().length > 0)).toBe(true);
		const searchConfigTarget = {};
		provider.setCredentialValue(searchConfigTarget, credentialValue);
		globalExpect(provider.getCredentialValue(searchConfigTarget)).toEqual(credentialValue);
		const config = { tools: { web: { search: {
			provider: provider.id,
			...searchConfigTarget
		} } } };
		const tool = provider.createTool({
			config,
			searchConfig: searchConfigTarget
		});
		globalExpect(tool).not.toBeNull();
		globalExpect(tool?.description.trim()).not.toBe("");
		globalExpect(tool?.parameters).toEqual(globalExpect.any(Object));
		globalExpect(typeof tool?.execute).toBe("function");
		if (provider.runSetup) globalExpect(typeof provider.runSetup).toBe("function");
	});
}
function installWebFetchProviderContractSuite(params) {
	it("satisfies the base web fetch provider contract", () => {
		const provider = resolveLazy(params.provider);
		const credentialValue = resolveLazy(params.credentialValue);
		globalExpect(provider.id).toMatch(/^[a-z0-9][a-z0-9-]*$/);
		globalExpect(provider.label.trim()).not.toBe("");
		globalExpect(provider.hint.trim()).not.toBe("");
		globalExpect(provider.placeholder.trim()).not.toBe("");
		globalExpect(provider.signupUrl.startsWith("https://")).toBe(true);
		if (provider.docsUrl) globalExpect(provider.docsUrl.startsWith("http")).toBe(true);
		globalExpect(provider.envVars).toEqual([...new Set(provider.envVars)]);
		globalExpect(provider.envVars.every((entry) => entry.trim().length > 0)).toBe(true);
		globalExpect(provider.credentialPath.trim()).not.toBe("");
		if (provider.inactiveSecretPaths) {
			globalExpect(provider.inactiveSecretPaths).toEqual([...new Set(provider.inactiveSecretPaths)]);
			globalExpect(provider.inactiveSecretPaths).toContain(provider.credentialPath);
		}
		const fetchConfigTarget = {};
		provider.setCredentialValue(fetchConfigTarget, credentialValue);
		globalExpect(provider.getCredentialValue(fetchConfigTarget)).toEqual(credentialValue);
		if (provider.setConfiguredCredentialValue && provider.getConfiguredCredentialValue) {
			const configTarget = {};
			provider.setConfiguredCredentialValue(configTarget, credentialValue);
			globalExpect(provider.getConfiguredCredentialValue(configTarget)).toEqual(credentialValue);
		}
		if (provider.applySelectionConfig && params.pluginId) globalExpect(provider.applySelectionConfig({}).plugins?.entries?.[params.pluginId]?.enabled).toBe(true);
		const config = { tools: { web: { fetch: {
			provider: provider.id,
			...fetchConfigTarget
		} } } };
		const tool = provider.createTool({
			config,
			fetchConfig: fetchConfigTarget
		});
		globalExpect(tool).not.toBeNull();
		globalExpect(tool?.description.trim()).not.toBe("");
		globalExpect(tool?.parameters).toEqual(globalExpect.any(Object));
		globalExpect(typeof tool?.execute).toBe("function");
	});
}
//#endregion
//#region test/helpers/plugins/provider-contract.ts
function describeProviderContracts(pluginId) {
	const providerIds = pluginRegistrationContractRegistry.find((entry) => entry.pluginId === pluginId)?.providerIds ?? [];
	describe(`${pluginId} provider contract registry load`, () => {
		it("loads bundled providers without import-time registry failure", () => {
			const providers = resolveProviderContractProvidersForPluginIds([pluginId]);
			globalExpect(providerContractLoadError).toBeUndefined();
			globalExpect(providers.length).toBeGreaterThan(0);
		});
	});
	for (const providerId of providerIds) describe(`${pluginId}:${providerId} provider contract`, () => {
		installProviderPluginContractSuite({ provider: () => requireProviderContractProvider$1(providerId) });
	});
}
//#endregion
//#region src/test-utils/provider-usage-fetch.ts
function makeResponse(status, body) {
	const payload = typeof body === "string" ? body : JSON.stringify(body);
	return new Response(payload, {
		status,
		headers: typeof body === "string" ? void 0 : { "Content-Type": "application/json" }
	});
}
function toRequestUrl(input) {
	return typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
}
function createProviderUsageFetch(handler) {
	return withFetchPreconnect(vi.fn(async (input, init) => handler(toRequestUrl(input), init)));
}
//#endregion
//#region test/helpers/plugins/provider-runtime-contract.ts
const CONTRACT_SETUP_TIMEOUT_MS = 3e5;
const refreshOpenAICodexTokenMock = vi.hoisted(() => vi.fn());
const getOAuthProvidersMock = vi.hoisted(() => vi.fn(() => [
	{
		id: "anthropic",
		envApiKey: "ANTHROPIC_API_KEY",
		oauthTokenEnv: "ANTHROPIC_OAUTH_TOKEN"
	},
	{
		id: "google",
		envApiKey: "GOOGLE_API_KEY",
		oauthTokenEnv: "GOOGLE_OAUTH_TOKEN"
	},
	{
		id: "openai-codex",
		envApiKey: "OPENAI_API_KEY",
		oauthTokenEnv: "OPENAI_OAUTH_TOKEN"
	}
]));
const providerRuntimeContractModules = vi.hoisted(() => ({
	anthropicIndexModuleId: "../../../extensions/anthropic/index.ts",
	githubCopilotIndexModuleId: "../../../extensions/github-copilot/index.ts",
	googleIndexModuleId: "../../../extensions/google/index.ts",
	openAIIndexModuleId: "../../../extensions/openai/index.ts",
	openAICodexProviderRuntimeModuleId: "../../../extensions/openai/openai-codex-provider.runtime.js",
	openRouterIndexModuleId: "../../../extensions/openrouter/index.ts",
	veniceIndexModuleId: "../../../extensions/venice/index.ts",
	xAIIndexModuleId: "../../../extensions/xai/index.ts",
	zaiIndexModuleId: "../../../extensions/zai/index.ts"
}));
vi.mock("@earendil-works/pi-ai/oauth", async () => {
	return {
		...await vi.importActual("@earendil-works/pi-ai/oauth"),
		refreshOpenAICodexToken: refreshOpenAICodexTokenMock,
		getOAuthProviders: getOAuthProvidersMock
	};
});
vi.mock(providerRuntimeContractModules.openAICodexProviderRuntimeModuleId, () => ({ refreshOpenAICodexToken: refreshOpenAICodexTokenMock }));
async function importBundledProviderPlugin$2(moduleUrl) {
	return await import(moduleUrl);
}
function createModel(overrides) {
	return {
		id: overrides.id,
		name: overrides.name ?? overrides.id,
		api: overrides.api ?? "openai-responses",
		provider: overrides.provider ?? "demo",
		baseUrl: overrides.baseUrl ?? "https://api.example.com/v1",
		reasoning: overrides.reasoning ?? true,
		input: overrides.input ?? ["text"],
		cost: overrides.cost ?? {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0
		},
		contextWindow: overrides.contextWindow ?? 2e5,
		maxTokens: overrides.maxTokens ?? 8192
	};
}
const PROVIDER_RUNTIME_CONTRACT_FIXTURES = [
	{
		providerIds: ["anthropic"],
		pluginId: "anthropic",
		name: "Anthropic",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.anthropicIndexModuleId)
	},
	{
		providerIds: ["github-copilot"],
		pluginId: "github-copilot",
		name: "GitHub Copilot",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.githubCopilotIndexModuleId)
	},
	{
		providerIds: ["google", "google-gemini-cli"],
		pluginId: "google",
		name: "Google",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.googleIndexModuleId)
	},
	{
		providerIds: ["openai", "openai-codex"],
		pluginId: "openai",
		name: "OpenAI",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.openAIIndexModuleId)
	},
	{
		providerIds: ["openrouter"],
		pluginId: "openrouter",
		name: "OpenRouter",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.openRouterIndexModuleId)
	},
	{
		providerIds: ["venice"],
		pluginId: "venice",
		name: "Venice",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.veniceIndexModuleId)
	},
	{
		providerIds: ["xai"],
		pluginId: "xai",
		name: "xAI",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.xAIIndexModuleId)
	},
	{
		providerIds: ["zai"],
		pluginId: "zai",
		name: "Z.AI",
		load: async () => await importBundledProviderPlugin$2(providerRuntimeContractModules.zaiIndexModuleId)
	}
];
const providerRuntimeContractProviders = /* @__PURE__ */ new Map();
let providerRuntimeContractLoadPromise = null;
function requireProviderContractProvider(providerId) {
	const provider = providerRuntimeContractProviders.get(providerId);
	if (!provider) throw new Error(`provider runtime contract fixture missing for ${providerId}`);
	return provider;
}
async function ensureProviderRuntimeContractProvidersLoaded() {
	if (!providerRuntimeContractLoadPromise) providerRuntimeContractLoadPromise = (async () => {
		providerRuntimeContractProviders.clear();
		const registeredFixtures = await Promise.all(PROVIDER_RUNTIME_CONTRACT_FIXTURES.map(async (fixture) => {
			return {
				fixture,
				providers: (await registerProviderPlugin({
					plugin: (await fixture.load()).default,
					id: fixture.pluginId,
					name: fixture.name
				})).providers
			};
		}));
		for (const { fixture, providers } of registeredFixtures) for (const providerId of fixture.providerIds) providerRuntimeContractProviders.set(providerId, requireRegisteredProvider$1(providers, providerId, "provider"));
	})();
	await providerRuntimeContractLoadPromise;
}
function installRuntimeHooks() {
	beforeAll(async () => {
		await ensureProviderRuntimeContractProvidersLoaded();
	}, CONTRACT_SETUP_TIMEOUT_MS);
	beforeEach(() => {
		refreshOpenAICodexTokenMock.mockReset();
		getOAuthProvidersMock.mockClear();
	}, CONTRACT_SETUP_TIMEOUT_MS);
}
function describeAnthropicProviderRuntimeContract() {
	describe("anthropic provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns anthropic 4.6 forward-compat resolution", () => {
			const model = requireProviderContractProvider("anthropic").resolveDynamicModel?.({
				provider: "anthropic",
				modelId: "claude-sonnet-4.6-20260219",
				modelRegistry: { find: (_provider, id) => id === "claude-sonnet-4.5-20260219" ? createModel({
					id,
					api: "anthropic-messages",
					provider: "anthropic",
					baseUrl: "https://api.anthropic.com"
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "claude-sonnet-4.6-20260219",
				provider: "anthropic",
				api: "anthropic-messages",
				baseUrl: "https://api.anthropic.com"
			});
		});
		it("owns usage auth resolution", async () => {
			await globalExpect(requireProviderContractProvider("anthropic").resolveUsageAuth?.({
				config: {},
				env: {},
				provider: "anthropic",
				resolveApiKeyFromConfigAndStore: () => void 0,
				resolveOAuthToken: async () => ({ token: "anthropic-oauth-token" })
			})).resolves.toEqual({ token: "anthropic-oauth-token" });
		});
		it("owns auth doctor hint generation", () => {
			const hint = requireProviderContractProvider("anthropic").buildAuthDoctorHint?.({
				provider: "anthropic",
				profileId: "anthropic:default",
				config: { auth: { profiles: { "anthropic:default": {
					provider: "anthropic",
					mode: "oauth"
				} } } },
				store: {
					version: 1,
					profiles: { "anthropic:oauth-user@example.com": {
						type: "oauth",
						provider: "anthropic",
						access: "oauth-access",
						refresh: "oauth-refresh",
						expires: Date.now() + 6e4
					} }
				}
			});
			globalExpect(hint).toContain("suggested profile: anthropic:oauth-user@example.com");
			globalExpect(hint).toContain("kaijibot doctor --yes");
		});
		it("owns usage snapshot fetching", async () => {
			const provider = requireProviderContractProvider("anthropic");
			const mockFetch = createProviderUsageFetch(async (url) => {
				if (url.includes("api.anthropic.com/api/oauth/usage")) return makeResponse(200, {
					five_hour: {
						utilization: 20,
						resets_at: "2026-01-07T01:00:00Z"
					},
					seven_day: {
						utilization: 35,
						resets_at: "2026-01-09T01:00:00Z"
					}
				});
				return makeResponse(404, "not found");
			});
			await globalExpect(provider.fetchUsageSnapshot?.({
				config: {},
				env: {},
				provider: "anthropic",
				token: "anthropic-oauth-token",
				timeoutMs: 5e3,
				fetchFn: mockFetch
			})).resolves.toEqual({
				provider: "anthropic",
				displayName: "Claude",
				windows: [{
					label: "5h",
					usedPercent: 20,
					resetAt: Date.parse("2026-01-07T01:00:00Z")
				}, {
					label: "Week",
					usedPercent: 35,
					resetAt: Date.parse("2026-01-09T01:00:00Z")
				}]
			});
		});
	});
}
function describeGithubCopilotProviderRuntimeContract() {
	describe("github-copilot provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns Copilot-specific forward-compat fallbacks", () => {
			const model = requireProviderContractProvider("github-copilot").resolveDynamicModel?.({
				provider: "github-copilot",
				modelId: "gpt-5.4",
				modelRegistry: { find: (_provider, id) => id === "gpt-5.2-codex" ? createModel({
					id,
					api: "openai-codex-responses",
					provider: "github-copilot",
					baseUrl: "https://api.copilot.example"
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gpt-5.4",
				provider: "github-copilot",
				api: "openai-codex-responses"
			});
		});
	});
}
function describeGoogleProviderRuntimeContract() {
	describe("google provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns google direct gemini 3.1 forward-compat resolution", () => {
			const model = requireProviderContractProvider("google").resolveDynamicModel?.({
				provider: "google",
				modelId: "gemini-3.1-pro-preview",
				modelRegistry: { find: (_provider, id) => id === "gemini-3-pro-preview" ? createModel({
					id,
					api: "google-generative-ai",
					provider: "google",
					baseUrl: "https://generativelanguage.googleapis.com",
					reasoning: false,
					contextWindow: 1048576,
					maxTokens: 65536
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gemini-3.1-pro-preview",
				provider: "google",
				api: "google-generative-ai",
				baseUrl: "https://generativelanguage.googleapis.com",
				reasoning: true
			});
		});
		it("owns gemini cli 3.1 forward-compat resolution", () => {
			const model = requireProviderContractProvider("google-gemini-cli").resolveDynamicModel?.({
				provider: "google-gemini-cli",
				modelId: "gemini-3.1-pro-preview",
				modelRegistry: { find: (_provider, id) => id === "gemini-3-pro-preview" ? createModel({
					id,
					api: "google-gemini-cli",
					provider: "google-gemini-cli",
					baseUrl: "https://cloudcode-pa.googleapis.com",
					reasoning: false,
					contextWindow: 1048576,
					maxTokens: 65536
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gemini-3.1-pro-preview",
				provider: "google-gemini-cli",
				reasoning: true
			});
		});
		it("owns usage-token parsing", async () => {
			await globalExpect(requireProviderContractProvider("google-gemini-cli").resolveUsageAuth?.({
				config: {},
				env: {},
				provider: "google-gemini-cli",
				resolveApiKeyFromConfigAndStore: () => void 0,
				resolveOAuthToken: async () => ({
					token: "{\"token\":\"google-oauth-token\"}",
					accountId: "google-account"
				})
			})).resolves.toEqual({
				token: "google-oauth-token",
				accountId: "google-account"
			});
		});
		it("owns OAuth auth-profile formatting", () => {
			globalExpect(requireProviderContractProvider("google-gemini-cli").formatApiKey?.({
				type: "oauth",
				provider: "google-gemini-cli",
				access: "google-oauth-token",
				refresh: "refresh-token",
				expires: Date.now() + 6e4,
				projectId: "proj-123"
			})).toBe("{\"token\":\"google-oauth-token\",\"projectId\":\"proj-123\"}");
		});
		it("owns usage snapshot fetching", async () => {
			const provider = requireProviderContractProvider("google-gemini-cli");
			const mockFetch = createProviderUsageFetch(async (url) => {
				if (url.includes("cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota")) return makeResponse(200, { buckets: [{
					modelId: "gemini-3.1-pro-preview",
					remainingFraction: .4
				}, {
					modelId: "gemini-3.1-flash-preview",
					remainingFraction: .8
				}] });
				return makeResponse(404, "not found");
			});
			const snapshot = await provider.fetchUsageSnapshot?.({
				config: {},
				env: {},
				provider: "google-gemini-cli",
				token: "google-oauth-token",
				timeoutMs: 5e3,
				fetchFn: mockFetch
			});
			globalExpect(snapshot).toMatchObject({
				provider: "google-gemini-cli",
				displayName: "Gemini"
			});
			globalExpect(snapshot?.windows[0]).toEqual({
				label: "Pro",
				usedPercent: 60
			});
			globalExpect(snapshot?.windows[1]?.label).toBe("Flash");
			globalExpect(snapshot?.windows[1]?.usedPercent).toBeCloseTo(20);
		});
	});
}
function describeOpenAIProviderRuntimeContract() {
	describe("openai provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns openai gpt-5.4 forward-compat resolution", () => {
			const model = requireProviderContractProvider("openai").resolveDynamicModel?.({
				provider: "openai",
				modelId: "gpt-5.4-pro",
				modelRegistry: { find: (_provider, id) => id === "gpt-5.2-pro" ? createModel({
					id,
					provider: "openai",
					baseUrl: "https://api.openai.com/v1",
					input: ["text", "image"]
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gpt-5.4-pro",
				provider: "openai",
				api: "openai-responses",
				baseUrl: "https://api.openai.com/v1",
				contextWindow: 105e4,
				maxTokens: 128e3
			});
		});
		it("owns openai gpt-5.4 mini forward-compat resolution", () => {
			const model = requireProviderContractProvider("openai").resolveDynamicModel?.({
				provider: "openai",
				modelId: "gpt-5.4-mini",
				modelRegistry: { find: (_provider, id) => id === "gpt-5-mini" ? createModel({
					id,
					provider: "openai",
					api: "openai-responses",
					baseUrl: "https://api.openai.com/v1",
					input: ["text", "image"],
					reasoning: true,
					contextWindow: 4e5,
					maxTokens: 128e3
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gpt-5.4-mini",
				provider: "openai",
				api: "openai-responses",
				baseUrl: "https://api.openai.com/v1",
				contextWindow: 4e5,
				maxTokens: 128e3
			});
		});
		it("owns direct openai transport normalization", () => {
			globalExpect(requireProviderContractProvider("openai").normalizeResolvedModel?.({
				provider: "openai",
				modelId: "gpt-5.4",
				model: createModel({
					id: "gpt-5.4",
					provider: "openai",
					api: "openai-completions",
					baseUrl: "https://api.openai.com/v1",
					input: ["text", "image"],
					contextWindow: 105e4,
					maxTokens: 128e3
				})
			})).toMatchObject({ api: "openai-responses" });
		});
		it("owns refresh fallback for accountId extraction failures", async () => {
			const provider = requireProviderContractProvider("openai-codex");
			const credential = {
				type: "oauth",
				provider: "openai-codex",
				access: "cached-access-token",
				refresh: "refresh-token",
				expires: Date.now() - 6e4
			};
			refreshOpenAICodexTokenMock.mockRejectedValueOnce(/* @__PURE__ */ new Error("Failed to extract accountId from token"));
			await globalExpect(provider.refreshOAuth?.(credential)).resolves.toEqual(credential);
		});
		it("owns forward-compat codex models", () => {
			const model = requireProviderContractProvider("openai-codex").resolveDynamicModel?.({
				provider: "openai-codex",
				modelId: "gpt-5.4",
				modelRegistry: { find: (_provider, id) => id === "gpt-5.2-codex" ? createModel({
					id,
					api: "openai-codex-responses",
					provider: "openai-codex",
					baseUrl: "https://chatgpt.com/backend-api"
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gpt-5.4",
				provider: "openai-codex",
				api: "openai-codex-responses",
				contextWindow: 105e4,
				maxTokens: 128e3
			});
		});
		it("owns forward-compat codex mini models", () => {
			const model = requireProviderContractProvider("openai-codex").resolveDynamicModel?.({
				provider: "openai-codex",
				modelId: "gpt-5.4-mini",
				modelRegistry: { find: (_provider, id) => id === "gpt-5.1-codex-mini" ? createModel({
					id,
					api: "openai-codex-responses",
					provider: "openai-codex",
					baseUrl: "https://chatgpt.com/backend-api"
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "gpt-5.4-mini",
				provider: "openai-codex",
				api: "openai-codex-responses",
				contextWindow: 272e3,
				maxTokens: 128e3
			});
		});
		it("owns codex transport defaults", () => {
			globalExpect(requireProviderContractProvider("openai-codex").prepareExtraParams?.({
				provider: "openai-codex",
				modelId: "gpt-5.4",
				extraParams: { temperature: .2 }
			})).toEqual({
				temperature: .2,
				transport: "auto"
			});
		});
		it("owns usage snapshot fetching", async () => {
			const provider = requireProviderContractProvider("openai-codex");
			const mockFetch = createProviderUsageFetch(async (url) => {
				if (url.includes("chatgpt.com/backend-api/wham/usage")) return makeResponse(200, {
					rate_limit: { primary_window: {
						used_percent: 12,
						limit_window_seconds: 10800,
						reset_at: 1705e3
					} },
					plan_type: "Plus"
				});
				return makeResponse(404, "not found");
			});
			await globalExpect(provider.fetchUsageSnapshot?.({
				config: {},
				env: {},
				provider: "openai-codex",
				token: "codex-token",
				accountId: "acc-1",
				timeoutMs: 5e3,
				fetchFn: mockFetch
			})).resolves.toEqual({
				provider: "openai-codex",
				displayName: "Codex",
				windows: [{
					label: "3h",
					usedPercent: 12,
					resetAt: 1705e6
				}],
				plan: "Plus"
			});
		});
	});
}
function describeXAIProviderRuntimeContract() {
	describe("xai provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns Grok forward-compat resolution for newer fast models", () => {
			const model = requireProviderContractProvider("xai").resolveDynamicModel?.({
				provider: "xai",
				modelId: "grok-4-1-fast-reasoning",
				modelRegistry: { find: () => null },
				providerConfig: {
					api: "openai-completions",
					baseUrl: "https://api.x.ai/v1"
				}
			});
			globalExpect(model).toMatchObject({
				id: "grok-4-1-fast-reasoning",
				provider: "xai",
				api: "openai-completions",
				baseUrl: "https://api.x.ai/v1",
				reasoning: true,
				contextWindow: 2e6
			});
		});
		it("owns modern-model matching without accepting multi-agent ids", () => {
			const provider = requireProviderContractProvider("xai");
			globalExpect(provider.isModernModelRef?.({
				provider: "xai",
				modelId: "grok-4-1-fast-reasoning"
			})).toBe(true);
			globalExpect(provider.isModernModelRef?.({
				provider: "xai",
				modelId: "grok-4.20-multi-agent-experimental-beta-0304"
			})).toBe(false);
		});
		it("owns direct xai compat flags on resolved models", () => {
			globalExpect(requireProviderContractProvider("xai").normalizeResolvedModel?.({
				provider: "xai",
				modelId: "grok-4-1-fast",
				model: createModel({
					id: "grok-4-1-fast",
					provider: "xai",
					api: "openai-completions",
					baseUrl: "https://api.x.ai/v1"
				})
			})).toMatchObject({ compat: {
				toolSchemaProfile: "xai",
				nativeWebSearchTool: true,
				toolCallArgumentsEncoding: "html-entities"
			} });
		});
		it("owns downstream xai compat contributions for x-ai routed models", () => {
			globalExpect(requireProviderContractProvider("xai").contributeResolvedModelCompat?.({
				provider: "openrouter",
				modelId: "x-ai/grok-4-1-fast",
				model: createModel({
					id: "x-ai/grok-4-1-fast",
					provider: "openrouter",
					api: "openai-completions",
					baseUrl: "https://openrouter.ai/api/v1"
				})
			})).toMatchObject({
				toolSchemaProfile: "xai",
				nativeWebSearchTool: true,
				toolCallArgumentsEncoding: "html-entities"
			});
		});
		it("owns xai tool_stream defaults", () => {
			const provider = requireProviderContractProvider("xai");
			globalExpect(provider.prepareExtraParams?.({
				provider: "xai",
				modelId: "grok-4-1-fast-reasoning",
				extraParams: { temperature: .2 }
			})).toEqual({
				temperature: .2,
				tool_stream: true
			});
			globalExpect(provider.prepareExtraParams?.({
				provider: "xai",
				modelId: "grok-4-1-fast-reasoning",
				extraParams: { tool_stream: false }
			})).toEqual({ tool_stream: false });
		});
		it("owns xai fast-mode model rewriting through the plugin stream hook", () => {
			const provider = requireProviderContractProvider("xai");
			let capturedModelId = "";
			const baseStreamFn = (model) => {
				capturedModelId = model.id;
				return {
					push() {},
					async result() {},
					async *[Symbol.asyncIterator]() {}
				};
			};
			const streamFn = provider.wrapStreamFn?.({
				provider: "xai",
				modelId: "grok-4",
				extraParams: { fastMode: true },
				streamFn: baseStreamFn
			});
			globalExpect(streamFn).toBeTypeOf("function");
			streamFn?.(createModel({
				id: "grok-4",
				provider: "xai",
				api: "openai-completions",
				baseUrl: "https://api.x.ai/v1"
			}), { messages: [] }, {});
			globalExpect(capturedModelId).toBe("grok-4-fast");
		});
	});
}
function describeOpenRouterProviderRuntimeContract() {
	describe("openrouter provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns dynamic OpenRouter model defaults", () => {
			const model = requireProviderContractProvider("openrouter").resolveDynamicModel?.({
				provider: "openrouter",
				modelId: "x-ai/grok-4-1-fast",
				modelRegistry: { find: () => null }
			});
			globalExpect(model).toMatchObject({
				id: "x-ai/grok-4-1-fast",
				provider: "openrouter",
				api: "openai-completions",
				baseUrl: "https://openrouter.ai/api/v1",
				maxTokens: 8192
			});
		});
	});
}
function describeVeniceProviderRuntimeContract() {
	describe("venice provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns xai downstream compat flags for grok-backed Venice models", () => {
			globalExpect(requireProviderContractProvider("venice").normalizeResolvedModel?.({
				provider: "venice",
				modelId: "grok-41-fast",
				model: createModel({
					id: "grok-41-fast",
					provider: "venice",
					api: "openai-completions",
					baseUrl: "https://api.venice.ai/api/v1"
				})
			})).toMatchObject({ compat: {
				toolSchemaProfile: "xai",
				nativeWebSearchTool: true,
				toolCallArgumentsEncoding: "html-entities"
			} });
		});
	});
}
function describeZAIProviderRuntimeContract() {
	describe("zai provider runtime contract", { timeout: CONTRACT_SETUP_TIMEOUT_MS }, () => {
		installRuntimeHooks();
		it("owns glm-5 forward-compat resolution", () => {
			const model = requireProviderContractProvider("zai").resolveDynamicModel?.({
				provider: "zai",
				modelId: "glm-5",
				modelRegistry: { find: (_provider, id) => id === "glm-4.7" ? createModel({
					id,
					api: "openai-completions",
					provider: "zai",
					baseUrl: "https://api.z.ai/api/paas/v4",
					reasoning: false,
					contextWindow: 202752,
					maxTokens: 16384
				}) : null }
			});
			globalExpect(model).toMatchObject({
				id: "glm-5",
				provider: "zai",
				api: "openai-completions",
				reasoning: true
			});
		});
		it("owns usage auth resolution", async () => {
			await globalExpect(requireProviderContractProvider("zai").resolveUsageAuth?.({
				config: {},
				env: { ZAI_API_KEY: "env-zai-token" },
				provider: "zai",
				resolveApiKeyFromConfigAndStore: () => "env-zai-token",
				resolveOAuthToken: async () => null
			})).resolves.toEqual({ token: "env-zai-token" });
		});
		it("falls back to legacy pi auth tokens for usage auth", async () => {
			const provider = requireProviderContractProvider("zai");
			const home = await fs.mkdtemp(path.join(os.tmpdir(), "kaijibot-zai-contract-"));
			await fs.mkdir(path.join(home, ".pi", "agent"), { recursive: true });
			await fs.writeFile(path.join(home, ".pi", "agent", "auth.json"), `${JSON.stringify({ "z-ai": { access: "legacy-zai-token" } }, null, 2)}\n`, "utf8");
			try {
				await globalExpect(provider.resolveUsageAuth?.({
					config: {},
					env: { HOME: home },
					provider: "zai",
					resolveApiKeyFromConfigAndStore: () => void 0,
					resolveOAuthToken: async () => null
				})).resolves.toEqual({ token: "legacy-zai-token" });
			} finally {
				await fs.rm(home, {
					recursive: true,
					force: true
				});
			}
		});
		it("owns usage snapshot fetching", async () => {
			const provider = requireProviderContractProvider("zai");
			const mockFetch = createProviderUsageFetch(async (url) => {
				if (url.includes("api.z.ai/api/monitor/usage/quota/limit")) return makeResponse(200, {
					success: true,
					code: 200,
					data: {
						planName: "Pro",
						limits: [{
							type: "TOKENS_LIMIT",
							percentage: 25,
							unit: 3,
							number: 6,
							nextResetTime: "2026-01-07T06:00:00Z"
						}]
					}
				});
				return makeResponse(404, "not found");
			});
			await globalExpect(provider.fetchUsageSnapshot?.({
				config: {},
				env: {},
				provider: "zai",
				token: "env-zai-token",
				timeoutMs: 5e3,
				fetchFn: mockFetch
			})).resolves.toEqual({
				provider: "zai",
				displayName: "z.ai",
				windows: [{
					label: "Tokens (6h)",
					usedPercent: 25,
					resetAt: 17677656e5
				}],
				plan: "Pro"
			});
		});
	});
}
//#endregion
//#region test/helpers/plugins/provider-discovery-contract.ts
const resolveCopilotApiTokenMock = vi.hoisted(() => vi.fn());
const buildOllamaProviderMock = vi.hoisted(() => vi.fn());
const buildVllmProviderMock = vi.hoisted(() => vi.fn());
const buildSglangProviderMock = vi.hoisted(() => vi.fn());
const ensureAuthProfileStoreMock$1 = vi.hoisted(() => vi.fn());
const listProfilesForProviderMock$1 = vi.hoisted(() => vi.fn());
const bundledProviderModules = vi.hoisted(() => ({
	cloudflareAiGatewayIndexModuleUrl: new URL("../../../extensions/cloudflare-ai-gateway/index.ts", import.meta.url).href,
	cloudflareAiGatewayIndexModuleId: new URL("../../../extensions/cloudflare-ai-gateway/index.js", import.meta.url).pathname,
	githubCopilotIndexModuleUrl: new URL("../../../extensions/github-copilot/index.ts", import.meta.url).href,
	githubCopilotTokenModuleId: new URL("../../../extensions/github-copilot/token.js", import.meta.url).pathname,
	minimaxIndexModuleUrl: new URL("../../../extensions/minimax/index.ts", import.meta.url).href,
	qwenIndexModuleUrl: new URL("../../../extensions/qwen/index.ts", import.meta.url).href,
	ollamaApiModuleId: new URL("../../../extensions/ollama/api.js", import.meta.url).pathname,
	ollamaIndexModuleUrl: new URL("../../../extensions/ollama/index.ts", import.meta.url).href,
	sglangApiModuleId: new URL("../../../extensions/sglang/api.js", import.meta.url).pathname,
	sglangIndexModuleUrl: new URL("../../../extensions/sglang/index.ts", import.meta.url).href,
	vllmApiModuleId: new URL("../../../extensions/vllm/api.js", import.meta.url).pathname,
	vllmIndexModuleUrl: new URL("../../../extensions/vllm/index.ts", import.meta.url).href
}));
function createModelConfig(id, name = id) {
	return {
		id,
		name,
		reasoning: false,
		input: ["text"],
		cost: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0
		},
		contextWindow: 128e3,
		maxTokens: 8192
	};
}
function setRuntimeAuthStore(store) {
	const resolvedStore = store ?? {
		version: 1,
		profiles: {}
	};
	ensureAuthProfileStoreMock$1.mockReturnValue(resolvedStore);
	listProfilesForProviderMock$1.mockImplementation((authStore, providerId) => Object.entries(authStore.profiles).filter(([, credential]) => credential.provider === providerId).map(([profileId]) => profileId));
}
function setGithubCopilotProfileSnapshot() {
	setRuntimeAuthStore({
		version: 1,
		profiles: { "github-copilot:github": {
			type: "token",
			provider: "github-copilot",
			token: "profile-token"
		} }
	});
}
function runCatalog(state, params) {
	return state.runProviderCatalog({
		provider: params.provider,
		config: params.config ?? {},
		env: params.env ?? {},
		resolveProviderApiKey: params.resolveProviderApiKey ?? (() => ({ apiKey: void 0 })),
		resolveProviderAuth: params.resolveProviderAuth ?? ((_, options) => ({
			apiKey: options?.oauthMarker,
			discoveryApiKey: void 0,
			mode: options?.oauthMarker ? "oauth" : "none",
			source: options?.oauthMarker ? "profile" : "none"
		}))
	});
}
async function importBundledProviderPlugin$1(moduleUrl) {
	return await import(`${moduleUrl}?t=${Date.now()}`);
}
function installDiscoveryHooks(state, providerIds) {
	beforeEach(async () => {
		vi.resetModules();
		vi.doMock("kaijibot/plugin-sdk/agent-runtime", () => {
			return {
				ensureAuthProfileStore: ensureAuthProfileStoreMock$1,
				listProfilesForProvider: listProfilesForProviderMock$1
			};
		});
		vi.doMock("kaijibot/plugin-sdk/provider-auth", () => {
			return {
				MINIMAX_OAUTH_MARKER: "minimax-oauth",
				applyAuthProfileConfig: (config) => config,
				buildApiKeyCredential: (provider, key, metadata) => ({
					type: "api_key",
					provider,
					...typeof key === "string" ? { key } : {},
					...metadata ? { metadata } : {}
				}),
				buildOauthProviderAuthResult: vi.fn(),
				coerceSecretRef: (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null,
				ensureApiKeyFromOptionEnvOrPrompt: vi.fn(),
				ensureAuthProfileStore: ensureAuthProfileStoreMock$1,
				listProfilesForProvider: listProfilesForProviderMock$1,
				normalizeApiKeyInput: (value) => typeof value === "string" ? value.trim() : "",
				normalizeOptionalSecretInput: (value) => typeof value === "string" && value.trim() ? value.trim() : void 0,
				resolveNonEnvSecretRefApiKeyMarker: (source) => typeof source === "string" ? source : "",
				upsertAuthProfile: vi.fn(),
				validateApiKeyInput: () => void 0
			};
		});
		vi.doMock(bundledProviderModules.githubCopilotTokenModuleId, async () => {
			return {
				...await vi.importActual(bundledProviderModules.githubCopilotTokenModuleId),
				resolveCopilotApiToken: resolveCopilotApiTokenMock
			};
		});
		vi.doMock(bundledProviderModules.ollamaApiModuleId, async () => {
			return {
				OLLAMA_DEFAULT_BASE_URL: "http://127.0.0.1:11434",
				buildOllamaProvider: (...args) => buildOllamaProviderMock(...args),
				configureOllamaNonInteractive: vi.fn(),
				ensureOllamaModelPulled: vi.fn(),
				promptAndConfigureOllama: vi.fn()
			};
		});
		vi.doMock(bundledProviderModules.vllmApiModuleId, async () => {
			return {
				VLLM_DEFAULT_API_KEY_ENV_VAR: "VLLM_API_KEY",
				VLLM_DEFAULT_BASE_URL: "http://127.0.0.1:8000/v1",
				VLLM_MODEL_PLACEHOLDER: "meta-llama/Meta-Llama-3-8B-Instruct",
				VLLM_PROVIDER_LABEL: "vLLM",
				buildVllmProvider: (...args) => buildVllmProviderMock(...args)
			};
		});
		vi.doMock(bundledProviderModules.sglangApiModuleId, async () => {
			return {
				SGLANG_DEFAULT_API_KEY_ENV_VAR: "SGLANG_API_KEY",
				SGLANG_DEFAULT_BASE_URL: "http://127.0.0.1:30000/v1",
				SGLANG_MODEL_PLACEHOLDER: "Qwen/Qwen3-8B",
				SGLANG_PROVIDER_LABEL: "SGLang",
				buildSglangProvider: (...args) => buildSglangProviderMock(...args)
			};
		});
		({runProviderCatalog: state.runProviderCatalog} = await import("../provider-discovery-DLizQest.js"));
		if (providerIds.includes("github-copilot")) {
			const { default: githubCopilotPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.githubCopilotIndexModuleUrl);
			state.githubCopilotProvider = requireRegisteredProvider(await registerProviderPlugins(githubCopilotPlugin), "github-copilot");
		}
		if (providerIds.includes("ollama")) {
			const { default: ollamaPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.ollamaIndexModuleUrl);
			state.ollamaProvider = requireRegisteredProvider(await registerProviderPlugins(ollamaPlugin), "ollama");
		}
		if (providerIds.includes("vllm")) {
			const { default: vllmPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.vllmIndexModuleUrl);
			state.vllmProvider = requireRegisteredProvider(await registerProviderPlugins(vllmPlugin), "vllm");
		}
		if (providerIds.includes("sglang")) {
			const { default: sglangPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.sglangIndexModuleUrl);
			state.sglangProvider = requireRegisteredProvider(await registerProviderPlugins(sglangPlugin), "sglang");
		}
		if (providerIds.includes("minimax")) {
			const { default: minimaxPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.minimaxIndexModuleUrl);
			const registeredProviders = await registerProviderPlugins(minimaxPlugin);
			state.minimaxProvider = requireRegisteredProvider(registeredProviders, "minimax");
			state.minimaxPortalProvider = requireRegisteredProvider(registeredProviders, "minimax-portal");
		}
		if (providerIds.includes("modelstudio")) {
			const { default: qwenPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.qwenIndexModuleUrl);
			state.modelStudioProvider = requireRegisteredProvider(await registerProviderPlugins(qwenPlugin), "qwen");
		}
		if (providerIds.includes("cloudflare-ai-gateway")) {
			const { default: cloudflareAiGatewayPlugin } = await importBundledProviderPlugin$1(bundledProviderModules.cloudflareAiGatewayIndexModuleUrl);
			state.cloudflareAiGatewayProvider = requireRegisteredProvider(await registerProviderPlugins(cloudflareAiGatewayPlugin), "cloudflare-ai-gateway");
		}
		setRuntimeAuthStore();
	});
	afterEach(() => {
		vi.restoreAllMocks();
		resolveCopilotApiTokenMock.mockReset();
		buildOllamaProviderMock.mockReset();
		buildVllmProviderMock.mockReset();
		buildSglangProviderMock.mockReset();
		ensureAuthProfileStoreMock$1.mockReset();
		listProfilesForProviderMock$1.mockReset();
	});
}
function describeGithubCopilotProviderDiscoveryContract() {
	const state = {};
	describe("github-copilot provider discovery contract", () => {
		installDiscoveryHooks(state, ["github-copilot"]);
		it("keeps catalog disabled without env tokens or profiles", async () => {
			await globalExpect(runCatalog(state, { provider: state.githubCopilotProvider })).resolves.toBeNull();
		});
		it("keeps profile-only catalog fallback provider-owned", async () => {
			setGithubCopilotProfileSnapshot();
			await globalExpect(runCatalog(state, { provider: state.githubCopilotProvider })).resolves.toEqual({ provider: {
				baseUrl: "https://api.individual.githubcopilot.com",
				models: []
			} });
		});
		it("keeps env-token base URL resolution provider-owned", async () => {
			resolveCopilotApiTokenMock.mockResolvedValueOnce({
				token: "copilot-api-token",
				baseUrl: "https://copilot-proxy.example.com",
				expiresAt: Date.now() + 6e4
			});
			await globalExpect(runCatalog(state, {
				provider: state.githubCopilotProvider,
				env: { GITHUB_TOKEN: "github-env-token" },
				resolveProviderApiKey: () => ({ apiKey: void 0 })
			})).resolves.toEqual({ provider: {
				baseUrl: "https://copilot-proxy.example.com",
				models: []
			} });
			globalExpect(resolveCopilotApiTokenMock).toHaveBeenCalledWith({
				githubToken: "github-env-token",
				env: globalExpect.objectContaining({ GITHUB_TOKEN: "github-env-token" })
			});
		});
	});
}
function describeOllamaProviderDiscoveryContract() {
	const state = {};
	describe("ollama provider discovery contract", () => {
		installDiscoveryHooks(state, ["ollama"]);
		it("keeps explicit catalog normalization provider-owned", async () => {
			await globalExpect(state.runProviderCatalog({
				provider: state.ollamaProvider,
				config: { models: { providers: { ollama: {
					baseUrl: "http://ollama-host:11434/v1/",
					models: [createModelConfig("llama3.2")]
				} } } },
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toMatchObject({ provider: {
				baseUrl: "http://ollama-host:11434",
				api: "ollama",
				apiKey: "ollama-local",
				models: [createModelConfig("llama3.2")]
			} });
			globalExpect(buildOllamaProviderMock).not.toHaveBeenCalled();
		});
		it("keeps empty autodiscovery disabled without keys or explicit config", async () => {
			buildOllamaProviderMock.mockResolvedValueOnce({
				baseUrl: "http://127.0.0.1:11434",
				api: "ollama",
				models: []
			});
			await globalExpect(runCatalog(state, {
				provider: state.ollamaProvider,
				config: {},
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toBeNull();
			globalExpect(buildOllamaProviderMock).toHaveBeenCalledWith(void 0, { quiet: true });
		});
		it("keeps empty default-ish provider stubs on the quiet ambient path", async () => {
			buildOllamaProviderMock.mockResolvedValueOnce({
				baseUrl: "http://127.0.0.1:11434",
				api: "ollama",
				models: []
			});
			await globalExpect(runCatalog(state, {
				provider: state.ollamaProvider,
				config: { models: { providers: { ollama: {
					baseUrl: "http://127.0.0.1:11434",
					api: "ollama",
					models: []
				} } } },
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toBeNull();
			globalExpect(buildOllamaProviderMock).toHaveBeenCalledWith("http://127.0.0.1:11434", { quiet: true });
		});
	});
}
function describeVllmProviderDiscoveryContract() {
	const state = {};
	describe("vllm provider discovery contract", () => {
		installDiscoveryHooks(state, ["vllm"]);
		it("keeps self-hosted discovery provider-owned", async () => {
			buildVllmProviderMock.mockResolvedValueOnce({
				baseUrl: "http://127.0.0.1:8000/v1",
				api: "openai-completions",
				models: [{
					id: "meta-llama/Meta-Llama-3-8B-Instruct",
					name: "Meta Llama 3"
				}]
			});
			await globalExpect(runCatalog(state, {
				provider: state.vllmProvider,
				config: {},
				env: { VLLM_API_KEY: "env-vllm-key" },
				resolveProviderApiKey: () => ({
					apiKey: "VLLM_API_KEY",
					discoveryApiKey: "env-vllm-key"
				}),
				resolveProviderAuth: () => ({
					apiKey: "VLLM_API_KEY",
					discoveryApiKey: "env-vllm-key",
					mode: "api_key",
					source: "env"
				})
			})).resolves.toEqual({ provider: {
				baseUrl: "http://127.0.0.1:8000/v1",
				api: "openai-completions",
				apiKey: "VLLM_API_KEY",
				models: [{
					id: "meta-llama/Meta-Llama-3-8B-Instruct",
					name: "Meta Llama 3"
				}]
			} });
			globalExpect(buildVllmProviderMock).toHaveBeenCalledWith({ apiKey: "env-vllm-key" });
		});
	});
}
function describeSglangProviderDiscoveryContract() {
	const state = {};
	describe("sglang provider discovery contract", () => {
		installDiscoveryHooks(state, ["sglang"]);
		it("keeps self-hosted discovery provider-owned", async () => {
			buildSglangProviderMock.mockResolvedValueOnce({
				baseUrl: "http://127.0.0.1:30000/v1",
				api: "openai-completions",
				models: [{
					id: "Qwen/Qwen3-8B",
					name: "Qwen3-8B"
				}]
			});
			await globalExpect(runCatalog(state, {
				provider: state.sglangProvider,
				config: {},
				env: { SGLANG_API_KEY: "env-sglang-key" },
				resolveProviderApiKey: () => ({
					apiKey: "SGLANG_API_KEY",
					discoveryApiKey: "env-sglang-key"
				}),
				resolveProviderAuth: () => ({
					apiKey: "SGLANG_API_KEY",
					discoveryApiKey: "env-sglang-key",
					mode: "api_key",
					source: "env"
				})
			})).resolves.toEqual({ provider: {
				baseUrl: "http://127.0.0.1:30000/v1",
				api: "openai-completions",
				apiKey: "SGLANG_API_KEY",
				models: [{
					id: "Qwen/Qwen3-8B",
					name: "Qwen3-8B"
				}]
			} });
			globalExpect(buildSglangProviderMock).toHaveBeenCalledWith({ apiKey: "env-sglang-key" });
		});
	});
}
function describeMinimaxProviderDiscoveryContract() {
	const state = {};
	describe("minimax provider discovery contract", () => {
		installDiscoveryHooks(state, ["minimax"]);
		it("keeps API catalog provider-owned", async () => {
			await globalExpect(state.runProviderCatalog({
				provider: state.minimaxProvider,
				config: {},
				env: { MINIMAX_API_KEY: "minimax-key" },
				resolveProviderApiKey: () => ({ apiKey: "minimax-key" }),
				resolveProviderAuth: () => ({
					apiKey: "minimax-key",
					discoveryApiKey: void 0,
					mode: "api_key",
					source: "env"
				})
			})).resolves.toMatchObject({ provider: {
				baseUrl: "https://api.minimax.io/anthropic",
				api: "anthropic-messages",
				authHeader: true,
				apiKey: "minimax-key",
				models: globalExpect.arrayContaining([globalExpect.objectContaining({ id: "MiniMax-M2.7" }), globalExpect.objectContaining({ id: "MiniMax-M2.7-highspeed" })])
			} });
		});
		it("keeps portal oauth marker fallback provider-owned", async () => {
			setRuntimeAuthStore({
				version: 1,
				profiles: { "minimax-portal:default": {
					type: "oauth",
					provider: "minimax-portal",
					access: "access-token",
					refresh: "refresh-token",
					expires: Date.now() + 6e4
				} }
			});
			await globalExpect(runCatalog(state, {
				provider: state.minimaxPortalProvider,
				config: {},
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: "minimax-oauth",
					discoveryApiKey: "access-token",
					mode: "oauth",
					source: "profile",
					profileId: "minimax-portal:default"
				})
			})).resolves.toMatchObject({ provider: {
				baseUrl: "https://api.minimax.io/anthropic",
				api: "anthropic-messages",
				authHeader: true,
				apiKey: "minimax-oauth",
				models: globalExpect.arrayContaining([globalExpect.objectContaining({ id: "MiniMax-M2.7" })])
			} });
		});
		it("keeps portal explicit base URL override provider-owned", async () => {
			await globalExpect(state.runProviderCatalog({
				provider: state.minimaxPortalProvider,
				config: { models: { providers: { "minimax-portal": {
					baseUrl: "https://portal-proxy.example.com/anthropic",
					apiKey: "explicit-key",
					models: []
				} } } },
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toMatchObject({ provider: {
				baseUrl: "https://portal-proxy.example.com/anthropic",
				apiKey: "explicit-key"
			} });
		});
	});
}
function describeModelStudioProviderDiscoveryContract() {
	const state = {};
	describe("modelstudio provider discovery contract", () => {
		installDiscoveryHooks(state, ["modelstudio"]);
		it("keeps catalog provider-owned", async () => {
			await globalExpect(state.runProviderCatalog({
				provider: state.modelStudioProvider,
				config: { models: { providers: { modelstudio: {
					baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
					models: []
				} } } },
				env: { MODELSTUDIO_API_KEY: "modelstudio-key" },
				resolveProviderApiKey: () => ({ apiKey: "modelstudio-key" }),
				resolveProviderAuth: () => ({
					apiKey: "modelstudio-key",
					discoveryApiKey: void 0,
					mode: "api_key",
					source: "env"
				})
			})).resolves.toMatchObject({ provider: {
				baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
				api: "openai-completions",
				apiKey: "modelstudio-key",
				models: globalExpect.arrayContaining([
					globalExpect.objectContaining({ id: "qwen3.5-plus" }),
					globalExpect.objectContaining({ id: "qwen3-max-2026-01-23" }),
					globalExpect.objectContaining({ id: "MiniMax-M2.5" })
				])
			} });
		});
	});
}
function describeCloudflareAiGatewayProviderDiscoveryContract() {
	const state = {};
	describe("cloudflare-ai-gateway provider discovery contract", () => {
		installDiscoveryHooks(state, ["cloudflare-ai-gateway"]);
		it("keeps catalog disabled without stored metadata", async () => {
			await globalExpect(runCatalog(state, {
				provider: state.cloudflareAiGatewayProvider,
				config: {},
				env: {},
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toBeNull();
		});
		it("keeps env-managed catalog provider-owned", async () => {
			setRuntimeAuthStore({
				version: 1,
				profiles: { "cloudflare-ai-gateway:default": {
					type: "api_key",
					provider: "cloudflare-ai-gateway",
					keyRef: {
						source: "env",
						provider: "default",
						id: "CLOUDFLARE_AI_GATEWAY_API_KEY"
					},
					metadata: {
						accountId: "acc-123",
						gatewayId: "gw-456"
					}
				} }
			});
			await globalExpect(runCatalog(state, {
				provider: state.cloudflareAiGatewayProvider,
				config: {},
				env: { CLOUDFLARE_AI_GATEWAY_API_KEY: "secret-value" },
				resolveProviderApiKey: () => ({ apiKey: void 0 }),
				resolveProviderAuth: () => ({
					apiKey: void 0,
					discoveryApiKey: void 0,
					mode: "none",
					source: "none"
				})
			})).resolves.toEqual({ provider: {
				baseUrl: "https://gateway.ai.cloudflare.com/v1/acc-123/gw-456/anthropic",
				api: "anthropic-messages",
				apiKey: "CLOUDFLARE_AI_GATEWAY_API_KEY",
				models: [globalExpect.objectContaining({ id: "claude-sonnet-4-5" })]
			} });
		});
	});
}
//#endregion
//#region test/helpers/plugins/onboard-config.ts
const EXPECTED_FALLBACKS = ["anthropic/claude-opus-4-5"];
function createLegacyProviderConfig(params) {
	return { models: { providers: { [params.providerId]: {
		baseUrl: params.baseUrl ?? "https://old.example.com",
		apiKey: params.apiKey ?? "old-key",
		api: params.api,
		models: [{
			id: params.modelId ?? "old-model",
			name: params.modelName ?? "Old",
			reasoning: false,
			input: ["text"],
			cost: {
				input: 1,
				output: 2,
				cacheRead: 0,
				cacheWrite: 0
			},
			contextWindow: 1e3,
			maxTokens: 100
		}]
	} } } };
}
function createConfigWithFallbacks() {
	return { agents: { defaults: { model: { fallbacks: [...EXPECTED_FALLBACKS] } } } };
}
//#endregion
//#region test/helpers/plugins/provider-wizard-contract-suites.ts
const resolvePluginProvidersMock = vi.fn();
vi.mock("../../../src/plugins/providers.runtime.js", () => ({
	isPluginProvidersLoadInFlight: () => false,
	resolvePluginProviders: (...args) => resolvePluginProvidersMock(...args)
}));
function createAuthMethod(params) {
	return {
		id: params.id,
		label: params.label,
		...params.hint ? { hint: params.hint } : {},
		...params.wizard ? { wizard: params.wizard } : {},
		kind: "api_key",
		run: async () => ({ profiles: [] })
	};
}
const TEST_PROVIDERS = [
	{
		id: "alpha",
		label: "Alpha",
		auth: [createAuthMethod({
			id: "api-key",
			label: "API key",
			wizard: {
				choiceLabel: "Alpha key",
				choiceHint: "Use an API key",
				groupId: "alpha",
				groupLabel: "Alpha",
				onboardingScopes: ["text-inference"]
			}
		}), createAuthMethod({
			id: "oauth",
			label: "OAuth",
			wizard: {
				choiceId: "alpha-oauth",
				choiceLabel: "Alpha OAuth",
				groupId: "alpha",
				groupLabel: "Alpha",
				groupHint: "Recommended"
			}
		})],
		wizard: { modelPicker: {
			label: "Alpha custom",
			hint: "Pick Alpha models",
			methodId: "oauth"
		} }
	},
	{
		id: "beta",
		label: "Beta",
		auth: [createAuthMethod({
			id: "token",
			label: "Token"
		})],
		wizard: {
			setup: {
				choiceLabel: "Beta setup",
				groupId: "beta",
				groupLabel: "Beta"
			},
			modelPicker: { label: "Beta custom" }
		}
	},
	{
		id: "gamma",
		label: "Gamma",
		auth: [createAuthMethod({
			id: "default",
			label: "Default auth"
		}), createAuthMethod({
			id: "alt",
			label: "Alt auth"
		})],
		wizard: { setup: {
			methodId: "alt",
			choiceId: "gamma-alt",
			choiceLabel: "Gamma alt",
			groupId: "gamma",
			groupLabel: "Gamma"
		} }
	}
];
const TEST_PROVIDER_IDS = TEST_PROVIDERS.map((provider) => provider.id).toSorted((left, right) => left.localeCompare(right));
function sortedValues(values) {
	return [...values].toSorted((left, right) => left.localeCompare(right));
}
function expectUniqueValues(values) {
	globalExpect(values).toEqual([...new Set(values)]);
}
function resolveExpectedWizardChoiceValues(providers) {
	return sortedValues(providers.flatMap((provider) => {
		const methodSetups = provider.auth.filter((method) => method.wizard);
		if (methodSetups.length > 0) return methodSetups.map((method) => method.wizard?.choiceId?.trim() || buildProviderPluginMethodChoice(provider.id, method.id));
		const setup = provider.wizard?.setup;
		if (!setup) return [];
		const explicitMethodId = setup.methodId?.trim();
		if (explicitMethodId && provider.auth.some((method) => method.id === explicitMethodId)) return [setup.choiceId?.trim() || buildProviderPluginMethodChoice(provider.id, explicitMethodId)];
		if (provider.auth.length === 1) return [setup.choiceId?.trim() || provider.id];
		return provider.auth.map((method) => buildProviderPluginMethodChoice(provider.id, method.id));
	}));
}
function resolveExpectedModelPickerValues(providers) {
	return sortedValues(providers.flatMap((provider) => {
		const modelPicker = provider.wizard?.modelPicker;
		if (!modelPicker) return [];
		const explicitMethodId = modelPicker.methodId?.trim();
		if (explicitMethodId) return [buildProviderPluginMethodChoice(provider.id, explicitMethodId)];
		if (provider.auth.length === 1) return [provider.id];
		return [buildProviderPluginMethodChoice(provider.id, provider.auth[0]?.id ?? "default")];
	}));
}
function expectAllChoicesResolve(values, resolver) {
	globalExpect(values.every((value) => Boolean(resolver(value))), values.join(", ")).toBe(true);
}
beforeEach(() => {
	resolvePluginProvidersMock.mockReset();
	resolvePluginProvidersMock.mockReturnValue(TEST_PROVIDERS);
});
function describeProviderWizardSetupOptionsContract() {
	describe("provider wizard setup options contract", () => {
		it("exposes every wizard setup choice through the shared wizard layer", () => {
			const options = resolveProviderWizardOptions({
				config: { plugins: {
					enabled: true,
					allow: TEST_PROVIDER_IDS,
					slots: { memory: "none" }
				} },
				env: process.env
			});
			globalExpect(sortedValues(options.map((option) => option.value))).toEqual(resolveExpectedWizardChoiceValues(TEST_PROVIDERS));
			expectUniqueValues(options.map((option) => option.value));
		});
	});
}
function describeProviderWizardChoiceResolutionContract() {
	describe("provider wizard choice resolution contract", () => {
		it("round-trips every shared wizard choice back to its provider and auth method", () => {
			expectAllChoicesResolve(resolveProviderWizardOptions({
				config: {},
				env: process.env
			}).map((option) => option.value), (choice) => resolveProviderPluginChoice({
				providers: TEST_PROVIDERS,
				choice
			}));
		});
	});
}
function describeProviderWizardModelPickerContract() {
	describe("provider wizard model picker contract", () => {
		it("exposes every model-picker entry through the shared wizard layer", () => {
			const entries = resolveProviderModelPickerEntries({
				config: {},
				env: process.env
			});
			globalExpect(sortedValues(entries.map((entry) => entry.value))).toEqual(resolveExpectedModelPickerValues(TEST_PROVIDERS));
			expectAllChoicesResolve(entries.map((entry) => entry.value), (choice) => resolveProviderPluginChoice({
				providers: TEST_PROVIDERS,
				choice
			}));
		});
	});
}
//#endregion
//#region test/helpers/plugins/web-fetch-provider-contract.ts
function describeWebFetchProviderContracts(pluginId) {
	const providerIds = pluginRegistrationContractRegistry.find((entry) => entry.pluginId === pluginId)?.webFetchProviderIds ?? [];
	const resolveProviders = () => resolveWebFetchProviderContractEntriesForPluginId(pluginId);
	describe(`${pluginId} web fetch provider contract registry load`, () => {
		it("loads bundled web fetch providers", () => {
			globalExpect(resolveProviders().length).toBeGreaterThan(0);
		});
	});
	for (const providerId of providerIds) describe(`${pluginId}:${providerId} web fetch contract`, () => {
		installWebFetchProviderContractSuite({
			provider: () => {
				const entry = resolveProviders().find((provider) => provider.provider.id === providerId);
				if (!entry) throw new Error(`web fetch provider contract entry missing for ${pluginId}:${providerId}`);
				return entry.provider;
			},
			credentialValue: () => {
				const entry = resolveProviders().find((provider) => provider.provider.id === providerId);
				if (!entry) throw new Error(`web fetch provider contract entry missing for ${pluginId}:${providerId}`);
				return entry.credentialValue;
			},
			pluginId
		});
	});
}
//#endregion
//#region test/helpers/plugins/web-search-provider-contract.ts
function describeWebSearchProviderContracts(pluginId) {
	const providerIds = pluginRegistrationContractRegistry.find((entry) => entry.pluginId === pluginId)?.webSearchProviderIds ?? [];
	const resolveProviders = () => resolveWebSearchProviderContractEntriesForPluginId(pluginId);
	describe(`${pluginId} web search provider contract registry load`, () => {
		it("loads bundled web search providers", () => {
			globalExpect(resolveProviders().length).toBeGreaterThan(0);
		});
	});
	for (const providerId of providerIds) describe(`${pluginId}:${providerId} web search contract`, () => {
		installWebSearchProviderContractSuite({
			provider: () => {
				const entry = resolveProviders().find((provider) => provider.provider.id === providerId);
				if (!entry) throw new Error(`web search provider contract entry missing for ${pluginId}:${providerId}`);
				return entry.provider;
			},
			credentialValue: () => {
				const entry = resolveProviders().find((provider) => provider.provider.id === providerId);
				if (!entry) throw new Error(`web search provider contract entry missing for ${pluginId}:${providerId}`);
				return entry.credentialValue;
			}
		});
	});
}
//#endregion
//#region test/helpers/plugins/provider-auth-contract.ts
const loginOpenAICodexOAuthMock = vi.hoisted(() => vi.fn());
const ensureAuthProfileStoreMock = vi.hoisted(() => vi.fn());
const listProfilesForProviderMock = vi.hoisted(() => vi.fn());
const providerAuthContractModules = vi.hoisted(() => ({ openAIIndexModuleUrl: new URL("../../../extensions/openai/index.ts", import.meta.url).href }));
vi.mock("kaijibot/plugin-sdk/provider-auth-login", async () => {
	return {
		...await vi.importActual("kaijibot/plugin-sdk/provider-auth-login"),
		loginOpenAICodexOAuth: loginOpenAICodexOAuthMock
	};
});
vi.mock("kaijibot/plugin-sdk/provider-auth", async () => {
	return {
		...await vi.importActual("kaijibot/plugin-sdk/provider-auth"),
		ensureAuthProfileStore: ensureAuthProfileStoreMock,
		listProfilesForProvider: listProfilesForProviderMock
	};
});
async function importBundledProviderPlugin(moduleUrl) {
	return await import(`${moduleUrl}?t=${Date.now()}`);
}
function buildPrompter() {
	const progress = {
		update() {},
		stop() {}
	};
	return {
		intro: async () => {},
		outro: async () => {},
		note: async () => {},
		select: async (params) => {
			const option = params.options[0];
			if (!option) throw new Error("missing select option");
			return option.value;
		},
		multiselect: async (params) => params.initialValues ?? [],
		text: async () => "",
		confirm: async () => false,
		progress: () => progress
	};
}
function buildAuthContext() {
	return {
		config: {},
		prompter: buildPrompter(),
		runtime: createNonExitingRuntime(),
		isRemote: false,
		openUrl: async () => {},
		oauth: { createVpsAwareHandlers: vi.fn() }
	};
}
function createJwt(payload) {
	return `${Buffer.from(JSON.stringify({
		alg: "none",
		typ: "JWT"
	})).toString("base64url")}.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.signature`;
}
function buildOpenAICodexOAuthResult(params) {
	return {
		profiles: [{
			profileId: params.profileId,
			credential: {
				type: "oauth",
				provider: "openai-codex",
				access: params.access,
				refresh: params.refresh,
				expires: params.expires,
				...params.email ? { email: params.email } : {}
			}
		}],
		configPatch: { agents: { defaults: { models: { "openai-codex/gpt-5.4": {} } } } },
		defaultModel: "openai-codex/gpt-5.4",
		notes: void 0
	};
}
function installSharedAuthProfileStoreHooks(state) {
	beforeEach(() => {
		state.authStore = {
			version: 1,
			profiles: {}
		};
		ensureAuthProfileStoreMock.mockReset();
		ensureAuthProfileStoreMock.mockImplementation(() => state.authStore);
		listProfilesForProviderMock.mockReset();
		listProfilesForProviderMock.mockImplementation((store, providerId) => Object.entries(store.profiles).filter(([, credential]) => credential?.provider === providerId).map(([profileId]) => profileId));
	});
	afterEach(() => {
		loginOpenAICodexOAuthMock.mockReset();
		ensureAuthProfileStoreMock.mockReset();
		listProfilesForProviderMock.mockReset();
		clearRuntimeAuthProfileStoreSnapshots();
	});
}
function describeOpenAICodexProviderAuthContract() {
	const state = { authStore: {
		version: 1,
		profiles: {}
	} };
	describe("openai-codex provider auth contract", () => {
		installSharedAuthProfileStoreHooks(state);
		async function expectStableFallbackProfile(params) {
			const { default: openAIPlugin } = await importBundledProviderPlugin(providerAuthContractModules.openAIIndexModuleUrl);
			const provider = requireRegisteredProvider(await registerProviderPlugins(openAIPlugin), "openai-codex");
			loginOpenAICodexOAuthMock.mockResolvedValueOnce({
				refresh: "refresh-token",
				access: params.access,
				expires: 17e11
			});
			globalExpect(await provider.auth[0]?.run(buildAuthContext())).toEqual(buildOpenAICodexOAuthResult({
				profileId: params.profileId,
				access: params.access,
				refresh: "refresh-token",
				expires: 17e11
			}));
		}
		async function getProvider() {
			const { default: openAIPlugin } = await importBundledProviderPlugin(providerAuthContractModules.openAIIndexModuleUrl);
			return requireRegisteredProvider(await registerProviderPlugins(openAIPlugin), "openai-codex");
		}
		it("keeps OAuth auth results provider-owned", async () => {
			const provider = await getProvider();
			loginOpenAICodexOAuthMock.mockResolvedValueOnce({
				email: "user@example.com",
				refresh: "refresh-token",
				access: "access-token",
				expires: 17e11
			});
			globalExpect(await provider.auth[0]?.run(buildAuthContext())).toEqual(buildOpenAICodexOAuthResult({
				profileId: "openai-codex:user@example.com",
				access: "access-token",
				refresh: "refresh-token",
				expires: 17e11,
				email: "user@example.com"
			}));
		});
		it("backfills OAuth email from the JWT profile claim", async () => {
			const provider = await getProvider();
			const access = createJwt({ "https://api.openai.com/profile": { email: "jwt-user@example.com" } });
			loginOpenAICodexOAuthMock.mockResolvedValueOnce({
				refresh: "refresh-token",
				access,
				expires: 17e11
			});
			globalExpect(await provider.auth[0]?.run(buildAuthContext())).toEqual(buildOpenAICodexOAuthResult({
				profileId: "openai-codex:jwt-user@example.com",
				access,
				refresh: "refresh-token",
				expires: 17e11,
				email: "jwt-user@example.com"
			}));
		});
		it("uses a stable fallback id when JWT email is missing", async () => {
			await expectStableFallbackProfile({
				access: createJwt({ "https://api.openai.com/auth": { chatgpt_account_user_id: "user-123__acct-456" } }),
				profileId: `openai-codex:id-${Buffer.from("user-123__acct-456", "utf8").toString("base64url")}`
			});
		});
		it("uses iss and sub to build a stable fallback id when auth claims are missing", async () => {
			await expectStableFallbackProfile({
				access: createJwt({
					iss: "https://accounts.openai.com",
					sub: "user-abc"
				}),
				profileId: `openai-codex:id-${Buffer.from("https://accounts.openai.com|user-abc").toString("base64url")}`
			});
		});
		it("uses sub alone to build a stable fallback id when iss is missing", async () => {
			await expectStableFallbackProfile({
				access: createJwt({ sub: "user-abc" }),
				profileId: `openai-codex:id-${Buffer.from("user-abc").toString("base64url")}`
			});
		});
		it("falls back to the default profile when JWT parsing yields no identity", async () => {
			const provider = await getProvider();
			loginOpenAICodexOAuthMock.mockResolvedValueOnce({
				refresh: "refresh-token",
				access: "not-a-jwt-token",
				expires: 17e11
			});
			globalExpect(await provider.auth[0]?.run(buildAuthContext())).toEqual(buildOpenAICodexOAuthResult({
				profileId: "openai-codex:default",
				access: "not-a-jwt-token",
				refresh: "refresh-token",
				expires: 17e11
			}));
		});
		it("keeps OAuth failures non-fatal at the provider layer", async () => {
			const provider = await getProvider();
			loginOpenAICodexOAuthMock.mockRejectedValueOnce(/* @__PURE__ */ new Error("oauth failed"));
			await globalExpect(provider.auth[0]?.run(buildAuthContext())).resolves.toEqual({ profiles: [] });
		});
	});
}
//#endregion
//#region test/helpers/media-generation/dashscope-video-provider.ts
function mockSuccessfulDashscopeVideoTask(mocks, params = {}) {
	const { requestId = "req-1", taskId = "task-1", taskStatus = "SUCCEEDED", videoUrl = "https://example.com/out.mp4" } = params;
	mocks.postJsonRequestMock.mockResolvedValue({
		response: { json: async () => ({
			request_id: requestId,
			output: { task_id: taskId }
		}) },
		release: vi.fn(async () => {})
	});
	mocks.fetchWithTimeoutMock.mockResolvedValueOnce({
		json: async () => ({ output: {
			task_status: taskStatus,
			results: [{ video_url: videoUrl }]
		} }),
		headers: new Headers()
	}).mockResolvedValueOnce({
		arrayBuffer: async () => Buffer.from("mp4-bytes"),
		headers: new Headers({ "content-type": "video/mp4" })
	});
}
function expectDashscopeVideoTaskPoll(fetchWithTimeoutMock, params = {}) {
	const { baseUrl = "https://dashscope-intl.aliyuncs.com", taskId = "task-1", timeoutMs = 12e4 } = params;
	globalExpect(fetchWithTimeoutMock).toHaveBeenNthCalledWith(1, `${baseUrl}/api/v1/tasks/${taskId}`, globalExpect.objectContaining({ method: "GET" }), timeoutMs, fetch);
}
function expectSuccessfulDashscopeVideoResult(result, params = {}) {
	const { requestId = "req-1", taskId = "task-1", taskStatus = "SUCCEEDED" } = params;
	globalExpect(result.videos).toHaveLength(1);
	globalExpect(result.videos[0]?.mimeType).toBe("video/mp4");
	globalExpect(result.metadata).toEqual(globalExpect.objectContaining({
		requestId,
		taskId,
		taskStatus
	}));
}
//#endregion
export { EXPECTED_FALLBACKS, createConfigWithFallbacks, createLegacyProviderConfig, describeAnthropicProviderRuntimeContract, describeCloudflareAiGatewayProviderDiscoveryContract, describeGithubCopilotProviderDiscoveryContract, describeGithubCopilotProviderRuntimeContract, describeGoogleProviderRuntimeContract, describeMinimaxProviderDiscoveryContract, describeModelStudioProviderDiscoveryContract, describeOllamaProviderDiscoveryContract, describeOpenAICodexProviderAuthContract, describeOpenAIProviderRuntimeContract, describeOpenRouterProviderRuntimeContract, describeProviderContracts, describeProviderWizardChoiceResolutionContract, describeProviderWizardModelPickerContract, describeProviderWizardSetupOptionsContract, describeSglangProviderDiscoveryContract, describeVeniceProviderRuntimeContract, describeVllmProviderDiscoveryContract, describeWebFetchProviderContracts, describeWebSearchProviderContracts, describeXAIProviderRuntimeContract, describeZAIProviderRuntimeContract, expectDashscopeVideoTaskPoll, expectSuccessfulDashscopeVideoResult, installProviderPluginContractSuite, installWebFetchProviderContractSuite, installWebSearchProviderContractSuite, mockSuccessfulDashscopeVideoTask };
