/** * vim: set noet ts=8: * DuckCoding AI Custom Provider * * Provides access to DuckCoding AI models via an OpenAI-compatible API. * * Usage: * Set the DUCKCODING_API_KEY environment variable with your API key. * Then use /model to select duckcoding/. * * Models are fetched from DuckCoding's pricing endpoint and cached locally. * The cache is refreshed after seven days by default. Set * DUCKCODING_MODEL_CACHE_TTL_MS to override the cache lifetime. */ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; type DuckCodingPricingResponse = { success?: boolean; data?: Array<{ model_name?: string; vendor_id?: number; supported_endpoint_types?: string[]; enable_groups?: string[]; model_price?: number; model_ratio?: number; completion_ratio?: number; cache_ratio?: number; create_cache_ratio?: number; }>; }; const PRICING_URL = "https://www.duckcoding.ai/api/pricing"; const DEFAULT_MODEL_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; const MODEL_CACHE_PATH = join(homedir(), ".cache", "pi-agent-duckcoding", "models.json"); type CachedModels = { fetchedAt: number; models: ReturnType; }; function titleCaseModelName(modelName: string) { return modelName .split(/[-_/]+/) .map((part) => (part ? part[0].toUpperCase() + part.slice(1) : part)) .join(" "); } function inferReasoning(modelName: string) { return /reasoner|thinking|o[34]|claude-sonnet|codex/i.test(modelName); } function inferInputModes(endpoints: string[] = []) { const input = ["text"]; if (endpoints.some((endpoint) => ["openai", "anthropic"].includes(endpoint))) { input.push("image"); } return input; } function inferContextWindow(modelName: string) { if (/gpt-5\./i.test(modelName) || /claude/i.test(modelName)) return 200000; if (/gpt-4o|o4|codex|deepseek/i.test(modelName)) return 128000; return 64000; } function inferMaxTokens(modelName: string) { if (/gpt-5\./i.test(modelName) || /claude/i.test(modelName)) return 8192; return 16384; } function inferCost(model: { model_price?: number; model_ratio?: number; completion_ratio?: number; cache_ratio?: number; create_cache_ratio?: number }) { const input = model.model_price ?? model.model_ratio ?? 0; const output = model.completion_ratio ?? 0; const cacheRead = model.cache_ratio ?? 0; const cacheWrite = model.create_cache_ratio ?? 0; return { input, output, cacheRead, cacheWrite }; } function createModels(pricing: DuckCodingPricingResponse) { return (pricing.data ?? []) .filter((model) => model.model_name) .filter((model) => (model.supported_endpoint_types ?? []).some((endpoint) => endpoint === "openai" || endpoint === "anthropic")) .map((model) => ({ id: model.model_name!, name: titleCaseModelName(model.model_name!), reasoning: inferReasoning(model.model_name!), input: inferInputModes(model.supported_endpoint_types), cost: inferCost(model), contextWindow: inferContextWindow(model.model_name!), maxTokens: inferMaxTokens(model.model_name!), })) .sort((a, b) => a.id.localeCompare(b.id)); } async function readCachedModels() { try { const cached = JSON.parse(await readFile(MODEL_CACHE_PATH, "utf8")) as CachedModels; if (Array.isArray(cached.models) && typeof cached.fetchedAt === "number") return cached; } catch { // A missing or invalid cache is treated as a cache miss. } return undefined; } async function writeCachedModels(models: CachedModels["models"]) { const directory = join(homedir(), ".cache", "pi-agent-duckcoding"); const temporaryPath = `${MODEL_CACHE_PATH}.tmp`; await mkdir(directory, { recursive: true }); await writeFile(temporaryPath, JSON.stringify({ fetchedAt: Date.now(), models }, null, 2)); await rename(temporaryPath, MODEL_CACHE_PATH); } async function getModels() { const cached = await readCachedModels(); const cacheTtl = Number(process.env.DUCKCODING_MODEL_CACHE_TTL_MS ?? DEFAULT_MODEL_CACHE_TTL_MS); const ttl = Number.isFinite(cacheTtl) && cacheTtl >= 0 ? cacheTtl : DEFAULT_MODEL_CACHE_TTL_MS; if (cached && Date.now() - cached.fetchedAt < ttl) return cached.models; try { const response = await fetch(PRICING_URL); if (!response.ok) { throw new Error(`${response.status} ${response.statusText}`); } const models = createModels((await response.json()) as DuckCodingPricingResponse); if (models.length === 0) throw new Error("pricing response contained no compatible models"); try { await writeCachedModels(models); } catch { // The freshly fetched list is still usable if the cache cannot be written. } return models; } catch (error) { if (cached) return cached.models; throw new Error(`Failed to fetch DuckCoding pricing: ${error instanceof Error ? error.message : String(error)}`); } } export default async function (pi: ExtensionAPI) { const models = await getModels(); pi.registerProvider("duckcoding", { name: "DuckCoding AI", baseUrl: "https://api.duckcoding.ai/v1", apiKey: "$DUCKCODING_API_KEY", api: "openai-completions", models, headers: {}, }); }