feat(provider): refresh models per AI provider

This commit is contained in:
yiling
2026-11-29 12:48:43 +08:00
parent d315253450
commit 13d06f8ebc
36 changed files with 1497 additions and 4396 deletions
+4 -3
View File
@@ -28,9 +28,10 @@
"@aws-sdk/s3-request-presigner": "3.1121.0",
"@better-auth/mcp": "1.7.12",
"@better-auth/oauth-provider": "1.7.12",
"@earendil-works/chord": "1.5.0",
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
"@earendil-works/chord": "1.7.0",
"@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-coding-agent": "1.7.0",
"@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0",
"@modelcontextprotocol/client": "2.0.0",
"@shumai/db": "workspace:*",
+3 -1
View File
@@ -92,8 +92,10 @@ export async function openSessionCache(sessionId: string) {
throw new Error('Session commit sequence mismatch')
seq = receipt.seq
}
if (result.stored !== commits.length)
if (result.kind === 'refused') {
throw result.refused ?? new Error('Session restoration refused')
}
if (result.stored !== commits.length) throw new Error('Session restoration was incomplete')
}
await save(true)
} catch (error) {
+1 -1
View File
@@ -19,7 +19,7 @@ export const ENV_MAP: Record<string, string> = {
openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY',
'github-copilot': 'COPILOT_GITHUB_TOKEN',
'azure-openai-responses': 'AZURE_OPENAI_API_KEY',
azure: 'AZURE_OPENAI_API_KEY',
deepseek: 'DEEPSEEK_API_KEY',
google: 'GEMINI_API_KEY',
'google-vertex': 'GOOGLE_CLOUD_API_KEY',
@@ -1,54 +0,0 @@
{
"anthropic": {
"models": {
"claude-3-5-sonnet-20241022": {
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 200000,
"output": 8192
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3,
"cache_write": 3.75
}
}
}
},
"openai": {
"models": {
"gpt-4o": {
"id": "gpt-4o",
"name": "GPT-4o",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
},
"gpt-4o-extra-new": {
"id": "gpt-4o-extra-new",
"name": "GPT-4o Extra New",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
}
}
}
}
@@ -1,7 +0,0 @@
{
"data": [
{
"id": "meta/llama-3.1-70b-instruct"
}
]
}
@@ -1,17 +0,0 @@
{
"data": [
{
"id": "meta-llama/llama-3.1-8b-instruct",
"name": "Meta: Llama 3.1 8B Instruct",
"context_length": 131072,
"pricing": {
"prompt": "0.00000005",
"completion": "0.00000008"
},
"top_provider": {
"max_completion_tokens": 8192
},
"supported_parameters": ["tools"]
}
]
}
File diff suppressed because it is too large Load Diff
@@ -1,42 +0,0 @@
import type { ThinkingLevel, ThinkingLevelMap } from '@earendil-works/pi-ai'
export type ModelsDevReasoningOption =
| { type: 'toggle' }
| {
type: 'effort'
values: Array<
'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'default' | null
>
}
| { type: 'budget_tokens'; min?: number; max?: number }
const THINKING_LEVELS: readonly ThinkingLevel[] = [
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
]
/**
* Converts models.dev verified effort values into Pi's selectable thinking levels.
* Values without a Pi equivalent (`default` and JSON `null`) are intentionally
* omitted.
*/
export function getEffortThinkingLevelMap(
options: readonly ModelsDevReasoningOption[],
): ThinkingLevelMap | undefined {
const effortValues = options.flatMap((option) => (option.type === 'effort' ? option.values : []))
if (effortValues.length === 0) return undefined
const supported = new Set(effortValues)
if (!THINKING_LEVELS.some((level) => supported.has(level)) && !supported.has('none'))
return undefined
const map: ThinkingLevelMap = { off: supported.has('none') ? 'none' : null }
for (const level of THINKING_LEVELS) {
map[level] = supported.has(level) ? level : null
}
return map
}
+170
View File
@@ -0,0 +1,170 @@
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
import { InMemoryCredentialStore } from '@earendil-works/pi-ai'
import { getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
import {
providerConfigSchema,
providerModelConfigSchema,
type ProviderConfigSerializable,
type ProviderRefreshUnavailableReason,
type RefreshedProviderModel,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
type RefreshConnection =
| { configured: boolean; unavailableReason: ProviderRefreshUnavailableReason }
| { configured: true; unavailableReason: null; piProviderId: string; apiKey: string }
type SelectionProvider = {
id: string
teamId: string
updatedAt: Date
}
type ModelCandidate = Omit<RefreshedProviderModel, 'selectionToken'>
const PREVIEW_LIFETIME_MS = 15 * 60 * 1000
const REFRESH_TIMEOUT_MS = 30_000
const localSigningKey = randomBytes(32)
const builtinConnections = new Map<string, Set<string>>(
getBuiltinProviders().map((id) => [
id,
new Set(getBuiltinModels(id).map((model) => connectionKey(model.api, model.baseUrl))),
]),
)
function connectionKey(api: string, baseUrl: string | undefined): string {
return JSON.stringify([api, (baseUrl ?? '').replace(/\/+$/, '')])
}
function resolveSavedKey(value: string | undefined): string | undefined {
const key = value?.trim()
if (!key) return undefined
const envValue = process.env[key]?.trim()
if (envValue) return envValue
if (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(key) || Object.hasOwn(process.env, key)) {
return undefined
}
return key
}
export function getRefreshConnection(
name: string,
config: ProviderConfigSerializable,
): RefreshConnection {
const apiKey = resolveSavedKey(config.apiKey)
if (!apiKey) return { configured: false, unavailableReason: 'missing_credentials' }
if (!providerConfigSchema.shape.api.safeParse(config.api).success) {
return { configured: true, unavailableReason: 'unsupported_connection' }
}
const key = connectionKey(config.api, config.baseUrl)
const providerName = name === 'azure-openai-responses' ? 'azure' : name
const namedConnections = builtinConnections.get(providerName)
if (namedConnections?.has(key)) {
return { configured: true, unavailableReason: null, piProviderId: providerName, apiKey }
}
// A renamed provider can still be recognized when its saved connection uniquely identifies it.
if (!namedConnections && config.baseUrl) {
const matches = [...builtinConnections].filter(([, connections]) => connections.has(key))
if (matches.length === 1) {
return { configured: true, unavailableReason: null, piProviderId: matches[0][0], apiKey }
}
}
return { configured: true, unavailableReason: 'unsupported_connection' }
}
export async function discoverProviderModels(
connection: Extract<RefreshConnection, { unavailableReason: null }>,
config: ProviderConfigSerializable,
): Promise<ModelCandidate[]> {
const { piProviderId, apiKey } = connection
const { ModelRuntime } = await import('@earendil-works/pi-coding-agent')
const credentials = new InMemoryCredentialStore()
await credentials.modify(piProviderId, async () => ({ type: 'api_key', key: apiKey }))
const runtime = await ModelRuntime.create({
credentials,
modelsPath: null,
refreshOnCreate: false,
})
const result = await runtime.refresh({
providers: [piProviderId],
allowNetwork: true,
force: true,
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
})
if (result.aborted || result.errors.has(piProviderId)) {
throw new HTTPException(502, { message: 'Could not refresh provider models' })
}
const key = connectionKey(config.api, config.baseUrl)
return runtime.getModels(piProviderId).flatMap((model) => {
if (
typeof model.id !== 'string' ||
!model.id ||
typeof model.baseUrl !== 'string' ||
connectionKey(model.api, model.baseUrl) !== key
) {
return []
}
const modelConfig = providerModelConfigSchema.safeParse({
api: model.api,
reasoning: model.reasoning,
input: model.input,
contextWindow: model.contextWindow,
maxTokens: model.maxTokens,
cost: model.cost,
})
if (!modelConfig.success) return []
const name = typeof model.name === 'string' && model.name ? model.name : model.id
return [{ modelId: model.id, name, config: modelConfig.data }]
})
}
function signSelection(
provider: SelectionProvider,
apiKey: string,
model: ModelCandidate,
expiresAt: number,
): Buffer {
const key = process.env.BETTER_AUTH_SECRET || localSigningKey
return createHmac('sha256', key)
.update(
JSON.stringify([
'shumai-provider-model-refresh:v1',
provider.teamId,
provider.id,
provider.updatedAt,
apiKey,
expiresAt,
model.modelId,
model.name,
providerModelConfigSchema.parse(model.config),
]),
)
.digest()
}
export function signModelPreview(
provider: SelectionProvider,
apiKey: string,
models: ModelCandidate[],
): RefreshedProviderModel[] {
const expiresAt = Date.now() + PREVIEW_LIFETIME_MS
return models.map((model) => ({
...model,
selectionToken: `${expiresAt}.${signSelection(provider, apiKey, model, expiresAt).toString('base64url')}`,
}))
}
export function isCurrentModelSelection(
provider: SelectionProvider,
apiKey: string,
model: RefreshedProviderModel,
): boolean {
const match = /^(\d{13})\.([\w-]{43})$/.exec(model.selectionToken)
if (!match) return false
const expiresAt = Number(match[1])
if (expiresAt <= Date.now()) return false
const signature = Buffer.from(match[2], 'base64url')
return timingSafeEqual(signature, signSelection(provider, apiKey, model, expiresAt))
}
+233 -194
View File
@@ -3,46 +3,49 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { teamService } from '@shumai/core/src/team/team'
import { agentService } from '@shumai/core/src/agent/agent'
import { providerService } from './provider'
import { describe, expect, it, vi } from 'vitest'
import * as generateModelsModule from './generator/generate-models'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { z } from 'zod'
import modelsDevFixture from './fixtures/models-dev.json'
import openRouterFixture from './fixtures/openrouter.json'
import nvidiaFixture from './fixtures/nvidia.json'
import type { RefreshedProviderModel } from '@shumai/dtos'
const originalFetch = globalThis.fetch
const openaiConfig = {
api: 'openai-responses',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'saved-test-key',
} satisfies ProviderConfigSerializable
function setupCatalogFetchMock() {
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
if (url.includes('models.dev')) {
return new Response(JSON.stringify(modelsDevFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
const candidateConfig = {
api: openaiConfig.api,
reasoning: true,
input: ['text'],
contextWindow: 256000,
maxTokens: 16000,
cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
} satisfies ProviderModel['config']
function catalogModel(id: string, options?: { api?: string; baseUrl?: string }) {
return { ...candidateConfig, baseUrl: openaiConfig.baseUrl, id, name: id, ...options }
}
function mockCatalog(models: ReturnType<typeof catalogModel>[]) {
const requests: Request[] = []
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const request = new Request(input, init)
requests.push(request)
if (new URL(request.url).origin !== 'https://pi.dev') {
throw new Error('Unexpected catalog host')
}
if (url.includes('openrouter.ai')) {
return new Response(JSON.stringify(openRouterFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('nvidia')) {
return new Response(JSON.stringify(nvidiaFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('ai-gateway')) {
return new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return originalFetch(input)
return Response.json(models, {
headers: { 'Last-Modified': 'Wed, 01 Jan 2031 00:00:00 GMT' },
})
})
return requests
}
function readyModels(result: Awaited<ReturnType<typeof providerService.refreshModels>>) {
if (result.status !== 'ready') throw new Error('Expected refreshed models')
return result.models
}
type ProviderModel = z.infer<typeof providerModelSchema>
@@ -385,182 +388,218 @@ describe('ProviderService', () => {
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
})
it('should check for updates and correctly segregate new vs existing providers', async () => {
const fetchSpy = setupCatalogFetchMock()
try {
// 1. Check updates with empty team: all discovered providers are new
const emptyTeam = await prisma.team.create({
data: { name: 'Empty Provider Team' },
describe('model refresh', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
it('reports resolved credentials and eligibility separately and preserves legacy Kimi', async () => {
vi.stubEnv('CUSTOM_OPENAI_KEY', 'a-resolved-test-key')
vi.stubEnv('UNSET_ANTHROPIC_KEY', undefined)
const team = await prisma.team.create({ data: { name: 'Providers' } })
const configured = await providerService.create(team.id, 'OpenAI production', {
...openaiConfig,
apiKey: 'CUSTOM_OPENAI_KEY',
})
const initialCheck = await providerService.checkUpdates(emptyTeam.id)
expect(initialCheck.totalNewProviders).toBeGreaterThan(0)
expect(initialCheck.totalNewModels).toBeGreaterThan(0)
expect(initialCheck.providers.every((p) => p.isNewProvider)).toBe(true)
const unconfigured = await providerService.create(team.id, 'anthropic', {
api: 'anthropic-messages',
baseUrl: 'https://api.anthropic.com',
apiKey: 'UNSET_ANTHROPIC_KEY',
})
const legacyConfig = {
api: 'anthropic-messages',
baseUrl: 'https://api.kimi.com/coding',
apiKey: 'literal-kimi-key',
} satisfies ProviderConfigSerializable
const legacy = await providerService.create(team.id, 'kimi-coding', legacyConfig)
const providers = await providerService.listByTeam(team.id)
expect(providers).toHaveLength(3)
expect(providers).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: configured.id,
configured: true,
refreshUnavailableReason: null,
config: { ...openaiConfig, apiKey: 'CUSTOM_OPENAI_KEY' },
}),
expect.objectContaining({
id: unconfigured.id,
configured: false,
refreshUnavailableReason: 'missing_credentials',
}),
expect.objectContaining({
id: legacy.id,
configured: true,
refreshUnavailableReason: 'unsupported_connection',
}),
]),
)
// 2. With default team (which has builtin providers initialized)
const teamWithBuiltins = await teamService.ensureDefaultTeam()
const requests = mockCatalog([])
await expect(providerService.refreshModels(team.id, unconfigured.id)).resolves.toEqual({
status: 'unavailable',
reason: 'missing_credentials',
})
await expect(providerService.refreshModels(team.id, legacy.id)).resolves.toEqual({
status: 'unavailable',
reason: 'unsupported_connection',
})
expect(requests).toHaveLength(0)
expect(await providerService.getById(legacy.id)).toMatchObject({ config: legacyConfig })
})
// 3. Check updates after init: existing providers should have isNewProvider: false
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
expect(existing).toBeDefined()
if (existing) {
expect(existing.isNewProvider).toBe(false)
const dbModels = await providerService.listModelsByProvider(
teamWithBuiltins.id,
(await providerService.listByTeam(teamWithBuiltins.id)).find(
(p) => p.name === existing.name,
)!.id,
)
const dbModelIds = new Set(dbModels.map((m) => m.modelId))
for (const m of existing.models) {
expect(dbModelIds.has(m.modelId)).toBe(false)
it('refreshes only the requested provider and filters existing and incompatible models', async () => {
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
const team = await teamService.ensureDefaultTeam()
const providers = await providerService.listByTeam(team.id)
const openai = providers.find(({ name }) => name === 'openai')!
const existingModels = await providerService.listModelsByProvider(team.id, openai.id)
const requests = mockCatalog([
catalogModel(existingModels[0].modelId),
catalogModel('new-model'),
catalogModel('wrong-api', { api: 'openai-completions' }),
catalogModel('wrong-url', { baseUrl: 'https://other.example/v1' }),
])
const result = await providerService.refreshModels(team.id, openai.id)
expect(result).toMatchObject({
status: 'ready',
models: [{ modelId: 'new-model', name: 'new-model', config: candidateConfig }],
})
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
'/api/models/providers/openai',
])
expect(requests[0].headers.has('Authorization')).toBe(false)
expect(JSON.stringify(result)).not.toContain(openaiConfig.apiKey)
expect(await providerService.listModelsByProvider(team.id, openai.id)).toEqual(existingModels)
expect(await providerService.listByTeam(team.id)).toEqual(providers)
})
it('passes the saved key to OpenRouter and confines the refresh to its trusted endpoint', async () => {
const openRouterKey = 'saved-openrouter-test-key'
vi.stubEnv('SHUMAI_TEST_OPENROUTER_KEY', openRouterKey)
const team = await prisma.team.create({ data: { name: 'OpenRouter' } })
const baseUrl = 'https://openrouter.ai/api/v1'
const api = 'openai-completions' as const
const provider = await providerService.create(team.id, 'openrouter', {
api,
baseUrl: baseUrl + '/',
apiKey: 'SHUMAI_TEST_OPENROUTER_KEY',
})
const modelId = 'org/new-openrouter-model'
const requestedUrls: string[] = []
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const request = new Request(input, init)
const url = new URL(request.url)
requestedUrls.push(url.origin + url.pathname)
if (url.hostname === 'pi.dev') {
expect(request.headers.has('Authorization')).toBe(false)
return Response.json([catalogModel(modelId, { api, baseUrl })], {
headers: { 'Last-Modified': 'Wed, 01 Jan 2031 00:00:00 GMT' },
})
}
}
} finally {
fetchSpy.mockRestore()
}
})
expect(url.href).toBe(baseUrl + '/models/user')
expect(request.headers.get('Authorization')).toBe('Bearer ' + openRouterKey)
return Response.json({ data: [{ id: modelId }] })
})
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
const spy = vi
.spyOn(generateModelsModule, 'generateModels')
.mockRejectedValueOnce(new Error('Failed to load models.dev catalog: 502 Bad Gateway'))
const models = readyModels(await providerService.refreshModels(team.id, provider.id))
expect(models.map(({ modelId }) => modelId)).toEqual([modelId])
expect(requestedUrls).toEqual([
'https://pi.dev/api/models/providers/openrouter',
baseUrl + '/models/user',
])
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
'Failed to load models.dev catalog: 502 Bad Gateway',
)
spy.mockRestore()
})
it('should throw an error when upstream catalog is empty in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
const spy = vi.spyOn(generateModelsModule, 'generateModels').mockResolvedValueOnce({
providers: {},
groupedProviders: {},
sortedProviderIds: [],
const customProvider = await providerService.update(team.id, provider.id, {
...provider.config,
baseUrl: 'https://openrouter-proxy.example/api/v1',
})
await expect(providerService.refreshModels(team.id, customProvider.id)).resolves.toEqual({
status: 'unavailable',
reason: 'unsupported_connection',
})
expect(requestedUrls).toHaveLength(2)
})
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
'Failed to retrieve model catalog from upstream services',
)
spy.mockRestore()
})
it('distinguishes a successful empty preview from an upstream error', async () => {
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
const team = await teamService.ensureDefaultTeam()
const provider = (await providerService.listByTeam(team.id)).find(
({ name }) => name === 'openai',
)!
mockCatalog([])
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
status: 'ready',
models: [],
})
vi.restoreAllMocks()
vi.spyOn(globalThis, 'fetch').mockImplementation(
async () => new Response(null, { status: 400 }),
)
it('should apply sync by adding selected providers and models without modifying existing ones', async () => {
const team = await teamService.ensureDefaultTeam()
// Create an existing provider with 1 model and a custom apiKey
const existingProvider = await providerService.create(
team.id,
'test-existing-provider',
{ api: 'openai-responses', apiKey: 'custom-api-key', baseUrl: 'https://example.com' },
[
{
modelId: 'existing-m1',
name: 'Existing Model 1',
config: {
api: 'openai-responses',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
)
// Apply sync with 1 new provider and 1 new model on the existing provider
const syncResult = await providerService.applySync(team.id, {
providers: [
{
name: 'test-new-synced-provider',
isNewProvider: true,
config: {
api: 'anthropic-messages',
apiKey: 'ENV_SYNC_KEY',
baseUrl: 'https://api.anthropic.com',
},
models: [
{
modelId: 'new-p-m1',
name: 'New Provider Model 1',
config: {
api: 'anthropic-messages',
reasoning: false,
input: ['text'],
contextWindow: 200000,
maxTokens: 8192,
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
},
},
],
},
{
name: 'test-existing-provider',
isNewProvider: false,
config: { api: 'openai-responses', apiKey: 'should-not-override' },
models: [
{
modelId: 'existing-m2',
name: 'Newly Added Model 2',
config: {
api: 'openai-responses',
reasoning: true,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
// Duplicate model that already exists: should be ignored
{
modelId: 'existing-m1',
name: 'Existing Model 1 Overwrite Attempt',
config: {
api: 'openai-responses',
reasoning: false,
input: ['text'],
contextWindow: 999999,
maxTokens: 999999,
cost: { input: 9, output: 9, cacheRead: 9, cacheWrite: 9 },
},
},
],
},
],
await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
status: 502,
})
})
expect(syncResult.addedProviders).toBe(1)
expect(syncResult.addedModels).toBe(2)
it('imports only the selected models once and preserves existing models and settings', async () => {
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
const team = await teamService.ensureDefaultTeam()
const provider = (await providerService.listByTeam(team.id)).find(
({ name }) => name === 'openai',
)!
const original = await providerService.getById(provider.id)
const existing = await providerService.listModelsByProvider(team.id, provider.id)
mockCatalog([catalogModel('new-model'), catalogModel('unselected-model')])
const preview = readyModels(await providerService.refreshModels(team.id, provider.id))
const selection = { models: preview.filter(({ modelId }) => modelId === 'new-model') }
// Verify existing provider config was NOT modified
const reloadedExisting = await providerService.getById(existingProvider.id)
expect((reloadedExisting?.config as { apiKey: string }).apiKey).toBe('custom-api-key')
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
addedModels: 1,
})
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
addedModels: 0,
})
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([
expect.objectContaining({ modelId: 'new-model', config: candidateConfig }),
...existing,
])
expect(await providerService.getById(provider.id)).toEqual(original)
})
// Verify existing model was NOT modified
const existingModels = await providerService.listModelsByProvider(team.id, existingProvider.id)
expect(existingModels).toHaveLength(2)
const m1 = existingModels.find((m) => m.modelId === 'existing-m1')
expect(m1?.name).toBe('Existing Model 1')
expect((m1?.config as { contextWindow: number }).contextWindow).toBe(128000)
it('rejects out-of-team, tampered, and stale selections without adding models', async () => {
const team = await prisma.team.create({ data: { name: 'Refresh Team' } })
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
const provider = await providerService.create(team.id, 'openai', openaiConfig)
const requests = mockCatalog([catalogModel('new-model')])
await expect(providerService.refreshModels(otherTeam.id, provider.id)).rejects.toMatchObject({
status: 404,
})
expect(requests).toHaveLength(0)
// Verify newly added model on existing provider
const m2 = existingModels.find((m) => m.modelId === 'existing-m2')
expect(m2).toBeDefined()
expect(m2?.name).toBe('Newly Added Model 2')
const preview = readyModels(await providerService.refreshModels(team.id, provider.id))
const candidate = preview.find(({ modelId }) => modelId === 'new-model')!
const expectRejected = (models: RefreshedProviderModel[]) =>
expect(
providerService.importModels(team.id, provider.id, { models }),
).rejects.toMatchObject({
status: 409,
})
await expect(
providerService.importModels(otherTeam.id, provider.id, { models: [candidate] }),
).rejects.toMatchObject({ status: 404 })
await expectRejected([{ ...candidate, name: 'Changed metadata' }])
// Verify newly added provider
const providers = await providerService.listByTeam(team.id)
const newProvider = providers.find((p) => p.name === 'test-new-synced-provider')
expect(newProvider).toBeDefined()
expect(newProvider?.isBuiltin).toBe(true)
expect((newProvider?.config as { apiKey: string }).apiKey).toBe('ENV_SYNC_KEY')
const secondProvider = await providerService.create(team.id, 'Other OpenAI', openaiConfig)
await expect(
providerService.importModels(team.id, secondProvider.id, { models: [candidate] }),
).rejects.toMatchObject({ status: 409 })
const newProviderModels = await providerService.listModelsByProvider(team.id, newProvider!.id)
expect(newProviderModels).toHaveLength(1)
expect(newProviderModels[0].modelId).toBe('new-p-m1')
await providerService.update(team.id, provider.id, { ...openaiConfig, apiKey: 'changed-key' })
await expectRejected([candidate])
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([])
expect(await providerService.listModelsByProvider(team.id, secondProvider.id)).toEqual([])
})
})
})
+69 -188
View File
@@ -1,22 +1,21 @@
import { prisma } from '@shumai/db'
import {
CreateModelRequest,
ImportProviderModelsRequest,
ProviderConfigSerializable,
ProviderModelRefreshResponse,
providerModelSchema,
SyncApplyRequest,
SyncApplyResponse,
SyncCheckResponse,
SyncModelItem,
SyncProviderItem,
UpdateModelRequest,
} from '@shumai/dtos'
import {
ENV_MAP,
getBuiltinProvidersMap,
PRIORITY_PROVIDERS,
} from '@shumai/core/src/provider/builtin'
import { generateModels } from '@shumai/core/src/provider/generator/generate-models'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { HTTPException } from 'hono/http-exception'
import { z } from 'zod'
import {
discoverProviderModels,
getRefreshConnection,
isCurrentModelSelection,
signModelPreview,
} from './model-refresh'
type ProviderModel = z.infer<typeof providerModelSchema>
@@ -70,11 +69,23 @@ export class ProviderService {
orderBy: { id: 'desc' },
})
return providers.map((p) => ({
...p,
modelsCount: p._count.models,
_count: undefined,
}))
return providers.map(
({ _count, id, teamId, name, config, isBuiltin, createdAt, updatedAt }) => {
const connection = getRefreshConnection(name, config)
return {
id,
teamId,
name,
config,
isBuiltin,
createdAt,
updatedAt,
modelsCount: _count.models,
configured: connection.configured,
refreshUnavailableReason: connection.unavailableReason,
}
},
)
}
async getById(id: string) {
@@ -124,6 +135,11 @@ export class ProviderService {
name?: string,
) {
return this.prismaClient.$transaction(async (tx) => {
const provider = await tx.provider.update({
where: { id, teamId },
data: { config, ...(name ? { name } : {}) },
})
if (models !== undefined) {
const existingModels = await tx.model.findMany({
where: { providerId: id },
@@ -189,15 +205,7 @@ export class ProviderService {
}
}
// Update provider config and optional name
return tx.provider.update({
where: { id, teamId },
data: {
config,
...(name ? { name } : {}),
},
include: { models: true },
})
return { ...provider, models: await tx.model.findMany({ where: { providerId: id } }) }
})
}
@@ -305,179 +313,52 @@ export class ProviderService {
})
}
async checkUpdates(teamId: string): Promise<SyncCheckResponse> {
const catalog = await generateModels({ strict: true, timeoutMs: 30000 })
if (!catalog || catalog.sortedProviderIds.length === 0) {
throw new Error('Failed to retrieve model catalog from upstream services')
}
const existingProviders = await this.prismaClient.provider.findMany({
where: { teamId },
include: { models: true },
async refreshModels(teamId: string, providerId: string): Promise<ProviderModelRefreshResponse> {
const provider = await this.prismaClient.provider.findUnique({
where: { id: providerId, teamId },
include: { models: { select: { modelId: true } } },
})
if (!provider) throw new HTTPException(404, { message: 'Provider not found' })
const existingProviderMap = new Map<string, (typeof existingProviders)[number]>()
for (const p of existingProviders) {
existingProviderMap.set(p.name, p)
const connection = getRefreshConnection(provider.name, provider.config)
if (connection.unavailableReason) {
return { status: 'unavailable', reason: connection.unavailableReason }
}
const items: SyncProviderItem[] = []
let totalNewProviders = 0
let totalNewModels = 0
for (const providerId of catalog.sortedProviderIds) {
const modelsMap = catalog.providers[providerId]
if (!modelsMap) continue
const modelList = Object.values(modelsMap)
if (modelList.length === 0) continue
const existingProvider = existingProviderMap.get(providerId)
if (!existingProvider) {
const firstModel = modelList[0]
const newModels: SyncModelItem[] = modelList.map((m) => ({
modelId: m.id,
name: m.name || m.id,
config: {
api: m.api as ProviderConfigSerializable['api'],
reasoning: m.reasoning ?? false,
input: (m.input ?? ['text']) as ('text' | 'image')[],
contextWindow: m.contextWindow,
maxTokens: m.maxTokens,
cost: {
input: m.cost?.input ?? 0,
output: m.cost?.output ?? 0,
cacheRead: m.cost?.cacheRead ?? 0,
cacheWrite: m.cost?.cacheWrite ?? 0,
},
},
}))
items.push({
name: providerId,
isNewProvider: true,
config: {
api: firstModel.api as ProviderConfigSerializable['api'],
baseUrl: firstModel.baseUrl,
apiKey: ENV_MAP[providerId] || '',
},
models: newModels,
})
totalNewProviders++
totalNewModels += newModels.length
} else {
const existingModelIds = new Set(existingProvider.models.map((m) => m.modelId))
const newModels: SyncModelItem[] = []
for (const m of modelList) {
if (!existingModelIds.has(m.id)) {
newModels.push({
modelId: m.id,
name: m.name || m.id,
config: {
api: m.api as ProviderConfigSerializable['api'],
reasoning: m.reasoning ?? false,
input: (m.input ?? ['text']) as ('text' | 'image')[],
contextWindow: m.contextWindow,
maxTokens: m.maxTokens,
cost: {
input: m.cost?.input ?? 0,
output: m.cost?.output ?? 0,
cacheRead: m.cost?.cacheRead ?? 0,
cacheWrite: m.cost?.cacheWrite ?? 0,
},
},
})
}
}
if (newModels.length > 0) {
items.push({
name: providerId,
isNewProvider: false,
config: existingProvider.config as ProviderConfigSerializable,
models: newModels,
})
totalNewModels += newModels.length
}
}
}
items.sort((a, b) => {
const indexA = PRIORITY_PROVIDERS.indexOf(a.name)
const indexB = PRIORITY_PROVIDERS.indexOf(b.name)
if (indexA !== -1 && indexB !== -1) return indexA - indexB
if (indexA !== -1) return -1
if (indexB !== -1) return 1
return a.name.localeCompare(b.name)
})
const models = await discoverProviderModels(connection, provider.config)
const existingIds = new Set(provider.models.map(({ modelId }) => modelId))
return {
providers: items,
totalNewProviders,
totalNewModels,
status: 'ready',
models: signModelPreview(
provider,
connection.apiKey,
models.filter(({ modelId }) => !existingIds.has(modelId)),
),
}
}
async applySync(teamId: string, payload: SyncApplyRequest): Promise<SyncApplyResponse> {
let addedProviders = 0
let addedModels = 0
async importModels(teamId: string, providerId: string, { models }: ImportProviderModelsRequest) {
return this.prismaClient.$transaction(async (tx) => {
// Keep the connection stable until the validated selection has been inserted.
const [locked] = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM providers WHERE id = ${providerId} AND team_id = ${teamId} FOR NO KEY UPDATE
`
if (!locked) throw new HTTPException(404, { message: 'Provider not found' })
const provider = await tx.provider.findUniqueOrThrow({ where: { id: providerId } })
await this.prismaClient.$transaction(async (tx) => {
for (const providerItem of payload.providers) {
let providerId: string
if (providerItem.isNewProvider) {
const existing = await tx.provider.findFirst({
where: { teamId, name: providerItem.name },
})
if (!existing) {
const created = await tx.provider.create({
data: {
teamId,
name: providerItem.name,
isBuiltin: true,
config: providerItem.config,
},
})
providerId = created.id
addedProviders++
} else {
providerId = existing.id
}
} else {
const existing = await tx.provider.findFirst({
where: { teamId, name: providerItem.name },
})
if (!existing) continue
providerId = existing.id
}
for (const modelItem of providerItem.models) {
const existingModel = await tx.model.findFirst({
where: {
providerId,
modelId: modelItem.modelId,
},
})
if (!existingModel) {
await tx.model.create({
data: {
providerId,
modelId: modelItem.modelId,
name: modelItem.name || modelItem.modelId,
config: modelItem.config,
},
})
addedModels++
}
}
const connection = getRefreshConnection(provider.name, provider.config)
if (
connection.unavailableReason ||
!models.every((model) => isCurrentModelSelection(provider, connection.apiKey, model))
) {
throw new HTTPException(409, { message: 'Refresh the model list before importing' })
}
})
return { addedProviders, addedModels }
const { count } = await tx.model.createMany({
data: models.map(({ modelId, name, config }) => ({ providerId, modelId, name, config })),
skipDuplicates: true,
})
return { addedModels: count }
})
}
}