| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218 |
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
- import { join } from 'node:path';
- import { getCodexDataDir } from './codexHome';
- import { DEFAULT_API_KEY_ENV, type CodexProviderSpec, type CodexRuntime, type JsonValue } from './codexRuntime';
- import type { AppliedProviderInfo, ApplyProviderInput } from './types';
- /**
- * 把后端「模型管理」里的一条记录翻译成 Codex 的 model provider。
- * 全程不做任何 Codex/OpenAI 账号登录:靠 wire_api="responses" + requires_openai_auth=false + env_key。
- * apiKey 只存在于内存与子进程环境变量,落盘的 AppliedProvider 不含任何密钥。
- */
- export const PROVIDER_ID = 'zsjz';
- export type AppliedProvider = AppliedProviderInfo;
- export interface ProviderCompatibility {
- compatible: boolean;
- /** null 表示网络不可达,无法判定 */
- status: number | null;
- detail: string;
- }
- const EXTRA_ALLOWLIST: readonly string[] = [
- 'request_max_retries',
- 'stream_max_retries',
- 'stream_idle_timeout_ms',
- 'query_params',
- ];
- function providerFile(): string {
- return join(getCodexDataDir(), 'provider.json');
- }
- /** Codex 要求 base_url 是 API 根(形如 https://api.openai.com/v1),它自己再拼 /responses */
- export function normalizeBaseUrl(raw: string | null | undefined): string | null {
- const value = (raw ?? '').trim().replace(/\/+$/u, '');
- return value || null;
- }
- /** 给页面的非阻断提示;返回 null 表示没问题 */
- export function baseUrlHint(baseUrl: string | null): string | null {
- if (!baseUrl) return '未配置 base_url';
- if (!/^https?:\/\//u.test(baseUrl)) return 'base_url 必须以 http:// 或 https:// 开头';
- if (!/\/v\d+$/u.test(baseUrl)) {
- return 'base_url 通常应写到版本段(如 .../v1),否则 Codex 拼出的 /responses 可能 404';
- }
- return null;
- }
- function parseJsonRecord(raw: unknown): Record<string, unknown> | null {
- if (!raw) return null;
- if (typeof raw === 'object' && !Array.isArray(raw)) return raw as Record<string, unknown>;
- if (typeof raw !== 'string') return null;
- try {
- const parsed = JSON.parse(raw) as unknown;
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
- ? (parsed as Record<string, unknown>)
- : null;
- } catch {
- return null;
- }
- }
- function readStringMap(raw: unknown): Record<string, string> | null {
- const record = parseJsonRecord(raw);
- if (!record) return null;
- const result: Record<string, string> = {};
- for (const [key, value] of Object.entries(record)) {
- if (typeof value === 'string' && value) result[key] = value;
- }
- return Object.keys(result).length ? result : null;
- }
- /** Codex 内置 ollama/lmstudio 走 OpenAI 兼容根(.../v1),而库里常只存到 host:port */
- function normalizeOssBaseUrl(raw: string | null | undefined): string | null {
- const base = normalizeBaseUrl(raw);
- if (!base) return null;
- return /\/v\d+$/u.test(base) ? base : `${base}/v1`;
- }
- /** OLLAMA 用 Codex 内置 provider(Responses API,默认端口 11434),不需要 api key */
- function resolveBuiltinProvider(input: ApplyProviderInput): string | null {
- if (input.builtinProvider) return input.builtinProvider;
- const type = `${input.providerType ?? ''}`.trim().toUpperCase();
- if (type === 'OLLAMA') return 'ollama';
- if (type === 'LMSTUDIO') return 'lmstudio';
- return null;
- }
- export function toProviderSpec(input: ApplyProviderInput): CodexProviderSpec {
- const model = `${input.modelId ?? ''}`.trim();
- if (!model) throw new Error('缺少 modelId');
- const builtinProvider = resolveBuiltinProvider(input);
- if (builtinProvider) {
- return {
- id: null,
- builtinProvider,
- model,
- name: input.name ?? `${builtinProvider} 本地模型`,
- // 内置 provider 的默认地址是 localhost,必须把库里的真实地址带上,否则连不到远端 Ollama
- baseUrl: normalizeOssBaseUrl(input.baseUrl),
- };
- }
- const baseUrl = normalizeBaseUrl(input.baseUrl);
- if (!baseUrl) throw new Error('缺少 baseUrl');
- const config = parseJsonRecord(input.config);
- const extra: Record<string, JsonValue> = {};
- for (const [key, value] of Object.entries(config ?? {})) {
- if (EXTRA_ALLOWLIST.includes(key)) extra[key] = value as JsonValue;
- }
- return {
- id: PROVIDER_ID,
- name: input.name ?? model,
- baseUrl,
- model,
- apiKey: input.apiKey ?? null,
- envKey: DEFAULT_API_KEY_ENV,
- httpHeaders: readStringMap(input.headersJson),
- extra: Object.keys(extra).length ? extra : null,
- };
- }
- /** config 里被丢弃的非白名单键,用于页面提示 */
- export function describeDroppedKeys(input: ApplyProviderInput): string[] {
- const config = parseJsonRecord(input.config);
- return Object.keys(config ?? {}).filter((key) => !EXTRA_ALLOWLIST.includes(key));
- }
- /**
- * 探测端点是否实现了 Responses API。
- * 404/405 = 未实现(Codex 0.155 起已下线 wire_api="chat",chat-only 端点用不了);
- * 401/403/400/422/2xx = 路由存在,判为兼容。
- */
- export async function probeResponsesEndpoint(
- baseUrl: string,
- apiKey?: string | null,
- ): Promise<ProviderCompatibility> {
- const url = `${baseUrl.replace(/\/+$/u, '')}/responses`;
- let status: number;
- try {
- const response = await fetch(url, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
- },
- body: JSON.stringify({ model: 'probe', input: 'probe' }),
- signal: AbortSignal.timeout(8_000),
- });
- status = response.status;
- } catch (error) {
- return {
- compatible: false,
- status: null,
- detail: `端点不可达:${error instanceof Error ? error.message : String(error)}`,
- };
- }
- if (status === 404 || status === 405) {
- return {
- compatible: false,
- status,
- detail: `该端点未实现 Responses API(HTTP ${status})。Codex 0.155 起已下线 wire_api="chat",只提供 /chat/completions 的服务需要额外网关转换。`,
- };
- }
- return { compatible: true, status, detail: `端点已实现 Responses API(HTTP ${status})` };
- }
- export async function readAppliedProvider(): Promise<AppliedProvider | null> {
- try {
- const raw = JSON.parse(await readFile(providerFile(), 'utf8')) as Partial<AppliedProvider>;
- return raw.model ? (raw as AppliedProvider) : null;
- } catch {
- return null;
- }
- }
- async function writeAppliedProvider(value: AppliedProvider | null): Promise<void> {
- await mkdir(getCodexDataDir(), { recursive: true });
- await writeFile(providerFile(), JSON.stringify(value ?? {}, null, 2), 'utf8');
- }
- /** 应用一条模型配置:先探端点,再重启子进程(api_key 走 env,换 key 必须重启) */
- export async function applyProvider(
- runtime: CodexRuntime,
- input: ApplyProviderInput & { modelRecordId?: string | number | null },
- ): Promise<AppliedProvider> {
- const spec = toProviderSpec(input);
- // 只要显式配了地址就探(含远端 Ollama):应用成功后才发现连不上,比这里直接报错更难排查。
- // 内置 provider 没配地址时不探(默认 localhost,可能压根没起本地服务)。
- if (spec.baseUrl) {
- const probe = await probeResponsesEndpoint(spec.baseUrl, spec.apiKey);
- if (!probe.compatible) throw new Error(probe.detail);
- }
- await runtime.applyProvider(spec);
- const applied: AppliedProvider = {
- model: spec.model,
- modelRecordId: input.modelRecordId === undefined || input.modelRecordId === null
- ? null
- : String(input.modelRecordId),
- baseUrl: spec.baseUrl ?? null,
- providerId: spec.id,
- builtinProvider: spec.builtinProvider ?? null,
- name: spec.name ?? null,
- appliedAt: new Date().toISOString(),
- };
- await writeAppliedProvider(applied);
- return applied;
- }
- export async function clearProvider(runtime: CodexRuntime): Promise<void> {
- await runtime.applyProvider(null);
- await writeAppliedProvider(null);
- }
|