|
| 1 | +import * as fs from "fs"; |
| 2 | +import * as os from "os"; |
| 3 | +import * as path from "path"; |
| 4 | +import { fetch as undiciFetch } from "undici"; |
| 5 | +import type { CreateOpenAIClient, OpenAIClientResult } from "./tool-types"; |
| 6 | + |
| 7 | +export const DEEPCODE_PLUS_LEGACY_HOST = "https://deepcode.vegamo.cn"; |
| 8 | +export const DEEPCODE_PLUS_HOST = "https://www.deepcodeplus.com"; |
| 9 | + |
| 10 | +/** Undefined means unconfigured; all explicitly configured values must be valid. */ |
| 11 | +export function normalizePlusApiKey( |
| 12 | + value: unknown, |
| 13 | + settingsPath = "~/.deepcode-plus/settings.json" |
| 14 | +): string | undefined { |
| 15 | + if (value === undefined) return undefined; |
| 16 | + const key = typeof value === "string" ? value.trim() : ""; |
| 17 | + const length = Array.from(key.slice(3)).length; |
| 18 | + if (!key.startsWith("sk-") || (length !== 24 && length !== 26)) { |
| 19 | + throw new Error(`Invalid PLUS_API_KEY in ${settingsPath}: expected "sk-" followed by 24 or 26 characters.`); |
| 20 | + } |
| 21 | + return key; |
| 22 | +} |
| 23 | + |
| 24 | +export function resolvePlusHost(apiKey?: string): string { |
| 25 | + const key = normalizePlusApiKey(apiKey); |
| 26 | + return key && Array.from(key.slice(3)).length === 26 ? DEEPCODE_PLUS_HOST : DEEPCODE_PLUS_LEGACY_HOST; |
| 27 | +} |
| 28 | + |
| 29 | +export function getDeepcodePlusSettingsPath(): string { |
| 30 | + return path.join(os.homedir(), ".deepcode-plus", "settings.json"); |
| 31 | +} |
| 32 | + |
| 33 | +export type SubscriptionPlan = "default" | "on" | "off"; |
| 34 | + |
| 35 | +export type DeepcodePlusSettings = { |
| 36 | + apiKey?: string; |
| 37 | + subscriptionPlan: SubscriptionPlan; |
| 38 | +}; |
| 39 | + |
| 40 | +export function readDeepcodePlusSettings(settingsPath: string = getDeepcodePlusSettingsPath()): DeepcodePlusSettings { |
| 41 | + let settings: { env?: { PLUS_API_KEY?: unknown }; subscriptionPlan?: unknown } | null; |
| 42 | + try { |
| 43 | + settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); |
| 44 | + } catch { |
| 45 | + return { subscriptionPlan: "default" }; |
| 46 | + } |
| 47 | + return { |
| 48 | + apiKey: normalizePlusApiKey(settings?.env?.PLUS_API_KEY, settingsPath), |
| 49 | + subscriptionPlan: |
| 50 | + settings?.subscriptionPlan === "on" || settings?.subscriptionPlan === "off" |
| 51 | + ? settings.subscriptionPlan |
| 52 | + : "default", |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +export function readDeepcodePlusApiKey(settingsPath: string = getDeepcodePlusSettingsPath()): string | undefined { |
| 57 | + return readDeepcodePlusSettings(settingsPath).apiKey; |
| 58 | +} |
| 59 | + |
| 60 | +export const DEEPCODE_PLUS_BASE_URL = `${DEEPCODE_PLUS_LEGACY_HOST}/plugin/openai`; |
| 61 | +export type PlusSubscriptionStatus = "api only" | "full ability" | "unknown"; |
| 62 | +export type OpenAIConnection = { |
| 63 | + apiKey?: string; |
| 64 | + baseURL: string; |
| 65 | + usingPlus: boolean; |
| 66 | + configurationError?: string; |
| 67 | +}; |
| 68 | +export type OpenAIConnectionContext = { |
| 69 | + connection: OpenAIConnection; |
| 70 | + plusApiKey?: string; |
| 71 | +}; |
| 72 | + |
| 73 | +export function resolveOpenAIConnection( |
| 74 | + settings: { apiKey?: string; baseURL: string }, |
| 75 | + plusApiKey?: string, |
| 76 | + subscriptionPlan: DeepcodePlusSettings["subscriptionPlan"] = "default", |
| 77 | + status: PlusSubscriptionStatus = "unknown" |
| 78 | +): OpenAIConnection { |
| 79 | + plusApiKey = normalizePlusApiKey(plusApiKey); |
| 80 | + const baseURL = `${resolvePlusHost(plusApiKey)}/plugin/openai`; |
| 81 | + const regular = { apiKey: settings.apiKey, baseURL: settings.baseURL, usingPlus: false }; |
| 82 | + if (subscriptionPlan === "off") return regular; |
| 83 | + if (subscriptionPlan === "on" && !plusApiKey) { |
| 84 | + return { |
| 85 | + apiKey: undefined, |
| 86 | + baseURL, |
| 87 | + usingPlus: false, |
| 88 | + configurationError: |
| 89 | + "PLUS_API_KEY not found. Please configure env.PLUS_API_KEY in ~/.deepcode-plus/settings.json.", |
| 90 | + }; |
| 91 | + } |
| 92 | + if ( |
| 93 | + subscriptionPlan === "default" && |
| 94 | + (!plusApiKey || status === "api only" || (status === "unknown" && settings.apiKey)) |
| 95 | + ) |
| 96 | + return regular; |
| 97 | + return { apiKey: plusApiKey, baseURL, usingPlus: true }; |
| 98 | +} |
| 99 | + |
| 100 | +type ProbeFetch = ( |
| 101 | + url: string, |
| 102 | + options: { |
| 103 | + method: "GET"; |
| 104 | + headers: Record<string, string>; |
| 105 | + signal: AbortSignal; |
| 106 | + redirect: "manual"; |
| 107 | + } |
| 108 | +) => Promise<{ status: number; body?: { cancel(): Promise<void> } | null }>; |
| 109 | + |
| 110 | +export async function checkPlusSubscription( |
| 111 | + apiKey: string, |
| 112 | + signal?: AbortSignal, |
| 113 | + fetcher: ProbeFetch = undiciFetch, |
| 114 | + timeoutMs = 3000 |
| 115 | +): Promise<PlusSubscriptionStatus> { |
| 116 | + signal?.throwIfAborted(); |
| 117 | + apiKey = normalizePlusApiKey(apiKey)!; |
| 118 | + const baseURL = `${resolvePlusHost(apiKey)}/plugin/openai`; |
| 119 | + const controller = new AbortController(); |
| 120 | + const abort = () => controller.abort(signal?.reason); |
| 121 | + signal?.addEventListener("abort", abort, { once: true }); |
| 122 | + const timer = setTimeout(() => controller.abort(), timeoutMs); |
| 123 | + try { |
| 124 | + const response = await fetcher(`${baseURL}/models`, { |
| 125 | + method: "GET", |
| 126 | + headers: { Authorization: `Bearer ${apiKey}` }, |
| 127 | + signal: controller.signal, |
| 128 | + redirect: "manual", |
| 129 | + }); |
| 130 | + signal?.throwIfAborted(); |
| 131 | + // Only HTTP status matters; release the body without requiring valid JSON. |
| 132 | + await response.body?.cancel().catch(() => {}); |
| 133 | + if (response.status === 200) return "full ability"; |
| 134 | + if (response.status === 401 || response.status === 403) return "api only"; |
| 135 | + return "unknown"; |
| 136 | + } catch { |
| 137 | + signal?.throwIfAborted(); |
| 138 | + return "unknown"; |
| 139 | + } finally { |
| 140 | + clearTimeout(timer); |
| 141 | + signal?.removeEventListener("abort", abort); |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +/** Keep the selected credentials stable for every LLM call within a turn. */ |
| 146 | +export function withPlusSubscription( |
| 147 | + getSettings: () => { apiKey?: string; baseURL: string }, |
| 148 | + buildClient: (context: OpenAIConnectionContext) => OpenAIClientResult, |
| 149 | + dependencies: { |
| 150 | + readSettings?: () => DeepcodePlusSettings; |
| 151 | + checkSubscription?: (apiKey: string, signal?: AbortSignal) => Promise<PlusSubscriptionStatus>; |
| 152 | + } = {} |
| 153 | +): CreateOpenAIClient { |
| 154 | + const readSettings = dependencies.readSettings ?? readDeepcodePlusSettings; |
| 155 | + const checkSubscription = dependencies.checkSubscription ?? checkPlusSubscription; |
| 156 | + let prepared: OpenAIConnectionContext | undefined; |
| 157 | + const resolve = (plus: DeepcodePlusSettings, status: PlusSubscriptionStatus): OpenAIConnectionContext => ({ |
| 158 | + connection: resolveOpenAIConnection(getSettings(), plus.apiKey, plus.subscriptionPlan, status), |
| 159 | + plusApiKey: plus.apiKey, |
| 160 | + }); |
| 161 | + return Object.assign(() => buildClient(prepared ?? resolve(readSettings(), "unknown")), { |
| 162 | + prepare: async (signal?: AbortSignal) => { |
| 163 | + signal?.throwIfAborted(); |
| 164 | + const settings = readSettings(); |
| 165 | + const plus = { ...settings, apiKey: normalizePlusApiKey(settings.apiKey) }; |
| 166 | + const status = |
| 167 | + plus.subscriptionPlan === "default" && plus.apiKey ? await checkSubscription(plus.apiKey, signal) : "unknown"; |
| 168 | + signal?.throwIfAborted(); |
| 169 | + prepared = resolve(plus, status); |
| 170 | + }, |
| 171 | + }); |
| 172 | +} |
0 commit comments