Files
Netcatty/infrastructure/ai/cattyProviderModels.test.ts
T
AlexPlumandbincxz 2ca3ae0e28 feat(ai): add OpenCode Go provider (#4253)
* 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>
2026-11-23 18:42:08 +08:00

175 lines
5.2 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {
clearProviderModelCatalogCache,
fetchProviderModelCatalog,
providerModelCacheKey,
resolveProviderDiscoveryBaseURL,
seedProviderModelCatalog,
} from './cattyProviderModels';
import type { ProviderConfig } from './types';
const provider: ProviderConfig = {
id: 'p1',
providerId: 'deepseek',
name: 'DeepSeek',
defaultModel: 'deepseek-chat',
baseURL: 'https://api.deepseek.com/v1',
apiKey: 'test-key',
enabled: true,
};
test('resolveProviderDiscoveryBaseURL falls back to the built-in preset host', () => {
assert.equal(
resolveProviderDiscoveryBaseURL({
id: 'openai-1',
providerId: 'openai',
name: 'OpenAI',
enabled: true,
}),
'https://api.openai.com/v1',
);
assert.equal(
resolveProviderDiscoveryBaseURL({
id: 'ollama-1',
providerId: 'ollama',
name: 'Ollama',
enabled: true,
baseURL: 'https://ollama.com',
}),
'https://ollama.com/v1',
);
});
test('fetchProviderModelCatalog discovers models when baseURL is omitted', async () => {
clearProviderModelCatalogCache();
const requested: string[] = [];
const catalog = await fetchProviderModelCatalog(
{
id: 'openai-legacy',
providerId: 'openai',
name: 'OpenAI',
defaultModel: 'gpt-4o',
apiKey: 'sk-test',
enabled: true,
},
{
aiFetch: async (url) => {
requested.push(url);
return {
ok: true,
data: JSON.stringify({ data: [{ id: 'gpt-4o' }, { id: 'gpt-5.5', context_length: 200000 }] }),
};
},
},
);
assert.deepEqual(requested, ['https://api.openai.com/v1/models']);
assert.equal(catalog.fetched, true);
assert.ok(catalog.models.some((model) => model.id === 'gpt-5.5'));
assert.equal(catalog.models.find((model) => model.id === 'gpt-5.5')?.contextWindow, 200000);
});
test('providerModelCacheKey changes when the stored API key changes', () => {
const base = { ...provider };
const before = providerModelCacheKey({ ...base, apiKey: 'enc-old' });
const after = providerModelCacheKey({ ...base, apiKey: 'enc-new' });
const empty = providerModelCacheKey({ ...base, apiKey: undefined });
assert.notEqual(before, after);
assert.notEqual(before, empty);
});
test('seedProviderModelCatalog includes the default and curated models', () => {
const seed = seedProviderModelCatalog(provider);
assert.equal(seed.fetched, false);
assert.ok(seed.models.some((model) => model.id === 'deepseek-chat'));
assert.ok(seed.models.some((model) => model.id === 'deepseek-v4-pro'));
});
test('fetchProviderModelCatalog merges discovered models and caches them', async () => {
clearProviderModelCatalogCache();
const catalog = await fetchProviderModelCatalog(provider, {
aiFetch: async () => ({
ok: true,
data: JSON.stringify({ data: [{ id: 'deepseek-reasoner', name: 'Reasoner' }] }),
}),
});
assert.equal(catalog.fetched, true);
assert.ok(catalog.models.some((model) => model.id === 'deepseek-reasoner'));
assert.ok(catalog.models.some((model) => model.id === 'deepseek-chat'));
const cached = await fetchProviderModelCatalog(provider, {
aiFetch: async () => {
throw new Error('should not refetch');
},
});
assert.equal(cached.fetched, true);
assert.ok(cached.models.some((model) => model.id === 'deepseek-reasoner'));
});
test('fetchProviderModelCatalog discovers OpenCode Go models and nested context limits', async () => {
clearProviderModelCatalogCache();
const requested: string[] = [];
const catalog = await fetchProviderModelCatalog(
{
id: 'opencode-go-1',
providerId: 'opencode-go',
name: 'OpenCode Go',
apiKey: 'oc_sk_test',
enabled: true,
},
{
aiFetch: async (url) => {
requested.push(url);
return {
ok: true,
data: JSON.stringify({
object: 'list',
data: [
{
id: 'deepseek-v4.1-flash',
name: 'DeepSeek V4.1 Flash 1017',
limit: { context: 1000000, output: 384000 },
},
],
}),
};
},
},
);
assert.deepEqual(requested, ['https://opencode.ai/inference/go/openai/v1/models']);
assert.equal(catalog.fetched, true);
assert.equal(
catalog.models.find((model) => model.id === 'deepseek-v4.1-flash')?.contextWindow,
1000000,
);
});
test('fetchProviderModelCatalog appends /v1 when listing Ollama Cloud from a bare origin', async () => {
clearProviderModelCatalogCache();
const requested: string[] = [];
const catalog = await fetchProviderModelCatalog(
{
id: 'ollama-cloud',
providerId: 'ollama',
name: 'Ollama',
defaultModel: 'deepseek-v4-flash:0731',
baseURL: 'https://ollama.com',
apiKey: 'cloud-key',
enabled: true,
},
{
aiFetch: async (url) => {
requested.push(url);
return {
ok: true,
data: JSON.stringify({ data: [{ id: 'deepseek-v4-flash:0731' }] }),
};
},
},
);
assert.deepEqual(requested, ['https://ollama.com/v1/models']);
assert.equal(catalog.fetched, true);
assert.ok(catalog.models.some((model) => model.id === 'deepseek-v4-flash:0731'));
});