mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(provider): add provider and model sync feature with vendored generator (#378)
* feat(provider): vendor and adapt pi model generator - Vendor generate-models.ts, model-data.ts, and models-dev-reasoning-options.ts from @earendil-works/pi tag v0.82.1 - Adapt imports to use @earendil-works/pi-ai and expose generateModels programmatic function - Add compare.test.ts to verify vendored generator against original built-in catalog - Add packages/core/src/provider/generator to eslint ignores * feat(provider): add provider and model sync api and ui * feat(webui): add checkbox for existing providers and clean dialog description * feat(webui): add expand all and collapse all to sync providers dialog * refactor(provider): remove compare.test.ts and cli overhead from generate-models * fix(provider): add 30s timeout and strict error handling to sync catalog fetching * fix(e2e): eliminate drag-and-drop race condition on webkit Allow requestAnimationFrame collision updates to settle in dragCard helper before releasing pointer, and scope fileCard locator via data-testid to avoid matching sidebar tree items.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
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
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
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 } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import * as generateModelsModule from './generator/generate-models'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import { z } from 'zod'
|
||||
@@ -346,4 +348,181 @@ describe('ProviderService', () => {
|
||||
expect((modelsAfterUpdate[0].config as { api: string }).api).toBe('anthropic-messages')
|
||||
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
|
||||
})
|
||||
|
||||
it(
|
||||
'should check for updates and correctly segregate new vs existing providers',
|
||||
{ timeout: 30000 },
|
||||
async () => {
|
||||
// 1. Check updates with empty team: all discovered providers are new
|
||||
const emptyTeam = await prisma.team.create({
|
||||
data: { name: 'Empty Provider Team' },
|
||||
})
|
||||
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)
|
||||
|
||||
// 2. With default team (which has builtin providers initialized)
|
||||
const teamWithBuiltins = await teamService.ensureDefaultTeam()
|
||||
|
||||
// 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)
|
||||
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('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'))
|
||||
|
||||
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: [],
|
||||
})
|
||||
|
||||
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
|
||||
'Failed to retrieve model catalog from upstream services',
|
||||
)
|
||||
spy.mockRestore()
|
||||
})
|
||||
|
||||
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 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(syncResult.addedProviders).toBe(1)
|
||||
expect(syncResult.addedModels).toBe(2)
|
||||
|
||||
// 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')
|
||||
|
||||
// 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)
|
||||
|
||||
// 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')
|
||||
|
||||
// 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 newProviderModels = await providerService.listModelsByProvider(team.id, newProvider!.id)
|
||||
expect(newProviderModels).toHaveLength(1)
|
||||
expect(newProviderModels[0].modelId).toBe('new-p-m1')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,9 +3,19 @@ import {
|
||||
CreateModelRequest,
|
||||
ProviderConfigSerializable,
|
||||
providerModelSchema,
|
||||
SyncApplyRequest,
|
||||
SyncApplyResponse,
|
||||
SyncCheckResponse,
|
||||
SyncModelItem,
|
||||
SyncProviderItem,
|
||||
UpdateModelRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import {
|
||||
ENV_MAP,
|
||||
getBuiltinProvidersMap,
|
||||
PRIORITY_PROVIDERS,
|
||||
} from '@shumai/core/src/provider/builtin'
|
||||
import { generateModels } from '@shumai/core/src/provider/generator/generate-models'
|
||||
import { z } from 'zod'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
@@ -294,6 +304,181 @@ export class ProviderService {
|
||||
where: { id, teamId },
|
||||
})
|
||||
}
|
||||
|
||||
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 },
|
||||
})
|
||||
|
||||
const existingProviderMap = new Map<string, (typeof existingProviders)[number]>()
|
||||
for (const p of existingProviders) {
|
||||
existingProviderMap.set(p.name, p)
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
return {
|
||||
providers: items,
|
||||
totalNewProviders,
|
||||
totalNewModels,
|
||||
}
|
||||
}
|
||||
|
||||
async applySync(teamId: string, payload: SyncApplyRequest): Promise<SyncApplyResponse> {
|
||||
let addedProviders = 0
|
||||
let addedModels = 0
|
||||
|
||||
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++
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return { addedProviders, addedModels }
|
||||
}
|
||||
}
|
||||
|
||||
export const providerService = new ProviderService()
|
||||
|
||||
Reference in New Issue
Block a user