index.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /**
  2. * vim: set noet ts=8:
  3. * DuckCoding AI Custom Provider
  4. *
  5. * Provides access to DuckCoding AI models via an OpenAI-compatible API.
  6. *
  7. * Usage:
  8. * Set the DUCKCODING_API_KEY environment variable with your API key.
  9. * Then use /model to select duckcoding/<model-id>.
  10. *
  11. * Models are fetched from DuckCoding's pricing endpoint and cached locally.
  12. * The cache is refreshed after seven days by default. Set
  13. * DUCKCODING_MODEL_CACHE_TTL_MS to override the cache lifetime.
  14. */
  15. import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
  16. import { homedir } from "node:os";
  17. import { join } from "node:path";
  18. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  19. type DuckCodingPricingResponse = {
  20. success?: boolean;
  21. data?: Array<{
  22. model_name?: string;
  23. vendor_id?: number;
  24. supported_endpoint_types?: string[];
  25. enable_groups?: string[];
  26. model_price?: number;
  27. model_ratio?: number;
  28. completion_ratio?: number;
  29. cache_ratio?: number;
  30. create_cache_ratio?: number;
  31. }>;
  32. };
  33. const PRICING_URL = "https://www.duckcoding.ai/api/pricing";
  34. const DEFAULT_MODEL_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
  35. const MODEL_CACHE_PATH = join(homedir(), ".cache", "pi-agent-duckcoding", "models.json");
  36. type CachedModels = {
  37. fetchedAt: number;
  38. models: ReturnType<typeof createModels>;
  39. };
  40. function titleCaseModelName(modelName: string) {
  41. return modelName
  42. .split(/[-_/]+/)
  43. .map((part) => (part ? part[0].toUpperCase() + part.slice(1) : part))
  44. .join(" ");
  45. }
  46. function inferReasoning(modelName: string) {
  47. return /reasoner|thinking|o[34]|claude-sonnet|codex/i.test(modelName);
  48. }
  49. function inferInputModes(endpoints: string[] = []) {
  50. const input = ["text"];
  51. if (endpoints.some((endpoint) => ["openai", "anthropic"].includes(endpoint))) {
  52. input.push("image");
  53. }
  54. return input;
  55. }
  56. function inferContextWindow(modelName: string) {
  57. if (/gpt-5\./i.test(modelName) || /claude/i.test(modelName)) return 200000;
  58. if (/gpt-4o|o4|codex|deepseek/i.test(modelName)) return 128000;
  59. return 64000;
  60. }
  61. function inferMaxTokens(modelName: string) {
  62. if (/gpt-5\./i.test(modelName) || /claude/i.test(modelName)) return 8192;
  63. return 16384;
  64. }
  65. function inferCost(model: { model_price?: number; model_ratio?: number; completion_ratio?: number; cache_ratio?: number; create_cache_ratio?: number }) {
  66. const input = model.model_price ?? model.model_ratio ?? 0;
  67. const output = model.completion_ratio ?? 0;
  68. const cacheRead = model.cache_ratio ?? 0;
  69. const cacheWrite = model.create_cache_ratio ?? 0;
  70. return { input, output, cacheRead, cacheWrite };
  71. }
  72. function createModels(pricing: DuckCodingPricingResponse) {
  73. return (pricing.data ?? [])
  74. .filter((model) => model.model_name)
  75. .filter((model) => (model.supported_endpoint_types ?? []).some((endpoint) => endpoint === "openai" || endpoint === "anthropic"))
  76. .map((model) => ({
  77. id: model.model_name!,
  78. name: titleCaseModelName(model.model_name!),
  79. reasoning: inferReasoning(model.model_name!),
  80. input: inferInputModes(model.supported_endpoint_types),
  81. cost: inferCost(model),
  82. contextWindow: inferContextWindow(model.model_name!),
  83. maxTokens: inferMaxTokens(model.model_name!),
  84. }))
  85. .sort((a, b) => a.id.localeCompare(b.id));
  86. }
  87. async function readCachedModels() {
  88. try {
  89. const cached = JSON.parse(await readFile(MODEL_CACHE_PATH, "utf8")) as CachedModels;
  90. if (Array.isArray(cached.models) && typeof cached.fetchedAt === "number") return cached;
  91. } catch {
  92. // A missing or invalid cache is treated as a cache miss.
  93. }
  94. return undefined;
  95. }
  96. async function writeCachedModels(models: CachedModels["models"]) {
  97. const directory = join(homedir(), ".cache", "pi-agent-duckcoding");
  98. const temporaryPath = `${MODEL_CACHE_PATH}.tmp`;
  99. await mkdir(directory, { recursive: true });
  100. await writeFile(temporaryPath, JSON.stringify({ fetchedAt: Date.now(), models }, null, 2));
  101. await rename(temporaryPath, MODEL_CACHE_PATH);
  102. }
  103. async function getModels() {
  104. const cached = await readCachedModels();
  105. const cacheTtl = Number(process.env.DUCKCODING_MODEL_CACHE_TTL_MS ?? DEFAULT_MODEL_CACHE_TTL_MS);
  106. const ttl = Number.isFinite(cacheTtl) && cacheTtl >= 0 ? cacheTtl : DEFAULT_MODEL_CACHE_TTL_MS;
  107. if (cached && Date.now() - cached.fetchedAt < ttl) return cached.models;
  108. try {
  109. const response = await fetch(PRICING_URL);
  110. if (!response.ok) {
  111. throw new Error(`${response.status} ${response.statusText}`);
  112. }
  113. const models = createModels((await response.json()) as DuckCodingPricingResponse);
  114. if (models.length === 0) throw new Error("pricing response contained no compatible models");
  115. try {
  116. await writeCachedModels(models);
  117. } catch {
  118. // The freshly fetched list is still usable if the cache cannot be written.
  119. }
  120. return models;
  121. } catch (error) {
  122. if (cached) return cached.models;
  123. throw new Error(`Failed to fetch DuckCoding pricing: ${error instanceof Error ? error.message : String(error)}`);
  124. }
  125. }
  126. export default async function (pi: ExtensionAPI) {
  127. const models = await getModels();
  128. pi.registerProvider("duckcoding", {
  129. name: "DuckCoding AI",
  130. baseUrl: "https://api.duckcoding.ai/v1",
  131. apiKey: "$DUCKCODING_API_KEY",
  132. api: "openai-completions",
  133. models,
  134. headers: {},
  135. });
  136. }