mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-25 18:16:32 +00:00
* feat(ai): add OpenCode Go provider with API-key auto-config Add OpenCode Go as a first-class AI provider preset for Catty: - Pre-fill the Console endpoint (https://opencode.ai/inference/go/openai/v1) and a curated model list, with live discovery from /models. - After the user pastes an API key and saves, select a sensible default model and activate the provider when no other provider is active. - Parse nested limit.context values from model list payloads (OpenCode Go reports context windows this way). - Point users at the Console API-key page from the provider form and make the settings search find the entry with "opencode". The existing x-opencode-session header already covers chat routing for opencode.ai hosts. * fix(ai): fix OpenCode Go protocol choices OpenCode Go exposes exactly one wire protocol and request format, so the provider form must not offer Anthropic/Google styles or a Responses toggle. Hide both controls for fixed-protocol presets, force the saved config back to OpenAI Chat Completions, and ignore stale overrides at request time. * fix(ai): route OpenCode Go models to their native protocol OpenCode Go's catalog is not uniformly Chat Completions: 20 models are native chat, 5 are Responses, 6 are Anthropic Messages, and 1 is Google GenerateContent. The Console gateway translates between them, but forcing Chat Completions loses each model's native reasoning and tool handling. Keep the protocol controls hidden, then pick the wire family from the selected model: - responses -> OpenAI Responses - messages -> Anthropic Messages (/anthropic/v1 prefix) - google -> Google GenerateContent (/google/v1beta prefix) - default -> OpenAI Chat Completions Model discovery stays on the OpenAI prefix, and a read-only Base URL makes it clear that the endpoint paths are fixed by the provider. * fix(ai): send OpenCode session and client headers OpenCode Go needs `x-opencode-session` on every model call for routing and prompt-cache affinity. Catty already forwards the chat session id; this also covers plugin model invocations, which previously had no session header. OpenCode also asks clients to identify themselves instead of presenting a generic SDK user agent. Send `Netcatty-AI/1.0` for opencode.ai hosts while keeping user-configured headers as the override. * fix(ai): hide custom headers for fixed-protocol providers OpenCode Go has one hosted endpoint and no proxy or self-signed setup to configure, so the custom-header editor only adds noise. Hide it for fixed-protocol presets and leave any previously stored headers untouched instead of overwriting them with the hidden rows. * fix(ai): use the official OpenCode mark for the provider icon The previous asset was a monochrome silhouette that was left-aligned and touched the badge edges, so it read as a generic terminal glyph. Replace it with the official OpenCode mark (white frame, gray block, dark background) and render it full-color instead of applying the monochrome invert filter. * fix(ai): keep the OpenCode icon square at small sizes The 16px composer badge used a 6px radius, so the full-color mark read as a black circle. Give full-color icons size-aware corners (3/4/6px) and move the asset to a new filename so a stale 300px SVG from an earlier build cannot be reused. * fix(ai): preserve disabled state when editing an existing OpenCode Go provider * fix(ai): recognize Google SSE streaming requests in bridge fetch --------- Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
171 lines
5.5 KiB
TypeScript
171 lines
5.5 KiB
TypeScript
import { decryptProviderHeaders } from './providerHeaderCredentials';
|
|
import { decryptField } from '../persistence/secureFieldAdapter';
|
|
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from './modelDiscoveryHeaders';
|
|
import { normalizeOllamaSdkBaseURL } from './ollamaCompatBaseUrl';
|
|
import { buildProviderProbeUrl } from './providerConnectionProbe';
|
|
import { readDiscoveredModelContextWindow } from './discoveredModelMetadata';
|
|
import { PROVIDER_PRESETS, resolveProviderDiscoveryStyle, type ProviderConfig } from './types';
|
|
import {
|
|
buildProviderSeedModels,
|
|
mergeComposerModels,
|
|
type ComposerPickerModel,
|
|
} from './composerPicker';
|
|
|
|
export interface ProviderModelCatalog {
|
|
models: ComposerPickerModel[];
|
|
fetched: boolean;
|
|
error?: string;
|
|
}
|
|
|
|
type FetchBridge = {
|
|
aiFetch?: (
|
|
url: string,
|
|
method?: string,
|
|
headers?: Record<string, string>,
|
|
body?: string,
|
|
providerId?: string,
|
|
skipHostCheck?: boolean,
|
|
followRedirects?: boolean,
|
|
skipTLSVerify?: boolean,
|
|
) => Promise<{ ok: boolean; status?: number; data: string; error?: string }>;
|
|
aiAllowlistAddHost?: (baseURL: string) => Promise<{ ok: boolean }>;
|
|
};
|
|
|
|
const catalogCache = new Map<string, { models: ComposerPickerModel[]; expiresAt: number }>();
|
|
const CATALOG_TTL_MS = 5 * 60 * 1000;
|
|
|
|
/** Length + FNV-1a of the stored secret so a key rotation busts the catalog cache. */
|
|
function credentialFingerprint(value: string | undefined): string {
|
|
const raw = String(value || '');
|
|
if (!raw) return '0';
|
|
let hash = 2166136261;
|
|
for (let i = 0; i < raw.length; i += 1) {
|
|
hash ^= raw.charCodeAt(i);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
return `${raw.length}:${(hash >>> 0).toString(16)}`;
|
|
}
|
|
|
|
export function readCachedProviderModelCatalog(
|
|
provider: ProviderConfig,
|
|
): ComposerPickerModel[] | null {
|
|
const cached = catalogCache.get(providerModelCacheKey(provider));
|
|
if (!cached || cached.expiresAt <= Date.now()) return null;
|
|
return cached.models;
|
|
}
|
|
|
|
export function providerModelCacheKey(provider: ProviderConfig): string {
|
|
return [
|
|
provider.id,
|
|
provider.providerId,
|
|
provider.style ?? '',
|
|
provider.baseURL ?? '',
|
|
provider.skipTLSVerify ? '1' : '0',
|
|
credentialFingerprint(provider.apiKey),
|
|
credentialFingerprint(JSON.stringify(provider.customHeaders)),
|
|
].join('|');
|
|
}
|
|
|
|
export function resolveProviderDiscoveryBaseURL(provider: ProviderConfig): string {
|
|
const raw = provider.baseURL || PROVIDER_PRESETS[provider.providerId]?.defaultBaseURL || '';
|
|
if (!raw) return '';
|
|
return provider.providerId === 'ollama' ? normalizeOllamaSdkBaseURL(raw) : raw;
|
|
}
|
|
|
|
export function seedProviderModelCatalog(provider: ProviderConfig): ProviderModelCatalog {
|
|
return {
|
|
models: buildProviderSeedModels(provider),
|
|
fetched: false,
|
|
};
|
|
}
|
|
|
|
export function clearProviderModelCatalogCache(): void {
|
|
catalogCache.clear();
|
|
}
|
|
|
|
function parseDiscoveredModels(parsed: unknown): ComposerPickerModel[] {
|
|
const record = parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {};
|
|
const rawModels = Array.isArray(record.data)
|
|
? record.data
|
|
: Array.isArray(record.models)
|
|
? record.models
|
|
: [];
|
|
return rawModels
|
|
.map((raw): ComposerPickerModel | null => {
|
|
if (!raw || typeof raw !== 'object') return null;
|
|
const model = raw as Record<string, unknown>;
|
|
if (typeof model.id !== 'string' || !model.id) return null;
|
|
const contextWindow = readDiscoveredModelContextWindow(model);
|
|
return {
|
|
id: model.id,
|
|
name: typeof model.name === 'string' && model.name ? model.name : model.id,
|
|
...(contextWindow != null ? { contextWindow } : {}),
|
|
};
|
|
})
|
|
.filter((model): model is ComposerPickerModel => model != null)
|
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
}
|
|
|
|
export async function fetchProviderModelCatalog(
|
|
provider: ProviderConfig,
|
|
bridge: FetchBridge | undefined,
|
|
): Promise<ProviderModelCatalog> {
|
|
const seed = seedProviderModelCatalog(provider);
|
|
const cacheKey = providerModelCacheKey(provider);
|
|
const cached = catalogCache.get(cacheKey);
|
|
if (cached && cached.expiresAt > Date.now()) {
|
|
return {
|
|
models: mergeComposerModels(seed.models, cached.models),
|
|
fetched: true,
|
|
};
|
|
}
|
|
|
|
const style = resolveProviderDiscoveryStyle(provider);
|
|
const endpoint = resolveModelsDiscoveryEndpoint(style, undefined);
|
|
const baseURL = resolveProviderDiscoveryBaseURL(provider);
|
|
if (!endpoint || !baseURL || !bridge?.aiFetch) {
|
|
return seed;
|
|
}
|
|
|
|
try {
|
|
const apiKey = await decryptField(provider.apiKey);
|
|
if (provider.providerId !== 'ollama' && !apiKey) {
|
|
return seed;
|
|
}
|
|
if (bridge.aiAllowlistAddHost) {
|
|
await bridge.aiAllowlistAddHost(baseURL);
|
|
}
|
|
const url = buildProviderProbeUrl(baseURL, endpoint);
|
|
const headers = buildModelDiscoveryHeaders(
|
|
style,
|
|
apiKey,
|
|
await decryptProviderHeaders(provider.customHeaders),
|
|
baseURL,
|
|
);
|
|
const result = await bridge.aiFetch(
|
|
url,
|
|
'GET',
|
|
headers,
|
|
undefined,
|
|
undefined,
|
|
undefined,
|
|
undefined,
|
|
provider.skipTLSVerify,
|
|
);
|
|
if (!result.ok) {
|
|
return { ...seed, error: result.error || 'Failed to fetch models' };
|
|
}
|
|
const fetched = parseDiscoveredModels(JSON.parse(result.data) as unknown);
|
|
catalogCache.set(cacheKey, { models: fetched, expiresAt: Date.now() + CATALOG_TTL_MS });
|
|
return {
|
|
models: mergeComposerModels(seed.models, fetched),
|
|
fetched: true,
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
...seed,
|
|
error: error instanceof Error ? error.message : 'Failed to fetch models',
|
|
};
|
|
}
|
|
}
|