import { S as detectLocalProviders, H as createLogger } from './src-CidJbygh.js';
import { d as getRequestId, r as requireAdmin, p as parseJsonBody, j as jsonBodyError, k as jsonResponse, e as errorResponse, g as getOpenCodeClient } from './helpers-kzwksNq1.js';
import { b as setProviderOptions, p as patchConfig, a as setProviderEnabled, g as getCurrentConfig, r as registerProvider, s as setMainModel } from './config-CO8OSXtU.js';
import { a as asStringOrEmpty, p as parseHeaders, d as updateNumberOption, u as updateBooleanOption, c as parseModels, b as buildModelConfig } from './_helpers-B_lb4-jB.js';
import './chunk-CLZ62Ad-.js';
import 'node:module';
import './provider-constants-DPrj3yBX.js';
import './dist-DOFcG0Zp.js';
import 'node:fs';
import 'node:path';
import 'buffer';
import 'fs';
import 'path';
import 'node:child_process';
import 'node:url';
import 'node:crypto';
import 'events';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'assert';
import 'zlib';
import 'node:assert';
import 'node:fs/promises';
import 'node:os';
import './endpoints-UdQGgKsR.js';
import './state-fxN45gBp.js';
import './coercion-TNFJisCC.js';
import './http-D8YVIqJa.js';

