From a77bc9810b19d796b9e2417e64b9bcce1db5b998 Mon Sep 17 00:00:00 2001 From: Agent Workbench Dev Date: Tue, 3 Nov 2026 20:44:08 +0800 Subject: [PATCH] docs: audit routing changes after confirmed GPT configuration error --- AGENTS.md | 10 +- CHANGELOG.md | 2 + docs/APIKEY-ROUTE-L-INVESTIGATION.md | 2 + docs/LIVE-MODEL-IDENTITY-J-RESULTS.md | 2 + docs/LIVE-RETEST-J-PLAN.md | 10 +- docs/QA-ANTHROPIC-MESSAGES-M.md | 4 +- docs/ROUTING-AUDIT-N.md | 67 + docs/VALIDATION.md | 2 + docs/routing-audit-n-evidence/.gitattributes | 2 + docs/routing-audit-n-evidence/README.md | 24 + .../shared/contracts/model-capabilities.mjs | 36 + .../src/shared/contracts/model-request.mjs | 98 + .../shared/contracts/native-parameters.mjs | 24 + .../shared/contracts/model-capabilities.mjs | 36 + .../src/shared/contracts/model-identity.mjs | 44 + .../src/shared/contracts/model-request.mjs | 98 + .../shared/contracts/native-parameters.mjs | 24 + .../configuration/concurrent-observation.json | 73 + .../configuration/correction-before.json | 120 + .../correction-export-current.json | 759 +++ .../configuration/correction-response.json | 55 + .../configuration/correction-result.json | 130 + .../configuration/local-state.json | 90 + .../drivers/route-n-check-source.mjs.txt | 45 + .../drivers/route-n-compare-gpt.mjs.txt | 66 + .../route-n-correct-connection-first.mjs.txt | 74 + .../route-n-correct-connection.mjs.txt | 75 + .../drivers/route-n-followup.mjs.txt | 32 + .../drivers/route-n-local.mjs.txt | 30 + .../drivers/route-n-public.mjs.txt | 37 + .../drivers/route-n-redirect-audit.mjs.txt | 24 + .../drivers/route-n-seal.mjs.txt | 102 + .../drivers/route-n-source-api.mjs.txt | 48 + .../drivers/route-n-source.mjs.txt | 41 + .../drivers/route-n-verify-correction.mjs.txt | 53 + docs/routing-audit-n-evidence/manifest.json | 286 ++ .../public/followup-receipts.json | 43 + .../public/handler-receipt.json | 13 + .../public/plaza-receipt.json | 9 + .../public/receipts.json | 38 + .../public/selected-sources.json | 119 + .../public/source-api-receipts.json | 112 + .../public/source-receipts.json | 45 + .../domain/openai_messages_dispatch.go.txt | 10 + .../handler/openai_gateway_handler.go.txt | 4514 +++++++++++++++++ .../apicompat/responses_to_anthropic.go.txt | 814 +++ .../internal/server/routes/gateway.go.txt | 695 +++ .../backend/internal/service/group.go.txt | 480 ++ .../service/openai_gateway_messages.go.txt | 1449 ++++++ .../service/openai_messages_dispatch.go.txt | 124 + .../service/openai_model_mapping.go.txt | 139 + .../public/upstream-summary.json | 76 + .../public/vendor-home.html | 18 + .../public/vendor-model-plaza.json | 1 + .../results/gpt-compatibility.json | 710 +++ .../results/gpt-redirect-audit.json | 31 + .../results/regression-summary.json | 25 + .../results/regression.tap | 878 ++++ .../results/source-integrity.json | 1779 +++++++ .../user-confirmation.json | 8 + .../verify-offline.mjs | 150 + docs/routing-audit-n-verification.json | 17 + findings.md | 10 + progress.md | 12 + task_plan.md | 9 + 65 files changed, 14945 insertions(+), 8 deletions(-) create mode 100644 docs/ROUTING-AUDIT-N.md create mode 100644 docs/routing-audit-n-evidence/.gitattributes create mode 100644 docs/routing-audit-n-evidence/README.md create mode 100644 docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-capabilities.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-request.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/native-parameters.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-capabilities.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-identity.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-request.mjs create mode 100644 docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/native-parameters.mjs create mode 100644 docs/routing-audit-n-evidence/configuration/concurrent-observation.json create mode 100644 docs/routing-audit-n-evidence/configuration/correction-before.json create mode 100644 docs/routing-audit-n-evidence/configuration/correction-export-current.json create mode 100644 docs/routing-audit-n-evidence/configuration/correction-response.json create mode 100644 docs/routing-audit-n-evidence/configuration/correction-result.json create mode 100644 docs/routing-audit-n-evidence/configuration/local-state.json create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-check-source.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-compare-gpt.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-correct-connection-first.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-correct-connection.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-followup.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-local.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-public.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-redirect-audit.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-seal.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-source-api.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-source.mjs.txt create mode 100644 docs/routing-audit-n-evidence/drivers/route-n-verify-correction.mjs.txt create mode 100644 docs/routing-audit-n-evidence/manifest.json create mode 100644 docs/routing-audit-n-evidence/public/followup-receipts.json create mode 100644 docs/routing-audit-n-evidence/public/handler-receipt.json create mode 100644 docs/routing-audit-n-evidence/public/plaza-receipt.json create mode 100644 docs/routing-audit-n-evidence/public/receipts.json create mode 100644 docs/routing-audit-n-evidence/public/selected-sources.json create mode 100644 docs/routing-audit-n-evidence/public/source-api-receipts.json create mode 100644 docs/routing-audit-n-evidence/public/source-receipts.json create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/domain/openai_messages_dispatch.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/handler/openai_gateway_handler.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/server/routes/gateway.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/service/group.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_gateway_messages.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_messages_dispatch.go.txt create mode 100644 docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_model_mapping.go.txt create mode 100644 docs/routing-audit-n-evidence/public/upstream-summary.json create mode 100644 docs/routing-audit-n-evidence/public/vendor-home.html create mode 100644 docs/routing-audit-n-evidence/public/vendor-model-plaza.json create mode 100644 docs/routing-audit-n-evidence/results/gpt-compatibility.json create mode 100644 docs/routing-audit-n-evidence/results/gpt-redirect-audit.json create mode 100644 docs/routing-audit-n-evidence/results/regression-summary.json create mode 100644 docs/routing-audit-n-evidence/results/regression.tap create mode 100644 docs/routing-audit-n-evidence/results/source-integrity.json create mode 100644 docs/routing-audit-n-evidence/user-confirmation.json create mode 100644 docs/routing-audit-n-evidence/verify-offline.mjs create mode 100644 docs/routing-audit-n-verification.json diff --git a/AGENTS.md b/AGENTS.md index 5cb8581c..b8bc8020 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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指手机,远程接入通过未来经验证的配对网关。 diff --git a/CHANGELOG.md b/CHANGELOG.md index a22125bb..6255e064 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 根地址,保存切换不自动调用模型。 diff --git a/docs/APIKEY-ROUTE-L-INVESTIGATION.md b/docs/APIKEY-ROUTE-L-INVESTIGATION.md index aadab889..4f479d64 100644 --- a/docs/APIKEY-ROUTE-L-INVESTIGATION.md +++ b/docs/APIKEY-ROUTE-L-INVESTIGATION.md @@ -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`。这是诊断结果,不是新协议已经上线的发行说明。 diff --git a/docs/LIVE-MODEL-IDENTITY-J-RESULTS.md b/docs/LIVE-MODEL-IDENTITY-J-RESULTS.md index bca3f678..8585dbde 100644 --- a/docs/LIVE-MODEL-IDENTITY-J-RESULTS.md +++ b/docs/LIVE-MODEL-IDENTITY-J-RESULTS.md @@ -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 工程能力的验收依据,也不能仅凭返回字段认证底层模型权重或判断代理原因。 | 项目 | 原始证据结果 | diff --git a/docs/LIVE-RETEST-J-PLAN.md b/docs/LIVE-RETEST-J-PLAN.md index 3dc70bcc..07ebcd4e 100644 --- a/docs/LIVE-RETEST-J-PLAN.md +++ b/docs/LIVE-RETEST-J-PLAN.md @@ -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及更大能力扩展继续保留计划,先得到真实闭环证据。 diff --git a/docs/QA-ANTHROPIC-MESSAGES-M.md b/docs/QA-ANTHROPIC-MESSAGES-M.md index b338bf76..32f2b088 100644 --- a/docs/QA-ANTHROPIC-MESSAGES-M.md +++ b/docs/QA-ANTHROPIC-MESSAGES-M.md @@ -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份原工件文件及模型中心在升级和窗口回看后精确一致。 diff --git a/docs/ROUTING-AUDIT-N.md b/docs/ROUTING-AUDIT-N.md new file mode 100644 index 00000000..52ec8d3c --- /dev/null +++ b/docs/ROUTING-AUDIT-N.md @@ -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`。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 8b5b429a..2d0d467d 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -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。 diff --git a/docs/routing-audit-n-evidence/.gitattributes b/docs/routing-audit-n-evidence/.gitattributes new file mode 100644 index 00000000..f221cf5e --- /dev/null +++ b/docs/routing-audit-n-evidence/.gitattributes @@ -0,0 +1,2 @@ +* -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol +*.tap binary diff --git a/docs/routing-audit-n-evidence/README.md b/docs/routing-audit-n-evidence/README.md new file mode 100644 index 00000000..02b86891 --- /dev/null +++ b/docs/routing-audit-n-evidence/README.md @@ -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)独立实测。 diff --git a/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-capabilities.mjs b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-capabilities.mjs new file mode 100644 index 00000000..5673b35c --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-capabilities.mjs @@ -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' ? '连接明确声明不支持所需能力' : '连接尚未声明或验证所需能力', + })); +} diff --git a/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-request.mjs b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-request.mjs new file mode 100644 index 00000000..13ff42d3 --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/model-request.mjs @@ -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('模型请求正文与已保存计划不一致,未发送请求。'); +} diff --git a/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/native-parameters.mjs b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/native-parameters.mjs new file mode 100644 index 00000000..0f6a15bf --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/410b3478/src/shared/contracts/native-parameters.mjs @@ -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 }; +} diff --git a/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-capabilities.mjs b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-capabilities.mjs new file mode 100644 index 00000000..5673b35c --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-capabilities.mjs @@ -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' ? '连接明确声明不支持所需能力' : '连接尚未声明或验证所需能力', + })); +} diff --git a/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-identity.mjs b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-identity.mjs new file mode 100644 index 00000000..306618ee --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-identity.mjs @@ -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] ?? '型号待核对') : '历史记录未核对返回型号'; +} diff --git a/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-request.mjs b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-request.mjs new file mode 100644 index 00000000..13ff42d3 --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/model-request.mjs @@ -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('模型请求正文与已保存计划不一致,未发送请求。'); +} diff --git a/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/native-parameters.mjs b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/native-parameters.mjs new file mode 100644 index 00000000..0f6a15bf --- /dev/null +++ b/docs/routing-audit-n-evidence/baseline/b832982d/src/shared/contracts/native-parameters.mjs @@ -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 }; +} diff --git a/docs/routing-audit-n-evidence/configuration/concurrent-observation.json b/docs/routing-audit-n-evidence/configuration/concurrent-observation.json new file mode 100644 index 00000000..b101fb56 --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/concurrent-observation.json @@ -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 +} diff --git a/docs/routing-audit-n-evidence/configuration/correction-before.json b/docs/routing-audit-n-evidence/configuration/correction-before.json new file mode 100644 index 00000000..eaf454fa --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/correction-before.json @@ -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 +} diff --git a/docs/routing-audit-n-evidence/configuration/correction-export-current.json b/docs/routing-audit-n-evidence/configuration/correction-export-current.json new file mode 100644 index 00000000..a0ce747a --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/correction-export-current.json @@ -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 + } +} diff --git a/docs/routing-audit-n-evidence/configuration/correction-response.json b/docs/routing-audit-n-evidence/configuration/correction-response.json new file mode 100644 index 00000000..a4469876 --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/correction-response.json @@ -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" + } +} diff --git a/docs/routing-audit-n-evidence/configuration/correction-result.json b/docs/routing-audit-n-evidence/configuration/correction-result.json new file mode 100644 index 00000000..fd37cbf1 --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/correction-result.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/configuration/local-state.json b/docs/routing-audit-n-evidence/configuration/local-state.json new file mode 100644 index 00000000..9c65ab4c --- /dev/null +++ b/docs/routing-audit-n-evidence/configuration/local-state.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/drivers/route-n-check-source.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-check-source.mjs.txt new file mode 100644 index 00000000..342fb752 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-check-source.mjs.txt @@ -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; diff --git a/docs/routing-audit-n-evidence/drivers/route-n-compare-gpt.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-compare-gpt.mjs.txt new file mode 100644 index 00000000..b3234674 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-compare-gpt.mjs.txt @@ -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 })); diff --git a/docs/routing-audit-n-evidence/drivers/route-n-correct-connection-first.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-correct-connection-first.mjs.txt new file mode 100644 index 00000000..594724ea --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-correct-connection-first.mjs.txt @@ -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(); } diff --git a/docs/routing-audit-n-evidence/drivers/route-n-correct-connection.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-correct-connection.mjs.txt new file mode 100644 index 00000000..5bd6cd54 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-correct-connection.mjs.txt @@ -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(); } diff --git a/docs/routing-audit-n-evidence/drivers/route-n-followup.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-followup.mjs.txt new file mode 100644 index 00000000..ddfcbd61 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-followup.mjs.txt @@ -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; diff --git a/docs/routing-audit-n-evidence/drivers/route-n-local.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-local.mjs.txt new file mode 100644 index 00000000..89ad99ac --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-local.mjs.txt @@ -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(); } diff --git a/docs/routing-audit-n-evidence/drivers/route-n-public.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-public.mjs.txt new file mode 100644 index 00000000..54690a2a --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-public.mjs.txt @@ -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(); +} diff --git a/docs/routing-audit-n-evidence/drivers/route-n-redirect-audit.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-redirect-audit.mjs.txt new file mode 100644 index 00000000..74ee9293 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-redirect-audit.mjs.txt @@ -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) })); diff --git a/docs/routing-audit-n-evidence/drivers/route-n-seal.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-seal.mjs.txt new file mode 100644 index 00000000..0389e109 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-seal.mjs.txt @@ -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 })); diff --git a/docs/routing-audit-n-evidence/drivers/route-n-source-api.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-source-api.mjs.txt new file mode 100644 index 00000000..4ad9987f --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-source-api.mjs.txt @@ -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; diff --git a/docs/routing-audit-n-evidence/drivers/route-n-source.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-source.mjs.txt new file mode 100644 index 00000000..b6df6917 --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-source.mjs.txt @@ -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(); +} diff --git a/docs/routing-audit-n-evidence/drivers/route-n-verify-correction.mjs.txt b/docs/routing-audit-n-evidence/drivers/route-n-verify-correction.mjs.txt new file mode 100644 index 00000000..db7cb2ed --- /dev/null +++ b/docs/routing-audit-n-evidence/drivers/route-n-verify-correction.mjs.txt @@ -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(); } diff --git a/docs/routing-audit-n-evidence/manifest.json b/docs/routing-audit-n-evidence/manifest.json new file mode 100644 index 00000000..0f08cefe --- /dev/null +++ b/docs/routing-audit-n-evidence/manifest.json @@ -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" + } + ] +} diff --git a/docs/routing-audit-n-evidence/public/followup-receipts.json b/docs/routing-audit-n-evidence/public/followup-receipts.json new file mode 100644 index 00000000..4eaa7357 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/followup-receipts.json @@ -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": [] +} diff --git a/docs/routing-audit-n-evidence/public/handler-receipt.json b/docs/routing-audit-n-evidence/public/handler-receipt.json new file mode 100644 index 00000000..768970fd --- /dev/null +++ b/docs/routing-audit-n-evidence/public/handler-receipt.json @@ -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 +} diff --git a/docs/routing-audit-n-evidence/public/plaza-receipt.json b/docs/routing-audit-n-evidence/public/plaza-receipt.json new file mode 100644 index 00000000..e2e64cea --- /dev/null +++ b/docs/routing-audit-n-evidence/public/plaza-receipt.json @@ -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 +} diff --git a/docs/routing-audit-n-evidence/public/receipts.json b/docs/routing-audit-n-evidence/public/receipts.json new file mode 100644 index 00000000..e89fa985 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/receipts.json @@ -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 + } + ] +} diff --git a/docs/routing-audit-n-evidence/public/selected-sources.json b/docs/routing-audit-n-evidence/public/selected-sources.json new file mode 100644 index 00000000..e5bd1d5e --- /dev/null +++ b/docs/routing-audit-n-evidence/public/selected-sources.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/public/source-api-receipts.json b/docs/routing-audit-n-evidence/public/source-api-receipts.json new file mode 100644 index 00000000..9a2a246e --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source-api-receipts.json @@ -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": [] +} diff --git a/docs/routing-audit-n-evidence/public/source-receipts.json b/docs/routing-audit-n-evidence/public/source-receipts.json new file mode 100644 index 00000000..e6e98288 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source-receipts.json @@ -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" + } + ] +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/domain/openai_messages_dispatch.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/domain/openai_messages_dispatch.go.txt new file mode 100644 index 00000000..6b018f1c --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/domain/openai_messages_dispatch.go.txt @@ -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"` +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/handler/openai_gateway_handler.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/handler/openai_gateway_handler.go.txt new file mode 100644 index 00000000..3518463f --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/handler/openai_gateway_handler.go.txt @@ -0,0 +1,4514 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "runtime/debug" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/ip" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" + "github.com/Wei-Shaw/sub2api/internal/securityaudit" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +// OpenAIGatewayHandler handles OpenAI API gateway requests +type OpenAIGatewayHandler struct { + compositeResolver *service.CompositeRouteResolver + gatewayService *service.OpenAIGatewayService + billingCacheService *service.BillingCacheService + apiKeyService *service.APIKeyService + usageRecordWorkerPool *service.UsageRecordWorkerPool + errorPassthroughService *service.ErrorPassthroughService + contentModerationService *service.ContentModerationService + securityAuditCoordinator *securityaudit.Coordinator + grokMediaEligibilityProber grokMediaEligibilityProber + opsService *service.OpsService + concurrencyHelper *ConcurrencyHelper + imageLimiter *imageConcurrencyLimiter + maxAccountSwitches int + cfg *config.Config +} + +type openAIWSTurnChannelMappingSnapshot struct { + turn int + mapping service.ChannelMappingResult +} + +func advanceOpenAIWSCyberBlockState(blocked, pending, marked bool, turnErr error) (bool, bool) { + var failoverErr *service.UpstreamFailoverError + isFailover := errors.As(turnErr, &failoverErr) + if marked { + if isFailover { + return false, true + } + return true, false + } + if pending && !isFailover { + return true, false + } + return blocked, pending +} + +var errOpenAIWSUnsupportedModelSwitch = errors.New("selected account does not support websocket model switch") + +func newOpenAIWSUnsupportedModelSwitchError(model string) error { + cause := fmt.Errorf("%w: model %q", errOpenAIWSUnsupportedModelSwitch, strings.TrimSpace(model)) + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "model switch requires reconnect", cause) +} + +func shouldReportOpenAIWSProxyAccountFailure(err error) bool { + return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && !service.IsOpenAIWSSessionPreemptedError(err) +} + +// openAIWSIngressEndedByClient reports whether a finished ingress WebSocket turn +// ended the way a healthy client ends one, rather than through an upstream or +// account fault. +// +// Three error shapes describe that same benign outcome and only the first was +// recognised: +// +// - *service.OpenAIWSClientCloseError carrying 1000 — the gateway closing the +// socket on its own terms, e.g. the inter-turn idle timeout. +// - a bare coderws.CloseError{Code: 1000} — what coder/websocket returns when +// the client closes cleanly. ReadOpenAIWSClientMessage hands conn.Read's +// error back verbatim, so nothing ever wraps it into the type above and an +// errors.As against that type cannot see it. +// - context.Canceled — the client went away mid-turn. That path closes with +// StatusGoingAway (1001) and carries the cancellation as its cause, so a +// check for 1000 alone never matched it either. +// +// The last two fell through to shouldReportOpenAIWSProxyAccountFailure, which +// filters only model-switch and session-preemption errors. Everything else +// reaches ObserveOpenAIAPIKeyHealthFailure and scheduler.ReportResult(false), so +// a client that merely disconnected counted against the upstream account's +// health and could trip it out of scheduling. +// +// failoverClientGone already states the rule this restores for the HTTP failover +// path — a cancelled client context "被误报成账号耗尽" is a bug, not a signal — +// and summarizeWSCloseErrorForLog already reads the close code the correct way, +// which is why the resulting WARN printed close_status=1000(StatusNormalClosure) +// for an error that was, in the same breath, being charged to the account. +// +// Deliberately narrow. StatusGoingAway is not matched on its own: the gateway +// emits 1001 when it tears a session down for its own reasons too, and the +// client-cancellation case is already covered by context.Canceled. +// context.DeadlineExceeded is left out as well — the idle-timeout path wraps it +// in a 1000 close error and stays benign through the first check, while any +// other deadline is a genuine stall worth reporting. +func openAIWSIngressEndedByClient(err error) bool { + if err == nil { + return true + } + var closeErr *service.OpenAIWSClientCloseError + if errors.As(err, &closeErr) && closeErr.StatusCode() == coderws.StatusNormalClosure { + return true + } + if coderws.CloseStatus(err) == coderws.StatusNormalClosure { + return true + } + return errors.Is(err, context.Canceled) +} + +func openAIWSTurnBillingModel(result *service.OpenAIForwardResult, mapping service.ChannelMappingResult, requestedModel, upstreamModel string) string { + billingModel := "" + if result != nil { + billingModel = strings.TrimSpace(result.BillingModel) + } + if billingModel == "" { + billingModel = strings.TrimSpace(upstreamModel) + } + if billingModel == "" { + billingModel = strings.TrimSpace(requestedModel) + } + + requestedModel = strings.TrimSpace(requestedModel) + switch mapping.BillingModelSource { + case service.BillingModelSourceRequested: + if requestedModel != "" { + billingModel = requestedModel + } + case service.BillingModelSourceChannelMapped: + mappedModel := strings.TrimSpace(mapping.MappedModel) + if mappedModel != "" && mappedModel != requestedModel { + billingModel = mappedModel + } + } + return billingModel +} + +// openAIChannelForwardModel returns the model used for upstream capability +// routing. The client-requested model remains separate for logs, billing, and +// responses. +func openAIChannelForwardModel(mapping service.ChannelMappingResult, requestedModel string) string { + if mapping.Mapped { + if mappedModel := strings.TrimSpace(mapping.MappedModel); mappedModel != "" { + return mappedModel + } + } + return requestedModel +} + +type grokMediaEligibilityProber interface { + ProbeMediaEligibility(ctx context.Context, accountID int64) (bool, string, error) +} + +const maxOpenAIFirstOutputTimeoutSwitches = 1 + +func openAIForwardSucceededForScheduling(result *service.OpenAIForwardResult) bool { + return result.SucceededForScheduling() +} + +func openAIAccountScheduleModel(c *gin.Context, account *service.Account, forwardModel string, requireCompact bool, result *service.OpenAIForwardResult) string { + if result != nil { + if actual := strings.TrimSpace(result.UpstreamModel); actual != "" { + return actual + } + } + if c != nil { + if value, ok := c.Get(service.OpsUpstreamModelKey); ok { + if actual, ok := value.(string); ok && strings.TrimSpace(actual) != "" { + return strings.TrimSpace(actual) + } + } + } + return service.ResolveOpenAIAccountUpstreamModelForRequest(account, forwardModel, requireCompact) +} + +func resolveOpenAIMessagesDispatchMappedModel(c *gin.Context, apiKey *service.APIKey, requestedModel string) string { + if apiKey == nil || apiKey.Group == nil { + return "" + } + // composite 解析到 grok/CN/OpenCode 目标时调度级映射不适用(Group 级映射的 + // gpt-5.x 默认值是 openai 专属,发给这些上游必错),模型改写交给账号级 model_mapping。 + if apiKey.Group.Platform == service.PlatformComposite && c != nil && c.Request != nil { + if platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()); ok && + (platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) { + return "" + } + } + return strings.TrimSpace(apiKey.Group.ResolveMessagesDispatchModel(requestedModel)) +} + +type openAIModelBodyReplaceFunc func([]byte, string) []byte + +func openAIModelMappedBody(body []byte, mapped bool, mappedModel string, replace openAIModelBodyReplaceFunc) []byte { + if !mapped || replace == nil { + return body + } + return replace(body, mappedModel) +} + +func seedOpenAIForwardImageIntentHint(c *gin.Context, channelMapped bool, imageIntent bool) { + if channelMapped { + // 渠道映射改变了规范请求,保持 unknown,由 Forward 按映射后的 model/body 初始化。 + return + } + service.SetOpenAIImageIntentHint(c, imageIntent) +} + +func newOpenAIModelMappedBodyCache(body []byte, replace openAIModelBodyReplaceFunc) func(bool, string) []byte { + replacedBodies := make(map[string][]byte) + return func(mapped bool, mappedModel string) []byte { + if !mapped { + return body + } + if cachedBody, ok := replacedBodies[mappedModel]; ok { + return cachedBody + } + replacedBody := openAIModelMappedBody(body, true, mappedModel, replace) + replacedBodies[mappedModel] = replacedBody + return replacedBody + } +} + +func usageRecordContext(parent context.Context, base context.Context) context.Context { + if base == nil { + base = context.Background() + } + if parent == nil { + return base + } + if clientRequestID, _ := parent.Value(ctxkey.ClientRequestID).(string); strings.TrimSpace(clientRequestID) != "" { + base = context.WithValue(base, ctxkey.ClientRequestID, strings.TrimSpace(clientRequestID)) + } + if requestID, _ := parent.Value(ctxkey.RequestID).(string); strings.TrimSpace(requestID) != "" { + base = context.WithValue(base, ctxkey.RequestID, strings.TrimSpace(requestID)) + } + return base +} + +// wrapUsageRecordTaskContext 包装计费任务:复制请求级 context 值,并接管请求的在途余额预留引用。 +// 返回的 abandon 在任务未被执行(被丢弃)时必须调用以归还预留引用;任务执行结束时(含 panic) +// 自动归还,此时余额缓存已在计费路径中同步扣减。 +func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecordTask) (service.UsageRecordTask, func()) { + if task == nil { + return nil, func() {} + } + done := func() {} + if parent != nil { + done = service.InflightReservationFromContext(parent).Acquire() + } + return func(ctx context.Context) { + defer done() + task(usageRecordContext(parent, ctx)) + }, done +} + +func openAICompatibleRequestPlatform(ctx context.Context, apiKey *service.APIKey) string { + if platform, ok := service.ResolvedTargetPlatformFromContext(ctx); ok { + // 保留 grok 与国产供应商原值,其他归一为 openai(与调度器精确匹配语义一致)。 + return service.NormalizeOpenAICompatiblePlatform(platform) + } + if apiKey != nil && apiKey.Group != nil { + return service.NormalizeOpenAICompatiblePlatform(apiKey.Group.Platform) + } + return service.PlatformOpenAI +} + +func openAIResponsesRequiredCapability(imageIntent bool, platform string) service.OpenAIEndpointCapability { + if imageIntent && platform == service.PlatformOpenAI { + return service.OpenAIEndpointCapabilityResponses + } + return service.OpenAIEndpointCapabilityChatCompletions +} + +// openAIResponsesRequiredCapabilityForRequest returns the endpoint capability +// required by an image or Responses request. needsResponses includes both the +// legacy /responses/compact endpoint and native remote compaction v2. +func openAIResponsesRequiredCapabilityForRequest(imageIntent bool, needsResponses bool, platform string) service.OpenAIEndpointCapability { + if needsResponses && platform == service.PlatformOpenAI { + return service.OpenAIEndpointCapabilityResponses + } + return openAIResponsesRequiredCapability(imageIntent, platform) +} + +func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKey) bool { + if apiKey == nil || apiKey.Group == nil { + return true + } + if apiKey.Group.Platform == service.PlatformGrok { + return true + } + // 国产供应商分组与 grok 同语义:/v1/messages 就是其主要服务形态(anthropic + // 协议账号原生直通 Claude Code),无需 allow_messages_dispatch 开关授权—— + // 该开关对非 openai/composite 平台恒被 sanitizeGroupMessagesDispatchFields 置 false, + // 若不豁免,CN 分组将永远 403。 + if service.IsMultiProtocolAPIKeyProvider(apiKey.Group.Platform) { + return true + } + // composite 分组解析到 grok/CN/OpenCode Go 目标时与对应独立分组同语义豁免; + // 解析到 openai 目标则受 composite 分组自身的可配置开关控制。 + if apiKey.Group.Platform == service.PlatformComposite && c != nil && c.Request != nil { + if platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()); ok && + (platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) { + return true + } + } + return apiKey.Group.AllowMessagesDispatch +} + +func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, model string) bool { + return compositeTargetPlatformAllowed(c, apiKey, model, + domain.PlatformIDsWhere(func(spec domain.PlatformSpec) bool { + return spec.Gateway == domain.PlatformGatewayOpenAI + })...) +} + +// isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket +// 上可服务的目标平台。CN 供应商(kimi/zhipu/deepseek)刻意排除:其账号无法通过 +// WSv2 ingress 的 transport 过滤,且 WS HTTP 桥没有面向 CN 的 Responses 转换, +// 放行只会把明确的策略拒绝变成误导性的 "no available account"。 +func isResponsesWebSocketCompositePlatform(platform string) bool { + switch platform { + case service.PlatformOpenAI, service.PlatformGrok: + return true + default: + return false + } +} + +// NewOpenAIGatewayHandler creates a new OpenAIGatewayHandler +func NewOpenAIGatewayHandler( + gatewayService *service.OpenAIGatewayService, + concurrencyService *service.ConcurrencyService, + billingCacheService *service.BillingCacheService, + apiKeyService *service.APIKeyService, + usageRecordWorkerPool *service.UsageRecordWorkerPool, + errorPassthroughService *service.ErrorPassthroughService, + contentModerationService *service.ContentModerationService, + opsService *service.OpsService, + cfg *config.Config, +) *OpenAIGatewayHandler { + pingInterval := time.Duration(0) + maxAccountSwitches := 3 + if cfg != nil { + pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second + if cfg.Gateway.MaxAccountSwitches > 0 { + maxAccountSwitches = cfg.Gateway.MaxAccountSwitches + } + } + return &OpenAIGatewayHandler{ + gatewayService: gatewayService, + billingCacheService: billingCacheService, + apiKeyService: apiKeyService, + usageRecordWorkerPool: usageRecordWorkerPool, + errorPassthroughService: errorPassthroughService, + contentModerationService: contentModerationService, + opsService: opsService, + concurrencyHelper: NewConcurrencyHelper(concurrencyService, SSEPingFormatComment, pingInterval), + imageLimiter: &imageConcurrencyLimiter{}, + maxAccountSwitches: maxAccountSwitches, + cfg: cfg, + } +} + +// Responses handles OpenAI Responses API endpoint +// POST /openai/v1/responses +func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { + // 局部兜底:确保该 handler 内部任何 panic 都不会击穿到进程级。 + streamStarted := false + defer h.recoverResponsesPanic(c, &streamStarted) + compactStartedAt := time.Now() + defer h.logOpenAIRemoteCompactOutcome(c, compactStartedAt) + setOpenAIClientTransportHTTP(c) + + requestStart := time.Now() + + // Get apiKey and user from context (set by ApiKeyAuth middleware) + apiKey, ok := middleware2.GetAPIKeyFromContext(c) + if !ok { + h.errorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key") + return + } + + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + h.errorResponse(c, http.StatusInternalServerError, "api_error", "User context not found") + return + } + reqLog := requestLogger( + c, + "handler.openai_gateway.responses", + zap.Int64("user_id", subject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + ) + if !h.ensureResponsesDependencies(c, reqLog) { + return + } + + // Read request body + body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) + if err != nil { + if maxErr, ok := extractMaxBytesError(err); ok { + h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) + return + } + logRequestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + return + } + + if len(body) == 0 { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty") + return + } + + setOpsRequestContext(c, "", false) + sessionHashBody := body + body, ok = h.normalizeOpenAIResponsesCompactRequest(c, reqLog, body) + if !ok { + return + } + legacyCompact := service.IsOpenAIResponsesCompactPath(c) + nativeV2 := isBareOpenAIResponsesPath(c) && isOpenAIRemoteCompactionV2Request(body) + if nativeV2 { + // 原生 v2 压缩出站前补注 x-codex-beta-features: remote_compaction_v2, + // 与真实 Codex 线型一致(网关链剥头后本级负责恢复,#5586)。 + service.MarkOpenAINativeCompactionV2(c) + } + // body-signal compact:上游 unary 等待期间向下游发 SSE 注释行心跳,防止 + // 反向代理空闲超时掐断长压缩连接(#3887)。首拍延迟一个心跳间隔,快速 + // 失败仍走 JSON+状态码链路;未标记客户端流式或间隔为 0 时是 no-op。 + stopCompactKeepalive := service.StartOpenAICompactSSEKeepalive(c, h.openAICompactKeepaliveInterval()) + defer stopCompactKeepalive() + + // 校验请求体 JSON 合法性 + if !gjson.ValidBytes(body) { + logRequestBodyParseFailure(reqLog, body, nil) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") + return + } + + // 使用 gjson 只读提取字段做校验,避免完整 Unmarshal + modelResult := gjson.GetBytes(body, "model") + if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") + return + } + reqModel := modelResult.String() + ensureCompositeTargetPlatform(c, apiKey, reqModel) + if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") + return + } + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + return + } else if changed { + body = cappedBody + } + if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed { + body = normalizedBody + reqLog.Info("openai.codex_automation_bootstrap_normalized", + zap.String("normalization", "call_output_to_user_message"), + ) + } + if normalizedBody, changed := normalizeCodexDelegationBootstrap(body); changed { + body = normalizedBody + reqLog.Info("openai.codex_delegation_bootstrap_normalized", + zap.String("normalization", "call_output_to_user_message"), + ) + } + + reqStream, ok := parseOpenAICompatibleStream(body) + if !ok { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) + return + } + if _, err := service.ValidateOpenAIServiceTierField(body); err != nil { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return + } + reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) + previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) + if previousResponseID != "" { + previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID) + reqLog = reqLog.With( + zap.Bool("has_previous_response_id", true), + zap.String("previous_response_id_kind", previousResponseIDKind), + zap.Int("previous_response_id_len", len(previousResponseID)), + ) + if previousResponseIDKind == service.OpenAIPreviousResponseIDKindMessageID { + reqLog.Warn("openai.request_validation_failed", + zap.String("reason", "previous_response_id_looks_like_message_id"), + ) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id must be a response.id (resp_*), not a message id") + return + } + groupID := int64(0) + if apiKey.GroupID != nil { + groupID = *apiKey.GroupID + } + owned, ownershipErr := h.gatewayService.ValidateOpenAIHTTPResponseOwner( + c.Request.Context(), + groupID, + previousResponseID, + subject.UserID, + apiKey.ID, + ) + if ownershipErr != nil { + reqLog.Warn("openai.previous_response_owner_lookup_failed", zap.Error(ownershipErr)) + } + if !owned { + reqLog.Warn("openai.request_validation_failed", zap.String("reason", "previous_response_owner_mismatch")) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id is not available for this user") + return + } + } + service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) + + setOpsRequestContext(c, reqModel, reqStream) + setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false))) + + if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage { + h.openAISecurityAuditError(c, decision) + return + } + + // 使用 IsExplicitImageGenerationIntent 排除被动 image_gen namespace 声明。 + // Codex 在所有请求中被动声明 image_gen namespace,宽泛检测会导致禁了生图的 + // 分组中所有 Codex 请求被 403(#4447),并误占生图并发槽位。 + imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, body) + if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) { + h.errorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage()) + return + } + var imageReleaseFunc func() + if imageIntent { + var imageAcquired bool + imageReleaseFunc, imageAcquired = h.acquireImageGenerationSlot(c, streamStarted) + if !imageAcquired { + return + } + if imageReleaseFunc != nil { + defer imageReleaseFunc() + } + } + + // 解析渠道级模型映射 + channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody) + seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent) + forwardModel := openAIChannelForwardModel(channelMapping, reqModel) + c.Request = c.Request.WithContext(service.WithOpenAIForwardModel( + c.Request.Context(), + forwardModel, + legacyCompact, + )) + + // 提前校验 function_call_output 是否具备可关联上下文,避免上游 400。 + if !h.validateFunctionCallOutputRequest(c, body, reqLog) { + return + } + + // 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。 + if h.errorPassthroughService != nil { + service.BindErrorPassthroughService(c, h.errorPassthroughService) + } + + // Get subscription info (may be nil) + subscription, _ := middleware2.GetSubscriptionFromContext(c) + requestPlatform := openAICompatibleRequestPlatform(c.Request.Context(), apiKey) + + service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds()) + routingStart := time.Now() + + userReleaseFunc, acquired := h.acquireResponsesUserSlot(c, subject.UserID, subject.Concurrency, reqStream, &streamStarted, reqLog) + if !acquired { + return + } + // 确保请求取消时也会释放槽位,避免长连接被动中断造成泄漏 + if userReleaseFunc != nil { + defer userReleaseFunc() + } + + // 2. Re-check billing eligibility after wait + if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { + reqLog.Info("openai.billing_eligibility_check_failed", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) + if err != nil { + reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightRelease() + + // Generate session hash (header first; fallback to prompt_cache_key) + sessionHash := h.gatewayService.GenerateSessionHash(c, sessionHashBody) + if h.rejectIfCyberSessionBlocked(c, apiKey, sessionHashBody, reqModel, cyberBlockFormatResponses) { + return + } + c.Request = c.Request.WithContext(service.WithOpenAIGuardianParentAffinity( + c.Request.Context(), c, sessionHashBody, reqModel, + )) + requireCompact := legacyCompact + + maxAccountSwitches := h.maxAccountSwitches + switchCount := 0 + firstOutputTimeoutSwitchCount := 0 + profitVetoCount := 0 + failedAccountIDs := make(map[int64]struct{}) + sameAccountRetryCount := make(map[int64]int) + var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState + var passthroughFailoverState openAIPassthroughFailoverState + + // 生图意图的 /v1/responses 请求必须调度到确实支持 Responses API 的账号,否则 + // 会在 forward 阶段被静默降级为无法生图的 Chat Completions 直转(#4417)。 + // 仅对 OpenAI 平台生效:Grok 生图走独立的 forwardGrokResponses 路径,不应被过滤。 + // 复用前置权限与并发阶段在未修改 body 上确认的显式生图意图,避免大 tools 请求重复扫描。 + // 该判断已排除 Codex 被动 image_gen namespace,避免 CC-only 账号被误过滤(#4476)。 + needsResponses := nativeV2 || legacyCompact + requiredCapability := openAIResponsesRequiredCapabilityForRequest(imageIntent, needsResponses, requestPlatform) + + // 分组利润控制:请求级装配定价上下文——pricingAt 固定本请求的 + // D 与计费高峰因子,选号、槽位终检与全部 failover 重入共用同一门与阈值。 + // 生图意图只影响能力路由与图片计费,不关门:混合 /v1/responses 请求的 + // token 计费部分仍受利润门保护,独立图片/视频端点才在门外。 + pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) + c.Request = c.Request.WithContext(pricingCtx) + + for { + // Streaming Forward intentionally detaches the upstream request so usage can + // be drained after a disconnect. Re-check the client context before every + // account attempt so a canceled request never starts a failover replay. + if !openAIRequestAllowsFailoverReplay(c) { + return + } + // Select account supporting the requested model + reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) + selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( + c.Request.Context(), + apiKey.GroupID, + previousResponseID, + sessionHash, + forwardModel, + failedAccountIDs, + service.OpenAIUpstreamTransportAny, + requiredCapability, + requireCompact, + false, + !imageIntent, + requestPlatform, + ) + if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai.account_select_aborted_client_disconnected", zap.Error(err)) + return + } + reqLog.Warn("openai.account_select_failed", + zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), + zap.Int("excluded_account_count", len(failedAccountIDs)), + ) + if len(failedAccountIDs) == 0 { + if legacyCompact && errors.Is(err, service.ErrNoAvailableCompactAccounts) { + markOpsRoutingCapacityLimitedIfNoAvailable(c, err) + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "compact_not_supported", "No available accounts support /responses/compact", streamStarted) + return + } + cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, requestPlatform) + cls = classifySelectionFailureError(err, cls) + if !cls.ModelNotFound { + markOpsRoutingCapacityLimitedIfNoAvailable(c, err) + } + h.handleStreamingAwareError(c, cls.Status, cls.ErrType, cls.Message, streamStarted) + return + } + if lastFailoverErr != nil { + h.handleFailoverExhausted(c, lastFailoverErr, streamStarted) + } else { + h.handleFailoverExhaustedSimple(c, 502, streamStarted) + } + return + } + if selection == nil || selection.Account == nil { + cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, requestPlatform) + if !cls.ModelNotFound { + markOpsRoutingCapacityLimited(c) + } + h.handleStreamingAwareError(c, cls.Status, cls.ErrType, cls.Message, streamStarted) + return + } + if previousResponseID != "" && selection != nil && selection.Account != nil { + reqLog.Debug("openai.account_selected_with_previous_response_id", zap.Int64("account_id", selection.Account.ID)) + } + reqLog.Debug("openai.account_schedule_decision", + zap.String("layer", scheduleDecision.Layer), + zap.Bool("sticky_previous_hit", scheduleDecision.StickyPreviousHit), + zap.Bool("sticky_session_hit", scheduleDecision.StickySessionHit), + zap.Int("candidate_count", scheduleDecision.CandidateCount), + zap.Int("top_k", scheduleDecision.TopK), + zap.Int64("latency_ms", scheduleDecision.LatencyMs), + zap.Float64("load_skew", scheduleDecision.LoadSkew), + ) + account := selection.Account + if previousResponseID != "" && requestPlatform == service.PlatformOpenAI && !account.IsOpenAIApiKey() { + // The public Responses HTTP API supports previous_response_id on API-key + // accounts. OAuth/SetupToken upstreams do not, so keep searching instead + // of silently deleting continuation state from a mixed account pool. + failedAccountIDs[account.ID] = struct{}{} + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + selection.ReleaseFunc = nil + } + lastFailoverErr = &service.UpstreamFailoverError{ + StatusCode: http.StatusBadRequest, + Stage: service.GatewayFailureStageInference, + Scope: service.GatewayFailureScopeRequest, + Reason: service.OpenAIHTTPContinuationUnsupportedReason, + ClientStatusCode: http.StatusBadRequest, + ClientMessage: "previous_response_id requires an OpenAI API-key account for HTTP requests", + } + reqLog.Debug("openai.account_skipped_http_continuation_unsupported", + zap.Int64("account_id", account.ID), + zap.String("account_type", account.Type), + ) + continue + } + sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account) + reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name)) + setOpsSelectedAccount(c, account.ID, account.Platform) + + accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog) + if slotResult == openAISlotAcquireProfitVetoed { + // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; + // 否决次数达上限则直接终止,避免排队抢槽后才终检的延迟放大。 + if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) { + h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount) + return + } + continue + } + if slotResult != openAISlotAcquireOK { + return + } + + // Forward request + service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds()) + forwardStart := time.Now() + // 用扣除非语义心跳字节的口径快照:心跳注释不构成语义响应, + // 不能因心跳字节变化而放弃 failover 换号(#3887)。 + writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c) + // 跨 passthrough 边界的 failover:从 Kiro 等透传账号切到 Bedrock 等非透传账号前, + // 从不可变的 canonical forwardBody 派生本次尝试 body 并整块剔除上游私有的加密 + // reasoning item(含耦合的 id/summary),避免非透传上游 400 拒绝 Kiro reasoning 形态。 + attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, forwardBody, account, &passthroughFailoverState) + result, err := func() (*service.OpenAIForwardResult, error) { + defer func() { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + }() + return h.gatewayService.Forward(c.Request.Context(), c, account, attemptBody) + }() + var cyberBlockBodyHTTP []byte + if service.GetOpsCyberPolicy(c) != nil { + cyberBlockBodyHTTP = sessionHashBody + } + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body)) + forwardDurationMs := time.Since(forwardStart).Milliseconds() + upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) + responseLatencyMs := forwardDurationMs + if upstreamLatencyMs > 0 && forwardDurationMs > upstreamLatencyMs { + responseLatencyMs = forwardDurationMs - upstreamLatencyMs + } + service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs) + if err == nil && result != nil && result.FirstTokenMs != nil { + service.SetOpsLatencyMs(c, service.OpsTimeToFirstTokenMsKey, int64(*result.FirstTokenMs)) + } + // #5148 对齐:错误返回携带的部分 result(流中断前上游已计量的 usage)照常 + // 入账;failover 错误恒定 result=nil,不会重复计费。 + submitResponsesUsage := func(res *service.OpenAIForwardResult) { + if res == nil { + return + } + stampOpenAIRequestedReasoningEffort(res, c) + userAgent := c.GetHeader("User-Agent") + clientIP := ip.GetClientIP(c) + requestPayloadHash := service.HashUsageRequestPayload(body) + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + sessionID := service.ExtractClientSessionID(c) + cyberBlocked := service.GetOpsCyberPolicy(c) != nil + h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ + Result: res, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: quotaPlatform, + SessionID: sessionID, + ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + PricingAt: pricingAt, + CyberBlocked: cyberBlocked, + NativeCompactionV2: nativeV2, + }); err != nil { + logger.L().With( + zap.String("component", "handler.openai_gateway.responses"), + zap.Int64("user_id", subject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + zap.String("model", reqModel), + zap.Int64("account_id", account.ID), + ).Error("openai.record_usage_failed", zap.Error(err)) + } + }) + } + if err != nil { + if result != nil && result.ClientDisconnect { + reqLog.Info("openai.client_disconnected", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + submitResponsesUsage(result) + return + } + if failoverClientGone(c) { + reqLog.Info("openai.client_disconnected", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + submitResponsesUsage(result) + return + } + if result != nil && result.ImageCount > 0 { + reqLog.Warn("openai.forward_partial_error_with_image_result", + zap.Int64("account_id", account.ID), + zap.Int("image_count", result.ImageCount), + zap.Error(err), + ) + } else { + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + if failoverClientGone(c) { + reqLog.Info("openai.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } + if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) { + h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err) + h.handleFailoverExhausted(c, failoverErr, true) + return + } + // openAIForwardMayFailover 已确认写出的字节不含语义输出, + // 但重试耗尽时仍须按已提交的 SSE 响应返回流内错误。 + if c.Writer.Written() { + streamStarted = true + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, nil), false, nil, err) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } + if openAIFirstOutputFailoverExhausted(failoverErr, &firstOutputTimeoutSwitchCount) { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } + // 池模式:同账号重试 + if failoverErr.RetryableOnSameAccount { + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + sameAccountRetryCount[account.ID]++ + retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) + reqLog.Warn("openai.pool_mode_same_account_retry", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("retry_limit", retryLimit), + zap.Int("retry_count", sameAccountRetryCount[account.ID]), + zap.Duration("retry_delay", retryDelay), + ) + select { + case <-c.Request.Context().Done(): + return + case <-time.After(retryDelay): + } + continue + } + } + h.gatewayService.RecordOpenAIAccountSwitch() + failedAccountIDs[account.ID] = struct{}{} + lastFailoverErr = failoverErr + if switchCount >= maxAccountSwitches { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } + switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } + failoverSwitchFields := []zap.Field{ + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("switch_count", switchCount), + zap.Int("max_switches", maxAccountSwitches), + } + if account.Proxy != nil { + failoverSwitchFields = append(failoverSwitchFields, + zap.Int64("proxy_id", account.Proxy.ID), + zap.String("proxy_name", account.Proxy.Name), + zap.String("proxy_host", account.Proxy.Host), + zap.Int("proxy_port", account.Proxy.Port), + ) + } else if account.ProxyID != nil { + failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID)) + } + reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...) + continue + } + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, result), false, nil, err) + upstreamErrorAlreadyCommunicated := openAIForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) + wroteFallback := false + if !upstreamErrorAlreadyCommunicated { + wroteFallback = h.ensureForwardErrorResponse(c, streamStarted) + } + fields := []zap.Field{ + zap.Int64("account_id", account.ID), + zap.Bool("fallback_error_response_written", wroteFallback), + zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), + zap.Error(err), + } + submitResponsesUsage(result) + if shouldLogOpenAIForwardFailureAsWarn(c, wroteFallback) { + reqLog.Warn("openai.forward_failed", fields...) + return + } + reqLog.Error("openai.forward_failed", fields...) + return + } + } + if result != nil { + // 排除 spark 影子:其 codex_* 仅由 QueryUsage(/wham/usage bengalfox)更新(外审第7轮 P1)。 + if account.Type == service.AccountTypeOAuth && !account.IsShadow() { + h.gatewayService.UpdateCodexUsageSnapshotFromHeaders(c.Request.Context(), account.ID, result.ResponseHeaders) + } + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, result), openAIForwardSucceededForScheduling(result), result.FirstTokenMs) + } else { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, result), openAIForwardSucceededForScheduling(result), nil) + } + + // 使用量记录通过有界 worker 池提交,避免请求热路径创建无界 goroutine。 + submitResponsesUsage(result) + reqLog.Debug("openai.request_completed", + zap.Int64("account_id", account.ID), + zap.Int("switch_count", switchCount), + ) + return + } +} + +func isOpenAILegacyCompactPath(c *gin.Context) bool { + return service.IsOpenAIResponsesCompactPath(c) +} + +// isBareOpenAIResponsesPath 仅匹配裸 /responses 端点(无 /compact 等子路径), +// body-signal 提升只允许发生在这里,避免误伤 /responses/{id}/... 形态的请求。 +func isBareOpenAIResponsesPath(c *gin.Context) bool { + if c == nil || c.Request == nil || c.Request.URL == nil { + return false + } + normalizedPath := strings.TrimRight(strings.TrimSpace(c.Request.URL.Path), "/") + switch normalizedPath { + case EndpointResponses, "/openai/v1/responses", "/responses", "/backend-api/codex/responses": + return true + default: + return false + } +} + +func isOpenAIRemoteCompactionV2Request(body []byte) bool { + stream, valid := parseOpenAICompatibleStream(body) + return valid && stream && service.HasCompactionTriggerInInput(body) +} + +// normalizeOpenAIResponsesCompactRequest keeps Codex remote compaction v2 on +// its native streaming /responses wire and preserves the legacy body-signal +// promotion for non-streaming requests. +// 返回归一化后的 body;ok=false 表示错误响应已写出,调用方应直接 return。 +func (h *OpenAIGatewayHandler) normalizeOpenAIResponsesCompactRequest(c *gin.Context, reqLog *zap.Logger, body []byte) ([]byte, bool) { + isCompactRequest := isOpenAILegacyCompactPath(c) + if !isCompactRequest && isBareOpenAIResponsesPath(c) && service.HasCompactionTriggerInInput(body) { + if normalized, changed, err := service.NormalizeCompactionTriggerInputOrder(body); err != nil { + reqLog.Warn("codex.remote_compact.trigger_order_normalization_failed", zap.Error(err)) + } else if changed { + body = normalized + } + if isOpenAIRemoteCompactionV2Request(body) { + return body, true + } + c.Request.URL.Path = strings.TrimRight(c.Request.URL.Path, "/") + "/compact" + isCompactRequest = true + clientStream := gjson.GetBytes(body, "stream").Bool() + if clientStream { + service.MarkOpenAICompactClientStream(c) + } + reqLog.Info("codex.remote_compact.detected_body_signal", zap.Bool("client_stream", clientStream)) + } + if !isCompactRequest { + return body, true + } + if compactSeed := strings.TrimSpace(gjson.GetBytes(body, "prompt_cache_key").String()); compactSeed != "" { + c.Set(service.OpenAICompactSessionSeedKeyForTest(), compactSeed) + } + normalizedCompactBody, normalizedCompact, compactErr := service.NormalizeOpenAICompactRequestBodyForTest(body) + if compactErr != nil { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to normalize compact request body") + return nil, false + } + if normalizedCompact { + body = normalizedCompactBody + } + return body, true +} + +func (h *OpenAIGatewayHandler) logOpenAIRemoteCompactOutcome(c *gin.Context, startedAt time.Time) { + if !isOpenAILegacyCompactPath(c) { + return + } + + var ( + ctx = context.Background() + path string + status int + ) + if c != nil { + if c.Request != nil { + ctx = c.Request.Context() + if c.Request.URL != nil { + path = strings.TrimSpace(c.Request.URL.Path) + } + } + if c.Writer != nil { + status = c.Writer.Status() + } + } + + outcome := "failed" + if status >= 200 && status < 300 { + outcome = "succeeded" + } + // compact 心跳提交后失败的 wire 状态码固化为 200,真实结局以流内错误 + // 标记为准(response.failed 降级路径会 MarkOpsStreamError)。 + if outcome == "succeeded" && c != nil { + if _, hasStreamErr := service.GetOpsStreamError(c); hasStreamErr { + outcome = "failed" + } + } + latencyMs := time.Since(startedAt).Milliseconds() + if latencyMs < 0 { + latencyMs = 0 + } + + fields := []zap.Field{ + zap.String("component", "handler.openai_gateway.responses"), + zap.Bool("remote_compact", true), + zap.String("compact_outcome", outcome), + zap.Int("status_code", status), + zap.Int64("latency_ms", latencyMs), + zap.String("path", path), + zap.Bool("force_codex_cli", h != nil && h.cfg != nil && h.cfg.Gateway.ForceCodexCLI), + } + + if c != nil { + if userAgent := strings.TrimSpace(c.GetHeader("User-Agent")); userAgent != "" { + fields = append(fields, zap.String("request_user_agent", userAgent)) + } + if v, ok := c.Get(opsModelKey); ok { + if model, ok := v.(string); ok && strings.TrimSpace(model) != "" { + fields = append(fields, zap.String("request_model", strings.TrimSpace(model))) + } + } + if v, ok := c.Get(opsAccountIDKey); ok { + if accountID, ok := v.(int64); ok && accountID > 0 { + fields = append(fields, zap.Int64("account_id", accountID)) + } + } + if c.Writer != nil { + if upstreamRequestID := strings.TrimSpace(c.Writer.Header().Get("x-request-id")); upstreamRequestID != "" { + fields = append(fields, zap.String("upstream_request_id", upstreamRequestID)) + } else if upstreamRequestID := strings.TrimSpace(c.Writer.Header().Get("X-Request-Id")); upstreamRequestID != "" { + fields = append(fields, zap.String("upstream_request_id", upstreamRequestID)) + } + } + } + + log := logger.FromContext(ctx).With(fields...) + if outcome == "succeeded" { + log.Info("codex.remote_compact.succeeded") + return + } + log.Warn("codex.remote_compact.failed") +} + +// Messages handles Anthropic Messages API requests routed to OpenAI platform. +// POST /v1/messages (when group platform is OpenAI) +func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { + streamStarted := false + defer h.recoverAnthropicMessagesPanic(c, &streamStarted) + + requestStart := time.Now() + + apiKey, ok := middleware2.GetAPIKeyFromContext(c) + if !ok { + h.anthropicErrorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key") + return + } + + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + h.anthropicErrorResponse(c, http.StatusInternalServerError, "api_error", "User context not found") + return + } + reqLog := requestLogger( + c, + "handler.openai_gateway.messages", + zap.Int64("user_id", subject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + ) + + // 检查分组是否允许 /v1/messages 调度 + if !allowOpenAICompatibleMessagesDispatch(c, apiKey) { + h.anthropicErrorResponse(c, http.StatusForbidden, "permission_error", + "This group does not allow /v1/messages dispatch") + return + } + + if !h.ensureResponsesDependencies(c, reqLog) { + return + } + + body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) + if err != nil { + if maxErr, ok := extractMaxBytesError(err); ok { + h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) + return + } + h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + return + } + if len(body) == 0 { + h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty") + return + } + + if !gjson.ValidBytes(body) { + logRequestBodyParseFailure(reqLog, body, nil) + h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") + return + } + + modelResult := gjson.GetBytes(body, "model") + if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" { + h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") + return + } + reqModel := modelResult.String() + ensureCompositeTargetPlatform(c, apiKey, reqModel) + if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) { + h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") + return + } + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body) + routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel) + preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel) + reqStream := gjson.GetBytes(body, "stream").Bool() + + reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) + + setOpsRequestContext(c, reqModel, reqStream) + setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false))) + + if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolAnthropicMessages, reqModel, body); decision != nil && !decision.AllowNextStage { + h.anthropicSecurityAuditError(c, decision) + return + } + + // 解析渠道级模型映射 + channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody) + + // 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。 + if h.errorPassthroughService != nil { + service.BindErrorPassthroughService(c, h.errorPassthroughService) + } + + subscription, _ := middleware2.GetSubscriptionFromContext(c) + requestPlatform := openAICompatibleRequestPlatform(c.Request.Context(), apiKey) + + service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds()) + routingStart := time.Now() + + userReleaseFunc, acquired := h.acquireResponsesUserSlot(c, subject.UserID, subject.Concurrency, reqStream, &streamStarted, reqLog) + if !acquired { + return + } + if userReleaseFunc != nil { + defer userReleaseFunc() + } + + if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { + reqLog.Info("openai_messages.billing_eligibility_check_failed", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.anthropicStreamingAwareError(c, status, code, message, streamStarted) + return + } + + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.anthropicStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightDone() + + sessionHash := h.gatewayService.GenerateSessionHash(c, body) + promptCacheKey := h.gatewayService.ExtractSessionID(c, body) + sessionHash, promptCacheKey = resolveOpenAIMessagesMetadataSession(c, sessionHash, promptCacheKey, reqModel, body) + if h.rejectIfCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatAnthropic) { + return + } + + maxAccountSwitches := h.maxAccountSwitches + switchCount := 0 + profitVetoCount := 0 + failedAccountIDs := make(map[int64]struct{}) + sameAccountRetryCount := make(map[int64]int) + var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState + effectiveMappedModel := preferredMappedModel + + // 分组利润控制:Messages 文本入口同样请求级装门并固定 pricingAt。 + msgPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) + c.Request = c.Request.WithContext(msgPricingCtx) + + for { + if failoverClientGone(c) { + return + } + currentRoutingModel := routingModel + if effectiveMappedModel != "" { + currentRoutingModel = effectiveMappedModel + } + reqLog.Debug("openai_messages.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) + selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( + c.Request.Context(), + apiKey.GroupID, + "", // no previous_response_id + sessionHash, + currentRoutingModel, + failedAccountIDs, + service.OpenAIUpstreamTransportAny, + service.OpenAIEndpointCapabilityChatCompletions, + false, + false, + true, + requestPlatform, + ) + if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai_messages.account_select_aborted_client_disconnected", zap.Error(err)) + return + } + reqLog.Warn("openai_messages.account_select_failed", + zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), + zap.Int("excluded_account_count", len(failedAccountIDs)), + ) + if len(failedAccountIDs) == 0 { + if err != nil { + cls := classifyOpenAICompatibleNoAccountErrorFromGin(c, h.gatewayService, apiKey, currentRoutingModel, reqModel) + if !cls.ModelNotFound { + markOpsRoutingCapacityLimitedIfNoAvailable(c, err) + } + h.anthropicStreamingAwareError(c, cls.Status, cls.ErrType, cls.Message, streamStarted) + return + } + } else { + if lastFailoverErr != nil { + h.handleAnthropicFailoverExhausted(c, lastFailoverErr, streamStarted) + } else { + h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) + } + return + } + } + if selection == nil || selection.Account == nil { + cls := classifyOpenAICompatibleNoAccountErrorFromGin(c, h.gatewayService, apiKey, currentRoutingModel, reqModel) + if !cls.ModelNotFound { + markOpsRoutingCapacityLimited(c) + } + h.anthropicStreamingAwareError(c, cls.Status, cls.ErrType, cls.Message, streamStarted) + return + } + account := selection.Account + sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account) + reqLog.Debug("openai_messages.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name)) + _ = scheduleDecision + setOpsSelectedAccount(c, account.ID, account.Platform) + + accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog) + if slotResult == openAISlotAcquireProfitVetoed { + // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; + // 否决次数达上限则直接终止,避免排队抢槽后才终检的延迟放大。 + if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) { + h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount) + return + } + continue + } + if slotResult != openAISlotAcquireOK { + return + } + + service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds()) + forwardStart := time.Now() + + defaultMappedModel := strings.TrimSpace(effectiveMappedModel) + // 应用渠道模型映射到请求体 + forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel) + writerSizeBeforeForward := c.Writer.Size() + result, err := func() (*service.OpenAIForwardResult, error) { + defer func() { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + }() + return h.gatewayService.ForwardAsAnthropic(c.Request.Context(), c, account, forwardBody, promptCacheKey, defaultMappedModel) + }() + var cyberBlockBodyMsg []byte + if service.GetOpsCyberPolicy(c) != nil { + cyberBlockBodyMsg = body + } + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyMsg, clientRequestedUsageFields(c, channelMappingMsg, reqModel, ""), service.HashUsageRequestPayload(body)) + forwardDurationMs := time.Since(forwardStart).Milliseconds() + upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) + responseLatencyMs := forwardDurationMs + if upstreamLatencyMs > 0 && forwardDurationMs > upstreamLatencyMs { + responseLatencyMs = forwardDurationMs - upstreamLatencyMs + } + service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs) + if err == nil && result != nil && result.FirstTokenMs != nil { + service.SetOpsLatencyMs(c, service.OpsTimeToFirstTokenMsKey, int64(*result.FirstTokenMs)) + } + // Forward 与错误一起返回的部分结果:流中断/客户端断开排水前上游已计量的 + // usage 照常入账,避免上游已产生消耗的请求完全漏记(#5148,对齐 anthropic + // 网关同名修复)。failover 错误恒定 result=nil,不会重复计费。 + submitMessagesUsage := func(res *service.OpenAIForwardResult) { + if res == nil { + return + } + stampOpenAIRequestedReasoningEffort(res, c) + userAgent := c.GetHeader("User-Agent") + clientIP := ip.GetClientIP(c) + requestPayloadHash := service.HashUsageRequestPayload(body) + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + sessionID := service.ExtractClientSessionID(c) + cyberBlocked := service.GetOpsCyberPolicy(c) != nil + h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ + Result: res, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: quotaPlatform, + SessionID: sessionID, + ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel), + PricingAt: pricingAt, + CyberBlocked: cyberBlocked, + }); err != nil { + logger.L().With( + zap.String("component", "handler.openai_gateway.messages"), + zap.Int64("user_id", subject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + zap.String("model", reqModel), + zap.Int64("account_id", account.ID), + ).Error("openai_messages.record_usage_failed", zap.Error(err)) + } + }) + } + if err != nil { + if result != nil && result.ImageCount > 0 { + reqLog.Warn("openai_messages.forward_partial_error_with_image_result", + zap.Int64("account_id", account.ID), + zap.Int("image_count", result.ImageCount), + zap.Error(err), + ) + } else { + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + if failoverClientGone(c) { + reqLog.Info("openai_messages.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } + if c.Writer.Size() != writerSizeBeforeForward { + h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err) + h.handleAnthropicFailoverExhausted(c, failoverErr, true) + return + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } + // 池模式:同账号重试 + if failoverErr.RetryableOnSameAccount { + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + sameAccountRetryCount[account.ID]++ + retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) + reqLog.Warn("openai_messages.pool_mode_same_account_retry", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("retry_limit", retryLimit), + zap.Int("retry_count", sameAccountRetryCount[account.ID]), + zap.Duration("retry_delay", retryDelay), + ) + select { + case <-c.Request.Context().Done(): + return + case <-time.After(retryDelay): + } + continue + } + } + h.gatewayService.RecordOpenAIAccountSwitch() + failedAccountIDs[account.ID] = struct{}{} + lastFailoverErr = failoverErr + if switchCount >= maxAccountSwitches { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } + switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } + reqLog.Warn("openai_messages.upstream_failover_switching", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("switch_count", switchCount), + zap.Int("max_switches", maxAccountSwitches), + ) + continue + } + if result != nil && result.ClientDisconnect { + reqLog.Info("openai_messages.client_disconnected", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + // 断开排水期间上游已计量的 usage 必须入账(此前直接 return 丢弃, + // payg 上游照常计费而平台漏记)。 + submitMessagesUsage(result) + return + } + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, result), false, nil, err) + wroteFallback := h.ensureAnthropicErrorResponse(c, streamStarted) + reqLog.Warn("openai_messages.forward_failed", + zap.Int64("account_id", account.ID), + zap.Bool("fallback_error_response_written", wroteFallback), + zap.Error(err), + ) + submitMessagesUsage(result) + return + } + } + if result != nil { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, result), true, result.FirstTokenMs) + } else { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, result), true, nil) + } + + submitMessagesUsage(result) + reqLog.Debug("openai_messages.request_completed", + zap.Int64("account_id", account.ID), + zap.Int("switch_count", switchCount), + ) + return + } +} + +func resolveOpenAIMessagesMetadataSession(c *gin.Context, sessionHash, promptCacheKey, reqModel string, body []byte) (string, string) { + // Anthropic metadata.user_id 只作为账号粘性信号。上游 GPT/Codex 缓存键 + // 交给 ForwardAsAnthropic 从 cache_control 或完整消息 digest 派生,避免 + // 固定 metadata key 压住后续 turn 的缓存滚动。 + // + // Claude Code 的 X-Claude-Code-Session-Id 是比 body content fallback 更稳定的 + // 会话边界,但它只用于本地账号粘性;不要把它提升为 prompt_cache_key 或上游 + // session_id,否则会改变现有 Messages→Codex 缓存滚动语义。 + if promptCacheKey == "" { + if claudeSessionID := service.ClaudeCodeSessionIDFromHeader(c); claudeSessionID != "" { + return service.DeriveSessionHashFromSeed(claudeSessionID), promptCacheKey + } + } + if sessionHash != "" { + return sessionHash, promptCacheKey + } + if userID := strings.TrimSpace(gjson.GetBytes(body, "metadata.user_id").String()); userID != "" { + seed := reqModel + "-" + userID + sessionHash = service.DeriveSessionHashFromSeed(seed) + } + return sessionHash, promptCacheKey +} + +// anthropicErrorResponse writes an error in Anthropic Messages API format. +func (h *OpenAIGatewayHandler) anthropicErrorResponse(c *gin.Context, status int, errType, message string) { + c.JSON(status, gin.H{ + "type": "error", + "error": gin.H{ + "type": errType, + "message": message, + }, + }) +} + +// anthropicStreamingAwareError handles errors that may occur during streaming, +// using Anthropic SSE error format. +func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, status int, errType, message string, streamStarted bool) { + if streamStarted { + flusher, ok := c.Writer.(http.Flusher) + if ok { + errPayload, _ := json.Marshal(gin.H{ + "type": "error", + "error": gin.H{ + "type": errType, + "message": message, + }, + }) + fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", errPayload) //nolint:errcheck + flusher.Flush() + } + return + } + h.anthropicErrorResponse(c, status, errType, message) +} + +// handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format. +func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr != nil { + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + } + if failoverErr != nil && failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.anthropicStreamingAwareError(c, status, "api_error", message, streamStarted) + return + } + if failoverErr != nil && failoverErr.IsOpenAICapacityShed() && strings.TrimSpace(failoverErr.ClientMessage) != "" { + status := failoverErr.ClientStatusCode + if status <= 0 { + status = http.StatusServiceUnavailable + } + h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted) + return + } + status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode) + h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted) +} + +// ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written. +func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool { + if c == nil || c.Writer == nil || c.Writer.Written() { + return false + } + h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) + return true +} + +func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, body []byte, reqLog *zap.Logger) bool { + if !gjson.GetBytes(body, `input.#(type=="function_call_output")`).Exists() { + return true + } + + validation := service.ValidateFunctionCallOutputContextBytes(body) + if !validation.HasFunctionCallOutput { + return true + } + + previousResponseID := gjson.GetBytes(body, "previous_response_id").String() + if strings.TrimSpace(previousResponseID) != "" || validation.HasToolCallContext { + return true + } + + if validation.HasFunctionCallOutputMissingCallID { + reqLog.Warn("openai.request_validation_failed", + zap.String("reason", "function_call_output_missing_call_id"), + ) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "function_call_output requires call_id on HTTP requests; continuation via previous_response_id is only supported on Responses WebSocket v2") + return false + } + if validation.HasItemReferenceForAllCallIDs { + return true + } + + reqLog.Warn("openai.request_validation_failed", + zap.String("reason", "function_call_output_missing_item_reference"), + ) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "function_call_output requires item_reference ids matching each call_id on HTTP requests; continuation via previous_response_id is only supported on Responses WebSocket v2") + return false +} + +func normalizeCodexDelegationBootstrap(body []byte) ([]byte, bool) { + // 已有任务通过 send_message_to_thread 唤醒时会携带 previous_response_id; + // 完整历史回放还会带有已配对的调用项。delegation 仍是客户端注入的用户输入, + // 不属于这些历史调用的结果,因此允许它与可明确配对的历史上下文共存。 + return normalizeCodexCallOutputBootstrap(body, isCodexDelegationCandidate, true) +} + +func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) { + return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false) +} + +func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]any) bool, allowHistoricalContext bool) ([]byte, bool) { + if !hasUniqueJSONMembers(body) { + return body, false + } + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + var request map[string]any + if err := decoder.Decode(&request); err != nil { + return body, false + } + if previousResponseID, exists := request["previous_response_id"]; exists { + value, ok := previousResponseID.(string) + if !ok || (!allowHistoricalContext && strings.TrimSpace(value) != "") { + return body, false + } + } + input, ok := request["input"].([]any) + if !ok { + return body, false + } + + // Responses built-ins follow the *_call / *_call_output naming convention, + // so classify by the wire type shape instead of maintaining an incomplete + // allowlist. Delegation may coexist with historical anchors only when their + // IDs make them unambiguous; automation retains the bootstrap-only boundary. + for _, raw := range input { + item, ok := raw.(map[string]any) + if !ok { + continue + } + typ := stringField(item, "type") + if isCandidate(item) { + callIDValue, exists := item["call_id"] + callID, isString := callIDValue.(string) + if exists && (!isString || strings.TrimSpace(callID) != "") { + return body, false + } + continue + } + if typ == "item_reference" { + if allowHistoricalContext && strings.TrimSpace(stringField(item, "id")) != "" { + continue + } + return body, false + } + if strings.HasSuffix(typ, "_call") || isResponsesCallOutputType(typ) { + if allowHistoricalContext && strings.TrimSpace(stringField(item, "call_id")) != "" { + continue + } + return body, false + } + } + + changed := false + for i, raw := range input { + item, ok := raw.(map[string]any) + if !ok || !isCandidate(item) { + continue + } + output, ok := item["output"].(string) + if !ok { + continue + } + input[i] = map[string]any{ + "type": "message", + "role": "user", + "content": []any{map[string]any{ + "type": "input_text", + "text": output, + }}, + } + changed = true + } + if !changed { + return body, false + } + normalized, err := json.Marshal(request) + if err != nil { + return body, false + } + return normalized, true +} + +func hasUniqueJSONMembers(body []byte) bool { + decoder := json.NewDecoder(bytes.NewReader(body)) + if !consumeUniqueJSONValue(decoder) { + return false + } + _, err := decoder.Token() + return err == io.EOF +} + +func consumeUniqueJSONValue(decoder *json.Decoder) bool { + token, err := decoder.Token() + if err != nil { + return false + } + delim, ok := token.(json.Delim) + if !ok { + return true + } + + switch delim { + case '{': + members := make(map[string]struct{}) + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return false + } + key, ok := keyToken.(string) + if !ok { + return false + } + if _, duplicate := members[key]; duplicate { + return false + } + members[key] = struct{}{} + if !consumeUniqueJSONValue(decoder) { + return false + } + } + end, err := decoder.Token() + return err == nil && end == json.Delim('}') + case '[': + for decoder.More() { + if !consumeUniqueJSONValue(decoder) { + return false + } + } + end, err := decoder.Token() + return err == nil && end == json.Delim(']') + default: + return false + } +} + +func isResponsesCallOutputType(typ string) bool { + return strings.HasSuffix(typ, "_call_output") || typ == "tool_search_output" +} + +func isCodexDelegationCandidate(item map[string]any) bool { + if stringField(item, "type") != "function_call_output" || + !isCodexDelegationTool(stringField(item, "namespace"), stringField(item, "name")) { + return false + } + output, ok := item["output"].(string) + return ok && validCodexDelegationEnvelope(output) +} + +func isCodexAutomationCandidate(item map[string]any) bool { + if stringField(item, "type") != "function_call_output" || + stringField(item, "namespace") != "codex_app" || + stringField(item, "name") != "automation_update" { + return false + } + output, ok := item["output"].(string) + return ok && (validCodexAutomationBootstrap(output) || validCodexAutomationHeartbeat(output)) +} + +func stringField(item map[string]any, key string) string { + value, _ := item[key].(string) + return value +} + +func isCodexDelegationTool(namespace, name string) bool { + return (namespace == "codex_app" || namespace == "codex_tui") && + (name == "create_thread" || name == "send_message_to_thread") +} + +func validCodexAutomationBootstrap(value string) bool { + normalized := strings.ReplaceAll(value, "\r\n", "\n") + if strings.ContainsRune(normalized, '\r') { + return false + } + lines := strings.Split(normalized, "\n") + if len(lines) < 6 { + return false + } + if _, ok := codexAutomationHeaderValue(lines[0], "Automation: "); !ok { + return false + } + automationID, ok := codexAutomationHeaderValue(lines[1], "Automation ID: ") + if !ok || !validCodexAutomationID(automationID) { + return false + } + expectedMemory := "Automation memory: $CODEX_HOME/automations/" + automationID + "/memory.md" + if lines[2] != expectedMemory { + return false + } + lastRun, ok := codexAutomationHeaderValue(lines[3], "Last run: ") + if !ok || !validCodexAutomationLastRun(lastRun) || lines[4] != "" { + return false + } + return strings.TrimSpace(strings.Join(lines[5:], "\n")) != "" +} + +func codexAutomationHeaderValue(line, prefix string) (string, bool) { + if !strings.HasPrefix(line, prefix) { + return "", false + } + value := strings.TrimPrefix(line, prefix) + return value, value != "" && strings.TrimSpace(value) == value +} + +func validCodexAutomationID(value string) bool { + if len(value) == 0 || len(value) > 128 || value == "." || value == ".." { + return false + } + for i := 0; i < len(value); i++ { + c := value[i] + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' { + continue + } + return false + } + return true +} + +func validCodexAutomationLastRun(value string) bool { + if value == "never" { + return true + } + separator := strings.LastIndex(value, " (") + if separator <= 0 || !strings.HasSuffix(value, ")") { + return false + } + runAt, err := time.Parse(time.RFC3339Nano, value[:separator]) + if err != nil { + return false + } + epochMillis, err := strconv.ParseInt(value[separator+2:len(value)-1], 10, 64) + return err == nil && runAt.UnixMilli() == epochMillis +} + +func validCodexAutomationHeartbeat(value string) bool { + decoder := xml.NewDecoder(strings.NewReader(value)) + var rootSeen, automationIDSeen bool + var childName string + var childText bytes.Buffer + fields := make(map[string]string) + depth := 0 + for { + token, err := decoder.Token() + if err == io.EOF { + id := fields["automation_id"] + timestamp, hasTime := fields["current_time_iso"] + instructions, hasInstructions := fields["instructions"] + if hasTime != hasInstructions { + return false + } + if hasTime { + if _, err := time.Parse(time.RFC3339Nano, timestamp); err != nil || strings.TrimSpace(instructions) == "" { + return false + } + } + return rootSeen && automationIDSeen && depth == 0 && + strings.TrimSpace(id) == id && validCodexAutomationID(id) + } + if err != nil { + return false + } + switch current := token.(type) { + case xml.StartElement: + depth++ + if current.Name.Space != "" || len(current.Attr) != 0 || depth > 2 { + return false + } + if depth == 1 { + if rootSeen || current.Name.Local != "heartbeat" { + return false + } + rootSeen = true + } else { + childName = current.Name.Local + switch childName { + case "automation_id", "current_time_iso", "instructions": + default: + return false + } + if _, duplicate := fields[childName]; duplicate { + return false + } + childText.Reset() + } + case xml.EndElement: + if current.Name.Space != "" { + return false + } + if depth == 2 { + fields[childName] = childText.String() + automationIDSeen = automationIDSeen || childName == "automation_id" + } + depth-- + if depth < 0 { + return false + } + case xml.CharData: + if depth == 2 { + _, _ = childText.Write(current) + } else if len(bytes.TrimSpace(current)) != 0 { + return false + } + case xml.Comment, xml.ProcInst, xml.Directive: + return false + } + } +} + +func validCodexDelegationEnvelope(value string) bool { + decoder := xml.NewDecoder(strings.NewReader(value)) + var rootSeen, sourceSeen, inputSeen bool + var childName string + var childText bytes.Buffer + depth := 0 + for { + token, err := decoder.Token() + if err == io.EOF { + return rootSeen && depth == 0 && sourceSeen && inputSeen + } + if err != nil { + return false + } + switch current := token.(type) { + case xml.StartElement: + depth++ + if current.Name.Space != "" || len(current.Attr) != 0 || (depth == 1 && current.Name.Local != "codex_delegation") || depth > 2 { + return false + } + if depth == 1 { + if rootSeen { + return false + } + rootSeen = true + continue + } + if current.Name.Local != "source_thread_id" && current.Name.Local != "input" { + return false + } + childName = current.Name.Local + childText.Reset() + case xml.EndElement: + if current.Name.Space != "" { + return false + } + if depth == 2 { + if current.Name.Local != childName || strings.TrimSpace(childText.String()) == "" { + return false + } + if childName == "source_thread_id" { + if sourceSeen { + return false + } + sourceSeen = true + } else { + if inputSeen { + return false + } + inputSeen = true + } + childName = "" + } + depth-- + if depth < 0 { + return false + } + case xml.CharData: + if depth == 2 { + _, _ = childText.Write(current) + } else if len(bytes.TrimSpace(current)) != 0 { + return false + } + case xml.Comment: + return false + case xml.ProcInst, xml.Directive: + return false + } + } +} + +func (h *OpenAIGatewayHandler) acquireResponsesUserSlot( + c *gin.Context, + userID int64, + userConcurrency int, + reqStream bool, + streamStarted *bool, + reqLog *zap.Logger, +) (func(), bool) { + ctx := c.Request.Context() + userReleaseFunc, err := h.concurrencyHelper.AcquireUserSlotWithWait(c, userID, userConcurrency, reqStream, streamStarted) + if err != nil { + reqLog.Warn("openai.user_slot_acquire_failed", zap.Error(err)) + h.handleConcurrencyError(c, err, "user", *streamStarted) + return nil, false + } + return wrapReleaseOnDone(ctx, userReleaseFunc), true +} + +// openAISlotAcquireResult 是账号槽位获取的三态结果。 +type openAISlotAcquireResult int + +const ( + openAISlotAcquireOK openAISlotAcquireResult = iota + // openAISlotAcquireFailed:错误响应已写出,调用方直接 return。 + openAISlotAcquireFailed + // openAISlotAcquireProfitVetoed:槽位获取成功后利润终检否决。槽位已释放、 + // 未写任何响应;调用方应经 recordOpenAIProfitVeto 把该账号加入本请求排除集 + // 后重新选号,全池耗尽由下一轮选号返回标准 no available accounts。 + openAISlotAcquireProfitVetoed +) + +// openAIWSTurnPricing 持有 WebSocket 连接内「当前 turn」的计费定价时刻。 +// 由 BeforeTurn 在每个 turn 开始时冻结,AfterTurn 的用量提交读取它;turn 在 +// 连接内串行推进,互斥锁只为跨用量提交 goroutine 的读取安全。 +// +// 零值语义(重要):首轮准入由握手路径完成,不调用 BeforeTurn,因此首轮保持 +// 零值并回退到 TurnStarted 记录的首轮开始时刻。后续 turn 在 response.create +// 写入上游前调用 BeforeTurn,按当时的利润门复核并冻结定价。绝不能用建连时刻 +// 初始化,否则会把长连接的所有 turn 钉死在建连时的峰谷因子。 +type openAIWSTurnPricing struct { + mu sync.Mutex + at time.Time +} + +func (p *openAIWSTurnPricing) freeze(at time.Time) { + p.mu.Lock() + p.at = at + p.mu.Unlock() +} + +func (p *openAIWSTurnPricing) currentOr(fallback time.Time) time.Time { + p.mu.Lock() + defer p.mu.Unlock() + if !p.at.IsZero() { + return p.at + } + return fallback +} + +// openAIWSTurnAPIKeyLookup 是后续 turn 重取 API Key 认证快照的入口 +// (APIKeyService.GetByKey:经 L1/L2 认证缓存,未命中才回源)。 +type openAIWSTurnAPIKeyLookup interface { + GetByKey(ctx context.Context, key string) (*service.APIKey, error) +} + +// openAIWSTurnBillingAPIKeys 按 turn 号保存每个 turn 计费用的 API Key 快照。 +// +// API Key 认证快照只在建连时取一次。若连接内所有 turn 共用它,分组定价(倍率、 +// 高峰、图片定价、利润门参数)会停留在建连时刻:管理员调价后,已打开的长连接 +// 在客户端重连前一直按旧价计费、按旧售价过利润门,而 HTTP 请求每次都经认证缓存 +// 取快照,缓存失效后即生效。 +// +// 因此后续 turn 在 BeforeTurn(与 HTTP 请求进入认证中间件同位)经同一认证缓存 +// 重取快照,只采用其中的分组,作为该 turn 利润门准入与用量计费共同的分组;用户、 +// Key 限额、订阅仍沿用建连快照。只在同一把 Key、同一分组且平台与订阅类型未变时 +// 采用:Key 换组或分组改平台/订阅类型不是调价,该连接按建连分组调度,继续按建连 +// 快照计费;重取失败同样保留建连快照,不断连。 +// +// 首轮沿用刚经认证中间件取得的建连快照;没有经过 BeforeTurn 的 turn 回退建连 +// 快照。只保留当前与上一个 turn:下一 turn 的 BeforeTurn 先于上一 turn 的 +// AfterTurn 执行时,上一 turn 仍取到自己的快照。 +type openAIWSTurnBillingAPIKeys struct { + mu sync.Mutex + keys map[int]*service.APIKey +} + +// begin 在 BeforeTurn 重装利润门前调用:后续 turn 重取计费分组并按 turn 记下, +// 返回换入该分组的上下文供本 turn 的利润门使用。 +func (k *openAIWSTurnBillingAPIKeys) begin(ctx context.Context, apiKeyService *service.APIKeyService, turn int, conn *service.APIKey) context.Context { + turnKey := conn + if turn > 1 && apiKeyService != nil { + turnKey = refreshOpenAIWSTurnBillingAPIKey(ctx, apiKeyService, conn) + } + k.set(turn, turnKey) + return withOpenAIWSTurnBillingGroup(ctx, turnKey) +} + +func (k *openAIWSTurnBillingAPIKeys) set(turn int, key *service.APIKey) { + k.mu.Lock() + defer k.mu.Unlock() + if k.keys == nil { + k.keys = make(map[int]*service.APIKey, 2) + } + for t := range k.keys { + if t < turn-1 { + delete(k.keys, t) + } + } + k.keys[turn] = key +} + +func (k *openAIWSTurnBillingAPIKeys) forTurn(turn int, conn *service.APIKey) *service.APIKey { + k.mu.Lock() + defer k.mu.Unlock() + if key := k.keys[turn]; key != nil { + return key + } + return conn +} + +// refreshOpenAIWSTurnBillingAPIKey 返回本 turn 计费用的 API Key:分组取当前认证 +// 快照,其余字段与建连快照共享。不满足采用条件时原样返回建连快照。 +func refreshOpenAIWSTurnBillingAPIKey(ctx context.Context, lookup openAIWSTurnAPIKeyLookup, conn *service.APIKey) *service.APIKey { + if lookup == nil || conn == nil || conn.Key == "" || conn.GroupID == nil || conn.Group == nil { + return conn + } + latest, err := lookup.GetByKey(ctx, conn.Key) + if err != nil || latest == nil || latest.ID != conn.ID || latest.GroupID == nil || *latest.GroupID != *conn.GroupID { + return conn + } + group := latest.Group + if group == nil || group.ID != conn.Group.ID || + group.Platform != conn.Group.Platform || + group.SubscriptionType != conn.Group.SubscriptionType { + return conn + } + turnKey := *conn + turnKey.Group = group + return &turnKey +} + +// withOpenAIWSTurnBillingGroup 把本 turn 的计费分组换进认证分组上下文,使利润门 +// 的售价与本 turn 计费同源。上下文里没有同 ID 的认证分组时不改动。 +func withOpenAIWSTurnBillingGroup(ctx context.Context, turnKey *service.APIKey) context.Context { + if turnKey == nil || turnKey.Group == nil { + return ctx + } + current, ok := ctx.Value(ctxkey.Group).(*service.Group) + if !ok || current == nil || current == turnKey.Group || current.ID != turnKey.Group.ID { + return ctx + } + return context.WithValue(ctx, ctxkey.Group, turnKey.Group) +} + +// recordOpenAIProfitVeto 记录 OpenAI 侧选号循环的一次利润门终检否决:把账号 +// 加入本请求排除集并递增否决计数。返回 false 表示否决次数已达 +// maxProfitVetoAttempts,调用方必须停止重选并按「无可用账号」终止。 +// +// OpenAI 路径用的是各自的 failedAccountIDs map + for 循环(不是 FailoverState), +// 这里用一个独立计数器复用同一上限语义。上限是必需的:WaitPlan 分支先阻塞 +// 排队(sticky 45s / fallback 30s)拿到槽位才终检,无上限重选会把单次请求的 +// 延迟放大到 N × WaitPlan.Timeout。 +func recordOpenAIProfitVeto(failedAccountIDs map[int64]struct{}, accountID int64, vetoCount *int) bool { + failedAccountIDs[accountID] = struct{}{} + *vetoCount++ + return *vetoCount < maxProfitVetoAttempts +} + +// handleOpenAIProfitVetoExhausted 在利润否决预算耗尽时写出错误响应。 +// 与 acquireResponsesAccountSlot 内部的 no-available-accounts 失败分支同形, +// 保证同一调用方在两条路径上拿到一致的响应格式。 +func (h *OpenAIGatewayHandler) handleOpenAIProfitVetoExhausted( + c *gin.Context, + streamStarted bool, + reqLog *zap.Logger, + vetoCount int, +) { + reqLog.Warn("openai.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", vetoCount)) + markOpsRoutingCapacityLimited(c) + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage, streamStarted) +} + +func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot( + c *gin.Context, + groupID *int64, + sessionHash string, + selection *service.AccountSelectionResult, + reqStream bool, + streamStarted *bool, + reqLog *zap.Logger, +) (func(), openAISlotAcquireResult) { + return h.acquireOpenAIAccountSlot(c, groupID, sessionHash, selection, reqStream, streamStarted, reqLog, nil) +} + +type openAISlotErrorWriter func(status int, errType, code, message string) + +// acquireOpenAIAccountSlot centralizes scheduler selection admission. The +// optional error writer lets non-Responses endpoints retain their wire format +// while sharing the same WaitPlan, cancellation, and release semantics. +func (h *OpenAIGatewayHandler) acquireOpenAIAccountSlot( + c *gin.Context, + groupID *int64, + sessionHash string, + selection *service.AccountSelectionResult, + reqStream bool, + streamStarted *bool, + reqLog *zap.Logger, + writeError openAISlotErrorWriter, +) (func(), openAISlotAcquireResult) { + if writeError == nil { + writeError = func(status int, errType, code, message string) { + h.handleStreamingAwareErrorWithCode(c, status, errType, code, message, *streamStarted, false) + } + } + if selection == nil || selection.Account == nil { + markOpsRoutingCapacityLimited(c) + writeError(http.StatusServiceUnavailable, "api_error", "", "No available accounts") + return nil, openAISlotAcquireFailed + } + + // 终检与准入后绑定使用选号结果携带的门:composite 等跨分组调度解析出的 + // 门只存在于调度栈的局部 ctx,必须经选号结果重放到本函数的 ctx 上。 + ctx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection) + account := selection.Account + if selection.Acquired { + latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account) + if vetoed { + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + return nil, openAISlotAcquireProfitVetoed + } + account = latest + selection.Account = latest + // 调度器已抢槽路径无门时由选号内部完成 eager 绑定;门下选号内部 + // 推迟绑定,这里在终检通过后补准入后绑定。 + if selection.ProfitGateActive() { + if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil { + reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + } + } + return wrapReleaseOnDone(ctx, selection.ReleaseFunc), openAISlotAcquireOK + } + if selection.WaitPlan == nil { + markOpsRoutingCapacityLimited(c) + writeError(http.StatusServiceUnavailable, "api_error", "", "No available accounts") + return nil, openAISlotAcquireFailed + } + + fastReleaseFunc, fastAcquired, err := h.concurrencyHelper.TryAcquireAccountSlot( + ctx, + account.ID, + selection.WaitPlan.MaxConcurrency, + ) + if err != nil { + reqLog.Warn("openai.account_slot_quick_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + status, errType, code, message := concurrencyErrorResponse(err, "account") + writeError(status, errType, code, message) + return nil, openAISlotAcquireFailed + } + if fastAcquired { + // 分组利润控制:快速抢槽成功后终检。选号与抢槽之间账号 + // 倍率可能刷新,越线则释放槽位交由调用方排除重选,不绑定粘连。 + latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account) + if vetoed { + if fastReleaseFunc != nil { + fastReleaseFunc() + } + reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + return nil, openAISlotAcquireProfitVetoed + } + account = latest + selection.Account = latest + if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil { + reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + } + return wrapReleaseOnDone(ctx, fastReleaseFunc), openAISlotAcquireOK + } + + canWait, waitErr := h.concurrencyHelper.IncrementAccountWaitCount(ctx, account.ID, selection.WaitPlan.MaxWaiting) + if waitErr != nil { + reqLog.Warn("openai.account_wait_counter_increment_failed", zap.Int64("account_id", account.ID), zap.Error(waitErr)) + } else if !canWait { + reqLog.Info("openai.account_wait_queue_full", + zap.Int64("account_id", account.ID), + zap.Int("max_waiting", selection.WaitPlan.MaxWaiting), + ) + writeError(http.StatusTooManyRequests, "rate_limit_error", gatewayQueueFullCode, "Too many pending requests, please retry later") + return nil, openAISlotAcquireFailed + } + + accountWaitCounted := waitErr == nil && canWait + releaseWait := func() { + if accountWaitCounted { + h.concurrencyHelper.DecrementAccountWaitCount(ctx, account.ID) + accountWaitCounted = false + } + } + defer releaseWait() + + accountReleaseFunc, err := h.concurrencyHelper.AcquireAccountSlotWithWaitTimeout( + c, + account.ID, + selection.WaitPlan.MaxConcurrency, + selection.WaitPlan.Timeout, + reqStream, + streamStarted, + ) + if err != nil { + reqLog.Warn("openai.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + status, errType, code, message := concurrencyErrorResponse(err, "account") + writeError(status, errType, code, message) + return nil, openAISlotAcquireFailed + } + + // Slot acquired: no longer waiting in queue. + releaseWait() + // 分组利润控制:WaitPlan 排队成功后终检。排队期间账号倍率 + // 可能上调,越线则释放槽位交由调用方排除重选,不绑定粘连。 + latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account) + if vetoed { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + return nil, openAISlotAcquireProfitVetoed + } + account = latest + selection.Account = latest + if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil { + reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + } + return wrapReleaseOnDone(ctx, accountReleaseFunc), openAISlotAcquireOK +} + +// ResponsesWebSocket handles OpenAI Responses API WebSocket ingress endpoint +// GET /openai/v1/responses (Upgrade: websocket) +func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { + if !isOpenAIWSUpgradeRequest(c.Request) { + h.errorResponse(c, http.StatusUpgradeRequired, "invalid_request_error", "WebSocket upgrade required (Upgrade: websocket)") + return + } + setOpenAIClientTransportWS(c) + + apiKey, ok := middleware2.GetAPIKeyFromContext(c) + if !ok { + h.errorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key") + return + } + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + h.errorResponse(c, http.StatusInternalServerError, "api_error", "User context not found") + return + } + + reqLog := requestLogger( + c, + "handler.openai_gateway.responses_ws", + zap.Int64("user_id", subject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + zap.Bool("openai_ws_mode", true), + ) + if !h.ensureResponsesDependencies(c, reqLog) { + return + } + reqLog.Info("openai.websocket_ingress_started") + clientIP := ip.GetClientIP(c) + userAgent := strings.TrimSpace(c.GetHeader("User-Agent")) + clientLifecycleCtx := c.Request.Context() + ctx := clientLifecycleCtx + maxIngressConnections := 0 + if h.cfg != nil { + maxIngressConnections = h.cfg.Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey + } + ingressLease, ingressLeaseAcquired, ingressLeaseErr := h.concurrencyHelper.AcquireOpenAIWSIngressLease(ctx, apiKey.ID, maxIngressConnections) + if ingressLeaseErr != nil { + reqLog.Error("openai.websocket_ingress_lease_acquire_failed", zap.Error(ingressLeaseErr)) + h.errorResponse(c, http.StatusServiceUnavailable, "service_unavailable", "WebSocket ingress capacity is temporarily unavailable") + return + } + if !ingressLeaseAcquired { + reqLog.Info("openai.websocket_ingress_capacity_rejected", zap.Int("max_ingress_connections_per_api_key", maxIngressConnections)) + c.Header("Retry-After", "5") + h.errorResponse(c, http.StatusTooManyRequests, "rate_limit_error", "Too many open WebSocket connections, please retry later") + return + } + if ingressLease != nil { + defer ingressLease.Release() + ctx = ingressLease.Context() + c.Request = c.Request.WithContext(ctx) + } + + wsConn, err := coderws.Accept(c.Writer, c.Request, &coderws.AcceptOptions{ + CompressionMode: coderws.CompressionContextTakeover, + }) + if err != nil { + reqLog.Warn("openai.websocket_accept_failed", + zap.Error(err), + zap.String("client_ip", clientIP), + zap.String("request_user_agent", userAgent), + zap.String("upgrade_header", strings.TrimSpace(c.GetHeader("Upgrade"))), + zap.String("connection_header", strings.TrimSpace(c.GetHeader("Connection"))), + zap.String("sec_websocket_version", strings.TrimSpace(c.GetHeader("Sec-WebSocket-Version"))), + zap.Bool("has_sec_websocket_key", strings.TrimSpace(c.GetHeader("Sec-WebSocket-Key")) != ""), + ) + return + } + defer func() { + _ = wsConn.CloseNow() + }() + wsConn.SetReadLimit(service.ResolveOpenAIWSClientReadLimitBytes(h.cfg)) + + firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg) + msgType, firstMessage, err := service.ReadOpenAIWSClientMessage( + ctx, + wsConn, + firstMessageTimeout, + coderws.StatusPolicyViolation, + "missing first response.create message", + ) + if err != nil { + if errors.Is(context.Cause(ctx), service.ErrOpenAIWSIngressLeaseLost) { + reqLog.Warn("openai.websocket_ingress_lease_lost_before_first_message", zap.Error(err)) + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "websocket ingress capacity lease lost; please reconnect") + return + } + closeStatus, closeReason := summarizeWSCloseErrorForLog(err) + reqLog.Warn("openai.websocket_read_first_message_failed", + zap.Error(err), + zap.String("client_ip", clientIP), + zap.String("close_status", closeStatus), + zap.String("close_reason", closeReason), + zap.Duration("read_timeout", firstMessageTimeout), + ) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "missing first response.create message") + return + } + firstTurnStartedAt := time.Now() + if msgType != coderws.MessageText && msgType != coderws.MessageBinary { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "unsupported websocket message type") + return + } + if !gjson.ValidBytes(firstMessage) { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "invalid JSON payload") + return + } + reqModel := strings.TrimSpace(gjson.GetBytes(firstMessage, "model").String()) + if reqModel == "" { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "model is required in first response.create payload") + return + } + // 分组级模型白名单:首帧校验客户端模型,不通过则关闭连接并标记运维原因。 + // 必须在合成路由解析和上游模型映射之前执行。 + // 与 HTTP 准入一致:帧内重复 model 键/大小写变体可能被上游按末值绑定, + // 全部候选值逐一校验,任一未命中即拒绝。 + if blocked := blockedModelAllowlistCandidate(apiKey.Group, requestmodel.FromBodyCandidates("", "application/json", firstMessage)); blocked != "" { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked)) + return + } + // Keep the client model in the frame for admission, response identity and usage. + // Apply the resolved upstream model through MapRequestModel on every turn. + wsRouteModel := reqModel + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite { + decision, resolveErr := h.compositeResolver.Resolve(c.Request.Context(), apiKey.Group.ID, reqModel, service.CompositeRouteEndpointResponses) + if resolveErr != nil { + reqLog.Error("openai.websocket_composite_route_failed", zap.Error(resolveErr)) + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "Failed to resolve composite model route") + return + } + if decision.OAuthAmbiguous() { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, decision.AmbiguousMessage()) + return + } + if decision.Matched { + c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) + wsRouteModel = decision.UpstreamModel + } + } + ctx = c.Request.Context() + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite { + platform, ok := service.ResolvedTargetPlatformFromContext(ctx) + if !ok || !isResponsesWebSocketCompositePlatform(platform) { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "Responses WebSocket API only supports OpenAI-compatible models for composite groups") + return + } + } + previousResponseID := strings.TrimSpace(gjson.GetBytes(firstMessage, "previous_response_id").String()) + previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID) + if previousResponseID != "" && previousResponseIDKind == service.OpenAIPreviousResponseIDKindMessageID { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "previous_response_id must be a response.id (resp_*), not a message id") + return + } + firstMessageToolCoverage := service.AnalyzeToolCallOutputContextCoverageBytes(firstMessage) + previousResponseCanMove := !firstMessageToolCoverage.HasFunctionCallOutput || firstMessageToolCoverage.ContextCoversAllCallIDs + reqLog = reqLog.With( + zap.Bool("ws_ingress", true), + zap.String("session_initial_model", reqModel), + zap.Bool("has_previous_response_id", previousResponseID != ""), + zap.String("previous_response_id_kind", previousResponseIDKind), + ) + setOpsRequestContext(c, reqModel, true) + setOpsEndpointContext(c, "", int16(service.RequestTypeWSV2)) + + if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, firstMessage, "first_turn"); decision != nil && !decision.AllowNextStage { + writeSecurityAuditWSError(ctx, wsConn, decision) + closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision)) + return + } + + imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, firstMessage) + if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, service.ImageGenerationPermissionMessage()) + return + } + + // The first response.create frame is available here, so explicit IDs are + // checked directly and body-derived sessions use the coarse scope gate. + if cyberBlockKey := h.findBlockedCyberSessionForAPIKey(c, apiKey, firstMessage); cyberBlockKey != "" { + writeCyberSessionBlockedWSError(c.Request.Context(), wsConn) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "session blocked by cyber-security policy") + h.enqueueCyberSessionBlockedOpsEntry(c, apiKey, reqModel, cyberBlockKey) + return + } + cyberBlockedThisConn := false + cyberBlockPendingAfterFailover := false + var cyberTurnBodiesMu sync.Mutex + cyberTurnBodies := map[int][]byte{1: append([]byte(nil), firstMessage...)} + setCyberTurnBody := func(turn int, payload []byte) { + cyberTurnBodiesMu.Lock() + cyberTurnBodies[turn] = append([]byte(nil), payload...) + cyberTurnBodiesMu.Unlock() + } + takeCyberTurnBody := func(turn int) []byte { + cyberTurnBodiesMu.Lock() + body := cyberTurnBodies[turn] + delete(cyberTurnBodies, turn) + cyberTurnBodiesMu.Unlock() + return body + } + + // 解析渠道级模型映射 + channelMappingWS, _ := h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, wsRouteModel) + wsForwardModel := openAIChannelForwardModel(channelMappingWS, wsRouteModel) + + var currentUserRelease func() + var currentAccountRelease func() + releaseAccountSlot := func() { + if currentAccountRelease != nil { + currentAccountRelease() + currentAccountRelease = nil + } + } + releaseTurnSlots := func() { + releaseAccountSlot() + if currentUserRelease != nil { + currentUserRelease() + currentUserRelease = nil + } + } + // 必须尽早注册,确保任何 early return 都能释放已获取的并发槽位。 + defer releaseTurnSlots() + + userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID) + if err != nil { + reqLog.Warn("openai.websocket_user_slot_acquire_failed", zap.Error(err)) + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot") + return + } + if !userAcquired { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "too many concurrent requests, please retry later") + return + } + currentUserRelease = wrapReleaseOnDone(ctx, userReleaseFunc) + ensureUserSlotHeld := func() bool { + if currentUserRelease != nil { + return true + } + userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID) + if err != nil { + reqLog.Warn("openai.websocket_user_slot_reacquire_failed", zap.Error(err)) + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot") + return false + } + if !userAcquired { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "too many concurrent requests, please retry later") + return false + } + currentUserRelease = wrapReleaseOnDone(ctx, userReleaseFunc) + return true + } + + subscription, _ := middleware2.GetSubscriptionFromContext(c) + requestPlatform := openAICompatibleRequestPlatform(ctx, apiKey) + requiredTransport := service.OpenAIUpstreamTransportResponsesWebsocketV2Ingress + if requestPlatform == service.PlatformGrok { + requiredTransport = service.OpenAIUpstreamTransportHTTPSSE + } + if err := h.billingCacheService.CheckBillingEligibility(ctx, apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { + reqLog.Info("openai.websocket_billing_eligibility_check_failed", zap.Error(err)) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") + return + } + + // 余额模式在途预留(会话级):按首帧估算一次,会话期间续期;每轮计费任务接管引用, + // 会话结束且所有轮次扣减落地后释放。 + inflightCtx, inflightDone, inflightErr := reserveInflightBalanceCtx(ctx, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, firstMessage)) + if inflightErr != nil { + reqLog.Info("openai.websocket_inflight_reservation_rejected", zap.Error(inflightErr)) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") + return + } + defer inflightDone() + ctx = inflightCtx + + // A WebSocket may outlive a key's remaining spending window. Recheck + // after acquiring turn slots, including the first account-selection wait. + // Restrict this extra check to the opt-in mode so standard-mode RPM checks + // are not charged a second time for the same request. + checkSimpleModeTurnBilling := func() error { + if h.cfg == nil || h.cfg.RunMode != config.RunModeSimple || !h.cfg.SimpleModeKeyRateLimitEnabled { + return nil + } + if err := h.billingCacheService.CheckBillingEligibility(ctx, apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(ctx, apiKey)); err != nil { + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "billing check failed", err) + } + return nil + } + + sessionHash := h.gatewayService.GenerateSessionHashWithFallback( + c, + firstMessage, + openAIWSIngressFallbackSessionSeed(subject.UserID, apiKey.ID, apiKey.GroupID), + ) + ctx = service.WithOpenAIGuardianParentAffinity(ctx, c, firstMessage, reqModel) + maxAccountSwitches := h.maxAccountSwitches + switchCount := 0 + profitVetoCount := 0 + failedAccountIDs := make(map[int64]struct{}) + sameAccountRetryCount := make(map[int64]int) + var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState + wsAttemptMessage := append([]byte(nil), firstMessage...) + waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { + if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() { + return false + } + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) + if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + return false + } + sameAccountRetryCount[account.ID]++ + retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) + reqLog.Warn("openai.websocket.same_account_retry", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("retry_count", sameAccountRetryCount[account.ID]), + zap.Duration("retry_delay", retryDelay), + ) + select { + case <-ctx.Done(): + return false + case <-time.After(retryDelay): + return true + } + } + handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { + if ctx.Err() != nil { + return false + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, wsForwardModel, false, nil), false, nil, failoverErr) + } + releaseAccountSlot() + if !failoverErr.ShouldRetryNextAccount() { + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return false + } + if ctx.Err() != nil { + return false + } + h.gatewayService.RecordOpenAIAccountSwitch() + failedAccountIDs[account.ID] = struct{}{} + lastFailoverErr = failoverErr + if switchCount >= maxAccountSwitches { + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return false + } + switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return false + } + reqLog.Warn("openai.websocket_upstream_failover_switching", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("switch_count", switchCount), + zap.Int("max_switches", maxAccountSwitches), + ) + if ctx.Err() != nil { + return false + } + return ensureUserSlotHeld() + } + + // 与 HTTP Responses 路径保持一致:生图意图请求要求账号支持 Responses API(#4417)。 + // WSv2 传输本身已隐含 Responses 支持,此处为防御性对齐。 + // 使用 IsExplicitImageGenerationIntent 排除被动 namespace 声明(#4476)。 + requiredCapability := service.OpenAIEndpointCapabilityChatCompletions + if service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, firstMessage) && requestPlatform == service.PlatformOpenAI { + requiredCapability = service.OpenAIEndpointCapabilityResponses + } + + // 分组利润控制:WS 桥按连接装配定价上下文并装门(选号与抢槽共用该 + // ctx)。连接内不重选号,但每个 turn 开始经 BeforeTurn 重新冻结 pricingAt + // 并按最新门复核当前账号(准入与计费同源),峰前建连保活不能让后续 turn + // 继续按建连时刻的谷价计费。生图意图只影响能力路由与图片计费,不关门。 + // 建连时刻只用于选号/准入,不作为任何 turn 的计费定价时刻。 + wsPricingCtx, _ := h.gatewayService.WithOpenAIRequestPricingContext(ctx, apiKey.GroupID) + ctx = wsPricingCtx + + for { + if ctx.Err() != nil { + return + } + reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) + selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( + ctx, + apiKey.GroupID, + previousResponseID, + sessionHash, + wsForwardModel, + failedAccountIDs, + requiredTransport, + requiredCapability, + false, + previousResponseCanMove, + !imageIntent, + requestPlatform, + ) + if err != nil { + reqLog.Warn("openai.websocket_account_select_failed", + zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), + zap.Int("excluded_account_count", len(failedAccountIDs)), + ) + if lastFailoverErr != nil { + closeOpenAIWSFailoverExhausted(c, wsConn, lastFailoverErr) + } else { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account") + } + return + } + if selection == nil || selection.Account == nil { + if lastFailoverErr != nil { + closeOpenAIWSFailoverExhausted(c, wsConn, lastFailoverErr) + } else { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account") + } + return + } + + account := selection.Account + accountMaxConcurrency := account.Concurrency + if selection.WaitPlan != nil && selection.WaitPlan.MaxConcurrency > 0 { + accountMaxConcurrency = selection.WaitPlan.MaxConcurrency + } + // 终检、准入后绑定与后续 turn 级复核都使用选号结果携带的门(composite + // 等跨分组调度的门只存在于调度栈局部 ctx);准入成功后并入连接 ctx。 + admissionCtx := service.ContextWithSelectionProfitGate(ctx, selection) + accountReleaseFunc := selection.ReleaseFunc + if selection.Acquired { + // 调度器已抢槽路径同样终检:选号与抢槽之间账号倍率可能刷新。 + latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(admissionCtx, account) + if vetoed { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + reqLog.Debug("openai.websocket_account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) { + reqLog.Warn("openai.websocket_profit_veto_attempts_exhausted", zap.Int("profit_veto_count", profitVetoCount)) + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account") + return + } + continue + } + account = latest + selection.Account = latest + } + if !selection.Acquired { + if selection.WaitPlan == nil { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account is busy, please retry later") + return + } + fastReleaseFunc, fastAcquired, err := h.concurrencyHelper.TryAcquireAccountSlot( + ctx, + account.ID, + selection.WaitPlan.MaxConcurrency, + ) + if err != nil { + reqLog.Warn("openai.websocket_account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire account concurrency slot") + return + } + if !fastAcquired { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account is busy, please retry later") + return + } + // 分组利润控制:WS 快速抢槽成功后终检,越线则释放 + // 槽位、排除该账号重新选号,全池耗尽由下一轮选号关闭连接。 + latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(admissionCtx, account) + if vetoed { + if fastReleaseFunc != nil { + fastReleaseFunc() + } + reqLog.Debug("openai.websocket_account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) { + reqLog.Warn("openai.websocket_profit_veto_attempts_exhausted", zap.Int("profit_veto_count", profitVetoCount)) + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account") + return + } + continue + } + account = latest + selection.Account = latest + accountReleaseFunc = fastReleaseFunc + } + // 准入完成:门并入连接 ctx,turn 级复核与 failover 重选共用。 + ctx = admissionCtx + // Account selection starts a fresh upstream attempt. Clear any model + // captured by the previous failover account before credential lookup. + setOpsSelectedAccount(c, account.ID, account.Platform) + currentAccountRelease = wrapReleaseOnDone(ctx, accountReleaseFunc) + if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, apiKey.GroupID, sessionHash, account.ID); err != nil { + reqLog.Warn("openai.websocket_bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + } + + token, _, err := h.gatewayService.GetRequestCredential(ctx, c, account) + if err != nil { + reqLog.Warn("openai.websocket_get_access_token_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + if ctx.Err() != nil { + return + } + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + if handleWSFailover(account, failoverErr) { + continue + } + return + } + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to get access token") + return + } + + reqLog.Debug("openai.websocket_account_selected", + zap.Int64("account_id", account.ID), + zap.String("account_name", account.Name), + zap.String("schedule_layer", scheduleDecision.Layer), + zap.Int("candidate_count", scheduleDecision.CandidateCount), + ) + + maxReasoningEffort, reasoningEffortMappings, maxReasoningEffortOverLimit, _ := openAIReasoningEffortPolicyForRequest(c, apiKey) + var requestPayloadHash string + var turnStartsMu sync.Mutex + turnStarts := make(map[int]time.Time, 4) + recordTurnStart := func(turn int, startedAt time.Time) { + if turn <= 0 || startedAt.IsZero() { + return + } + turnStartsMu.Lock() + turnStarts[turn] = startedAt + turnStartsMu.Unlock() + } + getTurnStart := func(turn int) time.Time { + turnStartsMu.Lock() + startedAt := turnStarts[turn] + delete(turnStarts, turn) + turnStartsMu.Unlock() + return startedAt + } + // Passthrough rejects overlapping response.create frames, so one immutable + // turn-tagged slot preserves the exact mapping used for the in-flight request. + var turnChannelMapping atomic.Pointer[openAIWSTurnChannelMappingSnapshot] + turnChannelMapping.Store(&openAIWSTurnChannelMappingSnapshot{turn: 1, mapping: channelMappingWS}) + // turn 级定价:首轮回退到 TurnStarted 的所属 turn 时刻;后续 turn 由 + // BeforeTurn 重新冻结 pricingAt 并按最新门复核当前账号。 + var turnPricing openAIWSTurnPricing + // 后续 turn 的计费分组同样在 BeforeTurn 经认证缓存重取,使分组调价对 + // 已打开的连接生效。 + var turnBillingAPIKeys openAIWSTurnBillingAPIKeys + // Passthrough ingress does not invoke BeforeTurn for the first frame. + if err := checkSimpleModeTurnBilling(); err != nil { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") + return + } + hooks := &service.OpenAIWSIngressHooks{ + ClientLifecycleContext: clientLifecycleCtx, + InitialRequestModel: reqModel, + InitialTurnStartedAt: firstTurnStartedAt, + MaxReasoningEffort: maxReasoningEffort, + MaxReasoningEffortOverLimit: maxReasoningEffortOverLimit, + ReasoningEffortMappings: reasoningEffortMappings, + TurnStarted: recordTurnStart, + BeforeRequest: func(turn int, payload []byte, originalModel string) error { + c.Set(securityAuditWSTurnContextKey, turn) + service.BeginOpsStreamTurn(c, turn) + setCyberTurnBody(turn, payload) + // 连接级 cyber session gate 也在 BeforeRequest 先执行,使 native 与 + // passthrough ingress 都能在 BeforeTurn 及上游写入前无副作用地拒绝。 + // BeforeTurn 中保留同一检查作为防御式兜底。 + if cyberBlockedThisConn && !h.cyberPolicyLogOnly(c, apiKey) { + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, cyberSessionBlockedClientMsg, nil) + } + if turn == 1 { + return nil + } + if !gjson.ValidBytes(payload) { + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", errors.New("invalid json")) + } + model := strings.TrimSpace(originalModel) + if model == "" { + model = strings.TrimSpace(gjson.GetBytes(payload, "model").String()) + } + if model == "" { + model = reqModel + } + // 分组级模型白名单:后续 turn 同样校验客户端模型(省略 model 时 + // 沿用会话实际生效模型,含 session.update 轮换后的模型),不通过 + // 则关闭整条连接,与推理强度 deny 一致。实际生效模型始终参与校验; + // 帧内重复 model 键/大小写变体/嵌套 session.model 额外逐一校验, + // 防止候选集非空时掩盖被轮换掉的禁用模型。 + candidates := append([]string{model}, requestmodel.FromBodyCandidates("", "application/json", payload)...) + if blocked := blockedModelAllowlistCandidate(apiKey.Group, candidates); blocked != "" { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked), nil) + } + if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, payload, "subsequent_turn"); decision != nil && !decision.AllowNextStage { + writeSecurityAuditWSError(ctx, wsConn, decision) + return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil) + } + return nil + }, + MapRequestModel: func(turn int, originalModel string) (string, error) { + model := strings.TrimSpace(originalModel) + if model == "" { + model = reqModel + } + setOpsRequestContext(c, model, true) + routeModel := model + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite { + // The account, target platform and route context are connection-scoped. + // A different public model needs a new connection and fresh resolution. + if model != reqModel { + return "", newOpenAIWSUnsupportedModelSwitchError(model) + } + routeModel = wsRouteModel + } + mapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, routeModel) + mappedModelUnchanged := false + if previous := turnChannelMapping.Load(); previous != nil && previous.turn < turn { + mappedModelUnchanged = strings.TrimSpace(previous.mapping.MappedModel) == strings.TrimSpace(mapping.MappedModel) + } + if turn > 1 && !mappedModelUnchanged && !account.IsModelSupported(model) && !account.IsModelSupported(mapping.MappedModel) { + return "", newOpenAIWSUnsupportedModelSwitchError(mapping.MappedModel) + } + turnChannelMapping.Store(&openAIWSTurnChannelMappingSnapshot{turn: turn, mapping: mapping}) + return mapping.MappedModel, nil + }, + BeforeTurn: func(turn int) error { + // turn==1 的会话屏蔽已由握手层检查覆盖;连接内 flag 只拦截后续 turn。 + if cyberBlockedThisConn && !h.cyberPolicyLogOnly(c, apiKey) { + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, cyberSessionBlockedClientMsg, nil) + } + // 长连接跨峰谷/倍率刷新防护:每个 turn 按当前时刻重装门并复核 + // 当前账号,越线即要求客户端重连重选(连接绑定单一上游账号, + // 无法中途换号)。本 turn 的准入与计费共用同一 pricingAt。 + turnBillingCtx := turnBillingAPIKeys.begin(ctx, h.apiKeyService, turn, apiKey) + turnCtx, turnAt := h.gatewayService.WithOpenAITurnPricingContext(turnBillingCtx, apiKey.GroupID) + if _, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(turnCtx, account); vetoed { + reqLog.Info("openai.websocket_turn_profit_vetoed", + zap.Int("turn", turn), + zap.Int64("account_id", account.ID), + zap.String("reason", reason)) + return service.NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, "account is no longer eligible for this connection, please reconnect", nil) + } + turnPricing.freeze(turnAt) + if turn == 1 { + return nil + } + // 防御式清理:避免异常路径下旧槽位覆盖导致泄漏。 + releaseTurnSlots() + // 非首轮 turn 需要重新抢占并发槽位,避免长连接空闲占槽。 + userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID) + if err != nil { + return service.NewOpenAIWSClientCloseError(coderws.StatusInternalError, "failed to acquire user concurrency slot", err) + } + if !userAcquired { + return service.NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, "too many concurrent requests, please retry later", nil) + } + accountReleaseFunc, accountAcquired, err := h.concurrencyHelper.TryAcquireAccountSlot(ctx, account.ID, accountMaxConcurrency) + if err != nil { + if userReleaseFunc != nil { + userReleaseFunc() + } + return service.NewOpenAIWSClientCloseError(coderws.StatusInternalError, "failed to acquire account concurrency slot", err) + } + if !accountAcquired { + if userReleaseFunc != nil { + userReleaseFunc() + } + return service.NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, "account is busy, please retry later", nil) + } + currentUserRelease = wrapReleaseOnDone(ctx, userReleaseFunc) + currentAccountRelease = wrapReleaseOnDone(ctx, accountReleaseFunc) + return checkSimpleModeTurnBilling() + }, + AfterTurn: func(turn int, result *service.OpenAIForwardResult, turnErr error) { + turnStart := getTurnStart(turn) + cyberBlockBody := takeCyberTurnBody(turn) + // 每次 attempt 都清 cyber mark;failover 链结束前保留 recorded guard, + // 避免同一逻辑 turn 换号后重复落风控。CyberBlocked 必须在 submit 前 + // 同步预捕获(task 闭包由 worker 池异步执行,届时 mark 已清除)。 + defer func() { + clearCyberPolicyAttemptState(c, !cyberBlockPendingAfterFailover) + }() + releaseTurnSlots() + turnRequestedModel := reqModel + turnUpstreamModel := "" + if result != nil && turn > 1 { + if model := strings.TrimSpace(result.Model); model != "" { + turnRequestedModel = model + } + } + if result != nil { + turnUpstreamModel = strings.TrimSpace(result.UpstreamModel) + } + var turnMapping service.ChannelMappingResult + if snapshot := turnChannelMapping.Load(); snapshot != nil && snapshot.turn == turn { + turnMapping = snapshot.mapping + } else { + turnMapping, _ = h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, turnRequestedModel) + } + if turnUpstreamModel == "" { + turnUpstreamModel = turnRequestedModel + } + turnUsageFields := turnMapping.ToUsageFields(turnRequestedModel, turnUpstreamModel) + cyberMarked := service.GetOpsCyberPolicy(c) != nil + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, turnRequestedModel, turnErr != nil, cyberBlockBody, turnUsageFields, requestPayloadHash) + cyberBlockedThisConn, cyberBlockPendingAfterFailover = advanceOpenAIWSCyberBlockState( + cyberBlockedThisConn, + cyberBlockPendingAfterFailover, + cyberMarked && !h.cyberPolicyLogOnly(c, apiKey), + turnErr, + ) + if turnErr != nil { + if result == nil || result.ImageCount <= 0 { + return + } + // cyber 命中时该 turn 的用量已由 recordCyberPolicyIfMarked(forwardErrored=true) + // 按真实 token 记录,这里不再走下方 RecordUsage,避免对同一 turn 双写/双扣费。 + if service.GetOpsCyberPolicy(c) != nil { + return + } + reqLog.Warn("openai.websocket_partial_error_with_image_result", + zap.Int64("account_id", account.ID), + zap.Int("image_count", result.ImageCount), + zap.Error(turnErr), + ) + } + if result == nil { + return + } + result.BillingModel = openAIWSTurnBillingModel(result, turnMapping, turnRequestedModel, turnUpstreamModel) + reqLog.Debug("openai.websocket_turn_billing", + zap.Int("turn", turn), + zap.String("turn_requested_model", turnRequestedModel), + zap.String("turn_upstream_model", turnUpstreamModel), + zap.String("billing_model", result.BillingModel), + ) + // 排除 spark 影子:其 codex_* 仅由 QueryUsage(/wham/usage bengalfox)更新(外审第7轮 P1)。 + if account.Type == service.AccountTypeOAuth && !account.IsShadow() { + h.gatewayService.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, result.ResponseHeaders) + } + scheduleModel := turnUpstreamModel + if scheduleModel == "" { + scheduleModel = turnRequestedModel + } + h.gatewayService.ReportOpenAIAccountScheduleResult(account, scheduleModel, openAIForwardSucceededForScheduling(result), result.FirstTokenMs) + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, result) + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + sessionID := service.ExtractClientSessionID(c) + turnRecordPricingAt := turnPricing.currentOr(turnStart) + turnBillingAPIKey := turnBillingAPIKeys.forTurn(turn, apiKey) + cyberBlocked := service.GetOpsCyberPolicy(c) != nil + h.submitOpenAIUsageRecordTask(ctx, result, func(taskCtx context.Context) { + if err := h.gatewayService.RecordUsage(taskCtx, &service.OpenAIRecordUsageInput{ + Result: result, + APIKey: turnBillingAPIKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: quotaPlatform, + SessionID: sessionID, + ChannelUsageFields: turnUsageFields, + PricingAt: turnRecordPricingAt, + CyberBlocked: cyberBlocked, + }); err != nil { + reqLog.Error("openai.websocket_record_usage_failed", + zap.Int64("account_id", account.ID), + zap.String("request_id", result.RequestID), + zap.Error(err), + ) + } + }) + }, + } + + wsFirstMessage := wsAttemptMessage + // 切组/会话失配防护:previous_response_id 未在当前分组命中粘连账号(StickyPreviousHit=false), + // 说明该会话链不属于本次调度到的账号,原样转发会触发上游会话链鉴权失败(“鉴权失败,请检查 API Key”)。 + // 故剥离首包里的 previous_response_id,改用首包内 input 重建上下文;带 function_call_output 的 + // 工具续链无法重建,保持原样。仅作用于首轮首包,后续 turn 的续链由 WS 转发层既有逻辑处理。 + if previousResponseID != "" && !scheduleDecision.StickyPreviousHit && previousResponseCanMove { + wsFirstMessage = service.RemovePreviousResponseIDFromBody(wsFirstMessage) + reqLog.Debug("openai.websocket_previous_response_id_stripped_cross_group", + zap.Int64("account_id", account.ID), + zap.String("schedule_layer", scheduleDecision.Layer), + ) + } + + // WebSocket 首包可能很大,hash 必须在 hooks 外算成字符串,避免 AfterTurn 闭包保活请求体。 + requestPayloadHash = service.HashUsageRequestPayload(wsFirstMessage) + if preemptCtx, cleanupPreempt, armed := h.gatewayService.BeginOpenAIWSIngressSessionPreemptionWithClient(ctx, c, account, wsFirstMessage, wsConn); armed { + ctx = preemptCtx + defer cleanupPreempt() + } + + for { + err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks) + if err == nil { + reqLog.Info("openai.websocket_ingress_closed", zap.Int64("account_id", account.ID)) + return + } + if service.IsOpenAIWSSessionPreemptedError(err) { + // 关闭帧已由抢占登记在取消前发给本连接,这里只记录并释放。 + reqLog.Info("openai.websocket_ingress_preempted", zap.Int64("account_id", account.ID)) + return + } + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + retryPayload, retryCurrentTurn := service.OpenAIWSCurrentTurnRetryPayload(err) + nextAttemptMessage, retrySafe := openAIWSNextAttemptMessage(wsAttemptMessage, retryPayload, retryCurrentTurn) + if !retrySafe { + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return + } + wsAttemptMessage = nextAttemptMessage + if retryCurrentTurn { + previousResponseID = "" + reqLog.Warn("openai.websocket_current_turn_failover_retry", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("retry_payload_bytes", len(retryPayload)), + ) + } + if waitForWSSameAccountRetry(account, failoverErr) { + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, wsForwardModel, false, nil), false, nil, err) + } + if !ensureUserSlotHeld() { + return + } + if currentAccountRelease == nil { + accountRelease, acquired, acquireErr := h.concurrencyHelper.TryAcquireAccountSlot(ctx, account.ID, accountMaxConcurrency) + if acquireErr != nil || !acquired { + reqLog.Warn("openai.websocket_same_account_retry_slot_unavailable", + zap.Int64("account_id", account.ID), + zap.Error(acquireErr), + ) + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account is busy, please retry later") + return + } + currentAccountRelease = wrapReleaseOnDone(ctx, accountRelease) + } + wsFirstMessage = wsAttemptMessage + continue + } + if handleWSFailover(account, failoverErr) { + break + } + return + } + + if errors.Is(context.Cause(ctx), service.ErrOpenAIWSIngressLeaseLost) { + reqLog.Warn("openai.websocket_ingress_lease_lost", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "websocket ingress capacity lease lost; please reconnect") + return + } + + var closeErr *service.OpenAIWSClientCloseError + hasClientCloseErr := errors.As(err, &closeErr) + if openAIWSIngressEndedByClient(err) { + closedFields := []zap.Field{zap.Int64("account_id", account.ID)} + if hasClientCloseErr { + closedFields = append(closedFields, zap.String("reason", closeErr.Reason())) + } else { + closedFields = append(closedFields, zap.Error(err)) + } + reqLog.Info("openai.websocket_ingress_closed_normally", closedFields...) + // A bare coderws.CloseError or a plain cancellation carries no + // gateway-chosen close frame; mirror the client's clean 1000 + // rather than the 1011 the proxy-failure tail would have sent. + if hasClientCloseErr { + closeOpenAIClientWS(wsConn, closeErr.StatusCode(), closeErr.Reason()) + } else { + closeOpenAIClientWS(wsConn, coderws.StatusNormalClosure, "") + } + return + } + + if shouldReportOpenAIWSProxyAccountFailure(err) { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, wsForwardModel, false, nil), false, nil, err) + } + closeStatus, closeReason := summarizeWSCloseErrorForLog(err) + proxyFailedFields := []zap.Field{ + zap.Int64("account_id", account.ID), + zap.Error(err), + zap.String("close_status", closeStatus), + zap.String("close_reason", closeReason), + } + if account.Proxy != nil { + proxyFailedFields = append(proxyFailedFields, + zap.Int64("proxy_id", account.Proxy.ID), + zap.String("proxy_name", account.Proxy.Name), + zap.String("proxy_host", account.Proxy.Host), + zap.Int("proxy_port", account.Proxy.Port), + ) + } else if account.ProxyID != nil { + proxyFailedFields = append(proxyFailedFields, zap.Int64p("proxy_id", account.ProxyID)) + } + reqLog.Warn("openai.websocket_proxy_failed", proxyFailedFields...) + if hasClientCloseErr { + closeOpenAIClientWS(wsConn, closeErr.StatusCode(), closeErr.Reason()) + return + } + closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "upstream websocket proxy failed") + return + } + } + +} + +func (h *OpenAIGatewayHandler) recoverResponsesPanic(c *gin.Context, streamStarted *bool) { + recovered := recover() + if recovered == nil { + return + } + + started := false + if streamStarted != nil { + started = *streamStarted + } + wroteFallback := h.ensureForwardErrorResponse(c, started) + requestLogger(c, "handler.openai_gateway.responses").Error( + "openai.responses_panic_recovered", + zap.Bool("fallback_error_response_written", wroteFallback), + zap.Any("panic", recovered), + zap.ByteString("stack", debug.Stack()), + ) +} + +// recoverAnthropicMessagesPanic recovers from panics in the Anthropic Messages +// handler and returns an Anthropic-formatted error response. +func (h *OpenAIGatewayHandler) recoverAnthropicMessagesPanic(c *gin.Context, streamStarted *bool) { + recovered := recover() + if recovered == nil { + return + } + + started := streamStarted != nil && *streamStarted + requestLogger(c, "handler.openai_gateway.messages").Error( + "openai.messages_panic_recovered", + zap.Bool("stream_started", started), + zap.Any("panic", recovered), + zap.ByteString("stack", debug.Stack()), + ) + if !started { + h.anthropicErrorResponse(c, http.StatusInternalServerError, "api_error", "Internal server error") + } +} + +func (h *OpenAIGatewayHandler) ensureResponsesDependencies(c *gin.Context, reqLog *zap.Logger) bool { + missing := h.missingResponsesDependencies() + if len(missing) == 0 { + return true + } + + if reqLog == nil { + reqLog = requestLogger(c, "handler.openai_gateway.responses") + } + reqLog.Error("openai.handler_dependencies_missing", zap.Strings("missing_dependencies", missing)) + + if c != nil && c.Writer != nil && !c.Writer.Written() { + c.JSON(http.StatusServiceUnavailable, gin.H{ + "error": gin.H{ + "type": "api_error", + "message": "Service temporarily unavailable", + }, + }) + } + return false +} + +func (h *OpenAIGatewayHandler) missingResponsesDependencies() []string { + missing := make([]string, 0, 5) + if h == nil { + return append(missing, "handler") + } + if h.gatewayService == nil { + missing = append(missing, "gatewayService") + } + if h.billingCacheService == nil { + missing = append(missing, "billingCacheService") + } + if h.apiKeyService == nil { + missing = append(missing, "apiKeyService") + } + if h.concurrencyHelper == nil || h.concurrencyHelper.concurrencyService == nil { + missing = append(missing, "concurrencyHelper") + } + return missing +} + +func getContextInt64(c *gin.Context, key string) (int64, bool) { + if c == nil || key == "" { + return 0, false + } + v, ok := c.Get(key) + if !ok { + return 0, false + } + switch t := v.(type) { + case int64: + return t, true + case int: + return int64(t), true + case int32: + return int64(t), true + case float64: + return int64(t), true + default: + return 0, false + } +} + +func (h *OpenAIGatewayHandler) submitUsageRecordTask(parent context.Context, task service.UsageRecordTask) { + if task == nil { + return + } + task, abandon := wrapUsageRecordTaskContext(parent, task) + if h.usageRecordWorkerPool != nil { + if mode := h.usageRecordWorkerPool.Submit(task); mode != service.UsageRecordSubmitModeDroppedStopped { + if mode.Dropped() { + abandon() + } + return + } + // 池已停止(进程关停窗口):计费任务不能静默丢失,降级为内联同步执行。 + // 显式配置的 drop/sample 溢出丢弃仍按配置语义保留。 + logger.L().With( + zap.String("component", "handler.openai_gateway.responses"), + ).Warn("openai.usage_record_task_stopped_sync_fallback") + } + // 回退路径:worker 池未注入或已停止时同步执行,避免退回到无界 goroutine 模式。 + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + defer func() { + if recovered := recover(); recovered != nil { + logger.L().With( + zap.String("component", "handler.openai_gateway.responses"), + zap.Any("panic", recovered), + ).Error("openai.usage_record_task_panic_recovered") + } + }() + task(ctx) +} + +func (h *OpenAIGatewayHandler) submitOpenAIUsageRecordTask(parent context.Context, result *service.OpenAIForwardResult, task service.UsageRecordTask) { + // Money-critical bills never drop on pool overflow: media, search surcharge, voice. + if result != nil && (result.ImageCount > 0 || result.VideoCount > 0 || + result.SearchCount > 0 || result.WebSearchCalls > 0 || result.AudioUsage != nil) { + h.submitMandatoryUsageRecordTask(parent, task) + return + } + h.submitUsageRecordTask(parent, task) +} + +func (h *OpenAIGatewayHandler) submitMandatoryUsageRecordTask(parent context.Context, task service.UsageRecordTask) { + if task == nil { + return + } + task, _ = wrapUsageRecordTaskContext(parent, task) + if h.usageRecordWorkerPool != nil { + if mode := h.usageRecordWorkerPool.Submit(task); !mode.Dropped() { + return + } + logger.L().With( + zap.String("component", "handler.openai_gateway.usage"), + ).Warn("openai.usage_record_task_mandatory_sync_fallback") + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + defer func() { + if recovered := recover(); recovered != nil { + logger.L().With( + zap.String("component", "handler.openai_gateway.usage"), + zap.Any("panic", recovered), + ).Error("openai.usage_record_task_panic_recovered") + } + }() + task(ctx) +} + +func (h *OpenAIGatewayHandler) acquireImageGenerationSlot(c *gin.Context, streamStarted bool) (func(), bool) { + if h == nil || h.cfg == nil || h.imageLimiter == nil { + return nil, true + } + imageConcurrency := h.cfg.Gateway.ImageConcurrency + wait := strings.TrimSpace(imageConcurrency.OverflowMode) == config.ImageConcurrencyOverflowModeWait + release, acquired := h.imageLimiter.Acquire( + c.Request.Context(), + imageConcurrency.Enabled, + imageConcurrency.MaxConcurrentRequests, + wait, + time.Duration(imageConcurrency.WaitTimeoutSeconds)*time.Second, + imageConcurrency.MaxWaitingRequests, + ) + if acquired { + return release, true + } + h.handleStreamingAwareErrorWithCode(c, http.StatusTooManyRequests, "rate_limit_error", gatewayConcurrencyLimitCode, "Image generation concurrency limit exceeded, please retry later", streamStarted, false) + return nil, false +} + +// handleConcurrencyError handles concurrency-related acquire errors. +func (h *OpenAIGatewayHandler) handleConcurrencyError(c *gin.Context, err error, slotType string, streamStarted bool) { + status, errType, code, message := concurrencyErrorResponse(err, slotType) + h.handleStreamingAwareErrorWithCode(c, status, errType, code, message, streamStarted, false) +} + +func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr == nil { + h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) + return + } + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + if failoverErr.IsOpenAIRequestBodyTooLarge() { + service.SetOpsUpstreamError(c, http.StatusRequestEntityTooLarge, service.OpenAIRequestBodyTooLargeClientMessage, "") + h.handleStreamingAwareError( + c, + http.StatusRequestEntityTooLarge, + "invalid_request_error", + service.OpenAIRequestBodyTooLargeClientMessage, + streamStarted, + ) + return + } + if failoverErr.Reason == service.OpenAIHTTPContinuationUnsupportedReason { + message := strings.TrimSpace(failoverErr.ClientMessage) + if message == "" { + message = "previous_response_id requires an OpenAI API-key account for HTTP requests" + } + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", message, streamStarted) + return + } + if failoverErr.Reason == service.OpenAIImagesInsufficientBalanceReason { + status := failoverErr.ClientStatusCode + if status <= 0 { + status = http.StatusPaymentRequired + } + message := strings.TrimSpace(failoverErr.ClientMessage) + if message == "" { + message = service.OpenAIImagesInsufficientBalanceMessage + } + service.SetOpsUpstreamError(c, failoverErr.StatusCode, message, "") + h.handleStreamingAwareErrorWithCode(c, status, "upstream_error", service.OpenAIImagesInsufficientBalanceCode, message, streamStarted, false) + return + } + if failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.handleStreamingAwareError(c, status, "upstream_error", message, streamStarted) + return + } + if failoverErr.IsOpenAICapacityShed() && strings.TrimSpace(failoverErr.ClientMessage) != "" { + status := failoverErr.ClientStatusCode + if status <= 0 { + status = http.StatusServiceUnavailable + } + h.handleStreamingAwareError(c, status, "server_error", failoverErr.ClientMessage, streamStarted) + return + } + statusCode := failoverErr.StatusCode + responseBody := failoverErr.ResponseBody + if statusCode == http.StatusBadRequest && service.IsOpenAICompatibleModelNotFound400(responseBody) && !streamStarted { + upstreamMsg := service.SanitizeUpstreamErrorMessage(service.ExtractUpstreamErrorMessage(responseBody)) + service.SetOpsUpstreamError(c, statusCode, upstreamMsg, "") + service.WriteOpenAIUpstreamClientError(c, statusCode, responseBody, upstreamMsg) + return + } + if service.IsOpenAISilentRefusalErrorBody(responseBody) { + service.SetOpsUpstreamError(c, statusCode, service.OpenAISilentRefusalClientMessage(), "") + h.handleStreamingAwareError(c, http.StatusBadGateway, "upstream_error", service.OpenAISilentRefusalClientMessage(), streamStarted) + return + } + + // 先检查透传规则 + if h.errorPassthroughService != nil && len(responseBody) > 0 { + if rule := h.errorPassthroughService.MatchRule("openai", statusCode, responseBody); rule != nil { + // 确定响应状态码 + respCode := statusCode + if !rule.PassthroughCode && rule.ResponseCode != nil { + respCode = *rule.ResponseCode + } + + // 确定响应消息 + msg := service.ExtractUpstreamErrorMessage(responseBody) + if !rule.PassthroughBody && rule.CustomMessage != nil { + msg = *rule.CustomMessage + } + + if rule.SkipMonitoring { + c.Set(service.OpsSkipPassthroughKey, true) + } + + h.handleStreamingAwareError(c, respCode, "upstream_error", msg, streamStarted) + return + } + } + + // 记录原始上游状态码,以便 ops 错误日志捕获真实的上游错误 + upstreamMsg := service.ExtractUpstreamErrorMessage(responseBody) + service.SetOpsUpstreamError(c, statusCode, upstreamMsg, "") + + // 使用默认的错误映射 + status, errType, errMsg := h.mapUpstreamError(statusCode) + h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted) +} + +func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError) (int, string) { + if failoverErr != nil && failoverErr.Reason == service.OpenAIUpstreamAccessStateReason && strings.TrimSpace(failoverErr.ClientMessage) != "" { + status := failoverErr.ClientStatusCode + if status <= 0 { + status = http.StatusServiceUnavailable + } + return status, failoverErr.ClientMessage + } + if failoverErr != nil && failoverErr.Reason == service.AntigravityCredentialRejectedReason { + return http.StatusBadGateway, service.AntigravityCredentialRejectedClientMessage + } + return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage +} + +func copyFailoverRetryAfter(c *gin.Context, headers http.Header) { + if c == nil || headers == nil { + return + } + retryAfter := strings.TrimSpace(headers.Get("Retry-After")) + if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) { + return + } + c.Header("Retry-After", retryAfter) +} + +func isSafeRetryAfter(value string) bool { + digitsOnly := true + for _, char := range value { + if char < '0' || char > '9' { + digitsOnly = false + break + } + } + if digitsOnly { + seconds, err := strconv.ParseUint(value, 10, 32) + return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second) + } + retryAt, err := http.ParseTime(value) + if err != nil { + return false + } + return !retryAt.After(time.Now().Add(7 * 24 * time.Hour)) +} + +// handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况 +func (h *OpenAIGatewayHandler) handleFailoverExhaustedSimple(c *gin.Context, statusCode int, streamStarted bool) { + status, errType, errMsg := h.mapUpstreamError(statusCode) + service.SetOpsUpstreamError(c, statusCode, errMsg, "") + h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted) +} + +func (h *OpenAIGatewayHandler) mapUpstreamError(statusCode int) (int, string, string) { + switch statusCode { + case 401: + return http.StatusBadGateway, "upstream_error", "Upstream authentication failed, please contact administrator" + case 403: + return http.StatusBadGateway, "upstream_error", "Upstream access forbidden, please contact administrator" + case 429: + return http.StatusTooManyRequests, "rate_limit_error", "Upstream rate limit exceeded, please retry later" + case 529: + return http.StatusServiceUnavailable, "upstream_error", "Upstream service overloaded, please retry later" + case 500, 502, 503, 504: + return http.StatusBadGateway, "upstream_error", "Upstream service temporarily unavailable" + default: + return http.StatusBadGateway, "upstream_error", "Upstream request failed" + } +} + +// handleStreamingAwareError handles errors that may occur after streaming has started +func (h *OpenAIGatewayHandler) handleStreamingAwareError(c *gin.Context, status int, errType, message string, streamStarted bool) { + h.handleStreamingAwareErrorWithCode(c, status, errType, "", message, streamStarted, false) +} + +func (h *OpenAIGatewayHandler) handleStreamingAwareErrorWithCode( + c *gin.Context, + status int, + errType string, + code string, + message string, + streamStarted bool, + countTowardsSLA bool, +) { + // body-signal compact 心跳可能已把响应头提交为 200:先停心跳(建立 + // happens-before,接管 ResponseWriter),并升级为流内错误处理。 + if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + streamStarted = true + } + if streamStarted { + if countTowardsSLA { + service.MarkOpsStreamFailure(c, errType, code, message, status) + } else { + service.MarkOpsStreamError(c, errType, message, status) + } + // /v1/responses 的严格 SDK(Codex CLI)要求终止事件必须属于 + // response.completed/failed/incomplete/cancelled 集合。 + // 通用 `event: error` 帧不被识别为终止事件,会导致 + // "stream closed before response.completed"。 + if inboundIsResponses(c) { + if writeResponsesFailedSSE(c, errType, code, message) { + return + } + } + // Stream already started, send error as SSE event then close + flusher, ok := c.Writer.(http.Flusher) + if ok { + errorObject := gin.H{"type": errType, "message": message} + if code != "" { + errorObject["code"] = code + } + payload, err := json.Marshal(gin.H{"error": errorObject}) + if err != nil { + payload = []byte(`{"error":{"type":"upstream_error","message":"Upstream request failed"}}`) + } + errorEvent := "event: error\ndata: " + string(payload) + "\n\n" + if _, err := fmt.Fprint(c.Writer, errorEvent); err != nil { + _ = c.Error(err) + } + flusher.Flush() + } + return + } + + // Normal case: return JSON response with proper status code + if code == "" { + h.errorResponse(c, status, errType, message) + return + } + c.JSON(status, gin.H{"error": gin.H{ + "type": errType, "code": code, "message": message, + }}) +} + +func (h *OpenAIGatewayHandler) ensureOpenAIStreamReadErrorResponse(c *gin.Context, err error, streamStarted bool) bool { + code, message, ok := service.OpenAIUpstreamStreamReadErrorDetails(err) + if !ok || c == nil || c.Writer == nil || service.IsResponseCommitted(c) { + return false + } + if c.Writer.Written() { + streamStarted = true + } + h.handleStreamingAwareErrorWithCode( + c, http.StatusBadGateway, "upstream_error", code, message, streamStarted, true, + ) + return true +} + +// ensureForwardErrorResponse 在 Forward 返回错误但尚未写响应时补写统一错误响应。 +func (h *OpenAIGatewayHandler) ensureForwardErrorResponse(c *gin.Context, streamStarted bool) bool { + if c == nil || c.Writer == nil { + return false + } + if c.Request != nil && errors.Is(c.Request.Context().Err(), context.Canceled) { + failoverClientGone(c) + return false + } + // 先停 compact 心跳再读 Writer 状态,避免与心跳 goroutine 竞争。 + compactKeepaliveCommitted := service.StopOpenAICompactSSEKeepaliveCommitted(c) + if compactKeepaliveCommitted { + streamStarted = true + } + imageKeepalivePresent := service.OpenAIImagesJSONKeepalivePresent(c) + service.StopOpenAIImagesJSONKeepaliveCommitted(c) + imageKeepalivePaddingOnly := false + imageKeepaliveResponseWritten := false + if imageKeepalivePresent { + adjustedSize := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) + imageKeepalivePaddingOnly = adjustedSize < 0 + imageKeepaliveResponseWritten = adjustedSize >= 0 + } + compactKeepaliveHasMeaningfulOutput := compactKeepaliveCommitted && service.OpenAICompactKeepaliveAdjustedWrittenSize(c) > 0 + // Compact keepalive may have committed 200 headers without writing a + // semantic SSE event. In that case the Responses stream still needs its + // protocol-correct terminal response.failed event. + if (service.IsResponseCommitted(c) && (!compactKeepaliveCommitted || compactKeepaliveHasMeaningfulOutput)) || (!compactKeepaliveCommitted && imageKeepaliveResponseWritten) { + return false + } + if c.Writer.Written() && !imageKeepalivePaddingOnly { + streamStarted = true + } + h.handleStreamingAwareError(c, http.StatusBadGateway, "upstream_error", "Upstream request failed", streamStarted) + return true +} + +func shouldLogOpenAIForwardFailureAsWarn(c *gin.Context, wroteFallback bool) bool { + if wroteFallback { + return false + } + if c == nil || c.Writer == nil { + return false + } + return c.Writer.Written() +} + +// openAIForwardErrorAlreadyCommunicated reports whether Forward returned an +// error after it had already written the upstream terminal error response to +// the client. +// +// This matters for Responses streams: upstream may return HTTP 200 with a +// non-retryable `response.failed` event (for example a policy/safety rejection). +// The service layer forwards that terminal event verbatim, then returns an +// error so the caller can log/account for the failed upstream response. The +// handler must not append its generic fallback `response.failed`, otherwise +// strict clients may see the useful upstream message replaced by "Upstream +// request failed" or receive duplicate terminal events. +func openAIForwardErrorAlreadyCommunicated(c *gin.Context, writerSizeBeforeForward int, err error) bool { + if err == nil || c == nil || c.Writer == nil { + return false + } + // 与快照同口径:排除 compact 心跳字节,避免"仅心跳写出"被误判为 + // 响应已写出(#3887)。 + if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) == writerSizeBeforeForward || + service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) == writerSizeBeforeForward { + return false + } + + // cyber_policy 命中时上游原始错误体已透传给客户端(非流式 c.Data 写出 400 body, + // 流式写出 response.failed 事件),不能再让 ensureForwardErrorResponse 追加 + // fallback —— 否则在已写出的完整响应尾部追加 SSE(responses 端点尾随 + // response.failed、chat 端点尾随 event:error),污染响应体。Size 已变化证明响应确已写出。 + if service.GetOpsCyberPolicy(c) != nil { + return true + } + + msg := strings.TrimSpace(err.Error()) + for _, prefix := range []string{ + "upstream response failed:", + "non-streaming openai protocol error:", + } { + if strings.HasPrefix(msg, prefix) { + return true + } + } + return false +} + +func openAIForwardMayFailover(c *gin.Context, writerSizeBeforeForward int, failoverErr *service.UpstreamFailoverError) bool { + if c == nil || c.Writer == nil { + return false + } + if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) == writerSizeBeforeForward { + return true + } + return failoverErr != nil && failoverErr.SafeToFailoverAfterWrite +} + +func openAIRequestAllowsFailoverReplay(c *gin.Context) bool { + if c == nil || c.Request == nil { + return false + } + return !failoverClientGone(c) +} + +func openAIFirstOutputFailoverExhausted(failoverErr *service.UpstreamFailoverError, switchCount *int) bool { + if failoverErr == nil || !failoverErr.SafeToFailoverAfterWrite || switchCount == nil { + return false + } + if *switchCount >= maxOpenAIFirstOutputTimeoutSwitches { + return true + } + *switchCount = *switchCount + 1 + return false +} + +// errorResponse returns OpenAI API format error response +func (h *OpenAIGatewayHandler) errorResponse(c *gin.Context, status int, errType, message string) { + // body-signal compact 心跳可能已把响应头提交为 200:JSON 错误体会与已 + // 提交的 SSE 流交错,必须降级为 response.failed 终止事件(#3887)。 + if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + service.MarkOpsStreamError(c, errType, message, status) + if writeResponsesFailedSSE(c, errType, "", message) { + return + } + } + c.JSON(status, gin.H{ + "error": gin.H{ + "type": errType, + "message": message, + }, + }) +} + +// openAICompactKeepaliveInterval 复用流式 keepalive 配置作为 compact 下游 +// 心跳间隔;0 表示禁用(与流式路径语义一致)。 +func (h *OpenAIGatewayHandler) openAICompactKeepaliveInterval() time.Duration { + if h.cfg == nil || h.cfg.Gateway.StreamKeepaliveInterval <= 0 { + return 0 + } + return time.Duration(h.cfg.Gateway.StreamKeepaliveInterval) * time.Second +} + +func setOpenAIClientTransportHTTP(c *gin.Context) { + service.SetOpenAIClientTransport(c, service.OpenAIClientTransportHTTP) +} + +func setOpenAIClientTransportWS(c *gin.Context) { + service.SetOpenAIClientTransport(c, service.OpenAIClientTransportWS) +} + +func ensureOpenAIPoolModeSessionHash(sessionHash string, account *service.Account) string { + if sessionHash != "" || account == nil || !account.IsPoolMode() { + return sessionHash + } + // 为当前请求生成一次性粘性会话键,确保同账号重试不会重新负载均衡到其他账号。 + return "openai-pool-retry-" + uuid.NewString() +} + +func openAIWSIngressFallbackSessionSeed(userID, apiKeyID int64, groupID *int64) string { + gid := int64(0) + if groupID != nil { + gid = *groupID + } + return fmt.Sprintf("openai_ws_ingress:%d:%d:%d", gid, userID, apiKeyID) +} + +func isOpenAIWSUpgradeRequest(r *http.Request) bool { + if r == nil { + return false + } + if !strings.EqualFold(strings.TrimSpace(r.Header.Get("Upgrade")), "websocket") { + return false + } + return strings.Contains(strings.ToLower(strings.TrimSpace(r.Header.Get("Connection"))), "upgrade") +} + +// blockedModelAllowlistCandidate 对全部候选模型逐一校验分组白名单,返回第一个 +// 未命中的值(全部命中或白名单未开启返回空串)。WS 帧与 HTTP 请求体共用该 +// 规则:重复 model 键/大小写变体可能被上游按末值绑定,任一未命中即拒绝。 +func blockedModelAllowlistCandidate(group *service.Group, candidates []string) string { + if group == nil || !group.ModelAllowlistEnabled() { + return "" + } + for _, candidate := range candidates { + if !group.ModelAllowlist.Allows(candidate) { + return candidate + } + } + return "" +} + +func closeOpenAIClientWS(conn *coderws.Conn, status coderws.StatusCode, reason string) { + if conn == nil { + return + } + reason = strings.TrimSpace(reason) + if len(reason) > 120 { + reason = reason[:120] + } + _ = conn.Close(status, reason) + _ = conn.CloseNow() +} + +func openAIWSNextAttemptMessage(current, retryPayload []byte, retryCurrentTurn bool) ([]byte, bool) { + if !retryCurrentTurn { + return append([]byte(nil), current...), true + } + if len(retryPayload) == 0 { + return nil, false + } + return append([]byte(nil), retryPayload...), true +} + +func closeOpenAIWSFailoverExhausted(c *gin.Context, conn *coderws.Conn, failoverErr *service.UpstreamFailoverError) { + intendedStatus := http.StatusBadGateway + errorType := "upstream_error" + errorCode := "upstream_ws_failover_exhausted" + message := "upstream websocket proxy failed" + closeStatus := coderws.StatusInternalError + + if failoverErr != nil { + if reason := strings.TrimSpace(string(failoverErr.Reason)); reason != "" { + errorCode = reason + } + if failoverErr.Stage == service.GatewayFailureStageAccountAuth { + intendedStatus = http.StatusServiceUnavailable + errorType = "api_error" + message = service.GrokCredentialUnavailableClientMessage + closeStatus = coderws.StatusTryAgainLater + } else { + switch failoverErr.StatusCode { + case http.StatusTooManyRequests: + intendedStatus = http.StatusTooManyRequests + errorType = "rate_limit_error" + message = "upstream rate limit exceeded, please retry later" + closeStatus = coderws.StatusTryAgainLater + case 529, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + intendedStatus = failoverErr.StatusCode + message = "upstream service temporarily unavailable" + closeStatus = coderws.StatusTryAgainLater + case http.StatusUnauthorized, http.StatusForbidden: + intendedStatus = failoverErr.StatusCode + errorType = "authentication_error" + message = "upstream websocket authentication failed" + closeStatus = coderws.StatusPolicyViolation + } + } + } + + service.MarkOpsStreamFailure(c, errorType, errorCode, message, intendedStatus) + closeOpenAIClientWS(conn, closeStatus, message) +} + +func writeContentModerationWSError(ctx context.Context, conn *coderws.Conn, decision *service.ContentModerationDecision) { + if conn == nil || decision == nil { + return + } + if ctx == nil { + ctx = context.Background() + } + message := strings.TrimSpace(decision.Message) + if message == "" { + message = "content moderation blocked this request" + } + payload, err := json.Marshal(gin.H{ + "event_id": "evt_content_moderation_blocked", + "type": "error", + "error": gin.H{ + "type": "invalid_request_error", + "code": contentModerationErrorCode(decision), + "message": message, + }, + }) + if err != nil { + payload = []byte(`{"event_id":"evt_content_moderation_blocked","type":"error","error":{"type":"invalid_request_error","code":"content_policy_violation","message":"content moderation blocked this request"}}`) + } + writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + _ = conn.Write(writeCtx, coderws.MessageText, payload) +} + +// writeCyberSessionBlockedWSError sends an error frame telling the client this +// session is blocked by the cyber session block (F5a) before closing. +func writeCyberSessionBlockedWSError(ctx context.Context, conn *coderws.Conn) { + if conn == nil { + return + } + if ctx == nil { + ctx = context.Background() + } + payload, err := json.Marshal(gin.H{ + "event_id": "evt_cyber_session_blocked", + "type": "error", + "error": gin.H{ + "type": "permission_error", + "code": "session_blocked_by_cyber_policy", + "message": cyberSessionBlockedClientMsg, + }, + }) + if err != nil { + payload = []byte(`{"event_id":"evt_cyber_session_blocked","type":"error","error":{"type":"permission_error","code":"session_blocked_by_cyber_policy","message":"This session is blocked by cyber-security policy, please start a new session"}}`) + } + writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + _ = conn.Write(writeCtx, coderws.MessageText, payload) +} + +// cyberPolicyRecordedKey guards against double-firing recordCyberPolicyIfMarked +// within one request (e.g. in a retry/failover loop). +const cyberPolicyRecordedKey = "ops_cyber_recorded" + +// cyberPolicyOpsErrorMeta carries request-scoped fields captured outside the +// async goroutine for building the cyber ops_error_logs entry. +type cyberPolicyOpsErrorMeta struct { + RequestID string + ClientRequestID string + Platform string + Model string + RequestPath string + Stream bool + InboundEndpoint string + UserAgent string + APIKeyPrefix string + UserID int64 + APIKeyID int64 + AccountID int64 + GroupID *int64 + ClientIP string + CreatedAt time.Time + SessionBlockKey string +} + +// buildCyberPolicyOpsErrorEntry builds the ops_error_logs entry for an upstream +// cyber_policy hit. StatusCode mirrors what the codex client actually received +// (400 non-stream / 200 stream), per F6. +func buildCyberPolicyOpsErrorEntry(meta cyberPolicyOpsErrorMeta, mark *service.CyberPolicyMark) *service.OpsInsertErrorLogInput { + rt := int16(service.RequestTypeCyberBlocked) + entry := &service.OpsInsertErrorLogInput{ + RequestID: meta.RequestID, + ClientRequestID: meta.ClientRequestID, + Platform: meta.Platform, + Model: meta.Model, + RequestPath: meta.RequestPath, + Stream: meta.Stream, + InboundEndpoint: meta.InboundEndpoint, + RequestType: &rt, + UserAgent: meta.UserAgent, + APIKeyPrefix: meta.APIKeyPrefix, + ErrorPhase: "request", + ErrorType: "cyber_policy", + Severity: "P3", + StatusCode: mark.UpstreamStatus, + IsBusinessLimited: true, + ErrorMessage: "cyber_policy: " + mark.Message, + // 原始 body 直接入队;ops service 落库前统一走 sanitizeErrorBodyForStorage 脱敏与截断。 + ErrorBody: mark.Body, + ErrorSource: "upstream_http", + ErrorOwner: "provider", + CreatedAt: meta.CreatedAt, + } + if meta.UserID > 0 { + entry.UserID = &meta.UserID + } + if meta.APIKeyID > 0 { + entry.APIKeyID = &meta.APIKeyID + } + if meta.AccountID > 0 { + entry.AccountID = &meta.AccountID + } + entry.GroupID = meta.GroupID + if meta.ClientIP != "" { + entry.ClientIP = &meta.ClientIP + } + return entry +} + +// 双语单串:网关客户端面向中英用户,且本错误无 i18n 协商通道。 +const cyberSessionBlockedClientMsg = "该会话已被网络安全策略屏蔽,请开启新会话 / This session is blocked by cyber-security policy, please start a new session" + +// buildCyberSessionBlockedOpsEntry builds the ops_error_logs entry for a request +// rejected locally by the cyber session block (F5a). Distinct error_type from +// upstream `cyber_policy`; never feeds moderation logs / violation counting +// (the request never reached upstream — see spec). +func buildCyberSessionBlockedOpsEntry(meta cyberPolicyOpsErrorMeta) *service.OpsInsertErrorLogInput { + rt := int16(service.RequestTypeCyberBlocked) + entry := &service.OpsInsertErrorLogInput{ + RequestID: meta.RequestID, + ClientRequestID: meta.ClientRequestID, + Platform: meta.Platform, + Model: meta.Model, + RequestPath: meta.RequestPath, + Stream: meta.Stream, + InboundEndpoint: meta.InboundEndpoint, + RequestType: &rt, + UserAgent: meta.UserAgent, + APIKeyPrefix: meta.APIKeyPrefix, + ErrorPhase: "request", + ErrorType: "cyber_policy_session_blocked", + Severity: "P3", + StatusCode: http.StatusForbidden, + IsBusinessLimited: true, + ErrorMessage: "cyber_policy_session_blocked: request rejected locally by session block", + ErrorSource: "gateway_local", + ErrorOwner: "platform", + CreatedAt: meta.CreatedAt, + // AccountID 有意不设:请求在账号选择前即被拒绝。 + } + if meta.SessionBlockKey != "" { + entry.ErrorBody = "session_block_key=" + meta.SessionBlockKey + } + if meta.UserID > 0 { + entry.UserID = &meta.UserID + } + if meta.APIKeyID > 0 { + entry.APIKeyID = &meta.APIKeyID + } + entry.GroupID = meta.GroupID + if meta.ClientIP != "" { + entry.ClientIP = &meta.ClientIP + } + return entry +} + +// cyberSessionBlockFormat selects the per-endpoint error envelope for a locally +// blocked session (用户决策:兼容路径各自格式). +type cyberSessionBlockFormat int + +const ( + cyberBlockFormatResponses cyberSessionBlockFormat = iota + cyberBlockFormatChat + cyberBlockFormatAnthropic +) + +// rejectIfCyberSessionBlocked checks the session-block table BEFORE account +// selection. Returns true when the request was rejected (response already +// written + ops entry enqueued). Fail-open: disabled switch / empty key / +// store error → false. +func (h *OpenAIGatewayHandler) rejectIfCyberSessionBlocked(c *gin.Context, apiKey *service.APIKey, body []byte, model string, format cyberSessionBlockFormat) bool { + if h == nil || h.gatewayService == nil || apiKey == nil { + return false + } + // 开关默认关:先走 ~ns 级缓存开关检查,再付出 key 派生(gjson+sha256)成本。 + if enabled, _ := h.gatewayService.CyberSessionBlockRuntime(c.Request.Context()); !enabled { + return false + } + key := h.findBlockedCyberSessionForAPIKey(c, apiKey, body) + if key == "" { + return false + } + // body-signal compact 心跳可能已把响应头提交为 200(cyber 检查在用户槽位 + // 长等待之后执行):以 response.failed 终止事件回传;未提交时停拍后照常 + // 写 JSON(#3887)。 + if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + service.MarkOpsStreamError(c, "permission_error", cyberSessionBlockedClientMsg, http.StatusForbidden) + if writeResponsesFailedSSE(c, "permission_error", "", cyberSessionBlockedClientMsg) { + h.enqueueCyberSessionBlockedOpsEntry(c, apiKey, model, key) + return true + } + } + switch format { + case cyberBlockFormatAnthropic: + c.JSON(http.StatusForbidden, gin.H{"type": "error", "error": gin.H{ + "type": "permission_error", + "message": cyberSessionBlockedClientMsg, + }}) + default: // cyberBlockFormatResponses 与 cyberBlockFormatChat:同构的 OpenAI error envelope + c.JSON(http.StatusForbidden, gin.H{"error": gin.H{ + "type": "permission_error", + "code": "session_blocked_by_cyber_policy", + "message": cyberSessionBlockedClientMsg, + }}) + } + h.enqueueCyberSessionBlockedOpsEntry(c, apiKey, model, key) + return true +} + +type cyberSessionBlockWritePlan struct { + scopeKey string + keys []string +} + +func buildCyberSessionBlockWritePlan(apiKeyID int64, c *gin.Context, body []byte) cyberSessionBlockWritePlan { + plan := cyberSessionBlockWritePlan{} + if key := service.CyberSessionExplicitBlockKey(apiKeyID, c, body); key != "" { + plan.keys = append(plan.keys, key) + } + transcriptKeys := service.CyberSessionTranscriptBlockKeys(apiKeyID, body) + for _, key := range transcriptKeys { + if len(plan.keys) == 0 || key != plan.keys[0] { + plan.keys = append(plan.keys, key) + } + } + if len(transcriptKeys) > 0 { + plan.scopeKey = cyberSessionScopeKey(apiKeyID, c) + } + return plan +} + +func findBlockedCyberSessionKey(ctx context.Context, gatewayService *service.OpenAIGatewayService, apiKeyID int64, c *gin.Context, body []byte) string { + if gatewayService == nil { + return "" + } + clientIP, userAgent := "", "" + if c != nil { + clientIP = strings.TrimSpace(ip.GetClientIP(c)) + userAgent = c.GetHeader("User-Agent") + } + return gatewayService.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, body, clientIP, userAgent) +} + +func cyberSessionScopeKey(apiKeyID int64, c *gin.Context) string { + if c == nil { + return "" + } + return service.CyberSessionScopeKey(apiKeyID, strings.TrimSpace(ip.GetClientIP(c)), c.GetHeader("User-Agent")) +} + +// enqueueCyberSessionBlockedOpsEntry captures request meta and enqueues the +// ops_error_logs entry for a locally blocked request. +func (h *OpenAIGatewayHandler) enqueueCyberSessionBlockedOpsEntry(c *gin.Context, apiKey *service.APIKey, model string, sessionBlockKey string) { + if h.opsService == nil { + return + } + // The dedicated cyber_session_blocked entry owns Ops semantics for this + // request; suppress the generic middleware record of the same 403 response. + c.Set(opsDedicatedErrorRecordedKey, true) + meta := cyberPolicyOpsErrorMeta{Model: model, InboundEndpoint: GetInboundEndpoint(c), CreatedAt: time.Now(), SessionBlockKey: sessionBlockKey} + meta.RequestID = c.Writer.Header().Get("X-Request-Id") + if c.Request != nil && c.Request.URL != nil { + meta.RequestPath = c.Request.URL.Path + } + if v, ok := c.Get(opsStreamKey); ok { + if b, ok := v.(bool); ok { + meta.Stream = b + } + } + requestCtx := context.Background() + if c.Request != nil { + requestCtx = c.Request.Context() + } + meta.Platform = resolveOpsPlatform(requestCtx, apiKey, guessPlatformFromPath(meta.RequestPath)) + if c.Request != nil { + meta.ClientRequestID, _ = c.Request.Context().Value(ctxkey.ClientRequestID).(string) + meta.UserAgent = c.GetHeader("User-Agent") + meta.ClientIP = strings.TrimSpace(ip.GetClientIP(c)) + } + meta.APIKeyID = apiKey.ID + meta.GroupID = apiKey.GroupID + meta.APIKeyPrefix = keyPrefix(apiKey.Key, 8) + if apiKey.User != nil { + meta.UserID = apiKey.User.ID + } + enqueueOpsErrorLog(h.opsService, buildCyberSessionBlockedOpsEntry(meta)) +} + +// recordCyberPolicyIfMarked 在 gateway forward 返回后检查 cyber 标记,异步写风控日志/邮件, +// 并在 forward 返回错误时写一条 tokens=0 用量行。标记由 gateway 服务层在透传 cyber 后设置; +// 当前请求已发给用户,本方法只做事后记录,不影响响应。forwardErrored 为 true 时才写用量行, +// 避免与正常 RecordUsage(forward 成功路径)重复。每请求至多记录一次。 +func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey *service.APIKey, account *service.Account, subscription *service.UserSubscription, model string, forwardErrored bool, cyberBlockBody []byte, channelFields service.ChannelUsageFields, requestPayloadHash string) { + mark := service.GetOpsCyberPolicy(c) + if mark == nil { + return + } + if c.GetBool(cyberPolicyRecordedKey) { + return + } + c.Set(cyberPolicyRecordedKey, true) + model = clientRequestedModel(c, model) + + requestID := c.Writer.Header().Get("X-Request-Id") + var userID, apiKeyID int64 + var userEmail, apiKeyName, groupName string + var groupID *int64 + if apiKey != nil { + apiKeyID = apiKey.ID + apiKeyName = apiKey.Name + groupID = apiKey.GroupID + if apiKey.User != nil { + userID = apiKey.User.ID + userEmail = apiKey.User.Email + } + if apiKey.Group != nil { + groupName = apiKey.Group.Name + } + } + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := "" + var accountID int64 + if account != nil { + accountID = account.ID + upstreamEndpoint = resolveOpenAIUpstreamEndpoint(c, account, nil) + } + stream := false + if v, ok := c.Get(opsStreamKey); ok { + if b, ok := v.(bool); ok { + stream = b + } + } + cmSvc := h.contentModerationService + gwSvc := h.gatewayService + opsSvc := h.opsService + apiKeySvc := h.apiKeyService + requestPath := "" + if c.Request != nil && c.Request.URL != nil { + requestPath = c.Request.URL.Path + } + requestCtx := context.Background() + if c.Request != nil { + requestCtx = c.Request.Context() + } + platform := resolveOpsPlatform(requestCtx, apiKey, guessPlatformFromPath(requestPath)) + var clientRequestID, userAgent, clientIPStr string + if c.Request != nil { + clientRequestID, _ = c.Request.Context().Value(ctxkey.ClientRequestID).(string) + userAgent = c.GetHeader("User-Agent") + clientIPStr = strings.TrimSpace(ip.GetClientIP(c)) + } + // 提前拍成标量,避免在下方 goroutine 内访问 gin.Context。 + sessionID := service.ExtractClientSessionID(c) + nativeCompactionV2 := service.IsOpenAINativeCompactionV2(c) + apiKeyPrefix := "" + if apiKey != nil { + apiKeyPrefix = keyPrefix(apiKey.Key, 8) + } + opsMeta := cyberPolicyOpsErrorMeta{ + RequestID: requestID, + ClientRequestID: clientRequestID, + Platform: platform, + Model: model, + RequestPath: requestPath, + Stream: stream, + InboundEndpoint: inboundEndpoint, + UserAgent: userAgent, + APIKeyPrefix: apiKeyPrefix, + UserID: userID, + APIKeyID: apiKeyID, + AccountID: accountID, + GroupID: groupID, + ClientIP: clientIPStr, + CreatedAt: time.Now(), + } + cyberLogOnly := h.cyberPolicyLogOnly(c, apiKey) + if gwSvc != nil && apiKey != nil && !cyberLogOnly { + plan := buildCyberSessionBlockWritePlan(apiKey.ID, c, cyberBlockBody) + if len(plan.keys) > 0 { + blockCtx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + gwSvc.MarkCyberSessionBlocked(blockCtx, plan.scopeKey, plan.keys) + cancel() + } + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if cmSvc != nil { + cmSvc.RecordCyberPolicyEvent(ctx, service.CyberPolicyRecordInput{ + LogOnly: cyberLogOnly, + RequestID: requestID, + UserID: userID, + UserEmail: userEmail, + APIKeyID: apiKeyID, + APIKeyName: apiKeyName, + GroupID: groupID, + GroupName: groupName, + Endpoint: inboundEndpoint, + Model: model, + UpstreamMessage: mark.Message, + UpstreamBody: mark.Body, + UpstreamStatus: mark.UpstreamStatus, + UpstreamInTok: mark.UpstreamInTok, + UpstreamOutTok: mark.UpstreamOutTok, + }) + } + if forwardErrored && gwSvc != nil { + gwSvc.RecordCyberPolicyUsageLog(ctx, service.CyberPolicyUsageInput{ + APIKey: apiKey, + Account: account, + Subscription: subscription, + RequestID: requestID, + Model: model, + Stream: stream, + InputTokens: mark.UpstreamInTok, + OutputTokens: mark.UpstreamOutTok, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIPStr, + SessionID: sessionID, + RequestPayloadHash: requestPayloadHash, + APIKeyService: apiKeySvc, + NativeCompactionV2: nativeCompactionV2, + ChannelUsageFields: channelFields, + }) + } + if opsSvc != nil { + enqueueOpsErrorLog(opsSvc, buildCyberPolicyOpsErrorEntry(opsMeta, mark)) + } + }() +} + +// clearCyberPolicyTurnState resets the cyber mark and recorded guard after a +// logical WS turn has finished. +func clearCyberPolicyTurnState(c *gin.Context) { + clearCyberPolicyAttemptState(c, true) +} + +func clearCyberPolicyAttemptState(c *gin.Context, resetRecorded bool) { + if c == nil { + return + } + service.ClearOpsCyberPolicy(c) + if resetRecorded { + c.Set(cyberPolicyRecordedKey, false) + } +} + +func summarizeWSCloseErrorForLog(err error) (string, string) { + if err == nil { + return "-", "-" + } + statusCode := coderws.CloseStatus(err) + if statusCode == -1 { + return "-", "-" + } + closeStatus := fmt.Sprintf("%d(%s)", int(statusCode), statusCode.String()) + closeReason := "-" + var closeErr coderws.CloseError + if errors.As(err, &closeErr) { + reason := strings.TrimSpace(closeErr.Reason) + if reason != "" { + closeReason = reason + } + } + return closeStatus, closeReason +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt new file mode 100644 index 00000000..424affde --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/pkg/apicompat/responses_to_anthropic.go.txt @@ -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 +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/server/routes/gateway.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/server/routes/gateway.go.txt new file mode 100644 index 00000000..3f09ebf4 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/server/routes/gateway.go.txt @@ -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 + } +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/service/group.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/service/group.go.txt new file mode 100644 index 00000000..bcaa3a04 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/service/group.go.txt @@ -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 +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_gateway_messages.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_gateway_messages.go.txt new file mode 100644 index 00000000..dfe326e8 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_gateway_messages.go.txt @@ -0,0 +1,1449 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync/atomic" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +// ForwardAsAnthropic accepts an Anthropic Messages request body, converts it +// to OpenAI Responses API format, forwards to the OpenAI upstream, and converts +// the response back to Anthropic Messages format. This enables Claude Code +// clients to access OpenAI models through the standard /v1/messages endpoint. +func (s *OpenAIGatewayService) ForwardAsAnthropic( + ctx context.Context, + c *gin.Context, + account *Account, + body []byte, + promptCacheKey string, + defaultMappedModel string, +) (*OpenAIForwardResult, error) { + // 工具 Schema 清洗必须先于所有分流:下游每条路径(原生 Anthropic 直通、 + // Chat Completions 转换、Responses 转换)都会把 tools 原样带给上游,而 + // xAI / Moonshot 等严格校验方会因 input_schema 里的 required:null 或 + // type:null 直接 400。 + if sanitized, changed, err := sanitizeOpenAIResponsesToolSchemasForPlatform(body, account.Platform); err != nil { + return nil, err + } else if changed { + body = sanitized + } + rememberOpenCodeInboundBody(c, body) + beginUpstreamResponseModelObservation(c) + ClearActualOpenAIUpstreamEndpoint(c) + // Web Search 模拟:Chat Completions 转换会丢掉 web_search 工具,纯 web_search + // 请求在此直接调用搜索 API 构造 Anthropic 响应,不访问上游。 + if groupID := getOpenAIGroupIDFromContext(c); shouldEmulateWebSearchFor(ctx, s.settingService, s.channelService, account, &groupID, body) { + stream := gjson.GetBytes(body, "stream").Bool() + res, err := writeEmulatedWebSearch(ctx, c, account, body, gjson.GetBytes(body, "model").String(), stream) + if err != nil { + return nil, err + } + return &OpenAIForwardResult{Model: res.Model, Stream: stream, Duration: res.Duration}, nil + } + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + SetActualOpenAIUpstreamEndpoint(c, "/v1/chat/completions") + } + setCodexToolNameReverse(c, nil) + if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil { + return nil, err + } + + // 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。Anthropic 分流必须先于 + // ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标 + // openai_responses_supported=false,否则会命中 CC 直转。 + routingModel := upstreamRoutingModel(account, body, defaultMappedModel) + if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) { + return nil, writeOpenCodeUnsupportedModelError(c, true, routingModel) + } + switch s.resolveUpstreamProtocolFor(ctx, account, APIProtocolAnthropic, routingModel) { + case APIProtocolAnthropic: + // 上游为供应商原生 Anthropic 端点:/v1/messages 零转换直通(仅模型名映射 + + // 少量 body 清洗),完整保留 thinking / tool_use / cache 语义。 + return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel) + case APIProtocolChatCompletions: + // 固定 chat_completions 的多协议账号、规则命中 CC 的按模型分流账号,以及 + // 不支持 Responses 的其他 APIKey 账号,均将 Messages 转为 CC。 + return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel) + } + SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) + + startTime := time.Now() + + // 1. Parse Anthropic request + var anthropicReq apicompat.AnthropicRequest + if err := json.Unmarshal(body, &anthropicReq); err != nil { + return nil, fmt.Errorf("parse anthropic request: %w", err) + } + anthropicDigestReq := cloneAnthropicRequestForDigest(&anthropicReq) + originalModel := anthropicReq.Model + applyOpenAICompatModelNormalization(&anthropicReq) + normalizedModel := anthropicReq.Model + clientStream := anthropicReq.Stream // client's original stream preference + + // 2. Model mapping + billingModel := resolveOpenAIForwardModel(account, normalizedModel, defaultMappedModel) + upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) + if err := validateGPT61SolCompatRequest(body, upstreamModel); err != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } + promptCacheKey = strings.TrimSpace(promptCacheKey) + apiKeyID := getAPIKeyIDFromContext(c) + anthropicDigestChain := "" + anthropicMatchedDigestChain := "" + compatPromptCacheInjected := false + // Grok is outside the gpt-5/codex compat injector, but Claude Code still + // carries a stable session id. Prefer that as the Grok prompt-cache seed so + // multi-turn /v1/messages traffic can hit xAI's server-side cache. + if promptCacheKey == "" && account.Platform == PlatformGrok { + if sessionSeed := extractClaudeCodeSessionID(c, body); sessionSeed != "" { + promptCacheKey = sessionSeed + compatPromptCacheInjected = true + } else if sessionSeed := promptCacheKeyFromAnthropicMetadataSession(&anthropicReq); sessionSeed != "" { + promptCacheKey = sessionSeed + compatPromptCacheInjected = true + } + } + if promptCacheKey == "" && shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) { + promptCacheKey = promptCacheKeyFromAnthropicMetadataSession(&anthropicReq) + if promptCacheKey == "" { + promptCacheKey = deriveAnthropicCacheControlPromptCacheKey(&anthropicReq) + } + if promptCacheKey == "" { + anthropicDigestChain = buildOpenAICompatAnthropicDigestChain(anthropicDigestReq) + if reusedKey, matchedChain := s.findOpenAICompatAnthropicDigestPromptCacheKey(account, apiKeyID, anthropicDigestChain); reusedKey != "" { + promptCacheKey = reusedKey + anthropicMatchedDigestChain = matchedChain + } else { + promptCacheKey = promptCacheKeyFromAnthropicDigest(anthropicDigestChain) + } + } + compatPromptCacheInjected = promptCacheKey != "" + } + compatReplayTrimmed := false + compatReplayGuardEnabled := shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) + compatContinuationEnabled := openAICompatContinuationEnabled(account, upstreamModel) + previousResponseID := "" + if compatContinuationEnabled { + previousResponseID = s.getOpenAICompatSessionResponseID(ctx, c, account, promptCacheKey) + } + compatContinuationDisabled := compatContinuationEnabled && + s.isOpenAICompatSessionContinuationDisabled(ctx, c, account, promptCacheKey) + compatTurnState := "" + // ChatGPT/Codex credentials rely on session_id + x-codex-turn-state; trimming to a + // sliding 12-message window makes the cached prefix stall at system/tools. + // Keep full replay there so upstream prompt caching can grow turn by turn. + if compatReplayGuardEnabled && !account.UsesOpenAICodexProtocol() && previousResponseID == "" && !compatContinuationDisabled { + compatReplayTrimmed = applyAnthropicCompatFullReplayGuard(&anthropicReq) + } + + // 3. Convert Anthropic → Responses after compatibility-only replay guard. + anthropicReq.Model = upstreamModel + responsesReq, err := anthropicToResponses(s.cfg, &anthropicReq) + if err != nil { + return nil, fmt.Errorf("convert anthropic to responses: %w", err) + } + + // Upstream always uses streaming (upstream may not support sync mode). + // The client's original preference determines the response format. + responsesReq.Stream = true + isStream := true + + // 3b. Handle BetaFastMode → service_tier: "priority" + if containsBetaToken(c.GetHeader("anthropic-beta"), claude.BetaFastMode) { + responsesReq.ServiceTier = "priority" + } + + responsesReq.Model = upstreamModel + if responsesReq.Reasoning != nil { + responsesReq.Reasoning.Effort = openAICompatAnthropicReasoningEffort(&anthropicReq, upstreamModel, responsesReq.Reasoning.Effort) + } + if previousResponseID != "" { + responsesReq.PreviousResponseID = previousResponseID + trimAnthropicCompatResponsesInputToLatestTurn(responsesReq) + } + if compatReplayGuardEnabled && !account.UsesOpenAICodexProtocol() { + appendOpenAICompatClaudeCodeTodoGuard(responsesReq) + } + + logFields := []zap.Field{ + zap.Int64("account_id", account.ID), + zap.String("original_model", originalModel), + zap.String("normalized_model", normalizedModel), + zap.String("billing_model", billingModel), + zap.String("upstream_model", upstreamModel), + zap.Bool("stream", isStream), + } + if compatPromptCacheInjected { + logFields = append(logFields, + zap.Bool("compat_prompt_cache_key_injected", true), + zap.String("compat_prompt_cache_key_sha256", hashSensitiveValueForLog(promptCacheKey)), + ) + } + if compatReplayTrimmed { + logFields = append(logFields, + zap.Bool("compat_full_replay_trimmed", true), + zap.Int("compat_messages_after_trim", len(anthropicReq.Messages)), + ) + } + if previousResponseID != "" { + logFields = append(logFields, + zap.Bool("compat_previous_response_id_attached", true), + zap.String("compat_previous_response_id", truncateOpenAIWSLogValue(previousResponseID, openAIWSIDValueMaxLen)), + ) + } + if compatTurnState != "" { + logFields = append(logFields, zap.Bool("compat_turn_state_attached", true)) + } + logger.L().Debug("openai messages: model mapping applied", logFields...) + + // 4. Marshal Responses request body, then apply the ChatGPT/Codex transform. + responsesBody, err := json.Marshal(responsesReq) + if err != nil { + return nil, fmt.Errorf("marshal responses request: %w", err) + } + + if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok { + var reqBody map[string]any + if err := json.Unmarshal(responsesBody, &reqBody); err != nil { + return nil, fmt.Errorf("unmarshal for codex transform: %w", err) + } + codexResult := applyCodexOAuthTransformWithOptions(reqBody, codexOAuthTransformOptions{ + SkipDefaultInstructions: true, + PreserveToolCallIDs: true, + }) + if codexResult.Error != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", codexResult.Error.Error()) + return nil, codexResult.Error + } + setCodexToolNameReverse(c, codexResult.ToolNameReverse) + forcedTemplateText := "" + if s.cfg != nil { + forcedTemplateText = s.cfg.Gateway.ForcedCodexInstructionsTemplate + } + templateUpstreamModel := upstreamModel + if codexResult.NormalizedModel != "" { + templateUpstreamModel = codexResult.NormalizedModel + } + existingInstructions, _ := reqBody["instructions"].(string) + if strings.TrimSpace(existingInstructions) == "" { + existingInstructions = extractPromptLikeInstructionsFromInput(reqBody) + } + if _, err := applyForcedCodexInstructionsTemplate(reqBody, forcedTemplateText, forcedCodexInstructionsTemplateData{ + ExistingInstructions: strings.TrimSpace(existingInstructions), + OriginalModel: originalModel, + NormalizedModel: normalizedModel, + BillingModel: billingModel, + UpstreamModel: templateUpstreamModel, + }); err != nil { + return nil, err + } + ensureCodexOAuthInstructionsField(reqBody) + if shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) { + appendOpenAICompatClaudeCodeTodoGuardToRequestBody(reqBody) + } + if codexResult.NormalizedModel != "" { + upstreamModel = codexResult.NormalizedModel + } + if codexResult.PromptCacheKey != "" { + promptCacheKey = codexResult.PromptCacheKey + } + applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), apiKeyID) + delete(reqBody, "prompt_cache_key") + if shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) { + compatTurnState = s.getOpenAICompatSessionTurnState(ctx, c, account, promptCacheKey) + } + // OAuth codex transform forces stream=true upstream, so always use + // the streaming response handler regardless of what the client asked. + isStream = true + responsesBody, err = json.Marshal(reqBody) + if err != nil { + return nil, fmt.Errorf("remarshal after codex transform: %w", err) + } + } + + // For API key accounts (including OpenAI-compatible upstream gateways), + // ensure promptCacheKey is also propagated via the request body so that + // upstreams using the Responses API can derive a stable session identifier + // from prompt_cache_key. This makes our Anthropic /v1/messages compatibility + // path behave more like a native Responses client. + if account.Type == AccountTypeAPIKey { + if trimmedKey := strings.TrimSpace(promptCacheKey); trimmedKey != "" { + var reqBody map[string]any + if err := json.Unmarshal(responsesBody, &reqBody); err != nil { + return nil, fmt.Errorf("unmarshal for prompt cache key injection: %w", err) + } + if existing, ok := reqBody["prompt_cache_key"].(string); !ok || strings.TrimSpace(existing) == "" { + reqBody["prompt_cache_key"] = trimmedKey + updated, err := json.Marshal(reqBody) + if err != nil { + return nil, fmt.Errorf("remarshal after prompt cache key injection: %w", err) + } + responsesBody = updated + } + } + } + if account.Platform == PlatformOpenAI { + policyBody, changed, policyErr := ApplyOpenAIReasoningEffortPolicyFromContext(ctx, responsesBody) + if policyErr != nil { + if IsReasoningEffortPolicyDenied(policyErr) { + MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied) + writeAnthropicError(c, http.StatusForbidden, "forbidden_error", policyErr.Error()) + } + return nil, policyErr + } + if changed { + responsesBody = policyBody + if responsesReq.Reasoning != nil { + responsesReq.Reasoning.Effort = gjson.GetBytes(responsesBody, "reasoning.effort").String() + } + } + } + + // 4c. Apply OpenAI fast policy (may filter service_tier or block the request). + // Mirrors the Claude anthropic-beta "fast-mode-2026-02-01" filter, but keyed + // on the body-level service_tier field (priority/flex). + updatedBody, policyErr := s.applyOpenAIFastPolicyToBody(ctx, account, upstreamModel, responsesBody) + if policyErr != nil { + var blocked *OpenAIFastBlockedError + if errors.As(policyErr, &blocked) { + MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied) + writeAnthropicError(c, http.StatusForbidden, "forbidden_error", blocked.Message) + } + return nil, policyErr + } + responsesBody = updatedBody + responsesReq.ServiceTier = normalizedOpenAIServiceTierValue(gjson.GetBytes(responsesBody, "service_tier").String()) + grokCacheIdentity := "" + if account.Platform == PlatformGrok { + grokIntentBody := responsesBody + grokCacheIdentity = resolveGrokCacheIdentity(c, grokIntentBody, promptCacheKey, upstreamModel) + patchedBody, patchErr := patchGrokResponsesBody(grokIntentBody, upstreamModel) + if patchErr != nil { + return nil, patchErr + } + responsesBody, patchErr = applyGrokResponsesCacheIdentity(patchedBody, grokIntentBody, grokCacheIdentity, account.IsGrokOAuth()) + if patchErr != nil { + return nil, fmt.Errorf("apply grok prompt cache identity: %w", patchErr) + } + responsesBody, patchErr = applyGrokFreeMessagesFunctionToolCacheRoute(responsesBody, grokIntentBody, account, grokCacheIdentity) + if patchErr != nil { + return nil, fmt.Errorf("apply grok Free function-tool cache route: %w", patchErr) + } + } + + // 5. Get access token + token, _, err := s.getRequestCredential(ctx, c, account) + if err != nil { + return nil, fmt.Errorf("get access token: %w", err) + } + + // 6. Build upstream request + if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok { + // Messages 兼容桥即使 body 未带 todo-guard/prompt_cache_key 标记(如映射到非 + // gpt-5/codex 模型),也必须让 buildUpstreamRequest 走 bridge 分支,以保留 + // 既有 body/session/conversation 行为。身份头在 post-build 阶段统一恢复。 + setOpenAICompatMessagesBridgeContext(c, true) + } + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + var upstreamReq *http.Request + if account.Platform == PlatformGrok { + upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, grokCacheIdentity, s.cfg, s.settingService) + } else { + upstreamReq, err = s.buildUpstreamRequest(upstreamCtx, c, account, responsesBody, token, isStream, promptCacheKey, false) + } + releaseUpstreamCtx() + if err != nil { + return nil, fmt.Errorf("build upstream request: %w", err) + } + + // Override session_id with a deterministic UUID derived from the isolated + // session key, ensuring different API keys produce different upstream sessions. + if account.Platform != PlatformGrok && promptCacheKey != "" { + isolatedSessionID := generateSessionUUID(isolateOpenAIUpstreamSessionID(apiKeyID, codexAccountIdentitySource(c, account), promptCacheKey)) + upstreamReq.Header.Set("session_id", isolatedSessionID) + if upstreamReq.Header.Get("conversation_id") != "" { + upstreamReq.Header.Set("conversation_id", isolatedSessionID) + } + } + if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok { + // buildUpstreamRequest 保留 Messages bridge 的 body/session 兼容行为,并会先 + // 清除身份头。真正发送前恢复完整 Codex 身份,避免 ChatGPT Codex 上游因缺失 + // originator/OpenAI-Beta 返回 404(issue #3901)。 + ensureCodexIdentityHeaders(upstreamReq.Header) + enforceCodexIdentityHeaders(upstreamReq.Header) + logger.L().Debug("openai messages: upstream identity restored", + zap.Int64("account_id", account.ID), + zap.String("upstream_model", upstreamModel), + zap.Bool("compat_identity_restored", true), + ) + } + if account.UsesOpenAICodexProtocol() && promptCacheKey != "" && strings.TrimSpace(c.GetHeader("conversation_id")) == "" { + upstreamReq.Header.Del("conversation_id") + } + if compatTurnState != "" && upstreamReq.Header.Get("x-codex-turn-state") == "" { + upstreamReq.Header.Set("x-codex-turn-state", compatTurnState) + } + + // 7. Send request + proxyURL := "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + // Grok may reject encrypted reasoning replayed under a different OAuth + // account/cache identity. Match forwardGrokResponses: one strip+retry before + // treating the 400 as a hard failure / failover trigger. + var resp *http.Response + for attempt := 0; ; attempt++ { + if attempt > 0 { + if account.Platform != PlatformGrok { + break + } + upstreamCtxRetry, releaseRetry := detachUpstreamContext(ctx) + upstreamReq, err = buildGrokResponsesRequest(upstreamCtxRetry, c, account, responsesBody, token, grokCacheIdentity, s.cfg, s.settingService) + releaseRetry() + if err != nil { + return nil, fmt.Errorf("build grok retry request: %w", err) + } + } + resp, err = s.doOpenAIUpstream(upstreamReq, proxyURL, account) + if err != nil { + return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, false) + } + if account.Platform != PlatformGrok || attempt > 0 || resp.StatusCode != http.StatusBadRequest { + break + } + respBody := s.readUpstreamErrorBody(resp) + if resp.Body != nil { + _ = resp.Body.Close() + } + // Prefer explicit decrypt errors; also strip once on any 400 when the + // outbound body still carries reasoning.encrypted_content (account + // switch often returns opaque "Upstream error: 400"). + shouldStrip := isGrokInvalidEncryptedContentResponse(resp.StatusCode, respBody) || + requestHasGrokEncryptedReasoning(responsesBody) + if !shouldStrip { + resp.Body = io.NopCloser(bytes.NewReader(respBody)) + break + } + retryBody, changed, trimErr := trimGrokInvalidEncryptedContentRetryBody(responsesBody) + if trimErr != nil { + return nil, fmt.Errorf("prepare Grok invalid encrypted_content retry: %w", trimErr) + } + if !changed { + resp.Body = io.NopCloser(bytes.NewReader(respBody)) + break + } + responsesBody = retryBody + logger.L().Info("openai messages: retrying after stripping invalid Grok encrypted_content", + zap.Int64("account_id", account.ID), + zap.Bool("cache_identity_present", strings.TrimSpace(grokCacheIdentity) != ""), + zap.String("upstream_error_preview", truncateOpenAIWSLogValue(string(respBody), 240)), + ) + } + defer func() { _ = resp.Body.Close() }() + + // 8. Handle error response with failover + if resp.StatusCode >= 400 { + respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.ForwardAsAnthropic(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel) + } + if previousResponseID != "" && (isOpenAICompatPreviousResponseNotFound(resp.StatusCode, upstreamMsg, respBody) || isOpenAICompatPreviousResponseUnsupported(resp.StatusCode, upstreamMsg, respBody)) { + if isOpenAICompatPreviousResponseUnsupported(resp.StatusCode, upstreamMsg, respBody) { + s.disableOpenAICompatSessionContinuation(ctx, c, account, promptCacheKey) + } else { + s.deleteOpenAICompatSessionResponseID(ctx, c, account, promptCacheKey) + } + logger.L().Info("openai messages: previous_response_id unavailable, retrying without continuation", + zap.Int64("account_id", account.ID), + zap.String("previous_response_id", truncateOpenAIWSLogValue(previousResponseID, openAIWSIDValueMaxLen)), + zap.String("upstream_model", upstreamModel), + ) + return s.ForwardAsAnthropic(ctx, c, account, body, promptCacheKey, defaultMappedModel) + } + // Grok account-switched history often fails decrypt; strip encrypted + // reasoning once at the client-body level so failover accounts can accept + // the multi-turn tool continuation instead of cascading 400s. + if account.Platform == PlatformGrok && + isGrokInvalidEncryptedContentResponse(resp.StatusCode, respBody) && + !grokEncryptedContentStripRetried(ctx) { + if strippedBody, ok := stripAnthropicThinkingSignatures(body); ok { + logger.L().Info("openai messages: stripping thinking signatures for Grok failover retry", + zap.Int64("account_id", account.ID), + ) + return s.ForwardAsAnthropic(markGrokEncryptedContentStripRetried(ctx), c, account, strippedBody, promptCacheKey, defaultMappedModel) + } + } + if foErr := s.failoverOpenAIUpstreamHTTPError(ctx, c, account, resp, respBody, upstreamMsg, upstreamModel); foErr != nil { + return nil, foErr + } + // Non-failover error: return Anthropic-formatted error to client + return s.handleAnthropicErrorResponse(resp, c, account, billingModel) + } + if account.Platform == PlatformGrok && account.Type == AccountTypeOAuth && !account.IsShadow() { + s.updateGrokUsageFromResponse(withGrokTeamRateLimitModel(ctx, upstreamModel), account, resp.Header, resp.StatusCode) + } + + if account.UsesOpenAICodexProtocol() && promptCacheKey != "" { + if turnState := strings.TrimSpace(resp.Header.Get("x-codex-turn-state")); turnState != "" { + s.bindOpenAICompatSessionTurnState(ctx, c, account, promptCacheKey, turnState) + } + } + + // 9. Handle normal response + // Upstream is always streaming; choose response format based on client preference. + var result *OpenAIForwardResult + var handleErr error + if clientStream { + result, handleErr = s.handleAnthropicStreamingResponse(resp, c, account, originalModel, billingModel, upstreamModel, startTime) + } else { + // Client wants JSON: buffer the streaming response and assemble a JSON reply. + result, handleErr = s.handleAnthropicBufferedStreamingResponse(resp, c, account, originalModel, billingModel, upstreamModel, startTime) + } + + // cyber_policy:标记已设、error 已按 Anthropic 格式发给客户端。丢弃 result、返回哨兵, + // 使 handler 落入 tokens=0 免费用量行(对齐 /v1/responses),不计费、不 failover。 + if GetOpsCyberPolicy(c) != nil { + if handleErr == nil { + handleErr = errOpenAICyberPolicyForwarded + } + return nil, handleErr + } + + // Propagate ServiceTier and ReasoningEffort to result for billing + if handleErr == nil && result != nil { + if compatContinuationEnabled && promptCacheKey != "" && result.ResponseID != "" { + s.bindOpenAICompatSessionResponseID(ctx, c, account, promptCacheKey, result.ResponseID) + } + if promptCacheKey != "" && anthropicDigestChain != "" { + s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, apiKeyID, anthropicDigestChain, promptCacheKey, anthropicMatchedDigestChain) + } + // 计费 tier 优先采用上游回显值;上游未回显时回退到最终出站 body(经过 + // fast policy filter/force 之后)里的 tier。 + if tier := resolvedOpenAIUpstreamServiceTier(c, extractOpenAIServiceTierFromBody(responsesBody)); tier != nil { + result.ServiceTier = tier + } + if responsesReq.Reasoning != nil && responsesReq.Reasoning.Effort != "" { + re := responsesReq.Reasoning.Effort + result.ReasoningEffort = &re + } + } + + // Extract and save Codex usage snapshot from response headers (for OAuth accounts). + // 排除 spark 影子:其 codex_* 仅由 QueryUsage(/wham/usage bengalfox)更新(外审第7轮 P1)。 + if handleErr == nil && account.Type == AccountTypeOAuth && !account.IsShadow() && account.Platform != PlatformGrok { + if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil { + s.updateCodexUsageSnapshot(ctx, account.ID, snapshot) + } + } else if handleErr == nil && account.IsShadow() && account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) + } + + stampOpenAIResponsesUpstreamEndpoint(c, result) + return result, handleErr +} + +func ensureCodexOAuthInstructionsField(reqBody map[string]any) { + if reqBody == nil { + return + } + if value, ok := reqBody["instructions"]; !ok || value == nil { + reqBody["instructions"] = "" + return + } + if _, ok := reqBody["instructions"].(string); !ok { + reqBody["instructions"] = "" + } +} + +// handleAnthropicErrorResponse reads an upstream error and returns it in +// Anthropic error format. +func (s *OpenAIGatewayService) handleAnthropicErrorResponse( + resp *http.Response, + c *gin.Context, + account *Account, + requestedModel ...string, +) (*OpenAIForwardResult, error) { + return s.handleCompatErrorResponse(resp, c, account, writeAnthropicError, requestedModel...) +} + +// handleAnthropicBufferedStreamingResponse reads all Responses SSE events from +// the upstream streaming response, finds the terminal event (response.completed +// / response.incomplete / response.failed), converts the complete response to +// Anthropic Messages JSON format, and writes it to the client. +// This is used when the client requested stream=false but the upstream is always +// streaming. +func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( + resp *http.Response, + c *gin.Context, + account *Account, + originalModel string, + billingModel string, + upstreamModel string, + startTime time.Time, +) (*OpenAIForwardResult, error) { + requestID := resp.Header.Get("x-request-id") + + finalResponse, usage, acc, prior, err := s.readOpenAICompatBufferedTerminal(resp, c, account, "openai messages buffered", requestID) + if err != nil { + var readErr *openAICompatBufferedReadError + if errors.As(err, &readErr) && readErr != nil { + return nil, readErr.cause + } + return nil, err + } + + if finalResponse == nil { + writeAnthropicError(c, http.StatusBadGateway, "api_error", "Upstream stream ended without a terminal response event") + return nil, fmt.Errorf("upstream stream ended without terminal event") + } + observer := upstreamResponseModelObserverFromContext(c) + if observer == nil { + observer = beginUpstreamResponseModelObservation(c) + } + prior.apply(observer) + observer.Observe(finalResponse.Model, true) + observer.ObserveServiceTier(finalResponse.ServiceTier, true) + + if strings.TrimSpace(finalResponse.Status) == "failed" { + payload, _ := json.Marshal(gin.H{"type": "response.failed", "response": finalResponse}) + if hit, code, msg := detectOpenAICyberPolicy(payload); hit { + MarkOpsCyberPolicy(c, CyberPolicyMark{ + Code: code, + Message: msg, + Body: truncateString(string(payload), 4096), + UpstreamStatus: http.StatusOK, + UpstreamInTok: usage.InputTokens, + UpstreamOutTok: usage.OutputTokens, + }) + clientMsg := msg + if clientMsg == "" { + clientMsg = "Request blocked by upstream cyber-security policy" + } + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", clientMsg) + return nil, fmt.Errorf("openai cyber_policy: %s", msg) + } + message := openAICompatFailedResponseMessage(finalResponse) + if openAIStreamFailedEventShouldFailover(payload, message) { + return nil, s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payload, message, upstreamModel, resp.Header) + } + message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payload, message) + // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), + // 使按错误码配置的透传规则可命中。 + if status, errType, errMsg, matched := applyOpenAIStreamFailedErrorPassthroughRule( + c, account.Platform, payload, message, + ); matched { + if errMsg == "" { + errMsg = message + } + MarkResponseCommitted(c) + writeAnthropicError(c, status, errType, errMsg) + return nil, fmt.Errorf("upstream response failed (passthrough): %s", errMsg) + } + writeAnthropicError(c, http.StatusBadGateway, "api_error", message) + return nil, fmt.Errorf("upstream response failed: %s", message) + } + if strings.TrimSpace(finalResponse.Status) == "completed" { + logOpenAISuccessMissingUsage(c.Request.Context(), c, account, resp, &usage, "response.completed", false) + } + + // When the terminal event has an empty output array, reconstruct from + // accumulated delta events so the client receives the full content. + acc.SupplementResponseOutput(finalResponse) + + anthropicResp := apicompat.ResponsesToAnthropic(finalResponse, originalModel) + + if s.responseHeaderFilter != nil { + responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) + } + c.Header("Content-Type", "application/json; charset=utf-8") + c.JSON(http.StatusOK, anthropicResp) + + result := &OpenAIForwardResult{ + RequestID: requestID, + UpstreamHeaders: resp.Header, + ResponseID: finalResponse.ID, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + Stream: false, + Duration: time.Since(startTime), + } + // Grok /v1/messages uses Responses upstream; count native search for surcharge. + if account != nil && account.IsGrok() && finalResponse != nil { + if body, err := json.Marshal(finalResponse); err == nil { + if n := countGrokNativeSearchCallsFromJSONBytes(body); n > 0 { + result.SearchCount = n + } + } + } + return result, nil +} + +func isOpenAICompatResponsesTerminalEvent(eventType string) bool { + switch strings.TrimSpace(eventType) { + case "response.completed", "response.done", "response.incomplete", "response.failed", "response.cancelled", "response.canceled", "error": + return true + default: + return false + } +} + +func (s *OpenAIGatewayService) recordOpenAIMessagesStreamUpstreamError(c *gin.Context, account *Account, upstreamRequestID, kind, message string) { + if c == nil { + return + } + message = sanitizeUpstreamErrorMessage(message) + setOpsUpstreamError(c, http.StatusBadGateway, message, "") + event := OpsUpstreamErrorEvent{ + ProxyID: opsUpstreamProxyID(account), + ProxyName: opsUpstreamProxyName(account), + Platform: PlatformOpenAI, + UpstreamStatusCode: http.StatusBadGateway, + UpstreamRequestID: strings.TrimSpace(upstreamRequestID), + Kind: kind, + Message: message, + } + if account != nil { + event.Platform = account.Platform + event.AccountID = account.ID + event.AccountName = account.Name + } + appendOpsUpstreamError(c, event) +} + +func isOpenAICompatDoneSentinelLine(line string) bool { + payload, ok := extractOpenAISSEDataLine(line) + return ok && strings.TrimSpace(payload) == "[DONE]" +} + +// openAICompatBufferedReadError 只标记错误发生在上游响应体读取阶段; +// 具体端点自行决定是否允许重放请求,避免共享读取器扩大重试范围。 +type openAICompatBufferedReadError struct { + cause error +} + +func (e *openAICompatBufferedReadError) Error() string { return e.cause.Error() } +func (e *openAICompatBufferedReadError) Unwrap() error { return e.cause } + +func openAICompatTerminalResponse(event *apicompat.ResponsesStreamEvent, payload []byte) *apicompat.ResponsesResponse { + if event == nil { + return nil + } + if event.Response != nil { + return event.Response + } + switch strings.TrimSpace(event.Type) { + case "response.failed", "error": + message := extractOpenAISSEErrorMessage(payload) + if message == "" { + message = "Upstream response failed" + } + return &apicompat.ResponsesResponse{ + Status: "failed", + Error: &apicompat.ResponsesError{Code: event.Code, Message: message}, + } + default: + return nil + } +} + +func openAICompatBufferedPriorModel(event *apicompat.ResponsesStreamEvent) (string, bool) { + if event == nil || event.Response == nil || isOpenAICompatResponsesTerminalEvent(event.Type) { + return "", false + } + model := strings.TrimSpace(event.Response.Model) + if model == "" { + return "", false + } + return model, true +} + +// openAICompatPriorModelAudit 是一次缓冲读取的固定大小审计状态。 +// 只有 Grok 折叠非终止 model:保留一条按既有上限截断的声明和冲突位。 +// 后面的不同声明只置冲突,不按事件数量或原文长度继续保存。 +type openAICompatPriorModelAudit struct { + enabled bool + observer upstreamResponseModelObserver +} + +func newOpenAICompatPriorModelAudit(account *Account) openAICompatPriorModelAudit { + return openAICompatPriorModelAudit{enabled: account != nil && account.IsGrok()} +} + +func (a *openAICompatPriorModelAudit) record(event *apicompat.ResponsesStreamEvent) { + if a == nil || !a.enabled { + return + } + model, ok := openAICompatBufferedPriorModel(event) + if !ok { + return + } + a.observer.Observe(model, false) +} + +func (a openAICompatPriorModelAudit) apply(observer *upstreamResponseModelObserver) { + if !a.enabled || observer == nil { + return + } + if a.observer.first != "" { + observer.Observe(a.observer.first, false) + } + if a.observer.conflict { + observer.conflict = true + } +} + +func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( + resp *http.Response, + c *gin.Context, + account *Account, + logPrefix string, + requestID string, +) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { + acc := apicompat.NewBufferedResponseAccumulator() + var usage OpenAIUsage + if resp == nil || resp.Body == nil { + return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") + } + prior := newOpenAICompatPriorModelAudit(account) + recordPrior := func(event *apicompat.ResponsesStreamEvent) { + prior.record(event) + } + + scanner := s.newUpstreamSSEScanner(resp.Body) + + streamInterval := time.Duration(0) + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + streamInterval = time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + var timeoutCh <-chan time.Time + var timeoutTimer *time.Timer + resetTimeout := func() { + if streamInterval <= 0 { + return + } + if timeoutTimer == nil { + timeoutTimer = time.NewTimer(streamInterval) + timeoutCh = timeoutTimer.C + return + } + if !timeoutTimer.Stop() { + select { + case <-timeoutTimer.C: + default: + } + } + timeoutTimer.Reset(streamInterval) + } + stopTimeout := func() { + if timeoutTimer == nil { + return + } + if !timeoutTimer.Stop() { + select { + case <-timeoutTimer.C: + default: + } + } + } + resetTimeout() + defer stopTimeout() + + type scanEvent struct { + line string + err error + } + events := make(chan scanEvent, 16) + done := make(chan struct{}) + go func() { + defer close(events) + for scanner.Scan() { + select { + case events <- scanEvent{line: scanner.Text()}: + case <-done: + return + } + } + if err := scanner.Err(); err != nil { + select { + case events <- scanEvent{err: err}: + case <-done: + } + } + }() + defer close(done) + + var parser openAICompatSSEFrameParser + for { + select { + case ev, ok := <-events: + if !ok { + if frame, ok := parser.Finish(); ok { + payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) + payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + var event apicompat.ResponsesStreamEvent + if err := json.Unmarshal([]byte(payload), &event); err == nil { + s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) + acc.ProcessEvent(&event) + recordPrior(&event) + if response := openAICompatTerminalResponse(&event, []byte(payload)); isOpenAICompatResponsesTerminalEvent(event.Type) && response != nil { + if event.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(event.Usage) + if response.Usage == nil { + response.Usage = event.Usage + } + } + if response.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(response.Usage) + } + return response, usage, acc, prior, nil + } + } + } + return nil, usage, acc, prior, nil + } + resetTimeout() + if ev.err != nil { + if !errors.Is(ev.err, context.Canceled) && !errors.Is(ev.err, context.DeadlineExceeded) { + logger.L().Warn(logPrefix+": read error", + zap.Error(ev.err), + zap.String("request_id", requestID), + ) + } + return nil, usage, acc, prior, &openAICompatBufferedReadError{cause: ev.err} + } + + if isOpenAICompatDoneSentinelLine(ev.line) { + return nil, usage, acc, prior, nil + } + frame, ok := parser.AddLine(ev.line) + if !ok { + continue + } + payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) + payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + + var event apicompat.ResponsesStreamEvent + if err := json.Unmarshal([]byte(payload), &event); err != nil { + logger.L().Warn(logPrefix+": failed to parse event", + zap.Error(err), + zap.String("request_id", requestID), + ) + continue + } + s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) + + acc.ProcessEvent(&event) + recordPrior(&event) + + if response := openAICompatTerminalResponse(&event, []byte(payload)); isOpenAICompatResponsesTerminalEvent(event.Type) && response != nil { + if event.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(event.Usage) + if response.Usage == nil { + response.Usage = event.Usage + } + } + if response.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(response.Usage) + } + return response, usage, acc, prior, nil + } + + case <-timeoutCh: + _ = resp.Body.Close() + logger.L().Warn(logPrefix+": data interval timeout", + zap.String("request_id", requestID), + zap.Duration("interval", streamInterval), + ) + return nil, usage, acc, prior, fmt.Errorf("stream data interval timeout") + } + } +} + +// handleAnthropicStreamingResponse reads Responses SSE events from upstream, +// converts each to Anthropic SSE events, and writes them to the client. +// When StreamKeepaliveInterval is configured, it uses a goroutine + channel +// pattern to send Anthropic ping events during periods of upstream silence, +// preventing proxy/client timeout disconnections. +func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( + resp *http.Response, + c *gin.Context, + account *Account, + originalModel string, + billingModel string, + upstreamModel string, + startTime time.Time, +) (*OpenAIForwardResult, error) { + requestID := resp.Header.Get("x-request-id") + writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) + + state := apicompat.NewResponsesEventToAnthropicState() + state.Model = originalModel + var usage OpenAIUsage + responseID := "" + var firstTokenMs *int + firstChunk := true + clientDisconnected := false + clientOutputStarted := false + var streamFailoverErr error + var streamNonFailoverErr error + terminalEventType := "" + searchCount := 0 + streamSearchSeen := make(map[string]struct{}) + countSearch := account != nil && account.IsGrok() + + scanner := s.newUpstreamSSEScanner(resp.Body) + + streamInterval := time.Duration(0) + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + streamInterval = time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + var intervalTicker *time.Ticker + if streamInterval > 0 { + intervalTicker = time.NewTicker(streamInterval) + defer intervalTicker.Stop() + } + var intervalCh <-chan time.Time + if intervalTicker != nil { + intervalCh = intervalTicker.C + } + observer := upstreamResponseModelObserverFromContext(c) + if observer == nil { + observer = beginUpstreamResponseModelObservation(c) + } + + // resultWithUsage builds the final result snapshot. + resultWithUsage := func() *OpenAIForwardResult { + out := &OpenAIForwardResult{ + RequestID: requestID, + UpstreamHeaders: resp.Header, + ResponseID: responseID, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: clientDisconnected, + } + if searchCount > 0 { + out.SearchCount = searchCount + } + return out + } + + // processDataLine handles a single "data: ..." SSE line from upstream. + processDataLine := func(payload string) bool { + payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + if firstChunk { + firstChunk = false + ms := int(time.Since(startTime).Milliseconds()) + firstTokenMs = &ms + } + if countSearch { + searchCount += countGrokNativeSearchCallsInSSEDataDedup([]byte(payload), streamSearchSeen) + } + + var event apicompat.ResponsesStreamEvent + if err := json.Unmarshal([]byte(payload), &event); err != nil { + logger.L().Warn("openai messages stream: failed to parse event", + zap.Error(err), + zap.String("request_id", requestID), + ) + return false + } + observer.ObserveOpenAI([]byte(payload), event.Type) + s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) + + eventType := strings.TrimSpace(event.Type) + isBareErrorEvent := eventType == "error" + isTerminalEvent := isOpenAICompatResponsesTerminalEvent(eventType) || isBareErrorEvent + if isTerminalEvent { + terminalEventType = eventType + if event.Response != nil { + if id := strings.TrimSpace(event.Response.ID); id != "" { + responseID = id + } + if event.Response.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(event.Response.Usage) + } + } + if event.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(event.Usage) + } + // cyber_policy 致命不可重试:标记供 handler 事后记录;以 Anthropic SSE error 事件 + // 回写让客户端感知并停止重试(F4),丢弃后续转换输出。 + if eventType == "response.failed" || isBareErrorEvent { + payloadBytes := []byte(payload) + if hit, code, msg := detectOpenAICyberPolicy(payloadBytes); hit { + MarkOpsCyberPolicy(c, CyberPolicyMark{ + Code: code, + Message: msg, + Body: truncateString(payload, 4096), + UpstreamStatus: http.StatusOK, + UpstreamInTok: usage.InputTokens, + UpstreamOutTok: usage.OutputTokens, + }) + if !clientDisconnected { + writeStreamHeaders() + clientMsg := msg + if clientMsg == "" { + clientMsg = "Request blocked by upstream cyber-security policy" + } + if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE("invalid_request_error", clientMsg)); err == nil { + c.Writer.Flush() + } + clientDisconnected = true + } + return true + } + message := extractOpenAISSEErrorMessage(payloadBytes) + // Once Anthropic output has started, switching accounts would splice + // two model streams together. Surface a proper Anthropic error event + // instead of returning a failover error that the handler cannot retry. + shouldFailover := openAIStreamFailedEventShouldFailover(payloadBytes, message) + if isBareErrorEvent { + shouldFailover = openAIStreamErrorEventShouldFailover(payloadBytes, message) + } + if !clientOutputStarted && shouldFailover { + streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header) + return true + } + message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message) + errStatus, errType, errMsg := http.StatusBadGateway, "api_error", message + // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), + // 使按错误码配置的透传规则可命中。 + if status, et, em, matched := applyOpenAIStreamFailedErrorPassthroughRule( + c, account.Platform, payloadBytes, message, + ); matched { + if em == "" { + em = errMsg + } + errStatus, errType, errMsg = status, et, em + MarkResponseCommitted(c) + } + if !clientDisconnected { + if !clientOutputStarted { + writeAnthropicError(c, errStatus, errType, errMsg) + clientOutputStarted = true + } else { + writeStreamHeaders() + if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, errMsg)); err == nil { + c.Writer.Flush() + } + } + } + streamNonFailoverErr = fmt.Errorf("upstream response failed: %s", errMsg) + return true + } + } + + // Convert to Anthropic events + events := apicompat.ResponsesEventToAnthropicEvents(&event, state) + if !clientDisconnected { + for _, evt := range events { + sse, err := apicompat.ResponsesAnthropicEventToSSE(evt) + if err != nil { + logger.L().Warn("openai messages stream: failed to marshal event", + zap.Error(err), + zap.String("request_id", requestID), + ) + continue + } + writeStreamHeaders() + if _, err := fmt.Fprint(c.Writer, sse); err != nil { + clientDisconnected = true + logger.L().Info("openai messages stream: client disconnected, continuing to drain upstream for billing", + zap.String("request_id", requestID), + ) + break + } + clientOutputStarted = true + } + } + if len(events) > 0 && !clientDisconnected { + c.Writer.Flush() + } + return isTerminalEvent + } + + // finalizeStream sends any remaining Anthropic events and returns the result. + finalizeStream := func() (*OpenAIForwardResult, error) { + if streamFailoverErr != nil { + return resultWithUsage(), streamFailoverErr + } + if streamNonFailoverErr != nil { + return resultWithUsage(), streamNonFailoverErr + } + if finalEvents := apicompat.FinalizeResponsesAnthropicStream(state); len(finalEvents) > 0 && !clientDisconnected { + for _, evt := range finalEvents { + sse, err := apicompat.ResponsesAnthropicEventToSSE(evt) + if err != nil { + continue + } + writeStreamHeaders() + if _, err := fmt.Fprint(c.Writer, sse); err != nil { + clientDisconnected = true + logger.L().Info("openai messages stream: client disconnected during final flush", + zap.String("request_id", requestID), + ) + break + } + clientOutputStarted = true + } + if !clientDisconnected { + c.Writer.Flush() + } + } + logOpenAISuccessMissingUsage(c.Request.Context(), c, account, resp, &usage, terminalEventType, clientDisconnected) + return resultWithUsage(), nil + } + + // handleScanErr logs scanner errors if meaningful. + handleScanErr := func(err error) { + if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { + logger.L().Warn("openai messages stream: read error", + zap.Error(err), + zap.String("request_id", requestID), + ) + } + } + missingTerminalErr := func() (*OpenAIForwardResult, error) { + result := resultWithUsage() + if clientDisconnected { + return result, fmt.Errorf("stream usage incomplete: missing terminal event") + } + message := "OpenAI messages stream ended before a terminal event" + if !clientOutputStarted { + return result, s.newOpenAIStreamFailoverError(c, account, false, requestID, nil, message) + } + s.recordOpenAIMessagesStreamUpstreamError(c, account, requestID, "stream_missing_terminal", message) + return result, fmt.Errorf("stream usage incomplete: missing terminal event") + } + processFrame := func(frame openAICompatSSEFrame) bool { + payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) + return processDataLine(payload) + } + + // ── Determine keepalive interval ── + keepaliveInterval := time.Duration(0) + if s.cfg != nil && s.cfg.Gateway.StreamKeepaliveInterval > 0 { + keepaliveInterval = time.Duration(s.cfg.Gateway.StreamKeepaliveInterval) * time.Second + } + + // ── No keepalive: fast synchronous path (no goroutine overhead) ── + if streamInterval <= 0 && keepaliveInterval <= 0 { + var parser openAICompatSSEFrameParser + for scanner.Scan() { + line := scanner.Text() + if isOpenAICompatDoneSentinelLine(line) { + return missingTerminalErr() + } + frame, ok := parser.AddLine(line) + if !ok { + continue + } + if processFrame(frame) { + return finalizeStream() + } + } + if err := scanner.Err(); err != nil { + handleScanErr(err) + return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", err) + } + if frame, ok := parser.Finish(); ok { + if strings.TrimSpace(frame.Data) == "[DONE]" { + return missingTerminalErr() + } + if processFrame(frame) { + return finalizeStream() + } + } + return missingTerminalErr() + } + + // ── With keepalive: goroutine + channel + select ── + type scanEvent struct { + line string + err error + } + events := make(chan scanEvent, 16) + done := make(chan struct{}) + var lastReadAt int64 + atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + sendEvent := func(ev scanEvent) bool { + select { + case events <- ev: + return true + case <-done: + return false + } + } + go func() { + defer close(events) + for scanner.Scan() { + atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + if !sendEvent(scanEvent{line: scanner.Text()}) { + return + } + } + if err := scanner.Err(); err != nil { + _ = sendEvent(scanEvent{err: err}) + } + }() + defer close(done) + + var keepaliveTicker *time.Ticker + if keepaliveInterval > 0 { + keepaliveTicker = time.NewTicker(keepaliveInterval) + defer keepaliveTicker.Stop() + } + var keepaliveCh <-chan time.Time + if keepaliveTicker != nil { + keepaliveCh = keepaliveTicker.C + } + lastDataAt := time.Now() + var parser openAICompatSSEFrameParser + + for { + select { + case ev, ok := <-events: + if !ok { + // Upstream closed + if frame, ok := parser.Finish(); ok { + if strings.TrimSpace(frame.Data) == "[DONE]" { + return missingTerminalErr() + } + if processFrame(frame) { + return finalizeStream() + } + } + return missingTerminalErr() + } + if ev.err != nil { + handleScanErr(ev.err) + return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", ev.err) + } + lastDataAt = time.Now() + line := ev.line + if isOpenAICompatDoneSentinelLine(line) { + return missingTerminalErr() + } + frame, ok := parser.AddLine(line) + if !ok { + continue + } + if processFrame(frame) { + return finalizeStream() + } + + case <-intervalCh: + lastRead := time.Unix(0, atomic.LoadInt64(&lastReadAt)) + if time.Since(lastRead) < streamInterval { + continue + } + if clientDisconnected { + return resultWithUsage(), fmt.Errorf("stream usage incomplete after timeout") + } + logger.L().Warn("openai messages stream: data interval timeout", + zap.String("request_id", requestID), + zap.String("model", originalModel), + zap.Duration("interval", streamInterval), + ) + return resultWithUsage(), fmt.Errorf("stream data interval timeout") + + case <-keepaliveCh: + if clientDisconnected { + continue + } + if time.Since(lastDataAt) < keepaliveInterval { + continue + } + // Send Anthropic-format ping event + writeStreamHeaders() + if _, err := fmt.Fprint(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n"); err != nil { + // Client disconnected + logger.L().Info("openai messages stream: client disconnected during keepalive", + zap.String("request_id", requestID), + ) + clientDisconnected = true + continue + } + clientOutputStarted = true + c.Writer.Flush() + } + } +} + +// writeAnthropicError writes an error response in Anthropic Messages API format. +func writeAnthropicError(c *gin.Context, statusCode int, errType, message string) { + c.JSON(statusCode, gin.H{ + "type": "error", + "error": gin.H{ + "type": errType, + "message": message, + }, + }) +} + +// buildAnthropicStreamErrorSSE builds one Anthropic SSE `error` event so a +// streaming response can terminate with a visible error (e.g. upstream +// cyber_policy) and programmatic clients stop retrying. +// Marshal 失败的兜底仅保留固定提示。 +func buildAnthropicStreamErrorSSE(errType, message string) string { + payload, err := json.Marshal(gin.H{ + "type": "error", + "error": gin.H{ + "type": errType, + "message": message, + }, + }) + if err != nil { + return "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"" + errType + "\",\"message\":\"upstream error\"}}\n\n" + } + return "event: error\ndata: " + string(payload) + "\n\n" +} + +func copyOpenAIUsageFromResponsesUsage(usage *apicompat.ResponsesUsage) OpenAIUsage { + if usage == nil { + return OpenAIUsage{} + } + result := OpenAIUsage{ + InputTokens: usage.InputTokens, + OutputTokens: usage.OutputTokens, + CacheCreationInputTokens: usage.CacheCreationInputTokens, + } + if usage.InputTokensDetails != nil { + result.CacheReadInputTokens = usage.InputTokensDetails.CachedTokens + } + return result +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_messages_dispatch.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_messages_dispatch.go.txt new file mode 100644 index 00000000..b17d498d --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_messages_dispatch.go.txt @@ -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{} +} diff --git a/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_model_mapping.go.txt b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_model_mapping.go.txt new file mode 100644 index 00000000..7fd67468 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/source/backend/internal/service/openai_model_mapping.go.txt @@ -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 +} diff --git a/docs/routing-audit-n-evidence/public/upstream-summary.json b/docs/routing-audit-n-evidence/public/upstream-summary.json new file mode 100644 index 00000000..4067296b --- /dev/null +++ b/docs/routing-audit-n-evidence/public/upstream-summary.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/public/vendor-home.html b/docs/routing-audit-n-evidence/public/vendor-home.html new file mode 100644 index 00000000..dd317c6d --- /dev/null +++ b/docs/routing-audit-n-evidence/public/vendor-home.html @@ -0,0 +1,18 @@ + + + + + + + APIKEY.FAN - AI中转,一个Api Key就够了! + + + + + + + + +
+ + diff --git a/docs/routing-audit-n-evidence/public/vendor-model-plaza.json b/docs/routing-audit-n-evidence/public/vendor-model-plaza.json new file mode 100644 index 00000000..b4f975e4 --- /dev/null +++ b/docs/routing-audit-n-evidence/public/vendor-model-plaza.json @@ -0,0 +1 @@ +{"code":404,"message":"Model plaza is not enabled"} \ No newline at end of file diff --git a/docs/routing-audit-n-evidence/results/gpt-compatibility.json b/docs/routing-audit-n-evidence/results/gpt-compatibility.json new file mode 100644 index 00000000..a6d65c3a --- /dev/null +++ b/docs/routing-audit-n-evidence/results/gpt-compatibility.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/results/gpt-redirect-audit.json b/docs/routing-audit-n-evidence/results/gpt-redirect-audit.json new file mode 100644 index 00000000..1e42c5b4 --- /dev/null +++ b/docs/routing-audit-n-evidence/results/gpt-redirect-audit.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/results/regression-summary.json b/docs/routing-audit-n-evidence/results/regression-summary.json new file mode 100644 index 00000000..23baa52c --- /dev/null +++ b/docs/routing-audit-n-evidence/results/regression-summary.json @@ -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." +} diff --git a/docs/routing-audit-n-evidence/results/regression.tap b/docs/routing-audit-n-evidence/results/regression.tap new file mode 100644 index 00000000..9e630362 --- /dev/null +++ b/docs/routing-audit-n-evidence/results/regression.tap @@ -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 diff --git a/docs/routing-audit-n-evidence/results/source-integrity.json b/docs/routing-audit-n-evidence/results/source-integrity.json new file mode 100644 index 00000000..38aed1d0 --- /dev/null +++ b/docs/routing-audit-n-evidence/results/source-integrity.json @@ -0,0 +1,1779 @@ +{ + "passed": true, + "checkedAt": "2026-11-03T12:39:07.456Z", + "version": "1.24.4", + "sourceCommit": "d62d03f93f0c1a94c3475bcc14385c4a3d9cde7a", + "freezePath": "docs/messages-m-evidence/release/product-freeze.json", + "freezeSha256": "ad49a4aeea61a2a3fe8232185653c3e053618a9605a8712eb8fc9548237e1e1b", + "sourceFiles": 220, + "actualSourceFiles": 220, + "extraPaths": [], + "mManifestPath": "docs/messages-m-evidence/manifest.json", + "mManifestSha256": "c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7", + "expectedMManifestSha256": "c35590ff7879807e9302dc25ab24bf246b97396c9c78167e981c222db722e4c7", + "results": [ + { + "path": "src/client/App.tsx", + "bytes": 76556, + "sha256": "4030908b949bcbbdf6b1f236964324cd351203b3c8809e824947c3d339e1dbfb", + "actualBytes": 76556, + "actualSha256": "4030908b949bcbbdf6b1f236964324cd351203b3c8809e824947c3d339e1dbfb", + "passed": true + }, + { + "path": "src/client/BrowserPanel.css", + "bytes": 5050, + "sha256": "3032abddc1cfeea3100cb4b34bb2e9e25e965f470c4fd38c73d564dfc80f3450", + "actualBytes": 5050, + "actualSha256": "3032abddc1cfeea3100cb4b34bb2e9e25e965f470c4fd38c73d564dfc80f3450", + "passed": true + }, + { + "path": "src/client/BrowserPanel.tsx", + "bytes": 16962, + "sha256": "24a7479a2740ac72de22dadb556565904fb4525117cddc2a08ab1b766437ce30", + "actualBytes": 16962, + "actualSha256": "24a7479a2740ac72de22dadb556565904fb4525117cddc2a08ab1b766437ce30", + "passed": true + }, + { + "path": "src/client/BudgetPausePanel.tsx", + "bytes": 10000, + "sha256": "4e1007c1c8b20114669535bfe8eb667fd03ba1558783f7896621c12e31533bf9", + "actualBytes": 10000, + "actualSha256": "4e1007c1c8b20114669535bfe8eb667fd03ba1558783f7896621c12e31533bf9", + "passed": true + }, + { + "path": "src/client/ChangeSetPanel.css", + "bytes": 4477, + "sha256": "c1ac9307b78e4e42159398e499074d85da395faf7c88f2f485c6b7901d142459", + "actualBytes": 4477, + "actualSha256": "c1ac9307b78e4e42159398e499074d85da395faf7c88f2f485c6b7901d142459", + "passed": true + }, + { + "path": "src/client/ChangeSetPanel.tsx", + "bytes": 11104, + "sha256": "b3a3b3e73bf74a23c08f74d124fe98c6b45e0c048d3fabb745fd488140d58f61", + "actualBytes": 11104, + "actualSha256": "b3a3b3e73bf74a23c08f74d124fe98c6b45e0c048d3fabb745fd488140d58f61", + "passed": true + }, + { + "path": "src/client/ChangesInspector.tsx", + "bytes": 3324, + "sha256": "5799507f52e1414ec573eb1d0452bb3c173728836d3c1644c760b31cab4a3ee4", + "actualBytes": 3324, + "actualSha256": "5799507f52e1414ec573eb1d0452bb3c173728836d3c1644c760b31cab4a3ee4", + "passed": true + }, + { + "path": "src/client/CodeIndexPanel.css", + "bytes": 6857, + "sha256": "62243c9ed7958486aa5485d32e0167262c5625172fd44e73afeef84940dd4fde", + "actualBytes": 6857, + "actualSha256": "62243c9ed7958486aa5485d32e0167262c5625172fd44e73afeef84940dd4fde", + "passed": true + }, + { + "path": "src/client/CodeIndexPanel.tsx", + "bytes": 12218, + "sha256": "ec876cdb163afd9137d7bea2326468117b94029c7e2068663ca7371e2b0aef3a", + "actualBytes": 12218, + "actualSha256": "ec876cdb163afd9137d7bea2326468117b94029c7e2068663ca7371e2b0aef3a", + "passed": true + }, + { + "path": "src/client/CompanionPanel.tsx", + "bytes": 8889, + "sha256": "f4235d8950da0338206aa0c6dc95d76ab112355bf642856923a9d7edacac8d05", + "actualBytes": 8889, + "actualSha256": "f4235d8950da0338206aa0c6dc95d76ab112355bf642856923a9d7edacac8d05", + "passed": true + }, + { + "path": "src/client/DeliveryPanel.css", + "bytes": 5070, + "sha256": "8c12813290c171b616ffb36c002395fc40ff2c7d5b63cd2f13613be435a2d3c6", + "actualBytes": 5070, + "actualSha256": "8c12813290c171b616ffb36c002395fc40ff2c7d5b63cd2f13613be435a2d3c6", + "passed": true + }, + { + "path": "src/client/DeliveryPanel.tsx", + "bytes": 14511, + "sha256": "7af056cc41826ce4676837b5560cf787354ada388f8d0cf0e4d487f30833a389", + "actualBytes": 14511, + "actualSha256": "7af056cc41826ce4676837b5560cf787354ada388f8d0cf0e4d487f30833a389", + "passed": true + }, + { + "path": "src/client/DesktopPanel.tsx", + "bytes": 4245, + "sha256": "1df1e92e9d1d8ac5f34c2cccf145ae48bf2ded3d034607c4635a801a7e18c4f7", + "actualBytes": 4245, + "actualSha256": "1df1e92e9d1d8ac5f34c2cccf145ae48bf2ded3d034607c4635a801a7e18c4f7", + "passed": true + }, + { + "path": "src/client/DiagnosticsPanel.tsx", + "bytes": 5189, + "sha256": "63c192e8312f220c1afb06374336f09cc8c0177490519b47893b232583ec1a81", + "actualBytes": 5189, + "actualSha256": "63c192e8312f220c1afb06374336f09cc8c0177490519b47893b232583ec1a81", + "passed": true + }, + { + "path": "src/client/EmbeddedBrowserPanel.css", + "bytes": 4657, + "sha256": "0f842b97d326691ac0518bd5eca4b0aa59f0b7db40d7b78073fc34f72e57bb56", + "actualBytes": 4657, + "actualSha256": "0f842b97d326691ac0518bd5eca4b0aa59f0b7db40d7b78073fc34f72e57bb56", + "passed": true + }, + { + "path": "src/client/EmbeddedBrowserPanel.tsx", + "bytes": 15597, + "sha256": "e257670d22fa76098dace6c4aafa73cc24ee3239228378290cfa4d08ce22e0b3", + "actualBytes": 15597, + "actualSha256": "e257670d22fa76098dace6c4aafa73cc24ee3239228378290cfa4d08ce22e0b3", + "passed": true + }, + { + "path": "src/client/EnginePanel.css", + "bytes": 6275, + "sha256": "5a0fc3b6fab7038751f346cdd40e6b4540e8886c0f0c54478c09c18eeaeec1d3", + "actualBytes": 6275, + "actualSha256": "5a0fc3b6fab7038751f346cdd40e6b4540e8886c0f0c54478c09c18eeaeec1d3", + "passed": true + }, + { + "path": "src/client/EnginePanel.tsx", + "bytes": 13355, + "sha256": "af5408d65620fe5b6791f7da8da54bcf80e41af732928835897b3f496e78f073", + "actualBytes": 13355, + "actualSha256": "af5408d65620fe5b6791f7da8da54bcf80e41af732928835897b3f496e78f073", + "passed": true + }, + { + "path": "src/client/EngineRunPanel.css", + "bytes": 3759, + "sha256": "18a7f4d5f782168c71e44754f2a55d440af384ea79c16945a9b997af8da6849c", + "actualBytes": 3759, + "actualSha256": "18a7f4d5f782168c71e44754f2a55d440af384ea79c16945a9b997af8da6849c", + "passed": true + }, + { + "path": "src/client/EngineRunPanel.tsx", + "bytes": 8747, + "sha256": "eb3efead7fe0d5f1b2c55069b0628101e024d3887818f1c92ef297233b741fbb", + "actualBytes": 8747, + "actualSha256": "eb3efead7fe0d5f1b2c55069b0628101e024d3887818f1c92ef297233b741fbb", + "passed": true + }, + { + "path": "src/client/EnvironmentPanel.css", + "bytes": 2907, + "sha256": "c50f2977db4b5125fe362c023ad73ca47fed5a10a42aec4ae21e627a053cc76c", + "actualBytes": 2907, + "actualSha256": "c50f2977db4b5125fe362c023ad73ca47fed5a10a42aec4ae21e627a053cc76c", + "passed": true + }, + { + "path": "src/client/EnvironmentPanel.tsx", + "bytes": 12619, + "sha256": "d2fe2c8b2964eec9341370ea1369a40601571d253af6580b2013b66c59f70f3a", + "actualBytes": 12619, + "actualSha256": "d2fe2c8b2964eec9341370ea1369a40601571d253af6580b2013b66c59f70f3a", + "passed": true + }, + { + "path": "src/client/EvaluationPanel.css", + "bytes": 7296, + "sha256": "d462e0ed0ed57e6957e2c09531c701a5821e3881dab2c0b2f9f2b9319ac035bc", + "actualBytes": 7296, + "actualSha256": "d462e0ed0ed57e6957e2c09531c701a5821e3881dab2c0b2f9f2b9319ac035bc", + "passed": true + }, + { + "path": "src/client/EvaluationPanel.tsx", + "bytes": 21028, + "sha256": "2c54b38ebd95ccfcf61e54a6d0e249e2c7bf37bad86633fcde97f43386cc29b6", + "actualBytes": 21028, + "actualSha256": "2c54b38ebd95ccfcf61e54a6d0e249e2c7bf37bad86633fcde97f43386cc29b6", + "passed": true + }, + { + "path": "src/client/FileResultsPanel.css", + "bytes": 1805, + "sha256": "ca8a4c33dcf26e4727c0fc496a37b0722b710a841d9df40b11390b2d35ae7d57", + "actualBytes": 1805, + "actualSha256": "ca8a4c33dcf26e4727c0fc496a37b0722b710a841d9df40b11390b2d35ae7d57", + "passed": true + }, + { + "path": "src/client/FileResultsPanel.tsx", + "bytes": 8909, + "sha256": "c55c04564f226920de48cb9f32353e0b188067975e5c380b5dbed2991ed757cb", + "actualBytes": 8909, + "actualSha256": "c55c04564f226920de48cb9f32353e0b188067975e5c380b5dbed2991ed757cb", + "passed": true + }, + { + "path": "src/client/HtmlFilePreview.tsx", + "bytes": 2643, + "sha256": "403650bf0fdc45ebef2ad0aa4a4a78a3331feaa7e681ded0dca0f1809f98d11e", + "actualBytes": 2643, + "actualSha256": "403650bf0fdc45ebef2ad0aa4a4a78a3331feaa7e681ded0dca0f1809f98d11e", + "passed": true + }, + { + "path": "src/client/InputAttachments.tsx", + "bytes": 5505, + "sha256": "9f1762247dbb72928d5e5ef1ed39cb8c356727fd53a59fbffb21cc2356a350c9", + "actualBytes": 5505, + "actualSha256": "9f1762247dbb72928d5e5ef1ed39cb8c356727fd53a59fbffb21cc2356a350c9", + "passed": true + }, + { + "path": "src/client/InstallationStatus.css", + "bytes": 2537, + "sha256": "09ec12fdb3cbc5f3299b797da3050a58cb7d01aac8c4e322424e6cdd2f08211d", + "actualBytes": 2537, + "actualSha256": "09ec12fdb3cbc5f3299b797da3050a58cb7d01aac8c4e322424e6cdd2f08211d", + "passed": true + }, + { + "path": "src/client/InstallationStatus.tsx", + "bytes": 6286, + "sha256": "e6bc68a67f56c2158abde1a5d7657900ca3ab77d7663da5f236c13cd89c16985", + "actualBytes": 6286, + "actualSha256": "e6bc68a67f56c2158abde1a5d7657900ca3ab77d7663da5f236c13cd89c16985", + "passed": true + }, + { + "path": "src/client/LocalFiles.css", + "bytes": 3098, + "sha256": "5a9f97c592dd10e1c8768a83cbc7b448294472f16478ab52923cf0c87582c002", + "actualBytes": 3098, + "actualSha256": "5a9f97c592dd10e1c8768a83cbc7b448294472f16478ab52923cf0c87582c002", + "passed": true + }, + { + "path": "src/client/McpJobHistory.tsx", + "bytes": 7508, + "sha256": "207ba78dce96c85dedf7ff34f7678dff1e925118fb93dd1d5a144f38c7aaf618", + "actualBytes": 7508, + "actualSha256": "207ba78dce96c85dedf7ff34f7678dff1e925118fb93dd1d5a144f38c7aaf618", + "passed": true + }, + { + "path": "src/client/McpPanel.css", + "bytes": 9547, + "sha256": "e1c89f3229acb0bb739fcf91e605d09f7d8f38f4f367da1f11835b2b9452538d", + "actualBytes": 9547, + "actualSha256": "e1c89f3229acb0bb739fcf91e605d09f7d8f38f4f367da1f11835b2b9452538d", + "passed": true + }, + { + "path": "src/client/McpPanel.tsx", + "bytes": 15591, + "sha256": "f1ea14216c4340f6cd76b267763a468bf0d311dd6f8b273afe3ee9cf6768a260", + "actualBytes": 15591, + "actualSha256": "f1ea14216c4340f6cd76b267763a468bf0d311dd6f8b273afe3ee9cf6768a260", + "passed": true + }, + { + "path": "src/client/ModelBudgetSettings.tsx", + "bytes": 1759, + "sha256": "31deb3cbf9bac393ec4b529eea512c2a4e58f3239bc7f67720b7eb2b4785e2a2", + "actualBytes": 1759, + "actualSha256": "31deb3cbf9bac393ec4b529eea512c2a4e58f3239bc7f67720b7eb2b4785e2a2", + "passed": true + }, + { + "path": "src/client/ModelCenter.css", + "bytes": 12692, + "sha256": "667c2d878d09d1ce44131d172418ca344f36b5ca64e228bf6c1193d52f5ed573", + "actualBytes": 12692, + "actualSha256": "667c2d878d09d1ce44131d172418ca344f36b5ca64e228bf6c1193d52f5ed573", + "passed": true + }, + { + "path": "src/client/ModelCenter.tsx", + "bytes": 45178, + "sha256": "dc595cae20505f72ce0a8d313fcfd0af294a271fcf1bd2394d7e5811c029a15d", + "actualBytes": 45178, + "actualSha256": "dc595cae20505f72ce0a8d313fcfd0af294a271fcf1bd2394d7e5811c029a15d", + "passed": true + }, + { + "path": "src/client/ModelErrorDetails.css", + "bytes": 1142, + "sha256": "42d76f138cea1bd02081dd9e541a20c46078776c4016bf1bf9f038605c3ff279", + "actualBytes": 1142, + "actualSha256": "42d76f138cea1bd02081dd9e541a20c46078776c4016bf1bf9f038605c3ff279", + "passed": true + }, + { + "path": "src/client/ModelErrorDetails.tsx", + "bytes": 5231, + "sha256": "76f7e721502929af23f691ccca56fbd2980ebe66bed27d5efabf68b99cc07715", + "actualBytes": 5231, + "actualSha256": "76f7e721502929af23f691ccca56fbd2980ebe66bed27d5efabf68b99cc07715", + "passed": true + }, + { + "path": "src/client/ModelIdentityDetails.css", + "bytes": 996, + "sha256": "5ea7b7c55236ce55bd4468a15ae49cb7aa4f099f4d9c3e750bc5d49a199a0d2b", + "actualBytes": 996, + "actualSha256": "5ea7b7c55236ce55bd4468a15ae49cb7aa4f099f4d9c3e750bc5d49a199a0d2b", + "passed": true + }, + { + "path": "src/client/ModelIdentityDetails.tsx", + "bytes": 1994, + "sha256": "3e8bd9f735e21cc62abf217fc5f184c04014ea246d45115c42a95616248ac40b", + "actualBytes": 1994, + "actualSha256": "3e8bd9f735e21cc62abf217fc5f184c04014ea246d45115c42a95616248ac40b", + "passed": true + }, + { + "path": "src/client/ModelWaitSettings.tsx", + "bytes": 1977, + "sha256": "a0ed88656e896d46968bcf9662edc088001aba3086a4f67461fd2defca1cdeba", + "actualBytes": 1977, + "actualSha256": "a0ed88656e896d46968bcf9662edc088001aba3086a4f67461fd2defca1cdeba", + "passed": true + }, + { + "path": "src/client/NativeParameters.tsx", + "bytes": 3367, + "sha256": "5e7a1089deda8ac09f8ad4f8ec234fbd1fd1b60e880549fb3715aeacb5148d95", + "actualBytes": 3367, + "actualSha256": "5e7a1089deda8ac09f8ad4f8ec234fbd1fd1b60e880549fb3715aeacb5148d95", + "passed": true + }, + { + "path": "src/client/PreviewPanel.css", + "bytes": 1230, + "sha256": "9afd03d3594fb065b78a9ad829368cc8b7ee364b24372790254139a70acc5370", + "actualBytes": 1230, + "actualSha256": "9afd03d3594fb065b78a9ad829368cc8b7ee364b24372790254139a70acc5370", + "passed": true + }, + { + "path": "src/client/PreviewPanel.tsx", + "bytes": 5781, + "sha256": "2e3fc535f14ec2ebbdef62b58a0fc976741c68960bc7d8f2365481f3dc359cd6", + "actualBytes": 5781, + "actualSha256": "2e3fc535f14ec2ebbdef62b58a0fc976741c68960bc7d8f2365481f3dc359cd6", + "passed": true + }, + { + "path": "src/client/ProjectDirectoryPicker.tsx", + "bytes": 3927, + "sha256": "549b5224cbff177ec5226bff420b541f5652a59f2abcbfd405d0d750d97f5ddd", + "actualBytes": 3927, + "actualSha256": "549b5224cbff177ec5226bff420b541f5652a59f2abcbfd405d0d750d97f5ddd", + "passed": true + }, + { + "path": "src/client/ProjectMemory.css", + "bytes": 4322, + "sha256": "0d6c9a23afafa77e7230edd9294299a3d233aa7b49c191d522ee9c106839a1f1", + "actualBytes": 4322, + "actualSha256": "0d6c9a23afafa77e7230edd9294299a3d233aa7b49c191d522ee9c106839a1f1", + "passed": true + }, + { + "path": "src/client/ProjectMemoryPanel.tsx", + "bytes": 7381, + "sha256": "b7c140f126bc2d48df00fe4111517e3ea2f43926d52797d26733e1f2522f6a03", + "actualBytes": 7381, + "actualSha256": "b7c140f126bc2d48df00fe4111517e3ea2f43926d52797d26733e1f2522f6a03", + "passed": true + }, + { + "path": "src/client/PurgeStrategyControl.css", + "bytes": 2605, + "sha256": "09545bccee1832c54275c884c830d1c8bb442469e919387d7a26cc77e0fb5cd4", + "actualBytes": 2605, + "actualSha256": "09545bccee1832c54275c884c830d1c8bb442469e919387d7a26cc77e0fb5cd4", + "passed": true + }, + { + "path": "src/client/PurgeStrategyControl.tsx", + "bytes": 6531, + "sha256": "9a87b85a2fb133c189c31e1916f364cc6ffb7e6a02d7b51291b2322f61ae03c1", + "actualBytes": 6531, + "actualSha256": "9a87b85a2fb133c189c31e1916f364cc6ffb7e6a02d7b51291b2322f61ae03c1", + "passed": true + }, + { + "path": "src/client/RequestContextPanel.tsx", + "bytes": 9245, + "sha256": "9b7bd92ff4afc6a8e4c1fd129dea053acb8b135330582643beef62608b737e79", + "actualBytes": 9245, + "actualSha256": "9b7bd92ff4afc6a8e4c1fd129dea053acb8b135330582643beef62608b737e79", + "passed": true + }, + { + "path": "src/client/ResearchPanel.css", + "bytes": 7271, + "sha256": "f24f8eb283c0b419037adcd680bc1bbe84002abf661bfda94891dcea5fc92682", + "actualBytes": 7271, + "actualSha256": "f24f8eb283c0b419037adcd680bc1bbe84002abf661bfda94891dcea5fc92682", + "passed": true + }, + { + "path": "src/client/ResearchPanel.tsx", + "bytes": 16684, + "sha256": "cae237fc267a491db18f24f88e0b6926a635225886bfa58683a37f6d4586c8e1", + "actualBytes": 16684, + "actualSha256": "cae237fc267a491db18f24f88e0b6926a635225886bfa58683a37f6d4586c8e1", + "passed": true + }, + { + "path": "src/client/SkillCenter.css", + "bytes": 6453, + "sha256": "d9f79bba3be7369a0231434aa29fe061e0c5d1f792aeb7e15e3f2a7744165242", + "actualBytes": 6453, + "actualSha256": "d9f79bba3be7369a0231434aa29fe061e0c5d1f792aeb7e15e3f2a7744165242", + "passed": true + }, + { + "path": "src/client/SkillCenter.tsx", + "bytes": 9303, + "sha256": "b227ffdccf1d90ac969f1e4e2a56c592b7c9eac13746bf0c90ee9d9e702e9f10", + "actualBytes": 9303, + "actualSha256": "b227ffdccf1d90ac969f1e4e2a56c592b7c9eac13746bf0c90ee9d9e702e9f10", + "passed": true + }, + { + "path": "src/client/TaskCheckpointPanel.tsx", + "bytes": 5367, + "sha256": "77b552924379531eff51c81c5bf4e2512c1201f39641245c781a468e6a7e397a", + "actualBytes": 5367, + "actualSha256": "77b552924379531eff51c81c5bf4e2512c1201f39641245c781a468e6a7e397a", + "passed": true + }, + { + "path": "src/client/TaskPanel.css", + "bytes": 8906, + "sha256": "6dc737d84406fafd2f1b36ba1eaf02c8b0f59594b30a1fadcf2d3451ada285db", + "actualBytes": 8906, + "actualSha256": "6dc737d84406fafd2f1b36ba1eaf02c8b0f59594b30a1fadcf2d3451ada285db", + "passed": true + }, + { + "path": "src/client/TaskPanel.tsx", + "bytes": 23895, + "sha256": "2032d71336d5c645067f1507d946b7daf2a4aa6c30cd95c0fd64ebc169346d18", + "actualBytes": 23895, + "actualSha256": "2032d71336d5c645067f1507d946b7daf2a4aa6c30cd95c0fd64ebc169346d18", + "passed": true + }, + { + "path": "src/client/TaskPlanPanel.css", + "bytes": 4257, + "sha256": "e47eb1195a61400d60817de793893d9e4924f334bdf452ffb744ed69741c43fc", + "actualBytes": 4257, + "actualSha256": "e47eb1195a61400d60817de793893d9e4924f334bdf452ffb744ed69741c43fc", + "passed": true + }, + { + "path": "src/client/TaskPlanPanel.tsx", + "bytes": 16192, + "sha256": "02de2817d2f9a888b50a272ee4c67707e76dc46580fae2db0625a7fd6d032760", + "actualBytes": 16192, + "actualSha256": "02de2817d2f9a888b50a272ee4c67707e76dc46580fae2db0625a7fd6d032760", + "passed": true + }, + { + "path": "src/client/WorkerPanel.css", + "bytes": 7998, + "sha256": "b9bbb50cb57339f3ca16242a7f32bbe230d54a1583c4ae46edc2ef68835d02b1", + "actualBytes": 7998, + "actualSha256": "b9bbb50cb57339f3ca16242a7f32bbe230d54a1583c4ae46edc2ef68835d02b1", + "passed": true + }, + { + "path": "src/client/WorkerPanel.tsx", + "bytes": 25071, + "sha256": "d7a19f9a834a7953940cb9a392061938a80f6635e1d021e17ef46e1941cc04d4", + "actualBytes": 25071, + "actualSha256": "d7a19f9a834a7953940cb9a392061938a80f6635e1d021e17ef46e1941cc04d4", + "passed": true + }, + { + "path": "src/client/WorkspacePanel.css", + "bytes": 3743, + "sha256": "d8c4558f6c559ff8b4bbc7723aca08e4e37f8fef8f5b8d5619faec8332314ba3", + "actualBytes": 3743, + "actualSha256": "d8c4558f6c559ff8b4bbc7723aca08e4e37f8fef8f5b8d5619faec8332314ba3", + "passed": true + }, + { + "path": "src/client/WorkspacePanel.tsx", + "bytes": 10026, + "sha256": "c91d097edd5e044f72583bdccd39848f35a5b82c4d9abf7c09648e21ecfdb8c2", + "actualBytes": 10026, + "actualSha256": "c91d097edd5e044f72583bdccd39848f35a5b82c4d9abf7c09648e21ecfdb8c2", + "passed": true + }, + { + "path": "src/client/api.ts", + "bytes": 5549, + "sha256": "13c5ee361d6b4766743361b4b4b5a360b4bd7c19cd69ce6a1a512e2e8f67845e", + "actualBytes": 5549, + "actualSha256": "13c5ee361d6b4766743361b4b4b5a360b4bd7c19cd69ce6a1a512e2e8f67845e", + "passed": true + }, + { + "path": "src/client/companion-panel.css", + "bytes": 3343, + "sha256": "00d2eddd5ed09434317d87a99c351799a38896c2a928cb985ac6c6c6b134bf84", + "actualBytes": 3343, + "actualSha256": "00d2eddd5ed09434317d87a99c351799a38896c2a928cb985ac6c6c6b134bf84", + "passed": true + }, + { + "path": "src/client/companion-types.ts", + "bytes": 2991, + "sha256": "4c7feaf322164bd144fb1d0507ae36d875aa0565b8fda99b740a6e016c546936", + "actualBytes": 2991, + "actualSha256": "4c7feaf322164bd144fb1d0507ae36d875aa0565b8fda99b740a6e016c546936", + "passed": true + }, + { + "path": "src/client/components.tsx", + "bytes": 13976, + "sha256": "6a92c18ba88286b736cb61cabd31e024841448cebe9fd7fad7856c1d24130973", + "actualBytes": 13976, + "actualSha256": "6a92c18ba88286b736cb61cabd31e024841448cebe9fd7fad7856c1d24130973", + "passed": true + }, + { + "path": "src/client/control-console.css", + "bytes": 5579, + "sha256": "400c3b2880476993001d819aa49e86e2edee3b6f959c0499fa1b8f307554a03f", + "actualBytes": 5579, + "actualSha256": "400c3b2880476993001d819aa49e86e2edee3b6f959c0499fa1b8f307554a03f", + "passed": true + }, + { + "path": "src/client/desktop.ts", + "bytes": 1487, + "sha256": "ec0d03aa1dcf7da45643de8e8f01480829922e95bf67fd9097aa95f2f8e13604", + "actualBytes": 1487, + "actualSha256": "ec0d03aa1dcf7da45643de8e8f01480829922e95bf67fd9097aa95f2f8e13604", + "passed": true + }, + { + "path": "src/client/input-attachments.css", + "bytes": 3104, + "sha256": "4e9b964b6ecb9eed2bf345ed5b689f5a56320b45e02c01a9cc6ac8cddd259db3", + "actualBytes": 3104, + "actualSha256": "4e9b964b6ecb9eed2bf345ed5b689f5a56320b45e02c01a9cc6ac8cddd259db3", + "passed": true + }, + { + "path": "src/client/main.tsx", + "bytes": 256, + "sha256": "6dec6d76306f0e47b1a9e77004377daa5312270d519a685f169c025a9e071792", + "actualBytes": 256, + "actualSha256": "6dec6d76306f0e47b1a9e77004377daa5312270d519a685f169c025a9e071792", + "passed": true + }, + { + "path": "src/client/mobile/MobileApp.tsx", + "bytes": 26434, + "sha256": "ca9627888c04513e89362e8cb6a52470c1c29b475f22f215171a3984120d133c", + "actualBytes": 26434, + "actualSha256": "ca9627888c04513e89362e8cb6a52470c1c29b475f22f215171a3984120d133c", + "passed": true + }, + { + "path": "src/client/mobile/MobileBrowserObservation.tsx", + "bytes": 2181, + "sha256": "08efad6a275c5d37fa2d0805b8f48d84c239113d78bbba2b39f624eb9570593f", + "actualBytes": 2181, + "actualSha256": "08efad6a275c5d37fa2d0805b8f48d84c239113d78bbba2b39f624eb9570593f", + "passed": true + }, + { + "path": "src/client/mobile/MobileInputImage.tsx", + "bytes": 2719, + "sha256": "57977b9e54deeb35067bd897c01d285805774d42ee538bc304dae7274888a654", + "actualBytes": 2719, + "actualSha256": "57977b9e54deeb35067bd897c01d285805774d42ee538bc304dae7274888a654", + "passed": true + }, + { + "path": "src/client/mobile/api.ts", + "bytes": 1999, + "sha256": "3104117da9a0802fda32f86773ea730dad29ff9a0fc9634ec1d8e9b7a4750d91", + "actualBytes": 1999, + "actualSha256": "3104117da9a0802fda32f86773ea730dad29ff9a0fc9634ec1d8e9b7a4750d91", + "passed": true + }, + { + "path": "src/client/mobile/file-results.css", + "bytes": 527, + "sha256": "5eacd27a9a5e5d99c68ffff619aca357f7d4dc5ad0d92fc8c630ebdd0ca49822", + "actualBytes": 527, + "actualSha256": "5eacd27a9a5e5d99c68ffff619aca357f7d4dc5ad0d92fc8c630ebdd0ca49822", + "passed": true + }, + { + "path": "src/client/mobile/main.tsx", + "bytes": 586, + "sha256": "c685a435aa5e124ed1593deec163e671a8a1f3458f08808da029911b22c9ad96", + "actualBytes": 586, + "actualSha256": "c685a435aa5e124ed1593deec163e671a8a1f3458f08808da029911b22c9ad96", + "passed": true + }, + { + "path": "src/client/mobile/mobile.css", + "bytes": 11978, + "sha256": "9a5ac0fb2cabc2dbb0b9f9ef3edbeb5ff26e31d1347fa712485c00605b3980a0", + "actualBytes": 11978, + "actualSha256": "9a5ac0fb2cabc2dbb0b9f9ef3edbeb5ff26e31d1347fa712485c00605b3980a0", + "passed": true + }, + { + "path": "src/client/styles.css", + "bytes": 40897, + "sha256": "13e59493e850b7642a395719a01e7a66228f3b13719c348b2764fe276627c033", + "actualBytes": 40897, + "actualSha256": "13e59493e850b7642a395719a01e7a66228f3b13719c348b2764fe276627c033", + "passed": true + }, + { + "path": "src/client/types.ts", + "bytes": 41045, + "sha256": "cbc6e0048a655c3c0fc3114c3a228aeb2201f7ae4b7f57a0a6701aee0dd8fcd6", + "actualBytes": 41045, + "actualSha256": "cbc6e0048a655c3c0fc3114c3a228aeb2201f7ae4b7f57a0a6701aee0dd8fcd6", + "passed": true + }, + { + "path": "src/core/browser/browser-driver.mjs", + "bytes": 18254, + "sha256": "d63e3ae49bdec13f2f86923c21d4af4d7f1ea1b07c768be3cc85b4833836bdd2", + "actualBytes": 18254, + "actualSha256": "d63e3ae49bdec13f2f86923c21d4af4d7f1ea1b07c768be3cc85b4833836bdd2", + "passed": true + }, + { + "path": "src/core/browser/browser-manager.mjs", + "bytes": 24633, + "sha256": "0efc0e30f19a8649c964e1193c455d6cc6f32bfd4a4a5e18fc6ff8014d67b820", + "actualBytes": 24633, + "actualSha256": "0efc0e30f19a8649c964e1193c455d6cc6f32bfd4a4a5e18fc6ff8014d67b820", + "passed": true + }, + { + "path": "src/core/browser/browsing-manager.mjs", + "bytes": 19138, + "sha256": "9b57f9a9b5479186fae2306925016264789e4b9e6f9f388ce025abe3a1df92d8", + "actualBytes": 19138, + "actualSha256": "9b57f9a9b5479186fae2306925016264789e4b9e6f9f388ce025abe3a1df92d8", + "passed": true + }, + { + "path": "src/core/browser/build-snapshot.mjs", + "bytes": 4309, + "sha256": "2424f37847e72621327b5c0157f9fc03c1e7dd266ca71292b4b70571f17170a9", + "actualBytes": 4309, + "actualSha256": "2424f37847e72621327b5c0157f9fc03c1e7dd266ca71292b4b70571f17170a9", + "passed": true + }, + { + "path": "src/core/check-runner.mjs", + "bytes": 23181, + "sha256": "4a6e3e312edc8e47c6e84178db510d2ec0c69d44fd4b3220f6236b07ae9d5a6b", + "actualBytes": 23181, + "actualSha256": "4a6e3e312edc8e47c6e84178db510d2ec0c69d44fd4b3220f6236b07ae9d5a6b", + "passed": true + }, + { + "path": "src/core/companion/device-registry.mjs", + "bytes": 9842, + "sha256": "2fe69e47a7acf303dfcf33697b667bae9ea53c7cd17e6830f9c607a7f0222537", + "actualBytes": 9842, + "actualSha256": "2fe69e47a7acf303dfcf33697b667bae9ea53c7cd17e6830f9c607a7f0222537", + "passed": true + }, + { + "path": "src/core/companion/projection.mjs", + "bytes": 5400, + "sha256": "20f8c02d63809b9c801ce72ed7168ab33aacf057c8cf2292a6fc733b7210971a", + "actualBytes": 5400, + "actualSha256": "20f8c02d63809b9c801ce72ed7168ab33aacf057c8cf2292a6fc733b7210971a", + "passed": true + }, + { + "path": "src/core/companion/tls-authority.mjs", + "bytes": 5328, + "sha256": "35ce38d5b71a2258b2739624b73c510745cb935969d312fa899df23997692cb1", + "actualBytes": 5328, + "actualSha256": "35ce38d5b71a2258b2739624b73c510745cb935969d312fa899df23997692cb1", + "passed": true + }, + { + "path": "src/core/context/budget-resume.mjs", + "bytes": 6734, + "sha256": "4341a940ae3dbf05e51403c282fa91ff45d6bfe08ab0df5c449cc3a243d888e3", + "actualBytes": 6734, + "actualSha256": "4341a940ae3dbf05e51403c282fa91ff45d6bfe08ab0df5c449cc3a243d888e3", + "passed": true + }, + { + "path": "src/core/context/delivery-progress.mjs", + "bytes": 5225, + "sha256": "b883448a7ff70508472b013d710f1a87dc6ac9711daadfe654179fdfbe348889", + "actualBytes": 5225, + "actualSha256": "b883448a7ff70508472b013d710f1a87dc6ac9711daadfe654179fdfbe348889", + "passed": true + }, + { + "path": "src/core/context/index-cache.mjs", + "bytes": 7439, + "sha256": "5d6c106108d543ad95e60bcd4513d749b77a2c875e02b66268282a5b1b8d0dd4", + "actualBytes": 7439, + "actualSha256": "5d6c106108d543ad95e60bcd4513d749b77a2c875e02b66268282a5b1b8d0dd4", + "passed": true + }, + { + "path": "src/core/context/input-attachments.mjs", + "bytes": 10744, + "sha256": "714b387ab8e9fd65ce6a8c6ea187020fdae9671022f2efda5b053491f3a97bf0", + "actualBytes": 10744, + "actualSha256": "714b387ab8e9fd65ce6a8c6ea187020fdae9671022f2efda5b053491f3a97bf0", + "passed": true + }, + { + "path": "src/core/context/project-index.mjs", + "bytes": 24767, + "sha256": "26c907ddcc4e828614806f0eb270a3d31377a4479a83afed8a9e94be25ca7380", + "actualBytes": 24767, + "actualSha256": "26c907ddcc4e828614806f0eb270a3d31377a4479a83afed8a9e94be25ca7380", + "passed": true + }, + { + "path": "src/core/context/read-budget.mjs", + "bytes": 13897, + "sha256": "8bf309d662240a89f952a3f70260301868c8976593f92696f46e64acc3e15307", + "actualBytes": 13897, + "actualSha256": "8bf309d662240a89f952a3f70260301868c8976593f92696f46e64acc3e15307", + "passed": true + }, + { + "path": "src/core/context/request-plan.mjs", + "bytes": 40633, + "sha256": "0525beddf1ca05d84d780972e9a97c013f48de69e716a77be1c86ff3a2952e7d", + "actualBytes": 40633, + "actualSha256": "0525beddf1ca05d84d780972e9a97c013f48de69e716a77be1c86ff3a2952e7d", + "passed": true + }, + { + "path": "src/core/context/tool-feedback.mjs", + "bytes": 9640, + "sha256": "a6c6350cd5b708624176c7b588b00a64358ec69ab6ab9447caedf7c482f4c817", + "actualBytes": 9640, + "actualSha256": "a6c6350cd5b708624176c7b588b00a64358ec69ab6ab9447caedf7c482f4c817", + "passed": true + }, + { + "path": "src/core/context/working-set.mjs", + "bytes": 11071, + "sha256": "a8e9183321c3b5bc2afb7955a6daf496ff72d3e938be9b9ec514eaacfa7352be", + "actualBytes": 11071, + "actualSha256": "a8e9183321c3b5bc2afb7955a6daf496ff72d3e938be9b9ec514eaacfa7352be", + "passed": true + }, + { + "path": "src/core/delivery-report.mjs", + "bytes": 26781, + "sha256": "c0151695fc4e277b8c1c54b3ed2f882681a648b3d7283ca5ba8cb837d65872ec", + "actualBytes": 26781, + "actualSha256": "c0151695fc4e277b8c1c54b3ed2f882681a648b3d7283ca5ba8cb837d65872ec", + "passed": true + }, + { + "path": "src/core/desktop/app-installation.mjs", + "bytes": 4592, + "sha256": "aa752f3044cb6dfb9ca56095114f1bb32f49980bc2246d24952ae5c78e533736", + "actualBytes": 4592, + "actualSha256": "aa752f3044cb6dfb9ca56095114f1bb32f49980bc2246d24952ae5c78e533736", + "passed": true + }, + { + "path": "src/core/desktop/desktop-bridge.mjs", + "bytes": 5749, + "sha256": "7d1b17ac869e51fa9be1ad327a8ed50d2ac16dae8c282cc346aa7138718cf92a", + "actualBytes": 5749, + "actualSha256": "7d1b17ac869e51fa9be1ad327a8ed50d2ac16dae8c282cc346aa7138718cf92a", + "passed": true + }, + { + "path": "src/core/desktop/file-state.mjs", + "bytes": 3610, + "sha256": "cf7b1541e4f8ed021cf680b2e4d110130a68957b38f1bd3f5ee3e5bcb3ed0c9b", + "actualBytes": 3610, + "actualSha256": "cf7b1541e4f8ed021cf680b2e4d110130a68957b38f1bd3f5ee3e5bcb3ed0c9b", + "passed": true + }, + { + "path": "src/core/desktop/host-authority.mjs", + "bytes": 11630, + "sha256": "18347308c5982d6400723b2635eb10f3b70818df071847836137953a4ab2afc1", + "actualBytes": 11630, + "actualSha256": "18347308c5982d6400723b2635eb10f3b70818df071847836137953a4ab2afc1", + "passed": true + }, + { + "path": "src/core/desktop/host-controller.mjs", + "bytes": 13817, + "sha256": "c5e61af394ede9a92d902868633c73c9d3059134f471d0d5d0beed392af8af45", + "actualBytes": 13817, + "actualSha256": "c5e61af394ede9a92d902868633c73c9d3059134f471d0d5d0beed392af8af45", + "passed": true + }, + { + "path": "src/core/desktop/install-manager.mjs", + "bytes": 23136, + "sha256": "91c216537666f690122071a5b53b7c8b3beba4ea549acd1534edca24390d9635", + "actualBytes": 23136, + "actualSha256": "91c216537666f690122071a5b53b7c8b3beba4ea549acd1534edca24390d9635", + "passed": true + }, + { + "path": "src/core/desktop/installation-progress.mjs", + "bytes": 7039, + "sha256": "80550667808e4caf5564b1931e33794b7eae201e6817f3abc0bb0132fe66bc45", + "actualBytes": 7039, + "actualSha256": "80550667808e4caf5564b1931e33794b7eae201e6817f3abc0bb0132fe66bc45", + "passed": true + }, + { + "path": "src/core/desktop/launch-options.mjs", + "bytes": 843, + "sha256": "f4306e4f128c2fc541362ee604dfac5251947144b9c1bb8c503698b1bfe6eab2", + "actualBytes": 843, + "actualSha256": "f4306e4f128c2fc541362ee604dfac5251947144b9c1bb8c503698b1bfe6eab2", + "passed": true + }, + { + "path": "src/core/desktop/process-identity.mjs", + "bytes": 4770, + "sha256": "fca6b8eb398f4191eb2b7d067874d56c95fa4d7bbf2b2e0d258e2445d8e8790b", + "actualBytes": 4770, + "actualSha256": "fca6b8eb398f4191eb2b7d067874d56c95fa4d7bbf2b2e0d258e2445d8e8790b", + "passed": true + }, + { + "path": "src/core/desktop/windows-dpapi.mjs", + "bytes": 2490, + "sha256": "8b2569f336df8be27f487f7f7a33987c0298b8770c2ec23146546dc839049339", + "actualBytes": 2490, + "actualSha256": "8b2569f336df8be27f487f7f7a33987c0298b8770c2ec23146546dc839049339", + "passed": true + }, + { + "path": "src/core/engine-manager.mjs", + "bytes": 12455, + "sha256": "ec29a945c84ee79a41d30ac3a70296281bdd7d7898cc727a85bb6d78af62f015", + "actualBytes": 12455, + "actualSha256": "ec29a945c84ee79a41d30ac3a70296281bdd7d7898cc727a85bb6d78af62f015", + "passed": true + }, + { + "path": "src/core/engines/controlled-installation.mjs", + "bytes": 3940, + "sha256": "0a246abc846dbc6ce4fcb7e21fa272466fc5a69a738c47a7848e37612e319aa0", + "actualBytes": 3940, + "actualSha256": "0a246abc846dbc6ce4fcb7e21fa272466fc5a69a738c47a7848e37612e319aa0", + "passed": true + }, + { + "path": "src/core/engines/controlled-plugin.mjs", + "bytes": 7265, + "sha256": "8f7b9da52b4afdd654ae5e020264e64daa4363f1d0d1d10ae766ed9d2a8f2016", + "actualBytes": 7265, + "actualSha256": "8f7b9da52b4afdd654ae5e020264e64daa4363f1d0d1d10ae766ed9d2a8f2016", + "passed": true + }, + { + "path": "src/core/engines/controlled-session.mjs", + "bytes": 18514, + "sha256": "448d164e3743dd585f24ad879f027d6c10db6a4a15d816a767a511f8b86f274e", + "actualBytes": 18514, + "actualSha256": "448d164e3743dd585f24ad879f027d6c10db6a4a15d816a767a511f8b86f274e", + "passed": true + }, + { + "path": "src/core/engines/deepseek-adapter.mjs", + "bytes": 10977, + "sha256": "b5d3e3f1ba74b8d15b002594f13652bbc98761226a3e5e3fb408071762958fa9", + "actualBytes": 10977, + "actualSha256": "b5d3e3f1ba74b8d15b002594f13652bbc98761226a3e5e3fb408071762958fa9", + "passed": true + }, + { + "path": "src/core/engines/deepseek-installation.mjs", + "bytes": 6119, + "sha256": "c52d65c0c2dd07144ae7734bfdc240e7c48436a35858373998000ad920ae26de", + "actualBytes": 6119, + "actualSha256": "c52d65c0c2dd07144ae7734bfdc240e7c48436a35858373998000ad920ae26de", + "passed": true + }, + { + "path": "src/core/engines/engine-runner.mjs", + "bytes": 29708, + "sha256": "7685b9cdd370eb136705980dc613dd004f20e5de60376b0a12e2d3d85938e968", + "actualBytes": 29708, + "actualSha256": "7685b9cdd370eb136705980dc613dd004f20e5de60376b0a12e2d3d85938e968", + "passed": true + }, + { + "path": "src/core/engines/original-purge-lock.json", + "bytes": 88993, + "sha256": "ef396c04a0ba0f2cfcef26660f8d39cd36bfbfdeedfcb526f1d3c58006cb7a3f", + "actualBytes": 88993, + "actualSha256": "ef396c04a0ba0f2cfcef26660f8d39cd36bfbfdeedfcb526f1d3c58006cb7a3f", + "passed": true + }, + { + "path": "src/core/engines/original-purge-runtime.mjs", + "bytes": 19176, + "sha256": "efbdc576edcc42931fc4ead441fea8dd44835441a427c945d6c3e8272b466698", + "actualBytes": 19176, + "actualSha256": "efbdc576edcc42931fc4ead441fea8dd44835441a427c945d6c3e8272b466698", + "passed": true + }, + { + "path": "src/core/engines/original-purge-source.mjs", + "bytes": 5069, + "sha256": "be4954bcc58bf16d17c79958068bd6e6196d195d13e73f2aa5bb4f7be583c21a", + "actualBytes": 5069, + "actualSha256": "be4954bcc58bf16d17c79958068bd6e6196d195d13e73f2aa5bb4f7be583c21a", + "passed": true + }, + { + "path": "src/core/engines/purge-strategy.mjs", + "bytes": 10095, + "sha256": "df7a48b76c7e5043f56d403b71894a53dff5c984ebe0921c2ba800c9c0711d19", + "actualBytes": 10095, + "actualSha256": "df7a48b76c7e5043f56d403b71894a53dff5c984ebe0921c2ba800c9c0711d19", + "passed": true + }, + { + "path": "src/core/engines/registered-sources.mjs", + "bytes": 4109, + "sha256": "f3732838bb4b8b3f8a070d8991a0eb1c8dec497cca56bf4579cc95d6ec0f2211", + "actualBytes": 4109, + "actualSha256": "f3732838bb4b8b3f8a070d8991a0eb1c8dec497cca56bf4579cc95d6ec0f2211", + "passed": true + }, + { + "path": "src/core/environment/environment-evidence.mjs", + "bytes": 2012, + "sha256": "02b2e32d3465403b135f9bf1d4232a9c9a16dd492f5469e63dfb0998eb8e3258", + "actualBytes": 2012, + "actualSha256": "02b2e32d3465403b135f9bf1d4232a9c9a16dd492f5469e63dfb0998eb8e3258", + "passed": true + }, + { + "path": "src/core/environment/environment-inspector.mjs", + "bytes": 14234, + "sha256": "d226f54236be2c9b47479b6c0c63c160ca068328d184e9d86f98fd6e791bd87c", + "actualBytes": 14234, + "actualSha256": "d226f54236be2c9b47479b6c0c63c160ca068328d184e9d86f98fd6e791bd87c", + "passed": true + }, + { + "path": "src/core/environment/environment-manager.mjs", + "bytes": 17237, + "sha256": "a83afa4b3fa467d38689a596646a490e8a16c86c064344e6d81e1e81c4afc340", + "actualBytes": 17237, + "actualSha256": "a83afa4b3fa467d38689a596646a490e8a16c86c064344e6d81e1e81c4afc340", + "passed": true + }, + { + "path": "src/core/evaluation/evaluation-manager.mjs", + "bytes": 28712, + "sha256": "c072e6c1894702955ce5d8838fbf7aa6c43c1a9cece1665a1309758878fda941", + "actualBytes": 28712, + "actualSha256": "c072e6c1894702955ce5d8838fbf7aa6c43c1a9cece1665a1309758878fda941", + "passed": true + }, + { + "path": "src/core/evaluation/provenance.mjs", + "bytes": 4199, + "sha256": "2626f683d56deeaf5dee146f4b23a87a629579a75197425c952006d277b7644f", + "actualBytes": 4199, + "actualSha256": "2626f683d56deeaf5dee146f4b23a87a629579a75197425c952006d277b7644f", + "passed": true + }, + { + "path": "src/core/git-delivery.mjs", + "bytes": 41256, + "sha256": "106d7f6384f69ecff0cd68ba89f0a45876d37cc0bce537b75490e78e1aae8ca6", + "actualBytes": 41256, + "actualSha256": "106d7f6384f69ecff0cd68ba89f0a45876d37cc0bce537b75490e78e1aae8ca6", + "passed": true + }, + { + "path": "src/core/git-process.mjs", + "bytes": 2655, + "sha256": "80547ec8928610ac4df5a05c5aef12d1aab0dca9e7b1def2773fc745f5adf5f5", + "actualBytes": 2655, + "actualSha256": "80547ec8928610ac4df5a05c5aef12d1aab0dca9e7b1def2773fc745f5adf5f5", + "passed": true + }, + { + "path": "src/core/initial-example-project.mjs", + "bytes": 1630, + "sha256": "9b9d6e7336e13ef083e21132d57315ae4175b829fa1fdd80746b6c941e794c6e", + "actualBytes": 1630, + "actualSha256": "9b9d6e7336e13ef083e21132d57315ae4175b829fa1fdd80746b6c941e794c6e", + "passed": true + }, + { + "path": "src/core/memory/project-memory.mjs", + "bytes": 13871, + "sha256": "9c7da0ef9c7f36b431015fd4414f55304f8d5e25a61bc527fb7e3be0b7971e51", + "actualBytes": 13871, + "actualSha256": "9c7da0ef9c7f36b431015fd4414f55304f8d5e25a61bc527fb7e3be0b7971e51", + "passed": true + }, + { + "path": "src/core/models/config-import.mjs", + "bytes": 9025, + "sha256": "7960d5d8df31e2614ee5253b916cf483e5e3f8584066a760b80d1563459ea94f", + "actualBytes": 9025, + "actualSha256": "7960d5d8df31e2614ee5253b916cf483e5e3f8584066a760b80d1563459ea94f", + "passed": true + }, + { + "path": "src/core/models/credential-vault.mjs", + "bytes": 6533, + "sha256": "631e259f3ad5e8ae42b40ecb7d00527e1d13eb1b450aa99208933a5027bf26cb", + "actualBytes": 6533, + "actualSha256": "631e259f3ad5e8ae42b40ecb7d00527e1d13eb1b450aa99208933a5027bf26cb", + "passed": true + }, + { + "path": "src/core/models/messages-stream.mjs", + "bytes": 5764, + "sha256": "26ee43925828b517790cf5c55ac7a728f7afe5dae2c2b0463103d9cd37a606e6", + "actualBytes": 5764, + "actualSha256": "26ee43925828b517790cf5c55ac7a728f7afe5dae2c2b0463103d9cd37a606e6", + "passed": true + }, + { + "path": "src/core/models/model-hub.mjs", + "bytes": 33935, + "sha256": "7c427ec5e2035e7dca52beb25b13db7a7decdc0a5ca061973697cd4b66466a8e", + "actualBytes": 33935, + "actualSha256": "7c427ec5e2035e7dca52beb25b13db7a7decdc0a5ca061973697cd4b66466a8e", + "passed": true + }, + { + "path": "src/core/models/model-stream.mjs", + "bytes": 11949, + "sha256": "a18b085d6d8ca728c31bff54a9ea5e1b296d92eaec5aacefd63b46e301501b22", + "actualBytes": 11949, + "actualSha256": "a18b085d6d8ca728c31bff54a9ea5e1b296d92eaec5aacefd63b46e301501b22", + "passed": true + }, + { + "path": "src/core/models/protocols.mjs", + "bytes": 8476, + "sha256": "31b9decb074909a598e2926487ff90aa36c0e8c46cb4154e8bfd8959085a2fba", + "actualBytes": 8476, + "actualSha256": "31b9decb074909a598e2926487ff90aa36c0e8c46cb4154e8bfd8959085a2fba", + "passed": true + }, + { + "path": "src/core/models/request-deadline.mjs", + "bytes": 2574, + "sha256": "8eef28c3250fa53149191373e60b7d746d5009a601cf87bae9c51361cdc6b0b8", + "actualBytes": 2574, + "actualSha256": "8eef28c3250fa53149191373e60b7d746d5009a601cf87bae9c51361cdc6b0b8", + "passed": true + }, + { + "path": "src/core/models/runtime-settings.mjs", + "bytes": 833, + "sha256": "41ba7fee56fbb1fc6997777ce140cbeca4094c840ff0765f619ee8b19e19c93e", + "actualBytes": 833, + "actualSha256": "41ba7fee56fbb1fc6997777ce140cbeca4094c840ff0765f619ee8b19e19c93e", + "passed": true + }, + { + "path": "src/core/models/transport.mjs", + "bytes": 1213, + "sha256": "d72c96a150b49d2c89d0360cb870f561105921c741f294d6d701b937359db7f5", + "actualBytes": 1213, + "actualSha256": "d72c96a150b49d2c89d0360cb870f561105921c741f294d6d701b937359db7f5", + "passed": true + }, + { + "path": "src/core/models/upstream-error.mjs", + "bytes": 5198, + "sha256": "161fac72c1ee8abc6f668ad53a06dd5c2952a89474cc80d501b26f21836da7b1", + "actualBytes": 5198, + "actualSha256": "161fac72c1ee8abc6f668ad53a06dd5c2952a89474cc80d501b26f21836da7b1", + "passed": true + }, + { + "path": "src/core/models/vision-probe.mjs", + "bytes": 1113, + "sha256": "94022c1221c0a73b27c96e146b787e7968b941f154628743f9a22bd20c5869ab", + "actualBytes": 1113, + "actualSha256": "94022c1221c0a73b27c96e146b787e7968b941f154628743f9a22bd20c5869ab", + "passed": true + }, + { + "path": "src/core/owned-command.mjs", + "bytes": 6419, + "sha256": "e6a9162a53094724bb84fd8d5c94f4f7ca95b8bb76046f4cf5ed9d9c97f8cedb", + "actualBytes": 6419, + "actualSha256": "e6a9162a53094724bb84fd8d5c94f4f7ca95b8bb76046f4cf5ed9d9c97f8cedb", + "passed": true + }, + { + "path": "src/core/owned-process-tree.mjs", + "bytes": 3010, + "sha256": "b1742eb2b3db3f661815cd5b3d806197082bcadb7b0ba20a91837590b2a394f4", + "actualBytes": 3010, + "actualSha256": "b1742eb2b3db3f661815cd5b3d806197082bcadb7b0ba20a91837590b2a394f4", + "passed": true + }, + { + "path": "src/core/preview/listener.mjs", + "bytes": 2156, + "sha256": "d65079d9c6e81d2dc4246160a4fef150c0b2b6d32ecf40972bdcab3d891b0eb4", + "actualBytes": 2156, + "actualSha256": "d65079d9c6e81d2dc4246160a4fef150c0b2b6d32ecf40972bdcab3d891b0eb4", + "passed": true + }, + { + "path": "src/core/preview/local-file-preview.mjs", + "bytes": 6469, + "sha256": "9d057594cb6435e02c0eab5f43a9c090d98239ddac4cebd131418a931ac46e4f", + "actualBytes": 6469, + "actualSha256": "9d057594cb6435e02c0eab5f43a9c090d98239ddac4cebd131418a931ac46e4f", + "passed": true + }, + { + "path": "src/core/preview/preview-manager.mjs", + "bytes": 14208, + "sha256": "80c2d0b7aec0fcabbb9a6b695b05636a1b82062f8b37c875e36e3da540ae933a", + "actualBytes": 14208, + "actualSha256": "80c2d0b7aec0fcabbb9a6b695b05636a1b82062f8b37c875e36e3da540ae933a", + "passed": true + }, + { + "path": "src/core/process-environment.mjs", + "bytes": 910, + "sha256": "05f7ca9bad79ed96a184c96643edffc320aef45567e888341531448f23c89702", + "actualBytes": 910, + "actualSha256": "05f7ca9bad79ed96a184c96643edffc320aef45567e888341531448f23c89702", + "passed": true + }, + { + "path": "src/core/project-inspector.mjs", + "bytes": 15489, + "sha256": "ac67653db74add2d1c0854405f4dc4616216837691e95d9eaee5f76280cc4415", + "actualBytes": 15489, + "actualSha256": "ac67653db74add2d1c0854405f4dc4616216837691e95d9eaee5f76280cc4415", + "passed": true + }, + { + "path": "src/core/python-project.mjs", + "bytes": 4721, + "sha256": "74e09a96f2e1970b155d37af176379807add0d5a05f72ccd9491d4d494d58707", + "actualBytes": 4721, + "actualSha256": "74e09a96f2e1970b155d37af176379807add0d5a05f72ccd9491d4d494d58707", + "passed": true + }, + { + "path": "src/core/python-runtime.mjs", + "bytes": 12568, + "sha256": "9e9f1b9128295f46404839ad95eaf8bcad60a8c4964756e7c1a1b21cc4add0d7", + "actualBytes": 12568, + "actualSha256": "9e9f1b9128295f46404839ad95eaf8bcad60a8c4964756e7c1a1b21cc4add0d7", + "passed": true + }, + { + "path": "src/core/research-manager.mjs", + "bytes": 19987, + "sha256": "15981370de1f02db4acec2c3e1450d068236e1f6ab70f677ec8617aa968fc2dc", + "actualBytes": 19987, + "actualSha256": "15981370de1f02db4acec2c3e1450d068236e1f6ab70f677ec8617aa968fc2dc", + "passed": true + }, + { + "path": "src/core/skills/skill-registry.mjs", + "bytes": 15494, + "sha256": "63e435d65e3dfe7dff1b1711590b5a4a5ca2efddaa67822087de06facdadf3bb", + "actualBytes": 15494, + "actualSha256": "63e435d65e3dfe7dff1b1711590b5a4a5ca2efddaa67822087de06facdadf3bb", + "passed": true + }, + { + "path": "src/core/storage/artifact-store.mjs", + "bytes": 2918, + "sha256": "2934d31a28da215f7ea73a3b5e56d106b723b34539ea8605d523b121762e488a", + "actualBytes": 2918, + "actualSha256": "2934d31a28da215f7ea73a3b5e56d106b723b34539ea8605d523b121762e488a", + "passed": true + }, + { + "path": "src/core/storage/legacy-import.mjs", + "bytes": 5029, + "sha256": "2d1b392b2c85597edfd89ae1bc9975f73b1381aa0b15179cc16bcb63fd6ff8ef", + "actualBytes": 5029, + "actualSha256": "2d1b392b2c85597edfd89ae1bc9975f73b1381aa0b15179cc16bcb63fd6ff8ef", + "passed": true + }, + { + "path": "src/core/storage/state-database.mjs", + "bytes": 8565, + "sha256": "2a38f7564df44c4ee5183d850064be1d46fba7e072e2b87f73afb8e1a85a1517", + "actualBytes": 8565, + "actualSha256": "2a38f7564df44c4ee5183d850064be1d46fba7e072e2b87f73afb8e1a85a1517", + "passed": true + }, + { + "path": "src/core/tasks/file-results.mjs", + "bytes": 13375, + "sha256": "65a5b25746468e3d4b9e0576d87c269f9ed1b8b90b68f32c6ad3a5de934dfdb7", + "actualBytes": 13375, + "actualSha256": "65a5b25746468e3d4b9e0576d87c269f9ed1b8b90b68f32c6ad3a5de934dfdb7", + "passed": true + }, + { + "path": "src/core/tasks/task-checkpoint-manager.mjs", + "bytes": 13524, + "sha256": "2f50f9de2e6b8c90376028ed2814eb795633e1ea917ab944a977299220ad820f", + "actualBytes": 13524, + "actualSha256": "2f50f9de2e6b8c90376028ed2814eb795633e1ea917ab944a977299220ad820f", + "passed": true + }, + { + "path": "src/core/tasks/task-plan-manager.mjs", + "bytes": 22733, + "sha256": "0bebf720614cb45eb840cc5007b5499ef4fc5ca3934d2261a439d1df90cde3ec", + "actualBytes": 22733, + "actualSha256": "0bebf720614cb45eb840cc5007b5499ef4fc5ca3934d2261a439d1df90cde3ec", + "passed": true + }, + { + "path": "src/core/tasks/worker-manager.mjs", + "bytes": 70505, + "sha256": "f33e326680c75bb73cb6327b80c21fc6d5345133809c79a0588fcdd954cabf65", + "actualBytes": 70505, + "actualSha256": "f33e326680c75bb73cb6327b80c21fc6d5345133809c79a0588fcdd954cabf65", + "passed": true + }, + { + "path": "src/core/tools/mcp-contract.mjs", + "bytes": 8366, + "sha256": "4860792132e2d18caa075ddca8c24687b3692c005a1c6c4c81933e6dc9e0a6bc", + "actualBytes": 8366, + "actualSha256": "4860792132e2d18caa075ddca8c24687b3692c005a1c6c4c81933e6dc9e0a6bc", + "passed": true + }, + { + "path": "src/core/tools/mcp-registry.mjs", + "bytes": 26252, + "sha256": "8f52b11ba37d1c350aa279e4890a0c5b00fff3b77fc4f2211a4ea1c07bbadebc", + "actualBytes": 26252, + "actualSha256": "8f52b11ba37d1c350aa279e4890a0c5b00fff3b77fc4f2211a4ea1c07bbadebc", + "passed": true + }, + { + "path": "src/core/tools/mcp-stdio.mjs", + "bytes": 8109, + "sha256": "1c1081b9356855db5c8964ac5b9f5fb2c79fef5323ff1f933447a06f77cac447", + "actualBytes": 8109, + "actualSha256": "1c1081b9356855db5c8964ac5b9f5fb2c79fef5323ff1f933447a06f77cac447", + "passed": true + }, + { + "path": "src/core/tools/rea-adapter.mjs", + "bytes": 9010, + "sha256": "36f7d2a095fcaef4e1ca056a1f2475e0b15fe1fc48d0179589b41abadf39c6c4", + "actualBytes": 9010, + "actualSha256": "36f7d2a095fcaef4e1ca056a1f2475e0b15fe1fc48d0179589b41abadf39c6c4", + "passed": true + }, + { + "path": "src/core/tools/research-output.mjs", + "bytes": 1750, + "sha256": "b9d53487192f12b0d2b0f0922c918b5b3d88a276777cd64903395800ff07c1c0", + "actualBytes": 1750, + "actualSha256": "b9d53487192f12b0d2b0f0922c918b5b3d88a276777cd64903395800ff07c1c0", + "passed": true + }, + { + "path": "src/core/workspaces/change-sets.mjs", + "bytes": 28215, + "sha256": "868377bcc441d959794dc9a7b5daaad7b6d9b185c0237eea0e6e5265141965f1", + "actualBytes": 28215, + "actualSha256": "868377bcc441d959794dc9a7b5daaad7b6d9b185c0237eea0e6e5265141965f1", + "passed": true + }, + { + "path": "src/core/workspaces/git-workspaces.mjs", + "bytes": 37508, + "sha256": "0276d2b877acdb065717f7c93154d6999d56a9358b93e50bae7e2c7afc191806", + "actualBytes": 37508, + "actualSha256": "0276d2b877acdb065717f7c93154d6999d56a9358b93e50bae7e2c7afc191806", + "passed": true + }, + { + "path": "src/desktop/Launcher.cs", + "bytes": 8967, + "sha256": "1c8e7d7ee5c383897bec48e9aadb8051b47c09686f74bbf34e0b6b695cd01ae5", + "actualBytes": 8967, + "actualSha256": "1c8e7d7ee5c383897bec48e9aadb8051b47c09686f74bbf34e0b6b695cd01ae5", + "passed": true + }, + { + "path": "src/desktop/browsing-view.mjs", + "bytes": 16825, + "sha256": "c201696d3e781c6707c5fbdff38d30d04ffcac77eaabf8955dccd66f773d35b2", + "actualBytes": 16825, + "actualSha256": "c201696d3e781c6707c5fbdff38d30d04ffcac77eaabf8955dccd66f773d35b2", + "passed": true + }, + { + "path": "src/desktop/host-cli.mjs", + "bytes": 1894, + "sha256": "f0cd97972e558512dcdfdb262093459c385cc0cae5c97cf305539504cbc297c6", + "actualBytes": 1894, + "actualSha256": "f0cd97972e558512dcdfdb262093459c385cc0cae5c97cf305539504cbc297c6", + "passed": true + }, + { + "path": "src/desktop/install-cli.mjs", + "bytes": 2039, + "sha256": "3aea34f4bb30a421437eb192a29c4f0e2f63a2092e8c8c85f068981f82d48048", + "actualBytes": 2039, + "actualSha256": "3aea34f4bb30a421437eb192a29c4f0e2f63a2092e8c8c85f068981f82d48048", + "passed": true + }, + { + "path": "src/desktop/installer.iss", + "bytes": 6572, + "sha256": "9fbb0ad022971ee860b141ed1354885e1fa6cd68f013725e8cf316835315efb6", + "actualBytes": 6572, + "actualSha256": "9fbb0ad022971ee860b141ed1354885e1fa6cd68f013725e8cf316835315efb6", + "passed": true + }, + { + "path": "src/desktop/main.mjs", + "bytes": 6530, + "sha256": "542736cfd88cd2c429862b9c8e304f6ea4b3b7db08dbcf25edc9724acf1b9527", + "actualBytes": 6530, + "actualSha256": "542736cfd88cd2c429862b9c8e304f6ea4b3b7db08dbcf25edc9724acf1b9527", + "passed": true + }, + { + "path": "src/desktop/preload.cjs", + "bytes": 774, + "sha256": "c5855d6b17ce1e565a196fa6e99dba0f119462f08082aaa2f43407eec1e485ce", + "actualBytes": 774, + "actualSha256": "c5855d6b17ce1e565a196fa6e99dba0f119462f08082aaa2f43407eec1e485ce", + "passed": true + }, + { + "path": "src/server/app.mjs", + "bytes": 74262, + "sha256": "788723edf5cf158083ff85e3fb80b9b6848c141e18e0cc3bb495e90bc4b34b97", + "actualBytes": 74262, + "actualSha256": "788723edf5cf158083ff85e3fb80b9b6848c141e18e0cc3bb495e90bc4b34b97", + "passed": true + }, + { + "path": "src/server/companion-gateway.mjs", + "bytes": 23182, + "sha256": "f13bf1412c6f20c0d0a825c8768dfa065f8c9201eafc381f40a5f13d62372385", + "actualBytes": 23182, + "actualSha256": "f13bf1412c6f20c0d0a825c8768dfa065f8c9201eafc381f40a5f13d62372385", + "passed": true + }, + { + "path": "src/server/diagnostics.mjs", + "bytes": 13775, + "sha256": "ebda9596c976ac31480d1d89d2e0bb8a21abd9de76dce10e2f43e0e4a8324204", + "actualBytes": 13775, + "actualSha256": "ebda9596c976ac31480d1d89d2e0bb8a21abd9de76dce10e2f43e0e4a8324204", + "passed": true + }, + { + "path": "src/server/files.mjs", + "bytes": 15810, + "sha256": "6aa4591839b34fcf1c49b598b390fd204c97f0948085fcf41faab2549e4d7592", + "actualBytes": 15810, + "actualSha256": "6aa4591839b34fcf1c49b598b390fd204c97f0948085fcf41faab2549e4d7592", + "passed": true + }, + { + "path": "src/server/hot-upgrade.mjs", + "bytes": 9290, + "sha256": "991acdf74cad72a56323ac510e235731d47d74cadf7a5e7e9c8d956bd3b74d28", + "actualBytes": 9290, + "actualSha256": "991acdf74cad72a56323ac510e235731d47d74cadf7a5e7e9c8d956bd3b74d28", + "passed": true + }, + { + "path": "src/server/index.mjs", + "bytes": 3425, + "sha256": "bd5259aa89b14f2a2c510f5699857493a36ee97bd2f6af617c2fcaadddd0616a", + "actualBytes": 3425, + "actualSha256": "bd5259aa89b14f2a2c510f5699857493a36ee97bd2f6af617c2fcaadddd0616a", + "passed": true + }, + { + "path": "src/server/local-directories.mjs", + "bytes": 2578, + "sha256": "f7613c37d7b54734e0041752111e5b699f3925097e834c81a6db88b929b8ddcc", + "actualBytes": 2578, + "actualSha256": "f7613c37d7b54734e0041752111e5b699f3925097e834c81a6db88b929b8ddcc", + "passed": true + }, + { + "path": "src/server/operations.mjs", + "bytes": 8208, + "sha256": "3f0a93aca24cba2d6b347f3c01b632168e91ccff0bd4a875a8daf087249b0e10", + "actualBytes": 8208, + "actualSha256": "3f0a93aca24cba2d6b347f3c01b632168e91ccff0bd4a875a8daf087249b0e10", + "passed": true + }, + { + "path": "src/server/provider.mjs", + "bytes": 42808, + "sha256": "77e656e594da1cb0feb28e3b5dfe0999df1e583979f7ecb6d55c03f8e59193bd", + "actualBytes": 42808, + "actualSha256": "77e656e594da1cb0feb28e3b5dfe0999df1e583979f7ecb6d55c03f8e59193bd", + "passed": true + }, + { + "path": "src/server/runtime.mjs", + "bytes": 88653, + "sha256": "b2648ac7e0bb6531a90ecde7ac2e3569c22d286eb58b9216771d22fd7dca447c", + "actualBytes": 88653, + "actualSha256": "b2648ac7e0bb6531a90ecde7ac2e3569c22d286eb58b9216771d22fd7dca447c", + "passed": true + }, + { + "path": "src/server/store.mjs", + "bytes": 57645, + "sha256": "9dc016f7bd81467c44ed66198d8d4c21e5cc3a4017e700ca2f58db9933f36950", + "actualBytes": 57645, + "actualSha256": "9dc016f7bd81467c44ed66198d8d4c21e5cc3a4017e700ca2f58db9933f36950", + "passed": true + }, + { + "path": "src/shared/approval-presentation.d.mts", + "bytes": 473, + "sha256": "7e2811bcc5c6017f43bfecfebb9a3f428a76e9af1f89d8640b7093d11fb60812", + "actualBytes": 473, + "actualSha256": "7e2811bcc5c6017f43bfecfebb9a3f428a76e9af1f89d8640b7093d11fb60812", + "passed": true + }, + { + "path": "src/shared/approval-presentation.mjs", + "bytes": 1621, + "sha256": "900dfe57f10d0d2b416ee90b1cc96f40c5bc0acaf4485db794a64588cbecddf7", + "actualBytes": 1621, + "actualSha256": "900dfe57f10d0d2b416ee90b1cc96f40c5bc0acaf4485db794a64588cbecddf7", + "passed": true + }, + { + "path": "src/shared/budget-presentation.d.mts", + "bytes": 236, + "sha256": "1edeb84f55e1ec5de8c7156e37a62c048337a72b50ca645f69370b778b5fc42b", + "actualBytes": 236, + "actualSha256": "1edeb84f55e1ec5de8c7156e37a62c048337a72b50ca645f69370b778b5fc42b", + "passed": true + }, + { + "path": "src/shared/budget-presentation.mjs", + "bytes": 1131, + "sha256": "23baec4a153ba3d00a5b75820997d1f35897f4758d76ee40890d903cef5eeb8a", + "actualBytes": 1131, + "actualSha256": "23baec4a153ba3d00a5b75820997d1f35897f4758d76ee40890d903cef5eeb8a", + "passed": true + }, + { + "path": "src/shared/contracts/anthropic-messages.mjs", + "bytes": 4861, + "sha256": "c13155123d408bb4f4254355076525d9c20e7ad0dedf65eb2282cc3e36201296", + "actualBytes": 4861, + "actualSha256": "c13155123d408bb4f4254355076525d9c20e7ad0dedf65eb2282cc3e36201296", + "passed": true + }, + { + "path": "src/shared/contracts/browser.mjs", + "bytes": 4775, + "sha256": "af8f71616097dbbb08bde31bf1cc42c90708802f17ad89b4ba220351fb30f439", + "actualBytes": 4775, + "actualSha256": "af8f71616097dbbb08bde31bf1cc42c90708802f17ad89b4ba220351fb30f439", + "passed": true + }, + { + "path": "src/shared/contracts/browsing.mjs", + "bytes": 3939, + "sha256": "7ba5c878755395d6abda3d7abe5e3ea4a17b4d3a0db47eea30555e15af58e1f8", + "actualBytes": 3939, + "actualSha256": "7ba5c878755395d6abda3d7abe5e3ea4a17b4d3a0db47eea30555e15af58e1f8", + "passed": true + }, + { + "path": "src/shared/contracts/change-sets.mjs", + "bytes": 1189, + "sha256": "01586cdcffe00129c2b61e4cbf4a622b22306cd5a893620f4a7db441f978f1da", + "actualBytes": 1189, + "actualSha256": "01586cdcffe00129c2b61e4cbf4a622b22306cd5a893620f4a7db441f978f1da", + "passed": true + }, + { + "path": "src/shared/contracts/companion.mjs", + "bytes": 2732, + "sha256": "29009ed9e0a25ad3673ea18dc773d423b6a4712e26220c707e304b83359d10b8", + "actualBytes": 2732, + "actualSha256": "29009ed9e0a25ad3673ea18dc773d423b6a4712e26220c707e304b83359d10b8", + "passed": true + }, + { + "path": "src/shared/contracts/delivery-review.mjs", + "bytes": 1368, + "sha256": "1b17efdfa2549801db72eabe439907419a4d85ea07e4d010563db2d483d565f9", + "actualBytes": 1368, + "actualSha256": "1b17efdfa2549801db72eabe439907419a4d85ea07e4d010563db2d483d565f9", + "passed": true + }, + { + "path": "src/shared/contracts/desktop-bridge.mjs", + "bytes": 2176, + "sha256": "41bf5f44abe0d0a4bca2833272c31bd5c6524b6e767580d9bcaf37aec740a09b", + "actualBytes": 2176, + "actualSha256": "41bf5f44abe0d0a4bca2833272c31bd5c6524b6e767580d9bcaf37aec740a09b", + "passed": true + }, + { + "path": "src/shared/contracts/desktop-host.mjs", + "bytes": 1699, + "sha256": "10caaf16b61e8f3a553496582c7a855ecf693909900565d7c0abb1b99b4da9a9", + "actualBytes": 1699, + "actualSha256": "10caaf16b61e8f3a553496582c7a855ecf693909900565d7c0abb1b99b4da9a9", + "passed": true + }, + { + "path": "src/shared/contracts/engine-context.mjs", + "bytes": 11155, + "sha256": "05fa7cbb0cf36bdf3cfbac180b074f6263ce9370c0efdd6d5525c428cdcd13d0", + "actualBytes": 11155, + "actualSha256": "05fa7cbb0cf36bdf3cfbac180b074f6263ce9370c0efdd6d5525c428cdcd13d0", + "passed": true + }, + { + "path": "src/shared/contracts/engine-execution.mjs", + "bytes": 13324, + "sha256": "6d5a4335f0052ff02e68df89acbb5251d511f99a9c5baf200394810bcc500ee8", + "actualBytes": 13324, + "actualSha256": "6d5a4335f0052ff02e68df89acbb5251d511f99a9c5baf200394810bcc500ee8", + "passed": true + }, + { + "path": "src/shared/contracts/engines.mjs", + "bytes": 2520, + "sha256": "cd0a6378682182b8c29884e725a284a7b4f32c1355067883321de071ff113bfb", + "actualBytes": 2520, + "actualSha256": "cd0a6378682182b8c29884e725a284a7b4f32c1355067883321de071ff113bfb", + "passed": true + }, + { + "path": "src/shared/contracts/environment.mjs", + "bytes": 961, + "sha256": "ca1d8e5653a3d91ae6e8155c05e5be96346699acf13dd289d7b9ae0364c6b314", + "actualBytes": 961, + "actualSha256": "ca1d8e5653a3d91ae6e8155c05e5be96346699acf13dd289d7b9ae0364c6b314", + "passed": true + }, + { + "path": "src/shared/contracts/evaluations.mjs", + "bytes": 6341, + "sha256": "d6e9e85be7f899deb544533156af8cede8915450516696de7b337c5a0b0ceedb", + "actualBytes": 6341, + "actualSha256": "d6e9e85be7f899deb544533156af8cede8915450516696de7b337c5a0b0ceedb", + "passed": true + }, + { + "path": "src/shared/contracts/execution.mjs", + "bytes": 6229, + "sha256": "0a5966caf08740b8b28c708e7da23cc6aa3d2ab1c28a213210632f2521a52968", + "actualBytes": 6229, + "actualSha256": "0a5966caf08740b8b28c708e7da23cc6aa3d2ab1c28a213210632f2521a52968", + "passed": true + }, + { + "path": "src/shared/contracts/file-intent.mjs", + "bytes": 2264, + "sha256": "9808107b51a0d51ef987e3ab6a8b38a9cdbd4db0e9fdddd8ee0fd6d30c6a735b", + "actualBytes": 2264, + "actualSha256": "9808107b51a0d51ef987e3ab6a8b38a9cdbd4db0e9fdddd8ee0fd6d30c6a735b", + "passed": true + }, + { + "path": "src/shared/contracts/file-results.mjs", + "bytes": 3602, + "sha256": "35dbbd552de347457875e25008762236f823fa2556a83421a9aae1911682f43e", + "actualBytes": 3602, + "actualSha256": "35dbbd552de347457875e25008762236f823fa2556a83421a9aae1911682f43e", + "passed": true + }, + { + "path": "src/shared/contracts/model-capabilities.mjs", + "bytes": 2268, + "sha256": "a71775c388d1afc5dfc9057528502882361694c6d9fb541e6f55257d0ca5686a", + "actualBytes": 2268, + "actualSha256": "a71775c388d1afc5dfc9057528502882361694c6d9fb541e6f55257d0ca5686a", + "passed": true + }, + { + "path": "src/shared/contracts/model-endpoint.d.mts", + "bytes": 418, + "sha256": "97bb7db1fe30825a0a5cbad8c25ed7cb230e5fed1f928bcd40feecf284abaf08", + "actualBytes": 418, + "actualSha256": "97bb7db1fe30825a0a5cbad8c25ed7cb230e5fed1f928bcd40feecf284abaf08", + "passed": true + }, + { + "path": "src/shared/contracts/model-endpoint.mjs", + "bytes": 1473, + "sha256": "06e9e7c70de5cb3e71bcc89cb2982e3e677a3bc91e562e0c6dc1566904a1df8f", + "actualBytes": 1473, + "actualSha256": "06e9e7c70de5cb3e71bcc89cb2982e3e677a3bc91e562e0c6dc1566904a1df8f", + "passed": true + }, + { + "path": "src/shared/contracts/model-identity.d.mts", + "bytes": 518, + "sha256": "1ca61152f9583a4b1c16ffeecdad07b0f11ed3473b45c0f1b3d0b1497c601057", + "actualBytes": 518, + "actualSha256": "1ca61152f9583a4b1c16ffeecdad07b0f11ed3473b45c0f1b3d0b1497c601057", + "passed": true + }, + { + "path": "src/shared/contracts/model-identity.mjs", + "bytes": 3608, + "sha256": "24d50bef6226c548b534c4318e9d50ed1a8856f639fbe0c1df586dfe6092e2e1", + "actualBytes": 3608, + "actualSha256": "24d50bef6226c548b534c4318e9d50ed1a8856f639fbe0c1df586dfe6092e2e1", + "passed": true + }, + { + "path": "src/shared/contracts/model-request.mjs", + "bytes": 7952, + "sha256": "c4846621c0405a6d89f09a611049579b2846e3fa2c2ef589fdb1abb1599e60a2", + "actualBytes": 7952, + "actualSha256": "c4846621c0405a6d89f09a611049579b2846e3fa2c2ef589fdb1abb1599e60a2", + "passed": true + }, + { + "path": "src/shared/contracts/model-reservation.mjs", + "bytes": 6741, + "sha256": "7f3e0f21720dc19efd5c675ae65e4eeed96dffb41c42a3d460fcc9f0b6473c6c", + "actualBytes": 6741, + "actualSha256": "7f3e0f21720dc19efd5c675ae65e4eeed96dffb41c42a3d460fcc9f0b6473c6c", + "passed": true + }, + { + "path": "src/shared/contracts/native-parameters.d.mts", + "bytes": 203, + "sha256": "e7ece4faeeacc563e5143c55c4b73bc4547d9d888c39709b0fdd438a16c4511f", + "actualBytes": 203, + "actualSha256": "e7ece4faeeacc563e5143c55c4b73bc4547d9d888c39709b0fdd438a16c4511f", + "passed": true + }, + { + "path": "src/shared/contracts/native-parameters.mjs", + "bytes": 3471, + "sha256": "e0140dc27baee32d67a4ca683516af0e9a38d11d917d5c742e532938ff0beb5f", + "actualBytes": 3471, + "actualSha256": "e0140dc27baee32d67a4ca683516af0e9a38d11d917d5c742e532938ff0beb5f", + "passed": true + }, + { + "path": "src/shared/contracts/preview.mjs", + "bytes": 1059, + "sha256": "6dd95d935c8ea057b2375fb09a08953f07e20b8eafdc9eec03a0b1aee57a1923", + "actualBytes": 1059, + "actualSha256": "6dd95d935c8ea057b2375fb09a08953f07e20b8eafdc9eec03a0b1aee57a1923", + "passed": true + }, + { + "path": "src/shared/contracts/research.mjs", + "bytes": 6860, + "sha256": "eb970b52f923d7dbfd8e7da49381ce135b8a2ae9d04c0d4321958a2e93d12003", + "actualBytes": 6860, + "actualSha256": "eb970b52f923d7dbfd8e7da49381ce135b8a2ae9d04c0d4321958a2e93d12003", + "passed": true + }, + { + "path": "src/shared/contracts/task-control.mjs", + "bytes": 6803, + "sha256": "3e8770f3c802d34c6fe434f500e0e866846b314a5b1fe07227eeb45d6af064d5", + "actualBytes": 6803, + "actualSha256": "3e8770f3c802d34c6fe434f500e0e866846b314a5b1fe07227eeb45d6af064d5", + "passed": true + }, + { + "path": "src/shared/contracts/task-plan-tools.mjs", + "bytes": 3129, + "sha256": "ef22e460621292b84b96438eb9356847634feb6ff5f4086502df6c9f3b01f70f", + "actualBytes": 3129, + "actualSha256": "ef22e460621292b84b96438eb9356847634feb6ff5f4086502df6c9f3b01f70f", + "passed": true + }, + { + "path": "src/shared/contracts/task-plans.mjs", + "bytes": 7339, + "sha256": "c5dc7a8ae028afcc7fa6b55a1261700998c41e799e48101759e48b05d2317d90", + "actualBytes": 7339, + "actualSha256": "c5dc7a8ae028afcc7fa6b55a1261700998c41e799e48101759e48b05d2317d90", + "passed": true + }, + { + "path": "src/shared/contracts/workers.mjs", + "bytes": 11781, + "sha256": "c9578b0e12ca4d14dbc636177814f0946ca3cc11f534da7b0aa1289a740845b4", + "actualBytes": 11781, + "actualSha256": "c9578b0e12ca4d14dbc636177814f0946ca3cc11f534da7b0aa1289a740845b4", + "passed": true + }, + { + "path": "src/shared/contracts/workspaces.mjs", + "bytes": 4187, + "sha256": "4d1eadbc0e99f9c71484bd2f26017f8f3c3f214fa9edb5c8218732285affe505", + "actualBytes": 4187, + "actualSha256": "4d1eadbc0e99f9c71484bd2f26017f8f3c3f214fa9edb5c8218732285affe505", + "passed": true + } + ], + "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." +} diff --git a/docs/routing-audit-n-evidence/user-confirmation.json b/docs/routing-audit-n-evidence/user-confirmation.json new file mode 100644 index 00000000..4ae68df1 --- /dev/null +++ b/docs/routing-audit-n-evidence/user-confirmation.json @@ -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 +} diff --git a/docs/routing-audit-n-evidence/verify-offline.mjs b/docs/routing-audit-n-evidence/verify-offline.mjs new file mode 100644 index 00000000..77b799fb --- /dev/null +++ b/docs/routing-audit-n-evidence/verify-offline.mjs @@ -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)); diff --git a/docs/routing-audit-n-verification.json b/docs/routing-audit-n-verification.json new file mode 100644 index 00000000..4a7ffcc6 --- /dev/null +++ b/docs/routing-audit-n-verification.json @@ -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." +} diff --git a/findings.md b/findings.md index 771069eb..3664a92d 100644 --- a/findings.md +++ b/findings.md @@ -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。 diff --git a/progress.md b/progress.md index c097c320..9b48b48a 100644 --- a/progress.md +++ b/progress.md @@ -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通配参数和一处猜测文件名只读失败已改为实际目录/文件,原件不变。 diff --git a/task_plan.md b/task_plan.md index 0d2a879b..d4400e04 100644 --- a/task_plan.md +++ b/task_plan.md @@ -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 原件,不续跑旧任务。