import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { ExtensionAPI, OAuthCredentials, OAuthLoginCallbacks, ProviderModelConfig, RefreshModelsContext, } from "@earendil-works/pi-coding-agent"; /** * Generic compatible endpoint. * * /login custom-endpoint asks for a base URL, an API key, and one of four * protocols. The model list is fetched from the endpoint on startup and * whenever /model opens, then cached for offline use. * * One endpoint at a time: logging in again replaces the previous one. */ const PROVIDER_ID = "custom-endpoint"; type ProtocolId = "openai-completions" | "openai-responses" | "anthropic-messages" | "google-generative-ai"; interface Protocol { id: ProtocolId; label: string; placeholder: string; } const PROTOCOLS: Protocol[] = [ { id: "openai-completions", label: "OpenAI Completions", placeholder: "https://example.com/v1", }, { id: "openai-responses", label: "OpenAI Responses", placeholder: "https://api.openai.com/v1", }, { id: "anthropic-messages", label: "Anthropic Messages", placeholder: "https://api.anthropic.com", }, { id: "google-generative-ai", label: "Google Generative AI", placeholder: "https://generativelanguage.googleapis.com/v1beta", }, ]; const DEFAULT_CONTEXT_WINDOW = 128_000; const DEFAULT_MAX_TOKENS = 8_192; const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; interface EndpointCredentials extends OAuthCredentials { baseUrl: string; api: ProtocolId; } function isProtocol(value: unknown): value is ProtocolId { return PROTOCOLS.some((protocol) => protocol.id === value); } function credentialsOf(credentials: OAuthCredentials): EndpointCredentials | undefined { const extra = credentials as Partial; if (!credentials.access || typeof extra.baseUrl !== "string" || !isProtocol(extra.api)) return undefined; return { ...credentials, access: credentials.access, baseUrl: extra.baseUrl.replace(/\/+$/, ""), api: extra.api }; } function requireCredentials(context: RefreshModelsContext): EndpointCredentials | undefined { if (context.credential?.type !== "oauth") return undefined; return credentialsOf(context.credential); } /** Credentials saved by the previous login, available before this session refreshes. */ function savedCredentials(): EndpointCredentials | undefined { try { const stored = JSON.parse(readFileSync(join(homedir(), ".pi", "agent", "auth.json"), "utf8")) as Record< string, unknown >; const credential = stored[PROVIDER_ID]; if (typeof credential !== "object" || !credential) return undefined; return credentialsOf(credential as OAuthCredentials); } catch { return undefined; } } async function login(callbacks: OAuthLoginCallbacks): Promise { const baseUrl = ( await callbacks.onPrompt({ message: "Base URL", placeholder: "https://example.com/v1", }) ).trim().replace(/\/+$/, ""); if (!baseUrl) throw new Error("Base URL is required"); const access = (await callbacks.onPrompt({ message: "API key" })).trim(); if (!access) throw new Error("API key is required"); const selected = await callbacks.onSelect({ message: "API format", options: PROTOCOLS.map((protocol) => ({ id: protocol.id, label: protocol.label })), }); if (!isProtocol(selected)) throw new Error("Login cancelled"); return { access, refresh: "none", expires: Date.now() + 10 * 365 * 24 * 60 * 60 * 1000, baseUrl, api: selected }; } interface RawModel { id?: unknown; name?: unknown; display_name?: unknown; displayName?: unknown; context_window?: unknown; contextWindow?: unknown; context_length?: unknown; inputTokenLimit?: unknown; max_output_tokens?: unknown; maxOutputTokens?: unknown; outputTokenLimit?: unknown; reasoning?: unknown; supported_reasoning_levels?: unknown; modalities?: { input?: unknown }; supportedGenerationMethods?: unknown; } function positiveNumber(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined; } function stringList(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; } function toModel(raw: RawModel, api: ProtocolId): ProviderModelConfig | undefined { const rawId = typeof raw.id === "string" ? raw.id : typeof raw.name === "string" ? raw.name : undefined; if (!rawId) return undefined; const id = api === "google-generative-ai" ? rawId.replace(/^models\//, "") : rawId; if (!id || id.includes("embedding") || id.includes("embed-")) return undefined; const display = [raw.display_name, raw.displayName, raw.name].find((value) => typeof value === "string" && value !== rawId); const inputs = stringList(raw.modalities?.input); const efforts = Array.isArray(raw.supported_reasoning_levels) ? raw.supported_reasoning_levels.flatMap((level) => typeof level === "object" && level && typeof (level as { effort?: unknown }).effort === "string" ? [(level as { effort: string }).effort] : [], ) : []; const reasoning = raw.reasoning === true || efforts.length > 0; return { id, name: typeof display === "string" ? display : id, api, baseUrl: "", reasoning, ...(reasoning && efforts.length > 0 ? { thinkingLevelMap: Object.fromEntries( ["off", "minimal", "low", "medium", "high", "xhigh", "max"].map((level) => [ level, efforts.includes(level) ? level : null, ]), ), } : {}), input: inputs.includes("image") ? ["text", "image"] : ["text"], cost: ZERO_COST, contextWindow: positiveNumber(raw.context_window) ?? positiveNumber(raw.contextWindow) ?? positiveNumber(raw.context_length) ?? positiveNumber(raw.inputTokenLimit) ?? DEFAULT_CONTEXT_WINDOW, maxTokens: positiveNumber(raw.max_output_tokens) ?? positiveNumber(raw.maxOutputTokens) ?? positiveNumber(raw.outputTokenLimit) ?? DEFAULT_MAX_TOKENS, }; } export function modelsFromPayload(payload: unknown, api: ProtocolId, baseUrl: string): ProviderModelConfig[] { const list = Array.isArray(payload) ? payload : typeof payload === "object" && payload && Array.isArray((payload as { data?: unknown; models?: unknown }).data) ? (payload as { data: unknown[] }).data : typeof payload === "object" && payload && Array.isArray((payload as { models?: unknown }).models) ? (payload as { models: unknown[] }).models : []; const models = list.flatMap((item) => { if (typeof item !== "object" || !item) return []; const model = toModel(item as RawModel, api); return model ? [{ ...model, baseUrl }] : []; }); const seen = new Set(); return models.filter((model) => (seen.has(model.id) ? false : (seen.add(model.id), true))); } async function fetchModels(credentials: EndpointCredentials, signal: AbortSignal): Promise { const headers: Record = { Accept: "application/json" }; let url = `${credentials.baseUrl}/models`; if (credentials.api === "anthropic-messages") { headers["x-api-key"] = credentials.access; headers["anthropic-version"] = "2023-06-01"; } else if (credentials.api === "google-generative-ai") { url += `?key=${encodeURIComponent(credentials.access)}`; } else { headers.Authorization = `Bearer ${credentials.access}`; } const response = await fetch(url, { headers, signal }); if (!response.ok) { const body = await response.text().catch(() => ""); throw new Error(`${PROVIDER_ID}: ${response.status} ${response.statusText} ${body.slice(0, 200)}`); } const models = modelsFromPayload(await response.json(), credentials.api, credentials.baseUrl); if (models.length === 0) throw new Error(`${PROVIDER_ID}: model list was empty`); return models; } export default function (pi: ExtensionAPI) { const saved = savedCredentials(); pi.registerProvider(PROVIDER_ID, { name: "Custom endpoint", baseUrl: saved?.baseUrl ?? "https://placeholder.invalid/v1", api: saved?.api ?? "openai-completions", models: [], oauth: { name: "Custom endpoint (URL + key)", login, refreshToken: async (credentials) => credentials, getApiKey: (credentials) => credentials.access, }, refreshModels: async (context) => { const credentials = requireCredentials(context); if (!credentials || !context.allowNetwork) return []; const models = await fetchModels(credentials, context.signal); if (context.signal.aborted) return []; await context.publish({ persist: { models: models as never, checkedAt: Date.now() }, }); return models; }, }); }