//#region src/routes/admin/providers/[id]/+server.ts
var logger = createLogger("admin.providers.patch");
/** Allowed format for a custom provider id */
var CUSTOM_PROVIDER_ID_PATTERN = /^[a-z0-9_-]+$/;
var LOCAL_PROVIDER_LABELS = {
	ollama: "Local Ollama",
	lmstudio: "Local LM Studio",
	"model-runner": "Docker Model Runner"
};
var PATCH = async (event) => {
	const requestId = getRequestId(event);
	const authError = requireAdmin(event, requestId);
	if (authError) return authError;
	const providerId = event.params.id;
	const parsed = await parseJsonBody(event.request);
	if ("error" in parsed) return jsonBodyError(parsed, requestId);
	const body = parsed.data;
	const kind = typeof body.kind === "string" ? body.kind : "";
	if (kind === "options") try {
		const baseURL = asStringOrEmpty(body.baseURL);
		const enterpriseUrl = asStringOrEmpty(body.enterpriseUrl);
		const headers = parseHeaders(asStringOrEmpty(body.headers));
		const nextOptions = {};
		updateNumberOption(nextOptions, "timeout", asStringOrEmpty(body.timeout));
		updateBooleanOption(nextOptions, "setCacheKey", body.setCacheKey === "on" || body.setCacheKey === true);
		await setProviderOptions(providerId, {
			baseURL: baseURL || void 0,
			enterpriseUrl: enterpriseUrl || void 0,
			timeout: typeof nextOptions.timeout === "number" ? nextOptions.timeout : void 0,
			setCacheKey: nextOptions.setCacheKey === true,
			headers: headers && Object.keys(headers).length > 0 ? headers : null
		});
		return jsonResponse(200, {
			ok: true,
			message: "Provider settings saved.",
			selectedProviderId: providerId
		}, requestId);
	} catch (error) {
		return jsonResponse(200, {
			ok: false,
			message: error instanceof Error ? error.message : "Internal error",
			selectedProviderId: void 0
		}, requestId);
	}
	if (kind === "toggle") try {
		const nextState = asStringOrEmpty(body.enabled) === "true" || body.enabled === true;
		await patchConfig(setProviderEnabled(await getCurrentConfig(), providerId, nextState));
		return jsonResponse(200, {
			ok: true,
			message: nextState ? "Provider enabled for model selection." : "Provider disabled for this workspace.",
			selectedProviderId: providerId
		}, requestId);
	} catch (error) {
		return jsonResponse(200, {
			ok: false,
			message: error instanceof Error ? error.message : "Internal error",
			selectedProviderId: void 0
		}, requestId);
	}
	if (kind === "register-local") try {
		if (!Object.prototype.hasOwnProperty.call(LOCAL_PROVIDER_LABELS, providerId)) return errorResponse(400, "bad_request", "provider must be one of: ollama, lmstudio, model-runner", {}, requestId);
		const match = (await detectLocalProviders()).find((d) => d.provider === providerId);
		if (!match || !match.available) return jsonResponse(200, {
			ok: false,
			message: `No reachable ${LOCAL_PROVIDER_LABELS[providerId] ?? providerId} endpoint found.`,
			selectedProviderId: providerId
		}, requestId);
		const existingEntry = ((await getCurrentConfig()).provider ?? {})[providerId];
		const existingOptions = existingEntry?.options ?? {};
		await registerProvider(providerId, {
			npm: typeof existingEntry?.npm === "string" ? existingEntry.npm : "@ai-sdk/openai-compatible",
			name: typeof existingEntry?.name === "string" ? existingEntry.name : LOCAL_PROVIDER_LABELS[providerId] ?? providerId,
			options: {
				...existingOptions,
				baseURL: match.url
			}
		}, true);
		return jsonResponse(200, {
			ok: true,
			message: `Registered ${LOCAL_PROVIDER_LABELS[providerId] ?? providerId} at ${match.url}.`,
			selectedProviderId: providerId
		}, requestId);
	} catch (err) {
		return jsonResponse(200, {
			ok: false,
			message: err instanceof Error ? err.message : String(err),
			selectedProviderId: providerId
		}, requestId);
	}
	if (kind === "register-custom") try {
		const displayName = asStringOrEmpty(body.displayName);
		const baseURL = asStringOrEmpty(body.baseURL);
		const apiKey = asStringOrEmpty(body.apiKey);
		const confirmOverwrite = asStringOrEmpty(body.confirmOverwrite) === "true";
		if (!CUSTOM_PROVIDER_ID_PATTERN.test(providerId)) return jsonResponse(200, {
			ok: false,
			message: "Use a lowercase provider id with letters, numbers, hyphens, or underscores.",
			selectedProviderId: void 0
		}, requestId);
		if (!displayName || !baseURL) return jsonResponse(200, {
			ok: false,
			message: "Display name and base URL are required for a custom provider.",
			selectedProviderId: providerId
		}, requestId);
		const models = parseModels(asStringOrEmpty(body.modelsJson));
		const headers = parseHeaders(asStringOrEmpty(body.headersJson));
		const entry = {
			npm: "@ai-sdk/openai-compatible",
			name: displayName,
			options: {
				baseURL,
				...Object.keys(headers).length > 0 ? { headers } : {}
			}
		};
		if (models.length > 0) entry.models = Object.fromEntries(models.map((m) => [m.id, buildModelConfig(m)]));
		if ((await registerProvider(providerId, entry, confirmOverwrite)).alreadyExists) return jsonResponse(200, {
			ok: false,
			message: "A provider with this ID already exists. Enable overwrite to replace it.",
			selectedProviderId: providerId
		}, requestId);
		if (apiKey) try {
			const authResult = await getOpenCodeClient().setProviderApiKey(providerId, apiKey);
			if (!authResult.ok) logger.warn("custom provider apiKey save failed", {
				providerId,
				code: authResult.code,
				message: authResult.message,
				requestId
			});
		} catch (err) {
			logger.warn("custom provider apiKey threw", {
				providerId,
				error: String(err),
				requestId
			});
		}
		return jsonResponse(200, {
			ok: true,
			message: "Custom provider saved.",
			selectedProviderId: providerId
		}, requestId);
	} catch (error) {
		return jsonResponse(200, {
			ok: false,
			message: error instanceof Error ? error.message : "Internal error",
			selectedProviderId: void 0
		}, requestId);
	}
	if (kind === "set-model") try {
		const modelId = asStringOrEmpty(body.modelId);
		const target = asStringOrEmpty(body.target);
		if (!modelId || target !== "model" && target !== "small_model") return jsonResponse(200, {
			ok: false,
			message: "Choose a provider model before saving it.",
			selectedProviderId: void 0
		}, requestId);
		await setMainModel(providerId, modelId, target);
		return jsonResponse(200, {
			ok: true,
			message: target === "model" ? "Main model updated for this project." : "Small model updated for lightweight tasks.",
			selectedProviderId: providerId
		}, requestId);
	} catch (error) {
		return jsonResponse(200, {
			ok: false,
			message: error instanceof Error ? error.message : "Internal error",
			selectedProviderId: void 0
		}, requestId);
	}
	return errorResponse(400, "bad_request", `Unknown kind "${kind}". Expected: options, toggle, register-local, register-custom, set-model`, {}, requestId);
};

export { PATCH };
//# sourceMappingURL=_server.ts-Ba5LpOKk.js.map
