docs: audit routing changes after confirmed GPT configuration error
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
# Agent Workbench项目执行规范
|
||||
|
||||
N当前结论优先:用户明确确认apikey密钥属于GPT分组,原请求误填Claude;结束供应商Claude故障推断。34组I前/M前与当前GPT请求字节/预算对照、24组型号对照、144相关回归及2个实际GPT协议重定向场景通过。220份src仍与正式M冻结一致,未回滚或修改产品代码;保留I交付/防空转、K模型选择及M独立Messages能力。见docs/ROUTING-AUDIT-N.md。
|
||||
|
||||
N已将apikey从误填Claude/Messages更正为GPT兼容代理/gpt-6.1-sol/Responses/https://api.apikey.fan/v1,型号策略恢复record,无别名。保存前外部已停用该连接(修订9→10),首驱动在POST前拒绝;保留停用,唯一保存修订10→11,凭据修订仍2。其它连接/默认高性能池/全局配置、项目/62未归档摘要、最近100条展示账本/事件游标保持;原M全导出仅生成时间不同,其余与封存原件相同。首次误比exportedAt的校验失败保留,未重复POST。原PID36552保持,本轮真实模型/远程凭据请求0,未重启或重存Key,也未整库/全工件重审。旧J/E/H/M原件及结果保持,不再把误配置当Claude线路故障。下一明确选择启用的GPT连接做新有界预检、Node交付及独立Purge,不自动启用apikey或重跑旧任务。
|
||||
|
||||
以下M及更早记录按当时尚未确认分组的历史理解,当前诊断与配置以N为准。
|
||||
|
||||
M已本地交付:1.24.4/source d62d03f9/候选20261103112054864,原生Messages、两种显式鉴权、实际URL、工具/PNG历史、JSON/SSE/身份与缓存用量已接入。25专项/144相关及61+48原协议、18升级相关、549源码ZIP输入重建22/22、三归档/便携、源码/便携/安装载荷各七组UI、4类历史UI、12实际安装/16+9安装UI通过。正式保留PID36552/Provider,原55项目71会话及全原行/导出/3570原工件/公开配置精确保持,网页/原生及再次核对通过。745份/54940236字节证据离线通过,见docs/QA-ANTHROPIC-MESSAGES-M.md及docs/anthropic-messages-release-identity.json;首兼容清单、封存取错目录和UI操作拒绝保持,不重建已安装包。
|
||||
|
||||
M真实单次预检已结束:同apikey原凭据修订2,Messages/Bearer实际https://api.apikey.fan/v1/messages请求claude-opus-5-5,但原message_start报告gpt-6.1-sol;1请求/221报告tokens/0未知/0工具/无重试切池,strict暂停。原201尝试、71原导出/3570原工件及所有原行按精确声明归一化保持,新增1自有项目/1会话/8记录/22事件与outbox/1尝试/4工件,当前56项目72会话。目标连接保留更正协议/严格身份,修订8→9;全局配置/默认高性能池保持,9229关闭,无Key提取或重存。Claude线路身份仍未通过,不能添加无依据别名、不重跑J/E/H/M,不把协议验收或返回型号当权重认证/工程/Purge收益。下一先核对供应商路由或新选连接,再独立单次预检,通过后按J计划做新Node工程与单列Purge。
|
||||
@@ -50,7 +56,7 @@ D固定可信来源生产策略已完成:实现9106655/最终验收d05a741,6
|
||||
|
||||
## 范围与目标
|
||||
|
||||
当前接续优先级:M原生Messages已完成本地交付,单次真实身份预检仍不符;先核对供应商Claude路由或用户明确新选连接,再按J计划另开单次预检。通过后才进入新Node工程和原版Purge独立实测,不重跑旧失败或将未交付对照宣称收益。docs/PLAN-1.25.md及新iPhone/其它供应商方案保留。发布前多轮完整目录核验耗时已记录为后续性能审查,不在运行中的安装流程削弱核验或改写载荷。
|
||||
当前接续优先级:N已确认GPT分组误填Claude,并完成相关实现回查和单连接校正;不继续将本次误配置归因于Claude线路故障。下一明确选定启用的GPT连接,按J计划另开单次预检,通过后进入新Node工程和原版Purge独立实测;不重跑旧失败或将未交付对照宣称收益。docs/PLAN-1.25.md及新iPhone/其它供应商方案保留。发布前多轮完整目录核验耗时已记录为后续性能审查,不在运行中的安装流程削弱核验或改写载荷。
|
||||
|
||||
本仓库专注AI编程与能力研究工作台。其他项目不纳入本项目计划或代码。用户确定的研究对象为Codex、Claude Code、Cursor、DeepSeek Harness、WorkBuddy及DSH-purge;目标是将有证据的机制独立开发成自有Harness内置能力。
|
||||
|
||||
@@ -108,7 +114,7 @@ D固定可信来源生产策略已完成:实现9106655/最终验收d05a741,6
|
||||
|
||||
## 当前本地服务与Windows
|
||||
|
||||
- 正式服务入口http://127.0.0.1:4318,当前1.24.3,沿用原PID36552与Provider;当前身份以docs/model-selection-release-identity.json为准。原模型连接、全部表/会话/工件精确保持;普通源码/规划/Git工作不重启服务、不读取或复制Key。正式原生窗口已通过Computer Use实际回看,当前保留1个窗口;旧F的Escape失败作为历史保留。
|
||||
- 正式服务入口http://127.0.0.1:4318,当前1.24.4,沿用原PID36552与Provider;不可变程序身份以docs/anthropic-messages-release-identity.json为准,N后的当前连接配置见docs/ROUTING-AUDIT-N.md。M已核对原全表/会话/工件保留,N只核对其声明的配置范围,不冒充重新整库验收;普通源码/规划/Git工作不重启服务、不读取或复制Key。正式原生窗口按M实际回看记录,旧F的Escape失败作为历史保留。
|
||||
- 浏览器/fixture验证使用独立端口与数据目录;用户项目与研究对象的登录/会话配置不用于测试凭据。
|
||||
- Windows执行环境以实测shell为准。现有工具使用PowerShell 5.1和UTF-8;不用&&/||拼接命令,使用换行和$LASTEXITCODE核对结果。
|
||||
- 桌面与移动共用执行宿主。手机127.0.0.1指手机,远程接入通过未来经验证的配对网关。
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Agent Workbench 更新记录
|
||||
|
||||
N配置与诊断更正(程序版本仍1.24.4):用户确认apikey实际属于GPT分组,原型号误填Claude。回查未发现需要回滚的产品代码;34组GPT请求/预算对照、24组型号对照、144相关回归和2组重定向观察通过。该连接改为gpt-6.1-sol/Responses、恢复默认记录策略并保留停用,其它连接/默认池/历史记录保持。本轮未发真实模型请求;见docs/ROUTING-AUDIT-N.md,原J/M结果保留为当时错误配置下的历史记录。
|
||||
|
||||
## 1.24.4 · 原生 Anthropic Messages(已本地交付)
|
||||
|
||||
- 模型中心增加 Messages 协议和 x-api-key/Bearer 鉴权;预览最终请求地址,支持服务根或 /v1 根地址,保存切换不自动调用模型。
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# apikey Claude接入调查
|
||||
|
||||
后续N更正:用户确认这把Key实际属于GPT分组,原型号误填Claude。L发现的“当时缺少Messages适配”是产品能力边界,不是该GPT连接故障的根因证明。Messages后由M独立交付,当前连接已按GPT/Responses校正并保留停用;见[复查](ROUTING-AUDIT-N.md)。以下为分组尚未确认时的历史调查,原证据保持。
|
||||
|
||||
本次确定了工作台的协议接入缺口:1.24.3尚未实现Anthropic Messages,现有apikey连接使用Chat Completions,其地址拼接也与供应商公开示例不同。原预检的GPT标识确实出现在上游原SSE;没有发现工作台将所选Claude请求替换成legacy GPT或把返回型号按默认模型填充的证据。供应商内部为何返回这个标识、这把Key的分组与映射,仍未得到验证。
|
||||
|
||||
本报告记录2026-11-03的调查,源码与已安装版本来源均为`f53eebb7171f169ac3620b93bdbd9b8bc6ba3401`。这是诊断结果,不是新协议已经上线的发行说明。
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# J:apikey Claude 真实连接预检
|
||||
|
||||
后续N更正:用户已确认apikey实际属于GPT分组,原型号误填Claude。下文保留当时的请求、GPT响应和暂停事实,不再把它归因于供应商Claude线路故障;该连接已改为GPT/Responses并保留停用,见[实现与配置复查](ROUTING-AUDIT-N.md)。原用量与证据不变。
|
||||
|
||||
**已发出一次真实请求,型号核对未通过。** 固定使用用户选择的 `apikey` 连接,发送 `claude-opus-5-5`,上游完整 SSE 中的型号字段均为 `gpt-6.1-sol`。系统以 `model_identity` 暂停,未执行任何工具,未切换号池或重试。不能将该请求作为 Claude 工程能力的验收依据,也不能仅凭返回字段认证底层模型权重或判断代理原因。
|
||||
|
||||
| 项目 | 原始证据结果 |
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# J:I交付后的新真实样本计划(单次身份预检未通过)
|
||||
# 新真实样本计划(N已纠正GPT分组配置,待新预检)
|
||||
|
||||
M接续状态:1.24.4已本地交付原生Messages,原apikey更正为Messages/Bearer后实际/v1/messages单次预检仍报告gpt-6.1-sol,请求为claude-opus-5-5;1请求/221报告tokens/0工具,strict暂停。见[原生协议验收与新结果](QA-ANTHROPIC-MESSAGES-M.md)。先核对供应商路由或新选连接,再新开下列步骤1;不能自动重试M/J或以别名强行通过。下列工程与Purge仍待真实身份预检通过。
|
||||
当前N结论:用户确认apikey属于GPT分组,原型号误填Claude;该连接现为gpt-6.1-sol/Responses,保留外部设置的停用状态。相关实现回查和GPT请求兼容对照通过,见[复查报告](ROUTING-AUDIT-N.md)。下一明确选择启用的GPT连接,新建下面的实验;不以默认池代替固定连接,不再等待所谓Claude线路修复。
|
||||
|
||||
用户选择 apikey Claude 后已执行一次独立真实预检:请求 claude-opus-5-5,上游完整 SSE 标记 gpt-6.1-sol;1 请求/4334 报告 tokens/0 工具,严格暂停。原参数/号池与凭据保持,原状态核对完成;见[实测结果](LIVE-MODEL-IDENTITY-J-RESULTS.md)。下列工程与 Purge 尚未执行,需更正或新选连接后另开预检;不自动重试本样本。
|
||||
历史J/M分别请求Claude而上游报告GPT,J为1请求/4334报告tokens,M为1请求/221报告tokens,均严格暂停、0工具。错误配置这一补充不改写[原J结果](LIVE-MODEL-IDENTITY-J-RESULTS.md)或[M原件](QA-ANTHROPIC-MESSAGES-M.md),也不把工程/Purge未执行变成通过。
|
||||
|
||||
1. 新开独立身份预检:冻结已配置连接和版本,严格核对请求/返回身份及来源;一请求、最多256输出、累计16000tokens、无重试或切池。输入估算超过原限即零发送拒绝。身份缺失、不一致、混合或中断立即停止,映射须有实际依据。凭据仅由原Provider使用。
|
||||
2. 预检通过后先做一个新Node工程交付样本:封存原功能测试/源码/Git和受保护文件,固定32K上下文、最多8请求和90000tokens;读失败、实现、整批审查、显式续接、新检查审批、原测试/构建和Git均须原证据。监督只做审查/审批/确认,不能代替模型实现;预算到期保存失败,不追加提示续跑。实际请求仍逐次严格核对身份。
|
||||
1. 新开独立身份预检:冻结启用的GPT连接、正确型号/协议和版本,仅该实验快照使用严格核对,不更改所有连接的默认record策略;一请求、最多256输出、累计16000tokens、无工具/重试/切池。输入估算超过原限即零发送拒绝。身份缺失、不一致、混合或中断立即停止,映射须有实际依据。凭据仅由原Provider使用。
|
||||
2. 预检通过后先做一个新Node工程交付样本:封存原功能测试/源码/Git和受保护文件,最多8请求和90000tokens。原32K上下文方案须先核对连接上限是否匹配,不能暗改当前16K连接限制来让实验通过;不匹配先明确调整并冻结计划。读失败、实现、整批审查、显式续接、新检查审批、原测试/构建和Git均须原证据。监督只做审查/审批/确认,不能代替模型实现;预算到期保存失败,不追加提示续跑。实际请求仍逐次严格核对身份。
|
||||
3. Node闭环通过后再分别测试React与Python的新样本。先定位模型输入、推进与执行问题,再考虑扩大题型;不以本机夹具代替模型推理成绩。
|
||||
4. 原版Purge收益另做同源/同题/同预算AB/BA。完成相同原测试/构建/Git才可比较成功交付的tokens、时延和监督次数;失败早停不算节省,少量样本仅作探索。保持默认关闭,保留加载来源、apply与每次实际输入。
|
||||
5. 每一步先小结、核对原状态和本地Git,再进入下一步。1.25及更大能力扩展继续保留计划,先得到真实闭环证据。
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# 1.24.4:原生 Messages 已本地交付,Claude 线路身份仍不一致
|
||||
# 1.24.4:原生 Messages 交付与历史型号预检
|
||||
|
||||
后续N更正:用户明确确认原apikey属于GPT分组,型号误填Claude。因此下文预检反映当时的错误配置,不能继续据此判定供应商Claude线路故障。当前该连接已按GPT/Responses校正并保留停用,相关实现回查通过;见[完整复查](ROUTING-AUDIT-N.md)。下文M原件、221报告tokens和暂停结果仍保持,不倒写为Claude成功,也不重做不可变发行。
|
||||
|
||||
工作台已在 `http://127.0.0.1:4318` 升级为 1.24.4。正式宿主仍为 PID36552,原 Provider 与凭据保持;原55项目、71会话、所有原表行、完整导出、3570份原工件文件及模型中心在升级和窗口回看后精确一致。
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# N:GPT分组误填Claude后的链路与改动复查
|
||||
|
||||
用户已明确确认:这条apikey密钥实际属于GPT分组,模型名称误填成了Claude。此前“请求Claude、返回GPT”不能继续当作供应商Claude线路故障,也没有证据表明工作台偷偷切换成GPT。原J/M的请求、响应和严格暂停都是当时配置下的真实记录,保持原样。
|
||||
|
||||
本次检查没有发现需要回滚的产品源码。保留I的交付推进/防空转修复、K的统一模型入口,以及M的独立Messages能力;纠正这条连接的配置和当前诊断结论。正式程序仍为1.24.4、原PID36552,未重新打包、安装或重启。
|
||||
|
||||
## 回查结果
|
||||
|
||||
| 范围 | 核对与处理 |
|
||||
| --- | --- |
|
||||
| 请求型号与号池 | 原J/M明确选中apikey、poolId=null,实际请求字段是Claude,GPT标识来自原响应。当前默认「高性能」池是两个连接的轮询池;默认池和某次Run的封存路由分别判断,不能只看左下角标签。 |
|
||||
| I:型号记录与暂停 | 默认是record,只记录原型号;仅显式require-match才暂停。没有全局强制严格策略,也没有根据品牌硬改请求型号。保留这项可选核对,不加Claude→GPT别名掩盖误配置。 |
|
||||
| I:应用后推进与防空转 | 依据当前文件SHA、实际检查、审批和审查结果推进,与模型品牌无关。E/H的交付失败及实际用量仍有效,不因用户补充分组信息变成通过。保留这些独立修复。 |
|
||||
| K:统一模型选择 | 左下角/顶部统一模型中心、预算不覆盖路由、旧Run不随默认选择改写,均有独立作用,保留。 |
|
||||
| M:新增Messages | 只是增加一种协议;Chat/Responses继续各走自己的请求和解析。此次GPT分组无需靠Messages解决,新增能力不能再作为该连接的必需修复来表述。产品保留这项协议能力,连接改回GPT的原生Responses使用方式。 |
|
||||
| 凭据兼容 | M只在Messages绑定中追加鉴权字段,Chat/Responses原绑定字段保持;没有提取或重存真实Key。目标连接原磁盘块在M前已是source_changed,本次没有把内存可用冒充可重启恢复。 |
|
||||
| 发行修复 | K的Windows长路径归档、M的1.24.4升级兼容清单属于实际出现过的独立问题,和这次型号误填无关,不回滚已验证的修复。 |
|
||||
|
||||
保留请求/响应原件、上游错误和用量,不代表所有模型能力都已接入,更不认证底层权重。未来以正确配置的真实任务结果判断工程交付和Purge收益。
|
||||
|
||||
## 实际验证
|
||||
|
||||
对照I前`410b3478`、M前`b832982d`与当前的实际请求模块,每个基线17例,共34例:Chat/Responses文本、流、工具历史、原生参数、视觉、品牌标签、Responses已有推理历史与混合协议池的请求字节及预算指标完全一致。另24例Chat/Responses型号观察结果与M前一致,默认策略仍为record。
|
||||
|
||||
本轮13个相关测试文件实际144/144通过,覆盖模型中心/选择、旧协议/流/原生参数、型号、Messages、凭据、升级、交付推进、读取预算与防空转。它们使用自有夹具,不使用正式Key,不能视为新的供应商或工程推理验收。
|
||||
|
||||
确有一项跨协议行为变化需要明示:M让模型请求不再自动跟随HTTP重定向。新做的Chat/Responses两个实际localhost 307场景均为原端1次、跳转目标0次;没有重复POST或向跳转目标发送凭据。保留该规则,依赖301/307的供应商需要填写正确终点地址,不能声称所有运输行为都与旧版相同。
|
||||
|
||||
当前220份src文件还与已部署M的冻结SHA逐项一致。本轮没有修改产品代码,也没有用回滚整个版本的方式消除错误提示。界面未重做,本轮未新增网页/原生/iPhone目视验收;M原有验收按当时范围保留。
|
||||
|
||||
## 连接配置校正与并发保护
|
||||
|
||||
保存前发现连接由外部操作从修订9变成10,唯一配置变化是enabled变为false。首个驱动在POST前停止,未覆盖该状态。随后以修订10为新基线,执行一次本地连接保存,得到修订11:
|
||||
|
||||
| 字段 | 校正前 | 当前 |
|
||||
| --- | --- | --- |
|
||||
| 名称/ID | apikey / 09b0293b-faad-45c3-832d-7c8b615813aa | 保持 |
|
||||
| 品牌标注 | Claude兼容代理 | GPT兼容代理 |
|
||||
| 请求型号 | claude-opus-5-5 | gpt-6.1-sol |
|
||||
| 协议/实际地址 | Messages / https://api.apikey.fan/v1/messages | Responses / https://api.apikey.fan/v1/responses |
|
||||
| 输出上限字段 | max_tokens | max_output_tokens |
|
||||
| 型号策略 | 调查期间require-match | 默认record,别名仍为空 |
|
||||
| 启用状态 | 已停用 | 仍停用 |
|
||||
| 凭据修订/存在位 | 2 / true | 2 / true |
|
||||
|
||||
原上下文/输出/并发上限、能力声明、空原生参数、其它连接、默认池、默认选择、全局配置、项目列表、62个未归档会话摘要、API返回的最近100条请求账本及事件游标逐项保持。最近100条是接口的展示范围,不冒充全部202条数据库记录的重新审计。本次没有再次整库/全工件逐项重验。
|
||||
|
||||
原M完整项目/会话/执行内容与M封存导出一致。首次收尾误把每次生成的`exportedAt`当成存储内容做哈希,出现校验失败;没有重复保存配置。只改变该生成时间字段,即能精确匹配保存前的原哈希;其余所有字段与M封存原件完整相等。首驱动和失败原因保留,后续只读核对通过。
|
||||
|
||||
本轮真实模型请求0、远程凭据请求0、连接保存1次;未重跑J/E/H/M或原用户任务。原M仍是暂停的历史预检,当前连接状态不改写它的请求或结果。
|
||||
|
||||
## 换思路排查得到的机制证据
|
||||
|
||||
供应商公开前端带有Sub2API名称及其公开源码链接。固定公开提交`4a4a83ee5ec86b19d3a2dd9b6471de5128963bec`中,网关先读取Key分组平台,再选择Messages处理器;OpenAI处理器可把Messages转换成Responses,支持分组Opus/Sonnet/Haiku映射、渠道和账号映射。渠道可在转发器之前改写body.model;因此Messages格式、响应ID前缀或返回型号都不等于Claude权重认证。
|
||||
|
||||
这些源码证明这种机制存在,不证明供应商当前生产版本或本次私有映射规则。部分公开代码会保留转发器入口的model,不能仅凭外观拼出唯一的后端调用链。公开模型广场返回“Model plaza is not enabled”,不代表推理接口失效。本次没有登录后台、查询私人Key分组、运行公开教程命令或联系供应商;用户的直接确认已补齐GPT分组这一事实,不再反复试探线路。
|
||||
|
||||
完整公开仓库树和多余研究输入保留在本地`.qa/route-n/public`;仓库仅保存本次必要来源、收据和复查结果,未将第三方实现接入运行时。
|
||||
|
||||
## 后续顺序
|
||||
|
||||
1. 结束“修Claude线路”的方向。apikey保持当前停用状态;真实实验明确选择一个启用的GPT连接,不让默认池的轮询掩盖实验归属。
|
||||
2. 新建单次身份预检,冻结正确的GPT请求配置、原响应和预算。仅该新实验快照用严格核对,不改所有连接的默认策略,也不续跑旧预检。
|
||||
3. 预检通过后按[真实任务计划](LIVE-RETEST-J-PLAN.md)先做新Node工程,再做React/Python;原版Purge按同一连接、同题同预算AB/BA单独测。原失败和收益未证实的结论保持。
|
||||
4. 后续诊断先核对用户意图、Key分组/平台、实际请求与原响应,再决定是否需要新增适配。配置中的品牌、协议和型号属于声明,不能作为供应商故障的唯一依据。
|
||||
|
||||
证据目录:[routing-audit-n-evidence](routing-audit-n-evidence/README.md)。52份材料、650216字节已封存并离线核对通过,manifest SHA-256为`d6f1dd8602d194758fc2423ba347cd7416441aef6a55c3411ff6a5285e1de731`;另保存清单与[核对结果](routing-audit-n-verification.json)。验证器不会访问模型、重跑测试或再次保存配置,历史写入驱动以文本原件保存供审查。原M manifest仍为`c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7`。
|
||||
@@ -1,5 +1,7 @@
|
||||
# Agent Workbench 验收记录
|
||||
|
||||
N补充:用户确认GPT分组误填Claude。34组实际旧/新模块GPT请求字节与预算对照、24组型号对照、13文件144/144相关回归及Chat/Responses两个实际localhost重定向场景通过;220份src仍与M冻结相同。apikey按GPT/Responses校正,保留并发期间外部设置的停用状态,凭据修订2及其它连接/池/原M导出内容等声明范围保持。程序仍1.24.4,本轮真实模型请求0,不宣称重新整库/全工件或真实工程/Purge通过;52份/650216字节N证据及原M绑定离线核对通过,见[复查报告](ROUTING-AUDIT-N.md)。M的协议交付仍有效,但旧型号差异不能继续当作Claude供应商故障。
|
||||
|
||||
1.24.4已本地交付原生Anthropic Messages与实际URL诊断。最终d62d03f9/候选20261103112054864,25专项/144相关、源码ZIP549输入独立重建22/22、三归档/便携、三载荷各七组UI、12实际安装及正式网页/原生回看通过,原PID36552/Provider与55项目71会话所有原数据精确保持。随后唯一真实Messages预检仍返回GPT标识,1请求/221报告tokens/0工具,严格暂停;当前56项目72会话追加均归属该预检,原数据和默认池保持。745份证据离线核对通过不表示Claude线路身份通过,见[完整报告](QA-ANTHROPIC-MESSAGES-M.md)及[发行身份](anthropic-messages-release-identity.json)。真实工程/Purge与1.25扩展保持待验/计划,下方按历史版本理解。
|
||||
|
||||
1.22.0已完成所属Vite预览、独立桌面浏览区、有界DOM/原截图与审批动作、独立登录资料/撤销/下载、手机原观察SHA核对的本地交付。独立源码683/683(C完整原轮通过,D严格绑定后沿用)、33类250组原B串行界面(产品输入相同,严格绑定后沿用)、源码/便携/实际安装各17组浏览流程、同载荷安装7组、正式30页及Edge/Electron两视口通过。原PID36552/Provider保持,17项目/32全部会话/3239记录/6229事件及1780工件文件原字节保持,9229关闭。本轮验收发起真实模型请求0。
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
* -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
|
||||
*.tap binary
|
||||
@@ -0,0 +1,24 @@
|
||||
# N:误配置确认后的复查证据
|
||||
|
||||
对应报告:[ROUTING-AUDIT-N.md](../ROUTING-AUDIT-N.md)。用户确认 apikey 属于 GPT 分组,原型号误填 Claude;本轮更正诊断和一条连接配置,保留已有有效修复与全部历史原件。产品版本仍为 1.24.4。
|
||||
|
||||
- `user-confirmation.json`:当前用户直接确认的原文。没有编造消息 ID 或接收时间。
|
||||
- `results/`:34 组旧/新请求、24 组型号观察、144 项相关回归原日志与范围、220 份源码 SHA 核对、两个 localhost 重定向场景。
|
||||
- `configuration/`:仅含公开元数据及指纹的配置前后记录、并发拒绝记录、M 原会话的只读导出核对。不含 Key、DPAPI 保存块或本地授权令牌。
|
||||
- `drivers/`:本轮历史脚本原字节,以 `.mjs.txt` 保存。**仅用于审查,不要执行或重放**;尤其配置纠正脚本已经完成一次 POST,不是恢复脚本。
|
||||
- `baseline/`:来自本地 Git 的必要旧模块,供核对对照来源。没有修改历史提交。
|
||||
- `public/`:匿名公开 GET 的原收据、必要源码及固定提交摘要。源码仅证明相应机制存在,不证明供应商生产版本、私有映射或模型权重;未接入产品运行时。完整树与其余研究输入留在本地 `.qa/route-n/public`。
|
||||
|
||||
本轮真实模型请求为 0。apikey 修订 10→11 后仍停用,凭据修订 2 不变;其它连接和默认池保持。核对 62 个未归档摘要及 API 返回的最近 100 条请求,不冒充全库/全部工件重审。原保存块 `source_changed` 已存在,本轮未处理其恢复能力。
|
||||
|
||||
首驱动因外部已停用连接、修订不符,在 POST 前停止;第二驱动只保存一次。随后把动态 `exportedAt` 误纳入存储内容哈希的校验失败保留,后续只读核对确认仅该生成字段不同。没有重复保存,原 M 请求、响应和暂停不变。
|
||||
|
||||
`manifest.json` 记录本目录每份材料的原字节 SHA-256,并绑定原 M manifest 和源码冻结清单。局部 `.gitattributes` 禁止转换原始字节,包括 PowerShell 产生的回归日志编码。公开 GET 首次五个下载失败在来源收据中保留,后由 blob API 成功获取,不涉及模型调用。
|
||||
|
||||
只运行以下离线验证器即可核对清单、结果范围、配置变化和旧 M 绑定;它仅使用文件读取与哈希,不访问服务、不调用模型、不执行历史驱动、不写配置,也不重跑回归测试:
|
||||
|
||||
```powershell
|
||||
& 'D:\Ai-project\REA逆向\tools\node-v24.22.1-win-x64\node.exe' 'D:\Ai-project\REA逆向\Agent-Workbench\docs\routing-audit-n-evidence\verify-offline.mjs'
|
||||
```
|
||||
|
||||
本轮离线核对结果见 [routing-audit-n-verification.json](../routing-audit-n-verification.json)。真实新工程交付与原版 Purge 收益仍按[后续计划](../LIVE-RETEST-J-PLAN.md)独立实测。
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
export const MODEL_PROTOCOLS = ['chat-completions', 'responses'];
|
||||
export const MODEL_CAPABILITIES = ['text', 'tools', 'streaming', 'vision', 'audio'];
|
||||
const failure = message => Object.assign(new Error(message), { status: 400 });
|
||||
|
||||
export function modelProtocol(value = 'chat-completions') {
|
||||
if (!MODEL_PROTOCOLS.includes(value)) throw failure('请选择已接入的 Chat Completions 或 Responses 协议。');
|
||||
return value;
|
||||
}
|
||||
|
||||
export function capabilityDeclarations(input, previous = null) {
|
||||
const result = { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown', ...previous };
|
||||
if (input === undefined) return result;
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw failure('模型能力声明格式无效。');
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (!MODEL_CAPABILITIES.includes(key) || !['supported', 'unsupported', 'unknown'].includes(value)) throw failure('能力只能声明支持、不支持或未知,不能自行标为已验证。');
|
||||
result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function capabilityView(connection, credentialRevision = 0) {
|
||||
const declarations = capabilityDeclarations(undefined, connection.capabilityDeclarations);
|
||||
const evidence = connection.capabilityEvidence;
|
||||
const current = evidence?.connectionRevision === connection.revision && evidence?.credentialRevision === credentialRevision;
|
||||
return Object.fromEntries(MODEL_CAPABILITIES.map(key => [key,
|
||||
declarations[key] === 'unsupported' ? 'unsupported' : current && evidence.results?.[key] === 'verified' ? 'verified'
|
||||
: declarations[key] === 'supported' ? 'protocol_declared' : 'unknown']));
|
||||
}
|
||||
|
||||
export function capabilityRejections(connection, requirements, credentialRevision = 0) {
|
||||
const view = capabilityView(connection, credentialRevision);
|
||||
return requirements.filter(key => !['verified', 'protocol_declared'].includes(view[key])).map(capability => ({
|
||||
connectionId: connection.id, connectionName: connection.name, capability, state: view[capability] ?? 'unknown',
|
||||
reason: view[capability] === 'unsupported' ? '连接明确声明不支持所需能力' : '连接尚未声明或验证所需能力',
|
||||
}));
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { modelProtocol } from './model-capabilities.mjs';
|
||||
import { nativeParameterSettings } from './native-parameters.mjs';
|
||||
|
||||
function wireBody(config, messages, tools) {
|
||||
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
|
||||
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField);
|
||||
if(config.inputImages?.length) messages=[...messages,{role:'user',content:protocol==='responses'
|
||||
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
|
||||
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
|
||||
const cleanMessages = messages.map(({ providerState, ...message }) => message);
|
||||
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', [native.outputTokenField]: config.maxOutputTokens, stream, ...native.nativeParameters,
|
||||
...(stream ? { stream_options: { include_usage: true } } : {}) };
|
||||
const input = messages.flatMap(message => {
|
||||
if (message.role === 'tool') return [{ type: 'function_call_output', call_id: message.tool_call_id, output: message.content }];
|
||||
if (message.role === 'assistant') {
|
||||
if (message.providerState?.protocol === 'responses' && message.providerState.endpoint === config.baseUrl && message.providerState.model === config.model) return message.providerState.items;
|
||||
return [...(message.content ? [{ role: 'assistant', content: message.content }] : []), ...(message.tool_calls ?? []).map(call => ({
|
||||
type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments }))];
|
||||
}
|
||||
return [{ role: message.role, content: message.content }];
|
||||
});
|
||||
return { model: config.model, input, tools: (tools ?? []).map(tool => ({ type: 'function', ...tool.function, strict: false })),
|
||||
tool_choice: 'auto', max_output_tokens: config.maxOutputTokens, stream, store: false, include: ['reasoning.encrypted_content'], ...native.nativeParameters };
|
||||
}
|
||||
|
||||
export function completionBody(config, messages, tools) {
|
||||
const members = config.modelRouting?.members;
|
||||
if (members?.some(member => member.protocol === 'responses' || member.streaming === true || member.nativeParameters || member.outputTokenField)) {
|
||||
return { schema: 1, kind: 'model-route-plan', messages, variants: members.map(member => ({ connectionId: member.id,
|
||||
protocol: modelProtocol(member.protocol), body: wireBody({ ...config, ...member, nativeParameters: member.nativeParameters ?? {}, outputTokenField: member.outputTokenField,
|
||||
maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
|
||||
}
|
||||
return wireBody(config, messages, tools);
|
||||
}
|
||||
|
||||
export function requestVariants(body) {
|
||||
return body.kind === 'model-route-plan' ? body.variants.map(value => value.body) : [body];
|
||||
}
|
||||
|
||||
export function actualRequest(body, member) {
|
||||
if (body.kind !== 'model-route-plan') return { ...body, model: member.model };
|
||||
const variant = body.variants.find(value => value.connectionId === member.id);
|
||||
if (!variant || variant.protocol !== modelProtocol(member.protocol) || variant.body.model !== member.model) throw new Error('实际连接与已封存协议请求不一致。');
|
||||
return structuredClone(variant.body);
|
||||
}
|
||||
|
||||
export const outputReservation = body => body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens;
|
||||
|
||||
export function requestHistory(body) {
|
||||
if (body.messages) return body.messages;
|
||||
const messages = [];
|
||||
for (const item of body.input ?? []) {
|
||||
if (item.type === 'reasoning') continue;
|
||||
if (item.type === 'function_call_output') messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output });
|
||||
else if (item.type === 'function_call') {
|
||||
if (!messages.at(-1)?.tool_calls) messages.push({ role: 'assistant', content: '', tool_calls: [] });
|
||||
messages.at(-1).tool_calls.push({ id: item.call_id, type: 'function', function: { name: item.name, arguments: item.arguments } });
|
||||
} else messages.push({ role: item.role, content: typeof item.content === 'string' ? item.content : JSON.stringify(item.content) });
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
export function requestMetrics(body) {
|
||||
const serialized = JSON.stringify(body);
|
||||
const bytes = Buffer.byteLength(serialized, 'utf8');
|
||||
const variants = requestVariants(body);
|
||||
const images=requestImages(body);
|
||||
const imageReserve=imageTokenReserve(body);
|
||||
const estimates=variants.map(value=>Math.ceil(Buffer.byteLength(JSON.stringify(value, (key,item)=>typeof item==='string'&&item.startsWith('data:image/')?'[bounded image bytes]':item),'utf8')/3)
|
||||
+ (value.messages?.length ?? value.input?.length ?? 0)*8+(value.tools?.length??0)*16+imageTokenReserve(value));
|
||||
if(images.length)return {bytes,sha256:createHash('sha256').update(serialized,'utf8').digest('hex'),estimatedInputTokens:Math.max(...estimates),
|
||||
imageReservationTokens:imageReserve,imageCount:Math.max(...variants.map(value=>requestImages(value).length)),estimateMethod:'text-utf8-plus-image-reservation-v1',imageEstimate:'local-reservation-not-provider-billing'};
|
||||
return { bytes, sha256: createHash('sha256').update(serialized, 'utf8').digest('hex'),
|
||||
estimatedInputTokens: Math.max(...variants.map(value => Math.ceil(Buffer.byteLength(JSON.stringify(value), 'utf8') / 3)
|
||||
+ (value.messages?.length ?? value.input?.length ?? 0) * 8 + (value.tools?.length ?? 0) * 16)),
|
||||
estimateMethod: body.kind === 'model-route-plan' ? 'maximum-wire-variant-utf8-v1' : 'utf8-third-plus-framing-v1' };
|
||||
}
|
||||
|
||||
export function requestImages(body) {
|
||||
return requestVariants(body).flatMap(value=>(value.messages??value.input??[]).flatMap(message=>Array.isArray(message.content)?message.content.filter(part=>['image_url','input_image'].includes(part.type)).map(part=>part.type==='image_url'?part.image_url?.url:part.image_url):[]));
|
||||
}
|
||||
export function imageTokenReserve(body){
|
||||
return Math.max(0,...requestVariants(body).map(value=>requestImages(value).reduce((total,url)=>{
|
||||
if(typeof url!=='string'||!url.startsWith('data:image/png;base64,'))throw new Error('视觉请求只允许已校验的PNG发送副本。');
|
||||
const bytes=Buffer.from(url.slice(22,70),'base64');
|
||||
if(bytes.length<24||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||bytes.readUInt32BE(8)!==13||bytes.toString('ascii',12,16)!=='IHDR')throw new Error('视觉请求图像头不完整或类型不符。');
|
||||
const width=bytes.readUInt32BE(16),height=bytes.readUInt32BE(20);
|
||||
if(!width||!height||Math.max(width,height)>1024)throw new Error('视觉请求超过已校验副本范围。');
|
||||
return total+Math.max(4096,Math.ceil(width/32)*Math.ceil(height/32)*4);
|
||||
},0)));
|
||||
}
|
||||
|
||||
export function assertPlannedRequest(body, plan) {
|
||||
if (!plan) return;
|
||||
const metrics = requestMetrics(body);
|
||||
if (metrics.sha256 !== plan.requestSha256 || metrics.bytes !== plan.requestBytes) throw new Error('模型请求正文与已保存计划不一致,未发送请求。');
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
const fail = message => { throw Object.assign(new Error(message), { status: 400 }); };
|
||||
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
||||
const efforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
|
||||
const verbosity = ['low', 'medium', 'high'];
|
||||
|
||||
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField) {
|
||||
if (!object(parameters) || JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
|
||||
const allowed = protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
|
||||
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed'];
|
||||
for (const [key, value] of Object.entries(parameters)) {
|
||||
if (!allowed.includes(key)) fail('所选协议尚未接入原生参数:' + key + '。参数未保存或发送。');
|
||||
if (key === 'temperature' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 2)) fail('temperature应为0–2之间的数字。');
|
||||
if (key === 'top_p' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) fail('top_p应为0–1之间的数字。');
|
||||
if (key === 'seed' && !Number.isSafeInteger(value)) fail('seed应为安全整数。');
|
||||
if (key === 'parallel_tool_calls' && typeof value !== 'boolean') fail('parallel_tool_calls应为布尔值。');
|
||||
if (key === 'reasoning_effort' && !efforts.includes(value)) fail('reasoning_effort应为none/minimal/low/medium/high/xhigh。');
|
||||
if (key === 'verbosity' && !verbosity.includes(value)) fail('verbosity应为low/medium/high。');
|
||||
if (key === 'reasoning' && (!object(value) || Object.keys(value).length !== 1 || !efforts.includes(value.effort))) fail('Responses reasoning当前接入格式为{"effort":"low|medium|high等"}。');
|
||||
if (key === 'text' && (!object(value) || Object.keys(value).length !== 1 || !verbosity.includes(value.verbosity))) fail('Responses text当前接入格式为{"verbosity":"low|medium|high"}。');
|
||||
}
|
||||
const field = outputTokenField ?? (protocol === 'responses' ? 'max_output_tokens' : 'max_tokens');
|
||||
if (!(protocol === 'responses' ? ['max_output_tokens'] : ['max_tokens', 'max_completion_tokens']).includes(field)) fail('输出上限字段与所选协议不兼容。');
|
||||
return { nativeParameters: structuredClone(parameters), outputTokenField: field };
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
export const MODEL_PROTOCOLS = ['chat-completions', 'responses'];
|
||||
export const MODEL_CAPABILITIES = ['text', 'tools', 'streaming', 'vision', 'audio'];
|
||||
const failure = message => Object.assign(new Error(message), { status: 400 });
|
||||
|
||||
export function modelProtocol(value = 'chat-completions') {
|
||||
if (!MODEL_PROTOCOLS.includes(value)) throw failure('请选择已接入的 Chat Completions 或 Responses 协议。');
|
||||
return value;
|
||||
}
|
||||
|
||||
export function capabilityDeclarations(input, previous = null) {
|
||||
const result = { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown', ...previous };
|
||||
if (input === undefined) return result;
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw failure('模型能力声明格式无效。');
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (!MODEL_CAPABILITIES.includes(key) || !['supported', 'unsupported', 'unknown'].includes(value)) throw failure('能力只能声明支持、不支持或未知,不能自行标为已验证。');
|
||||
result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function capabilityView(connection, credentialRevision = 0) {
|
||||
const declarations = capabilityDeclarations(undefined, connection.capabilityDeclarations);
|
||||
const evidence = connection.capabilityEvidence;
|
||||
const current = evidence?.connectionRevision === connection.revision && evidence?.credentialRevision === credentialRevision;
|
||||
return Object.fromEntries(MODEL_CAPABILITIES.map(key => [key,
|
||||
declarations[key] === 'unsupported' ? 'unsupported' : current && evidence.results?.[key] === 'verified' ? 'verified'
|
||||
: declarations[key] === 'supported' ? 'protocol_declared' : 'unknown']));
|
||||
}
|
||||
|
||||
export function capabilityRejections(connection, requirements, credentialRevision = 0) {
|
||||
const view = capabilityView(connection, credentialRevision);
|
||||
return requirements.filter(key => !['verified', 'protocol_declared'].includes(view[key])).map(capability => ({
|
||||
connectionId: connection.id, connectionName: connection.name, capability, state: view[capability] ?? 'unknown',
|
||||
reason: view[capability] === 'unsupported' ? '连接明确声明不支持所需能力' : '连接尚未声明或验证所需能力',
|
||||
}));
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
const validModel = value => typeof value === 'string' && value.length > 0 && value.length <= 200
|
||||
&& value === value.trim() && !/[\x00-\x1f\x7f]/.test(value);
|
||||
|
||||
export function modelIdentitySettings(input = {}, previous = {}) {
|
||||
const fields = ['modelIdentityPolicy', 'modelIdentityAliases', 'modelIdentityAliasSource'];
|
||||
if (!fields.some(key => Object.hasOwn(input, key) || Object.hasOwn(previous, key))) return {};
|
||||
const modelIdentityPolicy = input.modelIdentityPolicy ?? previous.modelIdentityPolicy ?? 'record';
|
||||
if (!['record', 'require-match'].includes(modelIdentityPolicy)) throw new Error('请选择记录型号或型号不一致时暂停。');
|
||||
const modelIdentityAliases = input.modelIdentityAliases ?? previous.modelIdentityAliases ?? [];
|
||||
const modelIdentityAliasSource = input.modelIdentityAliasSource ?? previous.modelIdentityAliasSource ?? '';
|
||||
if (!Array.isArray(modelIdentityAliases) || modelIdentityAliases.length > 8 || !modelIdentityAliases.every(validModel)
|
||||
|| new Set(modelIdentityAliases).size !== modelIdentityAliases.length) throw new Error('返回型号映射最多8项,需使用不重复的完整型号。');
|
||||
if (typeof modelIdentityAliasSource !== 'string' || modelIdentityAliasSource.length > 1000 || /[\x00-\x1f\x7f]/.test(modelIdentityAliasSource)
|
||||
|| modelIdentityAliases.length && !modelIdentityAliasSource.trim()) throw new Error('登记型号映射时需要填写可核对的映射依据。');
|
||||
return { modelIdentityPolicy, modelIdentityAliases: [...modelIdentityAliases], modelIdentityAliasSource: modelIdentityAliasSource.trim() };
|
||||
}
|
||||
|
||||
export function modelIdentityObserver(requestedModel, config = {}) {
|
||||
const settings = modelIdentitySettings(config), models = new Set(); let invalid = false;
|
||||
return {
|
||||
observe(value) {
|
||||
for (const object of [value, value?.response]) {
|
||||
if (!object || !Object.hasOwn(object, 'model')) continue;
|
||||
if (!validModel(object.model) || models.size >= 16 && !models.has(object.model)) { invalid = true; continue; }
|
||||
models.add(object.model);
|
||||
}
|
||||
},
|
||||
snapshot(complete) {
|
||||
const reportedModels = [...models];
|
||||
const status = !complete ? 'incomplete' : invalid ? 'invalid' : !reportedModels.length ? 'missing' : reportedModels.length > 1 ? 'mixed'
|
||||
: reportedModels[0] === requestedModel ? 'matched' : settings.modelIdentityAliases?.includes(reportedModels[0]) ? 'mapped' : 'mismatch';
|
||||
return { schemaVersion: 1, requestedModel, reportedModels, status, complete: complete === true, invalidIdentifiers: invalid,
|
||||
policy: settings.modelIdentityPolicy ?? 'record',
|
||||
...(settings.modelIdentityAliases?.length ? { mapping: { models: settings.modelIdentityAliases, source: settings.modelIdentityAliasSource, kind: 'user-declared' } } : {}),
|
||||
scope: 'Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.' };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function modelIdentityAccepted(identity) { return identity?.complete === true && ['matched', 'mapped'].includes(identity.status); }
|
||||
export function modelIdentityLabel(identity) {
|
||||
return identity ? ({ matched: '请求与返回型号一致', mapped: '符合已登记型号映射', mismatch: '请求与返回型号不一致', mixed: '同次响应包含多个型号',
|
||||
missing: '上游未报告型号', invalid: '上游型号字段无效', incomplete: '响应未完整,型号待核对' }[identity.status] ?? '型号待核对') : '历史记录未核对返回型号';
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { modelProtocol } from './model-capabilities.mjs';
|
||||
import { nativeParameterSettings } from './native-parameters.mjs';
|
||||
|
||||
function wireBody(config, messages, tools) {
|
||||
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
|
||||
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField);
|
||||
if(config.inputImages?.length) messages=[...messages,{role:'user',content:protocol==='responses'
|
||||
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
|
||||
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
|
||||
const cleanMessages = messages.map(({ providerState, ...message }) => message);
|
||||
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', [native.outputTokenField]: config.maxOutputTokens, stream, ...native.nativeParameters,
|
||||
...(stream ? { stream_options: { include_usage: true } } : {}) };
|
||||
const input = messages.flatMap(message => {
|
||||
if (message.role === 'tool') return [{ type: 'function_call_output', call_id: message.tool_call_id, output: message.content }];
|
||||
if (message.role === 'assistant') {
|
||||
if (message.providerState?.protocol === 'responses' && message.providerState.endpoint === config.baseUrl && message.providerState.model === config.model) return message.providerState.items;
|
||||
return [...(message.content ? [{ role: 'assistant', content: message.content }] : []), ...(message.tool_calls ?? []).map(call => ({
|
||||
type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments }))];
|
||||
}
|
||||
return [{ role: message.role, content: message.content }];
|
||||
});
|
||||
return { model: config.model, input, tools: (tools ?? []).map(tool => ({ type: 'function', ...tool.function, strict: false })),
|
||||
tool_choice: 'auto', max_output_tokens: config.maxOutputTokens, stream, store: false, include: ['reasoning.encrypted_content'], ...native.nativeParameters };
|
||||
}
|
||||
|
||||
export function completionBody(config, messages, tools) {
|
||||
const members = config.modelRouting?.members;
|
||||
if (members?.some(member => member.protocol === 'responses' || member.streaming === true || member.nativeParameters || member.outputTokenField)) {
|
||||
return { schema: 1, kind: 'model-route-plan', messages, variants: members.map(member => ({ connectionId: member.id,
|
||||
protocol: modelProtocol(member.protocol), body: wireBody({ ...config, ...member, nativeParameters: member.nativeParameters ?? {}, outputTokenField: member.outputTokenField,
|
||||
maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
|
||||
}
|
||||
return wireBody(config, messages, tools);
|
||||
}
|
||||
|
||||
export function requestVariants(body) {
|
||||
return body.kind === 'model-route-plan' ? body.variants.map(value => value.body) : [body];
|
||||
}
|
||||
|
||||
export function actualRequest(body, member) {
|
||||
if (body.kind !== 'model-route-plan') return { ...body, model: member.model };
|
||||
const variant = body.variants.find(value => value.connectionId === member.id);
|
||||
if (!variant || variant.protocol !== modelProtocol(member.protocol) || variant.body.model !== member.model) throw new Error('实际连接与已封存协议请求不一致。');
|
||||
return structuredClone(variant.body);
|
||||
}
|
||||
|
||||
export const outputReservation = body => body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens;
|
||||
|
||||
export function requestHistory(body) {
|
||||
if (body.messages) return body.messages;
|
||||
const messages = [];
|
||||
for (const item of body.input ?? []) {
|
||||
if (item.type === 'reasoning') continue;
|
||||
if (item.type === 'function_call_output') messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output });
|
||||
else if (item.type === 'function_call') {
|
||||
if (!messages.at(-1)?.tool_calls) messages.push({ role: 'assistant', content: '', tool_calls: [] });
|
||||
messages.at(-1).tool_calls.push({ id: item.call_id, type: 'function', function: { name: item.name, arguments: item.arguments } });
|
||||
} else messages.push({ role: item.role, content: typeof item.content === 'string' ? item.content : JSON.stringify(item.content) });
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
export function requestMetrics(body) {
|
||||
const serialized = JSON.stringify(body);
|
||||
const bytes = Buffer.byteLength(serialized, 'utf8');
|
||||
const variants = requestVariants(body);
|
||||
const images=requestImages(body);
|
||||
const imageReserve=imageTokenReserve(body);
|
||||
const estimates=variants.map(value=>Math.ceil(Buffer.byteLength(JSON.stringify(value, (key,item)=>typeof item==='string'&&item.startsWith('data:image/')?'[bounded image bytes]':item),'utf8')/3)
|
||||
+ (value.messages?.length ?? value.input?.length ?? 0)*8+(value.tools?.length??0)*16+imageTokenReserve(value));
|
||||
if(images.length)return {bytes,sha256:createHash('sha256').update(serialized,'utf8').digest('hex'),estimatedInputTokens:Math.max(...estimates),
|
||||
imageReservationTokens:imageReserve,imageCount:Math.max(...variants.map(value=>requestImages(value).length)),estimateMethod:'text-utf8-plus-image-reservation-v1',imageEstimate:'local-reservation-not-provider-billing'};
|
||||
return { bytes, sha256: createHash('sha256').update(serialized, 'utf8').digest('hex'),
|
||||
estimatedInputTokens: Math.max(...variants.map(value => Math.ceil(Buffer.byteLength(JSON.stringify(value), 'utf8') / 3)
|
||||
+ (value.messages?.length ?? value.input?.length ?? 0) * 8 + (value.tools?.length ?? 0) * 16)),
|
||||
estimateMethod: body.kind === 'model-route-plan' ? 'maximum-wire-variant-utf8-v1' : 'utf8-third-plus-framing-v1' };
|
||||
}
|
||||
|
||||
export function requestImages(body) {
|
||||
return requestVariants(body).flatMap(value=>(value.messages??value.input??[]).flatMap(message=>Array.isArray(message.content)?message.content.filter(part=>['image_url','input_image'].includes(part.type)).map(part=>part.type==='image_url'?part.image_url?.url:part.image_url):[]));
|
||||
}
|
||||
export function imageTokenReserve(body){
|
||||
return Math.max(0,...requestVariants(body).map(value=>requestImages(value).reduce((total,url)=>{
|
||||
if(typeof url!=='string'||!url.startsWith('data:image/png;base64,'))throw new Error('视觉请求只允许已校验的PNG发送副本。');
|
||||
const bytes=Buffer.from(url.slice(22,70),'base64');
|
||||
if(bytes.length<24||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||bytes.readUInt32BE(8)!==13||bytes.toString('ascii',12,16)!=='IHDR')throw new Error('视觉请求图像头不完整或类型不符。');
|
||||
const width=bytes.readUInt32BE(16),height=bytes.readUInt32BE(20);
|
||||
if(!width||!height||Math.max(width,height)>1024)throw new Error('视觉请求超过已校验副本范围。');
|
||||
return total+Math.max(4096,Math.ceil(width/32)*Math.ceil(height/32)*4);
|
||||
},0)));
|
||||
}
|
||||
|
||||
export function assertPlannedRequest(body, plan) {
|
||||
if (!plan) return;
|
||||
const metrics = requestMetrics(body);
|
||||
if (metrics.sha256 !== plan.requestSha256 || metrics.bytes !== plan.requestBytes) throw new Error('模型请求正文与已保存计划不一致,未发送请求。');
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
const fail = message => { throw Object.assign(new Error(message), { status: 400 }); };
|
||||
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
||||
const efforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
|
||||
const verbosity = ['low', 'medium', 'high'];
|
||||
|
||||
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField) {
|
||||
if (!object(parameters) || JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
|
||||
const allowed = protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
|
||||
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed'];
|
||||
for (const [key, value] of Object.entries(parameters)) {
|
||||
if (!allowed.includes(key)) fail('所选协议尚未接入原生参数:' + key + '。参数未保存或发送。');
|
||||
if (key === 'temperature' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 2)) fail('temperature应为0–2之间的数字。');
|
||||
if (key === 'top_p' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) fail('top_p应为0–1之间的数字。');
|
||||
if (key === 'seed' && !Number.isSafeInteger(value)) fail('seed应为安全整数。');
|
||||
if (key === 'parallel_tool_calls' && typeof value !== 'boolean') fail('parallel_tool_calls应为布尔值。');
|
||||
if (key === 'reasoning_effort' && !efforts.includes(value)) fail('reasoning_effort应为none/minimal/low/medium/high/xhigh。');
|
||||
if (key === 'verbosity' && !verbosity.includes(value)) fail('verbosity应为low/medium/high。');
|
||||
if (key === 'reasoning' && (!object(value) || Object.keys(value).length !== 1 || !efforts.includes(value.effort))) fail('Responses reasoning当前接入格式为{"effort":"low|medium|high等"}。');
|
||||
if (key === 'text' && (!object(value) || Object.keys(value).length !== 1 || !verbosity.includes(value.verbosity))) fail('Responses text当前接入格式为{"verbosity":"low|medium|high"}。');
|
||||
}
|
||||
const field = outputTokenField ?? (protocol === 'responses' ? 'max_output_tokens' : 'max_tokens');
|
||||
if (!(protocol === 'responses' ? ['max_output_tokens'] : ['max_tokens', 'max_completion_tokens']).includes(field)) fail('输出上限字段与所选协议不兼容。');
|
||||
return { nativeParameters: structuredClone(parameters), outputTokenField: field };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"observedAt": "2026-11-03T12:30:22.142Z",
|
||||
"connection": {
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "Claude 兼容代理",
|
||||
"protocol": "anthropic-messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"modelIdentityPolicy": "require-match",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"messagesAuth": "bearer",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"enabled": false,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 10,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:28:03.055Z",
|
||||
"hasKey": true,
|
||||
"credentialRevision": 2,
|
||||
"credentialStorage": "memory",
|
||||
"savedCredential": {
|
||||
"storage": "windows-user-dpapi",
|
||||
"status": "source_changed",
|
||||
"enabled": true,
|
||||
"connectionRevision": 1,
|
||||
"credentialRevision": 1,
|
||||
"savedAt": "2026-10-31T16:36:46.853Z",
|
||||
"message": "原保存块无法用于当前连接;重新填写后保存,或删除原保存。"
|
||||
},
|
||||
"status": "disabled",
|
||||
"activeRequests": 0,
|
||||
"health": {
|
||||
"state": "unverified"
|
||||
},
|
||||
"capabilities": {
|
||||
"text": "protocol_declared",
|
||||
"tools": "protocol_declared",
|
||||
"streaming": "protocol_declared",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
}
|
||||
},
|
||||
"selected": {
|
||||
"type": "pool",
|
||||
"id": "68e30376-b799-445b-a858-db2dba9920a0"
|
||||
},
|
||||
"registryRevision": 71,
|
||||
"attempts": 100,
|
||||
"eventCursor": 12953,
|
||||
"priorGuardFailure": {
|
||||
"expectedConnectionRevision": 9,
|
||||
"observedConnectionRevision": 10,
|
||||
"scriptStoppedBeforeAnyPOST": true
|
||||
},
|
||||
"realModelRequests": 0,
|
||||
"configurationWritesByThisInvestigation": 0
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"observedAt": "2026-11-03T12:31:04.652Z",
|
||||
"connection": {
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "Claude 兼容代理",
|
||||
"protocol": "anthropic-messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"modelIdentityPolicy": "require-match",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"messagesAuth": "bearer",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"enabled": false,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 10,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:28:03.055Z",
|
||||
"hasKey": true,
|
||||
"credentialRevision": 2,
|
||||
"credentialStorage": "memory",
|
||||
"savedCredential": {
|
||||
"storage": "windows-user-dpapi",
|
||||
"status": "source_changed",
|
||||
"enabled": true,
|
||||
"connectionRevision": 1,
|
||||
"credentialRevision": 1,
|
||||
"savedAt": "2026-10-31T16:36:46.853Z",
|
||||
"message": "原保存块无法用于当前连接;重新填写后保存,或删除原保存。"
|
||||
},
|
||||
"status": "disabled",
|
||||
"activeRequests": 0,
|
||||
"health": {
|
||||
"state": "unverified"
|
||||
},
|
||||
"capabilities": {
|
||||
"text": "protocol_declared",
|
||||
"tools": "protocol_declared",
|
||||
"streaming": "protocol_declared",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
}
|
||||
},
|
||||
"correction": {
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"enabled": false,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"streaming": true,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"revision": 10,
|
||||
"brand": "GPT 兼容代理",
|
||||
"protocol": "responses",
|
||||
"baseUrl": "https://api.apikey.fan/v1",
|
||||
"model": "gpt-6.1-sol",
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_output_tokens",
|
||||
"modelIdentityPolicy": "record",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": ""
|
||||
},
|
||||
"offlineRequestPreview": {
|
||||
"model": "gpt-6.1-sol",
|
||||
"input": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Owned offline configuration preview; do not send."
|
||||
}
|
||||
],
|
||||
"tools": [],
|
||||
"tool_choice": "auto",
|
||||
"max_output_tokens": 256,
|
||||
"stream": true,
|
||||
"store": false,
|
||||
"include": [
|
||||
"reasoning.encrypted_content"
|
||||
]
|
||||
},
|
||||
"fingerprints": {
|
||||
"attempts": "1cec376aef72ada7d763cae097e026ceffad5cba6264e8e5c7fadaa3e18a1d94",
|
||||
"otherConnections": "b9160471eaa2ba0ab2ac56882790aa95ab1a90dc641860136740dc2ce3cbd5fc",
|
||||
"pools": "f3e1c697739c631764f53d44ac657c79feb69e2b61506a3de38f166e2213163b",
|
||||
"selected": "7a99d0cc5119070bde45af01cd0f046d497f59b831449d624418bb31c80ec11d",
|
||||
"config": "a91c9918bd19acc3f9b01e51105014c975aafda5b9fcb9253cb235618cf68dbc",
|
||||
"projects": "98a140e543de636c96c06f61f57709def4d668fb0c9f31e0acf5fb82529bca86",
|
||||
"visibleSessions": "e3798936ddfd3997cecac2d97c1febf70ea383fc757633c11e941bbcae7b6675",
|
||||
"originalMExport": "e9090afb888265c7a50688adf91dbdd205097fa6a4a8a2ac280447a421159fe0"
|
||||
},
|
||||
"eventCursor": 12953,
|
||||
"modelRegistryRevision": 71,
|
||||
"attempts": 100,
|
||||
"unarchivedSessions": 62,
|
||||
"userConfirmedGptGroup": true,
|
||||
"realModelRequests": 0,
|
||||
"credentialValuesReadOrSaved": false
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"executionSchemaVersion": 1,
|
||||
"exportedAt": "2026-11-03T12:33:27.884Z",
|
||||
"project": {
|
||||
"id": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\messages-m\\live\\identity-only",
|
||||
"name": "identity-only",
|
||||
"addedAt": "2026-11-03T12:03:11.893Z"
|
||||
},
|
||||
"session": {
|
||||
"id": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"title": "M · Claude Messages 单次身份预检(无工具)",
|
||||
"status": "paused",
|
||||
"createdAt": "2026-11-03T12:03:11.895Z",
|
||||
"updatedAt": "2026-11-03T12:03:16.158Z",
|
||||
"messages": [
|
||||
{
|
||||
"id": "fc1c6dd2-6090-4db5-943e-c6fc3e4e66ee",
|
||||
"role": "user",
|
||||
"content": "这是单次连接身份预检,不是工程任务。只回复 OK d61bc9c6-48f2-4f91-af6c-930a128b959e。不要调用工具或执行任何项目工作。",
|
||||
"createdAt": "2026-11-03T12:03:12.022Z"
|
||||
},
|
||||
{
|
||||
"id": "37fb349c-a34d-4881-a568-1aff276802c5",
|
||||
"role": "system",
|
||||
"content": "请求与返回型号不一致。本次响应及用量已保留,工具未执行;核对连接或型号映射后显式续接。",
|
||||
"createdAt": "2026-11-03T12:03:16.150Z"
|
||||
}
|
||||
],
|
||||
"providerMessages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "这是单次连接身份预检,不是工程任务。只回复 OK d61bc9c6-48f2-4f91-af6c-930a128b959e。不要调用工具或执行任何项目工作。"
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"id": "b96e8215-8994-46aa-876a-42f7bf5018dc",
|
||||
"createdAt": "2026-11-03T12:03:12.048Z",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"kind": "model",
|
||||
"source": "model_connection",
|
||||
"label": "单次 Messages 身份预检(无工具)",
|
||||
"phase": "failed",
|
||||
"contextPlanId": "ac38f1b5-8124-4c96-9753-e4deb9c5cab7",
|
||||
"startedAt": "2026-11-03T12:03:12.048Z",
|
||||
"modelAttemptId": "231eaad2-3a1b-41a3-a225-c1304912604d",
|
||||
"connectionId": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"actualModel": "claude-opus-5-5",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"diagnostic": {
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"route": "/v1/messages",
|
||||
"attempt": 1,
|
||||
"attemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"responseUrl": "https://api.apikey.fan/v1/messages",
|
||||
"redirected": false,
|
||||
"redirectMode": "manual",
|
||||
"source": "model_connection",
|
||||
"origin": "local",
|
||||
"stage": "model_identity",
|
||||
"kind": "model_identity",
|
||||
"title": "模型返回型号需要核对",
|
||||
"message": "请求与返回型号不一致。本次响应及用量已保留,工具未执行;核对连接或型号映射后显式续接。",
|
||||
"modelIdentity": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "claude-opus-5-5",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
|
||||
"responseSource": {
|
||||
"artifactId": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"scope": "sse-stream"
|
||||
}
|
||||
},
|
||||
"retryable": false,
|
||||
"failoverAllowed": false,
|
||||
"outcome": "failed",
|
||||
"occurredAt": "2026-11-03T12:03:16.138Z",
|
||||
"attempts": 1,
|
||||
"wireAttemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"upstreamRequestId": "4b7dc9bb-7ed4-4a03-bc6c-645aef45b03f, 7828c8a5-9a47-4d1d-900f-448ff13cbd5a",
|
||||
"retryDecision": "stream_not_replayed",
|
||||
"remainingWaitBudgetMs": 295909
|
||||
},
|
||||
"finishedAt": "2026-11-03T12:03:16.155Z"
|
||||
}
|
||||
],
|
||||
"changes": [],
|
||||
"approvals": [],
|
||||
"failure": {
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"route": "/v1/messages",
|
||||
"attempt": 1,
|
||||
"attemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"responseUrl": "https://api.apikey.fan/v1/messages",
|
||||
"redirected": false,
|
||||
"redirectMode": "manual",
|
||||
"source": "model_connection",
|
||||
"origin": "local",
|
||||
"stage": "model_identity",
|
||||
"kind": "model_identity",
|
||||
"title": "模型返回型号需要核对",
|
||||
"message": "请求与返回型号不一致。本次响应及用量已保留,工具未执行;核对连接或型号映射后显式续接。",
|
||||
"modelIdentity": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "claude-opus-5-5",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
|
||||
"responseSource": {
|
||||
"artifactId": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"scope": "sse-stream"
|
||||
}
|
||||
},
|
||||
"retryable": false,
|
||||
"failoverAllowed": false,
|
||||
"outcome": "failed",
|
||||
"occurredAt": "2026-11-03T12:03:16.138Z",
|
||||
"attempts": 1,
|
||||
"wireAttemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"upstreamRequestId": "4b7dc9bb-7ed4-4a03-bc6c-645aef45b03f, 7828c8a5-9a47-4d1d-900f-448ff13cbd5a",
|
||||
"retryDecision": "stream_not_replayed",
|
||||
"remainingWaitBudgetMs": 295909,
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"messageId": "37fb349c-a34d-4881-a568-1aff276802c5"
|
||||
},
|
||||
"lastFailure": {
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"route": "/v1/messages",
|
||||
"attempt": 1,
|
||||
"attemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"responseUrl": "https://api.apikey.fan/v1/messages",
|
||||
"redirected": false,
|
||||
"redirectMode": "manual",
|
||||
"source": "model_connection",
|
||||
"origin": "local",
|
||||
"stage": "model_identity",
|
||||
"kind": "model_identity",
|
||||
"title": "模型返回型号需要核对",
|
||||
"message": "请求与返回型号不一致。本次响应及用量已保留,工具未执行;核对连接或型号映射后显式续接。",
|
||||
"modelIdentity": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "claude-opus-5-5",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
|
||||
"responseSource": {
|
||||
"artifactId": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"scope": "sse-stream"
|
||||
}
|
||||
},
|
||||
"retryable": false,
|
||||
"failoverAllowed": false,
|
||||
"outcome": "failed",
|
||||
"occurredAt": "2026-11-03T12:03:16.138Z",
|
||||
"attempts": 1,
|
||||
"wireAttemptId": "6bd71c48-a40d-427c-83ee-599be2856f09",
|
||||
"upstreamRequestId": "4b7dc9bb-7ed4-4a03-bc6c-645aef45b03f, 7828c8a5-9a47-4d1d-900f-448ff13cbd5a",
|
||||
"retryDecision": "stream_not_replayed",
|
||||
"remainingWaitBudgetMs": 295909,
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b"
|
||||
},
|
||||
"compactions": 0,
|
||||
"estimatedTokens": 155,
|
||||
"usage": {
|
||||
"prompt_tokens": 192,
|
||||
"completion_tokens": 29,
|
||||
"total_tokens": 221,
|
||||
"prompt_tokens_details": {
|
||||
"cached_tokens": 0,
|
||||
"cache_creation_tokens": 0
|
||||
},
|
||||
"raw": {
|
||||
"input_tokens": 192,
|
||||
"output_tokens": 29,
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0
|
||||
},
|
||||
"protocol": "anthropic-messages"
|
||||
},
|
||||
"archived": false,
|
||||
"revision": 22,
|
||||
"eventSeq": 12953,
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b"
|
||||
},
|
||||
"execution": {
|
||||
"schemaVersion": 1,
|
||||
"task": {
|
||||
"schemaVersion": 1,
|
||||
"id": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"goal": "这是单次连接身份预检,不是工程任务。只回复 OK d61bc9c6-48f2-4f91-af6c-930a128b959e。不要调用工具或执行任何项目工作。",
|
||||
"instructions": [],
|
||||
"constraints": [],
|
||||
"acceptance": [],
|
||||
"status": "paused",
|
||||
"previousTaskId": null,
|
||||
"createdAt": "2026-11-03T12:03:12.018Z",
|
||||
"updatedAt": "2026-11-03T12:03:16.158Z",
|
||||
"activeRunId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"usage": {
|
||||
"requests": 1,
|
||||
"inputTokens": 192,
|
||||
"outputTokens": 29,
|
||||
"totalTokens": 221,
|
||||
"unknownRequests": 0,
|
||||
"estimatedUnknownTokens": 0
|
||||
},
|
||||
"budget": {
|
||||
"maxTokens": 16000
|
||||
},
|
||||
"verification": {
|
||||
"status": "not_configured",
|
||||
"checkJobId": null
|
||||
},
|
||||
"origin": "workbench",
|
||||
"contract": {
|
||||
"schemaVersion": 1,
|
||||
"goal": "这是单次连接身份预检,不是工程任务。只回复 OK d61bc9c6-48f2-4f91-af6c-930a128b959e。不要调用工具或执行任何项目工作。",
|
||||
"kind": "general",
|
||||
"checks": "unspecified"
|
||||
},
|
||||
"workspaceIdentity": {
|
||||
"kind": "local-project",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\messages-m\\live\\identity-only"
|
||||
},
|
||||
"stagnation": null
|
||||
},
|
||||
"run": {
|
||||
"schemaVersion": 1,
|
||||
"id": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"engine": "workbench",
|
||||
"status": "paused",
|
||||
"startedAt": "2026-11-03T12:03:12.019Z",
|
||||
"finishedAt": "2026-11-03T12:03:16.158Z",
|
||||
"resumeOf": null,
|
||||
"model": {
|
||||
"mode": "compatible",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"model": "claude-opus-5-5",
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 256,
|
||||
"configRevision": 52,
|
||||
"modelResponseTimeoutMs": 300000,
|
||||
"modelStreamIdleTimeoutMs": 120000,
|
||||
"protocol": "anthropic-messages",
|
||||
"streaming": true,
|
||||
"messagesAuth": "bearer",
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"routing": {
|
||||
"type": "connection",
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"revision": 9,
|
||||
"strategy": "round-robin",
|
||||
"sticky": true,
|
||||
"maxAttempts": 1,
|
||||
"queueTimeoutMs": 15000,
|
||||
"members": [
|
||||
{
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "Claude 兼容代理",
|
||||
"protocol": "anthropic-messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"modelIdentityPolicy": "require-match",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"messagesAuth": "bearer",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"enabled": true,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 9,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:03:11.887Z",
|
||||
"weight": 1,
|
||||
"credentialRevision": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"budget": {
|
||||
"maxSteps": 1,
|
||||
"maxDurationMs": 320000,
|
||||
"maxTokens": 16000,
|
||||
"maxTaskTokens": 16000
|
||||
},
|
||||
"usage": {
|
||||
"requests": 1,
|
||||
"inputTokens": 192,
|
||||
"outputTokens": 29,
|
||||
"totalTokens": 221,
|
||||
"unknownRequests": 0,
|
||||
"estimatedUnknownTokens": 0
|
||||
},
|
||||
"steps": 1,
|
||||
"toolCalls": 0,
|
||||
"stopReason": "model_identity",
|
||||
"checkpoint": {
|
||||
"stepId": "e4081cda-bcd1-42a2-aaf6-9ec93ccc27d2",
|
||||
"completedToolIds": [],
|
||||
"pendingToolIds": [],
|
||||
"requiresVerification": []
|
||||
},
|
||||
"origin": "workbench",
|
||||
"purpose": "execution",
|
||||
"workspaceIdentity": {
|
||||
"kind": "local-project",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\messages-m\\live\\identity-only"
|
||||
},
|
||||
"currentContextPlanId": "ac38f1b5-8124-4c96-9753-e4deb9c5cab7",
|
||||
"consumption": [
|
||||
{
|
||||
"attemptId": "231eaad2-3a1b-41a3-a225-c1304912604d",
|
||||
"requestId": "ac38f1b5-8124-4c96-9753-e4deb9c5cab7",
|
||||
"connectionId": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"connectionName": "apikey",
|
||||
"model": "claude-opus-5-5",
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"protocol": "anthropic-messages",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"responseUrl": "https://api.apikey.fan/v1/messages",
|
||||
"redirected": false,
|
||||
"redirectMode": "manual",
|
||||
"startedAt": "2026-11-03T12:03:12.047Z",
|
||||
"finishedAt": "2026-11-03T12:03:16.141Z",
|
||||
"outcome": "failed",
|
||||
"usageStatus": "reported",
|
||||
"usage": {
|
||||
"prompt_tokens": 192,
|
||||
"completion_tokens": 29,
|
||||
"total_tokens": 221,
|
||||
"prompt_tokens_details": {
|
||||
"cached_tokens": 0,
|
||||
"cache_creation_tokens": 0
|
||||
},
|
||||
"raw": {
|
||||
"input_tokens": 192,
|
||||
"output_tokens": 29,
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0
|
||||
},
|
||||
"protocol": "anthropic-messages"
|
||||
},
|
||||
"localEstimate": {
|
||||
"schemaVersion": 1,
|
||||
"inputTokens": 155,
|
||||
"outputTokens": 256,
|
||||
"requestSha256": "5420746a315e7226d1636d6229bdb4545b2089c3f3e36c2019bfce32e250ef40",
|
||||
"requestBytes": 440,
|
||||
"estimateMethod": "utf8-third-plus-framing-v1"
|
||||
},
|
||||
"modelIdentity": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "claude-opus-5-5",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
|
||||
"responseSource": {
|
||||
"artifactId": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"scope": "sse-stream"
|
||||
}
|
||||
},
|
||||
"estimatedUnknownTokens": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"workspaceIdentity": {
|
||||
"kind": "local-project",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\messages-m\\live\\identity-only"
|
||||
},
|
||||
"workspaces": [],
|
||||
"runs": [
|
||||
{
|
||||
"id": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"status": "paused",
|
||||
"startedAt": "2026-11-03T12:03:12.019Z",
|
||||
"finishedAt": "2026-11-03T12:03:16.158Z",
|
||||
"steps": 1,
|
||||
"toolCalls": 0,
|
||||
"usage": {
|
||||
"requests": 1,
|
||||
"inputTokens": 192,
|
||||
"outputTokens": 29,
|
||||
"totalTokens": 221,
|
||||
"unknownRequests": 0,
|
||||
"estimatedUnknownTokens": 0
|
||||
},
|
||||
"stopReason": "model_identity",
|
||||
"model": {
|
||||
"mode": "compatible",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"model": "claude-opus-5-5",
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 256,
|
||||
"configRevision": 52,
|
||||
"modelResponseTimeoutMs": 300000,
|
||||
"modelStreamIdleTimeoutMs": 120000,
|
||||
"protocol": "anthropic-messages",
|
||||
"streaming": true,
|
||||
"messagesAuth": "bearer",
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"routing": {
|
||||
"type": "connection",
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"revision": 9,
|
||||
"strategy": "round-robin",
|
||||
"sticky": true,
|
||||
"maxAttempts": 1,
|
||||
"queueTimeoutMs": 15000,
|
||||
"members": [
|
||||
{
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "Claude 兼容代理",
|
||||
"protocol": "anthropic-messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_tokens",
|
||||
"modelIdentityPolicy": "require-match",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"messagesAuth": "bearer",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"enabled": true,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 9,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:03:11.887Z",
|
||||
"weight": 1,
|
||||
"credentialRevision": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"budget": {
|
||||
"maxSteps": 1,
|
||||
"maxDurationMs": 320000,
|
||||
"maxTokens": 16000,
|
||||
"maxTaskTokens": 16000
|
||||
},
|
||||
"resumeOf": null,
|
||||
"purpose": "execution",
|
||||
"consumption": [
|
||||
{
|
||||
"attemptId": "231eaad2-3a1b-41a3-a225-c1304912604d",
|
||||
"requestId": "ac38f1b5-8124-4c96-9753-e4deb9c5cab7",
|
||||
"connectionId": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"connectionName": "apikey",
|
||||
"model": "claude-opus-5-5",
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"protocol": "anthropic-messages",
|
||||
"requestUrl": "https://api.apikey.fan/v1/messages",
|
||||
"responseUrl": "https://api.apikey.fan/v1/messages",
|
||||
"redirected": false,
|
||||
"redirectMode": "manual",
|
||||
"startedAt": "2026-11-03T12:03:12.047Z",
|
||||
"finishedAt": "2026-11-03T12:03:16.141Z",
|
||||
"outcome": "failed",
|
||||
"usageStatus": "reported",
|
||||
"usage": {
|
||||
"prompt_tokens": 192,
|
||||
"completion_tokens": 29,
|
||||
"total_tokens": 221,
|
||||
"prompt_tokens_details": {
|
||||
"cached_tokens": 0,
|
||||
"cache_creation_tokens": 0
|
||||
},
|
||||
"raw": {
|
||||
"input_tokens": 192,
|
||||
"output_tokens": 29,
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0
|
||||
},
|
||||
"protocol": "anthropic-messages"
|
||||
},
|
||||
"localEstimate": {
|
||||
"schemaVersion": 1,
|
||||
"inputTokens": 155,
|
||||
"outputTokens": 256,
|
||||
"requestSha256": "5420746a315e7226d1636d6229bdb4545b2089c3f3e36c2019bfce32e250ef40",
|
||||
"requestBytes": 440,
|
||||
"estimateMethod": "utf8-third-plus-framing-v1"
|
||||
},
|
||||
"modelIdentity": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "claude-opus-5-5",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
|
||||
"responseSource": {
|
||||
"artifactId": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"scope": "sse-stream"
|
||||
}
|
||||
},
|
||||
"estimatedUnknownTokens": 0
|
||||
}
|
||||
],
|
||||
"workspaceIdentity": {
|
||||
"kind": "local-project",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\messages-m\\live\\identity-only"
|
||||
}
|
||||
}
|
||||
],
|
||||
"progress": {
|
||||
"totalTools": 0,
|
||||
"completedTools": 0,
|
||||
"requiresVerification": []
|
||||
},
|
||||
"artifacts": [
|
||||
{
|
||||
"id": "3f2dc729-eb5f-4adc-9963-5d98a7ce2263",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"kind": "model-request",
|
||||
"mediaType": "application/json",
|
||||
"sha256": "be6a6f17b2fd447f097514778202d8b4ee6c0d272882dd0ece9113c1535ad8d7",
|
||||
"bytes": 938,
|
||||
"relative": "be/be6a6f17b2fd447f097514778202d8b4ee6c0d272882dd0ece9113c1535ad8d7.blob",
|
||||
"createdAt": "2026-11-03T12:03:12.031Z",
|
||||
"status": "stored"
|
||||
},
|
||||
{
|
||||
"id": "8c0f7dfa-31ad-4a63-abd2-7c5161a2c287",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"kind": "context-plan",
|
||||
"mediaType": "application/json",
|
||||
"sha256": "a04e9f0cf68cfd3f3cb06b5e9fef1d8102d6b14ba2d2806b7b3acc80a8174629",
|
||||
"bytes": 2084,
|
||||
"relative": "a0/a04e9f0cf68cfd3f3cb06b5e9fef1d8102d6b14ba2d2806b7b3acc80a8174629.blob",
|
||||
"createdAt": "2026-11-03T12:03:12.033Z",
|
||||
"status": "stored"
|
||||
},
|
||||
{
|
||||
"id": "8f508263-0025-4553-a194-1daff505fc22",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"kind": "model-attempt-request",
|
||||
"mediaType": "application/json",
|
||||
"sha256": "5420746a315e7226d1636d6229bdb4545b2089c3f3e36c2019bfce32e250ef40",
|
||||
"bytes": 440,
|
||||
"relative": "54/5420746a315e7226d1636d6229bdb4545b2089c3f3e36c2019bfce32e250ef40.blob",
|
||||
"createdAt": "2026-11-03T12:03:12.040Z",
|
||||
"status": "stored"
|
||||
},
|
||||
{
|
||||
"id": "eeb6c2ef-c9aa-4202-ab19-dbc19877d0bc",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"kind": "model-stream-response",
|
||||
"mediaType": "text/event-stream",
|
||||
"sha256": "403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4",
|
||||
"bytes": 3214,
|
||||
"relative": "40/403a817ff9c9b4d4f7bd0094eac561cd358a541398a4875c9167a08ece1482c4.blob",
|
||||
"createdAt": "2026-11-03T12:03:16.135Z",
|
||||
"status": "stored"
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"browsingTabs": [],
|
||||
"browsingActions": [],
|
||||
"previewPlans": [],
|
||||
"previewJobs": [],
|
||||
"mcpJobs": [],
|
||||
"taskPlans": [],
|
||||
"taskProofs": [],
|
||||
"researchTargets": [],
|
||||
"researchJobs": [],
|
||||
"engineJobs": [],
|
||||
"browserPlans": [],
|
||||
"browserJobs": [],
|
||||
"contextPlans": [
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "ac38f1b5-8124-4c96-9753-e4deb9c5cab7",
|
||||
"sessionId": "f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76",
|
||||
"projectId": "cff9670c-f188-4187-833e-e552b2725b8c",
|
||||
"taskId": "15d22836-27a0-422c-a0a3-d0ed1752d1f4",
|
||||
"runId": "b175e0e0-1472-42af-99dd-bda5d1edcc0b",
|
||||
"stepId": "e4081cda-bcd1-42a2-aaf6-9ec93ccc27d2",
|
||||
"requestIndex": 1,
|
||||
"status": "failed",
|
||||
"createdAt": "2026-11-03T12:03:12.031Z",
|
||||
"finishedAt": "2026-11-03T12:03:16.153Z",
|
||||
"requestSha256": "be6a6f17b2fd447f097514778202d8b4ee6c0d272882dd0ece9113c1535ad8d7",
|
||||
"requestBytes": 938,
|
||||
"estimatedInputTokens": 155,
|
||||
"requestArtifactId": "3f2dc729-eb5f-4adc-9963-5d98a7ce2263",
|
||||
"tokenReservation": {
|
||||
"schemaVersion": 1,
|
||||
"method": "observed-route-max-v1",
|
||||
"overheadTokens": 0,
|
||||
"reservedTokens": 411,
|
||||
"routes": [
|
||||
{
|
||||
"connectionId": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"model": "claude-opus-5-5",
|
||||
"protocol": "anthropic-messages",
|
||||
"endpoint": "https://api.apikey.fan",
|
||||
"localInputTokens": 155,
|
||||
"outputReservation": 256,
|
||||
"inputRatio": 1,
|
||||
"observedOutputTokens": 256,
|
||||
"observedTotalFloor": 0,
|
||||
"reservedTokens": 411,
|
||||
"sources": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"maxBudgetAttempts": 8,
|
||||
"estimateMethod": "maximum-wire-variant-utf8-v1",
|
||||
"beforeInputTokens": 155,
|
||||
"beforeBytes": 938,
|
||||
"budget": {
|
||||
"contextLimit": 16000,
|
||||
"outputReservation": 256,
|
||||
"safetyTokens": 1600,
|
||||
"inputBudget": 14144,
|
||||
"targetInputTokens": 14144,
|
||||
"runRemainingTokens": 16000,
|
||||
"taskRemainingTokens": 16000,
|
||||
"limitingReason": "context_limit"
|
||||
},
|
||||
"mandatoryInputTokens": 155,
|
||||
"nextReadFixedInputTokens": 155,
|
||||
"workingRetentionTokens": 0,
|
||||
"workingRetentionPolicyVersion": 1,
|
||||
"originalMessages": 1,
|
||||
"retainedMessages": 1,
|
||||
"archivedGroups": 0,
|
||||
"retainedGroups": [
|
||||
0
|
||||
],
|
||||
"historyIndexArtifactId": null,
|
||||
"historyIndexSha256": null,
|
||||
"actualUsage": null,
|
||||
"workingSetArtifactId": null,
|
||||
"workingSetSha256": null,
|
||||
"workingSetEntries": 0,
|
||||
"workingSetViewVersion": 2,
|
||||
"latestToolsArtifactId": null,
|
||||
"latestToolsSha256": null,
|
||||
"latestToolsEntries": 0,
|
||||
"projectMemoryArtifactId": null,
|
||||
"projectMemorySha256": null,
|
||||
"projectMemoryEntries": 0,
|
||||
"skillCatalogArtifactId": null,
|
||||
"skillCatalogSha256": null,
|
||||
"skillCatalogEntries": 0,
|
||||
"mcpCatalogArtifactId": null,
|
||||
"mcpCatalogSha256": null,
|
||||
"mcpCatalogEntries": 0,
|
||||
"requestAttempts": 1,
|
||||
"responseSha256": null,
|
||||
"source": "workbench",
|
||||
"artifactId": "8c0f7dfa-31ad-4a63-abd2-7c5161a2c287",
|
||||
"error": "请求与返回型号不一致。本次响应及用量已保留,工具未执行;核对连接或型号映射后显式续接。"
|
||||
}
|
||||
],
|
||||
"changeSets": [],
|
||||
"plans": [],
|
||||
"deliveries": [],
|
||||
"deliveryPlans": [],
|
||||
"accountedTaskTokens": 221
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "GPT 兼容代理",
|
||||
"protocol": "responses",
|
||||
"model": "gpt-6.1-sol",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_output_tokens",
|
||||
"modelIdentityPolicy": "record",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"baseUrl": "https://api.apikey.fan/v1",
|
||||
"enabled": false,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 11,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:31:04.656Z",
|
||||
"hasKey": true,
|
||||
"credentialRevision": 2,
|
||||
"credentialStorage": "memory",
|
||||
"savedCredential": {
|
||||
"storage": "windows-user-dpapi",
|
||||
"status": "source_changed",
|
||||
"enabled": true,
|
||||
"connectionRevision": 1,
|
||||
"credentialRevision": 1,
|
||||
"savedAt": "2026-10-31T16:36:46.853Z",
|
||||
"message": "原保存块无法用于当前连接;重新填写后保存,或删除原保存。"
|
||||
},
|
||||
"status": "disabled",
|
||||
"activeRequests": 0,
|
||||
"health": {
|
||||
"state": "unverified"
|
||||
},
|
||||
"capabilities": {
|
||||
"text": "protocol_declared",
|
||||
"tools": "protocol_declared",
|
||||
"streaming": "protocol_declared",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"passed": true,
|
||||
"observedAt": "2026-11-03T12:33:27.888Z",
|
||||
"version": "1.24.4",
|
||||
"connection": {
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"brand": "GPT 兼容代理",
|
||||
"protocol": "responses",
|
||||
"model": "gpt-6.1-sol",
|
||||
"capabilitySchema": 1,
|
||||
"capabilityDeclarations": {
|
||||
"text": "supported",
|
||||
"tools": "supported",
|
||||
"streaming": "supported",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
},
|
||||
"streaming": true,
|
||||
"nativeParameters": {},
|
||||
"outputTokenField": "max_output_tokens",
|
||||
"modelIdentityPolicy": "record",
|
||||
"modelIdentityAliases": [],
|
||||
"modelIdentityAliasSource": "",
|
||||
"baseUrl": "https://api.apikey.fan/v1",
|
||||
"enabled": false,
|
||||
"requiresKey": true,
|
||||
"contextLimit": 16000,
|
||||
"maxOutputTokens": 2048,
|
||||
"concurrency": 8,
|
||||
"revision": 11,
|
||||
"source": "manual",
|
||||
"createdAt": "2026-10-31T16:36:46.574Z",
|
||||
"updatedAt": "2026-11-03T12:31:04.656Z",
|
||||
"hasKey": true,
|
||||
"credentialRevision": 2,
|
||||
"credentialStorage": "memory",
|
||||
"savedCredential": {
|
||||
"storage": "windows-user-dpapi",
|
||||
"status": "source_changed",
|
||||
"enabled": true,
|
||||
"connectionRevision": 1,
|
||||
"credentialRevision": 1,
|
||||
"savedAt": "2026-10-31T16:36:46.853Z",
|
||||
"message": "原保存块无法用于当前连接;重新填写后保存,或删除原保存。"
|
||||
},
|
||||
"status": "disabled",
|
||||
"activeRequests": 0,
|
||||
"health": {
|
||||
"state": "unverified"
|
||||
},
|
||||
"capabilities": {
|
||||
"text": "protocol_declared",
|
||||
"tools": "protocol_declared",
|
||||
"streaming": "protocol_declared",
|
||||
"vision": "unknown",
|
||||
"audio": "unknown"
|
||||
}
|
||||
},
|
||||
"requestUrl": "https://api.apikey.fan/v1/responses",
|
||||
"changed": [
|
||||
"brand",
|
||||
"protocol",
|
||||
"baseUrl",
|
||||
"model",
|
||||
"outputTokenField",
|
||||
"modelIdentityPolicy",
|
||||
"messagesAuth removed",
|
||||
"connection/model-registry revision and updatedAt"
|
||||
],
|
||||
"retained": {
|
||||
"originalCredentialRevision": 2,
|
||||
"hasKey": true,
|
||||
"disabledState": "exact",
|
||||
"otherConnections": "exact",
|
||||
"defaultPool": "exact",
|
||||
"defaultSelection": "exact",
|
||||
"globalConfig": "exact",
|
||||
"last100VisibleAttempts": "exact",
|
||||
"originalMProjectSessionExecution": "exact",
|
||||
"originalMExportGeneratedAt": "generated field only",
|
||||
"projectList": "exact",
|
||||
"unarchivedSessionList": "exact",
|
||||
"eventCursor": "exact",
|
||||
"limitsAndCapabilityDeclarations": "exact"
|
||||
},
|
||||
"exportVerification": {
|
||||
"matchedBeforeAt": "2026-11-03T12:31:04.649Z",
|
||||
"currentExportedAt": "2026-11-03T12:33:27.884Z",
|
||||
"beforeFullFingerprint": "e9090afb888265c7a50688adf91dbdd205097fa6a4a8a2ac280447a421159fe0",
|
||||
"normalizedFingerprint": "bd62afa0a40717ee58ee8cd90637aaf5dc14aeca1eae4c087d7240d46ea067ff",
|
||||
"sealedMNormalizedFingerprint": "bd62afa0a40717ee58ee8cd90637aaf5dc14aeca1eae4c087d7240d46ea067ff",
|
||||
"permittedDifference": "/exportedAt only"
|
||||
},
|
||||
"firstGuard": {
|
||||
"expectedRevision": 9,
|
||||
"observedRevision": 10,
|
||||
"stoppedBeforePOST": true,
|
||||
"externalChange": "enabled true to false"
|
||||
},
|
||||
"firstPostAudit": {
|
||||
"failedBecause": "Generated /exportedAt was hashed as stored session data",
|
||||
"source": "src/server/app.mjs:770",
|
||||
"configurationPOSTWasNotReplayed": true
|
||||
},
|
||||
"unarchivedSessions": 62,
|
||||
"visibleAttempts": 100,
|
||||
"calls": [
|
||||
{
|
||||
"method": "GET",
|
||||
"route": "/api/bootstrap",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"route": "/api/model-center",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"route": "/api/sessions/f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76/export",
|
||||
"status": 200
|
||||
}
|
||||
],
|
||||
"realModelRequests": 0,
|
||||
"totalConfigurationPOSTs": 1,
|
||||
"credentialValuesReadOrSaved": false,
|
||||
"localAuthorizationTokenSaved": false,
|
||||
"scope": "Confirmed GPT configuration corrected; disabled state and public metadata retained. No new inference, model-weights authentication, full-database/artifact re-audit or replay of old runs."
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"observedAt": "2026-11-03T12:20:27.580Z",
|
||||
"version": "1.24.4",
|
||||
"runtimeRoot": "C:\\Users\\wangy\\AppData\\Local\\Programs\\AgentWorkbench\\versions\\Agent-Workbench-1.24.4-win-x64-20261103112054864",
|
||||
"modelSelection": {
|
||||
"type": "pool",
|
||||
"id": "68e30376-b799-445b-a858-db2dba9920a0",
|
||||
"name": "高性能"
|
||||
},
|
||||
"selected": {
|
||||
"type": "pool",
|
||||
"id": "68e30376-b799-445b-a858-db2dba9920a0"
|
||||
},
|
||||
"defaultConfig": {
|
||||
"mode": "compatible",
|
||||
"model": "gpt-6.1-sol",
|
||||
"baseUrl": "https://jojocode.com/v1"
|
||||
},
|
||||
"connections": [
|
||||
{
|
||||
"id": "legacy-default",
|
||||
"name": "原模型连接",
|
||||
"protocol": "chat-completions",
|
||||
"model": "gpt-6.1-sol",
|
||||
"baseUrl": "https://jojocode.com/v1",
|
||||
"revision": 52,
|
||||
"credentialRevision": 1,
|
||||
"hasKey": true
|
||||
},
|
||||
{
|
||||
"id": "5b4daed9-b2f7-4de0-b949-573eba70c7b3",
|
||||
"name": "jojocode",
|
||||
"protocol": "chat-completions",
|
||||
"model": "gpt-6.1-sol",
|
||||
"baseUrl": "https://jojocode.com/v1",
|
||||
"revision": 3,
|
||||
"credentialRevision": 1,
|
||||
"hasKey": true
|
||||
},
|
||||
{
|
||||
"id": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"name": "apikey",
|
||||
"protocol": "anthropic-messages",
|
||||
"model": "claude-opus-5-5",
|
||||
"baseUrl": "https://api.apikey.fan",
|
||||
"messagesAuth": "bearer",
|
||||
"revision": 9,
|
||||
"credentialRevision": 2,
|
||||
"hasKey": true
|
||||
}
|
||||
],
|
||||
"pools": [
|
||||
{
|
||||
"id": "68e30376-b799-445b-a858-db2dba9920a0",
|
||||
"name": "高性能",
|
||||
"strategy": "round-robin",
|
||||
"members": [
|
||||
{
|
||||
"connectionId": "5b4daed9-b2f7-4de0-b949-573eba70c7b3",
|
||||
"weight": 1
|
||||
},
|
||||
{
|
||||
"connectionId": "09b0293b-faad-45c3-832d-7c8b615813aa",
|
||||
"weight": 1
|
||||
}
|
||||
],
|
||||
"maxAttempts": 3
|
||||
}
|
||||
],
|
||||
"projects": 56,
|
||||
"sessions": 62,
|
||||
"activeSessions": 0,
|
||||
"requests": [
|
||||
{
|
||||
"method": "GET",
|
||||
"route": "/api/bootstrap",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"route": "/api/model-center",
|
||||
"status": 200
|
||||
}
|
||||
],
|
||||
"realModelRequests": 0,
|
||||
"remoteCredentialRequests": 0,
|
||||
"credentialValuesReadOrSaved": false,
|
||||
"localAuthorizationTokenSaved": false,
|
||||
"scope": "Current public routing metadata only; no POST, credential endpoint, inference, restart, or historical process environment read."
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const root = process.cwd();
|
||||
const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
|
||||
const freezePath = 'docs/messages-m-evidence/release/product-freeze.json';
|
||||
const freezeBytes = await fs.readFile(path.join(root, freezePath));
|
||||
const freeze = JSON.parse(freezeBytes);
|
||||
const entries = freeze.files.filter(file => file.path.startsWith('src/'));
|
||||
const results = [];
|
||||
for (const entry of entries) {
|
||||
const actual = await fs.readFile(path.join(root, entry.path));
|
||||
const actualSha256 = sha256(actual);
|
||||
results.push({ ...entry, actualBytes: actual.length, actualSha256,
|
||||
passed: actual.length === entry.bytes && actualSha256 === entry.sha256 });
|
||||
}
|
||||
async function walk(directory) {
|
||||
const files = [];
|
||||
for (const entry of await fs.readdir(path.join(root, directory), { withFileTypes: true })) {
|
||||
const name = `${directory}/${entry.name}`;
|
||||
if (entry.isDirectory()) files.push(...await walk(name));
|
||||
else if (entry.isFile()) files.push(name);
|
||||
else throw new Error(`Unexpected non-file source entry: ${name}`);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
const expectedPaths = new Set(entries.map(file => file.path));
|
||||
const actualPaths = await walk('src');
|
||||
const extraPaths = actualPaths.filter(file => !expectedPaths.has(file));
|
||||
const mManifestPath = 'docs/messages-m-evidence/manifest.json';
|
||||
const mManifestSha256 = sha256(await fs.readFile(path.join(root, mManifestPath)));
|
||||
const expectedMManifestSha256 = 'c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7';
|
||||
const passed = entries.length === 220 && actualPaths.length === 220 &&
|
||||
results.every(file => file.passed) && extraPaths.length === 0 &&
|
||||
mManifestSha256 === expectedMManifestSha256;
|
||||
const result = { passed, checkedAt: new Date().toISOString(), version: freeze.version,
|
||||
sourceCommit: freeze.sourceCommit, freezePath, freezeSha256: sha256(freezeBytes),
|
||||
sourceFiles: entries.length, actualSourceFiles: actualPaths.length, extraPaths,
|
||||
mManifestPath, mManifestSha256, expectedMManifestSha256, results,
|
||||
realModelRequests: 0, productFilesWritten: 0,
|
||||
scope: 'Read-only comparison of current src files against the deployed M source freeze; not a new full artifact or database audit.' };
|
||||
await fs.writeFile(path.join(root, '.qa/route-n/source-integrity.json'), `${JSON.stringify(result, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ...result, results: undefined }));
|
||||
if (!passed) process.exitCode = 1;
|
||||
@@ -0,0 +1,66 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import * as current from '../src/shared/contracts/model-request.mjs';
|
||||
import * as currentIdentity from '../src/shared/contracts/model-identity.mjs';
|
||||
import { visionProbe } from '../src/core/models/vision-probe.mjs';
|
||||
|
||||
const root = path.resolve('.qa/route-n');
|
||||
const modules = ['src/shared/contracts/model-request.mjs', 'src/shared/contracts/model-capabilities.mjs', 'src/shared/contracts/native-parameters.mjs'];
|
||||
const hash = b => createHash('sha256').update(b).digest('hex');
|
||||
const base = { mode: 'compatible', model: 'gpt-6.1-sol', baseUrl: 'https://example.invalid/v1', maxOutputTokens: 1024 };
|
||||
const messages = [{ role: 'system', content: 'Owned offline fixture.' }, { role: 'user', content: 'Inspect the sample.' }];
|
||||
const tools = [{ type: 'function', function: { name: 'owned_echo', description: 'Owned fixture only', parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false } } }];
|
||||
const image = visionProbe().image;
|
||||
const history = [...messages, { role: 'assistant', content: '', tool_calls: [{ id: 'owned-call', type: 'function', function: { name: 'owned_echo', arguments: '{"text":"x"}' } }] }, { role: 'tool', tool_call_id: 'owned-call', content: '{"text":"x"}' }];
|
||||
const cases = [];
|
||||
for (const protocol of ['chat-completions', 'responses']) {
|
||||
const config = { ...base, protocol };
|
||||
cases.push(
|
||||
{ name: protocol + '/text', config, messages, tools: [] },
|
||||
{ name: protocol + '/tools', config, messages, tools },
|
||||
{ name: protocol + '/tool-history', config, messages: history, tools },
|
||||
{ name: protocol + '/stream', config: { ...config, streaming: true }, messages, tools },
|
||||
{ name: protocol + '/vision', config: { ...config, inputImages: [image] }, messages, tools },
|
||||
{ name: protocol + '/native', config: { ...config, nativeParameters: protocol === 'responses' ? { reasoning: { effort: 'high' }, text: { verbosity: 'low' }, parallel_tool_calls: false } : { reasoning_effort: 'high', verbosity: 'low', parallel_tool_calls: false }, outputTokenField: protocol === 'responses' ? 'max_output_tokens' : 'max_completion_tokens' }, messages, tools },
|
||||
{ name: protocol + '/brand-does-not-route', config: { ...config, brand: 'Claude 兼容代理' }, messages, tools },
|
||||
);
|
||||
}
|
||||
cases.push({ name: 'legacy-missing-protocol', config: base, messages, tools });
|
||||
cases.push({ name: 'responses-retained-reasoning', config: { ...base, protocol: 'responses' }, messages: [...messages, { role: 'assistant', content: 'prior', providerState: { protocol: 'responses', endpoint: base.baseUrl, model: base.model, items: [{ type: 'reasoning', encrypted_content: 'owned-fixture-not-a-secret' }, { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'prior' }] }] } }], tools });
|
||||
cases.push({ name: 'mixed-gpt-protocol-pool', config: { ...base, modelRouting: { members: [{ ...base, id: 'owned-chat', protocol: 'chat-completions', streaming: true }, { ...base, id: 'owned-responses', protocol: 'responses', streaming: true }] } }, messages: history, tools });
|
||||
|
||||
const comparisons = [];
|
||||
for (const ref of ['410b3478', 'b832982d']) {
|
||||
const directory = path.join(root, 'baseline', ref), bindings = [];
|
||||
for (const file of [...modules, ...(ref === 'b832982d' ? ['src/shared/contracts/model-identity.mjs'] : [])]) {
|
||||
const bytes = execFileSync('git', ['show', ref + ':' + file]);
|
||||
const target = path.join(directory, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, bytes, { flag: 'wx' });
|
||||
bindings.push({ path: file, beforeSha256: hash(bytes), currentSha256: hash(fs.readFileSync(file)) });
|
||||
}
|
||||
const old = await import(pathToFileURL(path.join(directory, modules[0])).href);
|
||||
const results = [];
|
||||
for (const item of cases) {
|
||||
const before = old.completionBody(item.config, item.messages, item.tools), after = current.completionBody(item.config, item.messages, item.tools);
|
||||
assert.equal(JSON.stringify(after), JSON.stringify(before), ref + '/' + item.name + ': request bytes changed');
|
||||
assert.deepEqual(current.requestMetrics(after), old.requestMetrics(before), ref + '/' + item.name + ': budget/framing changed');
|
||||
if (item.config.modelRouting) for (const member of item.config.modelRouting.members) assert.deepEqual(current.actualRequest(after, member), old.actualRequest(before, member));
|
||||
results.push({ name: item.name, equalRequestBytes: true, equalMetrics: true, sha256: hash(JSON.stringify(after)) });
|
||||
}
|
||||
comparisons.push({ ref, bindings, cases: results });
|
||||
}
|
||||
const oldIdentity = await import(pathToFileURL(path.join(root, 'baseline/b832982d/src/shared/contracts/model-identity.mjs')).href);
|
||||
const identities = [];
|
||||
for (const protocol of ['chat-completions', 'responses']) for (const settings of [{}, { modelIdentityPolicy: 'record' }, { modelIdentityPolicy: 'require-match' }]) for (const models of [[], ['gpt-6.1-sol'], ['other-model'], ['gpt-6.1-sol', 'other-model']]) {
|
||||
const before = oldIdentity.modelIdentityObserver(base.model, settings), after = currentIdentity.modelIdentityObserver(base.model, settings);
|
||||
for (const model of models) { const event = protocol === 'responses' ? { type: 'response.created', response: { model } } : { model }; before.observe(event); after.observe(event); }
|
||||
assert.deepEqual(after.snapshot(true), before.snapshot(true));
|
||||
identities.push({ protocol, configuredPolicy: settings.modelIdentityPolicy ?? 'default', reportedModels: models, result: after.snapshot(true) });
|
||||
}
|
||||
assert.equal(currentIdentity.modelIdentityObserver(base.model).snapshot(true).policy, 'record');
|
||||
const result = { passed: true, comparisons, identities, requestCasesPerBaseline: cases.length, baselineRequestComparisons: comparisons.length * cases.length, identityComparisons: identities.length, realModelRequests: 0, productCodeModified: false, scope: 'Execute actual pre-I/pre-M and current pure request modules using owned fixtures. Not a provider inference or model-weights test.' };
|
||||
fs.writeFileSync(path.join(root, 'gpt-compatibility.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
|
||||
console.log(JSON.stringify({ passed: true, baselineRequestComparisons: result.baselineRequestComparisons, identityComparisons: identities.length, realModelRequests: 0 }));
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
import { completionBody } from '../src/shared/contracts/model-request.mjs';
|
||||
import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs';
|
||||
|
||||
// One local configuration correction after the user's GPT-group confirmation.
|
||||
// No key field, credential endpoint, provider inference, retry or process restart.
|
||||
const origin = 'http://127.0.0.1:4318';
|
||||
const connectionId = '09b0293b-faad-45c3-832d-7c8b615813aa';
|
||||
const sessionId = 'f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76';
|
||||
const root = '.qa/route-n';
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const save = (name, value) => fs.writeFileSync(root + '/' + name, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 5000 } });
|
||||
const calls = [];
|
||||
try {
|
||||
const request = async (route, { token, body } = {}) => {
|
||||
const method = body === undefined ? 'GET' : 'POST';
|
||||
const response = await fetch(origin + route, { dispatcher, method, redirect: 'error', signal: AbortSignal.timeout(15000), headers: { ...(token ? { 'X-Workbench-Token': token } : {}), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
calls.push({ method, route, status: response.status });
|
||||
if (!response.ok) throw new Error('Local API rejected: ' + response.status + ' ' + route);
|
||||
return response.json();
|
||||
};
|
||||
const bootBefore = await request('/api/bootstrap');
|
||||
assert.equal(bootBefore.version, '1.24.4');
|
||||
assert.equal(bootBefore.sessions.filter(s => ['running', 'stopping', 'awaiting_approval'].includes(s.status)).length, 0);
|
||||
const token = bootBefore.token;
|
||||
const [centerBefore, exportBefore] = await Promise.all([
|
||||
request('/api/model-center', { token }), request('/api/sessions/' + sessionId + '/export', { token }),
|
||||
]);
|
||||
const before = centerBefore.connections.find(c => c.id === connectionId);
|
||||
assert.ok(before?.hasKey); assert.equal(before.revision, 9); assert.equal(before.credentialRevision, 2);
|
||||
assert.equal(before.model, 'claude-opus-5-5'); assert.equal(before.protocol, 'anthropic-messages');
|
||||
assert.deepEqual(before.nativeParameters, {}); assert.deepEqual(before.modelIdentityAliases, []);
|
||||
const kept = ['id', 'name', 'enabled', 'requiresKey', 'contextLimit', 'maxOutputTokens', 'concurrency', 'streaming', 'capabilityDeclarations'];
|
||||
const input = { ...Object.fromEntries(kept.map(field => [field, before[field]])), revision: before.revision,
|
||||
brand: 'GPT 兼容代理', protocol: 'responses', baseUrl: 'https://api.apikey.fan/v1', model: 'gpt-6.1-sol',
|
||||
nativeParameters: {}, outputTokenField: 'max_output_tokens', modelIdentityPolicy: 'record', modelIdentityAliases: [], modelIdentityAliasSource: '' };
|
||||
assert.equal(Object.hasOwn(input, 'apiKey'), false); assert.equal(Object.hasOwn(input, 'persistKey'), false);
|
||||
const preview = completionBody({ ...input, maxOutputTokens: 256 }, [{ role: 'user', content: 'Owned offline configuration preview; do not send.' }], []);
|
||||
assert.equal(preview.model, 'gpt-6.1-sol'); assert.equal(preview.max_output_tokens, 256); assert.equal(preview.messages, undefined);
|
||||
assert.equal(modelRequestUrl(input), 'https://api.apikey.fan/v1/responses');
|
||||
const beforeProof = { observedAt: new Date().toISOString(), connection: before, correction: input, offlineRequestPreview: preview,
|
||||
fingerprints: { attempts: hash(centerBefore.attempts), otherConnections: hash(centerBefore.connections.filter(c => c.id !== connectionId)), pools: hash(centerBefore.pools), selected: hash(centerBefore.selected), config: hash(bootBefore.config), projects: hash(bootBefore.projects), visibleSessions: hash(bootBefore.sessions), originalMExport: hash(exportBefore) },
|
||||
eventCursor: bootBefore.eventCursor, modelRegistryRevision: centerBefore.revision, attempts: centerBefore.attempts.length, unarchivedSessions: bootBefore.sessions.length,
|
||||
userConfirmedGptGroup: true, realModelRequests: 0, credentialValuesReadOrSaved: false };
|
||||
save('correction-before.json', beforeProof);
|
||||
const afterConnection = await request('/api/model-center/connections', { token, body: input });
|
||||
save('correction-response.json', afterConnection);
|
||||
const [bootAfter, centerAfter, exportAfter] = await Promise.all([
|
||||
request('/api/bootstrap'), request('/api/model-center', { token }), request('/api/sessions/' + sessionId + '/export', { token }),
|
||||
]);
|
||||
const after = centerAfter.connections.find(c => c.id === connectionId);
|
||||
assert.equal(after.revision, before.revision + 1); assert.equal(after.credentialRevision, before.credentialRevision); assert.equal(after.hasKey, true);
|
||||
for (const field of kept) assert.deepEqual(after[field], before[field], field);
|
||||
for (const field of ['brand', 'protocol', 'baseUrl', 'model', 'nativeParameters', 'outputTokenField', 'modelIdentityPolicy', 'modelIdentityAliases', 'modelIdentityAliasSource']) assert.deepEqual(after[field], input[field], field);
|
||||
assert.equal(after.messagesAuth, undefined); assert.equal(after.status, 'configured'); assert.equal(after.health.state, 'unverified');
|
||||
assert.equal(centerAfter.revision, centerBefore.revision + 1); assert.equal(bootAfter.eventCursor, bootBefore.eventCursor);
|
||||
assert.equal(hash(centerAfter.attempts), beforeProof.fingerprints.attempts);
|
||||
assert.equal(hash(centerAfter.connections.filter(c => c.id !== connectionId)), beforeProof.fingerprints.otherConnections);
|
||||
assert.equal(hash(centerAfter.pools), beforeProof.fingerprints.pools); assert.equal(hash(centerAfter.selected), beforeProof.fingerprints.selected);
|
||||
assert.equal(hash(bootAfter.config), beforeProof.fingerprints.config); assert.equal(hash(bootAfter.projects), beforeProof.fingerprints.projects);
|
||||
assert.equal(hash(bootAfter.sessions), beforeProof.fingerprints.visibleSessions); assert.equal(hash(exportAfter), beforeProof.fingerprints.originalMExport);
|
||||
const result = { passed: true, observedAt: new Date().toISOString(), version: bootAfter.version, connection: after, requestUrl: modelRequestUrl(after),
|
||||
changed: ['brand', 'protocol', 'baseUrl', 'model', 'outputTokenField', 'modelIdentityPolicy', 'messagesAuth removed', 'connection/model-registry revision and updatedAt'],
|
||||
retained: { originalCredentialRevision: after.credentialRevision, hasKey: true, otherConnections: 'exact', defaultPool: 'exact', defaultSelection: 'exact', globalConfig: 'exact', all202Attempts: 'exact', originalMExport: 'exact', projectList: 'exact', unarchivedSessionList: 'exact', eventCursor: 'exact', limitsAndCapabilityDeclarations: 'exact' },
|
||||
unarchivedSessions: bootAfter.sessions.length, attempts: centerAfter.attempts.length, requests: calls, realModelRequests: 0,
|
||||
automaticRetry: false, credentialValuesReadOrSaved: false, localAuthorizationTokenSaved: false,
|
||||
scope: 'Configuration corrected using confirmed GPT group and public Responses contract. Connectivity is unverified; no model inference or full-database/artifact re-audit asserted. Old M/J/H/E runs were not resumed or rewritten.' };
|
||||
save('correction-result.json', result);
|
||||
console.log(JSON.stringify({ passed: result.passed, version: result.version, model: after.model, protocol: after.protocol, requestUrl: result.requestUrl, revision: after.revision, credentialRevision: after.credentialRevision, realModelRequests: 0, retained: result.retained }));
|
||||
} finally { await dispatcher.close(); }
|
||||
@@ -0,0 +1,75 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
import { completionBody } from '../src/shared/contracts/model-request.mjs';
|
||||
import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs';
|
||||
|
||||
// One local configuration correction after the user's GPT-group confirmation.
|
||||
// No key field, credential endpoint, provider inference, retry or process restart.
|
||||
const origin = 'http://127.0.0.1:4318';
|
||||
const connectionId = '09b0293b-faad-45c3-832d-7c8b615813aa';
|
||||
const sessionId = 'f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76';
|
||||
const root = '.qa/route-n';
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const save = (name, value) => fs.writeFileSync(root + '/' + name, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 5000 } });
|
||||
const calls = [];
|
||||
try {
|
||||
const request = async (route, { token, body } = {}) => {
|
||||
const method = body === undefined ? 'GET' : 'POST';
|
||||
const response = await fetch(origin + route, { dispatcher, method, redirect: 'error', signal: AbortSignal.timeout(15000), headers: { ...(token ? { 'X-Workbench-Token': token } : {}), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
calls.push({ method, route, status: response.status });
|
||||
if (!response.ok) throw new Error('Local API rejected: ' + response.status + ' ' + route);
|
||||
return response.json();
|
||||
};
|
||||
const bootBefore = await request('/api/bootstrap');
|
||||
assert.equal(bootBefore.version, '1.24.4');
|
||||
assert.equal(bootBefore.sessions.filter(s => ['running', 'stopping', 'awaiting_approval'].includes(s.status)).length, 0);
|
||||
const token = bootBefore.token;
|
||||
const [centerBefore, exportBefore] = await Promise.all([
|
||||
request('/api/model-center', { token }), request('/api/sessions/' + sessionId + '/export', { token }),
|
||||
]);
|
||||
const before = centerBefore.connections.find(c => c.id === connectionId);
|
||||
assert.ok(before?.hasKey); assert.equal(before.revision, 10); assert.equal(before.credentialRevision, 2);
|
||||
assert.equal(before.enabled, false, 'Preserve the external decision to disable this connection.');
|
||||
assert.equal(before.model, 'claude-opus-5-5'); assert.equal(before.protocol, 'anthropic-messages');
|
||||
assert.deepEqual(before.nativeParameters, {}); assert.deepEqual(before.modelIdentityAliases, []);
|
||||
const kept = ['id', 'name', 'enabled', 'requiresKey', 'contextLimit', 'maxOutputTokens', 'concurrency', 'streaming', 'capabilityDeclarations'];
|
||||
const input = { ...Object.fromEntries(kept.map(field => [field, before[field]])), revision: before.revision,
|
||||
brand: 'GPT 兼容代理', protocol: 'responses', baseUrl: 'https://api.apikey.fan/v1', model: 'gpt-6.1-sol',
|
||||
nativeParameters: {}, outputTokenField: 'max_output_tokens', modelIdentityPolicy: 'record', modelIdentityAliases: [], modelIdentityAliasSource: '' };
|
||||
assert.equal(Object.hasOwn(input, 'apiKey'), false); assert.equal(Object.hasOwn(input, 'persistKey'), false);
|
||||
const preview = completionBody({ ...input, maxOutputTokens: 256 }, [{ role: 'user', content: 'Owned offline configuration preview; do not send.' }], []);
|
||||
assert.equal(preview.model, 'gpt-6.1-sol'); assert.equal(preview.max_output_tokens, 256); assert.equal(preview.messages, undefined);
|
||||
assert.equal(modelRequestUrl(input), 'https://api.apikey.fan/v1/responses');
|
||||
const beforeProof = { observedAt: new Date().toISOString(), connection: before, correction: input, offlineRequestPreview: preview,
|
||||
fingerprints: { attempts: hash(centerBefore.attempts), otherConnections: hash(centerBefore.connections.filter(c => c.id !== connectionId)), pools: hash(centerBefore.pools), selected: hash(centerBefore.selected), config: hash(bootBefore.config), projects: hash(bootBefore.projects), visibleSessions: hash(bootBefore.sessions), originalMExport: hash(exportBefore) },
|
||||
eventCursor: bootBefore.eventCursor, modelRegistryRevision: centerBefore.revision, attempts: centerBefore.attempts.length, unarchivedSessions: bootBefore.sessions.length,
|
||||
userConfirmedGptGroup: true, realModelRequests: 0, credentialValuesReadOrSaved: false };
|
||||
save('correction-before.json', beforeProof);
|
||||
const afterConnection = await request('/api/model-center/connections', { token, body: input });
|
||||
save('correction-response.json', afterConnection);
|
||||
const [bootAfter, centerAfter, exportAfter] = await Promise.all([
|
||||
request('/api/bootstrap'), request('/api/model-center', { token }), request('/api/sessions/' + sessionId + '/export', { token }),
|
||||
]);
|
||||
const after = centerAfter.connections.find(c => c.id === connectionId);
|
||||
assert.equal(after.revision, before.revision + 1); assert.equal(after.credentialRevision, before.credentialRevision); assert.equal(after.hasKey, true);
|
||||
for (const field of kept) assert.deepEqual(after[field], before[field], field);
|
||||
for (const field of ['brand', 'protocol', 'baseUrl', 'model', 'nativeParameters', 'outputTokenField', 'modelIdentityPolicy', 'modelIdentityAliases', 'modelIdentityAliasSource']) assert.deepEqual(after[field], input[field], field);
|
||||
assert.equal(after.messagesAuth, undefined); assert.equal(after.status, 'disabled'); assert.equal(after.health.state, 'unverified');
|
||||
assert.equal(centerAfter.revision, centerBefore.revision + 1); assert.equal(bootAfter.eventCursor, bootBefore.eventCursor);
|
||||
assert.equal(hash(centerAfter.attempts), beforeProof.fingerprints.attempts);
|
||||
assert.equal(hash(centerAfter.connections.filter(c => c.id !== connectionId)), beforeProof.fingerprints.otherConnections);
|
||||
assert.equal(hash(centerAfter.pools), beforeProof.fingerprints.pools); assert.equal(hash(centerAfter.selected), beforeProof.fingerprints.selected);
|
||||
assert.equal(hash(bootAfter.config), beforeProof.fingerprints.config); assert.equal(hash(bootAfter.projects), beforeProof.fingerprints.projects);
|
||||
assert.equal(hash(bootAfter.sessions), beforeProof.fingerprints.visibleSessions); assert.equal(hash(exportAfter), beforeProof.fingerprints.originalMExport);
|
||||
const result = { passed: true, observedAt: new Date().toISOString(), version: bootAfter.version, connection: after, requestUrl: modelRequestUrl(after),
|
||||
changed: ['brand', 'protocol', 'baseUrl', 'model', 'outputTokenField', 'modelIdentityPolicy', 'messagesAuth removed', 'connection/model-registry revision and updatedAt'],
|
||||
retained: { originalCredentialRevision: after.credentialRevision, hasKey: true, disabledState: 'exact', otherConnections: 'exact', defaultPool: 'exact', defaultSelection: 'exact', globalConfig: 'exact', last100VisibleAttempts: 'exact', originalMExport: 'exact', projectList: 'exact', unarchivedSessionList: 'exact', eventCursor: 'exact', limitsAndCapabilityDeclarations: 'exact' },
|
||||
unarchivedSessions: bootAfter.sessions.length, attempts: centerAfter.attempts.length, requests: calls, realModelRequests: 0,
|
||||
automaticRetry: false, credentialValuesReadOrSaved: false, localAuthorizationTokenSaved: false,
|
||||
scope: 'Configuration corrected using confirmed GPT group and public Responses contract. Connectivity is unverified; no model inference or full-database/artifact re-audit asserted. Old M/J/H/E runs were not resumed or rewritten.' };
|
||||
save('correction-result.json', result);
|
||||
console.log(JSON.stringify({ passed: result.passed, version: result.version, model: after.model, protocol: after.protocol, requestUrl: result.requestUrl, revision: after.revision, credentialRevision: after.credentialRevision, realModelRequests: 0, retained: result.retained }));
|
||||
} finally { await dispatcher.close(); }
|
||||
@@ -0,0 +1,32 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
|
||||
const root = path.resolve('.qa/route-n/public');
|
||||
const commit = JSON.parse(fs.readFileSync(path.join(root, 'upstream-commit.json'), 'utf8')).sha;
|
||||
const tree = JSON.parse(fs.readFileSync(path.join(root, 'upstream-tree.json'), 'utf8'));
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 10000 } });
|
||||
const receipts = [], errors = [];
|
||||
const sourceFiles = ['backend/internal/service/openai_messages_dispatch.go', 'backend/internal/server/routes/model_plaza.go', 'backend/internal/handler/model_plaza_handler.go'];
|
||||
try {
|
||||
const results = await Promise.allSettled(sourceFiles.map(async file => {
|
||||
const entry = tree.tree.find(f => f.path === file && f.type === 'blob');
|
||||
if (!entry) throw new Error('Not in pinned tree: ' + file);
|
||||
const url = 'https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/' + entry.sha;
|
||||
const response = await fetch(url, { dispatcher, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { 'User-Agent': 'AgentWorkbench-public-route-investigation', Accept: 'application/vnd.github+json' } });
|
||||
if (!response.ok) throw new Error('Public blob GET: ' + response.status);
|
||||
const payload = await response.json(); if (payload.encoding !== 'base64') throw new Error('Unexpected encoding');
|
||||
const bytes = Buffer.from(payload.content, 'base64');
|
||||
const blob = createHash('sha1').update(Buffer.from('blob ' + bytes.length + '\0')).update(bytes).digest('hex');
|
||||
if (blob !== entry.sha || bytes.length !== entry.size) throw new Error('Source binding failed');
|
||||
const target = path.join(root, 'source', file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, bytes, { flag: 'wx' });
|
||||
const receipt = { path: file, url, status: response.status, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), gitBlob: blob, expectedGitBlob: entry.sha, treeMatched: true, authentication: 'none', capturedAt: new Date().toISOString() };
|
||||
receipts.push(receipt); console.log(JSON.stringify(receipt));
|
||||
}));
|
||||
results.forEach((result, index) => { if (result.status === 'rejected') { const error = { path: sourceFiles[index], message: result.reason.message }; errors.push(error); console.log(JSON.stringify(error)); } });
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(root, 'followup-receipts.json'), JSON.stringify({ upstreamCommit: commit, realModelRequests: 0, receipts, errors }, null, 2) + '\n', { flag: 'wx' });
|
||||
await dispatcher.close();
|
||||
}
|
||||
if (errors.length) process.exitCode = 1;
|
||||
@@ -0,0 +1,30 @@
|
||||
import fs from 'node:fs';
|
||||
import { Agent, fetch } from 'undici';
|
||||
const origin = 'http://127.0.0.1:4318';
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 5000 } });
|
||||
const requests = [];
|
||||
try {
|
||||
const get = async (route, token) => {
|
||||
const response = await fetch(origin + route, { method: 'GET', dispatcher, redirect: 'error', signal: AbortSignal.timeout(10000), headers: token ? { 'X-Workbench-Token': token } : {} });
|
||||
requests.push({ method: 'GET', route, status: response.status });
|
||||
if (!response.ok) throw new Error('Local read failed: ' + response.status);
|
||||
return response.json();
|
||||
};
|
||||
const bootstrap = await get('/api/bootstrap');
|
||||
const center = await get('/api/model-center', bootstrap.token);
|
||||
const fields = (value, names) => Object.fromEntries(names.filter(n => value[n] !== undefined).map(n => [n, value[n]]));
|
||||
const result = {
|
||||
observedAt: new Date().toISOString(), version: bootstrap.version, runtimeRoot: bootstrap.runtimeRoot,
|
||||
modelSelection: bootstrap.modelSelection, selected: center.selected,
|
||||
defaultConfig: fields(bootstrap.config, ['mode', 'protocol', 'model', 'baseUrl']),
|
||||
connections: center.connections.map(c => fields(c, ['id', 'name', 'protocol', 'model', 'baseUrl', 'messagesAuth', 'revision', 'credentialRevision', 'hasKey'])),
|
||||
pools: center.pools.map(p => fields(p, ['id', 'name', 'strategy', 'members', 'maxAttempts'])),
|
||||
projects: bootstrap.projects.length, sessions: bootstrap.sessions.length,
|
||||
activeSessions: bootstrap.sessions.filter(s => ['running', 'stopping', 'awaiting_approval'].includes(s.status)).length,
|
||||
requests, realModelRequests: 0, remoteCredentialRequests: 0,
|
||||
credentialValuesReadOrSaved: false, localAuthorizationTokenSaved: false,
|
||||
scope: 'Current public routing metadata only; no POST, credential endpoint, inference, restart, or historical process environment read.',
|
||||
};
|
||||
fs.writeFileSync('.qa/route-n/local-state.json', JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
|
||||
console.log(JSON.stringify(result));
|
||||
} finally { await dispatcher.close(); }
|
||||
@@ -0,0 +1,37 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
|
||||
const root = path.resolve('.qa/route-n/public');
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 10000 } });
|
||||
const sha = b => createHash('sha256').update(b).digest('hex');
|
||||
const receipts = [];
|
||||
async function capture(name, url) {
|
||||
const response = await fetch(url, { dispatcher, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { 'User-Agent': 'AgentWorkbench-public-route-investigation', Accept: 'application/json,text/html,text/plain' } });
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const file = path.join(root, name); fs.writeFileSync(file, bytes, { flag: 'wx' });
|
||||
const receipt = { name, url, finalUrl: response.url, status: response.status, bytes: bytes.length, sha256: sha(bytes), capturedAt: new Date().toISOString(), authentication: 'none', environmentProxy: false };
|
||||
receipts.push(receipt); console.log(JSON.stringify(receipt));
|
||||
if (!response.ok) throw new Error('Public GET failed: ' + response.status + ' ' + url);
|
||||
return bytes;
|
||||
}
|
||||
try {
|
||||
const results = await Promise.allSettled([
|
||||
capture('vendor-home.html', 'https://apikey.fan/'),
|
||||
capture('upstream-commit.json', 'https://api.github.com/repos/Wei-Shaw/sub2api/commits/main'),
|
||||
]);
|
||||
for (const result of results) if (result.status === 'rejected') console.log(JSON.stringify({ error: result.reason.message }));
|
||||
const commitResult = results[1];
|
||||
if (commitResult.status === 'fulfilled') {
|
||||
const commit = JSON.parse(commitResult.value);
|
||||
const treeBytes = await capture('upstream-tree.json', 'https://api.github.com/repos/Wei-Shaw/sub2api/git/trees/' + commit.commit.tree.sha + '?recursive=1');
|
||||
const tree = JSON.parse(treeBytes);
|
||||
const candidates = tree.tree.filter(f => f.type === 'blob' && /backend\/.*(?:gateway|router|conversion|compat|model_mapping|model_resolver|group).*(?:\.go)$/.test(f.path)).map(f => f.path);
|
||||
console.log(JSON.stringify({ commit: commit.sha, commitTime: commit.commit.committer.date, tree: commit.commit.tree.sha, truncated: tree.truncated, candidates }));
|
||||
}
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(root, 'receipts.json'), JSON.stringify({ realModelRequests: 0, publicGets: receipts }, null, 2) + '\n', { flag: 'wx' });
|
||||
await dispatcher.close();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
const listen = server => new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve('http://127.0.0.1:' + server.address().port)));
|
||||
const close = server => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); });
|
||||
const results = [];
|
||||
for (const protocol of ['chat-completions', 'responses']) {
|
||||
let originRequests = 0, targetRequests = 0;
|
||||
const target = http.createServer((req, res) => { targetRequests++; req.resume(); res.end('{}'); });
|
||||
const targetUrl = await listen(target);
|
||||
const origin = http.createServer((req, res) => { originRequests++; req.resume(); res.writeHead(307, { Location: targetUrl + '/destination' }); res.end(); });
|
||||
const originUrl = await listen(origin);
|
||||
const provider = new Provider(); provider.setKey('owned-local-fixture-only');
|
||||
try {
|
||||
let diagnostic;
|
||||
await assert.rejects(provider.complete({ mode: 'compatible', protocol, baseUrl: originUrl + '/v1', model: 'owned-gpt-fixture', maxOutputTokens: 256 }, [{ role: 'user', content: 'Owned redirect audit; never send to a model.' }], null, undefined, undefined, null, [], { attempts: 1 }), error => { diagnostic = error.diagnostic; return !!diagnostic; });
|
||||
assert.equal(originRequests, 1); assert.equal(targetRequests, 0); assert.equal(provider.lastRequest.redirectMode, 'manual');
|
||||
assert.equal(provider.lastRequest.requestUrl, originUrl + '/v1/' + (protocol === 'responses' ? 'responses' : 'chat/completions'));
|
||||
results.push({ protocol, passed: true, originRequests, targetRequests, responseStatus: 307, redirectMode: provider.lastRequest.redirectMode, requestUrl: provider.lastRequest.requestUrl, diagnosticKind: diagnostic.kind, realModelRequests: 0, credential: 'owned fixture only' });
|
||||
} finally { await provider.abortRequests(); await Promise.all([close(origin), close(target)]); }
|
||||
}
|
||||
fs.writeFileSync('.qa/route-n/gpt-redirect-audit.json', JSON.stringify({ passed: true, results, realModelRequests: 0, scope: 'Observed cross-protocol compatibility change: redirects require a correct final endpoint; no automatic POST replay or credential forwarding.' }, null, 2) + '\n', { flag: 'wx' });
|
||||
console.log(JSON.stringify({ passed: true, cases: results.length, realModelRequests: 0, originRequests: results.map(r => r.originRequests), targetRequests: results.map(r => r.targetRequests) }));
|
||||
@@ -0,0 +1,102 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// Seals existing files only. Never executes a driver or contacts any service.
|
||||
const root = process.cwd();
|
||||
const directory = path.join(root, 'docs/routing-audit-n-evidence');
|
||||
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const readJson = async relative => JSON.parse(await fs.readFile(path.join(root, relative), 'utf8'));
|
||||
const write = async (relative, bytes) => {
|
||||
const target = path.join(directory, relative);
|
||||
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||
await fs.writeFile(target, bytes, { flag: 'wx' });
|
||||
};
|
||||
const writeJson = (relative, value) => write(relative, `${JSON.stringify(value, null, 2)}\n`);
|
||||
const copy = async (from, to) => write(to, await fs.readFile(path.join(root, from)));
|
||||
|
||||
await writeJson('user-confirmation.json', {
|
||||
sourceKind: 'direct user reply in this conversation',
|
||||
quote: '哈哈哈,是我的错,我把模型写错了,确实属于gpt分组的,确实是 gpt模型,抱歉,让你查了这么久。那你要把复查这个链路问题做的很多检修的内容要看看,别因为我的错误,把很多正确的,改成错的了。你认真的回查这个过程',
|
||||
interpretation: 'User confirms GPT group and incorrect Claude model label; review previous changes and correct the diagnosis. This does not independently authenticate the underlying model weights.',
|
||||
messageId: null, receivedAt: null, realModelRequests: 0,
|
||||
});
|
||||
for (const name of ['gpt-compatibility.json', 'gpt-redirect-audit.json', 'source-integrity.json', 'regression.tap']) {
|
||||
await copy(`.qa/route-n/${name}`, `results/${name}`);
|
||||
}
|
||||
for (const name of ['local-state.json', 'concurrent-observation.json', 'correction-before.json', 'correction-response.json', 'correction-result.json', 'correction-export-current.json']) {
|
||||
await copy(`.qa/route-n/${name}`, `configuration/${name}`);
|
||||
}
|
||||
const regressionBytes = await fs.readFile(path.join(root, '.qa/route-n/regression.tap'));
|
||||
const encoding = regressionBytes[0] === 0xff && regressionBytes[1] === 0xfe ? 'utf16le' : 'utf8';
|
||||
const regression = regressionBytes.toString(encoding);
|
||||
assert.match(regression, /^# pass 144\r?$/m);
|
||||
assert.match(regression, /^# fail 0\r?$/m);
|
||||
await writeJson('results/regression-summary.json', { passed: true, runner: 'node:test', encoding,
|
||||
tests: 144, pass: 144, fail: 0, realModelRequests: 0,
|
||||
testFiles: ['model-center', 'model-selection', 'model-identity', 'model-fidelity', 'model-protocols', 'model-stream', 'anthropic-messages', 'credential-vault', 'upgrade-model-center', 'delivery-progress', 'no-progress-integrity', 'read-budget', 'working-set'].map(name => `tests/${name}.test.mjs`),
|
||||
scope: 'Already completed owned-fixture regression; original log bytes retained, not a live-model or full-suite result.' });
|
||||
for (const name of ['check-source', 'compare-gpt', 'correct-connection-first', 'correct-connection', 'verify-correction', 'redirect-audit', 'local', 'public', 'source', 'source-api', 'followup', 'seal']) {
|
||||
await copy(`.qa/route-n-${name}.mjs`, `drivers/route-n-${name}.mjs.txt`);
|
||||
}
|
||||
async function copyTree(from, to) {
|
||||
for (const entry of await fs.readdir(path.join(root, from), { withFileTypes: true })) {
|
||||
if (entry.isDirectory()) await copyTree(`${from}/${entry.name}`, `${to}/${entry.name}`);
|
||||
else { assert.ok(entry.isFile()); await copy(`${from}/${entry.name}`, `${to}/${entry.name}`); }
|
||||
}
|
||||
}
|
||||
await copyTree('.qa/route-n/baseline', 'baseline');
|
||||
for (const name of ['receipts.json', 'source-receipts.json', 'source-api-receipts.json', 'followup-receipts.json', 'handler-receipt.json', 'plaza-receipt.json', 'vendor-home.html', 'vendor-model-plaza.json']) {
|
||||
await copy(`.qa/route-n/public/${name}`, `public/${name}`);
|
||||
}
|
||||
const receiptSets = await Promise.all(['source-receipts.json', 'source-api-receipts.json', 'followup-receipts.json'].map(name => readJson(`.qa/route-n/public/${name}`)));
|
||||
const receipts = [...receiptSets.flatMap(result => result.receipts), await readJson('.qa/route-n/public/handler-receipt.json')];
|
||||
const selectedPaths = ['backend/internal/server/routes/gateway.go', 'backend/internal/handler/openai_gateway_handler.go', 'backend/internal/service/openai_gateway_messages.go', 'backend/internal/service/openai_messages_dispatch.go', 'backend/internal/service/openai_model_mapping.go', 'backend/internal/service/group.go', 'backend/internal/domain/openai_messages_dispatch.go', 'backend/internal/pkg/apicompat/responses_to_anthropic.go'];
|
||||
const selected = [];
|
||||
for (const relative of selectedPaths) {
|
||||
const receipt = receipts.find(entry => entry.path === relative);
|
||||
assert.ok(receipt?.treeMatched, relative);
|
||||
const content = await fs.readFile(path.join(root, '.qa/route-n/public/source', relative));
|
||||
assert.equal(hash(content), receipt.sha256);
|
||||
const evidencePath = `public/source/${relative}.txt`;
|
||||
await write(evidencePath, content);
|
||||
selected.push({ ...receipt, evidencePath });
|
||||
}
|
||||
const commit = await readJson('.qa/route-n/public/upstream-commit.json');
|
||||
const tree = await readJson('.qa/route-n/public/upstream-tree.json');
|
||||
assert.equal(commit.sha, '4a4a83ee5ec86b19d3a2dd9b6471de5128963bec');
|
||||
assert.equal(commit.commit.tree.sha, tree.sha);
|
||||
for (const entry of selected) assert.equal(tree.tree.find(item => item.path === entry.path)?.sha, entry.expectedGitBlob);
|
||||
await writeJson('public/selected-sources.json', { repository: 'https://github.com/Wei-Shaw/sub2api', upstreamCommit: commit.sha,
|
||||
tree: tree.sha, files: selected,
|
||||
scope: 'Selected exact public source bytes, not product dependencies or authentication of the supplier production deployment.' });
|
||||
await writeJson('public/upstream-summary.json', { upstreamCommit: commit.sha, tree: tree.sha, treeTruncated: tree.truncated,
|
||||
originalsRetainedLocally: ['upstream-commit.json', 'upstream-tree.json'].map(name => `.qa/route-n/public/${name}`),
|
||||
selectedTreeEntries: selected.map(entry => tree.tree.find(item => item.path === entry.path)),
|
||||
note: 'Full original public API responses remain outside Git; their hashes and anonymous GET receipts are sealed in receipts.json.' });
|
||||
|
||||
const existingEvidenceBindings = [];
|
||||
for (const relative of ['docs/messages-m-evidence/manifest.json', 'docs/messages-m-evidence/release/product-freeze.json', 'docs/messages-m-evidence/live/export.json']) {
|
||||
existingEvidenceBindings.push({ path: relative, sha256: hash(await fs.readFile(path.join(root, relative))) });
|
||||
}
|
||||
assert.equal(existingEvidenceBindings[0].sha256, 'c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7');
|
||||
async function inventory(relative = '') {
|
||||
const results = [];
|
||||
for (const entry of await fs.readdir(path.join(directory, relative), { withFileTypes: true })) {
|
||||
const name = relative ? `${relative}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) results.push(...await inventory(name));
|
||||
else {
|
||||
assert.ok(entry.isFile());
|
||||
const content = await fs.readFile(path.join(directory, name));
|
||||
results.push({ path: name, bytes: content.length, sha256: hash(content) });
|
||||
}
|
||||
}
|
||||
return results.sort((a, b) => a.path.localeCompare(b.path, 'en'));
|
||||
}
|
||||
const files = await inventory();
|
||||
const manifest = { schemaVersion: 1, purpose: 'N: confirmed GPT configuration error, review and correction',
|
||||
createdAt: new Date().toISOString(), productVersion: '1.24.4', productCodeModified: false,
|
||||
realModelRequests: 0, configurationPOSTs: 1, files, bytes: files.reduce((sum, entry) => sum + entry.bytes, 0), existingEvidenceBindings };
|
||||
await writeJson('manifest.json', manifest);
|
||||
console.log(JSON.stringify({ sealedFiles: files.length, bytes: manifest.bytes, manifestSha256: hash(await fs.readFile(path.join(directory, 'manifest.json'))), realModelRequests: 0 }));
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
|
||||
const root = path.resolve('.qa/route-n/public');
|
||||
const commit = JSON.parse(fs.readFileSync(path.join(root, 'upstream-commit.json'), 'utf8')).sha;
|
||||
const tree = JSON.parse(fs.readFileSync(path.join(root, 'upstream-tree.json'), 'utf8'));
|
||||
const first = JSON.parse(fs.readFileSync(path.join(root, 'source-receipts.json'), 'utf8'));
|
||||
const wanted = [
|
||||
'backend/internal/server/routes/gateway.go',
|
||||
'backend/internal/service/openai_gateway_messages.go',
|
||||
'backend/internal/service/openai_gateway_messages_anthropic_native.go',
|
||||
'backend/internal/service/openai_gateway_messages_chat_fallback.go',
|
||||
'backend/internal/pkg/apicompat/anthropic_to_responses.go',
|
||||
'backend/internal/pkg/apicompat/responses_to_anthropic.go',
|
||||
'backend/internal/pkg/apicompat/responses_to_anthropic_request.go',
|
||||
'backend/internal/domain/openai_messages_dispatch.go',
|
||||
].filter(file => !first.receipts.some(r => r.path === file && r.treeMatched));
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 10000 } });
|
||||
const receipts = [];
|
||||
const errors = [];
|
||||
async function capture(file) {
|
||||
const entry = tree.tree.find(f => f.path === file && f.type === 'blob');
|
||||
if (!entry) throw new Error('Not in pinned tree: ' + file);
|
||||
const url = 'https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/' + entry.sha;
|
||||
const response = await fetch(url, { dispatcher, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { 'User-Agent': 'AgentWorkbench-public-route-investigation', Accept: 'application/vnd.github+json' } });
|
||||
if (!response.ok) throw new Error('Public blob GET: ' + response.status);
|
||||
const payload = await response.json();
|
||||
if (payload.encoding !== 'base64') throw new Error('Unexpected blob encoding');
|
||||
const bytes = Buffer.from(payload.content, 'base64');
|
||||
const blob = createHash('sha1').update(Buffer.from('blob ' + bytes.length + '\0')).update(bytes).digest('hex');
|
||||
const receipt = { path: file, url, status: response.status, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), gitBlob: blob, expectedGitBlob: entry.sha, treeBytes: entry.size, treeMatched: blob === entry.sha && bytes.length === entry.size, authentication: 'none', capturedAt: new Date().toISOString() };
|
||||
if (!receipt.treeMatched) throw new Error('Source binding failed');
|
||||
const target = path.join(root, 'source', file); fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, bytes, { flag: 'wx' }); receipts.push(receipt); console.log(JSON.stringify(receipt));
|
||||
}
|
||||
try {
|
||||
for (let at = 0; at < wanted.length; at += 3) {
|
||||
const batch = wanted.slice(at, at + 3);
|
||||
const results = await Promise.allSettled(batch.map(capture));
|
||||
results.forEach((result, index) => { if (result.status === 'rejected') { const error = { path: batch[index], message: result.reason.message }; errors.push(error); console.log(JSON.stringify(error)); } });
|
||||
}
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(root, 'source-api-receipts.json'), JSON.stringify({ upstreamCommit: commit, realModelRequests: 0, priorRawFetchFailures: 5, receipts, errors }, null, 2) + '\n', { flag: 'wx' });
|
||||
await dispatcher.close();
|
||||
}
|
||||
if (errors.length) process.exitCode = 1;
|
||||
@@ -0,0 +1,41 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
|
||||
const root = path.resolve('.qa/route-n/public');
|
||||
const commit = JSON.parse(fs.readFileSync(path.join(root, 'upstream-commit.json'), 'utf8')).sha;
|
||||
const tree = JSON.parse(fs.readFileSync(path.join(root, 'upstream-tree.json'), 'utf8'));
|
||||
const files = [
|
||||
'backend/internal/server/routes/gateway.go',
|
||||
'backend/internal/service/openai_model_mapping.go',
|
||||
'backend/internal/service/openai_gateway_messages.go',
|
||||
'backend/internal/service/openai_gateway_messages_anthropic_native.go',
|
||||
'backend/internal/service/openai_gateway_messages_chat_fallback.go',
|
||||
'backend/internal/service/group.go',
|
||||
'backend/internal/pkg/apicompat/anthropic_to_responses_response.go',
|
||||
'backend/internal/pkg/apicompat/anthropic_to_responses.go',
|
||||
];
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 10000 } });
|
||||
const receipts = [];
|
||||
try {
|
||||
const results = await Promise.allSettled(files.map(async file => {
|
||||
const entry = tree.tree.find(f => f.path === file && f.type === 'blob');
|
||||
if (!entry) throw new Error('Source file not in pinned tree: ' + file);
|
||||
const url = 'https://raw.githubusercontent.com/Wei-Shaw/sub2api/' + commit + '/' + file;
|
||||
const response = await fetch(url, { dispatcher, redirect: 'error', signal: AbortSignal.timeout(30000) });
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const target = path.join(root, 'source', file); fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, bytes, { flag: 'wx' });
|
||||
const blob = createHash('sha1').update(Buffer.from('blob ' + bytes.length + '\0')).update(bytes).digest('hex');
|
||||
const receipt = { path: file, url, status: response.status, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), gitBlob: blob, expectedGitBlob: entry.sha, treeBytes: entry.size, treeMatched: blob === entry.sha && bytes.length === entry.size, authentication: 'none', capturedAt: new Date().toISOString() };
|
||||
receipts.push(receipt);
|
||||
if (!response.ok || !receipt.treeMatched) throw new Error('Public source capture does not match pinned tree: ' + file);
|
||||
console.log(JSON.stringify(receipt));
|
||||
}));
|
||||
for (const result of results) if (result.status === 'rejected') console.log(JSON.stringify({ error: result.reason.message }));
|
||||
if (results.some(r => r.status === 'rejected')) process.exitCode = 1;
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(root, 'source-receipts.json'), JSON.stringify({ upstreamCommit: commit, realModelRequests: 0, receipts }, null, 2) + '\n', { flag: 'wx' });
|
||||
await dispatcher.close();
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Agent, fetch } from 'undici';
|
||||
import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs';
|
||||
|
||||
// Read-only follow-up. The correction POST already happened; never replay it.
|
||||
const root = '.qa/route-n', connectionId = '09b0293b-faad-45c3-832d-7c8b615813aa';
|
||||
const before = JSON.parse(fs.readFileSync(root + '/correction-before.json', 'utf8'));
|
||||
const saved = JSON.parse(fs.readFileSync(root + '/correction-response.json', 'utf8'));
|
||||
const originalM = JSON.parse(fs.readFileSync('docs/messages-m-evidence/live/export.json', 'utf8'));
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const save = (name, value) => fs.writeFileSync(root + '/' + name, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
|
||||
const dispatcher = new Agent({ connect: { autoSelectFamily: true, timeout: 5000 } });
|
||||
const calls = [];
|
||||
try {
|
||||
const get = async (route, token) => {
|
||||
const response = await fetch('http://127.0.0.1:4318' + route, { method: 'GET', dispatcher, redirect: 'error', signal: AbortSignal.timeout(10000), headers: token ? { 'X-Workbench-Token': token } : {} });
|
||||
calls.push({ method: 'GET', route, status: response.status }); assert.equal(response.status, 200); return response.json();
|
||||
};
|
||||
const boot = await get('/api/bootstrap');
|
||||
const [center, exported] = await Promise.all([get('/api/model-center', boot.token), get('/api/sessions/f7d1ec3d-aa41-4f4e-ab6d-f4df487b4d76/export', boot.token)]);
|
||||
const after = center.connections.find(c => c.id === connectionId);
|
||||
assert.deepEqual(after, saved); assert.equal(after.revision, 11); assert.equal(after.credentialRevision, 2); assert.equal(after.enabled, false);
|
||||
assert.equal(after.model, 'gpt-6.1-sol'); assert.equal(after.protocol, 'responses'); assert.equal(after.modelIdentityPolicy, 'record');
|
||||
assert.equal(modelRequestUrl(after), 'https://api.apikey.fan/v1/responses'); assert.equal(center.revision, before.modelRegistryRevision + 1);
|
||||
for (const [name, value] of Object.entries({ attempts: center.attempts, otherConnections: center.connections.filter(c => c.id !== connectionId), pools: center.pools, selected: center.selected,
|
||||
config: boot.config, projects: boot.projects, visibleSessions: boot.sessions })) assert.equal(hash(value), before.fingerprints[name], name);
|
||||
assert.equal(boot.eventCursor, before.eventCursor); assert.equal(boot.version, '1.24.4');
|
||||
const withoutGeneratedAt = value => { const result = structuredClone(value); delete result.exportedAt; return result; };
|
||||
assert.deepEqual(withoutGeneratedAt(exported), withoutGeneratedAt(originalM), 'All original M project/session/execution fields must still match the sealed M export.');
|
||||
// The first validator hashed exportedAt as if it were stored session data.
|
||||
// Match its exact fingerprint by changing ONLY that generated field within
|
||||
// the bounded one-second interval preceding the recorded before receipt.
|
||||
const template = structuredClone(exported), observed = Date.parse(before.observedAt); let matchedBeforeAt = null;
|
||||
for (let time = observed; time >= observed - 1000; time--) {
|
||||
template.exportedAt = new Date(time).toISOString();
|
||||
if (hash(template) === before.fingerprints.originalMExport) { matchedBeforeAt = template.exportedAt; break; }
|
||||
}
|
||||
assert.ok(matchedBeforeAt, 'The pre-correction export fingerprint must match every byte-level JSON field except its generated timestamp.');
|
||||
save('correction-export-current.json', exported);
|
||||
const result = { passed: true, observedAt: new Date().toISOString(), version: boot.version, connection: after, requestUrl: modelRequestUrl(after),
|
||||
changed: ['brand', 'protocol', 'baseUrl', 'model', 'outputTokenField', 'modelIdentityPolicy', 'messagesAuth removed', 'connection/model-registry revision and updatedAt'],
|
||||
retained: { originalCredentialRevision: 2, hasKey: after.hasKey, disabledState: 'exact', otherConnections: 'exact', defaultPool: 'exact', defaultSelection: 'exact', globalConfig: 'exact', last100VisibleAttempts: 'exact',
|
||||
originalMProjectSessionExecution: 'exact', originalMExportGeneratedAt: 'generated field only', projectList: 'exact', unarchivedSessionList: 'exact', eventCursor: 'exact', limitsAndCapabilityDeclarations: 'exact' },
|
||||
exportVerification: { matchedBeforeAt, currentExportedAt: exported.exportedAt, beforeFullFingerprint: before.fingerprints.originalMExport, normalizedFingerprint: hash(withoutGeneratedAt(exported)), sealedMNormalizedFingerprint: hash(withoutGeneratedAt(originalM)), permittedDifference: '/exportedAt only' },
|
||||
firstGuard: { expectedRevision: 9, observedRevision: 10, stoppedBeforePOST: true, externalChange: 'enabled true to false' },
|
||||
firstPostAudit: { failedBecause: 'Generated /exportedAt was hashed as stored session data', source: 'src/server/app.mjs:770', configurationPOSTWasNotReplayed: true },
|
||||
unarchivedSessions: boot.sessions.length, visibleAttempts: center.attempts.length, calls, realModelRequests: 0, totalConfigurationPOSTs: 1, credentialValuesReadOrSaved: false, localAuthorizationTokenSaved: false,
|
||||
scope: 'Confirmed GPT configuration corrected; disabled state and public metadata retained. No new inference, model-weights authentication, full-database/artifact re-audit or replay of old runs.' };
|
||||
save('correction-result.json', result);
|
||||
console.log(JSON.stringify({ passed: true, model: after.model, protocol: after.protocol, enabled: after.enabled, revision: after.revision, credentialRevision: after.credentialRevision, realModelRequests: 0, retained: result.retained, exportVerification: result.exportVerification }));
|
||||
} finally { await dispatcher.close(); }
|
||||
@@ -0,0 +1,286 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"purpose": "N: confirmed GPT configuration error, review and correction",
|
||||
"createdAt": "2026-11-03T12:41:38.872Z",
|
||||
"productVersion": "1.24.4",
|
||||
"productCodeModified": false,
|
||||
"realModelRequests": 0,
|
||||
"configurationPOSTs": 1,
|
||||
"files": [
|
||||
{
|
||||
"path": ".gitattributes",
|
||||
"bytes": 85,
|
||||
"sha256": "65c1ce84b19f5308051d3b65b9b1b14e234f63770723013b4be5171c872dcc2e"
|
||||
},
|
||||
{
|
||||
"path": "baseline/410b3478/src/shared/contracts/model-capabilities.mjs",
|
||||
"bytes": 2225,
|
||||
"sha256": "4d7afd6d273cd4a30a810a6939748126614e3a00fe5c357c5fb6e24c18c09ce4"
|
||||
},
|
||||
{
|
||||
"path": "baseline/410b3478/src/shared/contracts/model-request.mjs",
|
||||
"bytes": 7297,
|
||||
"sha256": "76d1efa21fc91bd09dbac368db8b4f79f9095663a186195eda260ec50ad29ab9"
|
||||
},
|
||||
{
|
||||
"path": "baseline/410b3478/src/shared/contracts/native-parameters.mjs",
|
||||
"bytes": 2440,
|
||||
"sha256": "d8e493018d2cf2c42049d1c173cda6af1be06fb3a85999c97cd25e92561b3b84"
|
||||
},
|
||||
{
|
||||
"path": "baseline/b832982d/src/shared/contracts/model-capabilities.mjs",
|
||||
"bytes": 2225,
|
||||
"sha256": "4d7afd6d273cd4a30a810a6939748126614e3a00fe5c357c5fb6e24c18c09ce4"
|
||||
},
|
||||
{
|
||||
"path": "baseline/b832982d/src/shared/contracts/model-identity.mjs",
|
||||
"bytes": 3547,
|
||||
"sha256": "c40254c5ba31aef0abe4873faeec14127e22853fbc9f482c2b7b2b870cc379fb"
|
||||
},
|
||||
{
|
||||
"path": "baseline/b832982d/src/shared/contracts/model-request.mjs",
|
||||
"bytes": 7297,
|
||||
"sha256": "76d1efa21fc91bd09dbac368db8b4f79f9095663a186195eda260ec50ad29ab9"
|
||||
},
|
||||
{
|
||||
"path": "baseline/b832982d/src/shared/contracts/native-parameters.mjs",
|
||||
"bytes": 2440,
|
||||
"sha256": "d8e493018d2cf2c42049d1c173cda6af1be06fb3a85999c97cd25e92561b3b84"
|
||||
},
|
||||
{
|
||||
"path": "configuration/concurrent-observation.json",
|
||||
"bytes": 2076,
|
||||
"sha256": "392ef67884a0a9d70029226bb850458428d49c28323f9cffeff68dcc7c57eef5"
|
||||
},
|
||||
{
|
||||
"path": "configuration/correction-before.json",
|
||||
"bytes": 3734,
|
||||
"sha256": "104ab1c70b2bda63f54755d86450d9a8852812eb7cdf745bb5e09d6c048c21a5"
|
||||
},
|
||||
{
|
||||
"path": "configuration/correction-export-current.json",
|
||||
"bytes": 29133,
|
||||
"sha256": "026b24c25c3649bd1f2ea7bd829749a310374a699551a2790a6339335cc688c3"
|
||||
},
|
||||
{
|
||||
"path": "configuration/correction-response.json",
|
||||
"bytes": 1485,
|
||||
"sha256": "5abed42e40685e5daed82362d830cd12fbc44d27292aa5e45dd3e00300316511"
|
||||
},
|
||||
{
|
||||
"path": "configuration/correction-result.json",
|
||||
"bytes": 4031,
|
||||
"sha256": "ac2feac8d7f17200d6bd19e2955330561853785b44d6693f7253c9da06c4ad97"
|
||||
},
|
||||
{
|
||||
"path": "configuration/local-state.json",
|
||||
"bytes": 2365,
|
||||
"sha256": "94ab70c94ca783223b2c99c6664f4b1faa3ff71c109baae8210b409833c54897"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-check-source.mjs.txt",
|
||||
"bytes": 2495,
|
||||
"sha256": "25770a38c1304e48efa3405c72149c2cd68e62abd879b74f656979ac4963e2ba"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-compare-gpt.mjs.txt",
|
||||
"bytes": 6498,
|
||||
"sha256": "3ce88e4413834f91a71749df16498198339b207dbbb0914c71aa24afb90ffd65"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-correct-connection-first.mjs.txt",
|
||||
"bytes": 7579,
|
||||
"sha256": "b66764c32e064fa801dae60072d0e8fccf062329706f52946105d87dca2fa24e"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-correct-connection.mjs.txt",
|
||||
"bytes": 7711,
|
||||
"sha256": "13d12e16ae70dd4d8ffba9456977166e7f5854dfea58301567dd62d7a29c006e"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-followup.mjs.txt",
|
||||
"bytes": 2649,
|
||||
"sha256": "e4f17c888c4d4fd0683cbe746c8449014e9618a71379a6db348a51b51cc69b69"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-local.mjs.txt",
|
||||
"bytes": 2095,
|
||||
"sha256": "bffc56961512a62b351e57112213bf1cb9ee6affa0b8bab2c8349d972d11401f"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-public.mjs.txt",
|
||||
"bytes": 2421,
|
||||
"sha256": "19a25bce021ca25d6378575eb014bed59bd518e029c20e150307e23ee24d023c"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-redirect-audit.mjs.txt",
|
||||
"bytes": 2481,
|
||||
"sha256": "d83257d77a16f11a62adea80965e3ff25e50bb1f423c9564fb51bde6de01fa5c"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-seal.mjs.txt",
|
||||
"bytes": 7822,
|
||||
"sha256": "daeaff27bac7e3676afa9555561cc0d96991a3bab1681d7cbbc7b412df866c56"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-source-api.mjs.txt",
|
||||
"bytes": 3326,
|
||||
"sha256": "2d1c405f0bf4ccee5796e53a93015038d0379f7197769aef578f1a5c80a0124d"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-source.mjs.txt",
|
||||
"bytes": 2695,
|
||||
"sha256": "517287baf4d4bad60630d7dc86fae8d2842c6b5e9022208a47383fe733b08d64"
|
||||
},
|
||||
{
|
||||
"path": "drivers/route-n-verify-correction.mjs.txt",
|
||||
"bytes": 5744,
|
||||
"sha256": "4e2bef17bcc194192152a4312243fdde0ff3476e3cd2336a1acb39714527742f"
|
||||
},
|
||||
{
|
||||
"path": "public/followup-receipts.json",
|
||||
"bytes": 1791,
|
||||
"sha256": "e8e6b7fcc593b9a7a615f812be9c32a65f13a71e37a07e2f4d06f0096bfded84"
|
||||
},
|
||||
{
|
||||
"path": "public/handler-receipt.json",
|
||||
"bytes": 535,
|
||||
"sha256": "c461067503fa25e5b06494185861ba07070a59130087ce3ec0cae2dffba8489f"
|
||||
},
|
||||
{
|
||||
"path": "public/plaza-receipt.json",
|
||||
"bytes": 263,
|
||||
"sha256": "e7d4583733a6d462e3bd053960a69a38bf4d53ddb96a0304300bb42bd1711fb2"
|
||||
},
|
||||
{
|
||||
"path": "public/receipts.json",
|
||||
"bytes": 1405,
|
||||
"sha256": "2d19ef81e9dd9996dde0c18bea8081dd0b7fbe01565f1c36f8f529664b021bf6"
|
||||
},
|
||||
{
|
||||
"path": "public/selected-sources.json",
|
||||
"bytes": 5750,
|
||||
"sha256": "ffa4b9eeb5e0aa1b9970bb624608286b293ead6f2dc11009d4640ec2bf45eb23"
|
||||
},
|
||||
{
|
||||
"path": "public/source-api-receipts.json",
|
||||
"bytes": 4871,
|
||||
"sha256": "f2b99acfaa9fb0087d9b9b3ef017dd579fb4b3121fbbef450f8168093b25130d"
|
||||
},
|
||||
{
|
||||
"path": "public/source-receipts.json",
|
||||
"bytes": 1990,
|
||||
"sha256": "7585a830b4b356a91cdd3d7ef65bdd6bff1e8ced926093d183489a1a927334a6"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/domain/openai_messages_dispatch.go.txt",
|
||||
"bytes": 494,
|
||||
"sha256": "c26623f1ae4c35a7ee9691feab637d1cc58860a62f5ef169e5721d8f775e2ab4"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/handler/openai_gateway_handler.go.txt",
|
||||
"bytes": 178238,
|
||||
"sha256": "3771bd42a673b562809b86df6848c9e1e14846e8fe388ea21f4e922de9f0879b"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt",
|
||||
"bytes": 24852,
|
||||
"sha256": "02f9cc5aa6f9cde9ff4477e5380db63ec58c10263cbf85149b1717e8f5474cdd"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/server/routes/gateway.go.txt",
|
||||
"bytes": 31276,
|
||||
"sha256": "8fd2ebf61aeb2e6b7b79976b0d44ab1b46178e803b225139f3401af123021be4"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/service/group.go.txt",
|
||||
"bytes": 18145,
|
||||
"sha256": "91d46705a0f361fcddcaf0949c977a8be0fc0e376669bc59ec60aecf8542b9a0"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/service/openai_gateway_messages.go.txt",
|
||||
"bytes": 54497,
|
||||
"sha256": "beedb4aad94c703b67971b06c3e72daaad630ea4331ff9dd9276d67529ac7d73"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/service/openai_messages_dispatch.go.txt",
|
||||
"bytes": 3756,
|
||||
"sha256": "8a99dbe433d0fd2c48d8496b076572f308691fc6eab1ce65423160859826292c"
|
||||
},
|
||||
{
|
||||
"path": "public/source/backend/internal/service/openai_model_mapping.go.txt",
|
||||
"bytes": 5364,
|
||||
"sha256": "e6fab13f0e7726052f918d60c21aa9247b399f9d8f508522840dc27bcd411834"
|
||||
},
|
||||
{
|
||||
"path": "public/upstream-summary.json",
|
||||
"bytes": 2958,
|
||||
"sha256": "dd62aa71719c0818a222f98e59c35edbea421a35379a4ae3d13de8af01635085"
|
||||
},
|
||||
{
|
||||
"path": "public/vendor-home.html",
|
||||
"bytes": 45934,
|
||||
"sha256": "5d268c6fe9a0398c74f2b55a9fe54d33b0bc957a3ec7faf59909dd1a5cc1ff7d"
|
||||
},
|
||||
{
|
||||
"path": "public/vendor-model-plaza.json",
|
||||
"bytes": 51,
|
||||
"sha256": "260ac9e933e7f57f7d3b449661017a51d6277c48f75cad21471ae4e0095fd835"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"bytes": 2862,
|
||||
"sha256": "88fafec651c9294de387abf0cd9f958e5eeafd1d12b00237dea66b62b0ffdd7f"
|
||||
},
|
||||
{
|
||||
"path": "results/gpt-compatibility.json",
|
||||
"bytes": 23770,
|
||||
"sha256": "616f7aaef6905d76a9384360739cdfc21831bc0669a64dbb127fff0510e12589"
|
||||
},
|
||||
{
|
||||
"path": "results/gpt-redirect-audit.json",
|
||||
"bytes": 927,
|
||||
"sha256": "3a75c264a5e2a4706f5c4c248558bbea43b934b8fe899fb2ae3d503d634d01ed"
|
||||
},
|
||||
{
|
||||
"path": "results/regression-summary.json",
|
||||
"bytes": 780,
|
||||
"sha256": "60da9500b98a090d0368bd53ec9b235f7abf37d2225ec6510946ebee520abb0c"
|
||||
},
|
||||
{
|
||||
"path": "results/regression.tap",
|
||||
"bytes": 38890,
|
||||
"sha256": "8af0b8f61260881f4bcf027e31ac0a54982228d66590d5b0970985e7dffc9ebd"
|
||||
},
|
||||
{
|
||||
"path": "results/source-integrity.json",
|
||||
"bytes": 68290,
|
||||
"sha256": "c2b6fab5701634ab60ea4d0bdc5d161d83e753576443dcd1320c47fe7e80713c"
|
||||
},
|
||||
{
|
||||
"path": "user-confirmation.json",
|
||||
"bytes": 649,
|
||||
"sha256": "7966cca213c1c4eef9efc3715a9b709a8d520aa6dca372d22401192df0de94b6"
|
||||
},
|
||||
{
|
||||
"path": "verify-offline.mjs",
|
||||
"bytes": 7982,
|
||||
"sha256": "8e7a5aa22e7da1a9d19ef10c6522cf3dbe53bd57bed8dab3afc11a656f425371"
|
||||
}
|
||||
],
|
||||
"bytes": 650216,
|
||||
"existingEvidenceBindings": [
|
||||
{
|
||||
"path": "docs/messages-m-evidence/manifest.json",
|
||||
"sha256": "c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7"
|
||||
},
|
||||
{
|
||||
"path": "docs/messages-m-evidence/release/product-freeze.json",
|
||||
"sha256": "ad49a4aeea61a2a3fe8232185653c3e053618a9605a8712eb8fc9548237e1e1b"
|
||||
},
|
||||
{
|
||||
"path": "docs/messages-m-evidence/live/export.json",
|
||||
"sha256": "14971c76bdcfc7edc5c2a1ba2ecb3bbc6794dccbd67e2642779221dabda3b112"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"upstreamCommit": "4a4a83ee5ec86b19d3a2dd9b6471de5128963bec",
|
||||
"realModelRequests": 0,
|
||||
"receipts": [
|
||||
{
|
||||
"path": "backend/internal/server/routes/model_plaza.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/51e1c1296cf10ddd2fc58abbf04b91b0cd3d73a2",
|
||||
"status": 200,
|
||||
"bytes": 984,
|
||||
"sha256": "f2b122ccece86e535293ee60c1aa2805c6c1879b05a77e685a36e8204c7dc2fb",
|
||||
"gitBlob": "51e1c1296cf10ddd2fc58abbf04b91b0cd3d73a2",
|
||||
"expectedGitBlob": "51e1c1296cf10ddd2fc58abbf04b91b0cd3d73a2",
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:18:54.071Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/handler/model_plaza_handler.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/6f3a905d816c3fc05ea3022ca38e7f4962959c0d",
|
||||
"status": 200,
|
||||
"bytes": 10661,
|
||||
"sha256": "63fb99572e18b5b56419f8762cd657d04d3468af704284a3b036ba6d18274189",
|
||||
"gitBlob": "6f3a905d816c3fc05ea3022ca38e7f4962959c0d",
|
||||
"expectedGitBlob": "6f3a905d816c3fc05ea3022ca38e7f4962959c0d",
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:18:54.084Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_messages_dispatch.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"status": 200,
|
||||
"bytes": 3756,
|
||||
"sha256": "8a99dbe433d0fd2c48d8496b076572f308691fc6eab1ce65423160859826292c",
|
||||
"gitBlob": "b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"expectedGitBlob": "b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:18:54.108Z"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"path": "backend/internal/handler/openai_gateway_handler.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"status": 200,
|
||||
"bytes": 178238,
|
||||
"gitBlob": "3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"expectedGitBlob": "3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"treeMatched": true,
|
||||
"sha256": "3771bd42a673b562809b86df6848c9e1e14846e8fe388ea21f4e922de9f0879b",
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:21:29.690Z",
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"url": "https://apikey.fan/api/v1/model-plaza",
|
||||
"status": 404,
|
||||
"bytes": 51,
|
||||
"sha256": "260ac9e933e7f57f7d3b449661017a51d6277c48f75cad21471ae4e0095fd835",
|
||||
"capturedAt": "2026-11-03T12:19:10.263Z",
|
||||
"authentication": "none",
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"realModelRequests": 0,
|
||||
"publicGets": [
|
||||
{
|
||||
"name": "upstream-commit.json",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/commits/main",
|
||||
"finalUrl": "https://api.github.com/repos/Wei-Shaw/sub2api/commits/main",
|
||||
"status": 200,
|
||||
"bytes": 303566,
|
||||
"sha256": "d3102e4b8859c585cfa7cef23c07f1104bdf9189c3b37ff934b5af57f460e386",
|
||||
"capturedAt": "2026-11-03T12:16:08.053Z",
|
||||
"authentication": "none",
|
||||
"environmentProxy": false
|
||||
},
|
||||
{
|
||||
"name": "vendor-home.html",
|
||||
"url": "https://apikey.fan/",
|
||||
"finalUrl": "https://apikey.fan/",
|
||||
"status": 200,
|
||||
"bytes": 45934,
|
||||
"sha256": "5d268c6fe9a0398c74f2b55a9fe54d33b0bc957a3ec7faf59909dd1a5cc1ff7d",
|
||||
"capturedAt": "2026-11-03T12:16:08.426Z",
|
||||
"authentication": "none",
|
||||
"environmentProxy": false
|
||||
},
|
||||
{
|
||||
"name": "upstream-tree.json",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/trees/f206215e531ff5062dff7f41136ab4c421484fff?recursive=1",
|
||||
"finalUrl": "https://api.github.com/repos/Wei-Shaw/sub2api/git/trees/f206215e531ff5062dff7f41136ab4c421484fff?recursive=1",
|
||||
"status": 200,
|
||||
"bytes": 1239557,
|
||||
"sha256": "31593e48032d152ce7459a5a3f758c6c556caf923cd5bde40ea436e1fbe55ee2",
|
||||
"capturedAt": "2026-11-03T12:16:09.251Z",
|
||||
"authentication": "none",
|
||||
"environmentProxy": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"repository": "https://github.com/Wei-Shaw/sub2api",
|
||||
"upstreamCommit": "4a4a83ee5ec86b19d3a2dd9b6471de5128963bec",
|
||||
"tree": "f206215e531ff5062dff7f41136ab4c421484fff",
|
||||
"files": [
|
||||
{
|
||||
"path": "backend/internal/server/routes/gateway.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"status": 200,
|
||||
"bytes": 31276,
|
||||
"sha256": "8fd2ebf61aeb2e6b7b79976b0d44ab1b46178e803b225139f3401af123021be4",
|
||||
"gitBlob": "3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"expectedGitBlob": "3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"treeBytes": 31276,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.303Z",
|
||||
"evidencePath": "public/source/backend/internal/server/routes/gateway.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/handler/openai_gateway_handler.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"status": 200,
|
||||
"bytes": 178238,
|
||||
"gitBlob": "3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"expectedGitBlob": "3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"treeMatched": true,
|
||||
"sha256": "3771bd42a673b562809b86df6848c9e1e14846e8fe388ea21f4e922de9f0879b",
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:21:29.690Z",
|
||||
"realModelRequests": 0,
|
||||
"evidencePath": "public/source/backend/internal/handler/openai_gateway_handler.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_gateway_messages.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"status": 200,
|
||||
"bytes": 54497,
|
||||
"sha256": "beedb4aad94c703b67971b06c3e72daaad630ea4331ff9dd9276d67529ac7d73",
|
||||
"gitBlob": "dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"expectedGitBlob": "dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"treeBytes": 54497,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.334Z",
|
||||
"evidencePath": "public/source/backend/internal/service/openai_gateway_messages.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_messages_dispatch.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"status": 200,
|
||||
"bytes": 3756,
|
||||
"sha256": "8a99dbe433d0fd2c48d8496b076572f308691fc6eab1ce65423160859826292c",
|
||||
"gitBlob": "b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"expectedGitBlob": "b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:18:54.108Z",
|
||||
"evidencePath": "public/source/backend/internal/service/openai_messages_dispatch.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_model_mapping.go",
|
||||
"url": "https://raw.githubusercontent.com/Wei-Shaw/sub2api/4a4a83ee5ec86b19d3a2dd9b6471de5128963bec/backend/internal/service/openai_model_mapping.go",
|
||||
"status": 200,
|
||||
"bytes": 5364,
|
||||
"sha256": "e6fab13f0e7726052f918d60c21aa9247b399f9d8f508522840dc27bcd411834",
|
||||
"gitBlob": "7fd67468b14be472c5c07166b4dfb5f142aac39f",
|
||||
"expectedGitBlob": "7fd67468b14be472c5c07166b4dfb5f142aac39f",
|
||||
"treeBytes": 5364,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:16:41.159Z",
|
||||
"evidencePath": "public/source/backend/internal/service/openai_model_mapping.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/group.go",
|
||||
"url": "https://raw.githubusercontent.com/Wei-Shaw/sub2api/4a4a83ee5ec86b19d3a2dd9b6471de5128963bec/backend/internal/service/group.go",
|
||||
"status": 200,
|
||||
"bytes": 18145,
|
||||
"sha256": "91d46705a0f361fcddcaf0949c977a8be0fc0e376669bc59ec60aecf8542b9a0",
|
||||
"gitBlob": "bcaa3a045054c484b787e5d4a29610cc744e5858",
|
||||
"expectedGitBlob": "bcaa3a045054c484b787e5d4a29610cc744e5858",
|
||||
"treeBytes": 18145,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:16:41.099Z",
|
||||
"evidencePath": "public/source/backend/internal/service/group.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/domain/openai_messages_dispatch.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"status": 200,
|
||||
"bytes": 494,
|
||||
"sha256": "c26623f1ae4c35a7ee9691feab637d1cc58860a62f5ef169e5721d8f775e2ab4",
|
||||
"gitBlob": "6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"expectedGitBlob": "6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"treeBytes": 494,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:42.319Z",
|
||||
"evidencePath": "public/source/backend/internal/domain/openai_messages_dispatch.go.txt"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/responses_to_anthropic.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"status": 200,
|
||||
"bytes": 24852,
|
||||
"sha256": "02f9cc5aa6f9cde9ff4477e5380db63ec58c10263cbf85149b1717e8f5474cdd",
|
||||
"gitBlob": "424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"expectedGitBlob": "424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"treeBytes": 24852,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.846Z",
|
||||
"evidencePath": "public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt"
|
||||
}
|
||||
],
|
||||
"scope": "Selected exact public source bytes, not product dependencies or authentication of the supplier production deployment."
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"upstreamCommit": "4a4a83ee5ec86b19d3a2dd9b6471de5128963bec",
|
||||
"realModelRequests": 0,
|
||||
"priorRawFetchFailures": 5,
|
||||
"receipts": [
|
||||
{
|
||||
"path": "backend/internal/service/openai_gateway_messages_anthropic_native.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/12a3344068974cdd17c167df7d35b1e77f7a9610",
|
||||
"status": 200,
|
||||
"bytes": 21717,
|
||||
"sha256": "11dc9b98942e363f84937b46dd86cd8d432ebe4788f170e9502e30967b69183c",
|
||||
"gitBlob": "12a3344068974cdd17c167df7d35b1e77f7a9610",
|
||||
"expectedGitBlob": "12a3344068974cdd17c167df7d35b1e77f7a9610",
|
||||
"treeBytes": 21717,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.277Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/server/routes/gateway.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"status": 200,
|
||||
"bytes": 31276,
|
||||
"sha256": "8fd2ebf61aeb2e6b7b79976b0d44ab1b46178e803b225139f3401af123021be4",
|
||||
"gitBlob": "3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"expectedGitBlob": "3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"treeBytes": 31276,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.303Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_gateway_messages.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"status": 200,
|
||||
"bytes": 54497,
|
||||
"sha256": "beedb4aad94c703b67971b06c3e72daaad630ea4331ff9dd9276d67529ac7d73",
|
||||
"gitBlob": "dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"expectedGitBlob": "dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"treeBytes": 54497,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.334Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_gateway_messages_chat_fallback.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/59a70dd191e8bf9c1c99f2b295a2b59e100e08f0",
|
||||
"status": 200,
|
||||
"bytes": 11128,
|
||||
"sha256": "2e996e26adf7e1f0f9aa9d1dbc8155263a061c8c3740cbca25231993e39f1a10",
|
||||
"gitBlob": "59a70dd191e8bf9c1c99f2b295a2b59e100e08f0",
|
||||
"expectedGitBlob": "59a70dd191e8bf9c1c99f2b295a2b59e100e08f0",
|
||||
"treeBytes": 11128,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.819Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/responses_to_anthropic.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"status": 200,
|
||||
"bytes": 24852,
|
||||
"sha256": "02f9cc5aa6f9cde9ff4477e5380db63ec58c10263cbf85149b1717e8f5474cdd",
|
||||
"gitBlob": "424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"expectedGitBlob": "424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"treeBytes": 24852,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.846Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/anthropic_to_responses.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/c27e44553717e9f5a5b71a71be5bdc38a1b80565",
|
||||
"status": 200,
|
||||
"bytes": 17037,
|
||||
"sha256": "0555fca7a7114176c1cd5e74a6c3529a270c663b7364ac5c93c6ec6ac731baed",
|
||||
"gitBlob": "c27e44553717e9f5a5b71a71be5bdc38a1b80565",
|
||||
"expectedGitBlob": "c27e44553717e9f5a5b71a71be5bdc38a1b80565",
|
||||
"treeBytes": 17037,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:41.849Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/domain/openai_messages_dispatch.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"status": 200,
|
||||
"bytes": 494,
|
||||
"sha256": "c26623f1ae4c35a7ee9691feab637d1cc58860a62f5ef169e5721d8f775e2ab4",
|
||||
"gitBlob": "6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"expectedGitBlob": "6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"treeBytes": 494,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:42.319Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/responses_to_anthropic_request.go",
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3ba7f638f19145547df4f721c6e4063c1f025a3e",
|
||||
"status": 200,
|
||||
"bytes": 27256,
|
||||
"sha256": "4718a7f9979ad665987c82d2ffb7cc630025e37bccc053b8a03f41395d098b8d",
|
||||
"gitBlob": "3ba7f638f19145547df4f721c6e4063c1f025a3e",
|
||||
"expectedGitBlob": "3ba7f638f19145547df4f721c6e4063c1f025a3e",
|
||||
"treeBytes": 27256,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:17:42.347Z"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"upstreamCommit": "4a4a83ee5ec86b19d3a2dd9b6471de5128963bec",
|
||||
"realModelRequests": 0,
|
||||
"receipts": [
|
||||
{
|
||||
"path": "backend/internal/service/group.go",
|
||||
"url": "https://raw.githubusercontent.com/Wei-Shaw/sub2api/4a4a83ee5ec86b19d3a2dd9b6471de5128963bec/backend/internal/service/group.go",
|
||||
"status": 200,
|
||||
"bytes": 18145,
|
||||
"sha256": "91d46705a0f361fcddcaf0949c977a8be0fc0e376669bc59ec60aecf8542b9a0",
|
||||
"gitBlob": "bcaa3a045054c484b787e5d4a29610cc744e5858",
|
||||
"expectedGitBlob": "bcaa3a045054c484b787e5d4a29610cc744e5858",
|
||||
"treeBytes": 18145,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:16:41.099Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/anthropic_to_responses_response.go",
|
||||
"url": "https://raw.githubusercontent.com/Wei-Shaw/sub2api/4a4a83ee5ec86b19d3a2dd9b6471de5128963bec/backend/internal/pkg/apicompat/anthropic_to_responses_response.go",
|
||||
"status": 200,
|
||||
"bytes": 26385,
|
||||
"sha256": "82a6fabd1d0ea8a3abfff6cc14ca26169c06364d4f972be8ad6b0b1fdd4b2479",
|
||||
"gitBlob": "2e7c85d3c94dcd36441301a94f9bb73b5ebfc899",
|
||||
"expectedGitBlob": "2e7c85d3c94dcd36441301a94f9bb73b5ebfc899",
|
||||
"treeBytes": 26385,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:16:41.158Z"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_model_mapping.go",
|
||||
"url": "https://raw.githubusercontent.com/Wei-Shaw/sub2api/4a4a83ee5ec86b19d3a2dd9b6471de5128963bec/backend/internal/service/openai_model_mapping.go",
|
||||
"status": 200,
|
||||
"bytes": 5364,
|
||||
"sha256": "e6fab13f0e7726052f918d60c21aa9247b399f9d8f508522840dc27bcd411834",
|
||||
"gitBlob": "7fd67468b14be472c5c07166b4dfb5f142aac39f",
|
||||
"expectedGitBlob": "7fd67468b14be472c5c07166b4dfb5f142aac39f",
|
||||
"treeBytes": 5364,
|
||||
"treeMatched": true,
|
||||
"authentication": "none",
|
||||
"capturedAt": "2026-11-03T12:16:41.159Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
// OpenAIMessagesDispatchModelConfig controls how Anthropic /v1/messages
|
||||
// requests are mapped onto OpenAI/Codex models.
|
||||
type OpenAIMessagesDispatchModelConfig struct {
|
||||
OpusMappedModel string `json:"opus_mapped_model,omitempty"`
|
||||
SonnetMappedModel string `json:"sonnet_mapped_model,omitempty"`
|
||||
HaikuMappedModel string `json:"haiku_mapped_model,omitempty"`
|
||||
ExactModelMappings map[string]string `json:"exact_model_mappings,omitempty"`
|
||||
}
|
||||
+4514
File diff suppressed because it is too large
Load Diff
+814
@@ -0,0 +1,814 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Non-streaming: ResponsesResponse → AnthropicResponse
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ResponsesToAnthropic converts a Responses API response directly into an
|
||||
// Anthropic Messages response. Reasoning output items are mapped to thinking
|
||||
// blocks; function_call items become tool_use blocks.
|
||||
func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicResponse {
|
||||
out := &AnthropicResponse{
|
||||
ID: resp.ID,
|
||||
Type: "message",
|
||||
Role: "assistant",
|
||||
Model: model,
|
||||
}
|
||||
|
||||
var blocks []AnthropicContentBlock
|
||||
|
||||
for _, item := range resp.Output {
|
||||
switch item.Type {
|
||||
case "reasoning":
|
||||
summaryText := ""
|
||||
for _, s := range item.Summary {
|
||||
if s.Type == "summary_text" && s.Text != "" {
|
||||
summaryText += s.Text
|
||||
}
|
||||
}
|
||||
// Always surface encrypted_content as thinking.signature so Claude
|
||||
// Code / multi-turn clients can send it back. Signature-only
|
||||
// thinking blocks are valid when the model omits a visible summary.
|
||||
if summaryText != "" || strings.TrimSpace(item.EncryptedContent) != "" {
|
||||
blocks = append(blocks, AnthropicContentBlock{
|
||||
Type: "thinking",
|
||||
Thinking: summaryText,
|
||||
Signature: item.EncryptedContent,
|
||||
})
|
||||
}
|
||||
case "message":
|
||||
for _, part := range item.Content {
|
||||
if part.Type == "output_text" && part.Text != "" {
|
||||
blocks = append(blocks, AnthropicContentBlock{
|
||||
Type: "text",
|
||||
Text: part.Text,
|
||||
})
|
||||
}
|
||||
}
|
||||
case "function_call":
|
||||
blocks = append(blocks, AnthropicContentBlock{
|
||||
Type: "tool_use",
|
||||
ID: fromResponsesCallID(item.CallID),
|
||||
Name: item.Name,
|
||||
Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments),
|
||||
})
|
||||
case "web_search_call":
|
||||
toolUseID := "srvtoolu_" + item.ID
|
||||
query := ""
|
||||
if item.Action != nil {
|
||||
query = item.Action.Query
|
||||
}
|
||||
inputJSON, _ := json.Marshal(map[string]string{"query": query})
|
||||
blocks = append(blocks, AnthropicContentBlock{
|
||||
Type: "server_tool_use",
|
||||
ID: toolUseID,
|
||||
Name: "web_search",
|
||||
Input: inputJSON,
|
||||
})
|
||||
emptyResults, _ := json.Marshal([]struct{}{})
|
||||
blocks = append(blocks, AnthropicContentBlock{
|
||||
Type: "web_search_tool_result",
|
||||
ToolUseID: toolUseID,
|
||||
Content: emptyResults,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(blocks) == 0 {
|
||||
blocks = append(blocks, AnthropicContentBlock{Type: "text", Text: ""})
|
||||
}
|
||||
out.Content = blocks
|
||||
|
||||
out.StopReason = AnthropicStopReasonPtr(responsesStatusToAnthropicStopReason(resp.Status, resp.IncompleteDetails, blocks))
|
||||
|
||||
if resp.Usage != nil {
|
||||
out.Usage = anthropicUsageFromResponsesUsage(resp.Usage)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage {
|
||||
if usage == nil {
|
||||
return AnthropicUsage{}
|
||||
}
|
||||
|
||||
cachedTokens := 0
|
||||
if usage.InputTokensDetails != nil {
|
||||
cachedTokens = usage.InputTokensDetails.CachedTokens
|
||||
}
|
||||
|
||||
inputTokens := usage.InputTokens - cachedTokens - usage.CacheCreationInputTokens
|
||||
if inputTokens < 0 {
|
||||
inputTokens = 0
|
||||
}
|
||||
|
||||
return AnthropicUsage{
|
||||
InputTokens: inputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheReadInputTokens: cachedTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
}
|
||||
}
|
||||
|
||||
func responsesStatusToAnthropicStopReason(status string, details *ResponsesIncompleteDetails, blocks []AnthropicContentBlock) string {
|
||||
switch status {
|
||||
case "incomplete":
|
||||
if details != nil && details.Reason == "max_output_tokens" {
|
||||
return "max_tokens"
|
||||
}
|
||||
return "end_turn"
|
||||
case "completed":
|
||||
if containsAnthropicToolUseBlock(blocks) {
|
||||
return "tool_use"
|
||||
}
|
||||
return "end_turn"
|
||||
default:
|
||||
return "end_turn"
|
||||
}
|
||||
}
|
||||
|
||||
func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool {
|
||||
for _, block := range blocks {
|
||||
if block.Type == "tool_use" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage {
|
||||
if name != "Read" || raw == "" {
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
var input map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(raw), &input); err != nil {
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
if pages, ok := input["pages"]; !ok || string(pages) != `""` {
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
delete(input, "pages")
|
||||
sanitized, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
return sanitized
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Streaming: ResponsesStreamEvent → []AnthropicStreamEvent (stateful converter)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// responsesTextPart identifies one output_text part of a streamed response.
|
||||
type responsesTextPart struct {
|
||||
OutputIndex int
|
||||
ContentIndex int
|
||||
}
|
||||
|
||||
// ResponsesEventToAnthropicState tracks state for converting a sequence of
|
||||
// Responses SSE events directly into Anthropic SSE events.
|
||||
type ResponsesEventToAnthropicState struct {
|
||||
MessageStartSent bool
|
||||
MessageStopSent bool
|
||||
|
||||
ContentBlockIndex int
|
||||
ContentBlockOpen bool
|
||||
CurrentBlockType string // "text" | "thinking" | "tool_use"
|
||||
CurrentToolName string
|
||||
CurrentToolArgs string
|
||||
CurrentToolHadDelta bool
|
||||
// PendingThinkingSignature is filled from reasoning.encrypted_content and
|
||||
// emitted as signature_delta before the thinking block is closed.
|
||||
PendingThinkingSignature string
|
||||
HasToolCall bool
|
||||
|
||||
// OutputIndexToBlockIdx maps Responses output_index → Anthropic content block index.
|
||||
OutputIndexToBlockIdx map[int]int
|
||||
|
||||
// textByPart records the text already delivered for each output_text part
|
||||
// so that a done payload can be reconciled against it. It outlives the
|
||||
// content block; closeCurrentBlock must not reset it.
|
||||
textByPart map[responsesTextPart]*strings.Builder
|
||||
// textDelivered records whether any assistant text reached the client.
|
||||
textDelivered bool
|
||||
|
||||
InputTokens int
|
||||
OutputTokens int
|
||||
CacheReadInputTokens int
|
||||
CacheCreationInputTokens int
|
||||
|
||||
ResponseID string
|
||||
Model string
|
||||
Created int64
|
||||
}
|
||||
|
||||
// NewResponsesEventToAnthropicState returns an initialised stream state.
|
||||
func NewResponsesEventToAnthropicState() *ResponsesEventToAnthropicState {
|
||||
return &ResponsesEventToAnthropicState{
|
||||
OutputIndexToBlockIdx: make(map[int]int),
|
||||
textByPart: make(map[responsesTextPart]*strings.Builder),
|
||||
Created: time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// ResponsesEventToAnthropicEvents converts a single Responses SSE event into
|
||||
// zero or more Anthropic SSE events, updating state as it goes.
|
||||
func ResponsesEventToAnthropicEvents(
|
||||
evt *ResponsesStreamEvent,
|
||||
state *ResponsesEventToAnthropicState,
|
||||
) []AnthropicStreamEvent {
|
||||
switch evt.Type {
|
||||
case "response.created":
|
||||
return resToAnthHandleCreated(evt, state)
|
||||
case "response.output_item.added":
|
||||
return resToAnthHandleOutputItemAdded(evt, state)
|
||||
case "response.output_text.delta":
|
||||
return resToAnthHandleTextDelta(evt, state)
|
||||
case "response.output_text.done":
|
||||
return resToAnthHandleTextDone(evt, state)
|
||||
case "response.function_call_arguments.delta",
|
||||
// custom/freeform 工具的输入增量与 function_call 参数增量同形。
|
||||
"response.custom_tool_call_input.delta":
|
||||
return resToAnthHandleFuncArgsDelta(evt, state)
|
||||
case "response.function_call_arguments.done":
|
||||
return resToAnthHandleFuncArgsDone(evt, state)
|
||||
case "response.output_item.done":
|
||||
return resToAnthHandleOutputItemDone(evt, state)
|
||||
case "response.reasoning_summary_text.delta",
|
||||
// 原始推理文本增量,与 reasoning summary 一样映射为 thinking。
|
||||
"response.reasoning_text.delta":
|
||||
return resToAnthHandleReasoningDelta(evt, state)
|
||||
case "response.reasoning_summary_text.done":
|
||||
// Keep the thinking block open until response.output_item.done.
|
||||
// Grok/Codex attach encrypted_content on the finished reasoning item;
|
||||
// closing early would drop signature_delta and break multi-turn cache.
|
||||
return nil
|
||||
// response.done 是 Realtime/WS 与项目透传路径使用的终止别名;
|
||||
// 普通 Responses HTTP SSE 的公开终止事件仍以 response.completed 为主。
|
||||
case "response.completed", "response.done", "response.incomplete", "response.failed":
|
||||
return resToAnthHandleCompleted(evt, state)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// FinalizeResponsesAnthropicStream emits synthetic termination events if the
|
||||
// stream ended without a proper completion event.
|
||||
func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if !state.MessageStartSent || state.MessageStopSent {
|
||||
return nil
|
||||
}
|
||||
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
stopReason := "end_turn"
|
||||
if state.HasToolCall {
|
||||
stopReason = "tool_use"
|
||||
}
|
||||
|
||||
events = append(events,
|
||||
AnthropicStreamEvent{
|
||||
Type: "message_delta",
|
||||
Delta: &AnthropicDelta{
|
||||
StopReason: stopReason,
|
||||
},
|
||||
Usage: &AnthropicUsage{
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
},
|
||||
},
|
||||
AnthropicStreamEvent{Type: "message_stop"},
|
||||
)
|
||||
state.MessageStopSent = true
|
||||
return events
|
||||
}
|
||||
|
||||
// ResponsesAnthropicEventToSSE formats an AnthropicStreamEvent as an SSE line pair.
|
||||
func ResponsesAnthropicEventToSSE(evt AnthropicStreamEvent) (string, error) {
|
||||
data, err := json.Marshal(evt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("event: %s\ndata: %s\n\n", evt.Type, data), nil
|
||||
}
|
||||
|
||||
// --- internal handlers ---
|
||||
|
||||
func resToAnthHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if evt.Response != nil {
|
||||
state.ResponseID = evt.Response.ID
|
||||
// Only use upstream model if no override was set (e.g. originalModel)
|
||||
if state.Model == "" {
|
||||
state.Model = evt.Response.Model
|
||||
}
|
||||
}
|
||||
|
||||
if state.MessageStartSent {
|
||||
return nil
|
||||
}
|
||||
state.MessageStartSent = true
|
||||
|
||||
// Official Anthropic message_start uses stop_reason: null and usage with
|
||||
// input_tokens when known. We leave StopReason nil (JSON null) and usage
|
||||
// zeros until response.completed; never emit stop_reason:"" which breaks
|
||||
// strict clients' turn-finalization / session usage accounting.
|
||||
return []AnthropicStreamEvent{{
|
||||
Type: "message_start",
|
||||
Message: &AnthropicResponse{
|
||||
ID: state.ResponseID,
|
||||
Type: "message",
|
||||
Role: "assistant",
|
||||
Content: []AnthropicContentBlock{},
|
||||
Model: state.Model,
|
||||
StopReason: nil,
|
||||
Usage: AnthropicUsage{
|
||||
InputTokens: 0,
|
||||
OutputTokens: 0,
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if evt.Item == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch evt.Item.Type {
|
||||
// function_call 与 custom_tool_call(custom/freeform 工具,如新版 apply_patch)
|
||||
// 同样映射为 Anthropic 的 tool_use 块。
|
||||
case "function_call", "custom_tool_call":
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
idx := state.ContentBlockIndex
|
||||
state.OutputIndexToBlockIdx[evt.OutputIndex] = idx
|
||||
state.ContentBlockOpen = true
|
||||
state.CurrentBlockType = "tool_use"
|
||||
state.CurrentToolName = evt.Item.Name
|
||||
state.CurrentToolArgs = ""
|
||||
state.CurrentToolHadDelta = false
|
||||
state.HasToolCall = true
|
||||
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_start",
|
||||
Index: &idx,
|
||||
ContentBlock: &AnthropicContentBlock{
|
||||
Type: "tool_use",
|
||||
ID: fromResponsesCallID(evt.Item.CallID),
|
||||
Name: evt.Item.Name,
|
||||
Input: json.RawMessage("{}"),
|
||||
},
|
||||
})
|
||||
return events
|
||||
|
||||
case "reasoning":
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
idx := state.ContentBlockIndex
|
||||
state.OutputIndexToBlockIdx[evt.OutputIndex] = idx
|
||||
state.ContentBlockOpen = true
|
||||
state.CurrentBlockType = "thinking"
|
||||
state.PendingThinkingSignature = strings.TrimSpace(evt.Item.EncryptedContent)
|
||||
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_start",
|
||||
Index: &idx,
|
||||
ContentBlock: &AnthropicContentBlock{
|
||||
Type: "thinking",
|
||||
Thinking: "",
|
||||
},
|
||||
})
|
||||
return events
|
||||
|
||||
case "message":
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func resToAnthHandleTextDelta(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
return resToAnthEmitText(evt.Delta, resToAnthTextPartOf(evt), state)
|
||||
}
|
||||
|
||||
func resToAnthTextPartOf(evt *ResponsesStreamEvent) responsesTextPart {
|
||||
return responsesTextPart{OutputIndex: evt.OutputIndex, ContentIndex: evt.ContentIndex}
|
||||
}
|
||||
|
||||
// resToAnthEmitText opens a text block when needed, emits text, and records it
|
||||
// against its part so that a later payload for the same part is reconciled
|
||||
// against what the client already received.
|
||||
func resToAnthEmitText(text string, part responsesTextPart, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var events []AnthropicStreamEvent
|
||||
|
||||
if !state.ContentBlockOpen || state.CurrentBlockType != "text" {
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
idx := state.ContentBlockIndex
|
||||
state.ContentBlockOpen = true
|
||||
state.CurrentBlockType = "text"
|
||||
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_start",
|
||||
Index: &idx,
|
||||
ContentBlock: &AnthropicContentBlock{
|
||||
Type: "text",
|
||||
Text: "",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
delivered, ok := state.textByPart[part]
|
||||
if !ok {
|
||||
delivered = &strings.Builder{}
|
||||
state.textByPart[part] = delivered
|
||||
}
|
||||
_, _ = delivered.WriteString(text)
|
||||
state.textDelivered = true
|
||||
|
||||
idx := state.ContentBlockIndex
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_delta",
|
||||
Index: &idx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "text_delta",
|
||||
Text: text,
|
||||
},
|
||||
})
|
||||
return events
|
||||
}
|
||||
|
||||
// resToAnthRecoverText emits the tail of a finished text payload that never
|
||||
// reached the client. Streamed text cannot be recalled, so a payload that does
|
||||
// not extend what was already delivered is left alone.
|
||||
func resToAnthRecoverText(text string, part responsesTextPart, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
builder, known := state.textByPart[part]
|
||||
if !known && state.textDelivered {
|
||||
// The payload is indexed differently from every delta seen so far, so
|
||||
// which part it finishes cannot be established. Recovering it could
|
||||
// repeat an answer the client already has, which is worse than leaving
|
||||
// a partially delivered one alone.
|
||||
return nil
|
||||
}
|
||||
|
||||
var delivered string
|
||||
if known {
|
||||
delivered = builder.String()
|
||||
}
|
||||
if text == delivered || !strings.HasPrefix(text, delivered) {
|
||||
return nil
|
||||
}
|
||||
return resToAnthEmitText(text[len(delivered):], part, state)
|
||||
}
|
||||
|
||||
// resToAnthHandleTextDone recovers text that upstream carried only on the done
|
||||
// event before closing the block, which some streams use instead of sending
|
||||
// output_text.delta at all.
|
||||
func resToAnthHandleTextDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if state.MessageStopSent {
|
||||
// The message is already terminated; a late payload cannot be delivered
|
||||
// without emitting a content block after message_stop.
|
||||
return resToAnthHandleBlockDone(state)
|
||||
}
|
||||
|
||||
events := resToAnthRecoverText(evt.Text, resToAnthTextPartOf(evt), state)
|
||||
return append(events, resToAnthHandleBlockDone(state)...)
|
||||
}
|
||||
|
||||
func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if evt.Delta == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if state.CurrentBlockType == "tool_use" && state.CurrentToolName == "Read" {
|
||||
state.CurrentToolArgs += evt.Delta
|
||||
if state.CurrentToolHadDelta || !json.Valid([]byte(state.CurrentToolArgs)) {
|
||||
return nil
|
||||
}
|
||||
|
||||
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
state.CurrentToolHadDelta = true
|
||||
sanitized := sanitizeAnthropicToolUseInput(state.CurrentToolName, state.CurrentToolArgs)
|
||||
return []AnthropicStreamEvent{{
|
||||
Type: "content_block_delta",
|
||||
Index: &blockIdx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "input_json_delta",
|
||||
PartialJSON: string(sanitized),
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
if state.CurrentBlockType == "tool_use" {
|
||||
state.CurrentToolHadDelta = true
|
||||
}
|
||||
|
||||
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return []AnthropicStreamEvent{{
|
||||
Type: "content_block_delta",
|
||||
Index: &blockIdx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "input_json_delta",
|
||||
PartialJSON: evt.Delta,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func resToAnthHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if !state.ContentBlockOpen {
|
||||
return nil
|
||||
}
|
||||
if state.CurrentBlockType != "tool_use" {
|
||||
return resToAnthHandleBlockDone(state)
|
||||
}
|
||||
|
||||
raw := evt.Arguments
|
||||
if raw == "" {
|
||||
raw = state.CurrentToolArgs
|
||||
}
|
||||
if raw == "" || state.CurrentToolHadDelta {
|
||||
return closeCurrentBlock(state)
|
||||
}
|
||||
if state.CurrentToolName == "Read" {
|
||||
sanitized := sanitizeAnthropicToolUseInput(state.CurrentToolName, raw)
|
||||
if len(sanitized) == 0 {
|
||||
return closeCurrentBlock(state)
|
||||
}
|
||||
raw = string(sanitized)
|
||||
}
|
||||
|
||||
// 从事件的 OutputIndex 解析正确的 block index,与 resToAnthHandleFuncArgsDelta 对齐
|
||||
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
|
||||
if !ok {
|
||||
blockIdx = state.ContentBlockIndex
|
||||
}
|
||||
|
||||
// 如果 block 已关闭(ContentBlockIndex 已越过它),说明 arguments 已通过 delta 流式发完,不再补发
|
||||
if !state.ContentBlockOpen || blockIdx != state.ContentBlockIndex {
|
||||
return nil
|
||||
}
|
||||
|
||||
events := []AnthropicStreamEvent{{
|
||||
Type: "content_block_delta",
|
||||
Index: &blockIdx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "input_json_delta",
|
||||
PartialJSON: raw,
|
||||
},
|
||||
}}
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
return events
|
||||
}
|
||||
|
||||
func resToAnthHandleReasoningDelta(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if evt.Delta == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return []AnthropicStreamEvent{{
|
||||
Type: "content_block_delta",
|
||||
Index: &blockIdx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "thinking_delta",
|
||||
Thinking: evt.Delta,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func resToAnthHandleBlockDone(state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if !state.ContentBlockOpen {
|
||||
return nil
|
||||
}
|
||||
return closeCurrentBlock(state)
|
||||
}
|
||||
|
||||
func resToAnthHandleOutputItemDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if evt.Item == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle web_search_call → synthesize server_tool_use + web_search_tool_result blocks.
|
||||
if evt.Item.Type == "web_search_call" && evt.Item.Status == "completed" {
|
||||
return resToAnthHandleWebSearchDone(evt, state)
|
||||
}
|
||||
|
||||
// Capture encrypted_content on reasoning item done (often only present here).
|
||||
if evt.Item.Type == "reasoning" {
|
||||
if sig := strings.TrimSpace(evt.Item.EncryptedContent); sig != "" {
|
||||
state.PendingThinkingSignature = sig
|
||||
}
|
||||
}
|
||||
|
||||
if state.ContentBlockOpen {
|
||||
return closeCurrentBlock(state)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resToAnthHandleWebSearchDone converts an OpenAI web_search_call output item
|
||||
// into Anthropic server_tool_use + web_search_tool_result content block pairs.
|
||||
// This allows Claude Code to count the searches performed.
|
||||
func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
toolUseID := "srvtoolu_" + evt.Item.ID
|
||||
query := ""
|
||||
if evt.Item.Action != nil {
|
||||
query = evt.Item.Action.Query
|
||||
}
|
||||
inputJSON, _ := json.Marshal(map[string]string{"query": query})
|
||||
|
||||
// Emit server_tool_use block (start + stop).
|
||||
idx1 := state.ContentBlockIndex
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_start",
|
||||
Index: &idx1,
|
||||
ContentBlock: &AnthropicContentBlock{
|
||||
Type: "server_tool_use",
|
||||
ID: toolUseID,
|
||||
Name: "web_search",
|
||||
Input: inputJSON,
|
||||
},
|
||||
})
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_stop",
|
||||
Index: &idx1,
|
||||
})
|
||||
state.ContentBlockIndex++
|
||||
|
||||
// Emit web_search_tool_result block (start + stop).
|
||||
// Content is empty because OpenAI does not expose individual search results;
|
||||
// the model consumes them internally and produces text output.
|
||||
emptyResults, _ := json.Marshal([]struct{}{})
|
||||
idx2 := state.ContentBlockIndex
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_start",
|
||||
Index: &idx2,
|
||||
ContentBlock: &AnthropicContentBlock{
|
||||
Type: "web_search_tool_result",
|
||||
ToolUseID: toolUseID,
|
||||
Content: emptyResults,
|
||||
},
|
||||
})
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_stop",
|
||||
Index: &idx2,
|
||||
})
|
||||
state.ContentBlockIndex++
|
||||
|
||||
return events
|
||||
}
|
||||
|
||||
// resToAnthRecoverTerminalText emits assistant text that only ever appeared in
|
||||
// the terminal response payload, which some streams populate without sending
|
||||
// any output_text event.
|
||||
//
|
||||
// It only runs when no text at all reached the client. Streamed events and the
|
||||
// terminal output array carry no guaranteed common identity, so reconciling
|
||||
// them part by part risks repeating an answer the client already has, which is
|
||||
// worse than leaving a partially streamed response as it is.
|
||||
func resToAnthRecoverTerminalText(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if state.textDelivered || evt.Response == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var events []AnthropicStreamEvent
|
||||
for outputIndex, item := range evt.Response.Output {
|
||||
if item.Type != "message" {
|
||||
continue
|
||||
}
|
||||
for contentIndex, content := range item.Content {
|
||||
if content.Type != "output_text" {
|
||||
continue
|
||||
}
|
||||
part := responsesTextPart{OutputIndex: outputIndex, ContentIndex: contentIndex}
|
||||
events = append(events, resToAnthEmitText(content.Text, part, state)...)
|
||||
}
|
||||
}
|
||||
if len(events) > 0 {
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if state.MessageStopSent {
|
||||
return nil
|
||||
}
|
||||
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
events = append(events, resToAnthRecoverTerminalText(evt, state)...)
|
||||
|
||||
stopReason := "end_turn"
|
||||
if evt.Usage != nil {
|
||||
usage := anthropicUsageFromResponsesUsage(evt.Usage)
|
||||
state.InputTokens = usage.InputTokens
|
||||
state.OutputTokens = usage.OutputTokens
|
||||
state.CacheReadInputTokens = usage.CacheReadInputTokens
|
||||
state.CacheCreationInputTokens = usage.CacheCreationInputTokens
|
||||
}
|
||||
if evt.Response != nil {
|
||||
if evt.Response.Usage != nil {
|
||||
usage := anthropicUsageFromResponsesUsage(evt.Response.Usage)
|
||||
state.InputTokens = usage.InputTokens
|
||||
state.OutputTokens = usage.OutputTokens
|
||||
state.CacheReadInputTokens = usage.CacheReadInputTokens
|
||||
state.CacheCreationInputTokens = usage.CacheCreationInputTokens
|
||||
}
|
||||
switch evt.Response.Status {
|
||||
case "incomplete":
|
||||
if evt.Response.IncompleteDetails != nil && evt.Response.IncompleteDetails.Reason == "max_output_tokens" {
|
||||
stopReason = "max_tokens"
|
||||
}
|
||||
case "completed":
|
||||
if state.HasToolCall {
|
||||
stopReason = "tool_use"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
events = append(events,
|
||||
AnthropicStreamEvent{
|
||||
Type: "message_delta",
|
||||
Delta: &AnthropicDelta{
|
||||
StopReason: stopReason,
|
||||
},
|
||||
Usage: &AnthropicUsage{
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
},
|
||||
},
|
||||
AnthropicStreamEvent{Type: "message_stop"},
|
||||
)
|
||||
state.MessageStopSent = true
|
||||
return events
|
||||
}
|
||||
|
||||
func closeCurrentBlock(state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
|
||||
if !state.ContentBlockOpen {
|
||||
return nil
|
||||
}
|
||||
idx := state.ContentBlockIndex
|
||||
var events []AnthropicStreamEvent
|
||||
// Emit signature_delta before stop so Claude clients retain encrypted
|
||||
// reasoning for the next turn (required for Grok multi-turn cache).
|
||||
if state.CurrentBlockType == "thinking" {
|
||||
if sig := strings.TrimSpace(state.PendingThinkingSignature); sig != "" {
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_delta",
|
||||
Index: &idx,
|
||||
Delta: &AnthropicDelta{
|
||||
Type: "signature_delta",
|
||||
Signature: sig,
|
||||
},
|
||||
})
|
||||
}
|
||||
state.PendingThinkingSignature = ""
|
||||
}
|
||||
state.ContentBlockOpen = false
|
||||
state.ContentBlockIndex++
|
||||
state.CurrentToolName = ""
|
||||
state.CurrentToolArgs = ""
|
||||
state.CurrentToolHadDelta = false
|
||||
events = append(events, AnthropicStreamEvent{
|
||||
Type: "content_block_stop",
|
||||
Index: &idx,
|
||||
})
|
||||
return events
|
||||
}
|
||||
+695
@@ -0,0 +1,695 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// RegisterGatewayRoutes 注册 API 网关路由(Claude/OpenAI/Gemini 兼容)
|
||||
func RegisterGatewayRoutes(
|
||||
r *gin.Engine,
|
||||
h *handler.Handlers,
|
||||
apiKeyAuth middleware.APIKeyAuthMiddleware,
|
||||
apiKeyService *service.APIKeyService,
|
||||
subscriptionService *service.SubscriptionService,
|
||||
opsService *service.OpsService,
|
||||
settingService *service.SettingService,
|
||||
compositeResolver *service.CompositeRouteResolver,
|
||||
cfg *config.Config,
|
||||
) {
|
||||
bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize)
|
||||
textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize)
|
||||
clientRequestID := middleware.ClientRequestID()
|
||||
opsErrorLogger := handler.OpsErrorLoggerMiddleware(opsService)
|
||||
endpointNorm := handler.InboundEndpointMiddleware()
|
||||
compositeTarget := compositeTargetPlatformMiddleware(compositeResolver)
|
||||
compositeGeminiTarget := compositeGeminiTargetPlatformMiddleware(compositeResolver)
|
||||
|
||||
// 未分组 Key 拦截中间件(按协议格式区分错误响应)
|
||||
requireGroupAnthropic := middleware.RequireGroupAssignment(settingService, middleware.AnthropicErrorWriter)
|
||||
requireGroupGoogle := middleware.RequireGroupAssignment(settingService, middleware.GoogleErrorWriter)
|
||||
|
||||
// 分组级模型白名单准入:在 apiKeyAuth 之后、compositeTarget 之前,
|
||||
// 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。
|
||||
groupModelAllowlist := middleware.GroupModelAllowlist()
|
||||
|
||||
isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool {
|
||||
// openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。
|
||||
return domain.UsesOpenAIGateway(getGroupPlatform(c))
|
||||
}
|
||||
countTokensHandler := func(c *gin.Context) {
|
||||
switch platform := getGroupPlatform(c); {
|
||||
case platform == service.PlatformGrok:
|
||||
h.OpenAIGateway.GrokCountTokens(c)
|
||||
case domain.UsesOpenAIGateway(platform):
|
||||
h.OpenAIGateway.CountTokens(c)
|
||||
default:
|
||||
h.Gateway.CountTokens(c)
|
||||
}
|
||||
}
|
||||
codexModelsHandler := func(c *gin.Context) {
|
||||
dispatchCodexModelsGateway(c, h.OpenAIGateway.CodexModels, h.Gateway.CodexModels)
|
||||
}
|
||||
modelsHandler := func(c *gin.Context) {
|
||||
if c.Query("client_version") != "" {
|
||||
codexModelsHandler(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Models(c)
|
||||
}
|
||||
isOpenAIOnlyEndpointGatewayPlatform := func(c *gin.Context) bool {
|
||||
return getGroupPlatform(c) == service.PlatformOpenAI
|
||||
}
|
||||
imagesHandler := func(c *gin.Context) {
|
||||
switch getGroupPlatform(c) {
|
||||
case service.PlatformOpenAI:
|
||||
h.OpenAIGateway.Images(c)
|
||||
case service.PlatformGrok:
|
||||
h.OpenAIGateway.GrokImages(c)
|
||||
default:
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Images API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
videoGenerationHandler := func(c *gin.Context) {
|
||||
// Video status/content lookups below already allow Composite groups; keep
|
||||
// task creation aligned so composite keys that route to Grok accounts can
|
||||
// submit video generation jobs.
|
||||
if platform := getGroupPlatform(c); platform == service.PlatformGrok || platform == service.PlatformComposite {
|
||||
h.OpenAIGateway.GrokVideoGeneration(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Videos API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
}
|
||||
videoStatusHandler := func(c *gin.Context) {
|
||||
// Video status requests do not carry a model, so composite groups cannot
|
||||
// be resolved by compositeTargetPlatformMiddleware. Route them through
|
||||
// the Grok handler and let scheduler/account selection enforce capacity.
|
||||
if getGroupPlatform(c) == service.PlatformGrok || getGroupPlatform(c) == service.PlatformComposite {
|
||||
h.OpenAIGateway.GrokVideoStatus(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Videos API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
}
|
||||
videoContentHandler := func(c *gin.Context) {
|
||||
// Video content requests do not carry a model, so composite groups cannot
|
||||
// be resolved by compositeTargetPlatformMiddleware. Route them through
|
||||
// the Grok handler just like video status lookups.
|
||||
if getGroupPlatform(c) == service.PlatformGrok || getGroupPlatform(c) == service.PlatformComposite {
|
||||
h.OpenAIGateway.GrokVideoContent(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Videos API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
}
|
||||
videoEditHandler := func(c *gin.Context) {
|
||||
if getGroupPlatform(c) == service.PlatformGrok {
|
||||
h.OpenAIGateway.GrokVideoEdit(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Videos API is not supported for this platform"}})
|
||||
}
|
||||
videoExtensionHandler := func(c *gin.Context) {
|
||||
if getGroupPlatform(c) == service.PlatformGrok {
|
||||
h.OpenAIGateway.GrokVideoExtension(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Videos API is not supported for this platform"}})
|
||||
}
|
||||
// /responses/*subpath 的子路径会被转发到上游同名端点之后,因此在入口就拒掉
|
||||
// 不可转发的子路径,不让它进入调度与转发流程。可转发的判定见
|
||||
// service.IsForwardableOpenAIResponsesRequestPath 及 upstream_path_guard.go。
|
||||
guardResponsesSubpath := func(next gin.HandlerFunc) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !service.IsForwardableOpenAIResponsesRequestPath(c) {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalPolicyDenied)
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Unsupported responses subpath",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
if service.IsOpenAIResponsesInputTokensRequestPath(c) && isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ResponsesInputTokens(c)
|
||||
return
|
||||
}
|
||||
next(c)
|
||||
}
|
||||
}
|
||||
|
||||
// API网关(Claude API兼容)
|
||||
gateway := r.Group("/v1")
|
||||
gateway.Use(bodyLimit)
|
||||
gateway.Use(clientRequestID)
|
||||
gateway.Use(opsErrorLogger)
|
||||
gateway.Use(endpointNorm)
|
||||
gateway.Use(gin.HandlerFunc(apiKeyAuth))
|
||||
gateway.GET("/sub2api/billing", h.Gateway.KeyBillingInfo)
|
||||
gateway.Use(groupModelAllowlist)
|
||||
gateway.Use(compositeTarget)
|
||||
gateway.Use(requireGroupAnthropic)
|
||||
{
|
||||
// /v1/messages: auto-route based on group platform
|
||||
gateway.POST("/messages", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Messages(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Messages(c)
|
||||
})
|
||||
// System One carries only JSON text, so it uses the text body limit.
|
||||
gateway.POST("/systemone", textBodyLimit, h.Gateway.SystemOne)
|
||||
// /v1/messages/count_tokens: OpenAI bridges upstream, Grok estimates
|
||||
// locally, and Anthropic-compatible platforms retain their existing path.
|
||||
gateway.POST("/messages/count_tokens", countTokensHandler)
|
||||
// Codex CLI / Codex app refresh their model picker from the provider's
|
||||
// /models endpoint with a client_version query and expect the ChatGPT
|
||||
// Codex manifest format; other clients keep the OpenAI-style list.
|
||||
gateway.GET("/models", modelsHandler)
|
||||
// Single-model discovery never selects the Codex client_version manifest.
|
||||
gateway.GET("/models/:model", h.Gateway.Models)
|
||||
gateway.GET("/usage", h.Gateway.Usage)
|
||||
gateway.POST("/live", h.OpenAIGateway.Live)
|
||||
gateway.GET("/live/:call_id", h.OpenAIGateway.LiveSideband)
|
||||
// OpenAI Responses API: auto-route based on group platform
|
||||
gateway.POST("/responses", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
})
|
||||
gateway.POST("/responses/*subpath", guardResponsesSubpath(func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
}))
|
||||
gateway.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
|
||||
gateway.GET("/responses", func(c *gin.Context) {
|
||||
h.OpenAIGateway.ResponsesWebSocket(c)
|
||||
})
|
||||
// OpenAI Chat Completions API: auto-route based on group platform
|
||||
gateway.POST("/chat/completions", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ChatCompletions(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.ChatCompletions(c)
|
||||
})
|
||||
gateway.POST("/embeddings", textBodyLimit, func(c *gin.Context) {
|
||||
if !isOpenAIOnlyEndpointGatewayPlatform(c) {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Embeddings API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.Embeddings(c)
|
||||
})
|
||||
gateway.POST("/images/generations", imagesHandler)
|
||||
gateway.POST("/images/edits", imagesHandler)
|
||||
gateway.POST("/images/generations/async", h.AsyncImage.Submit)
|
||||
gateway.POST("/images/edits/async", h.AsyncImage.Submit)
|
||||
gateway.GET("/images/tasks/:task_id", h.AsyncImage.Get)
|
||||
gateway.POST("/images/batches", h.BatchImage.Submit)
|
||||
gateway.GET("/images/batches", h.BatchImage.List)
|
||||
gateway.GET("/images/batches/models", h.BatchImage.Models)
|
||||
gateway.GET("/images/batches/:id", h.BatchImage.Get)
|
||||
gateway.GET("/images/batches/:id/items", h.BatchImage.Items)
|
||||
gateway.GET("/images/batches/:id/items/:custom_id/content", h.BatchImage.ItemContent)
|
||||
gateway.GET("/images/batches/:id/download", h.BatchImage.Download)
|
||||
gateway.POST("/images/batches/:id/cancel", h.BatchImage.Cancel)
|
||||
gateway.DELETE("/images/batches/:id", h.BatchImage.DeleteRecord)
|
||||
gateway.DELETE("/images/batches/:id/outputs", h.BatchImage.DeleteOutputs)
|
||||
// OpenAI-compatible clients may create through /videos; xAI receives the
|
||||
// canonical /videos/generations route inside the Grok media forwarder.
|
||||
gateway.POST("/videos", videoGenerationHandler)
|
||||
gateway.POST("/videos/generations", videoGenerationHandler)
|
||||
gateway.POST("/videos/edits", videoEditHandler)
|
||||
gateway.POST("/videos/extensions", videoExtensionHandler)
|
||||
gateway.GET("/videos/generations/:request_id/content", videoContentHandler)
|
||||
gateway.GET("/videos/edits/:request_id/content", videoContentHandler)
|
||||
gateway.GET("/videos/extensions/:request_id/content", videoContentHandler)
|
||||
gateway.GET("/videos/generations/:request_id", videoStatusHandler)
|
||||
gateway.GET("/videos/edits/:request_id", videoStatusHandler)
|
||||
gateway.GET("/videos/extensions/:request_id", videoStatusHandler)
|
||||
gateway.GET("/videos/:request_id", videoStatusHandler)
|
||||
gateway.GET("/videos/:request_id/content", videoContentHandler)
|
||||
|
||||
// xAI Voice APIs (Grok platform only): HTTP TTS/STT + Realtime WS.
|
||||
// Not part of the creation-center product surface — gateway relay only.
|
||||
voiceHandler := func(endpoint string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Voice API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokVoice(c, endpoint)
|
||||
}
|
||||
}
|
||||
gateway.POST("/tts", voiceHandler("tts"))
|
||||
gateway.POST("/stt", voiceHandler("stt"))
|
||||
gateway.POST("/custom-voices", voiceHandler("custom-voices"))
|
||||
customVoicePathHandler := func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Voice API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokVoice(c, grokCustomVoiceEndpoint(c))
|
||||
}
|
||||
gateway.GET("/custom-voices", voiceHandler("custom-voices"))
|
||||
gateway.GET("/custom-voices/:voice_id/audio", customVoicePathHandler)
|
||||
gateway.GET("/custom-voices/:voice_id", customVoicePathHandler)
|
||||
gateway.PATCH("/custom-voices/:voice_id", customVoicePathHandler)
|
||||
gateway.DELETE("/custom-voices/:voice_id", customVoicePathHandler)
|
||||
gateway.GET("/realtime", func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Realtime API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokRealtime(c)
|
||||
})
|
||||
gateway.POST("/web_search", func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Web Search API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.Gateway.WebSearch(c)
|
||||
})
|
||||
gateway.POST("/x_search", func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "X Search API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.Gateway.XSearch(c)
|
||||
})
|
||||
}
|
||||
|
||||
// Gemini 原生 API 兼容层(Gemini SDK/CLI 直连)
|
||||
gemini := r.Group("/v1beta")
|
||||
gemini.Use(bodyLimit)
|
||||
gemini.Use(clientRequestID)
|
||||
gemini.Use(opsErrorLogger)
|
||||
gemini.Use(endpointNorm)
|
||||
gemini.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg))
|
||||
gemini.Use(groupModelAllowlist)
|
||||
gemini.Use(compositeGeminiTarget)
|
||||
gemini.Use(requireGroupGoogle)
|
||||
{
|
||||
gemini.GET("/models", h.Gateway.GeminiV1BetaListModels)
|
||||
gemini.GET("/models/:model", h.Gateway.GeminiV1BetaGetModel)
|
||||
// Gin treats ":" as a param marker, but Gemini uses "{model}:{action}" in the same segment.
|
||||
gemini.POST("/models/*modelAction", h.Gateway.GeminiV1BetaModels)
|
||||
// 显式上下文缓存:网关自管资源 ID 与账号绑定,list/get 只读本地记录。
|
||||
gemini.POST("/cachedContents", h.Gateway.GeminiCachedContentsCreate)
|
||||
gemini.GET("/cachedContents", h.Gateway.GeminiCachedContentsList)
|
||||
gemini.GET("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsGet)
|
||||
gemini.PATCH("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsPatch)
|
||||
gemini.DELETE("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsDelete)
|
||||
}
|
||||
|
||||
// OpenAI Responses API(不带v1前缀的别名)— auto-route based on group platform
|
||||
responsesHandler := func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
}
|
||||
// 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget
|
||||
// 之前,避免逐条路由手工维护链导致漏挂。
|
||||
rootRoute := func(method, path string, limit gin.HandlerFunc, handler gin.HandlerFunc) {
|
||||
r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic, handler)
|
||||
}
|
||||
for _, prefix := range []string{"/api/v3", "/v3", "/v1", ""} {
|
||||
rootRoute(http.MethodPost, prefix+"/contents/generations/tasks", bodyLimit, h.OpenAIGateway.SeedanceTasks)
|
||||
rootRoute(http.MethodGet, prefix+"/contents/generations/tasks/:task_id", bodyLimit, h.OpenAIGateway.SeedanceTasks)
|
||||
rootRoute(http.MethodDelete, prefix+"/contents/generations/tasks/:task_id", bodyLimit, h.OpenAIGateway.SeedanceTasks)
|
||||
}
|
||||
rootRoute(http.MethodPost, "/responses", bodyLimit, responsesHandler)
|
||||
rootRoute(http.MethodPost, "/responses/*subpath", bodyLimit, guardResponsesSubpath(responsesHandler))
|
||||
rootRoute(http.MethodPost, "/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
|
||||
rootRoute(http.MethodGet, "/responses", bodyLimit, func(c *gin.Context) {
|
||||
h.OpenAIGateway.ResponsesWebSocket(c)
|
||||
})
|
||||
rootRoute(http.MethodGet, "/models", bodyLimit, modelsHandler)
|
||||
rootRoute(http.MethodGet, "/models/:model", bodyLimit, h.Gateway.Models)
|
||||
rootRoute(http.MethodPost, "/messages/count_tokens", bodyLimit, countTokensHandler)
|
||||
codexDirect := r.Group("/backend-api/codex")
|
||||
codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic)
|
||||
{
|
||||
codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live)
|
||||
codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband)
|
||||
codexDirect.POST("/responses", responsesHandler)
|
||||
codexDirect.POST("/responses/*subpath", guardResponsesSubpath(responsesHandler))
|
||||
codexDirect.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
|
||||
codexDirect.GET("/responses", func(c *gin.Context) {
|
||||
h.OpenAIGateway.ResponsesWebSocket(c)
|
||||
})
|
||||
codexDirect.GET("/models", codexModelsHandler)
|
||||
}
|
||||
// OpenAI Chat Completions API(不带v1前缀的别名)— auto-route based on group platform
|
||||
rootRoute(http.MethodPost, "/chat/completions", bodyLimit, func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ChatCompletions(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.ChatCompletions(c)
|
||||
})
|
||||
rootRoute(http.MethodPost, "/embeddings", textBodyLimit, func(c *gin.Context) {
|
||||
if !isOpenAIOnlyEndpointGatewayPlatform(c) {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Embeddings API is not supported for this platform",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.Embeddings(c)
|
||||
})
|
||||
rootRoute(http.MethodPost, "/images/generations", bodyLimit, imagesHandler)
|
||||
rootRoute(http.MethodPost, "/images/edits", bodyLimit, imagesHandler)
|
||||
rootRoute(http.MethodPost, "/images/generations/async", bodyLimit, h.AsyncImage.Submit)
|
||||
rootRoute(http.MethodPost, "/images/edits/async", bodyLimit, h.AsyncImage.Submit)
|
||||
rootRoute(http.MethodGet, "/images/tasks/:task_id", bodyLimit, h.AsyncImage.Get)
|
||||
rootRoute(http.MethodPost, "/videos", bodyLimit, videoGenerationHandler)
|
||||
rootRoute(http.MethodPost, "/videos/generations", bodyLimit, videoGenerationHandler)
|
||||
rootRoute(http.MethodPost, "/videos/edits", bodyLimit, videoEditHandler)
|
||||
rootRoute(http.MethodPost, "/videos/extensions", bodyLimit, videoExtensionHandler)
|
||||
rootRoute(http.MethodGet, "/videos/generations/:request_id/content", bodyLimit, videoContentHandler)
|
||||
rootRoute(http.MethodGet, "/videos/edits/:request_id/content", bodyLimit, videoContentHandler)
|
||||
rootRoute(http.MethodGet, "/videos/extensions/:request_id/content", bodyLimit, videoContentHandler)
|
||||
rootRoute(http.MethodGet, "/videos/generations/:request_id", bodyLimit, videoStatusHandler)
|
||||
rootRoute(http.MethodGet, "/videos/edits/:request_id", bodyLimit, videoStatusHandler)
|
||||
rootRoute(http.MethodGet, "/videos/extensions/:request_id", bodyLimit, videoStatusHandler)
|
||||
rootRoute(http.MethodGet, "/videos/:request_id", bodyLimit, videoStatusHandler)
|
||||
rootRoute(http.MethodGet, "/videos/:request_id/content", bodyLimit, videoContentHandler)
|
||||
|
||||
rootVoiceHandler := func(endpoint string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Voice API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokVoice(c, endpoint)
|
||||
}
|
||||
}
|
||||
rootRoute(http.MethodPost, "/tts", bodyLimit, rootVoiceHandler("tts"))
|
||||
rootRoute(http.MethodPost, "/stt", bodyLimit, rootVoiceHandler("stt"))
|
||||
rootRoute(http.MethodPost, "/custom-voices", bodyLimit, rootVoiceHandler("custom-voices"))
|
||||
rootCustomVoicePathHandler := func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Voice API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokVoice(c, grokCustomVoiceEndpoint(c))
|
||||
}
|
||||
rootRoute(http.MethodGet, "/custom-voices", bodyLimit, rootVoiceHandler("custom-voices"))
|
||||
rootRoute(http.MethodGet, "/custom-voices/:voice_id/audio", bodyLimit, rootCustomVoicePathHandler)
|
||||
rootRoute(http.MethodGet, "/custom-voices/:voice_id", bodyLimit, rootCustomVoicePathHandler)
|
||||
rootRoute(http.MethodPatch, "/custom-voices/:voice_id", bodyLimit, rootCustomVoicePathHandler)
|
||||
rootRoute(http.MethodDelete, "/custom-voices/:voice_id", bodyLimit, rootCustomVoicePathHandler)
|
||||
rootRoute(http.MethodGet, "/realtime", bodyLimit, func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Realtime API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.OpenAIGateway.GrokRealtime(c)
|
||||
})
|
||||
rootRoute(http.MethodPost, "/web_search", bodyLimit, func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Web Search API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.Gateway.WebSearch(c)
|
||||
})
|
||||
rootRoute(http.MethodPost, "/x_search", bodyLimit, func(c *gin.Context) {
|
||||
if getGroupPlatform(c) != service.PlatformGrok {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "X Search API is not supported for this platform"}})
|
||||
return
|
||||
}
|
||||
h.Gateway.XSearch(c)
|
||||
})
|
||||
|
||||
// Antigravity 模型列表
|
||||
r.GET("/antigravity/models", gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, h.Gateway.AntigravityModels)
|
||||
|
||||
// Antigravity 专用路由(仅使用 antigravity 账户,不混合调度)
|
||||
antigravityV1 := r.Group("/antigravity/v1")
|
||||
antigravityV1.Use(bodyLimit)
|
||||
antigravityV1.Use(clientRequestID)
|
||||
antigravityV1.Use(opsErrorLogger)
|
||||
antigravityV1.Use(endpointNorm)
|
||||
antigravityV1.Use(middleware.ForcePlatform(service.PlatformAntigravity))
|
||||
antigravityV1.Use(gin.HandlerFunc(apiKeyAuth))
|
||||
antigravityV1.Use(groupModelAllowlist)
|
||||
antigravityV1.Use(requireGroupAnthropic)
|
||||
{
|
||||
antigravityV1.POST("/messages", h.Gateway.Messages)
|
||||
antigravityV1.POST("/messages/count_tokens", h.Gateway.CountTokens)
|
||||
antigravityV1.GET("/models", h.Gateway.AntigravityModels)
|
||||
antigravityV1.GET("/usage", h.Gateway.Usage)
|
||||
}
|
||||
|
||||
antigravityV1Beta := r.Group("/antigravity/v1beta")
|
||||
antigravityV1Beta.Use(bodyLimit)
|
||||
antigravityV1Beta.Use(clientRequestID)
|
||||
antigravityV1Beta.Use(opsErrorLogger)
|
||||
antigravityV1Beta.Use(endpointNorm)
|
||||
antigravityV1Beta.Use(middleware.ForcePlatform(service.PlatformAntigravity))
|
||||
antigravityV1Beta.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg))
|
||||
antigravityV1Beta.Use(groupModelAllowlist)
|
||||
antigravityV1Beta.Use(requireGroupGoogle)
|
||||
{
|
||||
antigravityV1Beta.GET("/models", h.Gateway.GeminiV1BetaListModels)
|
||||
antigravityV1Beta.GET("/models/:model", h.Gateway.GeminiV1BetaGetModel)
|
||||
antigravityV1Beta.POST("/models/*modelAction", h.Gateway.GeminiV1BetaModels)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func dispatchCodexModelsGateway(c *gin.Context, openAIHandler, generatedHandler gin.HandlerFunc) {
|
||||
if getGroupPlatform(c) == service.PlatformOpenAI {
|
||||
openAIHandler(c)
|
||||
return
|
||||
}
|
||||
generatedHandler(c)
|
||||
}
|
||||
|
||||
// getGroupPlatform extracts the group platform from the API Key stored in context.
|
||||
func getGroupPlatform(c *gin.Context) string {
|
||||
apiKey, ok := middleware.GetAPIKeyFromContext(c)
|
||||
if !ok || apiKey.Group == nil {
|
||||
return ""
|
||||
}
|
||||
if apiKey.Group.Platform == service.PlatformComposite {
|
||||
if platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()); ok {
|
||||
return platform
|
||||
}
|
||||
}
|
||||
return apiKey.Group.Platform
|
||||
}
|
||||
|
||||
func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
resolver = service.NewCompositeRouteResolver(nil)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
apiKey, ok := middleware.GetAPIKeyFromContext(c)
|
||||
if !ok || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if c.Request == nil || c.Request.Method == http.MethodGet {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
|
||||
if err != nil {
|
||||
status := http.StatusBadRequest
|
||||
message := "Failed to read request body"
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
status = http.StatusRequestEntityTooLarge
|
||||
message = "Request body is too large"
|
||||
}
|
||||
c.JSON(status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Live 入口按 session.model 分发并改写(与白名单准入、Live handler 的
|
||||
// 解析保持一致),避免顶层 model 别名与 session 模型不一致时改错对象。
|
||||
routePath := c.FullPath()
|
||||
model := requestmodel.FromBodyForRoute(routePath, c.GetHeader("Content-Type"), body)
|
||||
if model != "" {
|
||||
decision, err := resolver.Resolve(c.Request.Context(), apiKey.Group.ID, model, compositeRouteEndpointForPath(c.Request.URL.Path))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": gin.H{"type": "server_error", "message": "Failed to resolve composite model route"}})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// 含 OAuth 账号的跨平台歧义是分组配置错误:拒绝而不是放行。否则未解析的
|
||||
// 请求落到默认 Anthropic handler,handler 再按模型名前缀另猜平台,
|
||||
// OAuth 凭据被送进不匹配的协议管线(如 ChatGPT token 发往 Anthropic)。
|
||||
if decision.OAuthAmbiguous() {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": decision.AmbiguousMessage()}})
|
||||
return
|
||||
}
|
||||
if decision.Matched {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
|
||||
if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" {
|
||||
if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil {
|
||||
body = rewritten
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
requestmodel.ResetRequestBody(c.Request, body)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func compositeGeminiTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
resolver = service.NewCompositeRouteResolver(nil)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
apiKey, ok := middleware.GetAPIKeyFromContext(c)
|
||||
if ok && apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite {
|
||||
model := compositeGeminiModelFromParams(c)
|
||||
if model != "" {
|
||||
decision, err := resolver.Resolve(c.Request.Context(), apiKey.Group.ID, model, service.CompositeRouteEndpointGemini)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": gin.H{"type": "server_error", "message": "Failed to resolve composite model route"}})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if decision.Matched {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
}
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); !resolved {
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformGemini))
|
||||
}
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// grokCustomVoiceEndpoint derives the upstream Voice endpoint for the
|
||||
// /custom-voices/:voice_id[/audio] routes.
|
||||
//
|
||||
// The /audio suffix must be decided from the matched route template, not from
|
||||
// the raw URL path: a voice literally named "audio" makes GET
|
||||
// /custom-voices/audio match /custom-voices/:voice_id, and a raw-path suffix
|
||||
// check would rewrite it to custom-voices/audio/audio — turning a profile
|
||||
// lookup into an audio download.
|
||||
func grokCustomVoiceEndpoint(c *gin.Context) string {
|
||||
endpoint := "custom-voices/" + c.Param("voice_id")
|
||||
if strings.HasSuffix(c.FullPath(), "/:voice_id/audio") {
|
||||
endpoint += "/audio"
|
||||
}
|
||||
return endpoint
|
||||
}
|
||||
|
||||
func compositeGeminiModelFromParams(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
if model := strings.TrimSpace(c.Param("model")); model != "" {
|
||||
return model
|
||||
}
|
||||
modelAction := strings.TrimPrefix(strings.TrimSpace(c.Param("modelAction")), "/")
|
||||
if modelAction == "" {
|
||||
return ""
|
||||
}
|
||||
if idx := strings.LastIndex(modelAction, ":"); idx >= 0 {
|
||||
return strings.TrimSpace(modelAction[:idx])
|
||||
}
|
||||
return modelAction
|
||||
}
|
||||
|
||||
func compositeRouteEndpointForPath(path string) string {
|
||||
switch {
|
||||
case strings.Contains(path, "/messages/count_tokens"):
|
||||
return service.CompositeRouteEndpointCountTokens
|
||||
case strings.Contains(path, "/messages"):
|
||||
return service.CompositeRouteEndpointMessages
|
||||
case strings.Contains(path, "/responses"),
|
||||
strings.Contains(path, "/alpha/search"),
|
||||
strings.Contains(path, "/realtime/calls"),
|
||||
strings.HasSuffix(strings.TrimRight(path, "/"), "/live"):
|
||||
return service.CompositeRouteEndpointResponses
|
||||
case strings.Contains(path, "/chat/completions"):
|
||||
return service.CompositeRouteEndpointChatCompletions
|
||||
case strings.Contains(path, "/embeddings"):
|
||||
return service.CompositeRouteEndpointEmbeddings
|
||||
case strings.Contains(path, "/images/"):
|
||||
return service.CompositeRouteEndpointImages
|
||||
case strings.Contains(path, "/v1beta/"):
|
||||
return service.CompositeRouteEndpointGemini
|
||||
default:
|
||||
return service.CompositeRouteEndpointAny
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
|
||||
)
|
||||
|
||||
type OpenAIMessagesDispatchModelConfig = domain.OpenAIMessagesDispatchModelConfig
|
||||
type GroupCodexModelsManifestConfig = domain.GroupCodexModelsManifestConfig
|
||||
type ReasoningEffortMapping = domain.ReasoningEffortMapping
|
||||
|
||||
type Group struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
I18n GroupI18n // 名称与描述的界面语言译文;缺失的语言沿用 Name/Description
|
||||
Platform string
|
||||
RateMultiplier float64
|
||||
// 高峰时段倍率:peak_rate_enabled 为 true 且当前时刻处于 [PeakStart, PeakEnd) 时,
|
||||
// token 计费倍率额外乘以 PeakRateMultiplier。详见 PeakMultiplierAt。
|
||||
PeakRateEnabled bool
|
||||
PeakStart string
|
||||
PeakEnd string
|
||||
PeakRateMultiplier float64
|
||||
IsExclusive bool
|
||||
Status string
|
||||
Hydrated bool // indicates the group was loaded from a trusted repository source
|
||||
// DuplicateOperationID is internal persistence metadata used only to recover
|
||||
// an already committed one-click copy. It must never be mapped to API DTOs.
|
||||
DuplicateOperationID string
|
||||
|
||||
SubscriptionType string
|
||||
DailyLimitUSD *float64
|
||||
WeeklyLimitUSD *float64
|
||||
MonthlyLimitUSD *float64
|
||||
DefaultValidityDays int
|
||||
|
||||
// 图片生成计费配置(antigravity 和 gemini 平台使用)
|
||||
AllowImageGeneration bool
|
||||
AllowBatchImageGeneration bool
|
||||
ImageCountBilling bool
|
||||
ImageRateIndependent bool
|
||||
ImageRateMultiplier float64
|
||||
ImagePrice1K *float64
|
||||
ImagePrice2K *float64
|
||||
ImagePrice4K *float64
|
||||
BatchImageDiscountMultiplier float64
|
||||
BatchImageHoldMultiplier float64
|
||||
VideoRateIndependent bool
|
||||
VideoRateMultiplier float64
|
||||
VideoPrice480P *float64
|
||||
VideoPrice720P *float64
|
||||
VideoPrice1080P *float64
|
||||
// VideoModelPrices is optional per-model-family per-second pricing
|
||||
// (groups.video_model_prices JSONB). Shape: family → resolution → USD/s.
|
||||
// When set for a model, overrides VideoPrice* for that model only.
|
||||
VideoModelPrices map[string]map[string]float64
|
||||
// Codex alpha/search 网页搜索单次价格(USD/次,仅 openai 平台使用);
|
||||
// nil 表示使用默认价 defaultWebSearchPricePerCall(官方 $10/1000 次)。
|
||||
WebSearchPricePerCall *float64
|
||||
|
||||
// 搜索工具显式定价(per 1k calls)。
|
||||
SearchPricePer1k *float64
|
||||
// Grok Voice 显式定价(分组级,不按文本 RateMultiplier)。
|
||||
AudioRealtimePricePerMin *float64
|
||||
AudioTTSPricePerMillionChars *float64
|
||||
AudioSTTPricePerHour *float64
|
||||
|
||||
// ModelPricing overrides channel and built-in prices for matching models.
|
||||
// Token intervals are selected only when LongContextPricingEnabled is true.
|
||||
LongContextPricingEnabled bool
|
||||
ModelPricing []ChannelModelPricing
|
||||
|
||||
// Claude Code 客户端限制
|
||||
ClaudeCodeOnly bool
|
||||
FallbackGroupID *int64
|
||||
// 无效请求兜底分组(仅 anthropic 平台使用)
|
||||
FallbackGroupIDOnInvalidRequest *int64
|
||||
|
||||
// 模型路由配置
|
||||
// key: 模型匹配模式(支持 * 通配符,如 "claude-opus-*")
|
||||
// value: 优先账号 ID 列表
|
||||
ModelRouting map[string][]int64
|
||||
ModelRoutingEnabled bool
|
||||
|
||||
// MCP XML 协议注入开关(仅 antigravity 平台使用)
|
||||
MCPXMLInject bool
|
||||
|
||||
// 支持的模型系列(仅 antigravity 平台使用)
|
||||
// 可选值: claude, gemini_text, gemini_image
|
||||
SupportedModelScopes []string
|
||||
|
||||
// 分组排序
|
||||
SortOrder int
|
||||
|
||||
// OpenAI Messages 调度配置(仅 openai 平台使用)
|
||||
AllowMessagesDispatch bool
|
||||
AllowLive bool
|
||||
ForceOpenAIFast bool // 强制 OpenAI 网关请求使用 service_tier=priority
|
||||
FreeOpenAIFast bool // OpenAI Fast 请求按 Standard 价格向用户计费
|
||||
RequireOAuthOnly bool // 仅允许非 apikey 类型账号关联(OpenAI/Antigravity/Anthropic/Gemini)
|
||||
RequirePrivacySet bool // 调度时仅允许 privacy 已成功设置的账号(OpenAI/Antigravity/Anthropic/Gemini)
|
||||
DefaultMappedModel string
|
||||
MessagesDispatchModelConfig OpenAIMessagesDispatchModelConfig
|
||||
ModelAllowlist GroupModelAllowlist
|
||||
// CodexModelsManifestConfig 开启后,普通模型列表与 Codex manifest 优先使用
|
||||
// 固定账号列表拉取并合并,不经过调度器(仅 openai 平台)。
|
||||
CodexModelsManifestConfig GroupCodexModelsManifestConfig
|
||||
|
||||
// RPMLimit 分组级每分钟请求数上限(0 = 不限制)。
|
||||
// 一旦设置即接管该分组用户的限流(覆盖用户级 rpm_limit),可被 user-group rpm_override 进一步覆盖。
|
||||
RPMLimit int
|
||||
|
||||
// MaxReasoningEffort limits the effective Anthropic/OpenAI reasoning effort.
|
||||
// Empty means unlimited; supported values are minimal/low/medium/high/xhigh/max.
|
||||
MaxReasoningEffort string
|
||||
// MaxReasoningEffortOverLimit is the access control when an explicit effort
|
||||
// exceeds the ceiling: downgrade (default) or deny.
|
||||
MaxReasoningEffortOverLimit string
|
||||
// ReasoningEffortMappings rewrites explicit request values before applying the ceiling.
|
||||
ReasoningEffortMappings []ReasoningEffortMapping
|
||||
|
||||
// 分组利润控制(五个 token 计费平台可启用)。
|
||||
// 调度准入条件:账号倍率 U 满足 U <= D*(1-margin-buffer),
|
||||
// D 为请求用户当刻有效下游倍率(用户覆盖 ?? 分组默认,再乘高峰因子)。
|
||||
// 只过滤候选账号,不改变既有排序/评分/粘性/熔断。
|
||||
ProfitControlEnabled bool
|
||||
ProfitMinMargin float64 // 最低毛利率,小数存储(0.30=30%)
|
||||
ProfitSafetyBuffer float64 // 安全缓冲,小数,与 margin 相加后从 D 中扣除
|
||||
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
AccountGroups []AccountGroup
|
||||
AccountCount int64
|
||||
ActiveAccountCount int64
|
||||
RateLimitedAccountCount int64
|
||||
}
|
||||
|
||||
// IsGroupBindableInSimpleMode is the shared policy for groups that may be
|
||||
// surfaced and bound to accounts while running in simple mode.
|
||||
func IsGroupBindableInSimpleMode(group *Group) bool {
|
||||
return group != nil && group.Platform != PlatformComposite
|
||||
}
|
||||
|
||||
func (g *Group) IsActive() bool {
|
||||
return g.Status == StatusActive
|
||||
}
|
||||
|
||||
func (g *Group) IsSubscriptionType() bool {
|
||||
return g.SubscriptionType == SubscriptionTypeSubscription
|
||||
}
|
||||
|
||||
func (g *Group) HasDailyLimit() bool {
|
||||
return g.DailyLimitUSD != nil && *g.DailyLimitUSD > 0
|
||||
}
|
||||
|
||||
func (g *Group) HasWeeklyLimit() bool {
|
||||
return g.WeeklyLimitUSD != nil && *g.WeeklyLimitUSD > 0
|
||||
}
|
||||
|
||||
func (g *Group) HasMonthlyLimit() bool {
|
||||
return g.MonthlyLimitUSD != nil && *g.MonthlyLimitUSD > 0
|
||||
}
|
||||
|
||||
// GetImagePrice 根据 image_size 返回对应的图片生成价格
|
||||
// 如果分组未配置价格,返回 nil(调用方应使用默认值)
|
||||
func (g *Group) GetImagePrice(imageSize string) *float64 {
|
||||
switch imageSize {
|
||||
case "1K":
|
||||
return g.ImagePrice1K
|
||||
case "2K":
|
||||
return g.ImagePrice2K
|
||||
case "4K":
|
||||
return g.ImagePrice4K
|
||||
default:
|
||||
// 未知尺寸默认按 2K 计费
|
||||
return g.ImagePrice2K
|
||||
}
|
||||
}
|
||||
|
||||
// GetVideoPrice 根据 resolution 返回对应的视频生成价格。
|
||||
// 如果分组未配置价格,返回 nil(调用方应使用默认值)。
|
||||
func (g *Group) GetVideoPrice(resolution string) *float64 {
|
||||
switch NormalizeVideoBillingResolutionOrDefault(resolution) {
|
||||
case VideoBillingResolution480P:
|
||||
return g.VideoPrice480P
|
||||
case VideoBillingResolution720P:
|
||||
return g.VideoPrice720P
|
||||
case VideoBillingResolution1080P:
|
||||
return g.VideoPrice1080P
|
||||
default:
|
||||
return g.VideoPrice480P
|
||||
}
|
||||
}
|
||||
|
||||
// GetVideoPriceForModel prefers VideoModelPrices for the model family, then flat columns.
|
||||
func (g *Group) GetVideoPriceForModel(model, resolution string) *float64 {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
if price := LookupVideoModelPrice(g.VideoModelPrices, model, resolution); price != nil {
|
||||
return price
|
||||
}
|
||||
return g.GetVideoPrice(resolution)
|
||||
}
|
||||
|
||||
// VideoPriceConfig builds billing config including optional per-model map.
|
||||
func (g *Group) VideoPriceConfig() *VideoPriceConfig {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
return &VideoPriceConfig{
|
||||
Price480P: g.VideoPrice480P,
|
||||
Price720P: g.VideoPrice720P,
|
||||
Price1080P: g.VideoPrice1080P,
|
||||
ModelPrices: NormalizeVideoModelPrices(g.VideoModelPrices),
|
||||
}
|
||||
}
|
||||
|
||||
// IsGroupContextValid reports whether a group from context has the fields required for routing decisions.
|
||||
func IsGroupContextValid(group *Group) bool {
|
||||
if group == nil {
|
||||
return false
|
||||
}
|
||||
if group.ID <= 0 {
|
||||
return false
|
||||
}
|
||||
if !group.Hydrated {
|
||||
return false
|
||||
}
|
||||
if group.Platform == "" || group.Status == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// GetRoutingAccountIDs 根据请求模型获取路由账号 ID 列表
|
||||
// 返回匹配的优先账号 ID 列表,如果没有匹配规则则返回 nil
|
||||
func (g *Group) GetRoutingAccountIDs(requestedModel string) []int64 {
|
||||
if !g.ModelRoutingEnabled || len(g.ModelRouting) == 0 || requestedModel == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 1. 精确匹配优先
|
||||
if accountIDs, ok := g.ModelRouting[requestedModel]; ok && len(accountIDs) > 0 {
|
||||
return accountIDs
|
||||
}
|
||||
|
||||
// 2. 通配符匹配(前缀匹配)
|
||||
for pattern, accountIDs := range g.ModelRouting {
|
||||
if matchModelPattern(pattern, requestedModel) && len(accountIDs) > 0 {
|
||||
return accountIDs
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// matchModelPattern 检查模型是否匹配模式
|
||||
// 支持 * 通配符,如 "claude-opus-*" 匹配 "claude-opus-4-20250514"
|
||||
func matchModelPattern(pattern, model string) bool {
|
||||
if pattern == model {
|
||||
return true
|
||||
}
|
||||
|
||||
// 处理 * 通配符(仅支持末尾通配符)
|
||||
if strings.HasSuffix(pattern, "*") {
|
||||
prefix := strings.TrimSuffix(pattern, "*")
|
||||
return strings.HasPrefix(model, prefix)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// parseMinutes 把 "HH:MM" 解析为当日分钟数(0..1439),格式非法返回 (0,false)。
|
||||
// 手工解析而非 time.Parse:本函数位于每请求的计费热路径(PeakMultiplierAt),
|
||||
// 避免对静态配置字符串重复走 layout 解析与 time.Time 分配。
|
||||
// 接受集与 time.Parse("15:04", s) 完全一致(存量数据按旧解析写入,不得收窄):
|
||||
// 小时 1–2 位数字(0..23,允许不补零如 "1:30"),分钟固定 2 位数字(00..59)。
|
||||
func parseMinutes(hhmm string) (int, bool) {
|
||||
colon := strings.IndexByte(hhmm, ':')
|
||||
if (colon != 1 && colon != 2) || len(hhmm)-colon-1 != 2 {
|
||||
return 0, false
|
||||
}
|
||||
h := 0
|
||||
for i := 0; i < colon; i++ {
|
||||
d := hhmm[i] - '0'
|
||||
if d > 9 {
|
||||
return 0, false
|
||||
}
|
||||
h = h*10 + int(d)
|
||||
}
|
||||
m1, m2 := hhmm[colon+1]-'0', hhmm[colon+2]-'0'
|
||||
if m1 > 9 || m2 > 9 {
|
||||
return 0, false
|
||||
}
|
||||
m := int(m1)*10 + int(m2)
|
||||
if h > 23 || m > 59 {
|
||||
return 0, false
|
||||
}
|
||||
return h*60 + m, true
|
||||
}
|
||||
|
||||
// PeakMultiplierAt 返回指定时刻 now 的高峰因子。
|
||||
// - 未启用 / 未配置 / 配置非法(start>=end 或格式错误) / 非高峰时段 → 返回 1.0(安全降级)
|
||||
// - 区间为左闭右开 [PeakStart, PeakEnd),仅支持当日区间,不支持跨天(如 22:00-次日02:00)
|
||||
// - 时刻基于全局系统时区(timezone.Location)判定
|
||||
//
|
||||
// 该方法是纯函数,不读取任何外部状态,便于单测。
|
||||
func (g *Group) PeakMultiplierAt(now time.Time) float64 {
|
||||
if g == nil || !g.IsSubscriptionType() || !g.PeakRateEnabled || g.PeakStart == "" || g.PeakEnd == "" {
|
||||
return 1.0
|
||||
}
|
||||
start, ok1 := parseMinutes(g.PeakStart)
|
||||
end, ok2 := parseMinutes(g.PeakEnd)
|
||||
if !ok1 || !ok2 || start >= end {
|
||||
return 1.0
|
||||
}
|
||||
t := now.In(timezone.Location())
|
||||
cur := t.Hour()*60 + t.Minute()
|
||||
if cur >= start && cur < end {
|
||||
return g.PeakRateMultiplier
|
||||
}
|
||||
return 1.0
|
||||
}
|
||||
|
||||
// ValidatePeakRateConfig 是高峰倍率配置的唯一校验来源,供 handler 与 service 层共用。
|
||||
// enabled=true 时仅允许订阅类型分组;并要求 start/end 合法且 end>start(不支持跨天),multiplier>=0。
|
||||
// multiplier=0 是允许的,表示高峰 token 请求按 0 倍计费,可用于折扣/免费策略。
|
||||
// enabled=false 时放行(不关心类型)。subscriptionType 为空按 standard 处理。
|
||||
func ValidatePeakRateConfig(subscriptionType string, enabled bool, start, end string, multiplier float64) error {
|
||||
if !enabled {
|
||||
return nil
|
||||
}
|
||||
if subscriptionType != SubscriptionTypeSubscription {
|
||||
return errors.New("高峰时段倍率仅支持订阅类型分组")
|
||||
}
|
||||
if start == "" || end == "" {
|
||||
return errors.New("peak_rate_enabled 为 true 时 peak_start 与 peak_end 必填")
|
||||
}
|
||||
st, okStart := parseMinutes(start)
|
||||
if !okStart {
|
||||
return fmt.Errorf("peak_start 格式应为 HH:MM,got %q", start)
|
||||
}
|
||||
en, okEnd := parseMinutes(end)
|
||||
if !okEnd {
|
||||
return fmt.Errorf("peak_end 格式应为 HH:MM,got %q", end)
|
||||
}
|
||||
if st >= en {
|
||||
return errors.New("peak_end 必须大于 peak_start(不支持跨天区间,如 22:00-02:00)")
|
||||
}
|
||||
if multiplier < 0 {
|
||||
return errors.New("peak_rate_multiplier 不能为负")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NormalizePeakRateConfig 归一化最终落库的高峰配置,CreateGroup 与 UpdateGroup 两条写路径共用(唯一收口):
|
||||
// - 非订阅类型分组不携带任何高峰配置,一律清空(enabled=false、窗口置空、倍率归 1.0);
|
||||
// - 订阅分组关闭高峰时保留已配置的合法窗口(便于临时停用后再启用),
|
||||
// 但清掉无法解析的脏字符串与负倍率,避免脏数据入库。
|
||||
//
|
||||
// 与 ValidatePeakRateConfig 的分工:enabled=true 时校验已保证各字段合法,本函数为无操作;
|
||||
// enabled=false 时校验放行,由本函数兜底清洗。调用顺序为先归一化、后校验,
|
||||
// 使"订阅转标准"这类更新能静默清空高峰配置而不是被校验拒绝。
|
||||
func NormalizePeakRateConfig(subscriptionType string, enabled bool, start, end string, multiplier float64) (bool, string, string, float64) {
|
||||
if subscriptionType != SubscriptionTypeSubscription {
|
||||
return false, "", "", 1.0
|
||||
}
|
||||
if !enabled {
|
||||
if _, ok := parseMinutes(start); !ok {
|
||||
start = ""
|
||||
}
|
||||
if _, ok := parseMinutes(end); !ok {
|
||||
end = ""
|
||||
}
|
||||
if multiplier < 0 {
|
||||
multiplier = 1.0
|
||||
}
|
||||
}
|
||||
return enabled, start, end, multiplier
|
||||
}
|
||||
|
||||
// computePeakAwareMultipliers 把"基础 token 倍率 base"(已含系统/分组/用户级倍率,但不含高峰)
|
||||
// 拆分为最终 token 倍率与图片按次倍率:图片按次倍率基于 base 现算、不受高峰影响;token 倍率在 base 上叠加高峰因子。
|
||||
// gateway_service.recordUsageCore 与 openai_gateway_service.RecordUsage 共用此函数,
|
||||
// 锁死"高峰因子只乘入 token 倍率、图片按次倍率不受影响"这一叠加顺序——任何调换都会被 group_peak_rate_test 覆盖。
|
||||
func computePeakAwareMultipliers(apiKey *APIKey, base float64, now time.Time) (text, image float64) {
|
||||
image = resolveImageRateMultiplier(apiKey, base)
|
||||
peak := 1.0
|
||||
if apiKey != nil && apiKey.Group != nil {
|
||||
peak = apiKey.Group.PeakMultiplierAt(now)
|
||||
}
|
||||
text = base * peak
|
||||
return
|
||||
}
|
||||
|
||||
// validProfitControlRatio 判定 margin/buffer 是否为可落库的合法小数:[0,1) 且非 NaN/Inf。
|
||||
func validProfitControlRatio(v float64) bool {
|
||||
return !math.IsNaN(v) && !math.IsInf(v, 0) && v >= 0 && v < 1
|
||||
}
|
||||
|
||||
// NormalizeGroupPlatform 把创建分组时省略的 platform 归一化为默认平台。
|
||||
// handler 的入参预校验必须与 CreateGroup 落库时用同一个归一化结果,否则
|
||||
// 「省略 platform + 启用利润控制」会被 handler 以「平台不支持」400 掉,
|
||||
// 而该分组本会被建成受支持的 anthropic 分组。
|
||||
func NormalizeGroupPlatform(platform string) string {
|
||||
if platform == "" {
|
||||
return PlatformAnthropic
|
||||
}
|
||||
return platform
|
||||
}
|
||||
|
||||
// ValidateProfitControlConfig 是分组利润控制配置的唯一校验来源,handler 与 service 层共用。
|
||||
// enabled=true 时仅允许五个可计费平台分组;margin/buffer 各自 ∈ [0,1),且 margin+buffer < 1
|
||||
// (相加 >=1 时阈值 <=0,所有可核价账号都会被排除,视为配置错误而不是静默全黑)。
|
||||
// enabled=false 时放行(不关心平台),由 Normalize 兜底清洗数值。
|
||||
func ValidateProfitControlConfig(platform string, enabled bool, minMargin, safetyBuffer float64) error {
|
||||
if !enabled {
|
||||
return nil
|
||||
}
|
||||
if !profitControlPlatformSupported(platform) {
|
||||
return errors.New("利润控制仅支持 openai、anthropic、gemini、grok、antigravity 平台分组")
|
||||
}
|
||||
if !validProfitControlRatio(minMargin) {
|
||||
return fmt.Errorf("profit_min_margin 应为 [0,1) 的小数,got %v", minMargin)
|
||||
}
|
||||
if !validProfitControlRatio(safetyBuffer) {
|
||||
return fmt.Errorf("profit_safety_buffer 应为 [0,1) 的小数,got %v", safetyBuffer)
|
||||
}
|
||||
if minMargin+safetyBuffer >= 1 {
|
||||
return errors.New("profit_min_margin 与 profit_safety_buffer 之和必须小于 1,否则将排除全部账号")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NormalizeProfitControlConfig 归一化最终落库的利润控制配置,CreateGroup 与 UpdateGroup 共用(唯一收口):
|
||||
// - 非五个平台分组不携带利润控制,一律重置为默认(关、0、0);
|
||||
// - 支持平台关闭开关时保留合法数值(便于再次启用),清洗 NaN/Inf/越界脏值。
|
||||
//
|
||||
// 与 ValidateProfitControlConfig 的分工同高峰倍率:先归一化、后校验,
|
||||
// 使"openai 转其他平台"这类更新能静默清空利润配置而不是被校验拒绝。
|
||||
func NormalizeProfitControlConfig(platform string, enabled bool, minMargin, safetyBuffer float64) (bool, float64, float64) {
|
||||
if !profitControlPlatformSupported(platform) {
|
||||
return false, 0, 0
|
||||
}
|
||||
if !enabled {
|
||||
if !validProfitControlRatio(minMargin) {
|
||||
minMargin = 0
|
||||
}
|
||||
if !validProfitControlRatio(safetyBuffer) {
|
||||
safetyBuffer = 0
|
||||
}
|
||||
}
|
||||
return enabled, minMargin, safetyBuffer
|
||||
}
|
||||
|
||||
func profitControlPlatformSupported(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformGrok, PlatformAntigravity:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// GetSearchPricePer1k returns explicit search/tool price per 1k calls if configured.
|
||||
func (g *Group) GetSearchPricePer1k() *float64 {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
return g.SearchPricePer1k
|
||||
}
|
||||
+1449
File diff suppressed because it is too large
Load Diff
+124
@@ -0,0 +1,124 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultOpenAIMessagesDispatchOpusMappedModel = "gpt-5.4"
|
||||
defaultOpenAIMessagesDispatchSonnetMappedModel = "gpt-5.3-codex"
|
||||
defaultOpenAIMessagesDispatchHaikuMappedModel = "gpt-5.4-mini"
|
||||
)
|
||||
|
||||
func normalizeOpenAIMessagesDispatchMappedModel(model string) string {
|
||||
model = NormalizeOpenAICompatRequestedModel(strings.TrimSpace(model))
|
||||
return strings.TrimSpace(model)
|
||||
}
|
||||
|
||||
func normalizeOpenAIMessagesDispatchModelConfig(cfg OpenAIMessagesDispatchModelConfig) OpenAIMessagesDispatchModelConfig {
|
||||
out := OpenAIMessagesDispatchModelConfig{
|
||||
OpusMappedModel: normalizeOpenAIMessagesDispatchMappedModel(cfg.OpusMappedModel),
|
||||
SonnetMappedModel: normalizeOpenAIMessagesDispatchMappedModel(cfg.SonnetMappedModel),
|
||||
HaikuMappedModel: normalizeOpenAIMessagesDispatchMappedModel(cfg.HaikuMappedModel),
|
||||
}
|
||||
|
||||
if len(cfg.ExactModelMappings) > 0 {
|
||||
out.ExactModelMappings = make(map[string]string, len(cfg.ExactModelMappings))
|
||||
for requestedModel, mappedModel := range cfg.ExactModelMappings {
|
||||
requestedModel = strings.TrimSpace(requestedModel)
|
||||
mappedModel = normalizeOpenAIMessagesDispatchMappedModel(mappedModel)
|
||||
if requestedModel == "" || mappedModel == "" {
|
||||
continue
|
||||
}
|
||||
out.ExactModelMappings[requestedModel] = mappedModel
|
||||
}
|
||||
if len(out.ExactModelMappings) == 0 {
|
||||
out.ExactModelMappings = nil
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func claudeMessagesDispatchFamily(model string) string {
|
||||
normalized := strings.ToLower(strings.TrimSpace(model))
|
||||
if !strings.HasPrefix(normalized, "claude") {
|
||||
return ""
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(normalized, "opus"):
|
||||
return "opus"
|
||||
case strings.Contains(normalized, "sonnet"):
|
||||
return "sonnet"
|
||||
case strings.Contains(normalized, "haiku"):
|
||||
return "haiku"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Group) ResolveMessagesDispatchModel(requestedModel string) string {
|
||||
if g == nil {
|
||||
return ""
|
||||
}
|
||||
requestedModel = strings.TrimSpace(requestedModel)
|
||||
if requestedModel == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if g.Platform == PlatformGrok {
|
||||
if claudeMessagesDispatchFamily(requestedModel) == "" {
|
||||
return ""
|
||||
}
|
||||
opts := xai.RuntimeModelMappingOptions()
|
||||
if !opts.EnableCrossClientMap {
|
||||
return ""
|
||||
}
|
||||
return xai.ModelMappingWithOptions(opts)["claude-*"]
|
||||
}
|
||||
|
||||
// 国产供应商 / OpenCode 分组:调度级模型映射不适用(其配置被 sanitize 置空,
|
||||
// 且下方的 gpt-5.x 默认值是 openai 专属,发给这些上游必错)。模型改写完全
|
||||
// 交给账号级 model_mapping;Anthropic 协议上游本身接受 claude-* 模型名。
|
||||
if IsMultiProtocolAPIKeyProvider(g.Platform) {
|
||||
return ""
|
||||
}
|
||||
|
||||
cfg := normalizeOpenAIMessagesDispatchModelConfig(g.MessagesDispatchModelConfig)
|
||||
if mappedModel := strings.TrimSpace(cfg.ExactModelMappings[requestedModel]); mappedModel != "" {
|
||||
return mappedModel
|
||||
}
|
||||
|
||||
switch claudeMessagesDispatchFamily(requestedModel) {
|
||||
case "opus":
|
||||
if mappedModel := strings.TrimSpace(cfg.OpusMappedModel); mappedModel != "" {
|
||||
return mappedModel
|
||||
}
|
||||
return defaultOpenAIMessagesDispatchOpusMappedModel
|
||||
case "sonnet":
|
||||
if mappedModel := strings.TrimSpace(cfg.SonnetMappedModel); mappedModel != "" {
|
||||
return mappedModel
|
||||
}
|
||||
return defaultOpenAIMessagesDispatchSonnetMappedModel
|
||||
case "haiku":
|
||||
if mappedModel := strings.TrimSpace(cfg.HaikuMappedModel); mappedModel != "" {
|
||||
return mappedModel
|
||||
}
|
||||
return defaultOpenAIMessagesDispatchHaikuMappedModel
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func sanitizeGroupMessagesDispatchFields(g *Group) {
|
||||
if g == nil || g.Platform == PlatformOpenAI {
|
||||
return
|
||||
}
|
||||
if g.Platform != PlatformComposite {
|
||||
g.AllowMessagesDispatch = false
|
||||
}
|
||||
g.DefaultMappedModel = ""
|
||||
g.MessagesDispatchModelConfig = OpenAIMessagesDispatchModelConfig{}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package service
|
||||
|
||||
import "strings"
|
||||
|
||||
// resolveOpenAIForwardModel 解析 OpenAI 兼容转发使用的模型。
|
||||
// messagesDispatchMappedModel 是调用方已为 /v1/messages 解析的显式调度结果;
|
||||
// 普通 OpenAI 请求必须传空,避免将分组配置作为通用模型兜底。
|
||||
func resolveOpenAIForwardModel(account *Account, requestedModel, messagesDispatchMappedModel string) string {
|
||||
messagesDispatchMappedModel = strings.TrimSpace(messagesDispatchMappedModel)
|
||||
if account == nil {
|
||||
if messagesDispatchMappedModel != "" {
|
||||
return messagesDispatchMappedModel
|
||||
}
|
||||
return requestedModel
|
||||
}
|
||||
|
||||
mappedModel, matched := account.ResolveMappedModel(requestedModel)
|
||||
if !matched && messagesDispatchMappedModel != "" {
|
||||
return messagesDispatchMappedModel
|
||||
}
|
||||
return mappedModel
|
||||
}
|
||||
|
||||
// openAIOAuthForeignModelPrefixes 列出明确属于其他厂商家族的模型名前缀。
|
||||
// Codex 上游不可能服务这些模型:转发阶段 normalizeOpenAIModelForUpstream
|
||||
// 对未知模型原样透传,上游必然返回不可重试的 400。
|
||||
//
|
||||
// 采用保守黑名单而非 Codex 模型白名单:未知/自定义别名保持「允许」,
|
||||
// 以兼容渠道级模型映射等「账号选定之后才改写模型名」的部署方式
|
||||
// (调度过滤看到的是改写前的原始模型名)。前缀分类的先例见
|
||||
// ResolveThinkingProtocol(thinking_protocol.go)。
|
||||
var openAIOAuthForeignModelPrefixes = []string{
|
||||
"deepseek-",
|
||||
"glm-",
|
||||
"kimi-",
|
||||
"moonshot-",
|
||||
"qwen-",
|
||||
"qwen2-",
|
||||
"qwen3-",
|
||||
"qwen4-",
|
||||
"qwq-",
|
||||
"minimax-",
|
||||
"gemini-",
|
||||
"gemma-",
|
||||
"grok-",
|
||||
"doubao-",
|
||||
"hunyuan-",
|
||||
"llama-",
|
||||
"llama2-",
|
||||
"llama3-",
|
||||
"meta-llama",
|
||||
"mistral-",
|
||||
"mixtral-",
|
||||
"baichuan-",
|
||||
"ernie-",
|
||||
"step-",
|
||||
"seed-",
|
||||
"yi-",
|
||||
}
|
||||
|
||||
// isOpenAIOAuthServableModel 判断「空 model_mapping 的 OpenAI OAuth 账号」能否
|
||||
// 服务请求模型。空映射默认仍是「允许」,仅排除明确属于其他厂商家族的模型
|
||||
// (deepseek-*/glm-*、以及 Kimi Code 官方 bare ID k3 / k3-256k 等)——这类
|
||||
// 请求原样透传必然被 Codex 上游以不可重试的 400 拒绝,且不触发 failover,
|
||||
// 应在调度阶段就跳过该账号,把请求让给显式声明支持该模型的账号(#3662)。
|
||||
// bare k3 仅精确匹配(取 last segment 后),不使用宽泛 k3- 前缀,以免误伤
|
||||
// 自定义别名;显式 model_mapping 命中路径不经过本函数,语义不变。
|
||||
func isOpenAIOAuthServableModel(requestedModel string) bool {
|
||||
model := strings.ToLower(lastOpenAIModelSegment(requestedModel))
|
||||
if model == "" {
|
||||
return true // 空模型交由上层必填校验处理
|
||||
}
|
||||
// Kimi Code 官方 bare model ID:无厂商前缀,prefix 黑名单挡不住。
|
||||
if model == "k3" || model == "k3-256k" {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range openAIOAuthForeignModelPrefixes {
|
||||
if strings.HasPrefix(model, prefix) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// deepseekServableModels 列出 DeepSeek 平台账号在「未配置 model_mapping」时
|
||||
// 可服务的官方模型名(精确匹配,小写比较)。deepseek-flash 与 deepseek-v4-pro
|
||||
// 为官方现行名;deepseek-v4-flash / deepseek-v4-flash-vision-exp 为处于兼容
|
||||
// 路由期的旧名(上游仍接受并按 flash 价计费);deepseek-v4-pro-0813 为与
|
||||
// 计费 pro 档口径一致的版本化名。
|
||||
var deepseekServableModels = []string{
|
||||
"deepseek-flash",
|
||||
"deepseek-v4-pro",
|
||||
"deepseek-v4-flash",
|
||||
"deepseek-v4-flash-vision-exp",
|
||||
"deepseek-v4-pro-0813",
|
||||
}
|
||||
|
||||
// isDeepseekServableModel 报告 DeepSeek 平台账号在「未配置 model_mapping」时
|
||||
// 可服务的模型名。官方现行模型为 deepseek-flash 与 deepseek-v4-pro;旧名
|
||||
// deepseek-v4-flash / deepseek-v4-flash-vision-exp 处于兼容路由期(上游仍接受并
|
||||
// 按 flash 价计费),deepseek-v4-pro-0813 为版本化名。其余一律拒绝:既避免把
|
||||
// 未知模型透传给上游(上游 404/400 会触发 per-model 冷却并掩盖真实配置错误),
|
||||
// 也避免上游把不认识的模型名静默兜底成 deepseek-flash。
|
||||
// Source: https://api-docs.deepseek.com/quick_start/pricing
|
||||
//
|
||||
// https://api-docs.deepseek.com/guides/anthropic_api
|
||||
func isDeepseekServableModel(requestedModel string) bool {
|
||||
// 官方 Claude Code 接入文档要求 ANTHROPIC_MODEL=deepseek-flash[1m]:
|
||||
// [1m] 是客户端上下文选择器,先按同一规则归一化再比对白名单。
|
||||
model := strings.ToLower(normalizeClaudeCodeLongContextModel(strings.TrimSpace(requestedModel)))
|
||||
if model == "" {
|
||||
return true // 空模型交由上层必填校验处理
|
||||
}
|
||||
for _, servable := range deepseekServableModels {
|
||||
if model == servable {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// resolveOpenAICompactForwardModel determines the compact-only upstream model
|
||||
// for /responses/compact requests. It never affects normal /responses traffic.
|
||||
// When no compact-specific mapping matches, the input model is returned as-is.
|
||||
func resolveOpenAICompactForwardModel(account *Account, model string) string {
|
||||
trimmedModel := strings.TrimSpace(model)
|
||||
if trimmedModel == "" || account == nil {
|
||||
return trimmedModel
|
||||
}
|
||||
|
||||
mappedModel, matched := account.ResolveCompactMappedModel(trimmedModel)
|
||||
if !matched {
|
||||
return trimmedModel
|
||||
}
|
||||
if trimmedMapped := strings.TrimSpace(mappedModel); trimmedMapped != "" {
|
||||
return trimmedMapped
|
||||
}
|
||||
return trimmedModel
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"upstreamCommit": "4a4a83ee5ec86b19d3a2dd9b6471de5128963bec",
|
||||
"tree": "f206215e531ff5062dff7f41136ab4c421484fff",
|
||||
"treeTruncated": false,
|
||||
"originalsRetainedLocally": [
|
||||
".qa/route-n/public/upstream-commit.json",
|
||||
".qa/route-n/public/upstream-tree.json"
|
||||
],
|
||||
"selectedTreeEntries": [
|
||||
{
|
||||
"path": "backend/internal/server/routes/gateway.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "3f09ebf4053c3af6375f0961959720687ea5a00f",
|
||||
"size": 31276,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3f09ebf4053c3af6375f0961959720687ea5a00f"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/handler/openai_gateway_handler.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "3518463f4fe04cca0772e1405b461ad790e0f1b0",
|
||||
"size": 178238,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/3518463f4fe04cca0772e1405b461ad790e0f1b0"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_gateway_messages.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "dfe326e8475a2f31cba43488985f6a2dd8b1f304",
|
||||
"size": 54497,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/dfe326e8475a2f31cba43488985f6a2dd8b1f304"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_messages_dispatch.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "b17d498d0a03d972fa0079f2f6e50105c72e4be9",
|
||||
"size": 3756,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/b17d498d0a03d972fa0079f2f6e50105c72e4be9"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/openai_model_mapping.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "7fd67468b14be472c5c07166b4dfb5f142aac39f",
|
||||
"size": 5364,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/7fd67468b14be472c5c07166b4dfb5f142aac39f"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/service/group.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "bcaa3a045054c484b787e5d4a29610cc744e5858",
|
||||
"size": 18145,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/bcaa3a045054c484b787e5d4a29610cc744e5858"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/domain/openai_messages_dispatch.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "6b018f1c30581dad66180f6e71728a45365a38ec",
|
||||
"size": 494,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/6b018f1c30581dad66180f6e71728a45365a38ec"
|
||||
},
|
||||
{
|
||||
"path": "backend/internal/pkg/apicompat/responses_to_anthropic.go",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "424affde73f4d869d685b54ac1040882ab6f7ae3",
|
||||
"size": 24852,
|
||||
"url": "https://api.github.com/repos/Wei-Shaw/sub2api/git/blobs/424affde73f4d869d685b54ac1040882ab6f7ae3"
|
||||
}
|
||||
],
|
||||
"note": "Full original public API responses remain outside Git; their hashes and anonymous GET receipts are sealed in receipts.json."
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"code":404,"message":"Model plaza is not enabled"}
|
||||
@@ -0,0 +1,710 @@
|
||||
{
|
||||
"passed": true,
|
||||
"comparisons": [
|
||||
{
|
||||
"ref": "410b3478",
|
||||
"bindings": [
|
||||
{
|
||||
"path": "src/shared/contracts/model-request.mjs",
|
||||
"beforeSha256": "76d1efa21fc91bd09dbac368db8b4f79f9095663a186195eda260ec50ad29ab9",
|
||||
"currentSha256": "c4846621c0405a6d89f09a611049579b2846e3fa2c2ef589fdb1abb1599e60a2"
|
||||
},
|
||||
{
|
||||
"path": "src/shared/contracts/model-capabilities.mjs",
|
||||
"beforeSha256": "4d7afd6d273cd4a30a810a6939748126614e3a00fe5c357c5fb6e24c18c09ce4",
|
||||
"currentSha256": "a71775c388d1afc5dfc9057528502882361694c6d9fb541e6f55257d0ca5686a"
|
||||
},
|
||||
{
|
||||
"path": "src/shared/contracts/native-parameters.mjs",
|
||||
"beforeSha256": "d8e493018d2cf2c42049d1c173cda6af1be06fb3a85999c97cd25e92561b3b84",
|
||||
"currentSha256": "e0140dc27baee32d67a4ca683516af0e9a38d11d917d5c742e532938ff0beb5f"
|
||||
}
|
||||
],
|
||||
"cases": [
|
||||
{
|
||||
"name": "chat-completions/text",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "af66066add57fae43d197c4cd5f3fc895682b1d6e15150ee1dc74a0faf648646"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/tools",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/tool-history",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "ba3dd438aa1476e1550b044919a1291df8be9d30322881006e37f1ce29863820"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/stream",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "c054619eda5f961260a25b9d563c761e2fa3f46c063a0d38dd1ec6736be7adec"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/vision",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "ce298a99e9442c789e16598beb4910620946b6a117b625b4d4e1db01f5e63d45"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/native",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "c764f3c09b034c46c2914d286216f4e2787e01e7c25e182d988e9e16e4a17fd2"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/brand-does-not-route",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "responses/text",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8e8ed8a67a419e7bc94b0258898eb7e5394ff1232959f858549626edd2ce2797"
|
||||
},
|
||||
{
|
||||
"name": "responses/tools",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8bacf4854475f1e2b846029c6c375b8f24cd7eef422544192a5fc05bdf0be406"
|
||||
},
|
||||
{
|
||||
"name": "responses/tool-history",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "de45d5be235873ac0f312c40500f437e7fb7c93a009b74fdb4037b9a72fa59f1"
|
||||
},
|
||||
{
|
||||
"name": "responses/stream",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "073dcfff4e4db3cb069668c4f466e29c084784351d1d2aa9003cecf463bdc87f"
|
||||
},
|
||||
{
|
||||
"name": "responses/vision",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "767c66711155c73623478f59a2254cefbb461bc39178e7eb9964f58adaa87a4c"
|
||||
},
|
||||
{
|
||||
"name": "responses/native",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "6044da9d64570d05a2921ee80e8e7aa780cd3c3fbb514e70655e8913f2a72c15"
|
||||
},
|
||||
{
|
||||
"name": "responses/brand-does-not-route",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8bacf4854475f1e2b846029c6c375b8f24cd7eef422544192a5fc05bdf0be406"
|
||||
},
|
||||
{
|
||||
"name": "legacy-missing-protocol",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "responses-retained-reasoning",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "b688e9d73d5040b6856921a20394da9d969c2ae54e74e0f46999c4061e400891"
|
||||
},
|
||||
{
|
||||
"name": "mixed-gpt-protocol-pool",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8296139693a9281f350e7257a930a64a5f012cc4ef1b3941f016b0c8f0b83eef"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ref": "b832982d",
|
||||
"bindings": [
|
||||
{
|
||||
"path": "src/shared/contracts/model-request.mjs",
|
||||
"beforeSha256": "76d1efa21fc91bd09dbac368db8b4f79f9095663a186195eda260ec50ad29ab9",
|
||||
"currentSha256": "c4846621c0405a6d89f09a611049579b2846e3fa2c2ef589fdb1abb1599e60a2"
|
||||
},
|
||||
{
|
||||
"path": "src/shared/contracts/model-capabilities.mjs",
|
||||
"beforeSha256": "4d7afd6d273cd4a30a810a6939748126614e3a00fe5c357c5fb6e24c18c09ce4",
|
||||
"currentSha256": "a71775c388d1afc5dfc9057528502882361694c6d9fb541e6f55257d0ca5686a"
|
||||
},
|
||||
{
|
||||
"path": "src/shared/contracts/native-parameters.mjs",
|
||||
"beforeSha256": "d8e493018d2cf2c42049d1c173cda6af1be06fb3a85999c97cd25e92561b3b84",
|
||||
"currentSha256": "e0140dc27baee32d67a4ca683516af0e9a38d11d917d5c742e532938ff0beb5f"
|
||||
},
|
||||
{
|
||||
"path": "src/shared/contracts/model-identity.mjs",
|
||||
"beforeSha256": "c40254c5ba31aef0abe4873faeec14127e22853fbc9f482c2b7b2b870cc379fb",
|
||||
"currentSha256": "24d50bef6226c548b534c4318e9d50ed1a8856f639fbe0c1df586dfe6092e2e1"
|
||||
}
|
||||
],
|
||||
"cases": [
|
||||
{
|
||||
"name": "chat-completions/text",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "af66066add57fae43d197c4cd5f3fc895682b1d6e15150ee1dc74a0faf648646"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/tools",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/tool-history",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "ba3dd438aa1476e1550b044919a1291df8be9d30322881006e37f1ce29863820"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/stream",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "c054619eda5f961260a25b9d563c761e2fa3f46c063a0d38dd1ec6736be7adec"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/vision",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "ce298a99e9442c789e16598beb4910620946b6a117b625b4d4e1db01f5e63d45"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/native",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "c764f3c09b034c46c2914d286216f4e2787e01e7c25e182d988e9e16e4a17fd2"
|
||||
},
|
||||
{
|
||||
"name": "chat-completions/brand-does-not-route",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "responses/text",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8e8ed8a67a419e7bc94b0258898eb7e5394ff1232959f858549626edd2ce2797"
|
||||
},
|
||||
{
|
||||
"name": "responses/tools",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8bacf4854475f1e2b846029c6c375b8f24cd7eef422544192a5fc05bdf0be406"
|
||||
},
|
||||
{
|
||||
"name": "responses/tool-history",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "de45d5be235873ac0f312c40500f437e7fb7c93a009b74fdb4037b9a72fa59f1"
|
||||
},
|
||||
{
|
||||
"name": "responses/stream",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "073dcfff4e4db3cb069668c4f466e29c084784351d1d2aa9003cecf463bdc87f"
|
||||
},
|
||||
{
|
||||
"name": "responses/vision",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "767c66711155c73623478f59a2254cefbb461bc39178e7eb9964f58adaa87a4c"
|
||||
},
|
||||
{
|
||||
"name": "responses/native",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "6044da9d64570d05a2921ee80e8e7aa780cd3c3fbb514e70655e8913f2a72c15"
|
||||
},
|
||||
{
|
||||
"name": "responses/brand-does-not-route",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8bacf4854475f1e2b846029c6c375b8f24cd7eef422544192a5fc05bdf0be406"
|
||||
},
|
||||
{
|
||||
"name": "legacy-missing-protocol",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8c858fda3c57c7c03c3d192c09a3e1d2212746902980aadab1b323b0f69b8287"
|
||||
},
|
||||
{
|
||||
"name": "responses-retained-reasoning",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "b688e9d73d5040b6856921a20394da9d969c2ae54e74e0f46999c4061e400891"
|
||||
},
|
||||
{
|
||||
"name": "mixed-gpt-protocol-pool",
|
||||
"equalRequestBytes": true,
|
||||
"equalMetrics": true,
|
||||
"sha256": "8296139693a9281f350e7257a930a64a5f012cc4ef1b3941f016b0c8f0b83eef"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"identities": [
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "default",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "record",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "record",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [],
|
||||
"status": "missing",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol"
|
||||
],
|
||||
"status": "matched",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"other-model"
|
||||
],
|
||||
"status": "mismatch",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"configuredPolicy": "require-match",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"result": {
|
||||
"schemaVersion": 1,
|
||||
"requestedModel": "gpt-6.1-sol",
|
||||
"reportedModels": [
|
||||
"gpt-6.1-sol",
|
||||
"other-model"
|
||||
],
|
||||
"status": "mixed",
|
||||
"complete": true,
|
||||
"invalidIdentifiers": false,
|
||||
"policy": "require-match",
|
||||
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights."
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestCasesPerBaseline": 17,
|
||||
"baselineRequestComparisons": 34,
|
||||
"identityComparisons": 24,
|
||||
"realModelRequests": 0,
|
||||
"productCodeModified": false,
|
||||
"scope": "Execute actual pre-I/pre-M and current pure request modules using owned fixtures. Not a provider inference or model-weights test."
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"passed": true,
|
||||
"results": [
|
||||
{
|
||||
"protocol": "chat-completions",
|
||||
"passed": true,
|
||||
"originRequests": 1,
|
||||
"targetRequests": 0,
|
||||
"responseStatus": 307,
|
||||
"redirectMode": "manual",
|
||||
"requestUrl": "http://127.0.0.1:64973/v1/chat/completions",
|
||||
"diagnosticKind": "service",
|
||||
"realModelRequests": 0,
|
||||
"credential": "owned fixture only"
|
||||
},
|
||||
{
|
||||
"protocol": "responses",
|
||||
"passed": true,
|
||||
"originRequests": 1,
|
||||
"targetRequests": 0,
|
||||
"responseStatus": 307,
|
||||
"redirectMode": "manual",
|
||||
"requestUrl": "http://127.0.0.1:64976/v1/responses",
|
||||
"diagnosticKind": "service",
|
||||
"realModelRequests": 0,
|
||||
"credential": "owned fixture only"
|
||||
}
|
||||
],
|
||||
"realModelRequests": 0,
|
||||
"scope": "Observed cross-protocol compatibility change: redirects require a correct final endpoint; no automatic POST replay or credential forwarding."
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"passed": true,
|
||||
"runner": "node:test",
|
||||
"encoding": "utf8",
|
||||
"tests": 144,
|
||||
"pass": 144,
|
||||
"fail": 0,
|
||||
"realModelRequests": 0,
|
||||
"testFiles": [
|
||||
"tests/model-center.test.mjs",
|
||||
"tests/model-selection.test.mjs",
|
||||
"tests/model-identity.test.mjs",
|
||||
"tests/model-fidelity.test.mjs",
|
||||
"tests/model-protocols.test.mjs",
|
||||
"tests/model-stream.test.mjs",
|
||||
"tests/anthropic-messages.test.mjs",
|
||||
"tests/credential-vault.test.mjs",
|
||||
"tests/upgrade-model-center.test.mjs",
|
||||
"tests/delivery-progress.test.mjs",
|
||||
"tests/no-progress-integrity.test.mjs",
|
||||
"tests/read-budget.test.mjs",
|
||||
"tests/working-set.test.mjs"
|
||||
],
|
||||
"scope": "Already completed owned-fixture regression; original log bytes retained, not a live-model or full-suite result."
|
||||
}
|
||||
@@ -0,0 +1,878 @@
|
||||
TAP version 13
|
||||
# Subtest: Messages builds native system/tool history, bounds images, and seals a distinct mixed-pool variant
|
||||
ok 1 - Messages builds native system/tool history, bounds images, and seals a distinct mixed-pool variant
|
||||
---
|
||||
duration_ms: 6.5788
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Messages URL and native parameter contracts preserve other protocol paths and hard output budget
|
||||
ok 2 - Messages URL and native parameter contracts preserve other protocol paths and hard output budget
|
||||
---
|
||||
duration_ms: 0.6015
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: native usage includes both cache buckets once, retains raw and rejects invalid counters
|
||||
ok 3 - native usage includes both cache buckets once, retains raw and rejects invalid counters
|
||||
---
|
||||
duration_ms: 0.1704
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: real HTTP Messages JSON executes one tool, retains opaque history, actual URL and cache accounting
|
||||
ok 4 - real HTTP Messages JSON executes one tool, retains opaque history, actual URL and cache accounting
|
||||
---
|
||||
duration_ms: 2704.113
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: real HTTP Messages SSE executes one tool, retains opaque history, actual URL and cache accounting
|
||||
ok 5 - real HTTP Messages SSE executes one tool, retains opaque history, actual URL and cache accounting
|
||||
---
|
||||
duration_ms: 1885.5117
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Messages api-key authentication is explicit; mismatched model remains blocked with original usage
|
||||
ok 6 - Messages api-key authentication is explicit; mismatched model remains blocked with original usage
|
||||
---
|
||||
duration_ms: 5.0091
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Messages bearer authentication is explicit; mismatched model remains blocked with original usage
|
||||
ok 7 - Messages bearer authentication is explicit; mismatched model remains blocked with original usage
|
||||
---
|
||||
duration_ms: 4.9868
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Messages redirect is not followed, either credential stays at the original server
|
||||
ok 8 - Messages redirect is not followed, either credential stays at the original server
|
||||
---
|
||||
duration_ms: 3.6953
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: strict native SSE reads the nested start model and retains mismatch source without retries
|
||||
ok 9 - strict native SSE reads the nested start model and retains mismatch source without retries
|
||||
---
|
||||
duration_ms: 2.7817
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a closed native tool block cannot execute before message_stop, then executes exactly once
|
||||
ok 10 - a closed native tool block cannot execute before message_stop, then executes exactly once
|
||||
---
|
||||
duration_ms: 2403.2934
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: mixed Chat/Messages pool seals both variants and preserves one completed tool on failover
|
||||
ok 11 - mixed Chat/Messages pool seals both variants and preserves one completed tool on failover
|
||||
---
|
||||
duration_ms: 2757.6706
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: native JSON rejects incomplete stops, duplicate tools and hosted content
|
||||
ok 12 - native JSON rejects incomplete stops, duplicate tools and hosted content
|
||||
---
|
||||
duration_ms: 0.2905
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: strict SSE validates all blocks, terminal, event names, UTF8 and tool JSON before dispatch
|
||||
# Subtest: reject native stream 0
|
||||
ok 1 - reject native stream 0
|
||||
---
|
||||
duration_ms: 1.0671
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 1
|
||||
ok 2 - reject native stream 1
|
||||
---
|
||||
duration_ms: 0.2519
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 2
|
||||
ok 3 - reject native stream 2
|
||||
---
|
||||
duration_ms: 0.2103
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 3
|
||||
ok 4 - reject native stream 3
|
||||
---
|
||||
duration_ms: 0.2057
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 4
|
||||
ok 5 - reject native stream 4
|
||||
---
|
||||
duration_ms: 0.3227
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 5
|
||||
ok 6 - reject native stream 5
|
||||
---
|
||||
duration_ms: 0.2245
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 6
|
||||
ok 7 - reject native stream 6
|
||||
---
|
||||
duration_ms: 0.1461
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 7
|
||||
ok 8 - reject native stream 7
|
||||
---
|
||||
duration_ms: 0.1371
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject native stream 8
|
||||
ok 9 - reject native stream 8
|
||||
---
|
||||
duration_ms: 0.1964
|
||||
type: 'test'
|
||||
...
|
||||
1..9
|
||||
ok 13 - strict SSE validates all blocks, terminal, event names, UTF8 and tool JSON before dispatch
|
||||
---
|
||||
duration_ms: 3.4121
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: upstream SSE error retains original type/request ID and initial usage, never retries
|
||||
ok 14 - upstream SSE error retains original type/request ID and initial usage, never retries
|
||||
---
|
||||
duration_ms: 4.3346
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: stop cancels the owned stream and retains partial consumption without running tool or replaying
|
||||
ok 15 - stop cancels the owned stream and retains partial consumption without running tool or replaying
|
||||
---
|
||||
duration_ms: 56.5906
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: saved Messages import preserves auth choice, rejects endpoint duplication, and keeps source file untouched
|
||||
ok 16 - saved Messages import preserves auth choice, rejects endpoint duplication, and keeps source file untouched
|
||||
---
|
||||
duration_ms: 548.8965
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a Windows virtual data-directory name binds new storage and credentials to its actual physical root
|
||||
ok 17 - a Windows virtual data-directory name binds new storage and credentials to its actual physical root
|
||||
---
|
||||
duration_ms: 1902.0432
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: physical data-root adoption still rejects explicit junctions at the directory or any ancestor
|
||||
ok 18 - physical data-root adoption still rejects explicit junctions at the directory or any ancestor
|
||||
---
|
||||
duration_ms: 618.2534
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damaged bytes and wrong entropy
|
||||
ok 19 - actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damaged bytes and wrong entropy
|
||||
---
|
||||
duration_ms: 1830.5381
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: only explicitly supplied keys persist; new provider restores original revisions and public views contain no key
|
||||
ok 20 - only explicitly supplied keys persist; new provider restores original revisions and public views contain no key
|
||||
---
|
||||
duration_ms: 2816.6115
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: registry and cipher commit failure restores original routing, keys, block and every database row
|
||||
ok 21 - registry and cipher commit failure restores original routing, keys, block and every database row
|
||||
---
|
||||
duration_ms: 1741.491
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a two-key import with a protection failure rolls back all registry and cipher entries and retains its preview
|
||||
ok 22 - a two-key import with a protection failure rolls back all registry and cipher entries and retains its preview
|
||||
---
|
||||
duration_ms: 1889.6754
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: connection revision changes retain the original saved block and report a source mismatch on restart
|
||||
ok 23 - connection revision changes retain the original saved block and report a source mismatch on restart
|
||||
---
|
||||
duration_ms: 2389.1824
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: disable skips real restart loading, explicit enable restores, delete preserves memory and forget removes both
|
||||
ok 24 - disable skips real restart loading, explicit enable restores, delete preserves memory and forget removes both
|
||||
---
|
||||
duration_ms: 2765.1503
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: corrupt saved block and another SID do not load; failures are visible without returning ciphertext or plaintext
|
||||
ok 25 - corrupt saved block and another SID do not load; failures are visible without returning ciphertext or plaintext
|
||||
---
|
||||
duration_ms: 2557.6793
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: legacy persistence requires a new explicit key and binds config and credential revisions; stale requests cannot save
|
||||
ok 26 - legacy persistence requires a new explicit key and binds config and credential revisions; stale requests cannot save
|
||||
---
|
||||
duration_ms: 2860.8784
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: owned plaintext keys never reach SQLite pages, WAL, config or public execution exports
|
||||
ok 27 - owned plaintext keys never reach SQLite pages, WAL, config or public execution exports
|
||||
---
|
||||
duration_ms: 1559.7853
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview
|
||||
ok 28 - reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview
|
||||
---
|
||||
duration_ms: 7011.4098
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries
|
||||
ok 29 - skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries
|
||||
---
|
||||
duration_ms: 3204.7375
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
|
||||
ok 30 - model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
|
||||
---
|
||||
duration_ms: 1030.049
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
|
||||
ok 31 - config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
|
||||
---
|
||||
duration_ms: 652.4551
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
|
||||
ok 32 - real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
|
||||
---
|
||||
duration_ms: 3311.3462
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
|
||||
ok 33 - pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
|
||||
---
|
||||
duration_ms: 4935.1345
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: 401 blocks the credential revision; updating the key restores availability without leaking error echoes
|
||||
ok 34 - 401 blocks the credential revision; updating the key restores availability without leaking error echoes
|
||||
---
|
||||
duration_ms: 1751.3549
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
|
||||
ok 35 - queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
|
||||
---
|
||||
duration_ms: 848.969
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
|
||||
ok 36 - compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
|
||||
---
|
||||
duration_ms: 2351.0678
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: model registry disk failures restore routing, pool profiles and credential references without partial updates
|
||||
ok 37 - model registry disk failures restore routing, pool profiles and credential references without partial updates
|
||||
---
|
||||
duration_ms: 697.6383
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: model selection and saved configuration commit together and failures preserve the original mode and endpoint
|
||||
ok 38 - model selection and saved configuration commit together and failures preserve the original mode and endpoint
|
||||
---
|
||||
duration_ms: 839.6094
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
|
||||
ok 39 - configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
|
||||
---
|
||||
duration_ms: 1058.2847
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: HTTP quota retains native code/type/param/request id, bounded original and allowlisted headers, never repeats that connection
|
||||
ok 40 - HTTP quota retains native code/type/param/request id, bounded original and allowlisted headers, never repeats that connection
|
||||
---
|
||||
duration_ms: 1734.2932
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Retry-After above 90 seconds remains exact and a short local budget cannot trigger an early retry
|
||||
ok 41 - Retry-After above 90 seconds remains exact and a short local budget cannot trigger an early retry
|
||||
---
|
||||
duration_ms: 1.8419
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Retry-After date, expired date, huge value and invalid header retain explicit semantics
|
||||
ok 42 - Retry-After date, expired date, huge value and invalid header retain explicit semantics
|
||||
---
|
||||
duration_ms: 1.262
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: unclassified 429 remains unspecified and every bounded actual retry retains its own original error
|
||||
ok 43 - unclassified 429 remains unspecified and every bounded actual retry retains its own original error
|
||||
---
|
||||
duration_ms: 1595.3746
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: oversized HTTP error saves exactly the bounded prefix and labels its incomplete range
|
||||
ok 44 - oversized HTTP error saves exactly the bounded prefix and labels its incomplete range
|
||||
---
|
||||
duration_ms: 1822.1821
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Chat SSE error preserves upstream fields, original failed event, partial tool and reported usage without executing or retrying
|
||||
ok 45 - Chat SSE error preserves upstream fields, original failed event, partial tool and reported usage without executing or retrying
|
||||
---
|
||||
duration_ms: 1489.9271
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Responses failed SSE retains original event/response identity and usage
|
||||
ok 46 - Responses failed SSE retains original event/response identity and usage
|
||||
---
|
||||
duration_ms: 1825.3615
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Responses incomplete SSE retains original event/response identity and usage
|
||||
ok 47 - Responses incomplete SSE retains original event/response identity and usage
|
||||
---
|
||||
duration_ms: 1915.8174
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: unsupported successful Responses output retains original JSON and usage with a local protocol origin
|
||||
ok 48 - unsupported successful Responses output retains original JSON and usage with a local protocol origin
|
||||
---
|
||||
duration_ms: 1422.0358
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: HTTP 200 native error is still an upstream failure rather than a fabricated successful answer
|
||||
ok 49 - HTTP 200 native error is still an upstream failure rather than a fabricated successful answer
|
||||
---
|
||||
duration_ms: 0.7854
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: JSON-escaped credential echoes are redacted in the original preview and capture as well as parsed fields
|
||||
ok 50 - JSON-escaped credential echoes are redacted in the original preview and capture as well as parsed fields
|
||||
---
|
||||
duration_ms: 0.6023
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: quota failover uses another independent pool member and never replays a failed stream
|
||||
ok 51 - quota failover uses another independent pool member and never replays a failed stream
|
||||
---
|
||||
duration_ms: 2581.7573
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: native parameters are isolated by pool member, preserve Responses state and bind the original output reservation
|
||||
ok 52 - native parameters are isolated by pool member, preserve Responses state and bind the original output reservation
|
||||
---
|
||||
duration_ms: 0.4212
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: unsupported native fields and invalid values reject before dispatch instead of silently dropping or overriding constraints
|
||||
ok 53 - unsupported native fields and invalid values reject before dispatch instead of silently dropping or overriding constraints
|
||||
---
|
||||
duration_ms: 0.4458
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: native settings for legacy and registered profiles persist without changing credentials or old records and reject stale edits
|
||||
ok 54 - native settings for legacy and registered profiles persist without changing credentials or old records and reject stale edits
|
||||
---
|
||||
duration_ms: 1104.5619
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: compiled native settings API saves/restores exact parameters and rejects reserved fields without mutating the profile
|
||||
ok 55 - compiled native settings API saves/restores exact parameters and rejects reserved fields without mutating the profile
|
||||
---
|
||||
duration_ms: 2401.8094
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: legacy connection test sends its saved native fields and selected output limit field without changing the configuration
|
||||
ok 56 - legacy connection test sends its saved native fields and selected output limit field without changing the configuration
|
||||
---
|
||||
duration_ms: 2455.9815
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: identity distinguishes missing, invalid, mixed, exact and explicitly declared aliases without guessing
|
||||
ok 57 - identity distinguishes missing, invalid, mixed, exact and explicitly declared aliases without guessing
|
||||
---
|
||||
duration_ms: 1.1596
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: chat-completions JSON rejects a different model before tool dispatch, retaining source and reported usage
|
||||
ok 58 - chat-completions JSON rejects a different model before tool dispatch, retaining source and reported usage
|
||||
---
|
||||
duration_ms: 1365.4853
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: chat-completions SSE rejects a different model before tool dispatch, retaining source and reported usage
|
||||
ok 59 - chat-completions SSE rejects a different model before tool dispatch, retaining source and reported usage
|
||||
---
|
||||
duration_ms: 1835.3514
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: responses JSON rejects a different model before tool dispatch, retaining source and reported usage
|
||||
ok 60 - responses JSON rejects a different model before tool dispatch, retaining source and reported usage
|
||||
---
|
||||
duration_ms: 1508.9017
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: responses SSE rejects a different model before tool dispatch, retaining source and reported usage
|
||||
ok 61 - responses SSE rejects a different model before tool dispatch, retaining source and reported usage
|
||||
---
|
||||
duration_ms: 1956.1724
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: record policy accepts missing identity but keeps it explicit, and strict declared mapping is frozen in the consumption
|
||||
ok 62 - record policy accepts missing identity but keeps it explicit, and strict declared mapping is frozen in the consumption
|
||||
---
|
||||
duration_ms: 1.228
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: mixed streamed identities cannot pass strict mode, and interrupted streams retain observed identifiers without authenticating them
|
||||
ok 63 - mixed streamed identities cannot pass strict mode, and interrupted streams retain observed identifiers without authenticating them
|
||||
---
|
||||
duration_ms: 1.1753
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: identity refusal never fails over to another pool member and raw response model cannot leak known credentials
|
||||
ok 64 - identity refusal never fails over to another pool member and raw response model cannot leak known credentials
|
||||
---
|
||||
duration_ms: 2046.6202
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: strict refusal remains visible even when the same original response exhausts the budget
|
||||
ok 65 - strict refusal remains visible even when the same original response exhausts the budget
|
||||
---
|
||||
duration_ms: 1729.4053
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: strict identity crosses the controlled engine bridge with its original source and zero tool dispatch
|
||||
ok 66 - strict identity crosses the controlled engine bridge with its original source and zero tool dispatch
|
||||
---
|
||||
duration_ms: 13176.6319
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: frozen direct connection policy and delivery reports preserve response identity without filling historical gaps
|
||||
ok 67 - frozen direct connection policy and delivery reports preserve response identity without filling historical gaps
|
||||
---
|
||||
duration_ms: 2296.6171
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: saved engine budgets verify all Chat/Responses route variants and reject a mismatched output allowance
|
||||
ok 68 - saved engine budgets verify all Chat/Responses route variants and reject a mismatched output allowance
|
||||
---
|
||||
duration_ms: 956.3865
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: owned CC Switch SQLite imports the selected TOML Responses wire_api and leaves unknown clients untouched
|
||||
ok 69 - owned CC Switch SQLite imports the selected TOML Responses wire_api and leaves unknown clients untouched
|
||||
---
|
||||
duration_ms: 1096.3097
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Responses executes one original tool through Runtime, carries encrypted Items, reports raw usage and seals exact wire bytes
|
||||
ok 70 - Responses executes one original tool through Runtime, carries encrypted Items, reports raw usage and seals exact wire bytes
|
||||
---
|
||||
duration_ms: 3329.3592
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: mixed-protocol pool keeps both actual variants and changes route on 429 without re-executing completed tools
|
||||
ok 71 - mixed-protocol pool keeps both actual variants and changes route on 429 without re-executing completed tools
|
||||
---
|
||||
duration_ms: 2821.0439
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Responses incomplete, failed, missing call identity and unsupported hosted outputs never dispatch a tool
|
||||
# Subtest: Reject {"body":{"id":"resp_owned","status":"incomplete","output":[{"type":"function_call","id":"fc_partial"
|
||||
ok 1 - Reject {"body":{"id":"resp_owned","status":"incomplete","output":[{"type":"function_call","id":"fc_partial"
|
||||
---
|
||||
duration_ms: 1321.9313
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Reject {"body":{"id":"resp_owned","status":"failed","output":[{"type":"function_call","id":"fc_failed","cal
|
||||
ok 2 - Reject {"body":{"id":"resp_owned","status":"failed","output":[{"type":"function_call","id":"fc_failed","cal
|
||||
---
|
||||
duration_ms: 1317.7458
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Reject {"body":{"id":"resp_owned","status":"completed","output":[{"type":"function_call","id":"fc_bad","cal
|
||||
ok 3 - Reject {"body":{"id":"resp_owned","status":"completed","output":[{"type":"function_call","id":"fc_bad","cal
|
||||
---
|
||||
duration_ms: 1110.8779
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Reject {"body":{"id":"resp_owned","status":"completed","output":[{"type":"computer_call","id":"not-supporte
|
||||
ok 4 - Reject {"body":{"id":"resp_owned","status":"completed","output":[{"type":"computer_call","id":"not-supporte
|
||||
---
|
||||
duration_ms: 1147.099
|
||||
type: 'test'
|
||||
...
|
||||
1..4
|
||||
ok 72 - Responses incomplete, failed, missing call identity and unsupported hosted outputs never dispatch a tool
|
||||
---
|
||||
duration_ms: 4898.4132
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: invalid JSON in a nonstream Chat or Responses tool group prevents every tool and pool replay
|
||||
# Subtest: chat-completions
|
||||
ok 1 - chat-completions
|
||||
---
|
||||
duration_ms: 1246.8546
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: responses
|
||||
ok 2 - responses
|
||||
---
|
||||
duration_ms: 1307.3013
|
||||
type: 'test'
|
||||
...
|
||||
1..2
|
||||
ok 73 - invalid JSON in a nonstream Chat or Responses tool group prevents every tool and pool replay
|
||||
---
|
||||
duration_ms: 2554.5352
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: wire adapter preserves tool IDs but never passes Responses-private Items to Chat or another endpoint
|
||||
ok 74 - wire adapter preserves tool IDs but never passes Responses-private Items to Chat or another endpoint
|
||||
---
|
||||
duration_ms: 0.2115
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: connection JSON import accepts explicit Responses protocol and continues to reject unknown protocols without reading client sessions
|
||||
ok 75 - connection JSON import accepts explicit Responses protocol and continues to reject unknown protocols without reading client sessions
|
||||
---
|
||||
duration_ms: 407.7425
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: selected connection owns the actual endpoint, credential, wire model and mismatch even when legacy is configured for GPT
|
||||
ok 76 - selected connection owns the actual endpoint, credential, wire model and mismatch even when legacy is configured for GPT
|
||||
---
|
||||
duration_ms: 2744.172
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: budget-only API and demo/real selection preserve routes, reject injected endpoint fields and publish authoritative selection without keys
|
||||
ok 77 - budget-only API and demo/real selection preserve routes, reject injected endpoint fields and publish authoritative selection without keys
|
||||
---
|
||||
duration_ms: 2719.5196
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: another session cannot change default model, mode or budgets while a request is active
|
||||
ok 78 - another session cannot change default model, mode or budgets while a request is active
|
||||
---
|
||||
duration_ms: 4127.854
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: HTTP download preserves original malformed SSE bytes and artifact SHA instead of decoding invalid UTF8
|
||||
ok 79 - HTTP download preserves original malformed SSE bytes and artifact SHA instead of decoding invalid UTF8
|
||||
---
|
||||
duration_ms: 2269.6883
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: terminated SSE adapts empty optional tool arguments, retains the exact wire bytes and executes the validated batch once
|
||||
ok 80 - terminated SSE adapts empty optional tool arguments, retains the exact wire bytes and executes the validated batch once
|
||||
---
|
||||
duration_ms: 3384.9583
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reported SSE usage survives rejected required arguments "" without dispatching any tool
|
||||
ok 81 - reported SSE usage survives rejected required arguments "" without dispatching any tool
|
||||
---
|
||||
duration_ms: 1690.3296
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reported SSE usage survives rejected required arguments "{\\"path\\":" without dispatching any tool
|
||||
ok 82 - reported SSE usage survives rejected required arguments "{\\"path\\":" without dispatching any tool
|
||||
---
|
||||
duration_ms: 1715.0265
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reported SSE usage survives rejected required arguments "null" without dispatching any tool
|
||||
ok 83 - reported SSE usage survives rejected required arguments "null" without dispatching any tool
|
||||
---
|
||||
duration_ms: 1769.2733
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a stream without DONE retains reported usage but cannot adapt or execute even an optional tool
|
||||
ok 84 - a stream without DONE retains reported usage but cannot adapt or execute even an optional tool
|
||||
---
|
||||
duration_ms: 1866.0212
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a timeout after reasoning-only fragments creates one unknown receipt and never invents reported tokens
|
||||
ok 85 - a timeout after reasoning-only fragments creates one unknown receipt and never invents reported tokens
|
||||
---
|
||||
duration_ms: 1973.0335
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: real Chat SSE carries UTF8 and split tool JSON; Runtime executes only after DONE, stores partial progress and original usage
|
||||
ok 86 - real Chat SSE carries UTF8 and split tool JSON; Runtime executes only after DONE, stores partial progress and original usage
|
||||
---
|
||||
duration_ms: 2625.4612
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: Responses typed SSE validates original item identity, terminal data, raw usage and tool result pair
|
||||
ok 87 - Responses typed SSE validates original item identity, terminal data, raw usage and tool result pair
|
||||
---
|
||||
duration_ms: 3083.8092
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: incomplete network stream retains unknown attempt and never automatically switches pool or dispatches fragment tools
|
||||
ok 88 - incomplete network stream retains unknown attempt and never automatically switches pool or dispatches fragment tools
|
||||
---
|
||||
duration_ms: 2045.9562
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: stopping an active HTTP stream closes only original request and keeps partial text without executing tools
|
||||
ok 89 - stopping an active HTTP stream closes only original request and keeps partial text without executing tools
|
||||
---
|
||||
duration_ms: 1844.2155
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: explicit streaming probe uses actual SSE despite unknown declaration and binds its own original attempt
|
||||
ok 90 - explicit streaming probe uses actual SSE despite unknown declaration and binds its own original attempt
|
||||
---
|
||||
duration_ms: 735.0531
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: coalesced initial SSE events publish the latest partial state even when the upstream stays idle
|
||||
ok 91 - coalesced initial SSE events publish the latest partial state even when the upstream stays idle
|
||||
---
|
||||
duration_ms: 1605.6682
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: stream timeout closes the original HTTP response, preserves redacted capture and never retries
|
||||
ok 92 - stream timeout closes the original HTTP response, preserves redacted capture and never retries
|
||||
---
|
||||
duration_ms: 973.7462
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: stream idle timeout preserves incomplete tool arguments, records unknown use and never fails over
|
||||
ok 93 - stream idle timeout preserves incomplete tool arguments, records unknown use and never fails over
|
||||
---
|
||||
duration_ms: 1301.3233
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: SSE accepts CR-only final event boundaries and retains exact invalid UTF8 bytes without dispatch
|
||||
ok 94 - SSE accepts CR-only final event boundaries and retains exact invalid UTF8 bytes without dispatch
|
||||
---
|
||||
duration_ms: 1.0156
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data
|
||||
# Subtest: reject 0
|
||||
ok 1 - reject 0
|
||||
---
|
||||
duration_ms: 0.2593
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject 1
|
||||
ok 2 - reject 1
|
||||
---
|
||||
duration_ms: 0.2064
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject 2
|
||||
ok 3 - reject 2
|
||||
---
|
||||
duration_ms: 0.1693
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject 3
|
||||
ok 4 - reject 3
|
||||
---
|
||||
duration_ms: 5.0898
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject 4
|
||||
ok 5 - reject 4
|
||||
---
|
||||
duration_ms: 0.1654
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reject 5
|
||||
ok 6 - reject 5
|
||||
---
|
||||
duration_ms: 0.1639
|
||||
type: 'test'
|
||||
...
|
||||
1..6
|
||||
ok 95 - stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data
|
||||
---
|
||||
duration_ms: 6.5948
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: unchanged proposals cannot hide repeated original-log reads or identical session inspections
|
||||
ok 96 - unchanged proposals cannot hide repeated original-log reads or identical session inspections
|
||||
---
|
||||
duration_ms: 6175.221
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: reusing a verified proof never resets identical-state detection or creates a new proof
|
||||
ok 97 - reusing a verified proof never resets identical-state detection or creates a new proof
|
||||
---
|
||||
duration_ms: 5341.2147
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation
|
||||
ok 98 - coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation
|
||||
---
|
||||
duration_ms: 0.7634
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: continuation reads advance through historical pages without a false pause while repeated current-Run pages still pause
|
||||
ok 99 - continuation reads advance through historical pages without a false pause while repeated current-Run pages still pause
|
||||
---
|
||||
duration_ms: 1.755
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a new tool page replaces old latest-feedback space and still obeys its escaped protocol budget
|
||||
ok 100 - a new tool page replaces old latest-feedback space and still obeys its escaped protocol budget
|
||||
---
|
||||
duration_ms: 0.4075
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: budgeted artifact pages count escaped protocol bytes and reconstruct original multilingual JSON without losing characters
|
||||
ok 101 - budgeted artifact pages count escaped protocol bytes and reconstruct original multilingual JSON without losing characters
|
||||
---
|
||||
duration_ms: 9.8117
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: known artifact coverage detects semantic repeats despite changing limits, and advancing pages or direct evidence restore progress
|
||||
ok 102 - known artifact coverage detects semantic repeats despite changing limits, and advancing pages or direct evidence restore progress
|
||||
---
|
||||
duration_ms: 0.3566
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual large artifact reads are present in the next bounded HTTP request and next_offset progresses without redoing tools
|
||||
ok 103 - actual large artifact reads are present in the next bounded HTTP request and next_offset progresses without redoing tools
|
||||
---
|
||||
duration_ms: 5080.8005
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a real repeated artifact loop pauses the same Task after recorded results, survives reload and only resumes explicitly
|
||||
ok 104 - a real repeated artifact loop pauses the same Task after recorded results, survives reload and only resumes explicitly
|
||||
---
|
||||
duration_ms: 6371.7039
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual HTTP continuation after reload sends distinct historically covered pages without false no_progress or replay
|
||||
ok 105 - actual HTTP continuation after reload sends distinct historically covered pages without false no_progress or replay
|
||||
---
|
||||
duration_ms: 6090.8734
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing
|
||||
ok 106 - hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing
|
||||
---
|
||||
duration_ms: 1288.8947
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: failed adoption restores the original virtual data-root name and original open database
|
||||
ok 107 - failed adoption restores the original virtual data-root name and original open database
|
||||
---
|
||||
duration_ms: 610.8265
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
|
||||
ok 108 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
|
||||
---
|
||||
duration_ms: 826.7938
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails
|
||||
ok 109 - hot upgrade refuses active probes and restores retained model methods if installation fails
|
||||
---
|
||||
duration_ms: 613.2784
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: small code and actual failed command stay visible when their original multi-tool group cannot fit
|
||||
ok 110 - small code and actual failed command stay visible when their original multi-tool group cannot fit
|
||||
---
|
||||
duration_ms: 1620.537
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: mixed group retains six distinct small file observations with exact multilingual text and bounded request bytes
|
||||
ok 111 - mixed group retains six distinct small file observations with exact multilingual text and bounded request bytes
|
||||
---
|
||||
duration_ms: 1489.4609
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: working observations are bound to the current Task and stop treating a pre-application file revision as current evidence
|
||||
ok 112 - working observations are bound to the current Task and stop treating a pre-application file revision as current evidence
|
||||
---
|
||||
duration_ms: 1572.9737
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a sealed observation rejects changed or missing original result artifacts instead of recreating evidence
|
||||
ok 113 - a sealed observation rejects changed or missing original result artifacts instead of recreating evidence
|
||||
---
|
||||
duration_ms: 923.4633
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a real passed-check observation is excluded after a source edit invalidates the check, while its historical sent evidence remains valid
|
||||
ok 114 - a real passed-check observation is excluded after a source edit invalidates the check, while its historical sent evidence remains valid
|
||||
---
|
||||
duration_ms: 4694.0926
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: budgeted file pages reconstruct UTF-8 text including long single lines and surrogate boundaries
|
||||
ok 115 - budgeted file pages reconstruct UTF-8 text including long single lines and surrogate boundaries
|
||||
---
|
||||
duration_ms: 4.2055
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual HTTP multi-tool reads survive an oversized runtime snapshot and the sealed evidence survives reopening
|
||||
ok 116 - actual HTTP multi-tool reads survive an oversized runtime snapshot and the sealed evidence survives reopening
|
||||
---
|
||||
duration_ms: 7874.5197
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual HTTP file pagination advances over a long file with each returned page visible in the next request
|
||||
ok 117 - actual HTTP file pagination advances over a long file with each returned page visible in the next request
|
||||
---
|
||||
duration_ms: 6669.2798
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: later mixed history pages cannot displace the actual module sources and complete requirements
|
||||
ok 118 - later mixed history pages cannot displace the actual module sources and complete requirements
|
||||
---
|
||||
duration_ms: 4168.9163
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a later narrow page of the same file revision cannot evict the wider actual observation
|
||||
ok 119 - a later narrow page of the same file revision cannot evict the wider actual observation
|
||||
---
|
||||
duration_ms: 2242.2088
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: six small source files stay complete across metadata turns even when mandatory evidence exceeds the soft target
|
||||
ok 120 - six small source files stay complete across metadata turns even when mandatory evidence exceeds the soft target
|
||||
---
|
||||
duration_ms: 2292.2594
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: historical read-artifact navigation points to the original artifact and next page, never its result wrapper
|
||||
ok 121 - historical read-artifact navigation points to the original artifact and next page, never its result wrapper
|
||||
---
|
||||
duration_ms: 815.6616
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: a 1.6.1 full-provenance sent view remains verifiable after introducing the compact view
|
||||
ok 122 - a 1.6.1 full-provenance sent view remains verifiable after introducing the compact view
|
||||
---
|
||||
duration_ms: 908.6299
|
||||
type: 'test'
|
||||
...
|
||||
# Subtest: actual HTTP requests keep four observed modules after a later large history read and preserve all source bytes
|
||||
ok 123 - actual HTTP requests keep four observed modules after a later large history read and preserve all source bytes
|
||||
---
|
||||
duration_ms: 8758.8091
|
||||
type: 'test'
|
||||
...
|
||||
1..123
|
||||
# tests 144
|
||||
# suites 0
|
||||
# pass 144
|
||||
# fail 0
|
||||
# cancelled 0
|
||||
# skipped 0
|
||||
# todo 0
|
||||
# duration_ms 141616.0072
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"sourceKind": "direct user reply in this conversation",
|
||||
"quote": "哈哈哈,是我的错,我把模型写错了,确实属于gpt分组的,确实是 gpt模型,抱歉,让你查了这么久。那你要把复查这个链路问题做的很多检修的内容要看看,别因为我的错误,把很多正确的,改成错的了。你认真的回查这个过程",
|
||||
"interpretation": "User confirms GPT group and incorrect Claude model label; review previous changes and correct the diagnosis. This does not independently authenticate the underlying model weights.",
|
||||
"messageId": null,
|
||||
"receivedAt": null,
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Read-only verification of sealed evidence, never replay the historical drivers.
|
||||
const directory = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repository = path.resolve(directory, '../..');
|
||||
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const json = async relative => JSON.parse(await fs.readFile(path.join(directory, relative), 'utf8'));
|
||||
const manifest = await json('manifest.json');
|
||||
const checked = new Set();
|
||||
let bytes = 0;
|
||||
for (const entry of manifest.files) {
|
||||
assert.ok(!path.isAbsolute(entry.path) && !entry.path.split(/[\\/]/).includes('..'));
|
||||
assert.ok(!checked.has(entry.path));
|
||||
const actual = await fs.readFile(path.join(directory, entry.path));
|
||||
assert.equal(actual.length, entry.bytes, entry.path);
|
||||
assert.equal(hash(actual), entry.sha256, entry.path);
|
||||
checked.add(entry.path);
|
||||
bytes += actual.length;
|
||||
}
|
||||
async function walk(relative = '') {
|
||||
const files = [];
|
||||
for (const entry of await fs.readdir(path.join(directory, relative), { withFileTypes: true })) {
|
||||
const name = relative ? `${relative}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) files.push(...await walk(name));
|
||||
else { assert.ok(entry.isFile(), name); files.push(name); }
|
||||
}
|
||||
return files;
|
||||
}
|
||||
assert.deepEqual((await walk()).filter(name => name !== 'manifest.json').sort(), [...checked].sort());
|
||||
assert.equal(bytes, manifest.bytes);
|
||||
for (const binding of manifest.existingEvidenceBindings) {
|
||||
assert.equal(hash(await fs.readFile(path.join(repository, binding.path))), binding.sha256, binding.path);
|
||||
}
|
||||
|
||||
const compatibility = await json('results/gpt-compatibility.json');
|
||||
assert.equal(compatibility.passed, true);
|
||||
assert.equal(compatibility.realModelRequests, 0);
|
||||
assert.equal(compatibility.baselineRequestComparisons, 34);
|
||||
assert.equal(compatibility.identityComparisons, 24);
|
||||
assert.equal(compatibility.comparisons.length, 2);
|
||||
for (const comparison of compatibility.comparisons) {
|
||||
assert.equal(comparison.cases.length, 17);
|
||||
for (const item of comparison.cases) {
|
||||
assert.equal(item.equalRequestBytes, true);
|
||||
assert.equal(item.equalMetrics, true);
|
||||
}
|
||||
for (const binding of comparison.bindings) {
|
||||
assert.equal(hash(await fs.readFile(path.join(directory, 'baseline', comparison.ref, binding.path))), binding.beforeSha256);
|
||||
}
|
||||
}
|
||||
assert.equal(compatibility.identities.length, 24);
|
||||
for (const item of compatibility.identities.filter(item => item.configuredPolicy === 'default')) {
|
||||
assert.equal(item.result.policy, 'record');
|
||||
}
|
||||
|
||||
const source = await json('results/source-integrity.json');
|
||||
assert.equal(source.passed, true);
|
||||
assert.equal(source.sourceFiles, 220);
|
||||
assert.equal(source.actualSourceFiles, 220);
|
||||
assert.deepEqual(source.extraPaths, []);
|
||||
assert.equal(source.results.length, 220);
|
||||
const freeze = JSON.parse(await fs.readFile(path.join(repository, source.freezePath), 'utf8'));
|
||||
const frozenSource = freeze.files.filter(entry => entry.path.startsWith('src/'));
|
||||
assert.equal(frozenSource.length, 220);
|
||||
for (const item of source.results) {
|
||||
const frozen = frozenSource.find(entry => entry.path === item.path);
|
||||
assert.ok(frozen);
|
||||
assert.equal(item.passed, true);
|
||||
assert.equal(item.sha256, frozen.sha256);
|
||||
assert.equal(item.actualSha256, item.sha256);
|
||||
assert.equal(item.actualBytes, item.bytes);
|
||||
}
|
||||
for (const comparison of compatibility.comparisons) {
|
||||
for (const binding of comparison.bindings) {
|
||||
assert.equal(source.results.find(entry => entry.path === binding.path)?.sha256, binding.currentSha256);
|
||||
}
|
||||
}
|
||||
const regression = await json('results/regression-summary.json');
|
||||
const logBytes = await fs.readFile(path.join(directory, 'results/regression.tap'));
|
||||
const log = logBytes.toString(regression.encoding).replace(/^\uFEFF/, '');
|
||||
assert.equal(regression.testFiles.length, 13);
|
||||
for (const [name, expected] of Object.entries({ tests: 144, pass: 144, fail: 0, cancelled: 0, skipped: 0, todo: 0 })) {
|
||||
assert.ok(new RegExp(`^# ${name} ${expected}\\r?$`, 'm').test(log), name);
|
||||
}
|
||||
assert.equal(regression.realModelRequests, 0);
|
||||
const redirects = await json('results/gpt-redirect-audit.json');
|
||||
assert.equal(redirects.passed, true);
|
||||
assert.equal(redirects.results.length, 2);
|
||||
for (const item of redirects.results) {
|
||||
assert.equal(item.passed, true);
|
||||
assert.equal(item.originRequests, 1);
|
||||
assert.equal(item.targetRequests, 0);
|
||||
assert.equal(item.responseStatus, 307);
|
||||
assert.equal(item.redirectMode, 'manual');
|
||||
assert.ok(item.requestUrl.startsWith('http://127.0.0.1:'));
|
||||
}
|
||||
|
||||
const before = await json('configuration/correction-before.json');
|
||||
const saved = await json('configuration/correction-response.json');
|
||||
const after = await json('configuration/correction-result.json');
|
||||
assert.equal(after.passed, true);
|
||||
assert.deepEqual(after.connection, saved);
|
||||
assert.equal(before.connection.revision, 10);
|
||||
assert.equal(after.connection.revision, 11);
|
||||
assert.equal(before.connection.enabled, false);
|
||||
assert.equal(after.connection.enabled, false);
|
||||
assert.equal(after.connection.credentialRevision, before.connection.credentialRevision);
|
||||
assert.equal(after.connection.credentialRevision, 2);
|
||||
assert.equal(after.connection.model, 'gpt-6.1-sol');
|
||||
assert.equal(after.connection.protocol, 'responses');
|
||||
assert.equal(after.requestUrl, 'https://api.apikey.fan/v1/responses');
|
||||
assert.equal(after.connection.modelIdentityPolicy, 'record');
|
||||
assert.deepEqual(after.connection.modelIdentityAliases, []);
|
||||
assert.equal(after.realModelRequests, 0);
|
||||
assert.equal(after.totalConfigurationPOSTs, 1);
|
||||
assert.equal(after.credentialValuesReadOrSaved, false);
|
||||
for (const field of ['contextLimit', 'maxOutputTokens', 'concurrency', 'streaming', 'capabilityDeclarations', 'savedCredential']) {
|
||||
assert.deepEqual(after.connection[field], before.connection[field], field);
|
||||
}
|
||||
assert.equal(after.firstGuard.stoppedBeforePOST, true);
|
||||
assert.equal(after.firstPostAudit.configurationPOSTWasNotReplayed, true);
|
||||
assert.equal(after.unarchivedSessions, 62);
|
||||
assert.equal(after.visibleAttempts, 100);
|
||||
const currentExport = await json('configuration/correction-export-current.json');
|
||||
const originalMExport = JSON.parse(await fs.readFile(path.join(repository, 'docs/messages-m-evidence/live/export.json'), 'utf8'));
|
||||
const normalized = value => { const result = structuredClone(value); delete result.exportedAt; return result; };
|
||||
assert.deepEqual(normalized(currentExport), normalized(originalMExport));
|
||||
const normalizedHash = hash(JSON.stringify(normalized(currentExport)));
|
||||
assert.equal(normalizedHash, after.exportVerification.normalizedFingerprint);
|
||||
assert.equal(normalizedHash, after.exportVerification.sealedMNormalizedFingerprint);
|
||||
assert.equal(hash(JSON.stringify({ ...currentExport, exportedAt: after.exportVerification.matchedBeforeAt })), before.fingerprints.originalMExport);
|
||||
|
||||
const sources = await json('public/selected-sources.json');
|
||||
assert.equal(sources.upstreamCommit, '4a4a83ee5ec86b19d3a2dd9b6471de5128963bec');
|
||||
for (const entry of sources.files) {
|
||||
const actual = await fs.readFile(path.join(directory, entry.evidencePath));
|
||||
assert.equal(hash(actual), entry.sha256);
|
||||
assert.equal(createHash('sha1').update(Buffer.from(`blob ${actual.length}\0`)).update(actual).digest('hex'), entry.expectedGitBlob);
|
||||
assert.equal(entry.treeMatched, true);
|
||||
}
|
||||
console.log(JSON.stringify({ passed: true, evidenceFiles: checked.size, evidenceBytes: bytes,
|
||||
manifestSha256: hash(await fs.readFile(path.join(directory, 'manifest.json'))),
|
||||
regressionTests: 144, baselineRequestComparisons: 34, identityComparisons: 24,
|
||||
sourceFiles: 220, localhostRedirectCases: 2, configurationPOSTs: 1, realModelRequests: 0,
|
||||
enabled: false, credentialRevision: 2, oldMManifestUnchanged: true,
|
||||
scope: 'Read-only verification of sealed N evidence and original M bindings; no driver, test, API, model, restart, credential or configuration replay.' }, null, 2));
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"passed": true,
|
||||
"evidenceFiles": 52,
|
||||
"evidenceBytes": 650216,
|
||||
"manifestSha256": "d6f1dd8602d194758fc2423ba347cd7416441aef6a55c3411ff6a5285e1de731",
|
||||
"regressionTests": 144,
|
||||
"baselineRequestComparisons": 34,
|
||||
"identityComparisons": 24,
|
||||
"sourceFiles": 220,
|
||||
"localhostRedirectCases": 2,
|
||||
"configurationPOSTs": 1,
|
||||
"realModelRequests": 0,
|
||||
"enabled": false,
|
||||
"credentialRevision": 2,
|
||||
"oldMManifestUnchanged": true,
|
||||
"scope": "Read-only verification of sealed N evidence and original M bindings; no driver, test, API, model, restart, credential or configuration replay."
|
||||
}
|
||||
+10
@@ -1,5 +1,15 @@
|
||||
# 汇总发现
|
||||
|
||||
## N:用户确认GPT分组后的复查结论
|
||||
|
||||
用户明确确认apikey属于GPT分组,原型号误填Claude;结束供应商Claude故障推断。公开Sub2API固定提交4a4a83ee证明按Key分组、Messages转Responses及分组/渠道/账号映射机制存在,但不能认证供应商生产版本、私有映射或模型权重。保留原J/M请求与GPT响应,新增更正而不改历史证据。
|
||||
|
||||
回查没有发现需回滚的产品代码。I的交付/防空转与型号记录、K统一模型入口/预算不改路由、M独立Messages、长路径及升级兼容修复均保留。实际模块与I前/M前34组GPT请求字节/预算相同、24组型号观察相同、默认record;相关13文件144/144通过。220份src实际SHA与M冻结相同。另两组实际localhost Chat/Responses 307证明M的manual redirect是跨协议行为变化:不重放POST、不向跳转目标转发凭据;需要正确终点,不能说所有运输行为全同旧版。
|
||||
|
||||
apikey仅更正为GPT兼容代理/gpt-6.1-sol/Responses、/v1与record;无别名,原上下文16K/输出2048/并发8不变。外部已停用(9→10),首驱动在POST前拒绝;唯一保存10→11并保留停用,凭据修订仍2,其它连接/默认池/全局配置保持。核对范围为项目/62未归档摘要/最近100条展示账本/事件游标及原M完整导出,不冒充全库或全部工件重审。原保存块source_changed此前已存在,本轮不读/重存Key,不认证重启后可恢复。
|
||||
|
||||
配置保存后的首校验误把动态exportedAt纳入内容哈希,保留失败驱动,未重放POST;仅替换生成时间即可匹配保存前指纹,其余字段与M封存导出完整相等。正式程序1.24.4/原PID36552保持,本轮真实模型与远程凭据请求0。下一在明确启用的GPT连接另开有界预检和新工程/Purge,不续跑旧任务;真实交付与收益仍未证明。
|
||||
|
||||
## L:Claude接入的协议缺口
|
||||
|
||||
原J的GPT标识存在于无脱敏原SSE,所选Claude请求SHA、poolId=null和单请求账本保持。八份源码等于正式1.24.3冻结输入,Provider直接JSON派发选中body,型号观察器读原事件model,没有legacy默认回填;三组真实localhost回放核对通过。供应商公开API教程分别给出GPT的/v1/chat/completions与Claude的/v1/messages;原连接域名根+/chat/completions与其示例不同,工作台目前只有Chat/Responses没有Messages适配。这是已确认能力缺口;没有证明Chat完全不支持Claude、缺/v1是唯一原因或Key属于哪个分组,更不能认证底层GPT权重。下一优先原生Messages适配和实际URL可见,再另开单次新身份预检。最终37份证据离线通过,正式数据与连接精确保持,本轮真实模型请求0,见docs/APIKEY-ROUTE-L-INVESTIGATION.md。
|
||||
|
||||
+12
@@ -1,5 +1,17 @@
|
||||
# 统一执行进度
|
||||
|
||||
## N:误配置确认后的实现回查与配置更正
|
||||
|
||||
用户确认apikey密钥属于GPT分组,原Claude名称填错,要求认真复查此前检修。M报告/原件已独立提交860a191b;本轮保留所有历史,未委派子代理、未重启宿主、未读/复制/解密/重存Key,也未发真实模型请求。
|
||||
|
||||
实际模块对照I前410b3478/M前b832982d:34组Chat/Responses请求字节与预算、24组型号观察完全一致;13文件144/144相关回归通过。220份src与正式M冻结SHA逐项一致,原M manifest仍为c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7。两个真实localhost 307场景确认原端各1请求、跳转目标各0,明确保留M跨协议manual redirect限制。产品源码无新增改动,I/K/M真实修复保留。
|
||||
|
||||
外部操作先将apikey停用,修订9→10,首纠正驱动在任何POST前拒绝;以修订10为基线只保存一次,校正为GPT兼容代理/gpt-6.1-sol/Responses/record,修订11、凭据2且仍停用。其它连接、默认高性能池/选择、全局配置、项目/62未归档摘要/最近100条展示账本和事件游标保持;原M完整导出仅生成时间变化。首驱动把exportedAt当存储内容比较导致误报,后续只读核对已通过,未重放配置写入。不是全库/全工件复验。
|
||||
|
||||
已更正AGENTS当前结论、J/L/M报告、J后续计划及验证记录,保留原失败。N的52份/650216字节来源、结果与历史驱动文本已封存,manifest d6f1dd8602d194758fc2423ba347cd7416441aef6a55c3411ff6a5285e1de731及原M绑定离线核对通过,本地Git只收尾本次范围。下一真实实验先明确启用的GPT连接和实际16K条件,不自动启用apikey,不用旧预检或夹具结果冒充工程/Purge通过。
|
||||
|
||||
收尾说明的首个多文件补丁因VALIDATION实际锚点不同而整批拒绝,核对无部分变更后按真实段落修正;不涉及产品代码、运行配置或封存原件。
|
||||
|
||||
## L:按用户要求继续调查apikey线路
|
||||
|
||||
基线cd5af2eb/正式1.24.3。已读取J原attempt与SSE:上游原字节直接标记GPT,poolId=null/单请求且严格暂停;继续核对底层URL拼接与供应商公开说明,尚不重发真实请求或变更正式配置。沿用planning-with-files记录,未启用子代理。两个Windows rg通配参数和一处猜测文件名只读失败已改为实际目录/文件,原件不变。
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
# Agent Workbench:核心代理能力研究与产品计划
|
||||
|
||||
## 当前 N:用户确认GPT分组后,回查诊断与改动
|
||||
|
||||
用户已确认apikey实际属于GPT分组,原请求误填Claude;不能再将该现象当成供应商Claude故障。M证据已独立提交860a191b。回查I/K/M相关实现和配置,保留真实历史;本轮真实模型请求预算为0,不重启原进程、不读取/复制Key、不重跑旧任务。
|
||||
|
||||
1. [complete] M原件/选线与公开网关源码已核对:存在按Key分组转发及渠道/账号映射,Messages接口本身不认证Claude;生产版本/映射规则未认证。用户进一步确认这是GPT分组的错误型号配置,结束供应商故障推断。
|
||||
2. [complete] I前/M前与当前实际模块的34组GPT请求字节及预算、24组型号观察一致;13文件144/144相关回归通过。220份src与正式M冻结SHA一致,保留I/K/M及独立发行修复;两个实际localhost 307场景确认跨协议manual redirect行为,不能声称运输行为全同旧版。
|
||||
3. [complete] 只校正apikey为GPT兼容代理/gpt-6.1-sol/Responses/record,无别名;外部已停用,首驱动因修订9→10在POST前拒绝。唯一保存修订10→11,停用保持、凭据修订2不变。其它连接/默认池/全局配置、项目/62未归档摘要/最近100条展示账本/事件游标精确保持;原M导出仅生成时间不同。误比exportedAt的首失败保留,后续只读核对通过,没有重复保存。
|
||||
4. [complete] 当前结论、J计划与J/L/M历史报告已加更正;N的52份/650216字节材料及原M绑定离线核对通过,历史驱动仅文本封存,本地提交身份见本阶段Git记录。不整体回滚有效修复,不修改旧SSE/预检结果或已安装发行,工程/Purge仍按实际结果判定。本轮真实模型请求0。
|
||||
|
||||
## 当前 M:原生 Anthropic Messages 与实际线路诊断
|
||||
|
||||
沿用 planning-with-files、product-ui-ux 与 frontend-design;仅修改本次接入流程,不委派子代理。基线 b832982d,分支 feat/anthropic-messages-1.24.4。保留原正式宿主、Provider、内存凭据及 J/K/L 原件,不续跑旧任务。
|
||||
|
||||
Reference in New Issue
Block a user