import { a as normalizeLowercaseStringOrEmpty, f as readStringValue } from "./string-coerce-Bje8XVt9.js";
import { i as formatErrorMessage } from "./errors-CSrrtEb1.js";
import { r as normalizeProviderId } from "./provider-id-DMUF3fJY.js";
import "./defaults-WmkV2Z8L.js";
import { r as ensureAuthProfileStoreForLocalUpdate } from "./store-BiKyivJC.js";
import { a as normalizeModelCompat } from "./provider-model-compat-BLsYZIOx.js";
import { n as listProfilesForProvider } from "./profile-list-Brv-7ky1.js";
import { d as cloneFirstTemplateModel, f as matchesExactOrPrefix } from "./provider-model-shared-C3XFO8Tx.js";
import "./text-runtime-BXDoRNVl.js";
import { t as buildOauthProviderAuthResult } from "./provider-auth-result-DOeLgCn0.js";
import "./provider-auth-DbAm5fnL.js";
import "./error-runtime-WuGIzMy0.js";
import { r as loginOpenAICodexOAuth } from "./provider-auth-login-CIt_iWGG.js";
import { s as findCatalogTemplate } from "./provider-catalog-shared-DyhemWxL.js";
import { i as fetchCodexUsage } from "./provider-usage-DoUZEJ8d.js";
import { i as isOpenAICodexBaseUrl, r as isOpenAIApiBaseUrl, t as OPENAI_CODEX_RESPONSES_BASE_URL } from "./base-url-60utcShF.js";
import { t as OPENAI_CODEX_DEFAULT_MODEL } from "./default-models-DGmGgd8l.js";
import { n as buildOpenAIResponsesProviderHooks, r as buildOpenAISyntheticCatalogEntry } from "./shared-CM_OyYfR.js";
import { a as OPENAI_CODEX_LOGIN_HINT, i as OPENAI_CODEX_DEVICE_PAIRING_LABEL, o as OPENAI_CODEX_LOGIN_LABEL, r as OPENAI_CODEX_DEVICE_PAIRING_HINT, s as OPENAI_CODEX_WIZARD_GROUP } from "./auth-choice-copy-tQjaDX5l.js";
import { r as resolveCodexAuthIdentity } from "./openai-codex-auth-identity-BqNksRZV.js";
import { n as buildOpenAICodexProvider } from "./openai-codex-catalog-CyAoDW-L.js";
import { t as loginOpenAICodexDeviceCode } from "./openai-codex-device-code-D5x9OGLw.js";
//#region extensions/openai/openai-codex-provider.ts
const PROVIDER_ID = "openai-codex";
const OPENAI_CODEX_BASE_URL = OPENAI_CODEX_RESPONSES_BASE_URL;
const OPENAI_CODEX_LOGIN_ASSISTANT_PRIORITY = -30;
const OPENAI_CODEX_DEVICE_PAIRING_ASSISTANT_PRIORITY = -10;
const OPENAI_CODEX_GPT_55_MODEL_ID = "gpt-5.5";
const OPENAI_CODEX_GPT_55_PRO_MODEL_ID = "gpt-5.5-pro";
const OPENAI_CODEX_GPT_54_MODEL_ID = "gpt-5.4";
const OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID = "gpt-5.4-codex";
const OPENAI_CODEX_GPT_54_PRO_MODEL_ID = "gpt-5.4-pro";
const OPENAI_CODEX_GPT_55_CODEX_CONTEXT_TOKENS = 4e5;
const OPENAI_CODEX_GPT_55_DEFAULT_RUNTIME_CONTEXT_TOKENS = 272e3;
const OPENAI_CODEX_GPT_55_PRO_NATIVE_CONTEXT_TOKENS = 1e6;
const OPENAI_CODEX_GPT_55_PRO_DEFAULT_CONTEXT_TOKENS = 272e3;
const OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS = 105e4;
const OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS = 272e3;
const OPENAI_CODEX_GPT_54_MAX_TOKENS = 128e3;
const OPENAI_CODEX_GPT_55_PRO_COST = {
	input: 30,
	output: 180,
	cacheRead: 0,
	cacheWrite: 0
};
const OPENAI_CODEX_GPT_54_COST = {
	input: 2.5,
	output: 15,
	cacheRead: .25,
	cacheWrite: 0
};
const OPENAI_CODEX_GPT_54_PRO_COST = {
	input: 30,
	output: 180,
	cacheRead: 0,
	cacheWrite: 0
};
const OPENAI_CODEX_GPT_54_TEMPLATE_MODEL_IDS = ["gpt-5.3-codex", "gpt-5.2-codex"];
/** Legacy codex rows first; fall back to catalog `gpt-5.4` when the API omits 5.3/5.2. */
const OPENAI_CODEX_GPT_54_CATALOG_SYNTH_TEMPLATE_MODEL_IDS = [...OPENAI_CODEX_GPT_54_TEMPLATE_MODEL_IDS, OPENAI_CODEX_GPT_54_MODEL_ID];
const OPENAI_CODEX_GPT_55_PRO_TEMPLATE_MODEL_IDS = [
	OPENAI_CODEX_GPT_54_MODEL_ID,
	OPENAI_CODEX_GPT_54_PRO_MODEL_ID,
	...OPENAI_CODEX_GPT_54_TEMPLATE_MODEL_IDS
];
const OPENAI_CODEX_GPT_53_MODEL_ID = "gpt-5.3-codex";
const OPENAI_CODEX_TEMPLATE_MODEL_IDS = ["gpt-5.2-codex"];
const OPENAI_CODEX_XHIGH_MODEL_IDS = [
	OPENAI_CODEX_GPT_55_MODEL_ID,
	OPENAI_CODEX_GPT_55_PRO_MODEL_ID,
	OPENAI_CODEX_GPT_54_MODEL_ID,
	OPENAI_CODEX_GPT_54_PRO_MODEL_ID,
	OPENAI_CODEX_GPT_53_MODEL_ID,
	"gpt-5.2-codex",
	"gpt-5.1-codex"
];
const OPENAI_CODEX_MODERN_MODEL_IDS = [
	OPENAI_CODEX_GPT_55_MODEL_ID,
	OPENAI_CODEX_GPT_55_PRO_MODEL_ID,
	OPENAI_CODEX_GPT_54_MODEL_ID,
	OPENAI_CODEX_GPT_54_PRO_MODEL_ID,
	"gpt-5.2",
	"gpt-5.2-codex",
	OPENAI_CODEX_GPT_53_MODEL_ID
];
function isLegacyCodexCompatBaseUrl(baseUrl) {
	const trimmed = baseUrl?.trim();
	return !!trimmed && /^https?:\/\/api\.githubcopilot\.com(?:\/v1)?\/?$/iu.test(trimmed);
}
function normalizeCodexTransportFields(params) {
	const useCodexTransport = !params.baseUrl || isOpenAIApiBaseUrl(params.baseUrl) || isOpenAICodexBaseUrl(params.baseUrl) || isLegacyCodexCompatBaseUrl(params.baseUrl);
	const api = useCodexTransport && (!params.api || params.api === "openai-responses" || params.api === "openai-completions") ? "openai-codex-responses" : params.api ?? void 0;
	return {
		api,
		baseUrl: api === "openai-codex-responses" && useCodexTransport ? OPENAI_CODEX_BASE_URL : params.baseUrl
	};
}
function normalizeCodexTransport(model) {
	const canonicalModelId = normalizeLowercaseStringOrEmpty(model.id) === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID ? OPENAI_CODEX_GPT_54_MODEL_ID : model.id;
	const canonicalName = normalizeLowercaseStringOrEmpty(model.name) === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID ? OPENAI_CODEX_GPT_54_MODEL_ID : model.name;
	const normalizedTransport = normalizeCodexTransportFields({
		api: model.api,
		baseUrl: model.baseUrl
	});
	const api = normalizedTransport.api ?? model.api;
	const baseUrl = normalizedTransport.baseUrl ?? model.baseUrl;
	if (api === model.api && baseUrl === model.baseUrl && canonicalModelId === model.id && canonicalName === model.name) return model;
	return {
		...model,
		id: canonicalModelId,
		name: canonicalName,
		api,
		baseUrl
	};
}
function resolveCodexForwardCompatModel(ctx) {
	const trimmedModelId = ctx.modelId.trim();
	const lower = normalizeLowercaseStringOrEmpty(trimmedModelId);
	if (lower === OPENAI_CODEX_GPT_55_MODEL_ID) return withDefaultCodexContextMetadata({
		model: ctx.modelRegistry.find(PROVIDER_ID, trimmedModelId),
		contextWindow: OPENAI_CODEX_GPT_55_CODEX_CONTEXT_TOKENS,
		contextTokens: OPENAI_CODEX_GPT_55_DEFAULT_RUNTIME_CONTEXT_TOKENS
	}) ?? normalizeModelCompat({
		id: trimmedModelId,
		name: trimmedModelId,
		api: "openai-codex-responses",
		provider: PROVIDER_ID,
		baseUrl: OPENAI_CODEX_BASE_URL,
		reasoning: true,
		input: ["text", "image"],
		cost: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0
		},
		contextWindow: OPENAI_CODEX_GPT_55_CODEX_CONTEXT_TOKENS,
		contextTokens: OPENAI_CODEX_GPT_55_DEFAULT_RUNTIME_CONTEXT_TOKENS,
		maxTokens: OPENAI_CODEX_GPT_54_MAX_TOKENS
	});
	let templateIds;
	let patch;
	if (lower === OPENAI_CODEX_GPT_55_PRO_MODEL_ID) {
		templateIds = OPENAI_CODEX_GPT_55_PRO_TEMPLATE_MODEL_IDS;
		patch = {
			contextWindow: OPENAI_CODEX_GPT_55_PRO_NATIVE_CONTEXT_TOKENS,
			contextTokens: OPENAI_CODEX_GPT_55_PRO_DEFAULT_CONTEXT_TOKENS,
			maxTokens: OPENAI_CODEX_GPT_54_MAX_TOKENS,
			cost: OPENAI_CODEX_GPT_55_PRO_COST
		};
	} else if (lower === OPENAI_CODEX_GPT_54_MODEL_ID || lower === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID) {
		templateIds = OPENAI_CODEX_GPT_54_CATALOG_SYNTH_TEMPLATE_MODEL_IDS;
		patch = {
			contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
			contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
			maxTokens: OPENAI_CODEX_GPT_54_MAX_TOKENS,
			cost: OPENAI_CODEX_GPT_54_COST
		};
	} else if (lower === OPENAI_CODEX_GPT_54_PRO_MODEL_ID) {
		templateIds = OPENAI_CODEX_GPT_54_CATALOG_SYNTH_TEMPLATE_MODEL_IDS;
		patch = {
			contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
			contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
			maxTokens: OPENAI_CODEX_GPT_54_MAX_TOKENS,
			cost: OPENAI_CODEX_GPT_54_PRO_COST
		};
	} else if (lower === OPENAI_CODEX_GPT_53_MODEL_ID) templateIds = OPENAI_CODEX_TEMPLATE_MODEL_IDS;
	else return;
	return cloneFirstTemplateModel({
		providerId: PROVIDER_ID,
		modelId: lower === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID ? OPENAI_CODEX_GPT_54_MODEL_ID : trimmedModelId,
		templateIds,
		ctx,
		patch
	}) ?? normalizeModelCompat({
		id: lower === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID ? OPENAI_CODEX_GPT_54_MODEL_ID : trimmedModelId,
		name: lower === OPENAI_CODEX_GPT_54_LEGACY_MODEL_ID ? OPENAI_CODEX_GPT_54_MODEL_ID : trimmedModelId,
		api: "openai-codex-responses",
		provider: PROVIDER_ID,
		baseUrl: OPENAI_CODEX_BASE_URL,
		reasoning: true,
		input: ["text", "image"],
		cost: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0
		},
		contextWindow: patch?.contextWindow ?? 2e5,
		contextTokens: patch?.contextTokens,
		maxTokens: patch?.maxTokens ?? 2e5
	});
}
function withDefaultCodexContextMetadata(params) {
	if (!params.model) return;
	const contextTokens = typeof params.model.contextTokens === "number" ? params.model.contextTokens : typeof params.model.contextWindow === "number" && params.model.contextWindow > 0 ? Math.min(params.contextTokens, params.model.contextWindow) : params.contextTokens;
	return {
		...params.model,
		contextWindow: params.contextWindow,
		contextTokens
	};
}
async function refreshOpenAICodexOAuthCredential(cred) {
	try {
		const { refreshOpenAICodexToken } = await import("./extensions/openai/openai-codex-provider.runtime.js");
		const refreshed = await refreshOpenAICodexToken(cred.refresh);
		return {
			...cred,
			...refreshed,
			type: "oauth",
			provider: PROVIDER_ID,
			email: cred.email,
			displayName: cred.displayName
		};
	} catch (error) {
		const message = formatErrorMessage(error);
		if (/extract\s+accountid\s+from\s+token/i.test(message) && typeof cred.access === "string" && cred.access.trim().length > 0) return cred;
		throw error;
	}
}
async function runOpenAICodexOAuth(ctx) {
	let creds;
	try {
		creds = await loginOpenAICodexOAuth({
			prompter: ctx.prompter,
			runtime: ctx.runtime,
			isRemote: ctx.isRemote,
			openUrl: ctx.openUrl,
			localBrowserMessage: "Complete sign-in in browser…"
		});
	} catch {
		return { profiles: [] };
	}
	if (!creds) return { profiles: [] };
	const identity = resolveCodexAuthIdentity({
		accessToken: creds.access,
		email: readStringValue(creds.email)
	});
	return buildOauthProviderAuthResult({
		providerId: PROVIDER_ID,
		defaultModel: OPENAI_CODEX_DEFAULT_MODEL,
		access: creds.access,
		refresh: creds.refresh,
		expires: creds.expires,
		email: identity.email,
		profileName: identity.profileName
	});
}
async function runOpenAICodexDeviceCode(ctx) {
	const spin = ctx.prompter.progress("Starting device code flow…");
	try {
		const creds = await loginOpenAICodexDeviceCode({
			onProgress: (message) => spin.update(message),
			onVerification: async ({ verificationUrl, userCode, expiresInMs }) => {
				const expiresInMinutes = Math.max(1, Math.round(expiresInMs / 6e4));
				const codeLine = ctx.isRemote ? "Code: [shown on the local device only]" : `Code: ${userCode}`;
				await ctx.prompter.note([
					ctx.isRemote ? "Open this URL in your LOCAL browser and enter the code below." : "Open this URL in your browser and enter the code below.",
					`URL: ${verificationUrl}`,
					codeLine,
					`Code expires in ${expiresInMinutes} minutes. Never share it.`
				].join("\n"), "OpenAI Codex device code");
				if (ctx.isRemote) {
					ctx.runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${verificationUrl}\n`);
					return;
				}
				try {
					await ctx.openUrl(verificationUrl);
					ctx.runtime.log(`Open: ${verificationUrl}`);
				} catch {
					ctx.runtime.log(`Open manually: ${verificationUrl}`);
				}
			}
		});
		spin.stop("OpenAI device code complete");
		const identity = resolveCodexAuthIdentity({ accessToken: creds.access });
		return buildOauthProviderAuthResult({
			providerId: PROVIDER_ID,
			defaultModel: OPENAI_CODEX_DEFAULT_MODEL,
			access: creds.access,
			refresh: creds.refresh,
			expires: creds.expires,
			email: identity.email,
			profileName: identity.profileName
		});
	} catch (error) {
		spin.stop("OpenAI device code failed");
		ctx.runtime.error(formatErrorMessage(error));
		await ctx.prompter.note("Trouble with device code login? See https://docs.openclaw.ai/start/faq", "OAuth help");
		throw error;
	}
}
function buildOpenAICodexAuthDoctorHint(ctx) {
	if (ctx.profileId !== "openai-codex:codex-cli") return;
	return "Deprecated profile. Run `openclaw models auth login --provider openai-codex` or `openclaw configure`.";
}
function buildOpenAICodexProviderPlugin() {
	return {
		id: PROVIDER_ID,
		label: "OpenAI Codex",
		docsPath: "/providers/models",
		oauthProfileIdRepairs: [{
			legacyProfileId: "openai-codex:default",
			promptLabel: "OpenAI Codex"
		}],
		auth: [{
			id: "oauth",
			label: OPENAI_CODEX_LOGIN_LABEL,
			hint: OPENAI_CODEX_LOGIN_HINT,
			kind: "oauth",
			wizard: {
				choiceId: "openai-codex",
				choiceLabel: OPENAI_CODEX_LOGIN_LABEL,
				choiceHint: OPENAI_CODEX_LOGIN_HINT,
				assistantPriority: OPENAI_CODEX_LOGIN_ASSISTANT_PRIORITY,
				...OPENAI_CODEX_WIZARD_GROUP
			},
			run: async (ctx) => await runOpenAICodexOAuth(ctx)
		}, {
			id: "device-code",
			label: OPENAI_CODEX_DEVICE_PAIRING_LABEL,
			hint: OPENAI_CODEX_DEVICE_PAIRING_HINT,
			kind: "device_code",
			wizard: {
				choiceId: "openai-codex-device-code",
				choiceLabel: OPENAI_CODEX_DEVICE_PAIRING_LABEL,
				choiceHint: OPENAI_CODEX_DEVICE_PAIRING_HINT,
				assistantPriority: OPENAI_CODEX_DEVICE_PAIRING_ASSISTANT_PRIORITY,
				...OPENAI_CODEX_WIZARD_GROUP
			},
			run: async (ctx) => {
				try {
					return await runOpenAICodexDeviceCode(ctx);
				} catch {
					return { profiles: [] };
				}
			}
		}],
		catalog: {
			order: "profile",
			run: async (ctx) => {
				if (listProfilesForProvider(ensureAuthProfileStoreForLocalUpdate(ctx.agentDir), PROVIDER_ID).length === 0) return null;
				return { provider: buildOpenAICodexProvider() };
			}
		},
		resolveDynamicModel: (ctx) => resolveCodexForwardCompatModel(ctx),
		buildAuthDoctorHint: (ctx) => buildOpenAICodexAuthDoctorHint(ctx),
		resolveThinkingProfile: ({ modelId }) => ({ levels: [
			{ id: "off" },
			{ id: "minimal" },
			{ id: "low" },
			{ id: "medium" },
			{ id: "high" },
			...matchesExactOrPrefix(modelId, OPENAI_CODEX_XHIGH_MODEL_IDS) ? [{ id: "xhigh" }] : []
		] }),
		isModernModelRef: ({ modelId }) => matchesExactOrPrefix(modelId, OPENAI_CODEX_MODERN_MODEL_IDS),
		preferRuntimeResolvedModel: (ctx) => {
			if (normalizeProviderId(ctx.provider) !== PROVIDER_ID) return false;
			const id = ctx.modelId.trim().toLowerCase();
			return [
				OPENAI_CODEX_GPT_55_MODEL_ID,
				OPENAI_CODEX_GPT_55_PRO_MODEL_ID,
				OPENAI_CODEX_GPT_54_MODEL_ID,
				OPENAI_CODEX_GPT_54_PRO_MODEL_ID
			].includes(id);
		},
		...buildOpenAIResponsesProviderHooks(),
		resolveReasoningOutputMode: () => "native",
		normalizeResolvedModel: (ctx) => {
			if (normalizeProviderId(ctx.provider) !== PROVIDER_ID) return;
			return normalizeCodexTransport(ctx.model);
		},
		normalizeTransport: ({ provider, api, baseUrl }) => {
			if (normalizeProviderId(provider) !== PROVIDER_ID) return;
			const normalized = normalizeCodexTransportFields({
				api,
				baseUrl
			});
			if (normalized.api === api && normalized.baseUrl === baseUrl) return;
			return normalized;
		},
		resolveUsageAuth: async (ctx) => await ctx.resolveOAuthToken(),
		fetchUsageSnapshot: async (ctx) => await fetchCodexUsage(ctx.token, ctx.accountId, ctx.timeoutMs, ctx.fetchFn),
		refreshOAuth: async (cred) => await refreshOpenAICodexOAuthCredential(cred),
		augmentModelCatalog: (ctx) => {
			const gpt54Template = findCatalogTemplate({
				entries: ctx.entries,
				providerId: PROVIDER_ID,
				templateIds: OPENAI_CODEX_GPT_54_CATALOG_SYNTH_TEMPLATE_MODEL_IDS
			});
			return [
				buildOpenAISyntheticCatalogEntry(findCatalogTemplate({
					entries: ctx.entries,
					providerId: PROVIDER_ID,
					templateIds: OPENAI_CODEX_GPT_55_PRO_TEMPLATE_MODEL_IDS
				}), {
					id: OPENAI_CODEX_GPT_55_PRO_MODEL_ID,
					reasoning: true,
					input: ["text", "image"],
					contextWindow: OPENAI_CODEX_GPT_55_PRO_NATIVE_CONTEXT_TOKENS,
					contextTokens: OPENAI_CODEX_GPT_55_PRO_DEFAULT_CONTEXT_TOKENS,
					cost: OPENAI_CODEX_GPT_55_PRO_COST
				}),
				buildOpenAISyntheticCatalogEntry(gpt54Template, {
					id: OPENAI_CODEX_GPT_54_MODEL_ID,
					reasoning: true,
					input: ["text", "image"],
					contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
					contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
					cost: OPENAI_CODEX_GPT_54_COST
				}),
				buildOpenAISyntheticCatalogEntry(gpt54Template, {
					id: OPENAI_CODEX_GPT_54_PRO_MODEL_ID,
					reasoning: true,
					input: ["text", "image"],
					contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
					contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
					cost: OPENAI_CODEX_GPT_54_PRO_COST
				})
			].filter((entry) => entry !== void 0);
		}
	};
}
//#endregion
export { buildOpenAICodexProviderPlugin as t };
