From f95507ab255d4a4fa41a998d1ea1e676a737d7b6 Mon Sep 17 00:00:00 2001 From: Agent Workbench Dev Date: Sat, 7 Nov 2026 15:36:33 +0800 Subject: [PATCH] feat(models): freeze provider request contracts and observe actual headers --- docs/M2-REQUEST-CONTRACT-PLAN.md | 6 +- docs/MODEL-REQUEST-CONTRACT.md | 2 + findings.md | 2 + progress.md | 10 + src/core/context/request-plan.mjs | 17 +- src/core/models/config-import.mjs | 2 + src/core/models/credential-vault.mjs | 4 +- src/core/models/model-catalog.mjs | 12 +- src/core/models/model-hub.mjs | 21 +- src/core/models/request-contract-audit.mjs | 48 ++++ src/core/models/upstream-error.mjs | 3 +- src/server/provider.mjs | 19 +- src/shared/contracts/execution.mjs | 3 +- src/shared/contracts/model-catalog.d.mts | 5 +- src/shared/contracts/model-catalog.mjs | 1 + src/shared/contracts/model-endpoint.d.mts | 5 +- src/shared/contracts/model-endpoint.mjs | 7 +- .../contracts/model-request-contract.d.mts | 13 + .../contracts/model-request-contract.mjs | 98 +++++++ .../contracts/official-model-registry.d.mts | 6 +- .../contracts/official-model-registry.mjs | 20 +- task_plan.md | 2 + tests/model-request-contract.test.mjs | 258 ++++++++++++++++++ 23 files changed, 526 insertions(+), 38 deletions(-) create mode 100644 src/core/models/request-contract-audit.mjs create mode 100644 src/shared/contracts/model-request-contract.d.mts create mode 100644 src/shared/contracts/model-request-contract.mjs create mode 100644 tests/model-request-contract.test.mjs diff --git a/docs/M2-REQUEST-CONTRACT-PLAN.md b/docs/M2-REQUEST-CONTRACT-PLAN.md index 30b908db..9e393f99 100644 --- a/docs/M2-REQUEST-CONTRACT-PLAN.md +++ b/docs/M2-REQUEST-CONTRACT-PLAN.md @@ -3,9 +3,9 @@ 2026-11-07,基线 `c7d1ad5e8af79e527840f0c2c866e224ac3115b4`,既有GitAtlas分支逐SHA一致、工作树干净。承接I15,完成I14的现有三协议请求契约;I12非提示字段/版本指纹与原前缀观察分开。I09缓存块、I11跨Run亲和/状态和I27/I28 CI仍各自验收,不据请求头透传称全部厂商适配完成。 1. [complete] 官方OpenAI API Overview、Anthropic overview/versioning/beta与既有DeepSeek原件11份/480878字节逐SHA固定。迁移页200地区重定向原件标为拒采,不能作正文已读;版本历史明确新版采样三字段删除且2023-06-01仍在历史。见MODEL-REQUEST-CONTRACT.md与新根source-review.json。 -2. [in_progress] 纯版本/头/路径契约与来源、现有凭据引用、额外非凭据头;新官方默认与已有连接版本分开,原生JSON不删除/改写,未知版本/beta透传。冻结Run/成员实际设置、目录同源身份与旧快照兼容,认证/端点变化和单纯版本/参数变化分开。 -3. [pending] 每次实际请求记录已准备的头/版本/端点、去凭据指纹、原body SHA、响应版本及source,不冒称整个HTTP原字节。原ordered-prefix v1/v2保留,新增指纹只观察字段变化、不声称供应商缓存命中。 -4. [pending] 相关单元与实际自有HTTP/JSON/SSE/错误/重定向、目录、混合池成员与保存/恢复;独立冻结构建、网页/实际Electron宽窄屏/三配色与已有原生参数流程,逐输入/编译/旧原件核对。 +2. [complete] 纯版本/头/路径契约与来源、现有凭据引用和额外非凭据头已实现;新官方默认/已有连接分开,未知值透传、普通编辑密文保持,目录声明绑定URL/头/凭据修订,旧冻结规格不重新解释。 +3. [complete] 物理fetch元数据与原Run冻结设置明确分别表示;原body SHA、ordered-prefix v1/v2不变,独立非提示指纹及响应版本已记录。最后核心相关38/38与tsc通过;原113/114和142/143、验收器错误与空规格修复前观察保留,不称整轮全绿。 +4. [in_progress] 实际自有HTTP/JSON/SSE/400/302、目录、混池和密文恢复已有专项;独立构建与网页/实际Electron宽窄屏/三配色、完整界面保存/错误/恢复仍待最终验证,逐输入/编译/旧原件核对。 5. [pending] 回顾、限定本地提交与授权既有GitAtlas普通增量推送;准确保留首失败与未验证事项。下一缓存块/亲和/状态、CI,再M3真实迁移增量和新处理器回退。 不新增本地token、头数量/大小额度或审批停顿;HTTP/JSON格式与凭据字段各自管理,上游语义错误保留一次原响应,不自动改版本重放。默认unrestricted/passthrough/preserve和持久ask/auto/full保持。公开文档调用不是模型请求。 diff --git a/docs/MODEL-REQUEST-CONTRACT.md b/docs/MODEL-REQUEST-CONTRACT.md index 0bce49e2..5104fbe5 100644 --- a/docs/MODEL-REQUEST-CONTRACT.md +++ b/docs/MODEL-REQUEST-CONTRACT.md @@ -20,4 +20,6 @@ 每次物理尝试保留 body 原 JSON SHA;另记录准备提交给 fetch 的去凭据头、方法、端点、版本、绑定和非提示参数指纹。明确该记录的规范化/脱敏表示,不称 HTTP 原字节;相同指纹只说明观察字段相同,缓存命中、真实兼容和工程收益仍由上游实际结果独立证明。 +原 Run 推导的对照单列为 `frozen-run-contract` / `frozen-request-contract-redacted-v1`,鉴权只表示模板,不证明本次已带 Key。物理尝试记录为 `prepared-fetch-arguments` / `fetch-request-metadata-redacted-v1`,采用传给 fetch 的有效头。新目录声明另绑定实际目录地址、有效头模板和凭据修订;组织、项目、版本或凭据变化后不把旧声明当当前事实,原目录与旧快照仍保留。逐字符串脱敏不改请求 JSON 结构,空规格也能显示未知。 + 默认 unrestricted/passthrough/preserve 与持久 ask/auto/full 保持。不改用户原生参数、不自动换线/换版本/重放失败请求。不请求真实模型或读取真实 Key、不写正式数据/配置或部署;历史网络异常、unknown、重复读取、R/W 边界与 Purge 收益 unknown 保留。 diff --git a/findings.md b/findings.md index 16835c4f..9f6c9085 100644 --- a/findings.md +++ b/findings.md @@ -1,5 +1,7 @@ # 汇总发现 +I14请求与证据:纯版本/Beta/普通头编辑应保留密文,但目录能力声明必须绑定实际目录URL、有效脱敏头及凭据修订;组织/项目变化不能沿用旧声明,旧Run与旧无绑定快照保持原解释。冻结规格不能因后续native/override重新解释;鉴权、协议或端点改变需要新绑定。新诊断按结构脱敏,直接替换序列化JSON可能被短Key中的标点破坏,从而在fetch前错误阻断。请求体原SHA、ordered-prefix v1/v2与去凭据设置指纹是不同证据,指纹相同不证明缓存命中。 + M2 I15完成:型号子串不代表容量/能力,精确官方记录要与协议/资料版本绑定,代理差异及旧声明来源不明都要可核对。目录已解析/脱敏JSON的SHA有独立表示,不冒称HTTP原字节;游标推进的空中间页可继续,重复游标/未知字段冲突不部分保存。普通推理修订与凭据身份分开,防止无故密文失效,真正身份改变仍失效。内存undefined与原存储JSON、原metadata与完整新账本投影不能混同比较。最终两端6组/7图、858输入/29编译和5688原件见[验收](docs/QA-M2-OFFICIAL-REGISTRY.md);I14实际版本/头/指纹、缓存状态、CI/M3及历史Purge收益unknown仍待。 M2 I15来源/基线已验:17份官方来源813289字节、6旧源码/4配置固定。DeepSeek当前Models API给出1048576上下文/393216最大输出、effort.supported_levels/default_level和api_capabilities;Messages max_tokens在其HTTP层可选、thinking预算被忽略,不能套Anthropic必填语义。Anthropic新版官方例用2026-10-21,现固定2023-06-01的有效性另由I14核对。首夹具把M1清单完整路径误当basename,原脚本/工具错误记录保留,第二按实际路径核SHA通过;无产品或旧证据写入。 diff --git a/progress.md b/progress.md index 51e8d766..0348402a 100644 --- a/progress.md +++ b/progress.md @@ -1,5 +1,15 @@ # 统一执行进度 +I14核心收口:source-contract-final五文件38/38、typecheck-final退出0,阶段2–3已完成,准备限定提交核心和类型/验收输入。未把原142/143当全绿;原断言1/1、空规格TypeError来源和最新38/38分别保留。下一独立freeze/build/candidate与真实网页/实际Electron核心路径。Mnemo新报告与旧固定计划SHA已只读核对一致,报告60调用/双180采样、3秒/5秒和十四声明检查保持为源方证据,不作本地推理复跑。 + +I14 source-sse-redirect-3原断言补验1/1,source-contract-5专项11+规格11为22/22。空规格默认调用实测TypeError后补空目录守卫与声明类型;最新专项覆盖。最后复核把原Run推导的请求契约标为frozen-run-contract,并在UI显示冻结设置;实际fetch元数据仍为prepared-fetch-arguments。避免把鉴权模板当成已发送头,不改旧ordered-prefix或原SHA。Mnemo本轮协调消息仅作为新的只读资料,原手机持续失败/任务unknown/旧固定文档和限制继续独立。 + +I14 source-related-2完整12文件为142/143;唯一失败为新增SSE验收读result.content,实际返回result.message.content。已封存当轮测试输入并仅修断言,产品源码未因该失败修改。新UI驱动已建立,实际界面尚未运行;目录requestValid现有条件确认正确,不增加修复。下一原失败专项补验与独立候选,保持首轮失败。 + +I14 source-contract-4为21/21(专项10与官方规格11),覆盖冻结native/override回归与结构脱敏400。追加Messages实际SSE/302不跟随及目录身份/凭据修订观察;纯观察元数据不把未保存目录误认作legacy连接。第二次组合patch误猜目录按钮整行,整批未应用;读到实际条件已正确限定新上游的requestValid,未改已有正确逻辑。下一最终相关组合与独立构建,两次patch工具失败均为调查过程。 + +I14实现接续复核:保留source-contract-1为5/9及自有残留进程处置、第二轮8/9字段断言错误、第三轮9/9;related-1为113/114,冻结规格被native/override重新解释的回归已定位修正,尚待最后复验。新目录声明绑定实际URL/头/凭据修订;补齐legacy运行修订与Messages鉴权绑定。新观察器改逐字符串脱敏,避免短合成Key匹配JSON标点时破坏结构;追加真实自有HTTP400边界。首次组合patch用了错误progress标题,整批未应用,已按真实标题重做;过量读取/工具输出截断作为调查失误保留。既有9/9、tsc及build-working-2不代签最后补强。无真实Key/模型/正式写入,旧封存根只读。 + I14接续来源复核:工作树仅原计划/progress与新fixture;11有效资料480878字节逐SHA一致。迁移页一次HTTP200实际跳到地区不可用页面,原记录与正文保留,追加复核将其accepted=false并明确不作为官方迁移正文。添加fixture原字节Git属性;旧I13/I15封存根未写。恢复中几次过量读取/猜错只读文件路径记录为调查失误,无产品或正式写入;下一核心契约。 M2第四批开始:c7d1ad5e干净且GitAtlas逐SHA一致,I14来源实际已取OpenAI API Overview及Anthropic overview/versioning/beta(200);最新2026-10-21删除采样三参数,2023-06-01仍有官方历史记录。新官方默认/原连接版本分开,原生参数不偷偷删改。API文档源保存在新的m2-request-contract根,I15旧根不追加;初读又有一个猜错planner文件路径与过量输出,只作调查错误记录。尚无本批产品改动、真实Key/模型/正式操作。 diff --git a/src/core/context/request-plan.mjs b/src/core/context/request-plan.mjs index 0070dd87..bed9a3f3 100644 --- a/src/core/context/request-plan.mjs +++ b/src/core/context/request-plan.mjs @@ -9,6 +9,7 @@ import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs'; import { modelReservation,taskConsumption,verifyModelReservation } from '../../shared/contracts/model-reservation.mjs'; import { fileContinuation } from './read-continuation.mjs'; import { prefixAudit } from './prefix-audit.mjs'; +import { requestContractAudit } from '../models/request-contract-audit.mjs'; import { observeRequest, providerHistory, requestPath } from './request-observation.mjs'; import { verifyToolSurface } from './tool-surface.mjs'; import { isPassthrough } from '../../shared/contracts/model-capacity.mjs'; @@ -414,12 +415,16 @@ export class RequestPlanner { .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.requestIndex - b.requestIndex).at(-1) ?? null; const previousBody = previousPlan ? JSON.parse(this.store.artifactStore.read(this.store.owned('artifact', previousPlan.requestArtifactId, session.id))) : null; const prefix = { ...prefixAudit(body, previousBody, { schemaVersion: 2 }), previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null }; + const previousModel = previousPlan ? this.store.owned('run', previousPlan.runId, session.id).model : null; + const contractAudit = config.mode === 'compatible' ? { ...requestContractAudit(body, config, previousBody, previousModel ? { ...previousModel, modelRouting: previousModel.routing } : null), + previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null } : null; const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id, stepId, requestIndex: [...this.store.core.context_plan.values()].filter(plan => plan.runId === run.id).length + 1, status: 'prepared', createdAt: new Date().toISOString(), finishedAt: null, requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens, requestArtifactId: requestArtifact.id, prefixAudit: prefix, + ...(contractAudit ? { requestContractAudit: contractAudit } : {}), requestObservation: observation, ...(progressReminder ? { progressReminder } : {}), ...(preserve ? { contextLayout: 'stable-prefix-1', historyPolicy: 'preserve', contextTailArtifactId: tailArtifact?.id ?? null, contextTailSha256: tailArtifact?.sha256 ?? null } : {}), @@ -494,7 +499,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) { historyGroups(requestHistory(body)); for (const variant of requestVariants(body)) historyGroups(requestHistory(variant)); const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan'))); - for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestObservation', 'progressReminder']) { + for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestContractAudit', 'requestObservation', 'progressReminder']) { if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。'); } verifyReminderMessage(store, session, plan, body); @@ -512,6 +517,16 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) { const expected = { ...prefixAudit(body, previousBody, { schemaVersion: plan.prefixAudit.schemaVersion }), previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null }; if (JSON.stringify(expected) !== JSON.stringify(plan.prefixAudit)) throw new Error('前缀观测与原请求字节不匹配。'); } + if (plan.requestContractAudit) { + const audit = plan.requestContractAudit; + if (audit.schemaVersion !== 1 || audit.previousPlanId !== plan.prefixAudit?.previousPlanId || audit.previousRequestSha256 !== plan.prefixAudit?.previousRequestSha256) throw new Error('请求协议观测版本或对照来源不匹配。'); + const previous = audit.previousPlanId ? store.owned('context_plan', audit.previousPlanId, session.id) : null; + const previousBody = previous ? JSON.parse(store.artifactStore.read(get(previous.requestArtifactId, 'model-request', previous.requestSha256))) : null; + const previousModel = previous ? store.owned('run', previous.runId, session.id).model : null; + const expected = { ...requestContractAudit(body, { ...runModel, modelRouting: runModel.routing }, previousBody, previousModel ? { ...previousModel, modelRouting: previousModel.routing } : null), + previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null }; + if (JSON.stringify(expected) !== JSON.stringify(audit)) throw new Error('请求协议观测与原运行快照或请求不匹配。'); + } const carriesContext = content => requestHistory(body).filter(value => typeof value.content === 'string' && (value.role === 'system' && value.content === content || plan.contextLayout === 'stable-prefix-1' && value.role === 'user' && value.content.includes(content))).length === 1; if (plan.contextTailArtifactId) { diff --git a/src/core/models/config-import.mjs b/src/core/models/config-import.mjs index 205b75ab..a399a1d9 100644 --- a/src/core/models/config-import.mjs +++ b/src/core/models/config-import.mjs @@ -9,6 +9,7 @@ import { modelEndpoint } from './model-hub.mjs'; import { MODEL_PROTOCOLS } from '../../shared/contracts/model-capabilities.mjs'; import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs'; import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs'; +import { effectiveRequestContract } from '../../shared/contracts/model-request-contract.mjs'; const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'); export class ConfigImporter { @@ -35,6 +36,7 @@ export class ConfigImporter { ...(item.nativeParameters !== undefined ? { nativeParameters: item.nativeParameters } : {}), ...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}), ...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}), + requestContract: effectiveRequestContract(item), ...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}), ...(item.contextLimit !== undefined ? { contextLimit: item.contextLimit } : {}), ...(item.maxOutputTokens !== undefined ? { maxOutputTokens: item.maxOutputTokens } : {}), diff --git a/src/core/models/credential-vault.mjs b/src/core/models/credential-vault.mjs index b46769c2..cd52346e 100644 --- a/src/core/models/credential-vault.mjs +++ b/src/core/models/credential-vault.mjs @@ -4,6 +4,7 @@ import { canonicalHost } from '../../shared/contracts/desktop-host.mjs'; import { observeWindowsProcess } from '../desktop/process-identity.mjs'; import { assertLocalTree } from '../desktop/file-state.mjs'; import { protectCredential, unprotectCredential, credentialError } from '../desktop/windows-dpapi.mjs'; +import { requestCredentialIdentity } from '../../shared/contracts/model-request-contract.mjs'; const metadata = 'modelCredentials'; const sha = value => createHash('sha256').update(value).digest('hex'); @@ -24,7 +25,8 @@ export class CredentialVault { return sha(JSON.stringify(canonicalHost({ app: 'agent-workbench', scope: 'Windows.CurrentUser', userSid: this.userSid, 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' } : {}) }))); + ...(connection.protocol === 'anthropic-messages' ? { messagesAuth: connection.messagesAuth ?? 'api-key' } : {}), + ...(requestCredentialIdentity(connection) ? { requestCredentialIdentity: requestCredentialIdentity(connection) } : {}) }))); } status(connection) { if (connection.credentialSource) return { status: 'reference', storage: 'source-reference', sourceId: connection.credentialSource.connectionId, diff --git a/src/core/models/model-catalog.mjs b/src/core/models/model-catalog.mjs index 7101104c..cf9dd88c 100644 --- a/src/core/models/model-catalog.mjs +++ b/src/core/models/model-catalog.mjs @@ -5,6 +5,7 @@ import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/con 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'; +import { requestCredentialIdentity, requestContractSettings, defaultMessagesAuth, requestCatalogBinding } from '../../shared/contracts/model-request-contract.mjs'; const fail = (message, status = 400) => Object.assign(new Error(message), { status }); const stamp = () => new Date().toISOString(); @@ -12,6 +13,7 @@ const clean = (value, max) => String(value ?? '').trim().slice(0, max); export const credentialScope = connection => createHash('sha256').update(JSON.stringify([ connection.protocol ?? 'chat-completions', connection.baseUrl, connection.requiresKey !== false, connection.protocol === 'anthropic-messages' ? connection.messagesAuth ?? 'api-key' : null, + ...(requestCredentialIdentity(connection) ? [requestCredentialIdentity(connection)] : []), ])).digest('hex'); export class ModelCatalog { @@ -59,8 +61,9 @@ export class ModelCatalog { const baseUrl = validateProtocolEndpoint(protocol, new URL(this.hub.provider.validate({ baseUrl: draft.baseUrl, mode: 'demo' })).toString().replace(/\/+$/, '')); if (baseUrl.length > 1000 || !clean(draft.name, 100)) throw fail('请先填写连接名称和接口根地址。'); connection = { name: clean(draft.name, 100), brand: clean(draft.brand || '自定义', 40), baseUrl, protocol, - ...messagesAuthSettings(protocol, draft.messagesAuth), requiresKey: draft.requiresKey !== false, enabled: true, + ...messagesAuthSettings(protocol, defaultMessagesAuth({ ...draft, baseUrl }, { existing: false })), requiresKey: draft.requiresKey !== false, enabled: true, contextLimit: draft.contextLimit, maxOutputTokens: draft.maxOutputTokens, concurrency: draft.concurrency }; + connection.requestContract = requestContractSettings(draft.requestContract, connection, { existing: false }); key = input.apiKey ?? ''; if (typeof key !== 'string' || key.length > 16000) throw fail('模型凭据格式无效。'); key = key.trim(); explicitKey = key || null; @@ -75,7 +78,7 @@ export class ModelCatalog { controller.signal.throwIfAborted(); this.current({ binding }); if (!unrestricted(this.hub.store) && (Date.now() >= deadline)) throw fail('获取模型目录超过60秒,请稍后重试。'); - const query = cursor ? '?' + cursorParameter + '=' + encodeURIComponent(cursor) + (cursorParameter === 'after_id' ? '&limit=100' : '') : connection.protocol === 'anthropic-messages' ? '?limit=100' : ''; + const query = cursor ? (route.includes('?') ? '&' : '?') + cursorParameter + '=' + encodeURIComponent(cursor) + (cursorParameter === 'after_id' ? '&limit=100' : '') : connection.protocol === 'anthropic-messages' ? (route.includes('?') ? '&' : '?') + '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); @@ -99,7 +102,7 @@ export class ModelCatalog { if (!unrestricted(this.hub.store) && this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value); const fetchedAt = stamp(), expires = Date.now() + 5 * 60000; const preview = { id, entries: [...entries.values()], fetchedAt, expiresAt: new Date(expires).toISOString(), complete, warning, - source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol }, limits: unrestricted(this.hub.store) ? { connections: null, poolMembers: null, catalog: null } : { connections: 100, poolMembers: 32, catalog: 1000 } }; + source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol, ...(connection.requestContract ? { requestContract: structuredClone(connection.requestContract) } : {}) }, limits: unrestricted(this.hub.store) ? { connections: null, poolMembers: null, catalog: null } : { connections: 100, poolMembers: 32, catalog: 1000 } }; this.previews.set(id, { preview, connection, binding, explicitKey, expires }); return preview; } finally { this.active.delete(id); } @@ -131,12 +134,14 @@ export class ModelCatalog { && (connection.id === owner?.id || connection.credentialSource?.connectionId === owner?.id)); const upstreamModel = structuredClone({ ...model, fetchedAt: value.preview.fetchedAt, endpoint: value.connection.baseUrl }); if (prior) { + upstreamModel.requestBinding = { contract: requestCatalogBinding(value.connection), credentialRevision: hub.credential(owner)?.revision ?? 0 }; 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, + ...(value.connection.requestContract ? { requestContract: structuredClone(value.connection.requestContract) } : {}), 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, capabilityDeclarationSources: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state !== 'unknown' ? 'upstream_catalog' : declarations[key] !== 'unknown' ? 'user' : 'protocol'])), @@ -146,6 +151,7 @@ export class ModelCatalog { const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog'; if (!owner) owner = connection; else connection.credentialSource = { connectionId: owner.id, scope: credentialScope(owner) }; + upstreamModel.requestBinding = { contract: requestCatalogBinding(value.connection), credentialRevision: hub.credential(owner)?.revision ?? 0 }; hub.save(); ids.push(connection.id); added.push(connection.id); } let selection = null; diff --git a/src/core/models/model-hub.mjs b/src/core/models/model-hub.mjs index 39b416b5..b936014f 100644 --- a/src/core/models/model-hub.mjs +++ b/src/core/models/model-hub.mjs @@ -18,6 +18,7 @@ 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'; +import { defaultMessagesAuth, effectiveRequestContract, requestContractSettings, requestCredentialIdentity } from '../../shared/contracts/model-request-contract.mjs'; const legacyId = 'legacy-default'; const stamp = () => new Date().toISOString(); @@ -25,7 +26,8 @@ const error = (message, status = 400) => Object.assign(new Error(message), { sta 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]); + connection.protocol === 'anthropic-messages' ? connection.messagesAuth ?? 'api-key' : null, + ...(requestCredentialIdentity(connection) ? [requestCredentialIdentity(connection)] : [])]); function declarationSources(input, previous, declarations) { const provided = input.capabilityDeclarationSources; if (provided !== undefined && (!provided || typeof provided !== 'object' || Array.isArray(provided) @@ -168,7 +170,7 @@ export class ModelHub { 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', + return { ...connection, requestContract: effectiveRequestContract(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' }, @@ -258,12 +260,13 @@ export class ModelHub { 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, capabilityDeclarationSources, ...specificationSettings, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}), - ...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth), + ...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth ?? defaultMessagesAuth({ baseUrl: input.baseUrl, protocol }, { existing: !!previous })), 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() }; + connection.requestContract = requestContractSettings(input.requestContract, connection, { existing: !!previous, previous: previous ? effectiveRequestContract(previous) : null }); // 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) @@ -338,19 +341,23 @@ export class ModelHub { } prepare(config, selection = this.state.selected) { 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 (selection.type === 'legacy' && !this.state.legacyConnection) { + const legacy = { ...config, requestContract: effectiveRequestContract(config), modelConnectionId: legacyId, + modelConnectionRevision: config.configRevision ?? 1, modelCredentialRevision: this.provider.legacyCredentialRevision ?? 1 }; + return { ...legacy, modelSpecification: resolveModelSpecification({ ...legacy, 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 => { 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, + const member = { ...connection, requestContract: effectiveRequestContract(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, + requestContract: structuredClone(members[0].requestContract), modelConnectionRevision: members[0].revision, 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, @@ -444,6 +451,7 @@ export class ModelHub { const progress = event => { if (event.modelIdentity) attempt.modelIdentity = event.modelIdentity; if (event.wireAttemptId) attempt.wireAttemptId = event.wireAttemptId; + if (event.requestMetadata) { attempt.requestMetadata = event.requestMetadata; this.saveAttempts(attempt); } if (event.upstreamResponse) attempt.upstreamResponse = event.upstreamResponse; if (event.consumption) { if (event.consumption.modelIdentity) attempt.modelIdentity = event.consumption.modelIdentity; @@ -477,6 +485,7 @@ export class ModelHub { onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, protocol: modelProtocol(member.protocol), model: member.model, modelAttemptId: attempt.id }); }; const result = await execute({ ...config, ...modelIdentitySettings(member), ...messagesAuthSettings(member.protocol, member.messagesAuth), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true, + requestContract: structuredClone(member.requestContract ?? effectiveRequestContract(member)), modelConnectionRevision: member.revision, modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision }, credential?.key ?? '', actualBody, progress); attempt.status = 'completed'; attempt.usage = result.usage ?? attempt.usage; attempt.usageStatus = attempt.usage ? 'reported' : 'unknown'; if (result.compatibility?.length) attempt.compatibility = result.compatibility; diff --git a/src/core/models/request-contract-audit.mjs b/src/core/models/request-contract-audit.mjs new file mode 100644 index 00000000..2fb139fb --- /dev/null +++ b/src/core/models/request-contract-audit.mjs @@ -0,0 +1,48 @@ +import { createHash } from 'node:crypto'; +import { effectiveRequestContract, requestHeaders, credentialHeader } from '../../shared/contracts/model-request-contract.mjs'; +import { modelRequestUrl } from '../../shared/contracts/model-endpoint.mjs'; +const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' + ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value; +const sha = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(canonical(value))).digest('hex'); +const promptFields = new Set(['model', 'tools', 'system', 'messages', 'input']); +// Redact string values before serialization. A credential containing JSON +// punctuation must never corrupt observation JSON or prevent an HTTP request. +const redactValues = (value, redact) => typeof value === 'string' ? redact(value) + : Array.isArray(value) ? value.map(item => redactValues(item, redact)) + : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([name, item]) => [name, redactValues(item, redact)])) : value; +export function preparedRequestMetadata(connection, body, { headers = requestHeaders(connection, '{{credential}}'), requestUrl = modelRequestUrl(connection), redact = String, wireBody } = {}) { + const contract = effectiveRequestContract(connection); + const templates = requestHeaders(connection, '{{credential}}'); + const observedHeaders = [...new Headers(headers)].map(([name, value]) => { + const template = templates.get(name); + return [name, credentialHeader(name) || template?.includes('{{credential}}') ? template ?? '[credential]' : redact(value)]; + }); + const nonPrompt = body ? Object.fromEntries(Object.entries(body).filter(([name]) => !promptFields.has(name))) : {}; + const nonPromptParameters = redactValues(nonPrompt, redact); + const identity = { connectionId: connection.modelConnectionId ?? connection.id ?? null, + connectionRevision: connection.revision ?? connection.modelConnectionRevision ?? null, + credentialRevision: connection.modelCredentialRevision ?? connection.credentialRevision ?? null }; + const metadata = { schemaVersion: 1, representation: 'fetch-request-metadata-redacted-v1', method: body ? 'POST' : 'GET', + protocol: connection.protocol ?? 'chat-completions', model: body?.model ?? connection.model ?? null, requestUrl: redact(requestUrl), + headers: observedHeaders, identity, contract: redactValues(contract, redact), + bodySha256: body ? sha(wireBody ?? JSON.stringify(body)) : null, + nonPromptParameters, nonPromptSha256: sha(nonPromptParameters), source: 'prepared-fetch-arguments', upstreamCache: 'unknown' }; + metadata.fingerprint = sha({ method: metadata.method, protocol: metadata.protocol, model: metadata.model, requestUrl: metadata.requestUrl, + headers: metadata.headers, identity, nonPromptParameters }); + metadata.fingerprintMethod = 'canonical-json-sha256-without-prompt-or-credential-values-v1'; + return metadata; +} +export function requestContractAudit(body, config, previousBody = null, previousConfig = null) { + const variants = input => input.kind === 'model-route-plan' ? input.variants : [{ connectionId: null, body: input }]; + const entries = (input, settings) => variants(input).map(variant => { + const member = settings.modelRouting?.members?.find(value => value.id === variant.connectionId) ?? settings; + return { connectionId: variant.connectionId, ...preparedRequestMetadata(member, variant.body), + representation: 'frozen-request-contract-redacted-v1', source: 'frozen-run-contract' }; + }); + const prior = previousBody && previousConfig ? entries(previousBody, previousConfig) : []; + return { schemaVersion: 1, method: 'frozen-request-contract-observation-v1', upstreamCache: 'unknown', variants: entries(body, config).map(entry => { + const old = prior.find(value => value.connectionId === entry.connectionId && value.protocol === entry.protocol); + return { ...entry, previousFingerprint: old?.fingerprint ?? null, reason: !old ? 'first_or_new_route' : old.fingerprint === entry.fingerprint ? 'same_observed_contract' : 'observed_contract_changed', + changed: old ? ['model', 'requestUrl', 'headers', 'identity', 'nonPromptParameters'].filter(field => JSON.stringify(canonical(old[field])) !== JSON.stringify(canonical(entry[field]))) : [] }; + }) }; +} diff --git a/src/core/models/upstream-error.mjs b/src/core/models/upstream-error.mjs index e7232ad0..761b3589 100644 --- a/src/core/models/upstream-error.mjs +++ b/src/core/models/upstream-error.mjs @@ -4,7 +4,8 @@ export const ERROR_CAPTURE_LIMIT = 64 * 1024; const PREVIEW_LIMIT = 8000; const allowedHeaders = ['content-type', 'retry-after', 'date', 'x-request-id', 'request-id', 'requestid', 'x-amzn-requestid', 'anthropic-request-id', 'x-ratelimit-limit-requests', 'x-ratelimit-remaining-requests', 'x-ratelimit-reset-requests', - 'x-ratelimit-limit-tokens', 'x-ratelimit-remaining-tokens', 'x-ratelimit-reset-tokens']; + 'x-ratelimit-limit-tokens', 'x-ratelimit-remaining-tokens', 'x-ratelimit-reset-tokens', 'openai-version', 'openai-organization', 'openai-project', 'openai-processing-ms', + 'x-ratelimit-limit-project-tokens', 'x-ratelimit-remaining-project-tokens', 'x-ratelimit-reset-project-tokens', 'anthropic-version', 'anthropic-workspace-id']; export function sanitizeModelText(value, redact = String) { return redact(String(value)) diff --git a/src/server/provider.mjs b/src/server/provider.mjs index b349a6a8..c54ff4d7 100644 --- a/src/server/provider.mjs +++ b/src/server/provider.mjs @@ -12,7 +12,9 @@ import { modelWaitSettings, requestDeadline } from '../core/models/request-deadl import { ModelTransport } from '../core/models/transport.mjs'; import { localModelEstimate } from '../shared/contracts/model-reservation.mjs'; import { ERROR_CAPTURE_LIMIT, readErrorResponse, upstreamCapture } from '../core/models/upstream-error.mjs'; -import { messagesAuthSettings } from '../shared/contracts/model-endpoint.mjs'; +import { endpointRequestUrl } from '../shared/contracts/model-endpoint.mjs'; +import { requestHeaders } from '../shared/contracts/model-request-contract.mjs'; +import { preparedRequestMetadata } from '../core/models/request-contract-audit.mjs'; import { fileDraftToolDefinitions } from '../shared/contracts/file-draft-tools.mjs'; export const engineToolDefinitions = [ @@ -181,13 +183,8 @@ export class Provider { } async request(config, route, body, signal, key = this.apiKey, onProgress, options = {}) { const base = this.validate({ ...config, mode: 'demo' }); - const headers = { 'Content-Type': 'application/json' }; - if (config.protocol === 'anthropic-messages') { - headers['anthropic-version'] = '2023-06-01'; - const { messagesAuth } = messagesAuthSettings(config.protocol, config.messagesAuth); - if (key) headers[messagesAuth === 'bearer' ? 'Authorization' : 'x-api-key'] = messagesAuth === 'bearer' ? 'Bearer ' + key : key; - } else if (key) headers.Authorization = 'Bearer ' + key; - const requestUrl = base + route; + const headers = requestHeaders(config, key); + const requestUrl = endpointRequestUrl(config, route, body ? 'completion' : 'models'); const waits = modelWaitSettings(config), timeoutMs = body || unrestricted(config) ? waits.modelResponseTimeoutMs : 20000; const policy = { attempts: 3, delays: [500, 1500], timeoutMs, totalTimeoutMs: timeoutMs, idleTimeoutMs: waits.modelStreamIdleTimeoutMs, ...this.retryPolicy, ...options }; @@ -235,8 +232,13 @@ export class Provider { const transport=this.fetcher?null:(this.transport??=new ModelTransport()); if(transport)onProgress?.({phase:'running',transport:transport.profile,attempt,maxAttempts:policy.attempts,wireAttemptId:receipt.attemptId}); wireBody = body ? JSON.stringify(body) : undefined; + const bound = { ...config, modelConnectionId: config.modelConnectionId ?? config.id ?? (body ? 'legacy-default' : null), + modelConnectionRevision: config.modelConnectionRevision ?? config.revision ?? (body ? config.configRevision ?? 1 : null), + modelCredentialRevision: config.modelCredentialRevision ?? config.credentialRevision ?? (config.id ? this.hub?.credential(config)?.revision ?? 0 : body ? this.legacyCredentialRevision ?? 1 : null) }; + receipt.requestMetadata = preparedRequestMetadata(bound, body, { headers, requestUrl, wireBody, redact: value => this.redact(value, key) }); const submitted = (this.fetcher??transport.fetch.bind(transport))(requestUrl, { method: body ? 'POST' : 'GET', headers, body: wireBody, signal: requestSignal, redirect: 'manual' }); + try { onProgress?.({ requestMetadata: receipt.requestMetadata, wireAttemptId: receipt.attemptId, attempt, maxAttempts: policy.attempts }); } catch { /* Observe after dispatch without stranding its promise. */ } if (wireBody && options.onSubmitted) { // Optional local observers cannot interrupt an already submitted HTTP // request or leave its promise unobserved. @@ -330,6 +332,7 @@ export class Provider { diagnostic = { ...diagnostic, requestUrl, ...(receipt.responseUrl ? { responseUrl: receipt.responseUrl } : {}), ...(receipt.redirectMode ? { redirected: receipt.redirected, redirectMode: receipt.redirectMode } : {}), origin: diagnostic.origin ?? 'local', wireAttemptId: receipt.attemptId, upstreamRequestId: diagnostic.upstreamRequestId ?? receipt.upstreamRequestId, + ...(receipt.requestMetadata ? { requestMetadata: receipt.requestMetadata } : {}), ...(responseDetails && !diagnostic.upstream ? { upstream: responseDetails } : {}) }; if (readingStream && diagnostic.kind !== 'model_identity') diagnostic = { ...diagnostic, retryable: false, failoverAllowed: false, outcome: streamTerminalSeen ? 'failed' : 'unknown', kind: diagnostic.origin === 'upstream' ? diagnostic.kind : timeout.timeout ? 'timeout' : streamTerminalSeen || diagnostic.kind === 'protocol' ? 'protocol' : 'stream_interrupted', diff --git a/src/shared/contracts/execution.mjs b/src/shared/contracts/execution.mjs index 164ca7f8..933532da 100644 --- a/src/shared/contracts/execution.mjs +++ b/src/shared/contracts/execution.mjs @@ -29,10 +29,11 @@ export function modelSnapshot(config) { ...modelIdentitySettings(config), ...(config.protocol ? { protocol: config.protocol, streaming: config.streaming === true } : {}), ...(config.protocol === 'anthropic-messages' ? { messagesAuth: config.messagesAuth ?? 'api-key' } : {}), + ...(config.requestContract ? { requestContract: structuredClone(config.requestContract) } : {}), ...(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.modelConnectionId ? { modelConnectionId: config.modelConnectionId, modelConnectionRevision: config.modelConnectionRevision, modelCredentialRevision: config.modelCredentialRevision } : {}), ...(config.modelRouting ? { routing: structuredClone(config.modelRouting) } : {}), }; } diff --git a/src/shared/contracts/model-catalog.d.mts b/src/shared/contracts/model-catalog.d.mts index c25a690b..42c099f7 100644 --- a/src/shared/contracts/model-catalog.d.mts +++ b/src/shared/contracts/model-catalog.d.mts @@ -6,11 +6,12 @@ export interface CatalogModel { inputModalities?: string[]; outputModalities?: string[]; nativeTools?: string[]; apiCapabilities?: Record>; rawItem?: Record; rawRepresentation?: string; rawSha256?: string; rawBytes?: number; endpoint?: string; fetchedAt?: string; + requestBinding?: { contract: ReturnType; credentialRevision: number }; } export interface CatalogPreview { id: string; entries: CatalogModel[]; fetchedAt: string; expiresAt: string; complete: boolean; warning: string; - source: { name: string; baseUrl: string; protocol: string }; limits: { connections: number | null; poolMembers: number | null; catalog: number | null }; + source: { name: string; baseUrl: string; protocol: string; requestContract?: import('./model-request-contract.mjs').RequestContract }; limits: { connections: number | null; poolMembers: number | null; catalog: number | null }; } -export function catalogRoute(config: { protocol?: string; baseUrl: string }): string; +export function catalogRoute(config: { protocol?: string; baseUrl: string; requestContract?: import('./model-request-contract.mjs').RequestContract }): string; export function catalogModel(item: unknown, config?: { executionMode?: string }): CatalogModel; 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 5f3f3e81..6b93bcb0 100644 --- a/src/shared/contracts/model-catalog.mjs +++ b/src/shared/contracts/model-catalog.mjs @@ -17,6 +17,7 @@ function rawDeclaration(value) { } export function catalogRoute(config) { + if (config.requestContract?.modelsPath != null) return config.requestContract.modelsPath; const protocol = modelProtocol(config.protocol); return protocol === 'anthropic-messages' && !/\/v1$/i.test(new URL(config.baseUrl).pathname.replace(/\/+$/, '')) ? '/v1/models' : '/models'; diff --git a/src/shared/contracts/model-endpoint.d.mts b/src/shared/contracts/model-endpoint.d.mts index aa47eea8..7fa6b6df 100644 --- a/src/shared/contracts/model-endpoint.d.mts +++ b/src/shared/contracts/model-endpoint.d.mts @@ -1,5 +1,6 @@ export function protocolLabel(protocol: string): string; -export function protocolRoute(config: { protocol?: string; baseUrl: string }): string; -export function modelRequestUrl(config: { protocol?: string; baseUrl: string }): string; +export function protocolRoute(config: { protocol?: string; baseUrl: string; requestContract?: import('./model-request-contract.mjs').RequestContract }): string; +export function endpointRequestUrl(config: { protocol?: string; baseUrl: string; requestContract?: import('./model-request-contract.mjs').RequestContract }, route: string, purpose?: string): string; +export function modelRequestUrl(config: { protocol?: string; baseUrl: string; requestContract?: import('./model-request-contract.mjs').RequestContract }): string; export function messagesAuthSettings(protocol?: string, value?: string): { messagesAuth?: string }; export function validateProtocolEndpoint(protocol: string, baseUrl: string): string; diff --git a/src/shared/contracts/model-endpoint.mjs b/src/shared/contracts/model-endpoint.mjs index 82af0651..21383a7b 100644 --- a/src/shared/contracts/model-endpoint.mjs +++ b/src/shared/contracts/model-endpoint.mjs @@ -3,6 +3,7 @@ import { modelProtocol } from './model-capabilities.mjs'; export const protocolLabel = protocol => ({ 'chat-completions': 'Chat Completions', responses: 'Responses', 'anthropic-messages': 'Anthropic Messages' }[protocol] ?? protocol); export function protocolRoute(config) { + if (config.requestContract?.completionPath != null) return config.requestContract.completionPath; const protocol = modelProtocol(config.protocol); if (protocol === 'responses') return '/responses'; if (protocol === 'anthropic-messages') { @@ -12,7 +13,11 @@ export function protocolRoute(config) { return '/chat/completions'; } -export function modelRequestUrl(config) { return config.baseUrl.replace(/\/+$/, '') + protocolRoute(config); } +export function endpointRequestUrl(config, route, purpose = 'completion') { + return config.requestContract?.[purpose === 'models' ? 'modelsPath' : 'completionPath'] != null + ? new URL(route, new URL(config.baseUrl).origin).href : config.baseUrl.replace(/\/+$/, '') + route; +} +export function modelRequestUrl(config) { return endpointRequestUrl(config, protocolRoute(config)); } export function messagesAuthSettings(protocol, value) { if (protocol !== 'anthropic-messages') return {}; diff --git a/src/shared/contracts/model-request-contract.d.mts b/src/shared/contracts/model-request-contract.d.mts new file mode 100644 index 00000000..06cfc2e4 --- /dev/null +++ b/src/shared/contracts/model-request-contract.d.mts @@ -0,0 +1,13 @@ +export interface RequestContract { schemaVersion: 1; defaultsVersion: string; anthropicVersion: string | null; versionSource: string; anthropicBetas: string[]; auth: 'default' | 'none'; headers: Record; completionPath: string | null; modelsPath: string | null } +export interface RequestConnection { baseUrl?: string; protocol?: string; messagesAuth?: string; requestContract?: RequestContract; model?: string; id?: string; revision?: number; modelConnectionId?: string; credentialRevision?: number; modelCredentialRevision?: number } +export const REQUEST_CONTRACT_SCHEMA: number; +export const REQUEST_CONTRACT_DEFAULTS_VERSION: string; +export const REQUEST_CONTRACT_SOURCES: Record; +export function credentialHeader(name: string): boolean; +export function officialRequestProvider(connection?: RequestConnection): string | null; +export function defaultMessagesAuth(connection: RequestConnection, options?: { existing?: boolean }): string; +export function requestContractSettings(value: unknown, connection?: RequestConnection, options?: { existing?: boolean; previous?: RequestContract | null; trusted?: boolean }): RequestContract; +export function effectiveRequestContract(connection?: RequestConnection): RequestContract; +export function requestHeaders(connection: RequestConnection, key?: string): Headers; +export function requestCredentialIdentity(connection: RequestConnection): { auth: string; headers: (string | null)[][]; completionPath: string | null; modelsPath: string | null } | null; +export function requestCatalogBinding(connection: RequestConnection): { schemaVersion: number; protocol: string; requestUrl: string; headers: [string, string][] }; diff --git a/src/shared/contracts/model-request-contract.mjs b/src/shared/contracts/model-request-contract.mjs new file mode 100644 index 00000000..1222d503 --- /dev/null +++ b/src/shared/contracts/model-request-contract.mjs @@ -0,0 +1,98 @@ +export const REQUEST_CONTRACT_SCHEMA = 1; +export const REQUEST_CONTRACT_DEFAULTS_VERSION = '2026-11-07.1'; +export const REQUEST_CONTRACT_SOURCES = Object.freeze({ + anthropicVersion: { url: 'https://platform.claude.com/docs/en/api/versioning', checkedAt: '2026-11-07', sha256: '47b7a604ef4d29427a8b02de7404d2146359371ac2c865c06be6e34cf385f990' }, + anthropicAuth: { url: 'https://platform.claude.com/docs/en/api/overview', checkedAt: '2026-11-07', sha256: 'e01f368e0ced0dd2aeec56ed76810eecaf3ba470490afea4f22dfdffd858c9e2' }, + anthropicBetas: { url: 'https://platform.claude.com/docs/en/api/beta-headers', checkedAt: '2026-11-07', sha256: 'a5eaed2894dee4da4dc9f80f7e58383e53545b42eea69f9aa780c7048280245d' }, + openai: { url: 'https://developers.openai.com/api/reference/overview', checkedAt: '2026-11-07', sha256: '23f1fae74b726b95d06dd195411b06e97c1d1356e0bbb58da54a15a8ce1f89af' }, + deepseek: { url: 'https://api-docs.deepseek.com/api/create-message.md', checkedAt: '2026-11-07', sha256: '46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8' }, +}); +const fail = message => { throw Object.assign(new Error(message), { status: 400 }); }; +const object = value => value && typeof value === 'object' && !Array.isArray(value); +export const credentialHeader = name => /^(?:authorization|proxy-authorization|x-api-key|api-key|cookie|set-cookie|.*(?:api[-_]?key|access[-_]?token|auth[-_]?token|secret))$/i.test(name); +export function officialRequestProvider(connection = {}) { + try { const url = new URL(connection.baseUrl); return url.protocol === 'https:' && !url.port ? { 'api.anthropic.com': 'anthropic', 'api.openai.com': 'openai', 'api.deepseek.com': 'deepseek' }[url.hostname] ?? null : null; } + catch { return null; } +} +export function defaultMessagesAuth(connection, { existing = true } = {}) { + return connection.messagesAuth ?? (!existing && officialRequestProvider(connection) === 'anthropic' ? 'bearer' : 'api-key'); +} +function defaults(connection, existing) { + const provider = officialRequestProvider(connection), messages = connection.protocol === 'anthropic-messages'; + return { schemaVersion: REQUEST_CONTRACT_SCHEMA, defaultsVersion: REQUEST_CONTRACT_DEFAULTS_VERSION, + anthropicVersion: messages ? !existing && provider === 'anthropic' ? '2026-10-21' : !existing && provider === 'deepseek' ? null : '2023-06-01' : null, + versionSource: existing ? 'legacy-default' : provider ? 'official-default' : 'compatibility-default', + anthropicBetas: [], auth: 'default', headers: {}, + completionPath: !existing && messages && provider === 'deepseek' ? '/anthropic/v1/messages' : null, + modelsPath: !existing && provider === 'deepseek' ? '/models' : null }; +} +// Validate HTTP representation, not vendor semantics or an artificial quota. +// Version/beta names remain explicit and unknown values go to the upstream. +export function requestContractSettings(value, connection = {}, { existing = true, previous = null, trusted = false } = {}) { + const initial = previous ?? defaults(connection, existing); + if (value === undefined) return structuredClone(initial); + if (!object(value) || value.schemaVersion !== undefined && value.schemaVersion !== REQUEST_CONTRACT_SCHEMA) fail('请求协议设置需要已支持版本的 JSON 对象。'); + const keys = ['schemaVersion', 'defaultsVersion', 'anthropicVersion', 'versionSource', 'anthropicBetas', 'auth', 'headers', 'completionPath', 'modelsPath']; + if (Object.keys(value).some(key => !keys.includes(key))) fail('请求协议设置含未知字段,请在原生参数或对应设置中填写。'); + const result = { ...structuredClone(initial), ...structuredClone(value), schemaVersion: REQUEST_CONTRACT_SCHEMA }; + if (typeof result.defaultsVersion !== 'string' || !result.defaultsVersion) fail('请求协议资料版本无效。'); + if (result.anthropicVersion !== null && typeof result.anthropicVersion !== 'string') fail('API 版本需要字符串或 null(省略)。'); + if (!Array.isArray(result.anthropicBetas) || result.anthropicBetas.some(item => typeof item !== 'string')) fail('Beta 需要字符串数组。'); + if (!['default', 'none'].includes(result.auth)) fail('鉴权请选择连接默认或不自动添加。'); + if (!object(result.headers) || Object.values(result.headers).some(item => item !== null && typeof item !== 'string')) fail('额外请求头需要字符串或 null(移除)的 JSON 对象。'); + for (const [name, header] of Object.entries(result.headers)) { + // Keys are managed in their existing memory/DPAPI store, never copied into + // ordinary connection metadata, Run snapshots or diagnostic fingerprints. + if (header && credentialHeader(name) && !header.includes('{{credential}}')) fail('鉴权或会话头请用 {{credential}} 引用独立 Key;凭据在 API Key 设置中填写。'); + try { new Headers([[name, (header ?? '').replaceAll('{{credential}}', 'credential')]]); } + catch { fail('请求头名称或值不符合 HTTP 格式:' + name); } + } + try { if (result.anthropicVersion !== null) new Headers([['anthropic-version', result.anthropicVersion]]); new Headers([['anthropic-beta', result.anthropicBetas.join(',')]]); } + catch { fail('API 版本或 Beta 值不符合 HTTP 头格式。'); } + for (const name of ['completionPath', 'modelsPath']) { + const route = result[name]; + if (route !== null && (typeof route !== 'string' || !route.startsWith('/') || route.startsWith('//') || /[\x00-\x20\x7f#\\]/.test(route))) fail('请求路径需要从 / 开始的同源路径,或 null(使用协议默认)。'); + if (route !== null) { + const base = new URL(connection.baseUrl), url = new URL(route, base.origin); + if (url.origin !== base.origin || url.username || url.password) fail('自定义请求路径必须与连接同源。'); + } + } + if (!trusted) result.versionSource = Object.hasOwn(value, 'anthropicVersion') && (!previous || value.anthropicVersion !== previous.anthropicVersion) ? 'explicit' : initial.versionSource; + if (!['legacy-default', 'official-default', 'compatibility-default', 'explicit'].includes(result.versionSource)) fail('请求版本来源无效。'); + return result; +} +export function effectiveRequestContract(connection = {}) { + return requestContractSettings(connection.requestContract, connection, { trusted: true }); +} +export function requestHeaders(connection, key = '') { + const contract = effectiveRequestContract(connection), headers = new Headers({ 'Content-Type': 'application/json' }); + if (connection.protocol === 'anthropic-messages') { + if (contract.anthropicVersion !== null) headers.set('anthropic-version', contract.anthropicVersion); + if (contract.anthropicBetas.length) headers.set('anthropic-beta', contract.anthropicBetas.join(',')); + } + if (contract.auth === 'default' && key) { + const apiKey = connection.protocol === 'anthropic-messages' && defaultMessagesAuth(connection) !== 'bearer'; + headers.set(apiKey ? 'x-api-key' : 'Authorization', apiKey ? key : 'Bearer ' + key); + } + for (const [name, value] of Object.entries(contract.headers)) { + if (value === null) headers.delete(name); + else headers.set(name, value.replaceAll('{{credential}}', key)); + } + return headers; +} +// Keep legacy hashes exactly when only non-authentication settings were added. +export function requestCredentialIdentity(connection) { + if (!connection.requestContract) return null; + const contract = effectiveRequestContract(connection); + const headers = Object.entries(contract.headers).filter(([name, value]) => credentialHeader(name) || value?.includes('{{credential}}')) + .map(([name, value]) => [name.toLowerCase(), value]).sort(([left], [right]) => left.localeCompare(right)); + return contract.auth !== 'default' || headers.length || contract.completionPath !== null || contract.modelsPath !== null + ? { auth: contract.auth, headers, completionPath: contract.completionPath, modelsPath: contract.modelsPath } : null; +} + +export function requestCatalogBinding(connection) { + const contract = effectiveRequestContract(connection), base = new URL(connection.baseUrl), protocol = connection.protocol ?? 'chat-completions'; + const defaultPath = protocol === 'anthropic-messages' && !/\/v1$/i.test(base.pathname.replace(/\/+$/, '')) ? '/v1/models' : '/models'; + const requestUrl = contract.modelsPath === null ? connection.baseUrl.replace(/\/+$/, '') + defaultPath : new URL(contract.modelsPath, base.origin).href; + return { schemaVersion: 1, protocol, requestUrl, headers: [...requestHeaders(connection, '{{credential}}')] }; +} diff --git a/src/shared/contracts/official-model-registry.d.mts b/src/shared/contracts/official-model-registry.d.mts index 5594c2ef..ea0e6dcd 100644 --- a/src/shared/contracts/official-model-registry.d.mts +++ b/src/shared/contracts/official-model-registry.d.mts @@ -1,13 +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 interface ModelSpecification { schemaVersion: number; registryVersion: string; model: string; protocol: string; provider: string | null; providerSource: string; apiVersion: string | null; connectionBinding?: { baseUrl: string | null; providerId: string | null; apiVersion: string | null; messagesAuth: string | null; requestContract: import('./model-request-contract.mjs').RequestContract; credentialRevision: number }; 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; requestContract?: import('./model-request-contract.mjs').RequestContract; messagesAuth?: string; nativeParameters?: Record; modelOverrides?: Record; modelSpecification?: ModelSpecification; modelSpecificationFrozen?: boolean; upstreamModel?: import('./model-catalog.mjs').CatalogModel; capabilityDeclarations?: Record; capabilityDeclarationSources?: Record; credentialRevision?: number; modelCredentialRevision?: 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 matchingUpstreamModel(connection?: ModelSpecConnection, credentialRevision?: number): 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 index d0ac0843..3ddb53b7 100644 --- a/src/shared/contracts/official-model-registry.mjs +++ b/src/shared/contracts/official-model-registry.mjs @@ -1,5 +1,6 @@ import sources from './official-model-sources.json' with { type: 'json' }; import { officialModelRecords } from './official-model-registry-data.mjs'; +import { effectiveRequestContract, requestCatalogBinding, defaultMessagesAuth } from './model-request-contract.mjs'; export const MODEL_REGISTRY_SCHEMA = 1; export const MODEL_REGISTRY_VERSION = sources.registryVersion; @@ -64,9 +65,12 @@ export function officialModelRecord(connection = {}) { return rows.length === 1 ? rows[0] : null; } -export function matchingUpstreamModel(connection = {}) { +export function matchingUpstreamModel(connection = {}, credentialRevision = connection.modelCredentialRevision ?? connection.credentialRevision) { const item = connection.upstreamModel; - return item?.id === connection.model && (!item.endpoint || item.endpoint === connection.baseUrl) ? item : null; + if (!item || item.id !== connection.model || item.endpoint && item.endpoint !== connection.baseUrl) return null; + if (item.requestBinding && (JSON.stringify(item.requestBinding.contract) !== JSON.stringify(requestCatalogBinding(connection)) + || credentialRevision !== undefined && item.requestBinding.credentialRevision !== credentialRevision)) return null; + return item; } export function modelOverrideSettings(input, previous = {}) { @@ -111,9 +115,13 @@ function overrideFacts(value) { 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); +export function resolveModelSpecification(connection = {}, credentialRevision = connection.modelCredentialRevision ?? connection.credentialRevision ?? 0) { + const connectionBinding = { baseUrl: connection.baseUrl ?? null, providerId: connection.providerId ?? null, apiVersion: connection.apiVersion ?? null, + messagesAuth: connection.protocol === 'anthropic-messages' ? defaultMessagesAuth(connection) : null, + requestContract: effectiveRequestContract(connection), credentialRevision }; + if (connection.modelSpecificationFrozen === true && connection.modelSpecification?.model === connection.model && connection.modelSpecification.protocol === (connection.protocol ?? 'chat-completions') + && (!connection.modelSpecification.connectionBinding || JSON.stringify(connection.modelSpecification.connectionBinding) === JSON.stringify(connectionBinding))) return structuredClone(connection.modelSpecification); + const provider = modelProvider(connection), entry = officialModelRecord(connection), catalog = matchingUpstreamModel(connection, credentialRevision); const candidates = new Map(), add = (key, value, origin) => { const values = candidates.get(key) ?? []; values.push({ value: structuredClone(value), ...origin }); candidates.set(key, values); @@ -144,7 +152,7 @@ export function resolveModelSpecification(connection = {}, credentialRevision = 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, + provider: provider.id, providerSource: provider.source, apiVersion: connection.apiVersion && connection.apiVersion !== 'auto' ? connection.apiVersion : entry?.apiVersion ?? null, connectionBinding, 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' }; diff --git a/task_plan.md b/task_plan.md index 9dd64f12..b3cc6288 100644 --- a/task_plan.md +++ b/task_plan.md @@ -1,5 +1,7 @@ # Agent Workbench:核心代理能力研究与产品计划 +I14/I12核心阶段2–3完成:最后相关38/38和tsc通过,原Run冻结设置与实际fetch头分开,目录声明按URL/头/凭据修订绑定;旧密文、快照和ordered-prefix保持。原source-related-1为113/114、第二轮142/143及其原断言补验1/1分别记录,不冒称同轮全绿。阶段4独立构建/两端UI正在开始,详见[请求契约计划](docs/M2-REQUEST-CONTRACT-PLAN.md);Mnemo仅只读核对新报告,M2余项/M3/历史unknown保持。 + M2第四批I14/I12从c7d1ad5e干净/远端一致基线开始,见[请求契约计划](docs/M2-REQUEST-CONTRACT-PLAN.md)。已实际取得官方OpenAI overview与Anthropic版本/头说明,先固定来源和旧/新默认分离,再请求版本/头/路径/快照与去凭据指纹。I15原根只读,0真实Key/模型/正式写入,不委派或重启;I09/I11/CI/M3与历史unknown保持。 M2 I15阶段1–5完成:源码ba4b4491/b5aaf1f7、来源0cbf14a2和验收bf07e66d已普通增量推送,既有GitAtlas分支逐SHA一致,[回执](docs/gitatlas-m2-official-registry-push.json)随完成接续再提交。5688原件/23当前链接只读复核通过,正式/历史unknown保持;下一I14与缓存块/亲和/状态、CI,再M3。 diff --git a/tests/model-request-contract.test.mjs b/tests/model-request-contract.test.mjs new file mode 100644 index 00000000..3b57af19 --- /dev/null +++ b/tests/model-request-contract.test.mjs @@ -0,0 +1,258 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import { createHash } from 'node:crypto'; +import { fixture, compatibleFixture, completion, call } from './helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Store } from '../src/server/store.mjs'; +import { Runtime } from '../src/server/runtime.mjs'; +import { CredentialVault } from '../src/core/models/credential-vault.mjs'; +import { credentialScope } from '../src/core/models/model-catalog.mjs'; +import { modelSnapshot } from '../src/shared/contracts/execution.mjs'; +import { completionBody } from '../src/shared/contracts/model-request.mjs'; +import { prefixAudit } from '../src/core/context/prefix-audit.mjs'; +import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs'; +import { preparedRequestMetadata, requestContractAudit } from '../src/core/models/request-contract-audit.mjs'; +import { defaultMessagesAuth, requestContractSettings, effectiveRequestContract, requestHeaders, REQUEST_CONTRACT_SOURCES } from '../src/shared/contracts/model-request-contract.mjs'; +import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs'; +import { resolveModelSpecification, matchingUpstreamModel } from '../src/shared/contracts/official-model-registry.mjs'; + +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); +const open = { mode: 'compatible', executionMode: 'unrestricted', capacityMode: 'passthrough', historyPolicy: 'preserve', maxOutputTokens: 128000 }; +const messagesResponse = () => ({ id: 'owned-message', type: 'message', role: 'assistant', model: 'claude-opus-5-5', content: [{ type: 'text', text: '完成' }], stop_reason: 'end_turn', usage: { input_tokens: 7, output_tokens: 2 } }); +const response = () => ({ id: 'owned-response', status: 'completed', model: 'gpt-6.1-sol', output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: '完成' }] }], usage: { input_tokens: 7, output_tokens: 2, total_tokens: 9 } }); +function ownedHub(f) { + const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store); + f.onCleanup(() => provider.abortRequests()); + hub.credentialVault = new CredentialVault(f.store, provider, { protect: bytes => Buffer.concat([Buffer.from('owned-only:'), bytes]), unprotect: bytes => bytes.subarray(11) }); + return { provider, hub }; +} + +test('request defaults cite pinned successful official sources; the region redirect is preserved and rejected', () => { + const manifest = JSON.parse(fs.readFileSync(new URL('./fixtures/model-request-contract/SOURCE.json', import.meta.url))); + assert.equal(manifest.sources.filter(source => source.accepted !== false).length, 11); + const rejected = manifest.sources.find(source => source.id === 'anthropic-migration'); + assert.equal(rejected.accepted, false); assert.match(rejected.responseUrl, /app-unavailable-in-region/); + for (const source of manifest.sources) { + const bytes = fs.readFileSync(new URL('./fixtures/model-request-contract/' + source.file, import.meta.url)); + assert.equal(sha(bytes), source.sha256, source.id); assert.equal(bytes.length, source.bytes); + } + for (const source of Object.values(REQUEST_CONTRACT_SOURCES)) assert.ok(manifest.sources.some(item => item.accepted !== false && item.sha256 === source.sha256 && item.url === source.url)); +}); + +test('new official defaults, existing connections and compatibility aliases have separate request contracts', () => { + assert.equal(matchingUpstreamModel(), null); assert.equal(resolveModelSpecification().model, ''); + const official = { protocol: 'anthropic-messages', baseUrl: 'https://api.anthropic.com', model: 'claude-opus-5-5' }; + const fresh = requestContractSettings(undefined, official, { existing: false }); + assert.equal(fresh.anthropicVersion, '2026-10-21'); assert.equal(fresh.versionSource, 'official-default'); + assert.equal(defaultMessagesAuth(official, { existing: false }), 'bearer'); + assert.equal(effectiveRequestContract(official).anthropicVersion, '2023-06-01'); assert.equal(defaultMessagesAuth(official), 'api-key'); + const proxy = { ...official, baseUrl: 'https://proxy.invalid', brand: 'Anthropic', providerId: 'anthropic' }; + assert.equal(requestContractSettings(undefined, proxy, { existing: false }).anthropicVersion, '2023-06-01'); + const deepseek = { ...official, baseUrl: 'https://api.deepseek.com/anthropic' }; + const contract = requestContractSettings(undefined, deepseek, { existing: false }); + assert.equal(contract.anthropicVersion, null); assert.equal(modelRequestUrl({ ...deepseek, requestContract: contract }), 'https://api.deepseek.com/anthropic/v1/messages'); + assert.equal(requestHeaders({ ...deepseek, requestContract: contract }, 'owned-key').has('anthropic-version'), false); + assert.equal(effectiveRequestContract(deepseek).anthropicVersion, '2023-06-01'); +}); + +test('explicit headers override case-insensitively, reference credentials and remove defaults without vendor whitelists or local quotas', () => { + const connection = { protocol: 'anthropic-messages', baseUrl: 'https://proxy.invalid/v1' }; + const headers = Object.fromEntries(Array.from({ length: 513 }, (_, index) => ['x-owned-' + index, 'kept-' + index])); + Object.assign(headers, { 'X-Client-Request-Id': 'a'.repeat(800), 'x-owned-long': 'b'.repeat(70 * 1024), Authorization: 'Basic {{credential}}', 'x-api-key': null, 'Content-Type': null, + 'anthropic-version': 'future-unknown-version', 'x-any-vendor-option': 'unchanged' }); + const contract = requestContractSettings({ anthropicBetas: ['unknown-beta', 'another-beta', 'unknown-beta'], headers }, connection); + const actual = requestHeaders({ ...connection, requestContract: contract }, 'owned-only-key'); + assert.equal(actual.get('authorization'), 'Basic owned-only-key'); assert.equal(actual.has('x-api-key'), false); assert.equal(actual.has('content-type'), false); + assert.equal(actual.get('anthropic-version'), 'future-unknown-version'); assert.equal(actual.get('anthropic-beta'), 'unknown-beta,another-beta,unknown-beta'); + assert.equal(actual.get('x-owned-long').length, 70 * 1024); assert.equal(actual.get('x-client-request-id').length, 800); + assert.equal(actual.get('x-owned-512'), 'kept-512'); + assert.throws(() => requestContractSettings({ headers: { 'bad\nname': 'value' } }, connection), /HTTP/); + assert.throws(() => requestContractSettings({ headers: { Authorization: 'Bearer plaintext-key' } }, connection), /独立 Key/); + assert.throws(() => requestContractSettings({ completionPath: '//other.invalid/messages' }, connection), /同源/); +}); + +test('mixed pool sends each frozen member version/auth/path/headers and records actual fetch metadata without keys', async t => { + const f = fixture(t, { modernDefaults: true }); + const server = await compatibleFixture(t, (url, input) => ({ body: url.startsWith('/owned/messages') ? messagesResponse() : response(), headers: { 'openai-version': '2020-10-01', 'openai-organization': 'org-owned', 'openai-processing-ms': '17', 'x-request-id': 'owned-request' } })); + const { provider, hub } = ownedHub(f); + const first = hub.upsert({ name: '自有 Messages', protocol: 'anthropic-messages', model: 'claude-opus-5-5', baseUrl: server.baseUrl, apiKey: 'owned-first-key', + requestContract: { anthropicVersion: '2026-10-21', anthropicBetas: ['owned-beta'], completionPath: '/owned/messages', headers: { 'anthropic-workspace-id': 'workspace-owned' } } }); + const second = hub.upsert({ name: '自有 Responses', protocol: 'responses', model: 'gpt-6.1-sol', baseUrl: server.baseUrl, apiKey: 'owned-second-key', + requestContract: { completionPath: '/owned/responses', headers: { 'OpenAI-Project': 'project-owned' } } }); + const pool = hub.pool({ name: '独立成员设置', members: [{ connectionId: first.id }, { connectionId: second.id }], sticky: false }); + const prepared = hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'pool', id: pool.id }), frozen = modelSnapshot(prepared), before = JSON.stringify(frozen); + for (let index = 0; index < 2; index++) await provider.complete(prepared, [{ role: 'user', content: '单次所属请求' }], null, undefined, undefined, null, []); + assert.equal(server.requests.length, 2); + assert.equal(server.requests[0].url, '/owned/messages'); assert.equal(server.requests[0].headers['anthropic-version'], '2026-10-21'); + assert.equal(server.requests[0].headers['x-api-key'], 'owned-first-key'); assert.equal(server.requests[0].headers['openai-project'], undefined); + assert.equal(server.requests[1].url, '/owned/responses'); assert.equal(server.requests[1].headers.authorization, 'Bearer owned-second-key'); + assert.equal(server.requests[1].headers['anthropic-version'], undefined); assert.equal(server.requests[1].headers['anthropic-beta'], undefined); + assert.equal(server.requests[1].headers['anthropic-workspace-id'], undefined); assert.equal(server.requests[1].headers['openai-project'], 'project-owned'); + for (const attempt of hub.attempts) { + assert.equal(attempt.status, 'completed'); assert.equal(attempt.requestMetadata.bodySha256, attempt.requestSha256); + assert.equal(attempt.requestMetadata.identity.connectionRevision, attempt.connectionRevision); + assert.equal(attempt.requestMetadata.identity.credentialRevision, attempt.credentialRevision); + assert.equal(attempt.upstreamResponse.headers['openai-version'], '2020-10-01'); + assert.equal(attempt.upstreamResponse.headers['openai-processing-ms'], '17'); + assert.equal(attempt.requestMetadata.upstreamCache, 'unknown'); assert.doesNotMatch(JSON.stringify(attempt), /owned-(?:first|second)-key/); + assert.equal(attempt.requestMetadata.source, 'prepared-fetch-arguments'); + } + const changed = hub.upsert({ ...hub.connection(first.id), requestContract: { ...first.requestContract, anthropicVersion: 'future-explicit-version' } }); + assert.equal(changed.requestContract.anthropicVersion, 'future-explicit-version'); assert.equal(JSON.stringify(frozen), before); + assert.equal(hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: first.id }).requestContract.anthropicVersion, 'future-explicit-version'); +}); + +test('new API version errors preserve the user sampling body and response/version diagnostics without automatic edits or replay', async t => { + const f = fixture(t, { modernDefaults: true }); + const server = await compatibleFixture(t, () => ({ status: 400, body: { error: { type: 'invalid_request_error', message: 'temperature is removed in 2026-10-21', param: 'temperature' } }, headers: { 'anthropic-version': '2026-10-21', 'x-request-id': 'owned-invalid-version' } })); + const { provider, hub } = ownedHub(f), native = { temperature: 0.7, top_p: 0.8, top_k: 5, output_config: { effort: 'high', vendor: { keep: true } } }; + const source = hub.upsert({ name: '自有原错', protocol: 'anthropic-messages', model: 'claude-opus-5-5', baseUrl: server.baseUrl, apiKey: 'owned-error-key', nativeParameters: native, + requestContract: { anthropicVersion: '2026-10-21', anthropicBetas: ['unknown-beta'], headers: { 'x-owned-auth': '{{credential}}' } } }); + await assert.rejects(provider.complete(hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: source.id }), [{ role: 'user', content: '保留参数' }], null, undefined, undefined, null, []), cause => { + assert.equal(cause.diagnostic.httpStatus, 400); assert.match(cause.diagnostic.upstream.rawPreview, /temperature is removed/); + assert.equal(cause.diagnostic.requestMetadata.headers.find(([name]) => name === 'anthropic-version')[1], '2026-10-21'); + assert.equal(cause.diagnostic.retryDecision, 'passthrough'); return true; + }); + assert.equal(server.requests.length, 1); for (const [name, value] of Object.entries(native)) assert.deepEqual(server.requests[0].input[name], value); + const attempt = hub.attempts[0]; assert.equal(attempt.status, 'failed'); assert.equal(attempt.upstreamResponse.headers['anthropic-version'], '2026-10-21'); + assert.doesNotMatch(JSON.stringify(attempt), /owned-error-key/); assert.deepEqual(hub.connection(source.id).nativeParameters, native); +}); + +test('request observations redact values structurally even when a synthetic credential contains JSON punctuation', async t => { + const f = fixture(t, { modernDefaults: true }); + const server = await compatibleFixture(t, () => ({ status: 400, body: { error: { type: 'invalid_request_error', message: 'owned upstream rejection' } } })); + const { provider, hub } = ownedHub(f); + const source = hub.upsert({ name: '自有脱敏边界', protocol: 'chat-completions', model: 'owned-redaction-model', baseUrl: server.baseUrl, apiKey: '{', + nativeParameters: { temperature: 0.7, metadata: { note: '{value}', preserved: [null, false, 9] } } }); + const config = hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: source.id }); + await assert.rejects(provider.complete(config, [{ role: 'user', content: '单次请求' }], null, undefined, undefined, null, []), cause => { + assert.equal(cause.diagnostic.httpStatus, 400); assert.equal(cause.diagnostic.origin, 'upstream'); return true; + }); + assert.equal(server.requests.length, 1); assert.equal(server.requests[0].input.metadata.note, '{value}'); + const observed = hub.attempts[0].requestMetadata; + assert.equal(observed.nonPromptParameters.temperature, 0.7); assert.equal(observed.nonPromptParameters.metadata.note, '[已隐藏]value}'); + assert.deepEqual(observed.nonPromptParameters.metadata.preserved, [null, false, 9]); + assert.equal(observed.contract.schemaVersion, 1); assert.equal(observed.bodySha256, hub.attempts[0].requestSha256); +}); + +test('version/beta/non-auth edits preserve encrypted binding and shared catalog credentials; auth/path changes invalidate without resurrecting old blocks', t => { + const f = fixture(t, { modernDefaults: true }), { provider, hub } = ownedHub(f); + const source = hub.upsert({ name: '自有绑定', model: 'owned-model', protocol: 'chat-completions', baseUrl: 'http://127.0.0.1:1/v1', apiKey: 'owned-contract-key', persistKey: true }); + const cipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value; + const credential = provider.credentials.get(source.id), scope = credentialScope(hub.connection(source.id)); + hub.vault().protect = () => { throw Error('Must not re-encrypt original credential'); }; + const harmless = hub.upsert({ ...hub.connection(source.id), requestContract: { ...source.requestContract, anthropicVersion: 'explicit-future', anthropicBetas: ['owned'], headers: { 'OpenAI-Organization': 'org-owned', 'OpenAI-Project': 'project-owned' } } }); + assert.equal(harmless.credentialBindingRevision, source.credentialBindingRevision); assert.equal(credentialScope(harmless), scope); + assert.equal(hub.vault().status(harmless).status, 'saved'); assert.equal(provider.credentials.get(source.id), credential); + assert.equal(f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value, cipher); + f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close()); + const newProvider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), restoredHub = newProvider.modelHub(reopened); + f.onCleanup(() => newProvider.abortRequests()); + restoredHub.credentialVault = new CredentialVault(reopened, newProvider, { protect: () => { throw Error('Restore cannot encrypt'); }, unprotect: bytes => bytes.subarray(11) }); + restoredHub.credentialVault.restore(restoredHub); assert.equal(newProvider.credentials.get(source.id)?.key, 'owned-contract-key'); + const restored = restoredHub.connection(source.id); + const edited = restoredHub.upsert({ ...restored, requestContract: { ...restored.requestContract, auth: 'none', headers: { 'x-owned-key': '{{credential}}' }, completionPath: '/changed/chat' } }); + assert.equal(restoredHub.vault().status(edited).status, 'source_changed'); + const reverted = restoredHub.upsert({ ...edited, requestContract: restored.requestContract }); + assert.equal(restoredHub.vault().status(reverted).status, 'source_changed'); + assert.equal(reopened.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value, cipher); +}); + +test('catalog uses custom model path/version/headers and inherits its frozen contract without copying credentials', async t => { + const f = fixture(t, { modernDefaults: true }), server = await compatibleFixture(t, () => ({ data: [{ id: 'owned-catalog-a' }, { id: 'owned-catalog-b' }] })); + const { hub } = ownedHub(f); + const source = hub.upsert({ name: '自有目录', model: 'owned-catalog-a', protocol: 'chat-completions', baseUrl: server.baseUrl, apiKey: 'owned-catalog-contract-key', + requestContract: { modelsPath: '/owned/models?group=one', completionPath: '/owned/chat', headers: { 'OpenAI-Project': 'catalog-project' } } }); + const preview = await hub.modelCatalog().fetch({ id: source.id, revision: source.revision }); + const result = hub.modelCatalog().apply({ previewId: preview.id, models: ['owned-catalog-a', 'owned-catalog-b'], routing: 'keep' }); + assert.equal(server.requests.length, 1); assert.equal(server.requests[0].url, '/owned/models?group=one'); + assert.equal(server.requests[0].headers['openai-project'], 'catalog-project'); + const added = hub.connection(result.added[0]); assert.equal(added.requestContract.modelsPath, '/owned/models?group=one'); + assert.equal(added.credentialSource.connectionId, source.id); assert.equal(hub.provider.credentials.has(added.id), false); + assert.equal(hub.credential(added).key, 'owned-catalog-contract-key'); assert.doesNotMatch(JSON.stringify(preview), /owned-catalog-contract-key/); + const original = structuredClone(added.upstreamModel), snapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: added.id })); + assert.equal(matchingUpstreamModel({ ...added, credentialRevision: 1 }).id, added.model); + const edited = hub.upsert({ ...added, requestContract: { ...added.requestContract, headers: { 'OpenAI-Project': 'other-project' } } }); + assert.equal(matchingUpstreamModel({ ...edited, credentialRevision: 1 }), null); assert.deepEqual(edited.upstreamModel, original); + assert.deepEqual(snapshot.routing.members[0].upstreamModel, original); + assert.equal(matchingUpstreamModel({ ...added, credentialRevision: 2 }), null); +}); + +test('actual Messages SSE and redirect keep their request headers; catalog observations bind the saved source identity', async t => { + const f = fixture(t, { modernDefaults: true }), requests = [], { provider, hub } = ownedHub(f); + const server = http.createServer(async (request, result) => { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + const input = chunks.length ? JSON.parse(Buffer.concat(chunks)) : null; + requests.push({ url: request.url, headers: request.headers, input }); + if (request.url === '/owned/redirect') { result.writeHead(302, { Location: '/owned/target' }); result.end(); return; } + if (request.method === 'GET') { result.writeHead(200, { 'Content-Type': 'application/json' }); result.end('{"data":[]}'); return; } + result.writeHead(200, { 'Content-Type': 'text/event-stream', 'anthropic-version': '2026-10-21', 'x-request-id': 'owned-sse' }); + const event = (name, value) => result.write('event: ' + name + '\ndata: ' + JSON.stringify({ type: name, ...value }) + '\n\n'); + event('message_start', { message: { id: 'owned-sse-message', model: input.model, role: 'assistant', type: 'message', content: [], usage: { input_tokens: 7, output_tokens: 0 } } }); + event('content_block_start', { index: 0, content_block: { type: 'text', text: '' } }); + event('content_block_delta', { index: 0, delta: { type: 'text_delta', text: '完成' } }); + event('content_block_stop', { index: 0 }); + event('message_delta', { delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 2 } }); + event('message_stop', {}); result.end(); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); })); + const baseUrl = 'http://127.0.0.1:' + server.address().port + '/v1'; + const source = hub.upsert({ name: '自有流式', baseUrl, protocol: 'anthropic-messages', model: 'claude-opus-5-5', streaming: true, apiKey: 'owned-sse-key', + requestContract: { completionPath: '/owned/sse', modelsPath: '/owned/models', anthropicVersion: '2026-10-21', anthropicBetas: ['owned-stream'], headers: { 'anthropic-workspace-id': 'owned-workspace' } } }); + const config = hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: source.id }); + const result = await provider.complete(config, [{ role: 'user', content: '流式请求' }], null, undefined, undefined, null, []); + assert.equal(result.message.content, '完成'); assert.equal(requests[0].input.stream, true); + assert.equal(requests[0].headers['anthropic-beta'], 'owned-stream'); assert.equal(requests[0].headers['anthropic-workspace-id'], 'owned-workspace'); + assert.equal(hub.attempts[0].requestMetadata.headers.find(([name]) => name === 'anthropic-version')[1], '2026-10-21'); + assert.equal(hub.attempts[0].stream.terminal, true); + let catalogMetadata; + await provider.request({ ...f.store.config, ...hub.connection(source.id) }, '/owned/models', undefined, undefined, 'owned-sse-key', value => { catalogMetadata ??= value.requestMetadata; }); + assert.equal(catalogMetadata.identity.connectionId, source.id); assert.equal(catalogMetadata.identity.connectionRevision, source.revision); + assert.equal(catalogMetadata.identity.credentialRevision, 1); + await assert.rejects(provider.request({ ...config, requestContract: { ...config.requestContract, completionPath: '/owned/redirect' } }, '/owned/redirect', { model: source.model }, undefined, 'owned-sse-key'), cause => { + assert.equal(cause.diagnostic.httpStatus, 302); assert.equal(cause.diagnostic.redirectMode, 'manual'); return true; + }); + assert.equal(requests.length, 3); assert.equal(requests.some(value => value.url === '/owned/target'), false); +}); + +test('contract fingerprints detect non-prompt/version/state changes independently of original ordered-prefix v1/v2', () => { + const config = { ...open, model: 'gpt-6.1-sol', protocol: 'responses', baseUrl: 'https://api.openai.com/v1', nativeParameters: { temperature: 0.1, prompt_cache_key: 'owned-key', previous_response_id: 'owned-first' } }; + const first = completionBody(config, [{ role: 'user', content: '原目标' }], []); + const changed = { ...first, temperature: 0.9, previous_response_id: 'owned-second' }; + for (const schemaVersion of [1, 2]) assert.equal(prefixAudit(changed, first, { schemaVersion }).variants[0].reason, 'same_prompt'); + const audit = requestContractAudit(changed, config, first, config).variants[0]; + assert.equal(audit.source, 'frozen-run-contract'); assert.equal(audit.representation, 'frozen-request-contract-redacted-v1'); + assert.equal(audit.reason, 'observed_contract_changed'); assert.deepEqual(audit.changed, ['nonPromptParameters']); assert.equal(audit.upstreamCache, 'unknown'); + const appended = { ...first, input: [...first.input, { role: 'user', content: '继续' }] }; + assert.equal(requestContractAudit(appended, config, first, config).variants[0].reason, 'same_observed_contract'); + const headerConfig = { ...config, requestContract: requestContractSettings({ headers: { 'OpenAI-Project': 'different-project' } }, config) }; + assert.ok(requestContractAudit(first, headerConfig, first, config).variants[0].changed.includes('headers')); + assert.equal(preparedRequestMetadata(config, first).bodySha256, sha(JSON.stringify(first))); + const specification = resolveModelSpecification(config), original = JSON.stringify(specification); + const frozen = { ...config, modelSpecification: specification, modelSpecificationFrozen: true }; + assert.equal(resolveModelSpecification(frozen).connectionBinding.baseUrl, config.baseUrl); + assert.equal(resolveModelSpecification({ ...frozen, baseUrl: 'https://other.invalid/v1' }).connectionBinding.baseUrl, 'https://other.invalid/v1'); + assert.equal(JSON.stringify(specification), original); + const legacy = structuredClone(specification); delete legacy.connectionBinding; + assert.deepEqual(resolveModelSpecification({ ...frozen, baseUrl: 'https://other.invalid/v1', modelSpecification: legacy }), legacy); +}); + +test('runtime freezes and verifies separate contract observations; later edits cannot rewrite old request artifacts or metadata', async t => { + const f = fixture(t, { modernDefaults: true }); let count = 0; + const server = await compatibleFixture(t, () => ++count === 1 ? completion([call('owned-list', 'list_files', { path: '' })]) : completion([], '完成')); + const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }); provider.setKey('owned-runtime-contract-key'); f.onCleanup(() => provider.abortRequests()); + f.store.saveConfig({ ...open, baseUrl: server.baseUrl, model: 'owned-runtime-model' }); + const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll()); + runtime.start(f.session.id, '读取项目一次'); await runtime.active.get(f.session.id).promise; + const plans = [...f.store.core.context_plan.values()]; assert.equal(plans.length, 2); + const original = plans.map(plan => f.store.artifactStore.read(f.store.core.artifact.get(plan.artifactId))); + for (const plan of plans) { assert.equal(plan.requestContractAudit.schemaVersion, 1); assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan)); } + assert.equal(plans[1].requestContractAudit.variants[0].reason, 'same_observed_contract'); + const old = plans[1].requestContractAudit; plans[1].requestContractAudit = { ...old, previousRequestSha256: '0'.repeat(64) }; + assert.throws(() => verifyPlanEvidence(f.store, f.session, plans[1]), /封存|对照/); plans[1].requestContractAudit = old; + for (const [index, plan] of plans.entries()) assert.deepEqual(f.store.artifactStore.read(f.store.core.artifact.get(plan.artifactId)), original[index]); + assert.equal(server.requests.length, 2); +});