diff --git a/docs/M2-OFFICIAL-REGISTRY-PLAN.md b/docs/M2-OFFICIAL-REGISTRY-PLAN.md index de54401b..c2366d94 100644 --- a/docs/M2-OFFICIAL-REGISTRY-PLAN.md +++ b/docs/M2-OFFICIAL-REGISTRY-PLAN.md @@ -3,8 +3,8 @@ 2026-11-07;基线 `3278c1851a650e320352698bd0ff4fa0ce8cac11`,工作树干净、既有 GitAtlas 分支逐 SHA 一致。承接 I10 用量和 I13 完整账本,推进 I15 与 I28 的注册表来源部分;I09/I11/I12/I14 请求版本/缓存状态与 I27 CI 仍独立验收。 1. [complete] 17份官方来源/813289字节及双方SHA固定于[来源清单](../tests/fixtures/official-model-registry/SOURCE.json),完整捕获留自有QA根。6旧源码/4配置和目录基线显示nextPageToken与原字段遗漏;精确协议/型号/版本/条件已核对。首次夹具脚本把M1清单路径误当basename,原失败保持,第二独立脚本按实际路径验封通过。官方Anthropic示例使用2026-10-21,与当前固定2023-06-01的有效性不能混称已验证,I14另核对实际请求版本。 -2. [in_progress] 建立可版本化、可校验与可更新的纯注册表;保留精确 ID、逐字段来源/冲突/有效范围、容量/推理/工具/媒体/缓存/结构化/弃用事实。替代重复的精确 Claude 表,不从型号子串或显示品牌猜能力;手选透传不变。 -3. [pending] 上游目录保留完整原始声明、正确分页并在选择/刷新时保持原凭据、用户字段与旧 Run;新连接取得官方后备元数据。现有模型中心/参数面板展示来源与冲突,提供显式兼容覆盖并持久保存。 +2. [complete] 纯注册表26协议记录/13精确ID及17逐字段来源,校验供应商来源/合法JSON/能力范围/重复,记录容量/推理/工具/媒体/缓存/结构化/弃用和条件;兼容覆盖与旧声明来源不猜,手选透传不变。首source-1为67/68,路由来源误映射已修;source-2为71/71、最后用户声明来源补强source-3为31/31,types-1/2/3与来源字节CLI通过。截断诊断只说明实际发送字段,DeepSeek可选/显式输出与注册表source-4为34/34;核心阶段限定提交。 +3. [in_progress] 目录完整脱敏item及原表示SHA、pageToken/after_id分页、空中间页和冲突已接入;新规格快照冻结、刷新保留用户字段。推理/覆盖编辑不改变既有凭据身份时保留原密文绑定,不解密重存;更换地址/型号/鉴权/Key仍失效。现有Orven规格来源/冲突/兼容编辑已实现、静态类型通过,实际两端验收待下一阶段。 4. [pending] 固定官方来源/条件矩阵、多页/未知/退役/冲突/旧配置/参数/真实本机 wire 和恢复;独立冻结构建与网页/实际 Electron 宽窄屏核心路径,检查源码/编译/原件身份。首失败完整保留,不为通过降低检查。 5. [pending] 回顾、限定本地提交与既有 GitAtlas 普通增量推送,更新准确接续。下一缓存块/状态/指纹/请求版本与 CI,再 M3 统一发行。 diff --git a/progress.md b/progress.md index cb81c5e7..128325fe 100644 --- a/progress.md +++ b/progress.md @@ -1,7 +1,13 @@ # 统一执行进度 +M2 I15核心最后专项source-4为34/34:精确注册表、目录/密文恢复、DeepSeek可选及显式输出截断诊断、原响应和reported用量/单物理尝试通过。此前source-1原67/68保留。进入核心限定提交与build-1独立冻结;网页/Electron实际路径仍待,I14实际版本及M3迁移回退未因此完成。 + +M2 I15后端复核:source-2为71/71,最后用户声明来源补强source-3为31/31,types-1/2/3和17来源813289字节CLI已通过。接续修正DeepSeek HTTP Messages可选max_tokens仍被截断诊断泛称必填的文案,保留原上游响应/用量和单次尝试;专项复验后先提交核心。UI未运行,不称I15完成。本轮一处猜错测试文件路径和过量输出记录为调查失误,原产品失败不改。正式/真实模型/Key均未操作,继续独立冻结和实际两端验收。 + M2 I15阶段1完成:官方17份813289字节和6旧源码/4配置观察已封于自有根,来源fixture含精确URL、捕获/原源SHA、时间和表示范围。下一纯注册表实现与相关确定性验证;本阶段没有产品/正式改动,公开文档请求不是模型调用。首夹具路径表示错误原件保留。 +M2 I15接续:0cbf14a2已固定17来源原字节。纯注册表import通过,26协议记录/13精确型号,逐字段来源、冲突、null/空数组覆盖及旧声明来源不推断;参数和能力、目录完整脱敏item/双游标、快照冻结已接入未提交。首源码专项source-1为67/68:原路由“upstream_declared”被通用能力视图误显“protocol_declared”,已修来源映射,需复验;types-1通过。原阶段日志和失败保持。读取中有输出过多/Windows glob与不存在路径的调查错误,仅记录过程,不作产品通过证明;改用限定文件和字段。下一现有Orven参数面板来源/冲突/兼容覆盖与独立冻结验收。0真实模型/Key/正式写入,不委派或重启,历史unknown和M3迁移回退待验保持。 + M2 I15开始:3278c185工作树干净且远端一致,官方文档工具先搜索并取得Models与五精确GPT6当前页面,原文本已保存到自有证据根。先补官方注册表与来源/条件,再目录/现有UI及独立候选;尚无本批产品改动/模型请求/正式操作,不委派。 M2 I13普通增量推送完成:da2e6313/a2c6e6f5已在既有GitAtlas分支、ls-remote逐SHA一致,回执docs/gitatlas-m2-request-ledger-push.json随最后接续提交再复核。原封存根不追加,下一I15;正式/历史unknown不变。 diff --git a/scripts/verify-official-model-registry.mjs b/scripts/verify-official-model-registry.mjs new file mode 100644 index 00000000..3a1c339d --- /dev/null +++ b/scripts/verify-official-model-registry.mjs @@ -0,0 +1,24 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import { modelRegistry, validateModelRegistry } from '../src/shared/contracts/official-model-registry.mjs'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const fixtureRoot = path.join(root, 'tests/fixtures/official-model-registry'); +const fixtures = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'SOURCE.json'), 'utf8')); +validateModelRegistry(modelRegistry); assert.deepEqual(modelRegistry.sources, fixtures.sources); +const sources = fixtures.sources.map(source => { + const file = path.resolve(fixtureRoot, source.file); + assert.ok(file.startsWith(fixtureRoot + path.sep), 'Source path must belong to the fixture'); + const bytes = fs.readFileSync(file), sha256 = createHash('sha256').update(bytes).digest('hex'); + assert.equal(sha256, source.sha256, source.id); + return { id: source.id, file: source.file, bytes: bytes.length, sha256 }; +}); +const report = { checkedAt: new Date().toISOString(), registryVersion: modelRegistry.version, sources, + records: modelRegistry.records.map(value => ({ provider: value.provider, model: value.model, protocol: value.protocol, apiVersion: value.apiVersion, fields: Object.keys(value.fields) })), + recordsCount: modelRegistry.records.length, modelsCount: new Set(modelRegistry.records.map(value => value.model)).size, + sourcesBytes: sources.reduce((sum, value) => sum + value.bytes, 0), scope: 'Pinned public specification and source bytes; no model request or live-route compatibility claim.' }; +if (process.argv[2]) fs.writeFileSync(path.resolve(process.argv[2]), JSON.stringify(report, null, 2) + '\n', { flag: 'wx' }); +console.log(JSON.stringify({ registryVersion: report.registryVersion, sourcesCount: sources.length, sourcesBytes: report.sourcesBytes, recordsCount: report.recordsCount, modelsCount: report.modelsCount, passed: true })); diff --git a/src/core/models/credential-vault.mjs b/src/core/models/credential-vault.mjs index 920bbbc5..b46769c2 100644 --- a/src/core/models/credential-vault.mjs +++ b/src/core/models/credential-vault.mjs @@ -22,7 +22,7 @@ export class CredentialVault { } binding(connection) { return sha(JSON.stringify(canonicalHost({ app: 'agent-workbench', scope: 'Windows.CurrentUser', userSid: this.userSid, - dataIdentity: this.dataIdentity, connectionId: connection.id, connectionRevision: connection.revision, + dataIdentity: this.dataIdentity, connectionId: connection.id, connectionRevision: connection.credentialBindingRevision ?? connection.revision, protocol: connection.protocol, baseUrl: connection.baseUrl, model: connection.model, requiresKey: connection.requiresKey, ...(connection.protocol === 'anthropic-messages' ? { messagesAuth: connection.messagesAuth ?? 'api-key' } : {}) }))); } @@ -40,7 +40,7 @@ export class CredentialVault { return { status: 'invalid_record', storage: 'windows-user-dpapi', message: '此连接的原保存登记无法核对,原记录已保留;其他有效连接继续加载。' }; } const issue = value.userSid !== this.userSid ? 'user_mismatch' : value.dataIdentity !== this.dataIdentity ? 'directory_mismatch' - : value.connectionRevision !== connection.revision || value.bindingSha256 !== this.binding(connection) ? 'source_changed' + : value.connectionRevision !== (connection.credentialBindingRevision ?? connection.revision) || value.bindingSha256 !== this.binding(connection) ? 'source_changed' : this.issues.get(connection.id); return { storage: 'windows-user-dpapi', status: issue ?? (value.enabled ? 'saved' : 'disabled'), enabled: value.enabled === true, connectionRevision: value.connectionRevision, credentialRevision: value.credentialRevision, savedAt: value.savedAt, @@ -56,7 +56,7 @@ export class CredentialVault { let protectedBytes; try { protectedBytes = this.protect(plain, Buffer.from(bindingSha256, 'hex')); } finally { plain.fill(0); } - try { return { schema: 1, connectionId: connection.id, connectionRevision: connection.revision, credentialRevision, + try { return { schema: 1, connectionId: connection.id, connectionRevision: connection.credentialBindingRevision ?? connection.revision, credentialRevision, userSid: this.userSid, dataIdentity: this.dataIdentity, bindingSha256, enabled: true, savedAt: new Date().toISOString(), ciphertext: protectedBytes.toString('base64') }; } finally { protectedBytes.fill(0); } } diff --git a/src/core/models/model-catalog.mjs b/src/core/models/model-catalog.mjs index 63b44cb0..7101104c 100644 --- a/src/core/models/model-catalog.mjs +++ b/src/core/models/model-catalog.mjs @@ -4,6 +4,7 @@ import { catalogPage, catalogRoute } from '../../shared/contracts/model-catalog. import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs'; import { modelProtocol, capabilityDeclarations } from '../../shared/contracts/model-capabilities.mjs'; import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs'; +import { resolveModelSpecification } from '../../shared/contracts/official-model-registry.mjs'; const fail = (message, status = 400) => Object.assign(new Error(message), { status }); const stamp = () => new Date().toISOString(); @@ -69,12 +70,12 @@ export class ModelCatalog { this.active.set(id, controller); try { const entries = new Map(), cursors = new Set(), route = catalogRoute(connection); - let cursor = '', complete = true, warning = '', pages = 0, bytes = 0; + let cursor = '', cursorParameter = 'after_id', complete = true, warning = '', pages = 0, bytes = 0; do { controller.signal.throwIfAborted(); this.current({ binding }); if (!unrestricted(this.hub.store) && (Date.now() >= deadline)) throw fail('获取模型目录超过60秒,请稍后重试。'); - const query = cursor ? '?after_id=' + encodeURIComponent(cursor) + '&limit=100' : connection.protocol === 'anthropic-messages' ? '?limit=100' : ''; + const query = cursor ? '?' + cursorParameter + '=' + encodeURIComponent(cursor) + (cursorParameter === 'after_id' ? '&limit=100' : '') : connection.protocol === 'anthropic-messages' ? '?limit=100' : ''; const raw = await this.hub.provider.request({ ...this.hub.store.config, ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined, { attempts: 1, timeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()), totalTimeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()) }); const encoded = this.hub.provider.redact(JSON.stringify(raw), key); bytes += Buffer.byteLength(encoded); @@ -82,13 +83,16 @@ export class ModelCatalog { const page = catalogPage(JSON.parse(encoded), this.hub.store.config); pages++; if (!unrestricted(this.hub.store) && (page.entries.length > 1000)) throw fail('单页模型超过1000项,请核对上游分页。'); for (const item of page.entries) { + const declaration = JSON.stringify(item.rawItem); + item.rawSha256 = createHash('sha256').update(declaration).digest('hex'); item.rawBytes = Buffer.byteLength(declaration); if (entries.has(item.id) && JSON.stringify(entries.get(item.id)) !== JSON.stringify(item)) throw fail('上游目录包含相同型号的冲突定义,请核对后重试。'); if (!unrestricted(this.hub.store) && (entries.size === 1000 && !entries.has(item.id))) { complete = false; warning = '已达到1000项目录上限;当前只显示已获取部分,可使用手动兼容入口。'; break; } entries.set(item.id, item); } if (!page.hasMore || !complete) break; - if (cursors.has(page.cursor) || !page.entries.length) throw fail('上游分页未向前推进,已停止获取。'); - cursors.add(page.cursor); cursor = page.cursor; + const nextCursor = JSON.stringify([page.cursorParameter, page.cursor]); + if (cursors.has(nextCursor)) throw fail('上游分页重复返回相同游标,未向前推进,已停止获取。'); + cursors.add(nextCursor); cursor = page.cursor; cursorParameter = page.cursorParameter; if (!unrestricted(this.hub.store) && (pages === 20 || entries.size === 1000)) { complete = false; warning = '目录仍有后续页,已达到本次获取上限;当前只显示部分模型。'; break; } } while (true); controller.signal.throwIfAborted(); this.current({ binding }); this.prune(); @@ -130,12 +134,14 @@ export class ModelCatalog { prior.upstreamModel = upstreamModel; hub.save(); ids.push(prior.id); existing.push(prior.id); continue; } + const reference = resolveModelSpecification({ ...value.connection, model: model.id, upstreamModel }); const profile = hub.upsert({ name: value.connection.name + ' · ' + model.id, model: model.id, protocol: value.connection.protocol, baseUrl: value.connection.baseUrl, brand: value.connection.brand, messagesAuth: value.connection.messagesAuth, requiresKey: value.connection.requiresKey, concurrency: value.connection.concurrency, parameterProfile: value.connection.parameterProfile ?? 'auto', capabilityDeclarations: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state === 'unknown' ? declarations[key] : state])), streaming: false, - contextLimit: model.contextLimit ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit, - maxOutputTokens: model.maxOutputTokens ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens, + capabilityDeclarationSources: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state !== 'unknown' ? 'upstream_catalog' : declarations[key] !== 'unknown' ? 'user' : 'protocol'])), + contextLimit: reference.fields.contextLimit?.value ?? model.maxInputTokens ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit, + maxOutputTokens: reference.fields.maxOutputTokens?.value ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens, ...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) }); const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog'; if (!owner) owner = connection; diff --git a/src/core/models/model-hub.mjs b/src/core/models/model-hub.mjs index e68eb2dd..39b416b5 100644 --- a/src/core/models/model-hub.mjs +++ b/src/core/models/model-hub.mjs @@ -17,12 +17,24 @@ import { NetworkDiagnostics } from './network-diagnostics.mjs'; import { ModelCatalog, credentialScope } from './model-catalog.mjs'; import { capacitySettings, routedCapacity } from '../../shared/contracts/model-capacity.mjs'; import { ModelRequestLedger } from './request-ledger.mjs'; +import { modelOverrideSettings, resolveModelSpecification } from '../../shared/contracts/official-model-registry.mjs'; const legacyId = 'legacy-default'; const stamp = () => new Date().toISOString(); const error = (message, status = 400) => Object.assign(new Error(message), { status }); const bounded = (value, fallback, min, max) => Number.isFinite(Number(value)) ? Math.max(min, Math.min(max, Math.trunc(Number(value)))) : fallback; const label = (value, maximum = 100) => String(value ?? '').trim().slice(0, maximum); +const credentialProfile = connection => JSON.stringify([connection.protocol, connection.baseUrl, connection.model, connection.requiresKey, + connection.protocol === 'anthropic-messages' ? connection.messagesAuth ?? 'api-key' : null]); +function declarationSources(input, previous, declarations) { + const provided = input.capabilityDeclarationSources; + if (provided !== undefined && (!provided || typeof provided !== 'object' || Array.isArray(provided) + || Object.entries(provided).some(([key, value]) => !Object.hasOwn(declarations, key) || !['user', 'protocol', 'upstream_catalog', 'legacy_connection'].includes(value)))) throw error('能力声明来源格式无效。'); + return Object.fromEntries(Object.keys(declarations).map(key => [key, previous && input.capabilityDeclarations && Object.hasOwn(input.capabilityDeclarations, key) + && input.capabilityDeclarations[key] !== previous.capabilityDeclarations?.[key] ? 'user' : provided?.[key] ?? ( + input.capabilityDeclarations && Object.hasOwn(input.capabilityDeclarations, key) && (!previous || input.capabilityDeclarations[key] !== previous.capabilityDeclarations?.[key]) ? 'user' + : previous?.capabilityDeclarationSources?.[key] ?? (previous?.capabilityDeclarations ? 'legacy_connection' : 'protocol'))])); +} export function modelEndpoint(value) { let url; try { url = new URL(String(value)); } catch { throw error('请输入有效的模型接口根地址。'); } @@ -154,14 +166,15 @@ export class ModelHub { + (connection.credentialSource ? ':' + (this.credentialOwner(connection)?.revision ?? 'unavailable') : ''); } status(connection) { const credential = this.credential(connection), health = this.health.get(this.identity(connection)); + const capabilityEvidence = this.state.capabilityResults?.[connection.id]; const ready = connection.enabled && (!connection.credentialSource || !!this.credentialOwner(connection)) && (!connection.requiresKey || !!credential?.key); return { ...connection, hasKey: !!credential?.key, credentialRevision: credential?.revision ?? 0, credentialStorage: 'memory', ...(this.credentialVault ? { savedCredential: this.credentialVault.status(connection) } : {}), status: !connection.enabled ? 'disabled' : !ready ? 'needs_key' : health?.blocked ? 'needs_attention' : health?.cooldownUntil > Date.now() ? 'cooling' : 'configured', activeRequests: this.leases.get(connection.id) ?? 0, health: health ?? { state: 'unverified' }, streaming: connection.streaming === true, capabilitySchema: 1, capabilityDeclarations: capabilityDeclarations(undefined, connection.capabilityDeclarations), - ...(this.state.capabilityResults?.[connection.id] ? { capabilityEvidence: this.state.capabilityResults[connection.id] } : {}), - capabilities: capabilityView({ ...connection, capabilityEvidence: this.state.capabilityResults?.[connection.id] }, credential?.revision ?? 0) }; + ...(capabilityEvidence ? { capabilityEvidence } : {}), modelSpecification: resolveModelSpecification({ ...connection, capabilityEvidence }, credential?.revision ?? 0), + capabilities: capabilityView({ ...connection, capabilityEvidence }, credential?.revision ?? 0) }; } view() { const page = this.ledger.page({ limit: 100 }); return { revision: this.state.revision, selected: this.state.selected, waitSettings: modelWaitSettings(this.store.config), connections: this.connections().map(value => this.status(value)), pools: this.state.pools, imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: page.items, attemptCount: page.retainedTotal, attemptsHasMore: page.hasMore, waiting: this.waiting, @@ -230,19 +243,31 @@ export class ModelHub { const native = Object.hasOwn(input, 'nativeParameters') || Object.hasOwn(input, 'outputTokenField') || Object.hasOwn(input, 'parameterProfile') || previous?.nativeParameters || previous?.parameterProfile ? nativeParameterSettings(protocol, input.nativeParameters ?? previous?.nativeParameters ?? {}, input.outputTokenField ?? previous?.outputTokenField, input.parameterProfile ?? previous?.parameterProfile, this.store.config) : null; const declarations = capabilityDeclarations(input.capabilityDeclarations, previous?.capabilityDeclarations); + const capabilityDeclarationSources = declarationSources(input, previous, declarations); + const specificationSettings = {}; + if (Object.hasOwn(input, 'modelOverrides') || previous?.modelOverrides) specificationSettings.modelOverrides = modelOverrideSettings(input.modelOverrides, previous?.modelOverrides); + for (const key of ['providerId', 'apiVersion']) if (Object.hasOwn(input, key) || previous?.[key]) { + const value = input[key] ?? previous?.[key]; + if (typeof value !== 'string' || !value || /[\x00-\x20\x7f]/.test(value)) throw error('模型供应商或规格版本标识无效。'); + specificationSettings[key] = value; + } if (input.streaming !== undefined && typeof input.streaming !== 'boolean') throw error('流式选项必须为开启或关闭。'); const streaming = input.streaming ?? previous?.streaming ?? false; if (!unrestricted(this.store) && streaming && declarations.streaming !== 'supported') throw error('请先声明服务支持流式输出,再开启流式请求。'); const name = label(input.name, ceiling(this.store, 100)), model = label(input.model, ceiling(this.store, 200)); if (!name || !model) throw error('请填写连接名称和实际模型名称。'); const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', ceiling(this.store, 40)), protocol, model, - capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}), + capabilitySchema: 1, capabilityDeclarations: declarations, capabilityDeclarationSources, ...specificationSettings, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}), ...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth), baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false, ...capacitySettings(input, previous ?? undefined, this.store.config), concurrency: unrestricted(this.store) ? (input.concurrency ?? 0) : bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1, source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}), createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() }; + // Keep an existing encrypted binding for edits that do not change its + // endpoint/model/auth/key identity. Never decrypt or re-save the old key. + connection.credentialBindingRevision = previous && !Object.hasOwn(input, 'apiKey') && credentialProfile(previous) === credentialProfile(connection) + ? previous.credentialBindingRevision ?? previous.revision : connection.revision; if (previous?.credentialSource && !Object.hasOwn(input, 'apiKey')) { if (credentialScope(previous) !== credentialScope(connection)) throw error('该模型共用上游凭据;改变地址或鉴权前,请新建上游或显式填写独立 Key。'); connection.credentialSource = previous.credentialSource; @@ -275,13 +300,14 @@ export class ModelHub { const connection = this.connection(input.id); if (connection.revision !== input.revision) throw error('连接已变化,请刷新后核对原生参数。', 409); const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField, input.parameterProfile ?? connection.parameterProfile, this.store.config); - if (connection.id === legacyId && !this.state.legacyConnection) this.save(settings); + if (Object.hasOwn(input, 'modelOverrides')) settings.modelOverrides = modelOverrideSettings(input.modelOverrides, connection.modelOverrides); + if (connection.id === legacyId && !this.state.legacyConnection && !Object.hasOwn(input, 'modelOverrides')) this.save(settings); else this.upsert({ ...connection, ...settings }); return { center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } }; } toggle(id, enabled) { if (id === legacyId) return this.upsert({ ...this.connection(id), enabled: enabled === true }); - const value = this.connection(id); value.enabled = enabled === true; value.revision++; value.updatedAt = stamp(); this.save(); return this.status(value); + const value = this.connection(id); value.credentialBindingRevision ??= value.revision; value.enabled = enabled === true; value.revision++; value.updatedAt = stamp(); this.save(); return this.status(value); } pool(input) { const previous = input.id ? this.state.pools.find(value => value.id === input.id) : null; @@ -311,16 +337,22 @@ export class ModelHub { return this.view(); } prepare(config, selection = this.state.selected) { - if (config.mode === 'demo' || selection.type === 'legacy' && !this.state.legacyConnection) return config; + if (config.mode === 'demo') return config; + if (selection.type === 'legacy' && !this.state.legacyConnection) return { ...config, + modelSpecification: resolveModelSpecification({ ...config, capabilityDeclarationSources: { text: 'protocol', tools: 'protocol' } }), modelSpecificationFrozen: true }; if (this.catalog?.active.size) throw error('正在获取上游模型目录,请等待完成或取消。', 409); const pool = selection.type === 'pool' ? this.state.pools.find(value => value.id === selection.id) : null; if (selection.type === 'pool' && !pool) throw error('选中的模型池不存在。'); - const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight, - credentialRevision: this.credential(this.connection(value.connectionId))?.revision ?? 0, - ...(this.connection(value.connectionId).credentialSource ? { credentialSourceRevision: this.credentialOwner(this.connection(value.connectionId))?.revision ?? null } : {}) })); + const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => { + const connection = this.connection(value.connectionId), credentialRevision = this.credential(connection)?.revision ?? 0; + const member = { ...connection, capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight, credentialRevision, + ...(connection.credentialSource ? { credentialSourceRevision: this.credentialOwner(connection)?.revision ?? null } : {}) }; + return { ...structuredClone(member), modelSpecification: resolveModelSpecification(member, credentialRevision), modelSpecificationFrozen: true }; + }); if (!members.some(value => unrestricted(this.store) && value.enabled || this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。'); return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true, nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile, + modelSpecification: structuredClone(members[0].modelSpecification), modelSpecificationFrozen: true, modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision, ...routedCapacity(config, members), modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision, diff --git a/src/server/provider.mjs b/src/server/provider.mjs index 5519f33f..b349a6a8 100644 --- a/src/server/provider.mjs +++ b/src/server/provider.mjs @@ -319,11 +319,10 @@ export class Provider { transport:this.transport?.profile,timedOut: !!timeout.timeout, timeout: timeout.timeout, redact: value => this.redact(value, key) }); if (config.capacityMode === 'passthrough' && diagnostic.reason === 'output_truncated') { // Describe the serialized request actually sent, including native user - // settings and Messages' mandatory field, rather than a local default. + // settings and provider-required fields, rather than a local default. const sent = wireBody ? JSON.parse(wireBody) : {}; const fields = ['max_tokens', 'max_completion_tokens', 'max_output_tokens'].filter(field => Object.hasOwn(sent, field)); - const output = fields.length ? '实际请求携带 ' + fields.map(field => field + '=' + (Number.isFinite(sent[field]) ? sent[field] : '非数值(见原请求)')).join('、') - + (config.protocol === 'anthropic-messages' ? '(Messages 协议要求 max_tokens)' : '') : '实际请求未携带输出 token 上限'; + const output = fields.length ? '实际请求携带 ' + fields.map(field => field + '=' + (Number.isFinite(sent[field]) ? sent[field] : '非数值(见原请求)')).join('、') : '实际请求未携带输出 token 上限'; const reason = diagnostic.upstream?.reason ?? responseDetails?.reason ?? (config.protocol === 'anthropic-messages' ? 'max_tokens' : config.protocol === 'responses' ? 'max_output_tokens' : 'length'); diagnostic = { ...diagnostic, origin: 'upstream', title: '上游响应因输出额度结束', message: '上游返回结束原因 ' + reason + '。' + output + '。原响应及用量已保存;不完整的工具批次未执行。' }; diff --git a/src/shared/contracts/anthropic-messages.mjs b/src/shared/contracts/anthropic-messages.mjs index 51c65ced..19b333c5 100644 --- a/src/shared/contracts/anthropic-messages.mjs +++ b/src/shared/contracts/anthropic-messages.mjs @@ -51,10 +51,10 @@ export function messagesBody(config, messages, tools, native) { }); return { model: config.model, ...(system.length ? { system } : {}), messages: wire, ...(definitions.length ? { tools: definitions, tool_choice: { type: 'auto' } } : {}), - // Messages requires max_tokens, even in passthrough mode. Prefer the - // synchronized upstream maximum; native parameters below remain exact. + // Standard Anthropic requires max_tokens; a reviewed compatible HTTP + // dialect may explicitly permit omission. Native parameters remain exact. // A saved connection declaration is a fallback, never a verified maximum. - max_tokens: isPassthrough(config) ? protocolOutput : config.maxOutputTokens, + ...(!isPassthrough(config) || protocolOutput !== undefined ? { max_tokens: isPassthrough(config) ? protocolOutput : config.maxOutputTokens } : {}), stream: config.streaming === true, ...native.nativeParameters }; } diff --git a/src/shared/contracts/execution.mjs b/src/shared/contracts/execution.mjs index 8675c4d7..164ca7f8 100644 --- a/src/shared/contracts/execution.mjs +++ b/src/shared/contracts/execution.mjs @@ -31,6 +31,7 @@ export function modelSnapshot(config) { ...(config.protocol === 'anthropic-messages' ? { messagesAuth: config.messagesAuth ?? 'api-key' } : {}), ...(config.nativeParameters ? { nativeParameters: structuredClone(config.nativeParameters), outputTokenField: config.outputTokenField } : {}), ...(config.parameterProfile ? { parameterProfile: config.parameterProfile } : {}), + ...(config.modelSpecification ? { modelSpecification: structuredClone(config.modelSpecification), modelSpecificationFrozen: config.modelSpecificationFrozen === true } : {}), ...(config.modelConnectionId ? { modelConnectionId: config.modelConnectionId, modelCredentialRevision: config.modelCredentialRevision } : {}), ...(config.modelRouting ? { routing: structuredClone(config.modelRouting) } : {}), }; diff --git a/src/shared/contracts/model-capabilities.mjs b/src/shared/contracts/model-capabilities.mjs index f306e8d0..ff9ddfc3 100644 --- a/src/shared/contracts/model-capabilities.mjs +++ b/src/shared/contracts/model-capabilities.mjs @@ -1,3 +1,5 @@ +import { resolveModelSpecification } from './official-model-registry.mjs'; + export const MODEL_PROTOCOLS = ['chat-completions', 'responses', 'anthropic-messages']; export const MODEL_CAPABILITIES = ['text', 'tools', 'streaming', 'vision', 'audio']; const failure = message => Object.assign(new Error(message), { status: 400 }); @@ -19,12 +21,13 @@ export function capabilityDeclarations(input, previous = null) { } export function capabilityView(connection, credentialRevision = 0) { - const declarations = capabilityDeclarations(undefined, connection.capabilityDeclarations); - const evidence = connection.capabilityEvidence; - const current = evidence?.connectionRevision === connection.revision && evidence?.credentialRevision === credentialRevision; - return Object.fromEntries(MODEL_CAPABILITIES.map(key => [key, - declarations[key] === 'unsupported' ? 'unsupported' : current && evidence.results?.[key] === 'verified' ? 'verified' - : declarations[key] === 'supported' ? 'protocol_declared' : 'unknown'])); + const specification = resolveModelSpecification({ ...connection, capabilityDeclarations: capabilityDeclarations(undefined, connection.capabilityDeclarations), + ...(!connection.capabilityDeclarations ? { capabilityDeclarationSources: { text: 'protocol', tools: 'protocol' } } : {}) }, credentialRevision); + return Object.fromEntries(MODEL_CAPABILITIES.map(key => { + const fact = specification.fields['capabilities.' + key]; + return [key, fact?.value === 'unsupported' ? 'unsupported' : fact?.kind === 'revision_bound_observation' ? 'verified' + : fact?.value === 'supported' ? 'protocol_declared' : 'unknown']; + })); } export function capabilityRejections(connection, requirements, credentialRevision = 0) { diff --git a/src/shared/contracts/model-capacity.d.mts b/src/shared/contracts/model-capacity.d.mts index dcdcdde7..42b72207 100644 --- a/src/shared/contracts/model-capacity.d.mts +++ b/src/shared/contracts/model-capacity.d.mts @@ -1,6 +1,6 @@ export const DEFAULT_MODEL_CAPACITY: Readonly<{ contextLimit: number; maxOutputTokens: number }>; export const CAPACITY_RANGES: Readonly>; export function capacitySettings(input?: { contextLimit?: number; maxOutputTokens?: number }, previous?: { contextLimit?: number; maxOutputTokens?: number }): { contextLimit: number; maxOutputTokens: number }; -export function capacityMode(value?: string): 'model' | 'manual'; -export function messagesOutputSetting(config: { model?: string; nativeParameters?: Record; maxOutputTokens?: number; upstreamModel?: { id: string; maxOutputTokens?: number | null } }): { value: unknown; source: string }; -export function modelCapacityDeclaration(config: { model?: string; upstreamModel?: { id: string; contextLimit?: number | null; maxOutputTokens?: number | null } }, field: 'contextLimit' | 'maxOutputTokens'): { value: number; source: 'upstream_catalog' | 'official_model_spec'; sourceUrl?: string; checkedAt?: string } | null; +export function capacityMode(value?: string): 'passthrough' | 'model' | 'manual'; +export function messagesOutputSetting(config: import('./official-model-registry.mjs').ModelSpecConnection & { maxOutputTokens?: number }): { value: unknown; source: string }; +export function modelCapacityDeclaration(config: import('./official-model-registry.mjs').ModelSpecConnection, field: 'contextLimit' | 'maxOutputTokens'): { value: number; source: string; sourceUrl?: string | null; checkedAt?: string | null; sourceSha256?: string | null; conflict?: boolean; provider?: string } | null; diff --git a/src/shared/contracts/model-capacity.mjs b/src/shared/contracts/model-capacity.mjs index ab7ceff8..5aae15fb 100644 --- a/src/shared/contracts/model-capacity.mjs +++ b/src/shared/contracts/model-capacity.mjs @@ -1,5 +1,6 @@ import { unrestricted } from './execution-policy.mjs'; import { officialModelCapacity } from './official-model-capacity.mjs'; +import { resolveModelSpecification } from './official-model-registry.mjs'; // Editable fallbacks for upstreams that do not publish capacity. These values // are not verified model capabilities or ceilings on larger models. @@ -20,16 +21,19 @@ export const isPassthrough = config => config.capacityMode === 'passthrough'; export function modelCapacityDeclaration(config, field) { if (!['contextLimit', 'maxOutputTokens'].includes(field)) return null; const member = config.modelRouting?.members?.find(value => value.id === config.modelConnectionId) ?? config; - const upstream = member.upstreamModel; - if (upstream?.id === member.model && Number.isSafeInteger(upstream[field]) && upstream[field] > 0) return { value: upstream[field], source: 'upstream_catalog' }; - const official = officialModelCapacity(member.model); - return official ? { value: official[field], source: official.source, sourceUrl: official.sourceUrl, checkedAt: official.checkedAt } : null; + const fact = resolveModelSpecification(member).fields[field]; + if (fact) return Number.isSafeInteger(fact.value) && fact.value > 0 ? { value: fact.value, source: fact.kind, sourceUrl: fact.url, checkedAt: fact.checkedAt, + sourceSha256: fact.sha256, provider: fact.provider, conflict: fact.conflict, alternatives: fact.alternatives } : null; + const official = officialModelCapacity(member.model, { providerId: member.providerId, apiVersion: member.apiVersion, protocol: member.protocol }); + return official && Number.isSafeInteger(official[field]) && official[field] > 0 ? { value: official[field], source: official.source, sourceUrl: official.sourceUrl, checkedAt: official.checkedAt, + sourceSha256: official.sourceSha256, provider: official.provider } : null; } export function messagesOutputSetting(config) { const member = config.modelRouting?.members?.find(value => value.id === config.modelConnectionId) ?? config; const native = config.nativeParameters ?? member.nativeParameters ?? {}; if (Object.hasOwn(native, 'max_tokens')) return { value: native.max_tokens, source: 'explicit_native' }; + if (resolveModelSpecification(member).fields['request.maxTokensRequired']?.value === false) return { value: undefined, source: 'upstream_optional' }; const declaration = modelCapacityDeclaration(config, 'maxOutputTokens'); if (declaration) return declaration; return { value: member.maxOutputTokens ?? config.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens, source: 'connection_declaration' }; diff --git a/src/shared/contracts/model-catalog.d.mts b/src/shared/contracts/model-catalog.d.mts index 8d4f8607..c25a690b 100644 --- a/src/shared/contracts/model-catalog.d.mts +++ b/src/shared/contracts/model-catalog.d.mts @@ -1,7 +1,11 @@ export interface CatalogModel { - id: string; name: string; owner: string; lifecycle: string | null; contextLimit: number | null; maxOutputTokens: number | null; + id: string; name: string; owner: string; lifecycle: string | null; contextLimit: number | null; maxOutputTokens: number | null; maxInputTokens?: number | null; capabilityDeclarations: Record; features: Record; efforts: string[]; modes: string[]; parameters: string[]; metadataSource: string; effortSupport?: Record; modeSupport?: Record; + reportedFields?: string[]; defaultEffort?: string; defaultMode?: string; modeEfforts?: Record; + inputModalities?: string[]; outputModalities?: string[]; nativeTools?: string[]; + apiCapabilities?: Record>; rawItem?: Record; rawRepresentation?: string; rawSha256?: string; rawBytes?: number; + endpoint?: string; fetchedAt?: string; } export interface CatalogPreview { id: string; entries: CatalogModel[]; fetchedAt: string; expiresAt: string; complete: boolean; warning: string; @@ -9,4 +13,4 @@ export interface CatalogPreview { } export function catalogRoute(config: { protocol?: string; baseUrl: string }): string; export function catalogModel(item: unknown, config?: { executionMode?: string }): CatalogModel; -export function catalogPage(response: unknown, config?: { executionMode?: string }): { entries: CatalogModel[]; hasMore: boolean; cursor: string }; +export function catalogPage(response: unknown, config?: { executionMode?: string }): { entries: CatalogModel[]; hasMore: boolean; cursor: string; cursorParameter: 'pageToken' | 'after_id' }; diff --git a/src/shared/contracts/model-catalog.mjs b/src/shared/contracts/model-catalog.mjs index 3f2980da..5f3f3e81 100644 --- a/src/shared/contracts/model-catalog.mjs +++ b/src/shared/contracts/model-catalog.mjs @@ -7,6 +7,14 @@ const supported = value => typeof value === 'boolean' ? value ? 'supported' : 'u : typeof value?.supported === 'boolean' ? value.supported ? 'supported' : 'unsupported' : ['supported', 'unsupported', 'unknown'].includes(value) ? value : 'unknown'; const positive = value => Number.isSafeInteger(value) && value > 0 ? value : null; +const object = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}; +const strings = value => Array.isArray(value) ? [...new Set(value.filter(item => typeof item === 'string' && item && !/[\x00-\x1f\x7f]/.test(item)))] : []; +const sensitiveFields = /^(?:api[-_]?key|access[-_]?token|refresh[-_]?token|authorization|x-api-key|secret|password|credential)$/i; +function rawDeclaration(value) { + if (Array.isArray(value)) return value.map(rawDeclaration); + if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, data]) => [key, sensitiveFields.test(key) ? '[redacted]' : rawDeclaration(data)])); + return value; +} export function catalogRoute(config) { const protocol = modelProtocol(config.protocol); @@ -15,18 +23,19 @@ export function catalogRoute(config) { } // Metadata is an upstream declaration, never capability-test evidence. Keep -// unsupported adapter features visible without passing arbitrary vendor fields. +// unsupported adapter features visible. Retain unknown vendor fields as a +// redacted declaration; none of those fields is copied into a model request. export function catalogModel(item, config = {}) { if (typeof item === 'string') item = { id: item }; if (!item || typeof item !== 'object' || Array.isArray(item)) throw fail('上游模型目录含无效条目。'); const field = (value, maximum = 200) => text(value, ceiling(config, maximum)); const id = field(item.id ?? item.name); if (!id || id.length !== String(item.id ?? item.name).trim().length || /[\x00-\x1f\x7f]/.test(id)) throw fail('上游模型名称为空、过长或含控制字符。'); - const caps = item.capabilities && typeof item.capabilities === 'object' && !Array.isArray(item.capabilities) ? item.capabilities : {}; + const caps = object(item.capabilities), reportedFields = []; const declarations = Object.fromEntries(['text', 'tools', 'streaming', 'vision', 'audio'].map(key => [key, supported(caps[key] ?? (key === 'vision' ? caps.image_input : key === 'tools' ? caps.tool_calling ?? caps.function_calling : undefined))])); - const input = item.input_modalities ?? item.architecture?.input_modalities; - const output = item.output_modalities ?? item.architecture?.output_modalities; + const input = item.input_modalities ?? item.architecture?.input_modalities ?? item.modalities?.input; + const output = item.output_modalities ?? item.architecture?.output_modalities ?? item.modalities?.output; if (Array.isArray(input)) { if (input.includes('image') && declarations.vision === 'unknown') declarations.vision = 'supported'; if (input.includes('audio') && declarations.audio === 'unknown') declarations.audio = 'supported'; @@ -34,25 +43,48 @@ export function catalogModel(item, config = {}) { if (Array.isArray(output) && output.includes('text') && declarations.text === 'unknown') declarations.text = 'supported'; const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && (unrestricted(config) || value.length <= 80)))].slice(0, ceiling(config, 80)) : []; if (declarations.tools === 'unknown' && parameters.includes('tools')) declarations.tools = 'supported'; - const effortSupport = Object.fromEntries(['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].map(value => [value, supported(caps.effort?.[value])])); - const modeSupport = Object.fromEntries(['disabled', 'enabled', 'adaptive', 'between_tools'].map(value => [value, supported(caps.thinking?.types?.[value])])); - const efforts = Object.keys(effortSupport).filter(value => effortSupport[value] === 'supported'); - const modes = Object.keys(modeSupport).filter(value => modeSupport[value] === 'supported'); - const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])])); + const effortDeclaration = item.effort ?? caps.effort; + const reportedEfforts = effortDeclaration?.supported_levels ?? item.reasoning_efforts; + const reportedModes = caps.thinking?.supported_types ?? item.thinking?.supported_types; + const effortSupport = Object.fromEntries([...new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', ...Object.keys(object(caps.effort)), ...strings(reportedEfforts)])] + .filter(value => !['supported', 'supported_levels', 'default_level'].includes(value)).map(value => [value, supported(caps.effort?.[value])])); + const modeSupport = Object.fromEntries([...new Set(['disabled', 'enabled', 'adaptive', 'between_tools', ...Object.keys(object(caps.thinking?.types)), ...strings(reportedModes)])] + .map(value => [value, supported(caps.thinking?.types?.[value])])); + if (Array.isArray(reportedEfforts)) { + reportedFields.push('efforts'); + for (const value of strings(reportedEfforts)) if (effortSupport[value] !== 'unsupported') effortSupport[value] = 'supported'; + } + if (Array.isArray(reportedModes)) { + reportedFields.push('modes'); + for (const value of strings(reportedModes)) if (modeSupport[value] !== 'unsupported') modeSupport[value] = 'supported'; + } + const efforts = (Array.isArray(reportedEfforts) ? strings(reportedEfforts) : Object.keys(effortSupport)).filter(value => effortSupport[value] === 'supported'); + const modes = (Array.isArray(reportedModes) ? strings(reportedModes) : Object.keys(modeSupport)).filter(value => modeSupport[value] === 'supported'); + const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'json_output', 'prompt_caching', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])])); + if (features.effort === 'unknown' && Array.isArray(reportedEfforts)) features.effort = reportedEfforts.length ? 'supported' : 'unsupported'; return { id, name: field(item.display_name ?? item.displayName ?? item.name ?? id), owner: field(item.owned_by ?? item.provider, 100), lifecycle: ['active', 'deprecated', 'retired'].includes(item.lifecycle) ? item.lifecycle : null, - contextLimit: positive(item.context_length ?? item.max_input_tokens ?? item.context_window ?? item.inputTokenLimit), + contextLimit: positive(item.context_length ?? item.context_window), maxInputTokens: positive(item.max_input_tokens ?? item.inputTokenLimit), maxOutputTokens: positive(item.max_output_tokens ?? item.max_tokens ?? item.top_provider?.max_completion_tokens ?? item.outputTokenLimit), capabilityDeclarations: declarations, features, efforts, modes, effortSupport, modeSupport, parameters, - metadataSource: 'upstream-model-list' }; + ...(typeof effortDeclaration?.default_level === 'string' ? { defaultEffort: effortDeclaration.default_level } : {}), + ...(typeof item.thinking?.default_type === 'string' ? { defaultMode: item.thinking.default_type } : {}), + ...(Array.isArray(input) ? { inputModalities: strings(input) } : {}), ...(Array.isArray(output) ? { outputModalities: strings(output) } : {}), + ...(Array.isArray(item.native_tools) ? { nativeTools: strings(item.native_tools) } : {}), + apiCapabilities: structuredClone(object(item.api_capabilities)), reportedFields, + rawItem: rawDeclaration(item), rawRepresentation: 'parsed-redacted-item-json-v1', metadataSource: 'upstream-model-list' }; } export function catalogPage(response, config = {}) { const data = response?.data ?? response?.models; if (!Array.isArray(data)) throw fail('上游未返回 data 或 models 模型列表;可核对接口或使用手动兼容入口。'); const entries = data.map(item => catalogModel(item, config)); - const hasMore = response.has_more === true; - const cursor = hasMore ? text(response.last_id ?? entries.at(-1)?.id, ceiling(config, 200)) : ''; + const pageToken = response.nextPageToken ?? response.next_page_token; + const hasMore = response.has_more === true || typeof pageToken === 'string' && pageToken.length > 0; + const cursorParameter = typeof pageToken === 'string' && pageToken ? 'pageToken' : 'after_id'; + const value = hasMore ? cursorParameter === 'pageToken' ? pageToken : response.last_id ?? entries.at(-1)?.id : ''; + const cursor = text(value, ceiling(config, 200)); + if (hasMore && (typeof value !== 'string' || cursor.length !== value.trim().length || /[\x00-\x1f\x7f]/.test(cursor))) throw fail('上游下一页游标无效。'); if (hasMore && !cursor) throw fail('上游声明还有下一页,却未提供有效游标。'); - return { entries, hasMore, cursor }; + return { entries, hasMore, cursor, cursorParameter }; } diff --git a/src/shared/contracts/model-parameter-profiles.d.mts b/src/shared/contracts/model-parameter-profiles.d.mts index d89d77ce..2d11cca1 100644 --- a/src/shared/contracts/model-parameter-profiles.d.mts +++ b/src/shared/contracts/model-parameter-profiles.d.mts @@ -1,4 +1,5 @@ -export interface ParameterConnection { +import type { ModelSpecConnection } from './official-model-registry.mjs'; +export interface ParameterConnection extends ModelSpecConnection { protocol?: string; parameterProfile?: string; brand?: string; model?: string; baseUrl?: string; nativeParameters?: Record; capabilities?: Record; capabilityDeclarations?: Record; upstreamModel?: import('./model-catalog.mjs').CatalogModel; @@ -8,8 +9,9 @@ export const messagesEfforts: string[]; export function parameterProfiles(protocol: string): { id: string; label: string }[]; export function parameterProfileSettings(protocol: string, value?: string): string; export function modelParameterProfile(connection: ParameterConnection): { id: string; label: string; source: string; sourceKind: string; - officialSource: { url: string; effortUrl: string; checkedAt: string } | null; efforts: string[]; thinking: boolean; modes: string[]; - modeEfforts: Record; defaultMode: string | null; defaultEffort: string | null }; + officialSource: { url: string; effortUrl: string; checkedAt: string; provider: string; apiVersion: string } | null; efforts: string[]; thinking: boolean; modes: string[]; + modeEfforts: Record; defaultMode: string | null; defaultEffort: string | null; thinkingBudget: string; + specification: import('./official-model-registry.mjs').ModelSpecification }; export function assertModelParameterSupport(connection: ParameterConnection, parameters: Record): void; export function reasoningSetting(connection: ParameterConnection, parameters: Record): { mode: string; effort: string; budget: number; canResetMode: boolean; thinkingSiblings: boolean }; export function changeReasoningSetting(connection: ParameterConnection, parameters: Record, field: string, value: string | number): Record; diff --git a/src/shared/contracts/model-parameter-profiles.mjs b/src/shared/contracts/model-parameter-profiles.mjs index 5a42a06c..3e5df5e1 100644 --- a/src/shared/contracts/model-parameter-profiles.mjs +++ b/src/shared/contracts/model-parameter-profiles.mjs @@ -1,4 +1,4 @@ -import { officialModelParameters } from './official-model-parameters.mjs'; +import { modelProvider, officialModelRecord, matchingUpstreamModel, resolveModelSpecification } from './official-model-registry.mjs'; export const reasoningEfforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']; export const messagesEfforts = ['low', 'medium', 'high', 'xhigh', 'max']; @@ -18,6 +18,7 @@ export function parameterProfileSettings(protocol, value = 'auto') { // proxy or particular model supports every field in that protocol. function declaredChoices(metadata, field, supportField, feature, fallback, official) { if (metadata?.features?.[feature] === 'unsupported') return []; + if (metadata?.reportedFields?.includes(field)) return (metadata[field] ?? []).filter(value => metadata[supportField]?.[value] !== 'unsupported'); const values = metadata?.[field] ?? [], support = metadata?.[supportField]; if (support && Object.values(support).some(value => value !== 'unknown')) { return [...new Set([...fallback, ...values, ...Object.keys(support)])].filter(value => support[value] === 'supported' @@ -29,31 +30,49 @@ function declaredChoices(metadata, field, supportField, feature, fallback, offic export function modelParameterProfile(connection) { const protocol = connection.protocol ?? 'chat-completions'; const selected = parameterProfileSettings(protocol, connection.parameterProfile); - const official = selected === 'auto' && protocol === 'anthropic-messages' ? officialModelParameters(connection.model) : null; - const deepseek = connection.brand === 'DeepSeek' || /^deepseek(?:-|$)/i.test(connection.model ?? '') - || /^https:\/\/api\.deepseek\.com(?:\/|$)/i.test(connection.baseUrl ?? '') || !!connection.nativeParameters?.thinking && protocol === 'chat-completions'; - const id = selected !== 'auto' ? selected : official ? 'anthropic' : deepseek ? 'deepseek' : protocol === 'anthropic-messages' ? 'anthropic' : 'openai'; - const metadata = !connection.model || connection.upstreamModel?.id === connection.model ? connection.upstreamModel : null; + const provider = modelProvider(connection), official = selected === 'auto' ? officialModelRecord(connection) : null; + const id = selected !== 'auto' ? selected : ['openai', 'anthropic', 'deepseek'].includes(provider.id) ? provider.id : protocol === 'anthropic-messages' ? 'anthropic' : 'openai'; + const metadata = matchingUpstreamModel(connection), specification = resolveModelSpecification(connection); + const field = key => { + const fact = specification.fields[key]; + if (!fact) return null; + if (selected === 'auto' || fact.kind !== 'official_model_spec') return fact; + return fact.alternatives.find(value => value.kind !== 'official_model_spec') ?? null; + }; const choices = id === 'deepseek' ? ['low', 'high', 'max'] : protocol === 'anthropic-messages' ? messagesEfforts : reasoningEfforts.filter(value => value !== 'none'); - const modes = official?.modes ?? ['disabled', 'enabled', ...(protocol === 'anthropic-messages' ? ['adaptive', 'between_tools'] : [])]; - return { id, label: labels[id], source: metadata ? '优先采用相符型号的上游目录声明,缺失项再匹配官方规格或兼容格式' - : official ? '按 Anthropic 官方精确型号规格匹配' : selected === 'auto' ? '按品牌、型号与协议匹配;未取得的型号能力待确认' : '用户选择的兼容格式,不套用官方型号后备选项', - sourceKind: metadata ? 'upstream_model_list' : official ? 'official_model_spec' : 'compatibility_profile', - officialSource: official ? { url: official.sourceUrl, effortUrl: official.effortSourceUrl, checkedAt: official.checkedAt } : null, - efforts: declaredChoices(metadata, 'efforts', 'effortSupport', 'effort', official?.efforts ?? choices, !!official), - modes: declaredChoices(metadata, 'modes', 'modeSupport', 'thinking', modes, !!official), - modeEfforts: official?.modeEfforts ?? {}, defaultMode: official?.defaultMode ?? null, defaultEffort: official?.defaultEffort ?? null, - thinking: protocol === 'anthropic-messages' || id === 'deepseek' && protocol === 'chat-completions' }; + const optionValues = (key, supportKey, feature, fallback) => { + const fact = field(key), featureFact = field('features.' + feature); + if (featureFact?.value === 'unsupported') return []; + if (fact?.kind === 'explicit_compatibility') return fact.value; + const known = fact?.value ?? fallback; + return declaredChoices(metadata, key, supportKey, feature, known, !!official || !!fact); + }; + const modes = optionValues('modes', 'modeSupport', 'thinking', ['disabled', 'enabled', ...(protocol === 'anthropic-messages' ? ['adaptive', 'between_tools'] : [])]); + const modeFact = field('modes'), effortFact = field('efforts'); + const origin = modeFact?.kind ?? effortFact?.kind; + const sourceKind = origin === 'explicit_compatibility' ? origin : metadata ? 'upstream_model_list' : official ? 'official_model_spec' : 'compatibility_profile'; + const officialFact = [modeFact, effortFact].find(value => value?.kind === 'official_model_spec'); + return { id, label: labels[id], source: sourceKind === 'explicit_compatibility' ? '采用用户显式兼容覆盖;原目录与官方来源另行保留' + : metadata ? '优先采用相符型号的上游目录声明,缺失项再匹配精确官方规格或兼容格式' + : official ? '按供应商、精确型号和协议匹配官方规格' : selected === 'auto' ? '未取得精确型号能力;以下为协议兼容选项,支持情况待确认' : '用户选择的兼容格式,不套用官方型号后备选项', + sourceKind, officialSource: officialFact ? { url: officialFact.url.split('#')[0], effortUrl: effortFact?.url?.split('#')[0] ?? officialFact.url.split('#')[0], checkedAt: officialFact.checkedAt, + provider: provider.id, apiVersion: official?.apiVersion ?? specification.officialRecord?.apiVersion ?? null } : null, + efforts: optionValues('efforts', 'effortSupport', 'effort', choices).filter(value => value !== 'none'), modes, + modeEfforts: field('modeEfforts')?.value ?? {}, defaultMode: field('defaultMode')?.value ?? null, defaultEffort: field('defaultEffort')?.value ?? null, + thinking: protocol === 'anthropic-messages' || id === 'deepseek' && protocol === 'chat-completions', + thinkingBudget: field('request.thinkingBudget')?.value === 'ignored' || id === 'deepseek' ? 'ignored' : protocol === 'anthropic-messages' ? 'required' : 'unknown', + specification }; } export function assertModelParameterSupport(connection, parameters) { - const metadata = !connection.model || connection.upstreamModel?.id === connection.model ? connection.upstreamModel : null; + const metadata = matchingUpstreamModel(connection); if (!metadata) return; + const overrides = connection.modelOverrides ?? {}; const effort = parameters.reasoning_effort ?? parameters.reasoning?.effort ?? parameters.output_config?.effort; const mode = parameters.thinking?.type; - if (effort && (metadata.features?.effort === 'unsupported' || metadata.effortSupport?.[effort] === 'unsupported' || effort !== 'none' && metadata.efforts?.length && !metadata.efforts.includes(effort))) + if (effort && !overrides.efforts?.includes(effort) && overrides.features?.effort !== 'supported' && (metadata.features?.effort === 'unsupported' || metadata.effortSupport?.[effort] === 'unsupported' || effort !== 'none' && (metadata.efforts?.length || metadata.reportedFields?.includes('efforts')) && !metadata.efforts.includes(effort))) throw Object.assign(new Error('上游目录声明该型号不支持所选推理强度,请选择支持的档位或保留默认。'), { status: 400 }); - if (mode && (metadata.features?.thinking === 'unsupported' || metadata.modeSupport?.[mode] === 'unsupported' || metadata.modes?.length && !metadata.modes.includes(mode))) + if (mode && !overrides.modes?.includes(mode) && overrides.features?.thinking !== 'supported' && (metadata.features?.thinking === 'unsupported' || metadata.modeSupport?.[mode] === 'unsupported' || (metadata.modes?.length || metadata.reportedFields?.includes('modes')) && !metadata.modes.includes(mode))) throw Object.assign(new Error('上游目录声明该型号不支持所选推理模式,请选择支持的模式或保留默认。'), { status: 400 }); } @@ -92,9 +111,10 @@ export function changeReasoningSetting(connection, parameters, field, value) { } } else if (profile.thinking) { - editObject('thinking', value === 'enabled' && protocol === 'anthropic-messages' + const budgetRequired = value === 'enabled' && profile.thinkingBudget === 'required'; + editObject('thinking', budgetRequired ? { type: value, budget_tokens: parameters.thinking?.budget_tokens ?? 1024 } : { type: value }, - value === 'enabled' && protocol === 'anthropic-messages' ? [] : ['budget_tokens']); + value === 'enabled' ? [] : ['budget_tokens']); } else { setEffort(value === 'disabled' ? 'none' : reasoningSetting(connection, parameters).effort || (profile.efforts.includes('medium') ? 'medium' : profile.efforts[0] ?? '')); } @@ -104,14 +124,17 @@ export function changeReasoningSetting(connection, parameters, field, value) { export function modelFeatureRows(connection) { const states = { supported: '声明支持', unsupported: '声明不支持', unknown: '待确认', verified: '已验证', protocol_declared: '声明支持' }; - const declared = key => states[connection.capabilities?.[key] ?? connection.capabilityDeclarations?.[key] ?? 'unknown'] ?? '待确认'; + const specification = resolveModelSpecification(connection); + const declared = key => states[connection.capabilities?.[key] ?? specification.fields['capabilities.' + key]?.value ?? 'unknown'] ?? '待确认'; + const feature = key => states[specification.fields['features.' + key]?.value ?? 'unknown']; return [ { name: '文本 / 工具调用', upstream: declared('text') + ' / ' + declared('tools'), local: '已接入,可单独检测' }, { name: '流式输出', upstream: declared('streaming'), local: '已接入,按连接开关发送' }, { name: '图像输入', upstream: declared('vision'), local: '已接入 PNG,可单独检测' }, { name: '推理模式 / 强度', upstream: modelParameterProfile(connection).source, local: '按原生字段发送;本地默认不限,协议条件以上游为准' }, { name: '语音 / 视频 / 服务端工具', upstream: '需供应商提供相应协议', local: '尚未接入' }, - { name: '结构化输出约束', upstream: states[connection.upstreamModel?.features?.structured_outputs ?? 'unknown'], local: '开放模式可透传约束参数;完整结果校验流程待接入' }, - ...(connection.upstreamModel ? [{ name: 'PDF / 服务端工具 / 批处理', upstream: ['pdf_input', 'server_tools', 'batch'].map(key => states[connection.upstreamModel.features?.[key] ?? 'unknown']).join(' / '), local: '目录声明已同步,执行能力尚未接入' }] : []), + { name: '结构化输出约束', upstream: feature('structured_outputs'), local: '开放模式可透传约束参数;完整结果校验流程待接入' }, + { name: 'PDF / 服务端工具 / 批处理', upstream: ['pdf_input', 'server_tools', 'batch'].map(feature).join(' / '), local: '来源声明已同步,执行能力尚未接入' }, + { name: '提示缓存', upstream: feature('prompt_caching'), local: '自动前缀缓存用量已记录;显式缓存块接入另行验证' }, ]; } diff --git a/src/shared/contracts/model-routing.mjs b/src/shared/contracts/model-routing.mjs index f66577bf..2c8e98b6 100644 --- a/src/shared/contracts/model-routing.mjs +++ b/src/shared/contracts/model-routing.mjs @@ -1,4 +1,5 @@ import { capabilityView } from './model-capabilities.mjs'; +import { matchingUpstreamModel, resolveModelSpecification } from './official-model-registry.mjs'; // This is an automatic-selection policy, not a gate on an explicitly selected // connection. Keep the observations bound to the frozen member/revisions. @@ -8,24 +9,30 @@ export function modelRoutingDecision(routing, requirements, { open = false, prob const candidates = routing.members.map(member => { const required = probe ? [] : [...new Set([...requirements, ...(member.streaming ? ['streaming'] : [])])]; const view = capabilityView(member, member.credentialRevision); - const upstream = member.upstreamModel; - const catalog = upstream?.id === member.model && (!upstream.endpoint || upstream.endpoint === member.baseUrl) ? upstream : null; + const specification = resolveModelSpecification(member, member.credentialRevision), catalog = matchingUpstreamModel(member); const capabilities = Object.fromEntries(required.map(capability => { let state = view[capability] ?? 'unknown'; - let source = state === 'verified' ? 'revision-bound-observation' : state === 'unknown' ? 'unknown' : 'connection-declaration'; - if (automatic && catalog?.capabilityDeclarations?.[capability] === 'unsupported') { + const fact = specification.fields['capabilities.' + capability]; + let source = state === 'unknown' ? 'unknown' : ({ revision_bound_observation: 'revision-bound-observation', upstream_catalog: 'upstream-model-list', official_model_spec: 'official-model-spec', + explicit_compatibility: 'explicit-compatibility', protocol_declaration: 'protocol-declaration' }[fact?.kind] ?? 'connection-declaration'); + if (state === 'protocol_declared' && fact?.kind === 'upstream_catalog') state = 'upstream_declared'; + if (state === 'protocol_declared' && fact?.kind === 'official_model_spec') state = 'official_declared'; + if (automatic && catalog?.capabilityDeclarations?.[capability] === 'unsupported' && fact?.kind !== 'explicit_compatibility' && state !== 'verified') { state = 'unsupported'; source = 'upstream-model-list'; } else if (automatic && state === 'unknown' && catalog?.capabilityDeclarations?.[capability] === 'supported') { state = 'upstream_declared'; source = 'upstream-model-list'; } - return [capability, { state, source }]; + return [capability, { state, source, ...(fact ? { specification: { kind: fact.kind, conflict: fact.conflict, sourceId: fact.sourceId ?? null, apiVersion: fact.apiVersion ?? null, url: fact.url ?? null } } : {}) }]; })); const reasons = required.filter(capability => capabilities[capability].state === 'unsupported' || !passthrough && !automatic && capabilities[capability].state === 'unknown') .map(capability => ({ capability, ...capabilities[capability], reason: capabilities[capability].state === 'unsupported' ? '明确声明不支持所需能力' : '尚未声明或验证所需能力' })); - if (automatic && catalog?.lifecycle === 'retired') reasons.push({ capability: 'lifecycle', state: 'retired', source: 'upstream-model-list', reason: '相符上游目录已标记型号退役' }); + const lifecycle = specification.fields.lifecycle; + if (automatic && lifecycle?.value === 'retired') reasons.push({ capability: 'lifecycle', state: 'retired', source: lifecycle.kind === 'upstream_catalog' ? 'upstream-model-list' : lifecycle.kind, + reason: '当前型号来源已标记退役' }); const unavailable = availability(member); return { connectionId: member.id, connectionName: member.name, model: member.model, protocol: member.protocol ?? 'chat-completions', connectionRevision: member.revision, credentialRevision: member.credentialRevision, requirements: required, capabilities, + registryVersion: specification.registryVersion, officialRecord: specification.officialRecord, ...(catalog ? { catalog: { id: catalog.id, fetchedAt: catalog.fetchedAt ?? null, lifecycle: catalog.lifecycle ?? null, source: 'upstream-model-list' } } : {}), tier: passthrough ? 'passthrough' : reasons.length ? 'unsupported' : Object.values(capabilities).some(value => value.state === 'unknown') ? 'unverified' : 'known', reasons, unavailable, disposition: unavailable ? 'unavailable' : !passthrough && reasons.length ? 'excluded' : 'eligible' }; diff --git a/src/shared/contracts/official-model-capacity.mjs b/src/shared/contracts/official-model-capacity.mjs index 88c0a307..edf8d692 100644 --- a/src/shared/contracts/official-model-capacity.mjs +++ b/src/shared/contracts/official-model-capacity.mjs @@ -1,12 +1,18 @@ -// Exact pinned IDs from Anthropic's Models overview, checked 2026-11-06. -// These are synchronous Messages declarations, not measured gateway limits. -// The separate 300K Message Batches beta is not used for ordinary requests. -const sourceUrl = 'https://platform.claude.com/docs/en/models/overview'; -const claude = Object.freeze(Object.fromEntries([ - 'claude-fable-5-1', 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', -].map(model => [model, Object.freeze({ model, contextLimit: 1000000, maxOutputTokens: 128000, - sourceUrl, checkedAt: '2026-11-06', source: 'official_model_spec' })]))); +import { modelRegistry, officialModelRecord } from './official-model-registry.mjs'; -export function officialModelCapacity(model) { - return typeof model === 'string' && Object.hasOwn(claude, model) ? claude[model] : null; +// Capacity is a published model reference, independent of whether the selected +// gateway/protocol was actually validated. Retain the legacy model-only view. +export function officialModelCapacity(model, options = {}) { + if (typeof model !== 'string') return null; + let entry = officialModelRecord({ model, ...options }); + if (!entry && !options.providerId && !options.apiVersion) { + const rows = modelRegistry.records.filter(value => value.model === model); + if (rows.length && new Set(rows.map(value => JSON.stringify([value.fields.contextLimit?.value, value.fields.maxOutputTokens?.value]))).size === 1) entry = rows[0]; + } + const capacity = entry?.fields.contextLimit, output = entry?.fields.maxOutputTokens; + if (!capacity && !output) return null; + const source = modelRegistry.sources.find(value => value.id === (capacity ?? output).source); + return { model, contextLimit: capacity?.value ?? null, maxOutputTokens: output?.value ?? null, + sourceUrl: source.url, checkedAt: source.checkedAt, source: 'official_model_spec', + provider: entry.provider, protocol: entry.protocol, apiVersion: entry.apiVersion, registryVersion: modelRegistry.version, sourceSha256: source.sha256 }; } diff --git a/src/shared/contracts/official-model-parameters.mjs b/src/shared/contracts/official-model-parameters.mjs index a7ecc19a..cbedbc35 100644 --- a/src/shared/contracts/official-model-parameters.mjs +++ b/src/shared/contracts/official-model-parameters.mjs @@ -1,20 +1,12 @@ -// Exact Messages IDs checked against Anthropic's thinking and effort articles -// on 2026-11-06. These are published defaults, not proof of proxy support. -// Broader provider/version discovery belongs to the capability registry. -const sourceUrl = 'https://platform.claude.com/docs/en/build-with-claude/thinking'; -const effortSourceUrl = 'https://platform.claude.com/docs/en/build-with-claude/effort'; -const efforts = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']); -const lowerEfforts = Object.freeze(['low', 'medium', 'high']); -const entries = [ - ['claude-fable-5-1', ['adaptive'], 'high', {}], - ['claude-opus-5-5', ['adaptive'], 'medium', {}], - ['claude-sonnet-5-5', ['adaptive', 'between_tools'], 'high', { between_tools: lowerEfforts }], - ['claude-haiku-5-5', ['disabled', 'adaptive'], 'medium', { disabled: lowerEfforts }], -]; -const models = Object.freeze(Object.fromEntries(entries.map(([model, modes, defaultEffort, modeEfforts]) => [model, - Object.freeze({ model, modes: Object.freeze(modes), efforts, defaultMode: 'adaptive', defaultEffort, modeEfforts: Object.freeze(modeEfforts), - sourceUrl, effortSourceUrl, checkedAt: '2026-11-06', source: 'official_model_spec' })]))); +import { modelRegistry, officialModelRecord } from './official-model-registry.mjs'; +// Retained exact Anthropic view. The registry owns the reviewed options and +// conditional combinations, so old helpers and new UI use the same facts. export function officialModelParameters(model) { - return typeof model === 'string' && Object.hasOwn(models, model) ? models[model] : null; + const entry = officialModelRecord({ model, providerId: 'anthropic', protocol: 'anthropic-messages' }); + if (!entry) return null; + const field = key => entry.fields[key]?.value; + const source = key => modelRegistry.sources.find(value => value.id === entry.fields[key]?.source); + return { model, modes: field('modes'), efforts: field('efforts'), defaultMode: field('defaultMode'), defaultEffort: field('defaultEffort'), modeEfforts: field('modeEfforts') ?? {}, + sourceUrl: source('modes')?.url, effortSourceUrl: source('efforts')?.url, checkedAt: source('modes')?.checkedAt, source: 'official_model_spec' }; } diff --git a/src/shared/contracts/official-model-registry-data.mjs b/src/shared/contracts/official-model-registry-data.mjs new file mode 100644 index 00000000..43e1d98c --- /dev/null +++ b/src/shared/contracts/official-model-registry-data.mjs @@ -0,0 +1,77 @@ +// Reviewed exact IDs and protocol conditions from the pinned official sources. +// A declaration here never means that a particular credential/route was tested. +const fact = (value, source, anchor = '') => ({ value, source, anchor }); +const record = (provider, protocol, apiVersion, model, fields) => ({ provider, protocol, apiVersion, model, fields }); + +const openaiModels = [ + { model: 'gpt-6-astra', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: null }, + { model: 'gpt-6-sol', efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'medium', chatTools: 'reasoning-none' }, + { model: 'gpt-6-luna', efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'medium', chatTools: 'reasoning-none' }, + { model: 'gpt-6.1-sol', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'medium', chatTools: 'responses-only' }, + { model: 'gpt-6.1-terra', efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'medium', chatTools: 'responses-only' }, +]; +const nativeTools = ['web_search', 'file_search', 'image_generation', 'code_interpreter', 'hosted_shell', 'apply_patch', 'skills', 'computer_use', 'mcp', 'tool_search']; +const openai = openaiModels.flatMap(item => ['chat-completions', 'responses'].map(protocol => { + const source = 'openai-' + item.model, value = (data, anchor) => fact(data, source, anchor); + return record('openai', protocol, 'v1', item.model, { + contextLimit: value(1050000, 'current-snapshot-details'), maxInputTokens: value(922000, 'current-snapshot-details'), maxOutputTokens: value(128000, 'current-snapshot-details'), + 'capabilities.text': value('supported', 'current-snapshot-details'), 'capabilities.vision': value('supported', 'current-snapshot-details'), + 'capabilities.tools': value(protocol === 'chat-completions' && item.chatTools === 'responses-only' ? 'unsupported' : 'supported', ''), + 'capabilities.streaming': value('supported', 'current-snapshot-details'), + 'features.thinking': value('supported', ''), 'features.effort': value('supported', ''), + 'features.structured_outputs': value('supported', 'current-snapshot-details'), 'features.prompt_caching': value('supported', 'current-snapshot-details'), + inputModalities: value(['text', 'image'], 'current-snapshot-details'), outputModalities: value(['text'], 'current-snapshot-details'), + efforts: value(item.efforts, ''), modes: value(item.efforts.includes('none') ? ['disabled', 'enabled'] : ['enabled'], ''), + defaultEffort: value(item.defaultEffort, ''), + ...(protocol === 'responses' ? { nativeTools: value(nativeTools, 'supported-tools') } : {}), + ...(protocol === 'chat-completions' && item.chatTools ? { toolsCondition: value(item.chatTools, '') } : {}), + }); +})); + +const claudeModels = [ + ['claude-fable-5-1', ['adaptive'], 'high', {}], + ['claude-opus-5-5', ['adaptive'], 'medium', {}], + ['claude-sonnet-5-5', ['adaptive', 'between_tools'], 'high', { between_tools: ['low', 'medium', 'high'] }], + ['claude-haiku-5-5', ['disabled', 'adaptive'], 'medium', { disabled: ['low', 'medium', 'high'] }], +]; +const claude = claudeModels.map(([model, modes, defaultEffort, modeEfforts]) => { + const overview = value => fact(value, 'claude-models__overview', 'latest-models-comparison'); + const thinking = value => fact(value, 'claude-build-with-claude__thinking', 'configuring-thinking'); + const effort = value => fact(value, 'claude-effort', 'effort-levels'); + return record('anthropic', 'anthropic-messages', '2026-10-21', model, { + contextLimit: overview(1000000), maxOutputTokens: overview(128000), + 'capabilities.text': overview('supported'), 'capabilities.tools': overview('supported'), 'capabilities.vision': overview('supported'), + inputModalities: overview(['text', 'image']), outputModalities: overview(['text']), + 'features.thinking': thinking('supported'), 'features.effort': effort('supported'), + modes: thinking(modes), efforts: effort(['low', 'medium', 'high', 'xhigh', 'max']), modeEfforts: thinking(modeEfforts), + defaultMode: thinking('adaptive'), defaultEffort: fact(defaultEffort, 'claude-build-with-claude__thinking-steering-and-cost', 'effort-levels'), + 'features.prompt_caching': fact('supported', 'claude-build-with-claude__prompt-caching', ''), + }); +}); + +const deepseek = ['deepseek-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'deepseek-v4-flash-vision-exp'].flatMap(model => ['chat-completions', 'responses', 'anthropic-messages'].map(protocol => { + const flash = model !== 'deepseek-v4-pro', alias = !['deepseek-flash', 'deepseek-v4-pro'].includes(model); + const limits = value => fact(value, 'deepseek-model-list', ''), pricing = value => fact(value, 'deepseek-models', 'model-details'); + const protocolSource = protocol === 'anthropic-messages' ? 'deepseek-message' : protocol === 'responses' ? 'deepseek-response' : 'deepseek-create'; + const native = value => fact(value, protocolSource, ''); + return record('deepseek', protocol, protocol === 'anthropic-messages' ? '2023-06-01' : 'v1', model, { + contextLimit: limits(1048576), maxOutputTokens: limits(393216), + 'capabilities.text': pricing('supported'), 'capabilities.tools': pricing('supported'), 'capabilities.vision': pricing(flash ? 'supported' : 'unsupported'), + inputModalities: limits(flash ? ['text', 'image'] : ['text']), outputModalities: limits(['text']), + 'features.thinking': native('supported'), 'features.effort': native('supported'), + efforts: limits(['low', 'high', 'max']), defaultEffort: limits('high'), + modes: native(protocol === 'anthropic-messages' ? ['disabled', 'enabled', 'adaptive'] : ['disabled', 'enabled']), + defaultMode: native('enabled'), + 'features.prompt_caching': fact('supported', 'deepseek-cache', ''), + ...(protocol === 'anthropic-messages' ? { + 'request.systemPromptUpdate': limits(flash ? 'in-history' : 'leading-only'), + 'request.versionHandling': native('ignored'), + 'request.thinkingBudget': native('ignored'), + 'features.structured_outputs': native('unsupported'), + } : { 'features.structured_outputs': native(protocol === 'responses' ? 'supported' : 'unsupported'), 'features.json_output': native('supported') }), + 'request.maxTokensRequired': native(false), + ...(alias ? { lifecycle: pricing('deprecated'), aliasOf: pricing('deepseek-flash'), 'request.aliasAccepted': pricing(true), 'request.originalModelRetired': pricing(true) } : {}), + }); +})); + +export const officialModelRecords = [...openai, ...claude, ...deepseek]; diff --git a/src/shared/contracts/official-model-registry.d.mts b/src/shared/contracts/official-model-registry.d.mts new file mode 100644 index 00000000..5594c2ef --- /dev/null +++ b/src/shared/contracts/official-model-registry.d.mts @@ -0,0 +1,13 @@ +export interface ModelSpecField { value: unknown; kind: string; note?: string; provider?: string; apiVersion?: string; url?: string | null; checkedAt?: string | null; sha256?: string | null; sourceId?: string; alternatives: Omit[]; conflict: boolean } +export interface ModelSpecification { schemaVersion: number; registryVersion: string; model: string; protocol: string; provider: string | null; providerSource: string; apiVersion: string | null; officialRecord: { provider: string; protocol: string; apiVersion: string; model: string } | null; fields: Record; conflicts: string[]; liveCompatibility: string } +export interface ModelSpecConnection { model?: string; protocol?: string; baseUrl?: string; providerId?: string; apiVersion?: string; nativeParameters?: Record; modelOverrides?: Record; modelSpecification?: ModelSpecification; modelSpecificationFrozen?: boolean; upstreamModel?: import('./model-catalog.mjs').CatalogModel; capabilityDeclarations?: Record; capabilityDeclarationSources?: Record; credentialRevision?: number; revision?: number; capabilityEvidence?: { connectionRevision?: number; credentialRevision?: number; results?: Record; checkedAt?: string } } +export const MODEL_REGISTRY_SCHEMA: number; +export const MODEL_REGISTRY_VERSION: string; +export const modelRegistry: Readonly<{ schemaVersion: number; version: string; sources: readonly { id: string; provider: string; url: string; checkedAt: string; sha256: string }[]; records: readonly { provider: string; protocol: string; apiVersion: string; model: string; fields: Record }[] }>; +export function validateModelRegistry(input: unknown): unknown; +export function modelProvider(connection?: ModelSpecConnection): { id: string | null; source: string }; +export function officialModelRecord(connection?: ModelSpecConnection): (typeof modelRegistry.records)[number] | null; +export function matchingUpstreamModel(connection?: ModelSpecConnection): import('./model-catalog.mjs').CatalogModel | null; +export function modelOverrideSettings(input?: unknown, previous?: Record): Record; +export function resolveModelSpecification(connection?: ModelSpecConnection, credentialRevision?: number): ModelSpecification; +export function specificationField(connection: ModelSpecConnection, field: string): ModelSpecField | null; diff --git a/src/shared/contracts/official-model-registry.mjs b/src/shared/contracts/official-model-registry.mjs new file mode 100644 index 00000000..d0ac0843 --- /dev/null +++ b/src/shared/contracts/official-model-registry.mjs @@ -0,0 +1,153 @@ +import sources from './official-model-sources.json' with { type: 'json' }; +import { officialModelRecords } from './official-model-registry-data.mjs'; + +export const MODEL_REGISTRY_SCHEMA = 1; +export const MODEL_REGISTRY_VERSION = sources.registryVersion; +const capabilities = ['text', 'tools', 'streaming', 'vision', 'audio']; +const providers = { 'api.openai.com': 'openai', 'api.anthropic.com': 'anthropic', 'api.deepseek.com': 'deepseek', 'api.moonshot.ai': 'moonshot', 'api.moonshot.cn': 'moonshot', 'generativelanguage.googleapis.com': 'google' }; +const state = value => ['supported', 'unsupported', 'unknown'].includes(value); +const officialHosts = { openai: ['developers.openai.com', 'platform.openai.com', 'learn.chatgpt.com'], anthropic: ['platform.claude.com', 'docs.anthropic.com', 'docs.claude.com'], deepseek: ['api-docs.deepseek.com'], google: ['ai.google.dev', 'cloud.google.com', 'docs.cloud.google.com'], moonshot: ['platform.moonshot.ai', 'platform.moonshot.cn'] }; +const stringList = value => Array.isArray(value) && value.every(item => typeof item === 'string' && item && !/[\x00-\x1f\x7f]/.test(item)); +const failure = message => Object.assign(new Error(message), { status: 400 }); +function jsonValue(value, active = new Set()) { + if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' && Number.isFinite(value)) return true; + if (!value || typeof value !== 'object' || active.has(value) || !Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return false; + active.add(value); const valid = Object.values(value).every(item => jsonValue(item, active)); active.delete(value); return valid; +} +const freeze = value => { if (value && typeof value === 'object' && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); } return value; }; + +export function validateModelRegistry(input) { + if (!jsonValue(input) || input?.schemaVersion !== MODEL_REGISTRY_SCHEMA || typeof input.version !== 'string' || !input.version || !Array.isArray(input.records) || !Array.isArray(input.sources)) throw failure('模型注册表版本或结构无效。'); + const ids = new Set(), sourceIds = new Map(); + for (const source of input.sources) { + if (!source || typeof source !== 'object' || Array.isArray(source)) throw failure('官方来源记录结构无效。'); + let url; try { url = new URL(source.url); } catch { throw failure('官方来源地址无效。'); } + if (typeof source.id !== 'string' || !source.id || sourceIds.has(source.id) || url.protocol !== 'https:' || url.username || url.password || !officialHosts[source.provider]?.includes(url.hostname) + || !/^[a-f0-9]{64}$/.test(source.sha256) || !/^\d{4}-\d{2}-\d{2}$/.test(source.checkedAt) || !Number.isFinite(Date.parse(source.checkedAt))) throw failure('官方来源标识、供应商地址、日期或 SHA256 无效。'); + sourceIds.set(source.id, source.provider); + } + for (const entry of input.records) { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw failure('官方型号记录结构无效。'); + const id = JSON.stringify([entry.provider, entry.protocol, entry.apiVersion, entry.model]); + if (ids.has(id) || [entry.provider, entry.protocol, entry.apiVersion, entry.model].some(value => typeof value !== 'string' || !value || /[\x00-\x1f\x7f]/.test(value)) || !entry.fields || typeof entry.fields !== 'object' || Array.isArray(entry.fields)) throw failure('官方型号、协议、版本或重复记录无效。'); + ids.add(id); + for (const [key, field] of Object.entries(entry.fields)) { + if (!key || !field || sourceIds.get(field.source) !== entry.provider || !jsonValue(field.value) || field.anchor !== undefined && typeof field.anchor !== 'string') throw failure('官方字段必须引用所属供应商的已固定来源并保存合法 JSON 值。'); + if (['contextLimit', 'maxInputTokens', 'maxOutputTokens'].includes(key) && field.value !== null && (!Number.isSafeInteger(field.value) || field.value < 1)) throw failure('官方容量字段需要正安全整数或明确未知。'); + if (/^(?:capabilities|features)\./.test(key) && !state(field.value)) throw failure('官方能力字段只能声明支持、不支持或未知。'); + if (['efforts', 'modes', 'inputModalities', 'outputModalities', 'nativeTools'].includes(key) && !stringList(field.value)) throw failure('官方模型选项必须保存字符串数组。'); + if (['defaultMode', 'defaultEffort', 'aliasOf'].includes(key) && field.value !== null && (typeof field.value !== 'string' || !field.value)) throw failure('官方默认选项或别名无效。'); + if (key === 'modeEfforts' && (!field.value || typeof field.value !== 'object' || Array.isArray(field.value) || Object.values(field.value).some(value => !stringList(value)))) throw failure('官方模式强度组合无效。'); + if (key === 'lifecycle' && !['active', 'deprecated', 'retired', 'unknown'].includes(field.value)) throw failure('官方模型生命周期无效。'); + } + } + return input; +} + +export const modelRegistry = freeze(validateModelRegistry({ schemaVersion: MODEL_REGISTRY_SCHEMA, version: MODEL_REGISTRY_VERSION, sources: sources.sources, records: officialModelRecords })); +const sourceMap = new Map(modelRegistry.sources.map(source => [source.id, source])); + +export function modelProvider(connection = {}) { + if (connection.providerId && !['auto', 'custom'].includes(connection.providerId)) return { id: connection.providerId, source: 'explicit-provider' }; + if (connection.providerId !== 'custom') { + try { const id = providers[new URL(connection.baseUrl).hostname]; if (id) return { id, source: 'official-endpoint' }; } catch { /* Unfinished draft or absent endpoint. */ } + } + const exact = [...new Set(modelRegistry.records.filter(entry => entry.model === connection.model).map(entry => entry.provider))]; + return { id: exact.length === 1 ? exact[0] : null, source: exact.length === 1 ? 'exact-model-reference' : 'unknown' }; +} + +export function officialModelRecord(connection = {}) { + const provider = modelProvider(connection), protocol = connection.protocol ?? 'chat-completions'; + const rows = modelRegistry.records.filter(entry => entry.provider === provider.id && entry.model === connection.model && entry.protocol === protocol); + if (connection.apiVersion && connection.apiVersion !== 'auto') return rows.find(entry => entry.apiVersion === connection.apiVersion + || entry.fields['request.versionHandling']?.value === 'ignored') ?? null; + return rows.length === 1 ? rows[0] : null; +} + +export function matchingUpstreamModel(connection = {}) { + const item = connection.upstreamModel; + return item?.id === connection.model && (!item.endpoint || item.endpoint === connection.baseUrl) ? item : null; +} + +export function modelOverrideSettings(input, previous = {}) { + if (input === undefined) return structuredClone(previous); + if (!input || typeof input !== 'object' || Array.isArray(input) || !jsonValue(input)) throw failure('模型兼容覆盖需要合法 JSON 对象。'); + const result = {}; + for (const [key, value] of Object.entries(input)) { + if (['contextLimit', 'maxInputTokens', 'maxOutputTokens'].includes(key)) { + if (value !== null && (!Number.isSafeInteger(value) || value < 1)) throw failure('模型容量覆盖需要正安全整数或 null(未知)。'); + } else if (['efforts', 'modes', 'inputModalities', 'outputModalities', 'nativeTools'].includes(key)) { + if (!stringList(value)) throw failure('模型选项覆盖需要字符串数组。'); + } else if (['capabilities', 'features'].includes(key)) { + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item => !state(item)) || key === 'capabilities' && Object.keys(value).some(item => !capabilities.includes(item))) throw failure('能力覆盖只能声明支持、不支持或未知。'); + } else if (['defaultMode', 'defaultEffort', 'lifecycle', 'note'].includes(key)) { + if (value !== null && typeof value !== 'string') throw failure('模型默认选项或备注格式无效。'); + if (key === 'lifecycle' && !['active', 'deprecated', 'retired', 'unknown', null].includes(value)) throw failure('模型生命周期覆盖无效。'); + } else if (key === 'modeEfforts') { + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item => !Array.isArray(item) || item.some(level => typeof level !== 'string'))) throw failure('模式强度组合覆盖格式无效。'); + } else throw failure('不支持的模型规格覆盖字段:' + key); + Object.defineProperty(result, key, { value: structuredClone(value), enumerable: true, writable: true, configurable: true }); + } + return result; +} + +function catalogFacts(item) { + if (!item) return {}; + const fields = {}; + for (const key of ['contextLimit', 'maxInputTokens', 'maxOutputTokens', 'lifecycle', 'defaultEffort', 'defaultMode', 'inputModalities', 'outputModalities', 'nativeTools']) if (item[key] !== null && item[key] !== undefined) fields[key] = item[key]; + for (const [key, value] of Object.entries(item.capabilityDeclarations ?? {})) if (value !== 'unknown') fields['capabilities.' + key] = value; + for (const [key, value] of Object.entries(item.features ?? {})) if (value !== 'unknown') fields['features.' + key] = value; + for (const key of ['efforts', 'modes']) if (item[key]?.length || item.reportedFields?.includes(key) || item.features?.[key === 'efforts' ? 'effort' : 'thinking'] === 'unsupported') fields[key] = item[key] ?? []; + if (item.modeEfforts) fields.modeEfforts = item.modeEfforts; + if (item.apiCapabilities?.anthropic_messages?.system_prompt_update) fields['request.systemPromptUpdate'] = item.apiCapabilities.anthropic_messages.system_prompt_update; + return fields; +} + +function overrideFacts(value) { + const fields = {}; + for (const [key, item] of Object.entries(value ?? {})) if (['capabilities', 'features'].includes(key)) { + for (const [name, data] of Object.entries(item)) fields[key + '.' + name] = data; + } else if (key !== 'note') fields[key] = item; + return fields; +} + +export function resolveModelSpecification(connection = {}, credentialRevision = connection.credentialRevision ?? 0) { + if (connection.modelSpecificationFrozen === true && connection.modelSpecification?.model === connection.model && connection.modelSpecification.protocol === (connection.protocol ?? 'chat-completions')) return structuredClone(connection.modelSpecification); + const provider = modelProvider(connection), entry = officialModelRecord(connection), catalog = matchingUpstreamModel(connection); + const candidates = new Map(), add = (key, value, origin) => { + const values = candidates.get(key) ?? []; + values.push({ value: structuredClone(value), ...origin }); candidates.set(key, values); + }; + const explicit = { kind: 'explicit_compatibility', note: connection.modelOverrides?.note ?? '用户显式兼容覆盖' }; + for (const [key, value] of Object.entries(overrideFacts(connection.modelOverrides))) add(key, value, explicit); + // Legacy declarations have no trustworthy edit provenance. Preserve them as + // explicit legacy settings, rather than guessing which ones were defaults. + for (const [key, value] of Object.entries(connection.capabilityDeclarations ?? {})) { + const origin = connection.capabilityDeclarationSources?.[key] ?? 'legacy_connection'; + if (['user', 'legacy_connection'].includes(origin) && value !== 'unknown') add('capabilities.' + key, value, { kind: origin === 'user' ? 'connection_declaration' : 'legacy_connection_declaration' }); + } + const evidence = connection.capabilityEvidence; + const current = evidence?.connectionRevision === connection.revision && evidence?.credentialRevision === credentialRevision; + if (current) for (const key of capabilities) if (evidence.results?.[key] === 'verified') add('capabilities.' + key, 'supported', { kind: 'revision_bound_observation', checkedAt: evidence.checkedAt ?? null, connectionRevision: connection.revision, credentialRevision }); + for (const [key, value] of Object.entries(catalogFacts(catalog))) add(key, value, { kind: 'upstream_catalog', url: catalog.endpoint ?? null, checkedAt: catalog.fetchedAt ?? null, sha256: catalog.rawSha256 ?? null }); + if (entry) for (const [key, field] of Object.entries(entry.fields)) { + const source = sourceMap.get(field.source); + let value = field.value; + if (key === 'capabilities.tools' && entry.fields.toolsCondition?.value === 'reasoning-none') value = connection.nativeParameters?.reasoning_effort === 'none' ? 'supported' : 'unsupported'; + add(key, value, { kind: 'official_model_spec', provider: entry.provider, apiVersion: entry.apiVersion, url: source.url + (field.anchor ? '#' + field.anchor : ''), checkedAt: source.checkedAt, sha256: source.sha256, sourceId: source.id }); + } + for (const [key, value] of Object.entries(connection.capabilityDeclarations ?? {})) if (!candidates.has('capabilities.' + key) && value !== 'unknown') add('capabilities.' + key, value, { kind: 'protocol_declaration' }); + const fields = Object.fromEntries([...candidates].map(([key, values]) => { + // Verified observations can strengthen support, but do not override an + // explicit denial. Keep every conflicting declaration in the result. + const selected = key.startsWith('capabilities.') && values[0].value === 'supported' ? values.find(value => value.kind === 'revision_bound_observation') ?? values[0] : values[0]; + return [key, { ...selected, alternatives: values.filter(value => value !== selected), conflict: values.some(value => JSON.stringify(value.value) !== JSON.stringify(selected.value)) }]; + })); + return { schemaVersion: MODEL_REGISTRY_SCHEMA, registryVersion: MODEL_REGISTRY_VERSION, model: connection.model ?? '', protocol: connection.protocol ?? 'chat-completions', + provider: provider.id, providerSource: provider.source, apiVersion: connection.apiVersion && connection.apiVersion !== 'auto' ? connection.apiVersion : entry?.apiVersion ?? null, + officialRecord: entry ? { provider: entry.provider, protocol: entry.protocol, apiVersion: entry.apiVersion, model: entry.model } : null, + fields, conflicts: Object.entries(fields).filter(([, value]) => value.conflict).map(([key]) => key), + liveCompatibility: 'not_established_by_registry' }; +} + +export function specificationField(connection, field) { return resolveModelSpecification(connection).fields[field] ?? null; } diff --git a/src/shared/contracts/official-model-sources.json b/src/shared/contracts/official-model-sources.json new file mode 100644 index 00000000..661d6178 --- /dev/null +++ b/src/shared/contracts/official-model-sources.json @@ -0,0 +1,194 @@ +{ + "schemaVersion": 1, + "registryVersion": "2026-11-07.1", + "sources": [ + { + "id": "claude-models__overview", + "provider": "anthropic", + "url": "https://platform.claude.com/docs/en/models/overview", + "checkedAt": "2026-11-06", + "sha256": "58a0bd14d9badfe29071397995bc87c1ced653a8b0acde20d34d85e3a9df5562", + "file": "sources/claude-models-overview.md", + "originalSha256": "04ced1978ad32f6015dfd82c4b4a89812f673411d4d0bd10aedb2957431d9907", + "representation": "extracted-official-markdown", + "scope": "complete-target-article-excerpt" + }, + { + "id": "claude-build-with-claude__thinking", + "provider": "anthropic", + "url": "https://platform.claude.com/docs/en/build-with-claude/thinking", + "checkedAt": "2026-11-06", + "sha256": "ff24b4c309610835c57611e4f5b6f8870b27950a8d4548bfae680c9eec1dfb42", + "file": "sources/claude-build-with-claude-thinking.md", + "originalSha256": "ff24b4c309610835c57611e4f5b6f8870b27950a8d4548bfae680c9eec1dfb42", + "representation": "extracted-official-markdown", + "scope": "complete-captured-source" + }, + { + "id": "claude-build-with-claude__thinking-steering-and-cost", + "provider": "anthropic", + "url": "https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost", + "checkedAt": "2026-11-06", + "sha256": "28b1226b41557efa8d43e3eb28aa038c70b96866939bf1e7cbfd976d82482854", + "file": "sources/claude-build-with-claude-thinking-steering-and-cost.md", + "originalSha256": "28b1226b41557efa8d43e3eb28aa038c70b96866939bf1e7cbfd976d82482854", + "representation": "extracted-official-markdown", + "scope": "complete-captured-source" + }, + { + "id": "claude-build-with-claude__prompt-caching", + "provider": "anthropic", + "url": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching", + "checkedAt": "2026-11-06", + "sha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d", + "file": "sources/claude-build-with-claude-prompt-caching.md", + "originalSha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d", + "representation": "extracted-official-markdown", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-create", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/api/create-chat-completion", + "checkedAt": "2026-11-06", + "sha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f", + "file": "sources/deepseek-create.body", + "originalSha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f", + "representation": "received-html-bytes", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-thinking", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/guides/thinking_mode", + "checkedAt": "2026-11-06", + "sha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd", + "file": "sources/deepseek-thinking.body", + "originalSha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd", + "representation": "received-html-bytes", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-cache", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/guides/kv_cache", + "checkedAt": "2026-11-06", + "sha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081", + "file": "sources/deepseek-cache.body", + "originalSha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081", + "representation": "received-html-bytes", + "scope": "complete-captured-source" + }, + { + "id": "openai-gpt-6.1-sol", + "provider": "openai", + "url": "https://developers.openai.com/api/docs/models/gpt-6.1-sol", + "checkedAt": "2026-11-07", + "sha256": "a128083565678e6a47a74a737a891a7df050309df19925db6902535fcb1f5f23", + "file": "sources/openai-gpt-6.1-sol.md", + "originalSha256": "a128083565678e6a47a74a737a891a7df050309df19925db6902535fcb1f5f23", + "representation": "official-documentation-tool-text", + "scope": "complete-captured-source" + }, + { + "id": "openai-gpt-6-astra", + "provider": "openai", + "url": "https://developers.openai.com/api/docs/models/gpt-6-astra", + "checkedAt": "2026-11-07", + "sha256": "7f2f28cf1a8dfdf2557eb1a51f1540e41396397795fe6c39f1f419c922d896ca", + "file": "sources/openai-gpt-6-astra.md", + "originalSha256": "7f2f28cf1a8dfdf2557eb1a51f1540e41396397795fe6c39f1f419c922d896ca", + "representation": "official-documentation-tool-text", + "scope": "complete-captured-source" + }, + { + "id": "openai-gpt-6-sol", + "provider": "openai", + "url": "https://developers.openai.com/api/docs/models/gpt-6-sol", + "checkedAt": "2026-11-07", + "sha256": "cae6df84b71d6ce278072a5e565db585ad8f946fd5a92492a9fdfa23eaca4e7f", + "file": "sources/openai-gpt-6-sol.md", + "originalSha256": "cae6df84b71d6ce278072a5e565db585ad8f946fd5a92492a9fdfa23eaca4e7f", + "representation": "official-documentation-tool-text", + "scope": "complete-captured-source" + }, + { + "id": "openai-gpt-6-luna", + "provider": "openai", + "url": "https://developers.openai.com/api/docs/models/gpt-6-luna", + "checkedAt": "2026-11-07", + "sha256": "be1678c26b17547a9b004286dd18065c9e08dfcaf53cb9e80517284fd1cba76e", + "file": "sources/openai-gpt-6-luna.md", + "originalSha256": "be1678c26b17547a9b004286dd18065c9e08dfcaf53cb9e80517284fd1cba76e", + "representation": "official-documentation-tool-text", + "scope": "complete-captured-source" + }, + { + "id": "openai-gpt-6.1-terra", + "provider": "openai", + "url": "https://developers.openai.com/api/docs/models/gpt-6.1-terra", + "checkedAt": "2026-11-07", + "sha256": "bab1c30e8d49d9be5e7ad0edf90508fb06fffb908123b97c4779f933e8b4bd2a", + "file": "sources/openai-gpt-6.1-terra.md", + "originalSha256": "bab1c30e8d49d9be5e7ad0edf90508fb06fffb908123b97c4779f933e8b4bd2a", + "representation": "official-documentation-tool-text", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-model-list", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/api/list-models", + "checkedAt": "2026-11-07", + "sha256": "5c8a4e4fe7256742a2d11218e6b155bb7210524a048cd0a14e733bee90194723", + "file": "sources/deepseek-model-list.html", + "originalSha256": "5c8a4e4fe7256742a2d11218e6b155bb7210524a048cd0a14e733bee90194723", + "representation": "received-html-bytes", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-models", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/quick_start/pricing", + "checkedAt": "2026-11-07", + "sha256": "af6679690eb9a7838c47727bfc5ffdc4ac91c4445a0c1219741ffe00c076ece5", + "file": "sources/deepseek-models.html", + "originalSha256": "af6679690eb9a7838c47727bfc5ffdc4ac91c4445a0c1219741ffe00c076ece5", + "representation": "received-html-bytes", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-response", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/api/create-response.md", + "checkedAt": "2026-11-07", + "sha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da", + "file": "sources/deepseek-response.md", + "originalSha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da", + "representation": "received-document-bytes", + "scope": "complete-captured-source" + }, + { + "id": "deepseek-message", + "provider": "deepseek", + "url": "https://api-docs.deepseek.com/api/create-message.md", + "checkedAt": "2026-11-07", + "sha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8", + "file": "sources/deepseek-message.md", + "originalSha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8", + "representation": "received-document-bytes", + "scope": "complete-captured-source" + }, + { + "id": "claude-effort", + "provider": "anthropic", + "url": "https://platform.claude.com/docs/en/build-with-claude/effort", + "checkedAt": "2026-11-06", + "sha256": "b19219d51d1ced67deb1451b8a0e243b13925d6e49454f0165d45e06a739704d", + "file": "sources/claude-effort.md", + "originalSha256": "b19219d51d1ced67deb1451b8a0e243b13925d6e49454f0165d45e06a739704d", + "representation": "extracted-official-markdown", + "scope": "complete-captured-source" + } + ], + "note": "Pinned official declarations and contract examples; not live-provider evidence. Original whole captures and first failures remain in the owned QA roots." +} diff --git a/tests/model-registry-integration.test.mjs b/tests/model-registry-integration.test.mjs new file mode 100644 index 00000000..0d79fffb --- /dev/null +++ b/tests/model-registry-integration.test.mjs @@ -0,0 +1,155 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { fixture, compatibleFixture } from './helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Store } from '../src/server/store.mjs'; +import { modelSnapshot } from '../src/shared/contracts/execution.mjs'; +import { resolveModelSpecification } from '../src/shared/contracts/official-model-registry.mjs'; + +const providerFor = f => { + // This constructor-free fixture never reads an environment model Key. + const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }); + return { provider, hub: provider.modelHub(f.store) }; +}; +const draft = server => ({ name: '自有兼容目录', protocol: 'chat-completions', baseUrl: server.baseUrl, requiresKey: false }); +const sha = value => createHash('sha256').update(value).digest('hex'); + +test('pageToken cursors, empty intermediate pages and all vendor fields survive selection with exact redacted JSON hashes', async t => { + const f = fixture(t, { modernDefaults: true }); + const token = 'owned +/中文?', raw = { id: 'gpt-6.1-sol', provider: 'owned', vendor_extension: { opaque: ['keep', { nested: true }], api_key: 'owned-do-not-export' } }; + const server = await compatibleFixture(t, url => url.includes('pageToken=second') ? { models: [{ id: 'gpt-6.1-terra' }] } + : url.includes('pageToken=') ? { models: [], nextPageToken: 'second' } : { models: [raw], nextPageToken: token }); + const { hub } = providerFor(f), preview = await hub.modelCatalog().fetch({ draft: draft(server) }); + assert.equal(server.requests.length, 3); + assert.equal(server.requests[1].url, '/v1/models?pageToken=' + encodeURIComponent(token)); + assert.equal(server.requests[2].url, '/v1/models?pageToken=second'); + const expected = structuredClone(raw); expected.vendor_extension.api_key = '[redacted]'; + const item = preview.entries[0]; + assert.deepEqual(item.rawItem, expected); assert.equal(item.rawSha256, sha(JSON.stringify(expected))); + assert.equal(item.rawBytes, Buffer.byteLength(JSON.stringify(expected))); assert.equal(item.rawRepresentation, 'parsed-redacted-item-json-v1'); + const result = hub.modelCatalog().apply({ previewId: preview.id, models: preview.entries.map(value => value.id), routing: 'manual', defaultModel: 'gpt-6.1-sol' }); + const connection = hub.connection(result.added[0]); + assert.equal(connection.maxOutputTokens, 128000); assert.equal(connection.contextLimit, 1050000); + assert.equal(connection.upstreamModel.rawSha256, item.rawSha256); assert.deepEqual(connection.upstreamModel.rawItem, expected); + assert.equal(hub.status(connection).capabilities.tools, 'unsupported'); + assert.equal(connection.capabilityDeclarationSources.tools, 'protocol'); + assert.equal(hub.attempts.length, 0); + assert.equal(JSON.stringify(hub.view()).includes('owned-do-not-export'), false); +}); + +test('repeated pagination tokens and unknown-field duplicate conflicts fail clearly without partial saves or retries', async t => { + const f = fixture(t, { modernDefaults: true }), { hub } = providerFor(f); + let mode = 'repeat'; + const server = await compatibleFixture(t, url => mode === 'repeat' ? { data: [{ id: 'owned' }], nextPageToken: 'unchanged' } + : url.includes('pageToken=') ? { data: [{ id: 'owned', vendor_field: 'second' }] } : { data: [{ id: 'owned', vendor_field: 'first' }], nextPageToken: 'next' }); + await assert.rejects(hub.modelCatalog().fetch({ draft: draft(server) }), /相同游标/); + assert.equal(server.requests.length, 2); assert.equal(hub.modelCatalog().previews.size, 0); + mode = 'conflict'; + await assert.rejects(hub.modelCatalog().fetch({ draft: draft(server) }), /冲突定义/); + assert.equal(server.requests.length, 4); assert.equal(hub.state.connections.length, 0); assert.equal(hub.attempts.length, 0); +}); + +test('refresh changes only current upstream facts, while prepared specification, native settings, original metadata and credential objects remain', async t => { + const f = fixture(t, { modernDefaults: true }); let output = 96000; + const server = await compatibleFixture(t, () => ({ data: [{ id: 'claude-opus-5-5', max_output_tokens: output, capabilities: { text: true, tools: true } }] })); + const { provider, hub } = providerFor(f); + const source = hub.upsert({ ...draft(server), model: 'claude-opus-5-5', protocol: 'anthropic-messages', requiresKey: true, + apiKey: 'owned-registry-refresh-only', persistKey: true, nativeParameters: { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'max' } }, parameterProfile: 'auto' }); + let preview = await hub.modelCatalog().fetch({ id: source.id, revision: source.revision }); + hub.modelCatalog().apply({ previewId: preview.id, models: [source.model], routing: 'manual', defaultModel: source.model }); + const connection = hub.connection(source.id), credential = provider.credentials.get(source.id), block = structuredClone(hub.vault().state); + const prepared = hub.prepare(f.store.config), snapshot = modelSnapshot(prepared), original = structuredClone(snapshot); + assert.equal(snapshot.routing.members[0].modelSpecificationFrozen, true); + assert.equal(snapshot.modelSpecification.fields.maxOutputTokens.value, 96000); + assert.equal(snapshot.modelSpecification.fields.maxOutputTokens.conflict, true); + output = 64000; preview = await hub.modelCatalog().fetch({ id: source.id, revision: connection.revision }); + hub.modelCatalog().apply({ previewId: preview.id, models: [source.model], routing: 'keep' }); + assert.equal(connection.upstreamModel.maxOutputTokens, 64000); assert.deepEqual(snapshot, original); + assert.equal(resolveModelSpecification(prepared.modelRouting.members[0]).fields.maxOutputTokens.value, 96000); + assert.equal(hub.prepare(f.store.config).modelSpecification.fields.maxOutputTokens.value, 64000); + assert.equal(provider.credentials.get(source.id), credential); assert.deepEqual(hub.vault().state, block); + assert.deepEqual(connection.nativeParameters, source.nativeParameters); assert.equal(connection.revision, source.revision); +}); + +test('native and explicit model-override edits persist through restart without re-encrypting the existing synthetic credential', t => { + const f = fixture(t, { modernDefaults: true }), { provider, hub } = providerFor(f); + const source = hub.upsert({ name: '自有存储恢复', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl: 'http://127.0.0.1:1', + apiKey: 'owned-registry-persistence-only', persistKey: true, nativeParameters: { thinking: { type: 'adaptive' } }, parameterProfile: 'auto' }); + const credential = provider.credentials.get(source.id), cipher = structuredClone(hub.vault().state); + hub.vault().protect = () => { throw Error('Existing Key must never be re-encrypted by a parameter edit'); }; + const overrides = { maxOutputTokens: 96000, efforts: ['low', 'custom'], modes: ['adaptive'], note: 'owned proxy declaration' }; + const native = { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'custom', vendor_field: { preserved: true } } }; + hub.setNativeParameters({ id: source.id, revision: source.revision, nativeParameters: native, parameterProfile: 'auto', modelOverrides: overrides }); + const edited = hub.connection(source.id); + assert.equal(edited.credentialBindingRevision, source.credentialBindingRevision); assert.ok(edited.revision > source.revision); + assert.equal(provider.credentials.get(source.id), credential); assert.deepEqual(hub.vault().state, cipher); assert.equal(hub.vault().status(edited).status, 'saved'); + assert.deepEqual(edited.nativeParameters, native); assert.deepEqual(edited.modelOverrides, overrides); + f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close()); + const freshProvider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), freshHub = freshProvider.modelHub(reopened), restored = freshHub.connection(source.id); + assert.deepEqual(restored.modelOverrides, overrides); assert.deepEqual(restored.nativeParameters, native); + assert.equal(freshHub.credential(restored).key, 'owned-registry-persistence-only'); assert.equal(freshHub.vault().status(restored).status, 'saved'); + assert.deepEqual(freshHub.vault().state, cipher); +}); + +test('credential endpoint, model, auth and new-Key changes still invalidate the original encrypted binding even if reverted', t => { + const f = fixture(t, { modernDefaults: true }), { hub } = providerFor(f); + const source = hub.upsert({ name: 'owned identity', model: 'owned', protocol: 'anthropic-messages', baseUrl: 'http://127.0.0.1:1', apiKey: 'owned-binding', persistKey: true }); + const cipher = structuredClone(hub.vault().state); + for (const update of [{ baseUrl: 'http://127.0.0.1:2' }, { model: 'other' }, { messagesAuth: 'bearer' }, { apiKey: 'owned-volatile-replacement' }]) { + let connection = hub.connection(source.id); + connection = hub.upsert({ ...connection, ...update }); + assert.equal(hub.vault().status(connection).status, 'source_changed'); + connection = hub.upsert({ ...connection, baseUrl: source.baseUrl, model: source.model, messagesAuth: 'api-key' }); + assert.equal(hub.vault().status(connection).status, 'source_changed'); + assert.deepEqual(hub.vault().state, cipher); + } +}); + +test('invalid override or transaction failure leaves every prior parameter, credential and registry row exact', t => { + const f = fixture(t, { modernDefaults: true }), { provider, hub } = providerFor(f); + const source = hub.upsert({ name: 'owned atomic', model: 'owned', baseUrl: 'http://127.0.0.1:1/v1', apiKey: 'owned-atomic-only', persistKey: true }); + const state = structuredClone(hub.state), native = { id: source.id, revision: source.revision, nativeParameters: { reasoning_effort: 'max' } }; + const credential = provider.credentials.get(source.id), cipher = structuredClone(hub.vault().state), rows = f.store.storage.database.prepare('SELECT * FROM metadata ORDER BY key').all(); + assert.throws(() => hub.setNativeParameters({ ...native, modelOverrides: { capabilities: { tools: 'verified' } } }), { status: 400 }); + f.store.storage.faultInjector = point => { if (point === 'before_commit') throw Error('owned registry commit failure'); }; + assert.throws(() => hub.setNativeParameters({ ...native, modelOverrides: { maxOutputTokens: 96000 } }), /owned registry commit failure/); + f.store.storage.faultInjector = null; + assert.deepEqual(hub.state, state); assert.equal(provider.credentials.get(source.id), credential); assert.deepEqual(hub.vault().state, cipher); + assert.deepEqual(f.store.storage.database.prepare('SELECT * FROM metadata ORDER BY key').all(), rows); +}); + +test('editing a catalog-sourced capability marks the new value as a user declaration despite inherited source labels', t => { + const f = fixture(t, { modernDefaults: true }), { hub } = providerFor(f); + const original = hub.upsert({ name: 'owned declaration', model: 'gpt-6.1-sol', protocol: 'responses', baseUrl: 'http://127.0.0.1:1/v1', requiresKey: false, + capabilityDeclarations: { tools: 'supported' }, capabilityDeclarationSources: { tools: 'upstream_catalog' } }); + hub.connection(original.id).upstreamModel = { id: original.model, capabilityDeclarations: { tools: 'supported' } }; + const changed = hub.upsert({ ...hub.connection(original.id), capabilityDeclarations: { ...original.capabilityDeclarations, tools: 'unsupported' } }); + assert.equal(changed.capabilityDeclarationSources.tools, 'user'); assert.equal(changed.capabilities.tools, 'unsupported'); + assert.equal(changed.modelSpecification.fields['capabilities.tools'].kind, 'connection_declaration'); +}); + +test('actual owned HTTP sends exact native parameters and optional DeepSeek output omission; original upstream errors are retained once', async t => { + const f = fixture(t, { modernDefaults: true }), inputs = []; let failed = false; + const server = await compatibleFixture(t, (url, body) => { + inputs.push(body); + if (failed) return { status: 400, body: { error: { type: 'owned_parameter_error', message: 'owned unchanged upstream body' } } }; + return { body: { id: 'owned-message', type: 'message', role: 'assistant', model: body.model, content: [{ type: 'text', text: 'owned answer' }], stop_reason: 'end_turn', usage: { input_tokens: 7, output_tokens: 3 } } }; + }); + const { provider, hub } = providerFor(f); + const source = hub.upsert({ name: 'owned DeepSeek HTTP', model: 'deepseek-flash', baseUrl: server.baseUrl, protocol: 'anthropic-messages', requiresKey: false, + nativeParameters: { thinking: { type: 'adaptive' }, output_config: { effort: 'max', vendor_field: { keep: true } } }, modelOverrides: { maxOutputTokens: 9000, note: 'owned display reference only' } }); + hub.select({ type: 'connection', id: source.id }); + const config = hub.prepare(f.store.config), original = structuredClone(config), input = [{ role: 'user', content: 'ORIGINAL ' + 'retain '.repeat(18000) + ' END' }]; + await provider.complete(config, input, null, undefined, undefined, null, []); + assert.equal(inputs.length, 1); assert.equal(Object.hasOwn(inputs[0], 'max_tokens'), false); + assert.equal(inputs[0].messages[0].content[0].text, input[0].content); assert.deepEqual(inputs[0].output_config, source.nativeParameters.output_config); + assert.equal(Object.hasOwn(inputs[0], 'modelOverrides'), false); assert.equal(Object.hasOwn(inputs[0], 'modelSpecification'), false); + failed = true; + await assert.rejects(provider.complete(config, input, null, undefined, undefined, null, []), cause => { + assert.equal(cause.diagnostic.httpStatus, 400); assert.equal(cause.diagnostic.origin, 'upstream'); assert.equal(cause.diagnostic.retryDecision, 'passthrough'); + assert.match(cause.diagnostic.upstream.rawPreview, /owned unchanged upstream body/); return true; + }); + assert.equal(inputs.length, 2); assert.deepEqual(config, original); assert.equal(hub.attempts.length, 2); + t.after(() => provider.abortRequests()); +}); diff --git a/tests/official-model-registry.test.mjs b/tests/official-model-registry.test.mjs new file mode 100644 index 00000000..640850fa --- /dev/null +++ b/tests/official-model-registry.test.mjs @@ -0,0 +1,165 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { createHash } from 'node:crypto'; +import { modelRegistry, validateModelRegistry, officialModelRecord, modelProvider, modelOverrideSettings, resolveModelSpecification } from '../src/shared/contracts/official-model-registry.mjs'; +import { modelParameterProfile, changeReasoningSetting, reasoningSetting } from '../src/shared/contracts/model-parameter-profiles.mjs'; +import { capabilityView } from '../src/shared/contracts/model-capabilities.mjs'; +import { completionBody } from '../src/shared/contracts/model-request.mjs'; +import { modelCapacityDeclaration } from '../src/shared/contracts/model-capacity.mjs'; +import { modelSnapshot } from '../src/shared/contracts/execution.mjs'; +import { catalogModel } from '../src/shared/contracts/model-catalog.mjs'; +import { modelRoutingDecision } from '../src/shared/contracts/model-routing.mjs'; + +const open = { mode: 'compatible', executionMode: 'unrestricted', capacityMode: 'passthrough', historyPolicy: 'preserve', baseUrl: 'http://127.0.0.1:1/v1' }; +const sol = { ...open, protocol: 'responses', model: 'gpt-6.1-sol' }; +const claude = { ...open, protocol: 'anthropic-messages', model: 'claude-opus-5-5' }; + +test('every published fact resolves to its original pinned official document bytes', () => { + const fixture = JSON.parse(fs.readFileSync(new URL('./fixtures/official-model-registry/SOURCE.json', import.meta.url))); + assert.equal(modelRegistry.sources.length, 17); + assert.equal(modelRegistry.records.length, 26); + assert.equal(new Set(modelRegistry.records.map(item => item.model)).size, 13); + assert.deepEqual(modelRegistry.sources, fixture.sources); + for (const source of fixture.sources) { + const bytes = fs.readFileSync(new URL('./fixtures/official-model-registry/' + source.file, import.meta.url)); + assert.equal(createHash('sha256').update(bytes).digest('hex'), source.sha256, source.id); + } + assert.equal(Object.isFrozen(modelRegistry.records[0].fields.efforts.value), true); + assert.throws(() => modelRegistry.records[0].fields.efforts.value.push('fabricated'), TypeError); +}); + +test('registry rejects forged origins, non-JSON values, duplicate keys and malformed selectable options', () => { + const mutations = [ + input => input.sources[0].url = 'https://unreviewed.invalid/models', + input => input.sources[0].sha256 = 'unverified', + input => input.records[0].fields.contextLimit.source = input.sources[0].id, + input => input.records[0].fields.contextLimit.value = 0, + input => input.records[0].fields['capabilities.tools'].value = 'verified', + input => input.records[0].fields.efforts.value = 'all', + input => input.records[0].fields.defaultEffort.value = {}, + input => input.records.push(structuredClone(input.records[0])), + input => input.records[0].fields.cyclic = { source: input.records[0].fields.efforts.source, value: input }, + ]; + for (const change of mutations) { const input = structuredClone(modelRegistry); change(input); assert.throws(() => validateModelRegistry(input), { status: 400 }); } + const future = structuredClone(modelRegistry); future.records[0].protocol = 'future-data-only-protocol'; + assert.equal(validateModelRegistry(future), future, 'A registry reference must not pretend to install a protocol adapter'); +}); + +test('provider, exact case-sensitive model, protocol and explicit API version all bind a reference', () => { + assert.equal(modelProvider({ ...sol, brand: 'DeepSeek' }).id, 'openai'); + assert.equal(modelProvider({ model: 'deepseek-owned-alias', brand: 'DeepSeek' }).id, null); + assert.equal(officialModelRecord({ ...sol, model: sol.model + '-custom' }), null); + assert.equal(officialModelRecord({ ...sol, model: sol.model.toUpperCase() }), null); + assert.equal(officialModelRecord({ ...sol, providerId: 'anthropic' }), null); + assert.equal(officialModelRecord({ ...claude, apiVersion: '2023-06-01' }), null); + assert.equal(officialModelRecord({ ...claude, apiVersion: '2026-10-21' }).model, claude.model); + assert.equal(officialModelRecord({ ...sol, protocol: 'anthropic-messages' }), null); + assert.equal(modelParameterProfile({ ...open, protocol: 'chat-completions', model: 'deepseek-owned-alias', brand: 'DeepSeek' }).id, 'openai'); + assert.equal(modelParameterProfile({ ...open, protocol: 'chat-completions', model: 'owned', parameterProfile: 'deepseek' }).id, 'deepseek'); +}); + +test('OpenAI exact Chat tool conditions and reasoning-none are independent of manual passthrough', () => { + for (const model of ['gpt-6.1-sol', 'gpt-6.1-terra']) { + assert.equal(capabilityView({ ...open, model, protocol: 'chat-completions' }).tools, 'unsupported'); + assert.equal(capabilityView({ ...open, model, protocol: 'responses' }).tools, 'protocol_declared'); + } + for (const model of ['gpt-6-sol', 'gpt-6-luna']) { + const connection = { ...open, model, protocol: 'chat-completions' }; + assert.equal(capabilityView(connection).tools, 'unsupported'); + assert.equal(capabilityView({ ...connection, nativeParameters: { reasoning_effort: 'none' } }).tools, 'protocol_declared'); + assert.equal(modelParameterProfile(connection).modes.includes('disabled'), true); + } + assert.deepEqual(modelParameterProfile(sol).efforts, ['low', 'medium', 'high', 'xhigh', 'max']); + assert.deepEqual(modelParameterProfile(sol).modes, ['enabled']); + const body = completionBody({ ...sol, protocol: 'chat-completions' }, [{ role: 'user', content: 'original request' }], []); + assert.equal(Object.hasOwn(body, 'max_tokens'), false); +}); + +test('DeepSeek official dialect facts distinguish HTTP budgets, structured output and alias retirement', () => { + const messages = { ...open, model: 'deepseek-flash', protocol: 'anthropic-messages' }; + const profile = modelParameterProfile(messages), fields = profile.specification.fields; + assert.deepEqual(profile.efforts, ['low', 'high', 'max']); assert.equal(profile.defaultEffort, 'high'); + assert.equal(profile.thinkingBudget, 'ignored'); + assert.equal(fields.contextLimit.value, 1048576); assert.equal(fields.maxOutputTokens.value, 393216); + assert.equal(fields['request.systemPromptUpdate'].value, 'in-history'); + assert.equal(fields['request.maxTokensRequired'].value, false); + assert.equal(Object.hasOwn(completionBody(messages, [{ role: 'user', content: 'intact' }], []), 'max_tokens'), false); + assert.equal(completionBody({ ...messages, nativeParameters: { max_tokens: 700000 } }, [{ role: 'user', content: 'intact' }], []).max_tokens, 700000); + assert.deepEqual(changeReasoningSetting(messages, { output_config: { effort: 'max' } }, 'mode', 'enabled'), { output_config: { effort: 'max' }, thinking: { type: 'enabled' } }); + assert.equal(resolveModelSpecification({ ...messages, model: 'deepseek-v4-pro' }).fields['capabilities.vision'].value, 'unsupported'); + assert.equal(resolveModelSpecification({ ...messages, protocol: 'chat-completions' }).fields['features.structured_outputs'].value, 'unsupported'); + assert.equal(resolveModelSpecification({ ...messages, protocol: 'responses' }).fields['features.structured_outputs'].value, 'supported'); + const alias = resolveModelSpecification({ ...messages, model: 'deepseek-v4-flash' }); + assert.equal(alias.fields.lifecycle.value, 'deprecated'); assert.equal(alias.fields.aliasOf.value, 'deepseek-flash'); + assert.equal(alias.fields['request.originalModelRetired'].value, true); +}); + +test('catalog values, explicit denial and matching observations retain all conflicting origins', () => { + const connection = { ...sol, revision: 3, credentialRevision: 7, upstreamModel: { id: sol.model, endpoint: sol.baseUrl, maxOutputTokens: 96000, + capabilityDeclarations: { tools: 'unsupported' } }, capabilityDeclarations: { tools: 'unknown' }, + capabilityEvidence: { connectionRevision: 3, credentialRevision: 7, checkedAt: '2026-11-07', results: { tools: 'verified' } } }; + let fields = resolveModelSpecification(connection).fields; + assert.equal(fields.maxOutputTokens.kind, 'upstream_catalog'); assert.equal(fields.maxOutputTokens.value, 96000); + assert.equal(fields.maxOutputTokens.alternatives[0].value, 128000); assert.equal(fields.maxOutputTokens.conflict, true); + assert.equal(fields['capabilities.tools'].kind, 'revision_bound_observation'); assert.equal(capabilityView(connection, 7).tools, 'verified'); + const explicit = { ...connection, modelOverrides: { capabilities: { tools: 'unsupported' } } }; + assert.equal(capabilityView(explicit, 7).tools, 'unsupported'); assert.equal(resolveModelSpecification(explicit).fields['capabilities.tools'].conflict, true); + assert.equal(capabilityView(connection, 8).tools, 'unsupported', 'Stale observation is excluded'); + const staleCatalog = { ...connection, capabilityEvidence: null, upstreamModel: { ...connection.upstreamModel, endpoint: 'https://other.invalid/v1' } }; + assert.equal(resolveModelSpecification(staleCatalog).fields.maxOutputTokens.value, 128000); +}); + +test('legacy declarations keep their edit uncertainty instead of silently changing old routing settings', () => { + const connection = { ...open, model: 'gpt-6.1-sol', protocol: 'chat-completions', capabilityDeclarations: { tools: 'supported' } }; + const field = resolveModelSpecification(connection).fields['capabilities.tools']; + assert.equal(field.kind, 'legacy_connection_declaration'); assert.equal(field.value, 'supported'); assert.equal(field.conflict, true); + assert.equal(resolveModelSpecification({ ...connection, capabilityDeclarationSources: { tools: 'protocol' } }).fields['capabilities.tools'].value, 'unsupported'); +}); + +test('explicit unknown capacity and empty option arrays suppress backfills without overwriting native values', () => { + const overrides = modelOverrideSettings({ maxOutputTokens: null, efforts: [], modes: [], features: { effort: 'unsupported' }, note: 'proxy does not report a maximum' }); + const connection = { ...sol, modelOverrides: overrides, nativeParameters: { reasoning: { effort: 'custom', summary: 'auto' }, max_output_tokens: 300000 } }; + const before = structuredClone(connection); + assert.equal(modelCapacityDeclaration(connection, 'maxOutputTokens'), null); + assert.deepEqual(modelParameterProfile(connection).efforts, []); assert.deepEqual(modelParameterProfile(connection).modes, []); + assert.equal(completionBody(connection, [{ role: 'user', content: 'intact' }], []).max_output_tokens, 300000); + assert.deepEqual(connection, before); + for (const value of [{ maxOutputTokens: 0 }, { modes: 'all' }, { capabilities: { tools: 'verified' } }, { unknownField: true }]) assert.throws(() => modelOverrideSettings(value), { status: 400 }); + assert.deepEqual(modelOverrideSettings(undefined, overrides), overrides); + assert.deepEqual(modelOverrideSettings({}), {}, 'Removing overrides restores future discovery, without mutating past specifications'); +}); + +test('an existing frozen model specification survives a new catalog or registry interpretation', () => { + const original = resolveModelSpecification(sol), connection = { ...sol, modelSpecification: original, modelSpecificationFrozen: true }; + const snapshot = modelSnapshot(connection), before = structuredClone(snapshot); + connection.upstreamModel = { id: sol.model, maxOutputTokens: 9000 }; + connection.modelOverrides = { maxOutputTokens: 3000 }; + assert.deepEqual(resolveModelSpecification(connection), original); + assert.equal(modelCapacityDeclaration(connection, 'maxOutputTokens').value, 128000); + original.fields.maxOutputTokens.value = 1; + assert.deepEqual(snapshot, before); +}); + +test('catalog no-options and individual denials cannot be mistaken for missing official facts', () => { + const empty = catalogModel({ id: sol.model, effort: { supported_levels: [] } }); + assert.deepEqual(modelParameterProfile({ ...sol, upstreamModel: empty }).efforts, []); + const negative = catalogModel({ id: sol.model, capabilities: { effort: { high: false } } }); + assert.deepEqual(modelParameterProfile({ ...sol, upstreamModel: negative }).efforts, ['low', 'medium', 'xhigh', 'max']); + const custom = { ...sol, upstreamModel: empty, modelOverrides: { efforts: ['custom'], features: { effort: 'supported' } } }; + assert.deepEqual(modelParameterProfile(custom).efforts, ['custom']); + assert.equal(reasoningSetting(sol, { reasoning: { effort: 'max', summary: 'auto' } }).canResetMode, true); +}); + +test('automatic routing records official protocol conditions and explicit proxy differences; manual selection remains open', () => { + const member = { ...sol, id: 'owned', name: 'owned', protocol: 'chat-completions', revision: 1, credentialRevision: 0 }; + const automatic = modelRoutingDecision({ type: 'pool', members: [member] }, ['tools'], { open: true }); + assert.equal(automatic.candidates[0].disposition, 'excluded'); + assert.equal(automatic.candidates[0].capabilities.tools.source, 'official-model-spec'); + assert.equal(automatic.candidates[0].capabilities.tools.specification.conflict, false); + assert.equal(modelRoutingDecision({ type: 'connection', members: [member] }, ['tools'], { open: true }).candidates[0].disposition, 'eligible'); + const proxy = { ...member, modelOverrides: { capabilities: { tools: 'supported' } }, upstreamModel: { id: member.model, capabilityDeclarations: { tools: 'unsupported' } } }; + const declared = modelRoutingDecision({ type: 'pool', members: [proxy] }, ['tools'], { open: true }).candidates[0]; + assert.equal(declared.disposition, 'eligible'); assert.equal(declared.capabilities.tools.source, 'explicit-compatibility'); + assert.equal(declared.capabilities.tools.specification.conflict, true); +}); diff --git a/tests/passthrough-output-diagnostics.test.mjs b/tests/passthrough-output-diagnostics.test.mjs index c358ee22..5f911cba 100644 --- a/tests/passthrough-output-diagnostics.test.mjs +++ b/tests/passthrough-output-diagnostics.test.mjs @@ -16,6 +16,8 @@ test('passthrough truncation describes actual HTTP output fields and preserves u { protocol: 'anthropic-messages', value: 2048 }, { protocol: 'anthropic-messages', upstreamModel: { id: model, maxOutputTokens: 128000 }, value: 128000 }, { protocol: 'anthropic-messages', nativeParameters: { max_tokens: 65536 }, value: 65536 }, + { protocol: 'anthropic-messages', model: 'deepseek-flash' }, + { protocol: 'anthropic-messages', model: 'deepseek-flash', nativeParameters: { max_tokens: 65536 }, value: 65536 }, { protocol: 'chat-completions' }, { protocol: 'chat-completions', nativeParameters: { max_tokens: 96000 }, value: 96000 }, { protocol: 'chat-completions', nativeParameters: { max_completion_tokens: 128000 }, field: 'max_completion_tokens', value: 128000 }, @@ -23,7 +25,7 @@ test('passthrough truncation describes actual HTTP output fields and preserves u { protocol: 'responses', nativeParameters: { max_output_tokens: 48000 }, value: 48000 }, ]; for (const scenario of scenarios) await t.test(scenario.protocol + ' ' + (scenario.value ?? 'no output field'), async child => { - const response = truncated(scenario.protocol), upstream = await compatibleFixture(child, () => ({ body: response })); + const response = { ...truncated(scenario.protocol), model: scenario.model ?? model }, upstream = await compatibleFixture(child, () => ({ body: response })); const provider = new Provider(), events = []; child.after(() => provider.abortRequests()); const config = { executionMode: 'unrestricted', capacityMode: 'passthrough', mode: 'compatible', @@ -36,6 +38,7 @@ test('passthrough truncation describes actual HTTP output fields and preserves u assert.equal(diagnostic.upstream.rawPreview, JSON.stringify(response)); assert.ok(diagnostic.wireAttemptId); assert.equal(diagnostic.upstream.httpStatus, 200); assert.doesNotMatch(diagnostic.message, /工作台未附加输出额度/); + if (scenario.model === 'deepseek-flash') assert.doesNotMatch(diagnostic.message, /Messages 协议要求 max_tokens/); if (scenario.value !== undefined) assert.ok(diagnostic.message.includes(field + '=' + scenario.value), diagnostic.message); else assert.match(diagnostic.message, /实际请求未携带输出 token 上限/); return true;