import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
import { d as ensureAuthProfileStore, h as normalizeOptionalSecretInput } from "./auth-profiles-BSw0aQND.js";
import { c as normalizeProviderId } from "./model-selection-BqshlIZc.js";
import path from "node:path";
import fs from "node:fs/promises";

//#region src/agents/pi-auth-json.ts
var pi_auth_json_exports = /* @__PURE__ */ __exportAll({ ensurePiAuthJsonFromAuthProfiles: () => ensurePiAuthJsonFromAuthProfiles });
async function readAuthJson(filePath) {
	try {
		const raw = await fs.readFile(filePath, "utf8");
		const parsed = JSON.parse(raw);
		if (!parsed || typeof parsed !== "object") return {};
		return parsed;
	} catch {
		return {};
	}
}
/**
* Convert an Symi auth-profiles credential to pi-coding-agent auth.json format.
* Returns null if the credential cannot be converted.
*/
function convertCredential(cred) {
	if (cred.type === "api_key") {
		const key = typeof cred.key === "string" ? cred.key.trim() : "";
		if (!key) return null;
		return {
			type: "api_key",
			key
		};
	}
	if (cred.type === "token") {
		const token = typeof cred.token === "string" ? cred.token.trim() : "";
		if (!token) return null;
		const expires = typeof cred.expires === "number" ? cred.expires : NaN;
		if (Number.isFinite(expires) && expires > 0 && Date.now() >= expires) return null;
		return {
			type: "api_key",
			key: token
		};
	}
	if (cred.type === "oauth") {
		const accessRaw = cred.access;
		const refreshRaw = cred.refresh;
		const expiresRaw = cred.expires;
		const access = typeof accessRaw === "string" ? accessRaw.trim() : "";
		const refresh = typeof refreshRaw === "string" ? refreshRaw.trim() : "";
		const expires = typeof expiresRaw === "number" ? expiresRaw : NaN;
		if (!access || !refresh || !Number.isFinite(expires) || expires <= 0) return null;
		return {
			type: "oauth",
			access,
			refresh,
			expires
		};
	}
	return null;
}
/**
* Check if two auth.json credentials are equivalent.
*/
function credentialsEqual(a, b) {
	if (!a || typeof a !== "object") return false;
	if (a.type !== b.type) return false;
	if (a.type === "api_key" && b.type === "api_key") return a.key === b.key;
	if (a.type === "oauth" && b.type === "oauth") return a.access === b.access && a.refresh === b.refresh && a.expires === b.expires;
	return false;
}
/**
* pi-coding-agent's ModelRegistry/AuthStorage expects credentials in auth.json.
*
* Symi stores credentials in auth-profiles.json instead. This helper
* bridges all credentials into agentDir/auth.json so pi-coding-agent can
* (a) consider providers authenticated and (b) include built-in models in its
* registry/catalog output.
*
* Syncs all credential types: api_key, token (as api_key), and oauth.
*
* When a SymiConfig is supplied via options.config, any provider in
* config.models.providers that declares an inline apiKey is also seeded into
* auth.json (for providers not already covered by an auth-profile). This is
* required for user-defined OpenAI-compatible endpoints (e.g. CoreWeave vLLM
* with apiKey: "none"): without an auth.json entry, pi-coding-agent's
* AuthStorage treats the provider as unauthenticated and the SDK fails with
* "Connection error" before any HTTP request is made.
*/
async function ensurePiAuthJsonFromAuthProfiles(agentDir, options) {
	const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false });
	const authPath = path.join(agentDir, "auth.json");
	const providerCredentials = /* @__PURE__ */ new Map();
	for (const [, cred] of Object.entries(store.profiles)) {
		const provider = normalizeProviderId(String(cred.provider ?? "")).trim();
		if (!provider || providerCredentials.has(provider)) continue;
		const converted = convertCredential(cred);
		if (converted) providerCredentials.set(provider, converted);
	}
	const inlineProviders = options?.config?.models?.providers;
	if (inlineProviders) for (const [providerKey, providerCfg] of Object.entries(inlineProviders)) {
		const provider = normalizeProviderId(String(providerKey ?? "")).trim();
		if (!provider || providerCredentials.has(provider)) continue;
		const inlineKey = normalizeOptionalSecretInput(providerCfg?.apiKey);
		if (!inlineKey) continue;
		providerCredentials.set(provider, {
			type: "api_key",
			key: inlineKey
		});
	}
	if (providerCredentials.size === 0) return {
		wrote: false,
		authPath
	};
	const existing = await readAuthJson(authPath);
	let changed = false;
	for (const [provider, cred] of providerCredentials) if (!credentialsEqual(existing[provider], cred)) {
		existing[provider] = cred;
		changed = true;
	}
	if (!changed) return {
		wrote: false,
		authPath
	};
	await fs.mkdir(agentDir, {
		recursive: true,
		mode: 448
	});
	await fs.writeFile(authPath, `${JSON.stringify(existing, null, 2)}\n`, { mode: 384 });
	return {
		wrote: true,
		authPath
	};
}

//#endregion
export { pi_auth_json_exports as n, ensurePiAuthJsonFromAuthProfiles as t };