Compare commits

...

4 Commits

Author SHA1 Message Date
Agent Workbench Dev 1a8975769b docs(qa): seal native cache and provider-state acceptance 2026-11-07 20:37:50 +08:00
Agent Workbench Dev ee97aaae73 feat(models): expose connection affinity and native-state provenance 2026-11-07 20:31:50 +08:00
Agent Workbench Dev 9e1feeebb3 feat(models): retain native cache blocks and bind cross-run provider state 2026-11-07 20:00:33 +08:00
Agent Workbench Dev 71f1805561 docs(models): pin native cache and provider-state sources 2026-11-07 19:51:54 +08:00
33 changed files with 3924 additions and 38 deletions
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench项目执行规范
M2第五批I09/I11源码与隔离验收完成:来源71f18055、核心9e1feeeb、界面ee97aaae。原生缓存块/工具元数据与状态身份绑定、会话/Task/Run/关闭保持;纯Chat混池误带首成员reasoning实际缺陷已修。最后专项16/16,首候选127/129与两改文件26/26按178后端/213测试输入SHA复用覆盖,不能称最后单轮全套全绿。最终880输入/29编译/74runtime、网页/实际Electron各8组/10图/三配色/1280及390、原metadata/cipher/存储快照/历史exact,20图SHA/8图实看、自有候选进程和记录端口监听0。5126份2008555583字节已封存,见[验收](docs/QA-M2-NATIVE-CACHE-STATE.md)与[机器记录](docs/m2-native-cache-state-2026-11-07.json);文档及既有GitAtlas普通增量推送收尾。下一I27/I28 CI,再M3实际schema2迁移增量及新处理器结果后回退,不能删除新账本或去掉逐表全等守卫。本批0真实模型/Key/正式写入,不发行/正式重启/委派或续旧工程,不作新正式health声明;默认开放/透传/持久权限及W/AD/AE/AG网络/unknown、重复读/R-W边界/Purge收益unknown保持。下方旧接续按原时点理解。
M2第四批I14/I12源码完成:来源337d1bc9、核心f95507ab、界面26472d28;新/旧版本与认证分开、Beta/头/同源路径、冻结契约及非提示指纹,实际fetch设置与原Run推导不混同。最后相关38/38、首候选143/143后端输入未变,最终871输入/29编译/74runtime、网页和实际Electron各8组/8图/三配色/1280及390,原metadata/cipher/存储快照exact,原I13/I15封存只读一致、自有进程/已知监听0。见[验收](docs/QA-M2-REQUEST-CONTRACT.md)与[计划](docs/M2-REQUEST-CONTRACT-PLAN.md)。3207份1498866416字节已封存,源码与验收04c0556c已普通增量推送至既有GitAtlas分支、远端逐SHA一致,见[回执](docs/gitatlas-m2-request-contract-push.json);完成接续最后提交再核对。下一I09/I11缓存块/亲和/状态及CI,再M3真实schema2迁移增量和新处理器结果后的回退。0真实模型/Key/正式写入,不发行/重启/委派或续旧工程,不作新正式health声明,开放默认/持久权限与W/AD/AE/AG、重复读、R/W边界、Purge收益unknown保持。下方旧进行中说明按原时点理解。
M2 I15推送完成:0cbf14a2/ba4b4491/b5aaf1f7与验收bf07e66d已普通增量推送至既有GitAtlas feat/task-agreement-1.25,远端逐SHA一致;[回执](docs/gitatlas-m2-official-registry-push.json)与完成接续最后提交再核对。5688原件/858输入/29编译保持,正式未部署/重启。下一I14实际版本/头/指纹,随后缓存块/亲和/状态及CI,M3需真实迁移增量/激活后回退;历史unknown保持。下方进行中说明按原时点理解。
@@ -1,5 +1,7 @@
# 官方优先开发路线(2026-11-06)
2026-11-07 M2第五批I09/I11已完成源码及隔离验收:来源71f18055/核心9e1feeeb/界面ee97aaae,原生缓存块/工具元数据保持、跨Run状态身份与四范围连接保持,纯Chat混池实际误带状态缺陷已修。最后16/16、首127/129加两文件26/26分开按SHA复用,最终880输入/29编译/74runtime、网页和实际Electron各8组/10图/三配色/1280及390、原存储/密文/历史exact,5126原件封存,见[验收](QA-M2-NATIVE-CACHE-STATE.md)。文档/授权普通增量推送收尾;下一I27/I28 CI,再M3实际schema2迁移增量和新处理器结果后的回退,不能删除新账本或直接移除逐表全等守卫。正式未部署/重启,无真实Key/模型,历史网络/unknown/重复读/R-W边界/Purge收益unknown不动;下方历史接续按原时点理解。
2026-11-07 M2第四批I14与I12本批指纹已完成源码337d1bc9/f95507ab/26472d28:请求版本/Beta/认证/头/路径与目录身份绑定、实际fetch参数与原Run冻结设置分别记录;原body/ordered-prefix和密文保持。最后相关38/38、首候选143/143后端输入未变,最终871输入/29编译/74runtime、两端各8组/8图/三配色通过,旧I13/I15封存只读一致,见[请求契约验收](QA-M2-REQUEST-CONTRACT.md)。3207原件已封存,源码/验收04c0556c已普通增量推送、远端逐SHA一致,见[回执](gitatlas-m2-request-contract-push.json)。完成接续最后提交再核对;下一I09/I11缓存块/跨Run亲和/原生状态和I27/I28 CI,再M3声明迁移增量与新处理器结果后回退。正式/真实Key/模型/旧实验与历史unknown不动,下方历史接续按原时点理解。
2026-11-07 M2第三批I15已完成ba4b4491/b5aaf1f7及来源0cbf14a2:26记录/13精确型号/17来源、完整目录/覆盖/原规格快照/凭据绑定保持。最终858输入/29编译、两端各6组/7图与5688原件核对,见[注册表验收](QA-M2-OFFICIAL-REGISTRY.md)。首候选62/62后端输入未变,最后UI补强另有新构建和两端证据。普通增量推送收尾中;下一先I14实际版本/供应商头/指纹,再I09/I11/I12缓存块/亲和/状态及I27/I28 CI。M2/M3与真实收益未因此完成,正式/Key/模型/历史unknown不动。
+17
View File
@@ -0,0 +1,17 @@
# M2 第五批:原生缓存块与跨 Run 状态
2026-11-07,基线 `bdfeb29c85b3231bfd7bc24b8b5f49d40a3beebf`,干净工作树。承接 I14/I12 的冻结契约/当次 fetch 数据区分,完成 I09 原生块与工具缓存注解往返、I11 可配置会话/Task亲和与供应商状态绑定;I27/I28 CI 与 M3 单独续接。
1. [complete] 固定当前官方缓存/状态来源、复用 I15 原件并核SHA;8份来源清单见 tests/fixtures/native-cache-state/SOURCE.json 与 docs/NATIVE-CACHE-STATE-SOURCES.md。保留原丢注解、跨 Run 选线和状态身份缺项观察。Mnemo新结果只读登记,不作为本地验收。
2. [complete] 保留 Messages 系统/用户/工具块及工具元数据;新增原生状态身份绑定和会话/Task/Run亲和,修复纯Chat混池仅换model造成旧状态误用,optional亲和存储失败不改变原响应。原用户设置、完整历史和未知原件保留,默认不添加缓存参数。source-5最终16/16,源码类型检查通过。
3. [complete] 自有 HTTP JSON/SSE、混池、跨 Run、手选换模、修订/停用、停止/恢复/重启与所有工具结果不重放的确定性核对;上游原错误保留。source-5为16/16;首候选127/129,两项旧亲和假设准确修正后两文件26/26。最终178后端输入与首候选一致、213测试输入中211未改,按SHA复用103原通过项,不冒称最终单轮全套全绿。
4. [complete] 复用 Orven 模型中心/原生参数/上下文,四范围保存/重载、跨Run沿用/自动重选/手选与原错通过。build-5/candidate-5为880输入/29编译/74runtime,逐SHA核对;web-ui-5与electron-ui-1各实际8组/10图/三配色/1280及390、原metadata/cipher/存储快照/原历史exact。实际Electron保持隐藏窗口原生capturePage,正常关闭后独立宿主恢复。
5. [in_progress] 来源71f18055、核心9e1feeeb已限定本地提交,UI及两旧测试的准确契约修正完成两端验收。接续最终证据清单、输入/Git/来源与自有进程核对、回顾提交和普通GitAtlas增量推送;旧封存根只读,原失败保留。
本批不委派、不读真实Key、不请求真实模型、不操作正式数据/配置/安装/重启,不续旧实验或用户工程。默认 unrestricted/passthrough/preserve 与持久 ask/auto/full 保持,不增加预算、上下文、输出、头或历史额度。工具权限以当前模式为准,不能把状态核对做成新增审批。缓存使用与供应商命中由原 usage 表示,保留 unknown;稳定前缀/亲和或相同指纹不是缓存收益证明。
W/AD/AE/AG 网络/unknown、重复读取普遍收益未证明、R/W v2真实排除边界与 Purge收益unknown保持。M3须真实 schema2迁移增量及新处理器产生结果后的回退,不能删新账本或直接移除逐表全等守卫。新证据只写 `.qa/m2-native-cache-state-2026-11-07/`。
接续保留原 source-1/source-2/source-3:首夹具错误、亲和来源断言失败和跨线状态整正文搜索失败仍待准确核对,不能把接续摘要当全绿。首次接续 mkdir 遇既有目录即停止;改为读取已有原件并使用新文件名,未覆盖证据。规划辅助只读路径/输出错误见 progress.md。
source-4纯Chat混池问题已修后source-5通过,原source-1至4保留。网页1精确标签、2宽屏缩到手机后抽屉隐藏、3误期待失效亲和仍选A、4手机抽屉挡后方工具箱的原失败/图/驱动分别保留;已按真实UI返回路径和自动选线结果修正,新增手选A一次原400验收。最后文本规范化检查0项改动,来源原尾空白保持。
+18
View File
@@ -0,0 +1,18 @@
# M2 原生缓存与状态来源
2026-11-07,沿 `bdfeb29c` 接续 I09/I11。来源清单与正文 SHA 在 [SOURCE.json](../tests/fixtures/native-cache-state/SOURCE.json)。OpenAI 两篇完整页面复用本批已取得的官方 Docs 原件,Claude/DeepSeek 六篇复用 I15 的原正文,并逐 SHA 只读核对。接续时再次检索并打开 OpenAI 当前页面;新查询不覆盖先前原件或失败记录。
| 官方来源 | 本批采用范围 |
| --- | --- |
| [OpenAI conversation state](https://developers.openai.com/api/docs/guides/conversation-state) | 手动历史保留完整 output 数组、encrypted reasoning 与 assistant phase;不把仅有 response ID 当完整本地状态 |
| [OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) | 显式 content breakpoint、缓存 key/TTL/retention 独立透传;会话持续存在或前缀相同不保证命中 |
| [Claude prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) | 系统、消息、工具和工具结果的 cache_control、各块 TTL 及原生元数据保持原位置和顺序 |
| [DeepSeek thinking](https://api-docs.deepseek.com/guides/thinking_mode) / [chat](https://api-docs.deepseek.com/api/create-chat-completion) | 同供应商范围内历史 assistant reasoning_content 完整保留;工具身份与原结果不重放 |
| [DeepSeek cache](https://api-docs.deepseek.com/guides/kv_cache) | 缓存是上游行为,用原 usage 区分读写、未报告和 unknown |
| [DeepSeek Responses](https://api-docs.deepseek.com/api/create-response.md) / [Messages](https://api-docs.deepseek.com/api/create-message.md) | 兼容接口原字段与原生状态分开,不按协议名称推断账户或供应商状态可互换 |
本地状态绑定记录实际使用的协议、请求 URL、型号、连接、凭据修订和有效请求头模板。它用于防止不透明历史在不同供应商范围误用,不认证缓存命中、模型身份或供应商兼容。普通生成参数和连接修订不等于凭据变更。旧无完整身份的状态保留原件和适用原因;常规文本与原工具调用可继续进入新请求。
新模型池默认会话保持;已有池沿原 Run 范围或关闭设置。用户可选择关闭、Run、Task、会话;手动选模和当前可用成员优先。跨 Run 亲和仅从已完成响应保存,诊断独立、未知请求不补成成功,不新增执行审批或 token 额度。
该来源核对及合成验证不能证明全球实际兼容、真实缓存收益、重复读取普遍改善或 Purge 收益。W/AD/AE/AG 的网络与 unknown、R/W v2 真实排除边界和原工程结果保持。
+2
View File
@@ -1,5 +1,7 @@
# 1.25 计划:任务要求与交付复核
M2第五批I09/I11源码71f18055/9e1feeeb/ee97aaae已完成:原生缓存块与跨Run状态身份、四范围连接保持、纯Chat混池实际状态误送修复。最后16/16,首127/129与两文件26/26按SHA分别保留,最终880输入/29编译/74runtime、网页/实际Electron各8组/10图、原metadata/cipher/snapshot/history exact,5126原件封存,见[验收](QA-M2-NATIVE-CACHE-STATE.md)。文档/授权普通增量推送收尾,下一I27/I28 CI,再M3实际schema2增量迁移及新处理器结果后回退,不能删除新账本或去掉逐表全等守卫。默认开放/透传/持久权限与W/AD/AE/AG、重复读/R-W边界/Purge收益unknown保持,正式未写入/重启。下方旧接续按原时点理解。
M2第三批I15源码ba4b4491/b5aaf1f7与来源0cbf14a2完成:26记录/13精确型号/17来源,最终858输入/29编译、网页与实际Electron各6组/7图、原metadata/密文/存储快照exact,5688原件封存,见[注册表验收](QA-M2-OFFICIAL-REGISTRY.md)。首候选62/62的未变后端范围和原失败分开记录,文档/授权普通增量推送收尾中。下一I14版本/头/指纹与缓存块/亲和/状态、CI,M2全阶段及M3实际迁移/回退未完成。本批0真实模型/Key/正式写入,未部署/重启或新health查询,W/AD/AE/AG异常/unknown/重复读取与Purge收益unknown保持;下方旧当前按历史时点。
当前M2第二批I13源码da2e6313完成完整请求账本与逐请求增量存储,原metadata/初始记录/unknown不改。最终build-4独立39/39、网页与实际Electron各5组/7图/23页通过;830输入/29编译与candidate-app-5一致,4328原件只读验封通过,见[验收](QA-M2-REQUEST-LEDGER.md)和[机器记录](m2-request-ledger-2026-11-07.json)。相关102/102发生在最后公开数据库版本修正前,不能混称最后一轮;首失败完整保持。文档与授权GitAtlas普通增量推送收尾中。下一I15官方注册表和I09/I11/I12/I14缓存块/状态/指纹/版本、I27/I28 CI,M3统一发行须实际核验schema2安装增量及新处理器回退,不去掉数据保持守卫。本批未正式部署/重启或新health复查,历史真实异常/重复读取/Purge收益unknown保持;下方旧当前按历史时点理解。
+50
View File
@@ -0,0 +1,50 @@
# M2 原生缓存块与跨 Run 状态:验收及回顾
2026-11-07,承接 [本批计划](M2-NATIVE-CACHE-STATE-PLAN.md) 与 [官方优先路线](DEVELOPMENT-ROADMAP-OFFICIAL-FIRST.md)。来源 `71f18055`、核心 `9e1feeeb`、界面 `ee97aaae`,分支 `feat/task-agreement-1.25`。本批完成 I09/I11 源码和隔离验收;I27/I28 CI、M3 发行、真实供应商与收益仍分别待验。
原生缓存注解和供应商助手状态能按原协议保持,用户可选择会话、任务、运行或关闭连接保持。旧历史与未知状态仍完整保存;连接、型号、凭据或请求范围变化后,用普通文本及原工具调用构造当前请求,保留上游原错误。连接保持、同指纹或前缀稳定不证明上游缓存命中。
## 实际改动
- Messages 系统、用户、工具和工具结果保持原生块顺序、缓存注解、独立 TTL 与元数据;Responses 保持完整 output、encrypted reasoning、phase、工具元数据和用户显式缓存参数。默认不添加缓存参数,来源见 [官方原件说明](NATIVE-CACHE-STATE-SOURCES.md)。
- 新 schema2 状态绑定实际协议、请求 URL、精确型号、连接、凭据修订和请求头模板。不能解释或不适用的原状态保留原件、原因与 SHA;继续发送普通文本、原工具调用和结果,不执行历史工具。
- 修复纯 Chat 混池的实际缺陷:原实现只构造首成员正文,换线只改 model,导致首成员 reasoning_content 进入后备连接。存在状态时逐成员投影,同型号但不同凭据也分别核对。
- 新模型池默认会话保持;用户可保存 task/run/none,原池的 run/关闭设置不补写新默认。跨 Run 仅记录完成响应的连接,诊断独立、手选优先;可选亲和存储失败不把成功响应变成失败或重放请求。
- 模型中心保存范围,账本显示本次连接状态及沿用/重选依据,上下文逐候选连接显示状态。候选连接不重复相加同一原状态;旧无元数据的 unknown 记录不补造身份或用量。复用 Orven 三配色和现有 React 流程。
## 验证
| 范围 | 原证据与结果 | 实际证明 |
| --- | --- | --- |
| 最后核心专项 | `source-5.log`,16/16;类型检查通过 | Messages/Responses JSON/SSE 原生块、混池状态、停止/同任务恢复、重启、unknown 与可选存储故障 |
| 首独立候选 | `candidate-backend-1`,127/129 | 11 相关文件;两项旧亲和假设失败原样保留 |
| 准确修正后两文件 | `candidate-backend-2`,26/26 | 跨 Run 权重测试显式选择 run;关闭保持不暗存连接,重新启用后先选择再沿用 |
| 最终输入/编译 | `build-5` → `candidate-app-5`,880 输入/29 编译/74 runtime | 300 产品源码、178 后端输入、213 测试输入及全部编译/复制逐 SHA 相符 |
| 最终网页 | `web-ui-5`,8 组/10 图,1280/390 | 真实保存重载、自动重选、手选、原 400、账本/上下文及宿主恢复 |
| 实际桌面 | `electron-ui-1`,8 组/10 图,1280/390 | Electron 原生隐藏 capturePage、正常关闭后独立宿主重启及原存储恢复 |
最终 178 后端输入与首候选相同,213 测试输入中 211 未改,两改文件与 26/26 候选相同。因此复用 103 个原通过项并加两文件 26 项,覆盖 129 项;**没有把首轮失败改成全绿,也不宣称最终完整单轮全套运行**。源码与编译身份见 `input-identity-1.json`、`source-git-final-proof.json`,22 个变更冻结输入与提交原字节相符;8 份官方原件与 SOURCE 清单的 SHA/Git 原字节核对通过。
最终两端各 5 次自有 HTTP POST:3 成功、2 原 400,另保留 1 条原 unknown,最终各 6 条账本。所有原 metadata、DPAPI 密文、存储模型快照和原历史 exact;合成 Claude 凭据与原生设置在独立宿主重启后恢复,实际只执行 1 次 list_files,未重放。以上 10 次是最终两端请求数,不代替本阶段全部合成请求总数。
三配色实际操作与截图通过,页面错误/外部页面请求均 0,没有文档横向溢出。20 张最终图逐 SHA 核对,8 张实际打开复看;中文、长地址/状态 SHA、保存与原错误可读,被测正文与提示对比度至少 5.46。原横向标签滚动与文档溢出分别核对。
## 原失败与回顾
1. source-1 的错误夹具 API、source-2 亲和来源断言、source-3 整正文查找及 source-4 14/15 保留。收窄 source-3 断言后 source-4 确认纯 Chat 混池实际缺陷,修复后 source-5 16/16;不能把产品缺陷全归为测试问题。
2. 首候选两失败是旧测试假设:新池默认会话保持不应按三 Run 轮询;关闭保持不应暗存连接供以后启用。测试按其真实目的显式选择 run,并核对关闭不暗存/重新启用首次选择/后续沿用,保留原失败。
3. web-ui-1 精确标签匹配失败,实看下拉存在后补 aria-label;web-ui-2 宽屏打开检视再缩至手机触发既有隐藏行为,改为先设窄屏再打开入口。
4. web-ui-3 已按失效亲和正确选 B,驱动误期待 A 的修改头;按原 requests 核对自动重选,并新增真实 UI 手选 A 的原头/原错检查。web-ui-4 在手机抽屉打开时点击后方工具箱,被可见检视区拦住;先 Escape 返回后继续,不强行点击后方控件。
5. 所有轮次的驱动输入、日志、图和原请求保留。两次错误文档锚点使 patch 整体未应用、只读路径/glob 与输出截断均记录为开发操作错误;文本规范化末轮检查为 0 项。官方原文 6 处尾空白保持原字节,没有修剪来源。
`final-review.json`、`final-ui-proof.json`、`prior-seals-1.json`、`owned-processes-final.json` 保存回顾、结果与清理依据。I10/I13/I15/I14 四个旧根共 16171 原件及原 MANIFEST SHA 只读复核一致,构建依赖 junction 不递归。自有候选 Node/Electron 进程和记录中的非正式端口监听均 0,未查询正式 4318。
## 封存与后续
新根 `.qa/m2-native-cache-state-2026-11-07/` 已封存 5126 份、2008555583 字节。MANIFEST SHA256 `c887364e54fe3f68e5f432155db87517fb8413966f5786156bedceddadbf2217`;五个构建依赖 junction 只登记、不递归。封存后本根只读,推送和后续回执写独立新根。
完整机器记录:[m2-native-cache-state-2026-11-07.json](m2-native-cache-state-2026-11-07.json)。来源/核心/界面已本地分阶段提交,验收记录及普通 GitAtlas 增量推送接续完成;不用 force。
本批只有源码和隔离验收,0 真实模型/真实 Key 读取/正式写入,不委派、不续旧实验或用户项目、不发行/安装/重启正式服务。正式仅沿 F 的 1.25.12/PID71628 历史记录,不作新的健康声明。默认 unrestricted/passthrough/preserve 与持久 ask/auto/full 保持。
W/AD/AE/AG 网络/unknown、重复读取普遍改善未证明、R/W v2 真实排除边界未触达、Purge 收益 unknown 均保留。下一 I27/I28 CI,然后 M3 统一独立源码/程序发行,必须核对实际 schema2 迁移增量及新处理器产生结果后的回退;不能删除新账本或直接移除逐表全等守卫。之后另冻 M4 新真实供应商与工程基线,再按可比结果开展收益验证。
+2
View File
@@ -1,5 +1,7 @@
# Tianshu 研究后的 Agent Workbench 采用计划
M2 I09/I11原生缓存块/状态与四范围连接保持已完成源码71f18055/9e1feeeb/ee97aaae及两端各8组/10图隔离验收,原存储/密文/历史exact,见[验收](QA-M2-NATIVE-CACHE-STATE.md)。5126原件封存,首失败与16专项/两文件26项按SHA分别保留;文档/普通GitAtlas增量推送收尾。下一I27/I28 CI及M3实际schema2增量/新处理器结果后回退,后续新真实供应商/工程与收益另冻样本。原A–F机制及真实AD/AE成功、W/AG网络/unknown、重复读/R-W边界和Purge收益unknown均保持,正式本批未写入/重启。下方旧当前按原时点理解。
M2第三批I15来源/纯注册表及现有Orven来源/冲突/推理/兼容覆盖已完成,源码ba4b4491/b5aaf1f7;最终858输入/29编译、两端各6组/7图及原metadata/cipher/存储快照exact,5688原件封存,见[注册表验收](QA-M2-OFFICIAL-REGISTRY.md)。首候选62/62只证明未变后端,原失败保持;文档/授权增量推送收尾中。下一I14版本/头/指纹、I09/I11/I12缓存块/亲和/状态与CI;M3真实迁移增量/新处理器回退待验。本批不部署/重启或触真实Key/模型/正式数据,不续旧实验,历史网络/unknown/重复读取/Purge收益unknown保持。下方按原时点理解。
当前M2第二批I13源码da2e6313完成完整请求账本与逐请求增量存储,原metadata/初始记录/unknown不改。最终build-4独立39/39、网页与实际Electron各5组/7图/23页通过;830输入/29编译与candidate-app-5一致,4328原件只读验封通过,见[验收](QA-M2-REQUEST-LEDGER.md)和[机器记录](m2-request-ledger-2026-11-07.json)。相关102/102发生在最后公开数据库版本修正前,不能混称最后一轮;首失败完整保持。文档与授权GitAtlas普通增量推送收尾中。下一I15官方注册表和I09/I11/I12/I14缓存块/状态/指纹/版本、I27/I28 CI,M3统一发行须实际核验schema2安装增量及新处理器回退,不去掉数据保持守卫。本批未正式部署/重启或新health复查,历史真实异常/重复读取/Purge收益unknown保持;下方旧当前按历史时点理解。
+980
View File
@@ -0,0 +1,980 @@
{
"schemaVersion": 1,
"checkedAt": "2026-11-07T12:35:16.944Z",
"milestone": "M2 I09/I11 source acceptance",
"baseline": "bdfeb29c85b3231bfd7bc24b8b5f49d40a3beebf",
"sourceCommits": {
"sources": "71f1805561e6082011ed4f0c70bb38f4546413c5",
"core": "9e1feeebb3eca5c82bfa9efb4f32e68a73628df4",
"ui": "ee97aaae7389e0aff7f89eced8d06ecce7d4f982"
},
"productVersion": "1.25.12",
"node": {
"executable": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"version": "v24.22.1"
},
"sourceAcceptanceComplete": true,
"sourceReview": {
"schemaVersion": 1,
"baseline": "bdfeb29c85b3231bfd7bc24b8b5f49d40a3beebf",
"sources": [
{
"id": "openai-conversation-state",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/conversation-state",
"checkedAt": "2026-11-07",
"file": "sources/openai-conversation-state.md",
"sha256": "8a62162c2ef6ff7e94dfdad5ba06f417f5a6c00ea6521e6466d462ff2fcd9b96",
"bytes": 24788,
"captureSha256": "df7776f8ac54a84b55cbc0d42bc2b80192428921d96b2e272d21754e2f3d5f8b",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true
},
{
"id": "openai-prompt-caching",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/prompt-caching",
"checkedAt": "2026-11-07",
"file": "sources/openai-prompt-caching.md",
"sha256": "01e57dacc2e5c0fb881b2d1909649983e9e327a5d6c17a98bb1183ee00e9d334",
"bytes": 56425,
"captureSha256": "ed312ad7e34d4de7f5861317481ae82b1bc3b9a1ae78d525c916a0d94231d522",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true
},
{
"id": "claude-build-with-claude__prompt-caching",
"provider": "anthropic",
"url": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
"checkedAt": "2026-11-06",
"sha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"file": "../official-model-registry/sources/claude-build-with-claude-prompt-caching.md",
"originalSha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"representation": "extracted-official-markdown",
"scope": "complete-captured-source",
"bytes": 164465,
"reusedReadOnly": true
},
{
"id": "deepseek-create",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-chat-completion",
"checkedAt": "2026-11-06",
"sha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"file": "../official-model-registry/sources/deepseek-create.body",
"originalSha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 129498,
"reusedReadOnly": true
},
{
"id": "deepseek-thinking",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/thinking_mode",
"checkedAt": "2026-11-06",
"sha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"file": "../official-model-registry/sources/deepseek-thinking.body",
"originalSha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 117778,
"reusedReadOnly": true
},
{
"id": "deepseek-cache",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/kv_cache",
"checkedAt": "2026-11-06",
"sha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"file": "../official-model-registry/sources/deepseek-cache.body",
"originalSha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 35850,
"reusedReadOnly": true
},
{
"id": "deepseek-response",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-response.md",
"checkedAt": "2026-11-07",
"sha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"file": "../official-model-registry/sources/deepseek-response.md",
"originalSha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 33870,
"reusedReadOnly": true
},
{
"id": "deepseek-message",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-message.md",
"checkedAt": "2026-11-07",
"sha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"file": "../official-model-registry/sources/deepseek-message.md",
"originalSha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 51134,
"reusedReadOnly": true
}
],
"newRealModelRequests": 0,
"previousEvidenceRootsWritten": 0,
"scope": "request-block-fidelity-provider-state-and-affinity-contracts-not-live-cache-benefit",
"retainedEarlierRounds": [
"source-1",
"source-2",
"source-3"
],
"sourceReview": [
"Messages cache_control and TTL stay on their original system/user/tool blocks.",
"OpenAI explicit cache breakpoints and independent retention controls are passed only when supplied.",
"Responses complete output items, encrypted reasoning and phase must survive applicable manual history.",
"DeepSeek assistant reasoning_content remains with every applicable historical assistant turn.",
"Affinity and scope fingerprints are local continuity observations, never supplier cache-hit evidence."
]
},
"inputIdentity": {
"schemaVersion": 1,
"checkedAt": "2026-11-07T12:24:22.125Z",
"finalBuild": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\build-5",
"app": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\candidate-app-5",
"inputFiles": 880,
"compiledFiles": 29,
"runtimeFiles": 74,
"inputsExact": true,
"compiledCopiesExact": true,
"runtimeCopiesExact": true,
"productFiles": 300,
"productMatchesLatestBackendCandidate": true,
"backendFiles": 178,
"backendMatchesFirstCandidate": true,
"testInputs": 213,
"unchangedTestInputs": 211,
"correctedTestFiles": [
"tests/model-center.test.mjs",
"tests/model-routing-permission.test.mjs"
],
"coverage": {
"firstCandidate": {
"build": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\build-1",
"app": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\candidate-app-1",
"node": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"files": [
"tests/native-cache-state.test.mjs",
"tests/model-protocols.test.mjs",
"tests/model-stream.test.mjs",
"tests/model-parameter-fidelity.test.mjs",
"tests/model-request-contract.test.mjs",
"tests/model-center.test.mjs",
"tests/model-routing-capabilities.test.mjs",
"tests/model-routing-permission.test.mjs",
"tests/task-context.test.mjs",
"tests/model-identity.test.mjs",
"tests/model-capacity.test.mjs"
],
"startedAt": "2026-11-07T12:06:32.105Z",
"finishedAt": "2026-11-07T12:09:47.462Z",
"durationMs": 195356,
"code": 1,
"signal": null,
"totals": {
"tests": 129,
"pass": 127,
"fail": 2,
"cancelled": 0,
"skipped": 0,
"todo": 0,
"duration_ms": 195312.8855
},
"success": false
},
"correctedFiles": {
"build": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\build-3",
"app": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\candidate-app-3",
"node": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"files": [
"tests/model-center.test.mjs",
"tests/model-routing-permission.test.mjs"
],
"startedAt": "2026-11-07T12:17:59.645Z",
"finishedAt": "2026-11-07T12:18:49.887Z",
"durationMs": 50242,
"code": 0,
"signal": null,
"totals": {
"tests": 26,
"pass": 26,
"fail": 0,
"cancelled": 0,
"skipped": 0,
"todo": 0,
"duration_ms": 50205.9558
},
"success": true
},
"unchangedPassedTestsReused": 103,
"compositeCoveredTests": 129,
"singleFinalFullSuiteClaim": false
},
"sourceManifestSha256": "ced3703c4afb174c5b939ffb3dd8572f22ff8e5f3fb8489f627f45880315b799",
"officialSources": [
{
"id": "openai-conversation-state",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/conversation-state",
"checkedAt": "2026-11-07",
"file": "sources/openai-conversation-state.md",
"sha256": "8a62162c2ef6ff7e94dfdad5ba06f417f5a6c00ea6521e6466d462ff2fcd9b96",
"bytes": 24788,
"captureSha256": "df7776f8ac54a84b55cbc0d42bc2b80192428921d96b2e272d21754e2f3d5f8b",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/native-cache-state/sources/openai-conversation-state.md",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "openai-prompt-caching",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/prompt-caching",
"checkedAt": "2026-11-07",
"file": "sources/openai-prompt-caching.md",
"sha256": "01e57dacc2e5c0fb881b2d1909649983e9e327a5d6c17a98bb1183ee00e9d334",
"bytes": 56425,
"captureSha256": "ed312ad7e34d4de7f5861317481ae82b1bc3b9a1ae78d525c916a0d94231d522",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/native-cache-state/sources/openai-prompt-caching.md",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "claude-build-with-claude__prompt-caching",
"provider": "anthropic",
"url": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
"checkedAt": "2026-11-06",
"sha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"file": "../official-model-registry/sources/claude-build-with-claude-prompt-caching.md",
"originalSha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"representation": "extracted-official-markdown",
"scope": "complete-captured-source",
"bytes": 164465,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/claude-build-with-claude-prompt-caching.md",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "deepseek-create",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-chat-completion",
"checkedAt": "2026-11-06",
"sha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"file": "../official-model-registry/sources/deepseek-create.body",
"originalSha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 129498,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/deepseek-create.body",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "deepseek-thinking",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/thinking_mode",
"checkedAt": "2026-11-06",
"sha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"file": "../official-model-registry/sources/deepseek-thinking.body",
"originalSha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 117778,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/deepseek-thinking.body",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "deepseek-cache",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/kv_cache",
"checkedAt": "2026-11-06",
"sha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"file": "../official-model-registry/sources/deepseek-cache.body",
"originalSha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 35850,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/deepseek-cache.body",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "deepseek-response",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-response.md",
"checkedAt": "2026-11-07",
"sha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"file": "../official-model-registry/sources/deepseek-response.md",
"originalSha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 33870,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/deepseek-response.md",
"bytesExact": true,
"committedBytesExact": true
},
{
"id": "deepseek-message",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-message.md",
"checkedAt": "2026-11-07",
"sha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"file": "../official-model-registry/sources/deepseek-message.md",
"originalSha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 51134,
"reusedReadOnly": true,
"repositoryPath": "tests/fixtures/official-model-registry/sources/deepseek-message.md",
"bytesExact": true,
"committedBytesExact": true
}
],
"realModelRequests": 0,
"productionWrites": 0
},
"committedInputs": {
"checkedAt": "2026-11-07T12:32:35.873Z",
"base": "bdfeb29c85b3231bfd7bc24b8b5f49d40a3beebf",
"head": "ee97aaae7389e0aff7f89eced8d06ecce7d4f982",
"sourceCommits": [
"71f1805561e6082011ed4f0c70bb38f4546413c5",
"9e1feeebb3eca5c82bfa9efb4f32e68a73628df4",
"ee97aaae7389e0aff7f89eced8d06ecce7d4f982"
],
"rows": [
{
"path": "scripts/verify-native-cache-state-ui.mjs",
"bytes": 26680,
"sha256": "5a40f1a284174e2d7e3394441e6f091d23fc75eb5c495fcd5353d54b9624596d",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelCenter.css",
"bytes": 18118,
"sha256": "8e10c42d67393805ed2a3b64fa10303381d90d9e08eba8f6c2c0d5074a478fc1",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelCenter.tsx",
"bytes": 50355,
"sha256": "7f01e7e59b50a009d6a32dfdb573e6a83637020649a4b4921a017afbe75c150e",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelProviderStateDetails.css",
"bytes": 1404,
"sha256": "1c1f5c2c124b004b68d20affd4c9bad9594d0bc00ab63a0e569b922f49ce1417",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelProviderStateDetails.tsx",
"bytes": 3118,
"sha256": "4172ab798b7afe9dbb2ecb50c6eb0e399b8fe9c7a759c3f78f7d0bbb2ae8e1f8",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelRequestLedger.tsx",
"bytes": 11836,
"sha256": "e35dab71c350b758e2c0878f439665190bce6ff422ad91b395f89171e65bc626",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/ModelRoutingDetails.tsx",
"bytes": 4801,
"sha256": "a3b93157e305954076fa78e62a285a01eb58a307a8c6cf27a2338e89a653e338",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/RequestContextPanel.tsx",
"bytes": 13414,
"sha256": "b2c6152198eba74aa1c4d0cbfb29d9ca354b71bab2cf34309b2929beb2723e1e",
"committedWorkingFrozenExact": true
},
{
"path": "src/client/types.ts",
"bytes": 49501,
"sha256": "b45fc5851ae0d8620f503cb00b338cbde9dc76c8e9d2b3b3a374bebb1c10e95e",
"committedWorkingFrozenExact": true
},
{
"path": "src/core/context/request-plan.mjs",
"bytes": 56816,
"sha256": "3f56d3cc7c0757c62133a086f6b2743398a16be4cf87ecff1bce472fbadab6e1",
"committedWorkingFrozenExact": true
},
{
"path": "src/core/models/model-affinity.mjs",
"bytes": 3384,
"sha256": "fd642ecfb4c8a2e085812a1a03f5fc63784103758d4482b842555e2dada7a717",
"committedWorkingFrozenExact": true
},
{
"path": "src/core/models/model-hub.mjs",
"bytes": 47089,
"sha256": "e9c8fdc19e1076ef993c23ddf3d101c2a1a9a3bc2824c1733e6d0785a38f11cc",
"committedWorkingFrozenExact": true
},
{
"path": "src/core/models/protocols.mjs",
"bytes": 12242,
"sha256": "2f071a2e0c8308d55fde1913ee4980b6a181f935cd4836951a196af7ab165ce2",
"committedWorkingFrozenExact": true
},
{
"path": "src/shared/contracts/anthropic-messages.mjs",
"bytes": 6732,
"sha256": "7e245ba13e98fef31f5aef5f430e7b9691c46ca4c91ad1c90c1d4864f3a1afa9",
"committedWorkingFrozenExact": true
},
{
"path": "src/shared/contracts/model-provider-state.mjs",
"bytes": 3660,
"sha256": "8de752e559e32cb6cab6820a54001affde3996c07fb9e1636a2a1a189012c471",
"committedWorkingFrozenExact": true
},
{
"path": "src/shared/contracts/model-request.mjs",
"bytes": 9247,
"sha256": "b0a2b6cdb7939785eee61fb188e536a0886b8281ae9e9e403dc990ec12c2f0c8",
"committedWorkingFrozenExact": true
},
{
"path": "tests/fixtures/native-cache-state/SOURCE.json",
"bytes": 4883,
"sha256": "ced3703c4afb174c5b939ffb3dd8572f22ff8e5f3fb8489f627f45880315b799",
"committedWorkingFrozenExact": true
},
{
"path": "tests/fixtures/native-cache-state/sources/openai-conversation-state.md",
"bytes": 24788,
"sha256": "8a62162c2ef6ff7e94dfdad5ba06f417f5a6c00ea6521e6466d462ff2fcd9b96",
"committedWorkingFrozenExact": true
},
{
"path": "tests/fixtures/native-cache-state/sources/openai-prompt-caching.md",
"bytes": 56425,
"sha256": "01e57dacc2e5c0fb881b2d1909649983e9e327a5d6c17a98bb1183ee00e9d334",
"committedWorkingFrozenExact": true
},
{
"path": "tests/model-center.test.mjs",
"bytes": 16904,
"sha256": "c3aa558bdc79a9dc4181c3df85a598c94c3345081a12b7cca0a638cc9bb43af9",
"committedWorkingFrozenExact": true
},
{
"path": "tests/model-routing-permission.test.mjs",
"bytes": 21169,
"sha256": "b9339274c946a33e60928c9aa90fce2c894e32b5dd176ea982da0b355a735fde",
"committedWorkingFrozenExact": true
},
{
"path": "tests/native-cache-state.test.mjs",
"bytes": 29644,
"sha256": "ce063484e154f072aa024dd20a49fb0c9ea5846ed8b78f45baa12fb40e93567c",
"committedWorkingFrozenExact": true
}
],
"allowedChangedInputs": true,
"byteExact": true,
"productWorktreeClean": true
},
"finalUI": {
"checkedAt": "2026-11-07T12:32:35.904Z",
"ends": [
{
"stage": "web-ui-5",
"resultFile": "web-ui-5/web-d6b3ea8a-032b-4eef-a718-0efd492e3803/result.json",
"success": true,
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\candidate-app-5",
"actualElectron": false,
"hostUrl": "http://127.0.0.1:51514",
"checks": [
"Existing pools retain their original Run/disabled scope without saving new defaults or issuing model requests",
"All four pool scopes save through the real form and survive reload; new pools start with session affinity and explicit selection persists",
"The request ledger shows completed-response affinity and applicable native states separately from the retained original unknown state and cache usage",
"The actual task inspector exposes the frozen state projection and upstream-owned context limits at 390px",
"Changed provider scope reselects the next eligible pool member, retains old states and one original upstream 400, and fabricates no old metadata",
"Manual model selection takes precedence, transmits its changed header and preserves the original 400 once without applying old opaque history or replaying tools",
"State details and scope settings remain readable and usable in the three existing palettes without narrow-screen document overflow",
"Candidate host restart retains saved scope, original pools, native cache settings, original metadata/cipher/snapshot and history; no tool or request is replayed"
],
"screenshots": [
{
"file": "existing-pools-1280.png",
"sha256": "76421e822001fcd91efc5ba380723b8aa928a4ead63a2ae90f88ea68d2b68445",
"method": "playwright-page"
},
{
"file": "new-session-pool-1280.png",
"sha256": "7026f014adc9301bfc94f76d36d891b1d64528accd7f39a8035168592efbb80d",
"method": "playwright-page"
},
{
"file": "task-pool-390.png",
"sha256": "80c91f796599e7db989792a8ea93172b366f33973d1e46f2a2b827eeded643f7",
"method": "playwright-page"
},
{
"file": "continued-history-1280.png",
"sha256": "36a122de9da3a7dea868cde6e20198f127c2044addd89cb18b946e4a517f6333",
"method": "playwright-page"
},
{
"file": "context-state-390.png",
"sha256": "9212ea44c965134340d596528511ce4057131ccbf7524b3446fa852daf5097ec",
"method": "playwright-page"
},
{
"file": "changed-state-original-error-390.png",
"sha256": "df74718897986f6f911ad0b4620048e97e48ca85650cbf4f525edb91b278f6a9",
"method": "playwright-page"
},
{
"file": "manual-selection-original-error-390.png",
"sha256": "664827ca950d238a6512056d903c6f0b3b1a0ef61b39edc63fa70aa0fe69c61c",
"method": "playwright-page"
},
{
"file": "state-green-390.png",
"sha256": "6c682a50caf511a41d2468ad955b8b91c38d34f1ed7a0d40419fe12d11f1d930",
"method": "playwright-page"
},
{
"file": "state-blue-390.png",
"sha256": "d93ee1edecff973a47c059a1ae8a70f8b6762e426d2bc1add72149e874790570",
"method": "playwright-page"
},
{
"file": "state-purple-390.png",
"sha256": "49c700c76dc3164c2e97738e53e6958ed14f1c17713c0ac215474b700dee9794",
"method": "playwright-page"
}
],
"contrast": [
{
"label": "green summary",
"color": "rgb(40, 56, 47)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.375218151996188
},
{
"label": "green note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
},
{
"label": "blue summary",
"color": "rgb(36, 51, 75)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.7261609258878
},
{
"label": "blue note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
},
{
"label": "purple summary",
"color": "rgb(55, 51, 63)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.296868538533582
},
{
"label": "purple note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
}
],
"errors": [],
"externalBlocked": [],
"syntheticRequests": 5,
"originalUnknownAttempts": 1,
"originalMetadataExact": true,
"originalCipherExact": true,
"originalSnapshotExact": true,
"originalHistoryExact": true,
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"viewportWidths": [
1280,
390
]
},
{
"stage": "electron-ui-1",
"resultFile": "electron-ui-1/electron-8288962e-dccf-4b68-af88-c1ab414a6e0d/result.json",
"success": true,
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\m2-native-cache-state-2026-11-07\\candidate-app-5",
"actualElectron": true,
"hostUrl": "http://127.0.0.1:49470",
"checks": [
"Existing pools retain their original Run/disabled scope without saving new defaults or issuing model requests",
"All four pool scopes save through the real form and survive reload; new pools start with session affinity and explicit selection persists",
"The request ledger shows completed-response affinity and applicable native states separately from the retained original unknown state and cache usage",
"The actual task inspector exposes the frozen state projection and upstream-owned context limits at 390px",
"Changed provider scope reselects the next eligible pool member, retains old states and one original upstream 400, and fabricates no old metadata",
"Manual model selection takes precedence, transmits its changed header and preserves the original 400 once without applying old opaque history or replaying tools",
"State details and scope settings remain readable and usable in the three existing palettes without narrow-screen document overflow",
"Candidate host restart retains saved scope, original pools, native cache settings, original metadata/cipher/snapshot and history; no tool or request is replayed"
],
"screenshots": [
{
"file": "existing-pools-1280.png",
"sha256": "28cf8b907206581c360332aa4b20c6e7b035a985a1d2ac6b9ee67e8c0871bb19",
"method": "electron-native-stay-hidden",
"size": {
"width": 1280,
"height": 960
}
},
{
"file": "new-session-pool-1280.png",
"sha256": "c0db064b9079b100149d71d62e63b41a30a025aeb0551f593531224c2ee08e71",
"method": "electron-native-stay-hidden",
"size": {
"width": 1280,
"height": 960
}
},
{
"file": "task-pool-390.png",
"sha256": "dc80d6680a3c95e1c3008dc555e77250cb69475e7ac7c6f5af604c9f474409a5",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "continued-history-1280.png",
"sha256": "ac66c9a0f476b46ac10302c310cf1e1328839d7408033297a1ef64a79aefe820",
"method": "electron-native-stay-hidden",
"size": {
"width": 1280,
"height": 960
}
},
{
"file": "context-state-390.png",
"sha256": "8a59a8897f23201cc93ef633ad4cdfd7febd6aeb1d02723be1fcd26bf21995f8",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "changed-state-original-error-390.png",
"sha256": "a74278d90550e334bcf34492bf9887268a936a36c0a3e36b05366e499e33a52a",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "manual-selection-original-error-390.png",
"sha256": "faf88e5559ba552d749fd8df559eb7f6ae45a73482b426a68d5133153c96367f",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "state-green-390.png",
"sha256": "beeb74a2e0aa01b5751523addf4ee9d98361b8e540885f4a5877479b540fd702",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "state-blue-390.png",
"sha256": "b5fef93757654577f56bfbd058192d9d3e94f506ff605aeecf9501669f2d88e0",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
},
{
"file": "state-purple-390.png",
"sha256": "fa9f551ad43bd5e8f38f8fb3eaf4a51c28a5af04b988c48ff455daa1024d8a0b",
"method": "electron-native-stay-hidden",
"size": {
"width": 390,
"height": 844
}
}
],
"contrast": [
{
"label": "green summary",
"color": "rgb(40, 56, 47)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.375218151996188
},
{
"label": "green note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
},
{
"label": "blue summary",
"color": "rgb(36, 51, 75)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.7261609258878
},
{
"label": "blue note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
},
{
"label": "purple summary",
"color": "rgb(55, 51, 63)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 12.296868538533582
},
{
"label": "purple note",
"color": "rgb(85, 107, 135)",
"background": "rgb(255, 255, 255)",
"fontSize": "12px",
"ratio": 5.469902501657171
}
],
"errors": [],
"externalBlocked": [],
"syntheticRequests": 5,
"originalUnknownAttempts": 1,
"originalMetadataExact": true,
"originalCipherExact": true,
"originalSnapshotExact": true,
"originalHistoryExact": true,
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"viewportWidths": [
1280,
390
]
}
],
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"totalFinalEndToEndRequests": 10,
"allEndToEndRequestsNotWholeStageTotal": true,
"success": true
},
"review": {
"schemaVersion": 1,
"milestone": "M2 I09/I11 native cache blocks and cross-Run provider state",
"sourceCommits": {
"sources": "71f1805561e6082011ed4f0c70bb38f4546413c5",
"core": "9e1feeebb3eca5c82bfa9efb4f32e68a73628df4",
"ui": "ee97aaae7389e0aff7f89eced8d06ecce7d4f982"
},
"implementationReview": [
"Messages system/user/tool/tool_result block order, cache_control, independent TTLs and native extensions retain their original positions.",
"Responses complete output items, encrypted reasoning, phase, native tool metadata and explicit cache controls retain supplied upstream fields.",
"Schema2 native assistant state is bound to protocol, actual request URL, exact model, connection, credential revision and request header template. Unknown or incompatible original state remains stored; the request uses ordinary text and original tool calls/results.",
"Plain Chat pools now project history for every member when provider state exists, including same-model members with different credentials; switching only the model field no longer sends the first member's opaque reasoning to another route.",
"New pools default to session affinity, with persisted task/run/none choices; original pools keep their original run/disabled settings. Optional affinity persistence failure does not turn a completed upstream response into an error or cause replay.",
"Model center saves actual scope; ledger shows selected-route state and affinity provenance; context shows candidate connection count without adding the same state across projections.",
"Default unrestricted/passthrough/preserve, persisted ask/auto/full, user native parameters and complete history remain unchanged. No cache controls or optional output-token fields are automatically added.",
"Only completed response affinity is stored across Runs; manual selection wins and independent diagnostics do not overwrite main-task continuity. Completed/interrupted tools are not replayed by these metadata paths."
],
"validation": {
"sourceFinal": "source-5.log: 16/16, original source-1..4 preserved",
"firstCandidate": "candidate-backend-1: 127/129, two outdated affinity assumptions failed",
"correctedCandidateFiles": "candidate-backend-2: 26/26 for both affected test files",
"coverage": "103 unchanged passed tests reused by exact backend/test SHA plus 26 corrected-file tests; no single final full-suite claim",
"finalCandidate": "build-5/candidate-app-5: 880 inputs, 300 product sources, 178 backend inputs, 213 test inputs, 29 compiled outputs, 74 runtime files",
"finalWeb": "web-ui-5: 8 groups, 10 screenshots, 5 owned HTTP requests",
"finalElectron": "electron-ui-1: 8 groups, 10 native hidden-window screenshots, 5 owned HTTP requests",
"retention": "Original metadata, DPAPI ciphertext, stored model snapshot and original history exact on both ends; saved synthetic credentials/native parameters survive independent host restart; one executed list_files tool, no replay",
"sourceIdentity": "22 changed frozen inputs match current Git blobs and working bytes; 8 official captures and source manifest match their original SHA",
"oldSeals": "16171 original entries across I10/I13/I15/I14 roots checked read-only, original manifest SHA exact",
"cleanup": "No current candidate node/Electron processes or listeners at recorded nonformal ports; formal 4318 excluded"
},
"visualReview": {
"workflow": "Existing Orven React model center and task inspector, Chinese programming workflow, persistent scope and request provenance; no new console",
"reviewedScreenshots": [
"web-ui-5/web-d6b3ea8a-032b-4eef-a718-0efd492e3803/new-session-pool-1280.png",
"web-ui-5/web-d6b3ea8a-032b-4eef-a718-0efd492e3803/state-green-390.png",
"web-ui-5/web-d6b3ea8a-032b-4eef-a718-0efd492e3803/state-blue-390.png",
"web-ui-5/web-d6b3ea8a-032b-4eef-a718-0efd492e3803/state-purple-390.png",
"electron-ui-1/electron-8288962e-dccf-4b68-af88-c1ab414a6e0d/new-session-pool-1280.png",
"electron-ui-1/electron-8288962e-dccf-4b68-af88-c1ab414a6e0d/context-state-390.png",
"electron-ui-1/electron-8288962e-dccf-4b68-af88-c1ab414a6e0d/manual-selection-original-error-390.png",
"electron-ui-1/electron-8288962e-dccf-4b68-af88-c1ab414a6e0d/state-purple-390.png"
],
"observations": "Real Chinese text, saved fields, long request URLs/state SHA and original 400 remain readable at 1280/390. Existing horizontal tab scrolling is separate from document overflow. All 20 final screenshots SHA-checked, 8 opened for visual review; measured summary/note contrasts are at least 5.46.",
"failuresPreserved": "web-ui-1 label matching; web-ui-2 viewport transition hides existing narrow inspector; web-ui-3 expected A after automatic reselection chose B; web-ui-4 attempted background tools while narrow inspector was open. Drivers corrected from observed UI/request evidence; no force clicks."
},
"historical": [
"W/AD/AE/AG network failures and unknown usage retain original classifications and receipts.",
"Repeated-reading general improvement is unproven; R/W reserve-v2 live exclusion boundary remains untested.",
"Purge benefit remains unknown; this batch sends no real model requests and does not resume old experiments or user projects.",
"Mobile metadata performance, original host identity observation failure/late lifecycle cause and physical-device paths remain open."
],
"remaining": [
"I27/I28 CI with separate runnable checks and artifact/source binding.",
"M3 final independent source/program release, actual schema2 migration deltas and rollback after the new handler has produced records; do not remove new ledger entries or the existing per-table equality guard.",
"M4 new official/compatible-provider live compatibility and autonomous Node/React/Python samples, each frozen separately after M3.",
"M5 remaining native provider/media/server-tool protocols; M6 real engineering/computer/interactive-host paths; M7 performance/physical-phone/ecosystem; M8 comparable actual benefit and Purge AB/BA."
],
"productionDeployed": false,
"officialServiceHealthRechecked": false,
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"installed": false,
"restartedProduction": false,
"delegated": false,
"sourceAcceptanceComplete": true,
"wholeSystemOrLiveBenefitComplete": false
},
"priorSeals": {
"checkedAt": "2026-11-07T12:28:30.311Z",
"records": [
{
"root": ".qa/m2-cache-usage-2026-11-07",
"entries": 2948,
"bytes": 1018919970,
"manifestSha256": "b3438146114a6c0f0f303f5fa025ec11c647d560188beb14ae0405aaa9a202f7",
"entriesExact": true,
"dependencyLinksNotTraversed": 3,
"writes": 0
},
{
"root": ".qa/m2-request-ledger-2026-11-07",
"entries": 4328,
"bytes": 1620432307,
"manifestSha256": "6ed883ec1fb3e2147795f696802b575e4508e15775c4b764bc8aea166aa34035",
"entriesExact": true,
"dependencyLinksNotTraversed": 4,
"writes": 0
},
{
"root": ".qa/m2-official-registry-2026-11-07",
"entries": 5688,
"bytes": 1037272654,
"manifestSha256": "fbe078468917d79b280aecd4038e537b87ec5de212a772449ba000d7e507d763",
"entriesExact": true,
"dependencyLinksNotTraversed": 6,
"writes": 0
},
{
"root": ".qa/m2-request-contract-2026-11-07",
"entries": 3207,
"bytes": 1498866416,
"manifestSha256": "3963ad9e02d3f62c1ae4d5fefcb59fdc0bcdc63682be1c72109542a60a2b408c",
"entriesExact": true,
"dependencyLinksNotTraversed": 3,
"writes": 0
}
],
"realCredentialsRead": 0,
"productionWrites": 0,
"success": true
},
"cleanup": {
"checkedAt": "2026-11-07T12:33:10.4367296Z",
"root": "m2-native-cache-state-2026-11-07",
"count": 0,
"listenCount": 0,
"processes": [],
"listeners": [],
"portsChecked": [
11434,
49470,
49869,
51514,
56527,
56542,
56544,
62945,
63879
],
"formalPortExcluded": 4318,
"realCredentialsRead": 0,
"productionWrites": 0
},
"evidence": {
"path": ".qa/m2-native-cache-state-2026-11-07/MANIFEST.json",
"files": 5126,
"bytes": 2008555583,
"manifestSha256": "c887364e54fe3f68e5f432155db87517fb8413966f5786156bedceddadbf2217",
"dependencyLinksRecordedNotTraversed": 5,
"sealedReadOnlyFromNow": true,
"subsequentPushReceiptsSeparate": true
},
"productionDeployed": false,
"officialServiceHealthRechecked": false,
"realModelRequests": 0,
"realCredentialsRead": 0,
"productionWrites": 0,
"installed": false,
"restartedProduction": false,
"delegated": false,
"scope": "Source and independent deterministic candidate only; no live-provider, delivery or cache/Purge benefit claim",
"historicalUnknown": [
"W/AD/AE/AG network failures and unknown usage retain original classifications and receipts.",
"Repeated-reading general improvement is unproven; R/W reserve-v2 live exclusion boundary remains untested.",
"Purge benefit remains unknown; this batch sends no real model requests and does not resume old experiments or user projects.",
"Mobile metadata performance, original host identity observation failure/late lifecycle cause and physical-device paths remain open."
],
"remaining": [
"I27/I28 CI with separate runnable checks and artifact/source binding.",
"M3 final independent source/program release, actual schema2 migration deltas and rollback after the new handler has produced records; do not remove new ledger entries or the existing per-table equality guard.",
"M4 new official/compatible-provider live compatibility and autonomous Node/React/Python samples, each frozen separately after M3.",
"M5 remaining native provider/media/server-tool protocols; M6 real engineering/computer/interactive-host paths; M7 performance/physical-phone/ecosystem; M8 comparable actual benefit and Purge AB/BA."
]
}
+18
View File
@@ -1,5 +1,23 @@
# 汇总发现
I09/I11封存收口:5126原件、2008555583字节、5依赖junction不递归;原四M2根16171原件/manifest只读一致,22源码Git字节一致,实际候选进程/记录非正式端口监听0。源码/隔离验收完成与正式部署/真实缓存/Purge收益分别记录;下一CI后M3必须验证迁移增量与新结果回退。封存后误用Tianshu文档标题的失败patch只记录在新close/当前进展,不回写原证据根。
I09/I11最终Electron通过且实际复看1280新池编辑与390任务上下文:现有Orven布局/中文/长SHA/下拉与真实保存保留,输出“本次不限/不附加上限/由上游处理”与冻结状态分别呈现。网页绿/紫状态图亦复看,三配色和窄屏保持一致。两个端各5本机POST、3成功/2原400,6账本含原unknown;完成工具1、不重放,原metadata/cipher/snapshot/history全部exact。本批不证明真实缓存命中/上游普遍兼容。
最终网页两图实看:web-ui-5 new-session-pool-1280的连接保持下拉、真实成员及保存动作布局完整;state-blue-390原400/状态数量/地址可读且无文档横溢,顶部当前A与历史B请求分别保留,没有倒改旧请求型号。手机横向导航为既有必要滚动,不误记为文档溢出。实际Electron仍在独立运行,桌面及紫/绿色最终图另验。
I09/I11最终输入首核对通过:880输入/300产品源码/178后端/213测试/29编译/74runtime。178后端全与首候选相同;213测试输入中211未改,两改测试文件与26/26候选一致,复用103原通过项。8官方原件/source清单与Git原字节一致,来源正文6尾空白不修剪。web-ui-5实际8组/10图、5本机请求+1原unknown账本、原metadata/cipher/snapshot/history exact、三配色被测文字对比≥5.46;实际Electron与清理仍待,不把网页通过当桌面或真实供应商通过。
I09/I11 web-ui-3四组通过后仍失败:实际第4次选中owned-b,未发送A修改的X-Owned-Scope;原驱动误以为失效亲和仍应选A。原requests.json核对前三次A及相符reasoning,第四次B且无旧reasoning。按实际自动重选保留400,并新增实际模型中心手选A一次核对修改头、原错与不重放;最终应5本机请求/6账本而非旧4/5。候选3产品不变,另冻最后验收输入,避免重复编译与runtime复制。实际已查看web-ui-3的1280账本与390上下文:中文/长地址与状态SHA可读,手机没有文档溢出;最终三配色和Electron仍需验。
I09/I11接续:candidate-backend-1为127/129,两项旧假设已核对。跨Run权重轮询测试必须显式选run,默认新池应session;关闭保持时不再暗存连接,重新启用run后应先按权重选择,再沿用本次记录。web-ui-2先完成3组/3本机请求,在宽屏打开检视后直接缩到手机触发App已有关闭wide行为,失败现场只显示会话;改为先设390再由真实任务入口打开,不修改已有布局行为。上下文候选状态不能把同一原状态跨连接相加,改为候选连接数,各连接单独列状态数量。
I09/I11 source-4为14/15:收窄断言后确认真实纯Chat混池缺陷,不是整正文误命中。completionBody在所有成员均无native/streaming时只构造首成员body,actualRequest只换model,旧reasoning_content进入后备连接。现有状态时必须逐成员投影,连同型号相同但凭据不同的池验证。原source-3/4失败保留;原生Messages/Responses SSE、停止续同Task与可选亲和存储故障均在source-4通过。未知亲和记录保留不重写,optional存储失败不改变已完成上游响应的结果。
I09/I11接续决策:新池可默认会话保持,但旧池必须保留原Run范围;亲和只来自完成的真实响应且诊断路径独立。状态身份要核对实际请求路径/认证模板/版本头/型号/连接与凭据修订,改变原生普通生成参数不应误认凭据变化。状态无法适用时保留原件和原因、以常规文本/原调用构造新历史,不丢用户数据或自动重放工具。沿既有Orven池编辑与上下文/请求账本补真实控制和反馈,不另立页面。
I09/I11具体缺口:messagesBody重建文本和工具时丢非结构元数据,messagesHistory反向只取text并改变tool_result顺序;Messages/Responses原生助手状态只有endpoint/model绑定,缺实际请求版本/头/凭据范围;ModelHub sticky仅runId且重启不持久。需要按来源区分声明原生输入与不透明输出状态,当前状态不能跨供应商或凭据误用,原件不能因此丢弃。
原生状态核对新增源方参考:冻结预设/用户设置不等于actual standard会话采用,创建失败也不代表发过模型请求;输入估算/额外预留、压缩请求值与当次fetch数据必须分别核对。手机客户端期限/确认、服务端原任务成功、容量样本和被清理的分段证据不能互相补数或推定延迟段。新同步仅按源方报告登记,自己的透传/预算/身份和原未知结论不改变。
I14收尾复核:实际请求头观察必须绑定prepared fetch参数,原Run只能表示冻结设置;认证模板/独立Key引用、HTTP传输层补头和真实缓存命中证据分别说明。最终两端各8组验证通知正常滚动、原配置/密文/快照保持;871输入与29输出一致,176后端/209测试未变可复用原143/143。首身份验证误用TAP计数不是产品失败,原件保留后仅修验证器。源码交付不升级为真实供应商/自主工程/Purge收益通过;迁移增量与激活新处理器后的回退仍必须在M3证明。
+26
View File
@@ -1,5 +1,31 @@
# 统一执行进度
I09/I11 UI源码ee97aaae已限定提交,22变更冻结输入/Git原字节复核通过;5126份2008555583字节封存,MANIFEST c887364e54fe3f68e5f432155db87517fb8413966f5786156bedceddadbf2217,旧四根16171项只读exact,自有进程及记录非正式端口监听0。当前验收/机器记录/接续入口提交及普通GitAtlas增量推送收尾;新封存根只读,后续写独立close根。一次接续文档patch误用Tianshu标题整体未应用,按实际标题重做,不追加原封存。
I09/I11实际Electron独立8组/10图完成:5本机请求、原metadata/cipher/snapshot/history exact、合成Claude凭据重载、1工具不重放;窗口保持隐藏,原生capturePage,正常关闭并独立宿主重启,三配色/1280及390和外部/页面错误0。已复看网页绿/紫及Electron宽表单/窄上下文,真实字体与结构可读;最终源/界面审查、限定提交与封存收尾,正式未写入/重启。
I09/I11 web-ui-5完成8组/10图,5本机请求及6账本、所有原metadata/cipher/snapshot/history exact、1工具未重放;外部页面/错误0,三配色/1280及390通过。最终880输入/300源码/178后端/213测试/29编译/74runtime首身份复核通过,规范化0项;source-5为16/16,原127/129加两文件26/26按SHA覆盖129(103未变复用)。实际Electron独立运行中;随后限定UI/回归提交及最终封存,不作正式部署/缓存/Purge收益声明。
I09/I11 web-ui-4在手机任务抽屉打开后直接点后方工具箱,被可见检视区截住,4组/4请求的原失败与failure-center保留。open辅助先按用户Escape返回,再打开模型中心;不force点击后方元素,不改产品布局。最终按.gitattributes只规范化本批变更文本CRLF为LF、保留原冻结字节和来源正文,另冻build-5验最终源码/桌面。
I09/I11 build-3/candidate-3为880输入/29编译/74runtime,相关两文件26/26通过。web-ui-3通过4组,原第4次确实自动重选B,因驱动误期待A修改头而失败;保留4请求/原图/原日志。最新驱动分别验证自动B和UI手选A(新增一请求),不修改产品选线;最后使用build-4冻结验收输入及不变candidate-3,产品编译输入逐SHA复用。实际宽窄两图已复看,最终两端/三配色和原件保持仍待。
I09/I11接续已读原计划/未提交diff并取web-ui-2结果:3组通过后窄屏截图等待失败(3本机请求),candidate-backend-1为127/129。核源码确认两项为旧亲和假设、检视跨手机边界会关闭已有wide状态;按显式run/关闭不暗存更新旧测试,验收器先设390再打开真实任务入口。候选状态汇总改显示连接数,避免跨连接重复加原状态。两次文档patch使用错误findings/progress标题,均整体未应用,第三次按真实锚点完成;原错误保留。下一另冻build-3,只重验受改测试文件和两端核心路径,复用需逐SHA核对的未变后端结果。
I09/I11独立build-1通过:880输入、29编译、74runtime逐复制SHA;相关候选回归进行中。web-ui-1在第一个旧池编辑的精确标签定位失败,实看1280截图和原DOM已确认下拉存在且显示原Run范围;嵌套select选项参与label文本,新增与可见文案一致的aria-label后另冻build-2。0模型请求,原失败截图/文本/日志保留。旧metadata、密文和快照尚待最终两端验收,不抢先宣称exact。
I09/I11阶段2核心完成:source-5最终16/16、typecheck-2退出0。纯Chat状态逐成员投影已通过相同型号/不同凭据、实际停用/改头边界;原生块TTL/工具元数据、JSON/SSE签名/加密reasoning/phase、跨Run/Store与Provider重启、手选、同Task停止恢复和optional保存故障保持。原source-1/2/3/4失败原件不动。核心限定本地提交后独立构建与相关回归/两端UI继续;未发行或触正式服务。
I09/I11 source-4完整新15项为14过1失败:纯Chat池只换型号、误用首成员推理状态已定位并修复,新增相同型号/不同凭据的独立投影边界,下一source-5不覆盖原轮。原生JSON/SSE及phase/cache块、停止恢复不重放、unknown亲和和可选保存故障通过。额外只读调查误猜两个.d.mts路径以及rg参数放在--后均保留为工具使用错误,无产品或正式数据改变。
I09/I11来源提交前git diff --check发现官方原文6处原有尾空白,来源字节/SHA保持不修剪;限定排除这两份官方正文后核对其它新增文件,后续另核Git blob原字节。不是产品检查失败,不改原来源来制造通过。
I09/I11阶段1来源复核完成:8份官方来源固定,SOURCE.json SHA ced3703c4afb174c5b939ffb3dd8572f22ff8e5f3fb8489f627f45880315b799;OpenAI完整Docs原件复用、Claude/DeepSeek六份逐SHA一致。接续再次打开当前两篇页面,原source-1/2/3失败保留,未重跑旧轮次;首次mkdir既有目录拒绝后改为新文件名写入。下一完成核心与用户连接保持范围及确定性边界,限定来源提交先行。
I09/I11接续复核(2026-11-07):沿bdfeb29c与已有未提交实现继续,planning catchup退出0且无补遗;已核AGENTS最新范围、采用计划、1.25计划与M2第五批计划。工作树含缓存块/身份/亲和核心及新测试,界面/来源封存/验证/提交尚未完成,不把简短接续摘要当验收。初次工作区根AGENTS不存在、过宽清单输出截断和假定CI目录不存在仅属只读调查错误;以后限定Agent-Workbench真实路径和输出范围。当前不委派/真实模型/Key/正式写入或重启,先核未提交输入再完成本批。
I09/I11阶段1开始:确认Messages转换丢系统/内容/工具缓存注解、亲和仅在Run;先保存当前OpenAI官方缓存/会话原件并复用I15 Claude/DeepSeek来源。planning catchup退出0/无补遗。初读误猜model-settings/model-native-settings文件名及PowerShell rg glob、过量来源结果输出仅属调查错误,后续改为真实文件列表/摘要输出。Mnemo新增准确报告/固定计划SHA与SSE partial只读资料另保留,不替代工作台验收;主任务继续。
Mnemo新调用方预算/状态同步已仅作只读登记:源方新版手机短3/3、900秒49/60发起/48客户端确认/p95约48.4/125新鲜采样仍失败;后查49服务端原任务成功不补成客户端窗口通过。47无网络响应与8离线/过期、分段事件清理后的延迟unknown分别保留。Harness2048→23→1/额外4096预留、修后2048与默认压缩65536/standard身份缺项分开;最新启动不能创建会话、0模型请求,14公开检查与独立边界失败分别记录,完整读改测/恢复未通过。固定旧计划SHA一致,明确reviews路径未找到。见[只读同步](docs/integration/MNEMO-CALLER-BUDGET-STATE-READONLY-2026-11-07.md)。工作台M2下一I09/I11/CI及M3顺序、开放默认/模型偏好/历史unknown保持,无真实模型/正式写入/委派或向源线程回复。
I14/I12本批阶段5完成:3207份1498866416字节已封存,manifest 3963ad9e02d3f62c1ae4d5fefcb59fdc0bcdc63682be1c72109542a60a2b408c;封存后全3207原件/871工作输入只读复核,35改变输入Git原字节与17当前文档链接通过,2个文档仅规范化行尾、产品输入未变。来源337d1bc9、核心f95507ab、界面26472d28及验收04c0556c已普通增量推送至既有GitAtlas feat/task-agreement-1.25,远端逐SHA一致。回执和完成接续最后另提交/推送再核对,不递归改回执。下一I09/I11缓存块/跨Run状态与I27/I28 CI,再M3真实schema2迁移增量/新处理器结果后回退;未发行/正式操作/真实模型,W/AD/AE/AG与重复读/R/W边界/Purge收益unknown保持。
+262
View File
@@ -0,0 +1,262 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until, completion, call } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
if (process.argv.includes('--help')) {
console.log('AGENT_WORKBENCH_QA_APP_ROOT=<independent candidate> AGENT_WORKBENCH_QA_EVIDENCE_ROOT=<new evidence directory> node scripts/verify-native-cache-state-ui.mjs [--desktop]. Owned HTTP only; no production or real model calls.');
process.exit(0);
}
const desktop = process.argv.includes('--desktop');
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate');
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
const directory = path.resolve(process.env.AGENT_WORKBENCH_QA_EVIDENCE_ROOT ?? '.qa/m2-native-cache-state-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: value => disposers.push(value) }, f = fixture(t, { modernDefaults: true });
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [], contrast = [];
const cache = { type: 'ephemeral', ttl: '1h', owned_extension: { preserved: true } };
const native = { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, cache_control: cache,
metadata: { preserved: ['owned', { nested: true }] } };
const legacyAttempt = { id: 'owned-original-unknown', model: 'owned-original', status: 'unknown', usage: null,
original_extension: { keep: ['network failure', 'unknown usage', 'repeated reads'] } };
const originalHistory = [{ role: 'user', content: '原用户内容完整保留。' }, { role: 'assistant', content: '原答复完整保留。',
providerState: { schemaVersion: 999, protocol: 'chat-completions', endpoint: 'https://original.invalid/v1', model: 'original', reasoningContent: 'owned-original-opaque' } }];
let reject = false;
const model = http.createServer(async (request, response) => {
try {
const chunks = []; for await (const chunk of request) chunks.push(chunk);
const body = JSON.parse(Buffer.concat(chunks));
requests.push({ path: request.url, body, headers: Object.fromEntries(Object.entries(request.headers).map(([name, value]) => [name, credentialHeader(name) ? '{{credential}}' : value])) });
if (reject) {
response.writeHead(400, { 'Content-Type': 'application/json', 'x-request-id': 'owned-original-cache-state-error' });
response.end(JSON.stringify({ error: { type: 'invalid_request_error', message: 'owned-original-header-scope-error' } })); return;
}
const value = completion(requests.length === 1 ? [call('owned-first-tool', 'list_files', { path: '', depth: 1 })] : [], '完成');
value.model = body.model; value.choices[0].message.reasoning_content = 'owned-current-reasoning-' + requests.length;
value.usage.prompt_tokens_details = { cached_tokens: 2 };
response.writeHead(200, { 'Content-Type': 'application/json', 'x-request-id': 'owned-cache-state-' + requests.length }); response.end(JSON.stringify(value));
} catch (cause) { response.writeHead(500); response.end(cause.message); }
});
let host, browser, application, controller, page, window, result, memberA, memberB, claude, legacyPool, disabledPool, newPool;
let originalMetadata, originalCipher, originalSnapshotMetadata, desktopStdout = '', desktopStderr = '';
const center = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const poolForm = () => center().getByRole('form', { name: '编辑模型池', exact: true });
const poolCard = id => center().locator('.mc-pool[data-pool-id="' + id + '"]');
const mark = text => { checks.push(text); console.log('PASS ' + text); };
async function resize(width, height = 960) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(width => innerWidth === width, width)); }
else await page.setViewportSize({ width, height });
}
async function open(tab = '模型池') {
if (!await center().count()) { await page.keyboard.press('Escape'); await openWorkbenchTool(page, '打开模型中心'); }
await expect(center()).toBeVisible(); await center().getByRole('button', { name: tab, exact: true }).click();
}
async function capture(file) {
if (!window) { await page.screenshot({ path: file, scale: 'css' }); return { method: 'playwright-page' }; }
const picture = await window.evaluate(async win => {
const [width, height] = win.getContentSize(), image = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true });
return { png: image.toPNG().toString('base64'), empty: image.isEmpty(), size: image.getSize(), hidden: !win.isVisible() };
});
assert.equal(picture.empty, false); assert.equal(picture.hidden, true); fs.writeFileSync(file, Buffer.from(picture.png, 'base64'), { flag: 'wx' });
return { method: 'electron-native-stay-hidden', size: picture.size };
}
async function shot(name, anchor) {
if (anchor) await anchor.scrollIntoViewIfNeeded();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No document overflow');
const file = path.join(directory, name + '.png'), evidence = await capture(file);
screenshots.push({ file: path.basename(file), sha256: sha(fs.readFileSync(file)), ...evidence });
fs.writeFileSync(path.join(directory, name + '.txt'), await (await center().count() ? center() : page.locator('body')).innerText(), { flag: 'wx' });
}
async function sampleContrast(locator, label) {
const sample = await locator.evaluate(element => {
const style = getComputedStyle(element); let ancestor = element, background;
while (ancestor) { const color = getComputedStyle(ancestor).backgroundColor; if (!['rgba(0, 0, 0, 0)', 'transparent'].includes(color)) { background = color; break; } ancestor = ancestor.parentElement; }
return { color: style.color, background, fontSize: style.fontSize };
});
const luminance = text => text.match(/[\d.]+/g).slice(0, 3).map(Number).map(value => value / 255).map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
const a = luminance(sample.color), b = luminance(sample.background), ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
contrast.push({ label, ...sample, ratio }); assert.ok(ratio >= 4.5, label + ': ' + ratio);
}
async function editPool(id) { await open(); await poolCard(id).getByRole('button', { name: '编辑', exact: true }).click(); await expect(poolForm()).toBeVisible(); }
async function savePool() { await poolForm().getByRole('button', { name: '保存模型池', exact: true }).click(); await expect(poolForm()).toHaveCount(0); }
async function run(content, count) {
await host.api('/sessions/' + f.session.id + '/messages', { content });
await until(async () => { const value = await host.api('/sessions/' + f.session.id); return ['completed', 'failed', 'paused'].includes(value.status) && requests.length === count; }, 40000);
await until(async () => (await host.api('/model-center')).attempts.filter(value => value.sessionId === f.session.id).every(value => value.status !== 'running'), 20000);
}
async function entryFor(id) {
await open('请求账本'); const ledger = center().locator('.mc-ledger'); await ledger.getByRole('button', { name: '刷新记录', exact: true }).click();
const records = await host.api('/model-center/attempts'), index = records.items.findIndex(value => value.id === id); assert.ok(index >= 0);
const entry = ledger.locator('article[data-ledger-sequence="' + records.references[index].sequence + '"]'); await expect(entry).toBeVisible(); return entry;
}
try {
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
const baseUrl = 'http://127.0.0.1:' + model.address().port + '/v1';
f.store.saveConfig({ mode: 'compatible', approvalMode: 'full' });
f.store.storage.setMeta('modelAttempts', [legacyAttempt]); originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store);
memberA = hub.upsert({ name: '自有 Chat A', model: 'owned-a', baseUrl, requiresKey: false });
memberB = hub.upsert({ name: '自有 Chat B', model: 'owned-b', baseUrl, requiresKey: false });
claude = hub.upsert({ name: '自有 Claude 缓存设置', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl,
apiKey: 'owned-cache-state-synthetic-key', persistKey: true, nativeParameters: native });
legacyPool = hub.pool({ name: '原模型池 · 运行保持', members: [{ connectionId: memberA.id }], sticky: true });
disabledPool = hub.pool({ name: '原模型池 · 关闭保持', members: [{ connectionId: memberB.id }], sticky: false });
delete legacyPool.affinityScope; delete disabledPool.affinityScope; hub.save();
legacyPool = structuredClone(legacyPool); disabledPool = structuredClone(disabledPool);
hub.select({ type: 'pool', id: legacyPool.id });
const snapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' })); f.store.storage.setMeta('ownedModelSnapshot', snapshot);
originalSnapshotMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
originalCipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
f.session.providerMessages = structuredClone(originalHistory); f.store.save(f.session);
fs.writeFileSync(path.join(directory, 'retention-before.json'), JSON.stringify({ metadata: originalMetadata, cipher: originalCipher, snapshot: originalSnapshotMetadata, legacyPool, disabledPool, originalHistory }, null, 2));
f.store.close();
if (desktop) {
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
page = await application.firstWindow(); window = await application.browserWindow(page);
} else {
host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage();
}
page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message));
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); });
await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle'); await open();
fs.writeFileSync(path.join(directory, 'initial-dom.html'), await page.content(), { flag: 'wx' }); await shot('existing-pools-1280');
await editPool(legacyPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('run'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
await editPool(disabledPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('none'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
let current = await host.api('/model-center'); assert.deepEqual(current.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(current.pools.find(value => value.id === disabledPool.id), disabledPool);
assert.equal(requests.length, 0); mark('Existing pools retain their original Run/disabled scope without saving new defaults or issuing model requests');
await center().locator('.mc-section-title').getByRole('button').click(); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('session');
await poolForm().getByLabel('模型池名称', { exact: true }).fill('自有会话模型池');
for (const name of [memberA.name, memberB.name]) await poolForm().locator('fieldset label').filter({ hasText: name }).getByRole('checkbox').check();
await shot('new-session-pool-1280', poolForm()); await savePool();
newPool = (await host.api('/model-center')).pools.find(value => value.name === '自有会话模型池'); assert.equal(newPool.affinityScope, 'session');
for (const scope of ['task', 'run', 'none', 'session']) {
await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption(scope); await savePool();
await page.reload(); await page.waitForLoadState('networkidle'); await editPool(newPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue(scope);
if (scope === 'task') { await resize(390, 844); await shot('task-pool-390', poolForm().getByLabel('连接保持范围', { exact: true })); }
await poolForm().getByRole('button', { name: '取消', exact: true }).click();
}
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === newPool.id); await page.keyboard.press('Escape');
mark('All four pool scopes save through the real form and survive reload; new pools start with session affinity and explicit selection persists');
await run('读取工程目录然后结束', 2); await run('追加一句说明然后结束', 3);
current = await host.api('/model-center'); const lastSuccess = current.attempts.find(value => value.sessionId === f.session.id && value.nativeStateAudit?.applied === 2);
assert.ok(lastSuccess); assert.equal(lastSuccess.routingDecision.affinity.source, 'saved-completed-response'); assert.equal(lastSuccess.routingDecision.affinity.scope, 'session');
assert.ok(requests.every(value => value.body.model === memberA.model)); assert.ok(requests[2].body.messages.some(value => value.reasoning_content === 'owned-current-reasoning-1'));
assert.ok(requests.every(value => value.body.max_tokens === undefined && value.body.max_completion_tokens === undefined));
let entry = await entryFor(lastSuccess.id); await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('当前会话 · 沿用连接');
await entry.locator('.model-provider-state > summary').click(); await expect(entry.locator('.model-provider-state')).toContainText('可续接 2 / 仅保留 1');
await expect(entry.locator('.model-provider-state')).toContainText('原状态版本尚未支持');
await resize(1280); await shot('continued-history-1280', entry.locator('.model-provider-state > summary'));
mark('The request ledger shows completed-response affinity and applicable native states separately from the retained original unknown state and cache usage');
await page.keyboard.press('Escape'); await resize(390, 844); await openWorkbenchTool(page, '查看任务记录');
const context = page.getByRole('region', { name: '请求上下文', exact: true }); await expect(context).toBeVisible();
await context.locator('.model-provider-state > summary').click(); await expect(context).toContainText('发送前冻结的各连接历史投影');
await expect(context.locator('.model-provider-state > summary')).toContainText('2 条候选连接');
await shot('context-state-390', context.locator('.model-provider-state > summary'));
mark('The actual task inspector exposes the frozen state projection and upstream-owned context limits at 390px');
const changedConnection = (await host.api('/model-center')).connections.find(value => value.id === memberA.id);
await host.api('/model-center/connections', { ...changedConnection, requestContract: { ...changedConnection.requestContract, headers: { 'X-Owned-Scope': 'changed' } } });
reject = true; await run('继续任务并返回原错误', 4);
current = await host.api('/model-center'); const failed = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed'); assert.ok(failed);
assert.equal(failed.nativeStateAudit.retainedOnly, 4); assert.equal(failed.routingDecision.affinity.reason, 'saved-provider-scope-changed');
assert.equal(failed.connectionId, memberB.id); assert.equal(requests[3].body.model, memberB.model);
assert.ok(requests[3].body.messages.every(value => value.reasoning_content === undefined)); assert.equal(requests[3].headers['x-owned-scope'], undefined);
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click(); await expect(entry).toContainText('可续接 0 / 仅保留 4');
await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('连接身份或请求范围已变化');
await expect(entry).toContainText('owned-original-header-scope-error'); await shot('changed-state-original-error-390', entry.locator('.model-provider-state > summary'));
const old = await entryFor(legacyAttempt.id); await expect(old).toContainText('用量未知'); assert.equal(await old.locator('.model-provider-state').count(), 0);
mark('Changed provider scope reselects the next eligible pool member, retains old states and one original upstream 400, and fabricates no old metadata');
await open('模型连接');
await center().locator('.mc-connection[data-connection-id="' + memberA.id + '"]').getByRole('button', { name: '用于新任务', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === memberA.id); await page.keyboard.press('Escape');
await run('显式选择连接并保留原错误', 5);
current = await host.api('/model-center'); const manualFailure = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed' && value.connectionId === memberA.id);
assert.ok(manualFailure); assert.equal(manualFailure.nativeStateAudit.retainedOnly, 4); assert.equal(manualFailure.routingDecision.reason, 'explicit-selection');
assert.equal(requests[4].body.model, memberA.model); assert.equal(requests[4].headers['x-owned-scope'], 'changed');
assert.ok(requests[4].body.messages.every(value => value.reasoning_content === undefined));
entry = await entryFor(manualFailure.id); await entry.locator('.model-provider-state > summary').click();
await expect(entry).toContainText('显式选择:按原配置透传'); await expect(entry).toContainText('owned-original-header-scope-error');
await shot('manual-selection-original-error-390', entry.locator('.model-provider-state > summary'));
mark('Manual model selection takes precedence, transmits its changed header and preserves the original 400 once without applying old opaque history or replaying tools');
for (const [palette, name] of [['green', '深青绿'], ['blue', '雾蓝'], ['purple', '鸢尾紫']]) {
await page.keyboard.press('Escape'); await page.getByRole('button', { name: '外观', exact: true }).click();
await page.getByRole('dialog', { name: '外观', exact: true }).getByRole('radio', { name, exact: true }).check(); await page.keyboard.press('Escape');
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click();
await sampleContrast(entry.locator('.model-provider-state > summary'), palette + ' summary'); await sampleContrast(entry.locator('.model-provider-state > p').first(), palette + ' note');
await shot('state-' + palette + '-390', entry.locator('.model-provider-state > summary'));
}
await open(); await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption('task'); await savePool();
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === newPool.id);
mark('State details and scope settings remain readable and usable in the three existing palettes without narrow-screen document overflow');
const finalCenter = await host.api('/model-center'); fs.writeFileSync(path.join(directory, 'center-final.json'), JSON.stringify(finalCenter, null, 2));
fs.writeFileSync(path.join(directory, 'session-export.json'), JSON.stringify(await host.api('/sessions/' + f.session.id + '/export'), null, 2));
assert.equal(finalCenter.attemptCount, 6); assert.deepEqual(finalCenter.attempts.find(value => value.id === legacyAttempt.id), legacyAttempt);
assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []);
if (application) { await application.close(); application = null; } if (browser) { await browser.close(); browser = null; }
if (controller) { await controller.stop(); controller = null; } await host.close?.(); host = null;
host = await launchWorkbench(t, f.data, {}, { appRoot }); const restoredHostUrl = host.url;
const restored = await host.api('/model-center'); assert.equal(restored.attemptCount, 6); assert.equal(restored.selected.id, newPool.id);
assert.equal(restored.pools.find(value => value.id === newPool.id).affinityScope, 'task');
assert.deepEqual(restored.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(restored.pools.find(value => value.id === disabledPool.id), disabledPool);
const restoredClaude = restored.connections.find(value => value.id === claude.id); assert.equal(restoredClaude.hasKey, true); assert.deepEqual(restoredClaude.nativeParameters, native);
await host.close(); host = null;
const storage = new Store(f.data);
try {
const metadata = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const cipher = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
const snapshot = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
fs.writeFileSync(path.join(directory, 'retention-after.json'), JSON.stringify({ metadata, cipher, snapshot, history: storage.session(f.session.id).providerMessages, affinity: storage.session(f.session.id).modelAffinity }, null, 2));
assert.equal(metadata, originalMetadata); assert.equal(cipher, originalCipher); assert.equal(snapshot, originalSnapshotMetadata);
assert.deepEqual(storage.session(f.session.id).providerMessages.slice(0, originalHistory.length), originalHistory); assert.equal(storage.core.tool.size, 1);
for (const plan of storage.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(storage, storage.session(f.session.id), plan));
} finally { storage.close(); }
mark('Candidate host restart retains saved scope, original pools, native cache settings, original metadata/cipher/snapshot and history; no tool or request is replayed');
result = { success: true, appRoot, actualElectron: desktop, hostUrl: restoredHostUrl, checks, screenshots, contrast, errors, externalBlocked,
syntheticRequests: requests.length, originalUnknownAttempts: 1, originalMetadataExact: true, originalCipherExact: true, originalSnapshotExact: true, originalHistoryExact: true,
realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
} catch (cause) {
if (page) { await capture(path.join(directory, 'failure.png')).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
if (host) { const state = await host.api('/model-center').catch(() => null); if (state) fs.writeFileSync(path.join(directory, 'failure-center.json'), JSON.stringify(state, null, 2), { flag: 'wx' }); }
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, contrast, errors, externalBlocked, error: cause.stack,
syntheticRequests: requests.length, realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0 };
} finally {
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
if (application) await application.close(); if (browser) await browser.close();
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
if (model.listening) await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); });
for (const dispose of disposers.reverse()) await dispose();
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
+2
View File
@@ -21,6 +21,8 @@
.mc-routing-decision li{border-left:2px solid var(--line);padding-left:10px}
.mc-routing-decision li>span{display:block}
.mc-routing-decision summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.mc-affinity-record{margin:10px 0;padding-left:10px;border-left:2px solid var(--line)}.mc-affinity-record>p{margin:5px 0}.mc-affinity-record code{white-space:normal;overflow-wrap:anywhere}
.mc-affinity-setting{margin:16px 0;min-width:0}.mc-affinity-setting>label{display:grid;gap:7px;font-size:13px;color:var(--ink)}.mc-affinity-setting select{min-height:44px;padding:10px 12px;border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--ink);font:inherit;width:100%;min-width:0}.mc-affinity-setting select:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.mc-affinity-setting .mc-help{margin:8px 0;color:var(--muted);line-height:1.7}
.mc-stream-receipt { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 8px; }
.mc-stream-receipt code { display: block; overflow-wrap: anywhere; font-size: 11px; line-height: 1.7; }
.mc-stream-receipt .button { margin-top: 8px; }
+7 -4
View File
@@ -32,7 +32,10 @@ const protocolOutput = (value: ModelSpecConnection & { maxOutputTokens?: number
type Connection = NativeConnection & { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type AffinityScope = 'none' | 'run' | 'task' | 'session';
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; affinityScope?: AffinityScope; maxAttempts: number; revision?: number; queueTimeoutMs: number };
const affinityLabels: Record<AffinityScope, string> = { none: '每次请求重新选择', run: '当前运行保持连接', task: '当前任务保持连接', session: '当前会话保持连接' };
const poolAffinity = (pool: Pool): AffinityScope => pool.sticky === false ? 'none' : pool.affinityScope ?? 'run';
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
@@ -44,7 +47,7 @@ const states: Record<string, string> = { configured: '已配置', needs_key: '
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, ...DEFAULT_MODEL_CAPACITY, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
const capabilityStates: Record<string, string> = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, affinityScope: 'session', maxAttempts: 3, queueTimeoutMs: 15000 };
export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Config, selection?: ModelSelection) => void; busy: boolean; runModel?: ModelSnapshot }) {
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
@@ -213,8 +216,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
</section>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>自动选择优先已知适配成员,能力未知时保留后备尝试。明确不支持的成员不参与自动选择,仍可手动选用。透传请求失败后保留原错,等待处理。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询或权重与连接亲和。</p>}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
{view.pools.map(value => <article className="mc-pool" key={value.id} data-pool-id={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {affinityLabels[poolAffinity(value)]}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><div className="mc-affinity-setting"><label>连接保持范围<select aria-label="连接保持范围" value={poolAffinity(pool)} onChange={event => { const affinityScope = event.target.value as AffinityScope; setPool({ ...pool, affinityScope, sticky: affinityScope !== 'none' }); }}><option value="session">当前会话 · 跨任务与运行</option><option value="task">当前任务 · 跨运行</option><option value="run">当前运行</option><option value="none">关闭 · 每次请求重新选择</option></select></label><p className="mc-help">优先沿用此范围内上次完成响应的连接。停用、身份变化或不适配时重新选择;手动选模优先,上游错误按原结果保留。</p></div>
<fieldset><legend>模型池成员与权重</legend>{connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
+14
View File
@@ -0,0 +1,14 @@
.model-provider-state { min-width: 0; margin-top: 12px; border-top: 1px solid var(--line); padding-top: 8px; color: var(--muted); font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.model-provider-state > summary { cursor: pointer; min-height: 42px; padding: 10px 0; color: var(--ink); font-weight: 600; }
.model-provider-state > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.model-provider-state p { margin: 6px 0 10px; }
.model-provider-state section { padding: 8px 0; }
.model-provider-state h4 { margin: 4px 0 8px; color: var(--ink); font-size: 12px; }
.model-provider-state dl { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: 6px 12px; margin: 0; }
.model-provider-state dt, .model-provider-state dd { margin: 0; min-width: 0; }
.model-provider-state code { font: 11px/1.7 var(--font-mono, Consolas, monospace); white-space: normal; overflow-wrap: anywhere; }
.model-provider-state ul { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 12px; }
.model-provider-state li { border-left: 2px solid var(--line); padding-left: 10px; }
.model-provider-state li strong { color: var(--ink); }
.model-provider-state li > span, .model-provider-state li > code { display: block; }
@media (max-width: 620px) { .model-provider-state dl { grid-template-columns: 1fr; gap: 3px; } .model-provider-state dd { margin-bottom: 7px; } }
+35
View File
@@ -0,0 +1,35 @@
import { protocolLabel } from '../shared/contracts/model-endpoint.mjs';
import './ModelProviderStateDetails.css';
export type ProviderStateVariant = {
connectionId: string | null; model: string; protocol: string; applied: number; retainedOnly: number;
binding: { requestUrl: string | null; credentialRevision: number | null; fingerprint: string; headers: [string, string][] };
states: { index: number; protocol: string; responseId: string | null; stateSchemaVersion: number; applicable: boolean; reason: string; stateSha256: string }[];
};
export type ProviderStateAuditView = Partial<ProviderStateVariant> & { schemaVersion?: number; source?: string; requestPlanId?: string; variants?: ProviderStateVariant[] };
const reasons: Record<string, string> = { 'same-provider-scope': '当前供应商范围一致', 'provider-scope-changed': '连接、凭据、型号或请求头范围已变化',
'unknown-state-schema': '原状态版本尚未支持', 'legacy-chat-identity-match': '原 Chat 连接与凭据身份一致',
'legacy-provider-changed': '原连接或型号已变化', 'legacy-direct-protocol': '原直接协议历史', 'legacy-identity-unavailable': '旧状态未保存完整身份' };
export function ModelProviderStateDetails({ audit }: { audit?: ProviderStateAuditView }) {
if (!audit) return null;
const variants = audit.variants ?? (audit.binding && audit.states ? [audit as ProviderStateVariant] : []);
if (!variants.length) return null;
const summary = audit.variants ? `${variants.length} 条候选连接` : `可续接 ${variants[0].applied} / 仅保留 ${variants[0].retainedOnly}`;
return <details className="model-provider-state"><summary>原生历史状态 · {summary}</summary>
<p>{audit.variants ? '发送前冻结的各连接历史投影。' : '本次选中连接对应的冻结历史投影。'}按协议、地址、型号、凭据和请求头核对;原历史保留,是否被上游接受以原响应为准。</p>
{variants.map((variant, index) => <section key={variant.connectionId ?? index}>
<h4>{variant.model} · {protocolLabel(variant.protocol)}</h4>
<dl><dt>可续接 / 仅保留</dt><dd>{variant.applied} / {variant.retainedOnly}</dd>
<dt>请求地址</dt><dd>{variant.binding.requestUrl ?? '原记录未保存'}</dd>
<dt>凭据修订</dt><dd>{variant.binding.credentialRevision ?? '原记录未保存'}</dd>
<dt>状态范围指纹</dt><dd><code>{variant.binding.fingerprint}</code></dd></dl>
{variant.states.length ? <ul>{variant.states.map(state => <li key={state.index}>
<strong>{state.applicable ? '可续接' : '仅保留原件'} · {reasons[state.reason] ?? state.reason}</strong>
<span>原状态版本 {state.stateSchemaVersion}{state.responseId ? ' · 响应 ' + state.responseId : ''}</span>
<code>原状态 SHA256 {state.stateSha256}</code>
</li>)}</ul> : <p>本次没有待续接的原生助手状态。</p>}
</section>)}
<p>连接保持与指纹一致不代表缓存命中。缓存读写和未报告用量在本次用量记录中分别显示。</p>
</details>;
}
+4
View File
@@ -10,9 +10,11 @@ import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
import type { RuntimeFailure } from './types';
import './ModelRequestLedger.css';
import { ModelRequestDetails } from './ModelRequestDetails';
import { ModelProviderStateDetails, type ProviderStateAuditView } from './ModelProviderStateDetails';
import type { PreparedRequestMetadata } from './types';
export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; requestMetadata?: PreparedRequestMetadata;
nativeStateAudit?: ProviderStateAuditView; affinityPersistence?: { status: string; reason?: string };
upstreamResponse?: { requestId?: string | null; responseUrl?: string | null; headers?: Record<string, string> }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean;
rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal?: number; usageStatus: string; reason?: string;
taskId?: string; sessionId?: string; runId?: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean;
@@ -73,6 +75,8 @@ export function ModelRequestLedger({ connections, refreshVersion }: { connection
{value.requestMetadata && <ModelRequestDetails request={value.requestMetadata} responseHeaders={value.upstreamResponse?.headers} />}
{value.reason && <p className="mc-card-warning">{value.reason}</p>}
<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model ?? '原记录未保存'} />
<ModelProviderStateDetails audit={value.nativeStateAudit} />
{value.affinityPersistence && ['unknown', 'retained-unknown'].includes(value.affinityPersistence.status) && <p className="mc-card-warning">连接保持记录{value.affinityPersistence.status === 'unknown' ? '保存结果未知' : '暂不能解释,原件保留'};本次模型响应仍按原结果处理。{value.affinityPersistence.reason}</p>}
{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}
{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={disabled} onClick={() => void act(() => downloadArtifact(value.sessionId!, value.requestArtifactId!, 'model-request-' + value.id + '.json'))}>下载实际请求</button>}
{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + item.capability + ' · ' + item.reason).join(';')}</p>}
+8
View File
@@ -1,5 +1,6 @@
export type RoutingDecision = {
schemaVersion: number; mode: string; reason: string; selectedConnectionId: string | null; selectedBy?: string;
affinity?: { scope: string; reason: string; continued: boolean; source: string; previousConnectionId: string | null; sourceRunId: string | null; selectedConnectionId: string };
candidates: { connectionId: string; connectionName: string; model: string; connectionRevision: number; credentialRevision: number;
disposition: string; tier: string; unavailable?: string | null; requirements: string[];
capabilities: Record<string, { state: string; source: string }>;
@@ -12,11 +13,18 @@ const labels: Record<string, string> = { text: '文本', tools: '工具', stream
'revision-bound-observation': '对应连接及凭据修订的观测', 'connection-declaration': '连接声明', 'upstream-model-list': '相符上游目录', 'official-model-spec': '官方精确型号规格', 'explicit-compatibility': '用户显式兼容覆盖', 'protocol-declaration': '协议声明' };
const reasons: Record<string, string> = { 'known-capabilities': '自动适配:已知能力满足请求', 'unverified-fallback': '自动适配:未知能力后备尝试(未验证)',
'no-eligible-candidate': '自动适配:没有可用适配成员', 'explicit-selection': '显式选择:按原配置透传', 'restricted-capabilities': '按手动限制模式核对能力' };
const affinityScopes: Record<string, string> = { none: '关闭', run: '当前运行', task: '当前任务', session: '当前会话' };
const affinityReasons: Record<string, string> = { disabled: '按当前调度规则选择', 'no-saved-affinity': '此范围尚无完成响应的连接记录',
'saved-provider-scope-match': '上次连接及供应商状态范围一致', 'saved-provider-scope-changed': '连接身份或请求范围已变化',
'saved-member-not-eligible': '上次成员当前停用或不适配', 'independent-run-path': '独立诊断使用自己的运行范围', 'unknown-affinity-state': '旧连接记录无法解释,原件保留' };
export function ModelRoutingDetails({ decision }: { decision?: RoutingDecision }) {
if (!decision) return null;
return <details className="mc-routing-decision"><summary>{reasons[decision.reason] ?? '本次模型选择依据'}</summary>
<p>这是本次请求的选择记录。声明支持与实际验证分别记录;请求发出后的上游错误仍按原结果保留。</p>
{decision.affinity && <div className="mc-affinity-record"><strong>连接保持:{affinityScopes[decision.affinity.scope] ?? decision.affinity.scope} · {decision.affinity.continued ? '沿用连接' : '本次重新选择'}</strong>
<p>{affinityReasons[decision.affinity.reason] ?? decision.affinity.reason}{decision.affinity.source === 'current-run' ? ' · 当前运行的连接记录' : decision.affinity.source === 'saved-completed-response' ? ' · 上次完成响应的记录' : ''}</p>
{decision.affinity.sourceRunId && <p>来源 Run <code>{decision.affinity.sourceRunId}</code></p>}</div>}
<ul>{decision.candidates.map(candidate => <li key={candidate.connectionId}>
<strong>{candidate.connectionName} · {labels[candidate.disposition] ?? candidate.disposition}</strong>
<span>{candidate.model} · 连接修订 {candidate.connectionRevision} / 凭据修订 {candidate.credentialRevision}</span>
+2
View File
@@ -5,6 +5,7 @@ import { Modal } from './components';
import { ModelUsageDetails } from './ModelUsageDetails';
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
import { ModelRequestDetails } from './ModelRequestDetails';
import { ModelProviderStateDetails } from './ModelProviderStateDetails';
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
@@ -57,6 +58,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
</dl>
<ModelProviderStateDetails audit={plan.nativeStateAudit} />
<ModelUsageDetails key={'usage-' + plan.id} usage={plan.actualUsage} expanded />
{surface && <details className="context-tool-surface" key={plan.id}><summary>本轮工具 · 可见 {surface.entries.filter(entry => entry.visible).length} / 已登记 {surface.entries.length}</summary>
<p className="record-footnote">这是本次实际发送的工具范围。资源和权限在执行时重新核对;登记不代表本轮可用。</p>
+1
View File
@@ -210,6 +210,7 @@ export interface ContextPlan {
blocks?: { path: string; role: string | null; sha256: string; bytes: number }[];
}[] };
requestContractAudit?: { schemaVersion: number; previousPlanId: string | null; variants: PreparedRequestMetadata[] };
nativeStateAudit?: import('./ModelProviderStateDetails').ProviderStateAuditView;
requestObservation?: { schemaVersion: number; path: { kind: string; key: string }; providerHistorySha256: string;
userMessageInstances: { id: string; providerIndex: number; origin: string; sha256: string }[];
toolSurface: { generation: string; execution: string; entries: { name: string; group: string; registered: boolean; assembled: boolean; visible: boolean; reason: string; schemaSha256: string; definitionSha256: string; definitionBytes: number; generation: string }[] } | null };
+10 -1
View File
@@ -10,6 +10,7 @@ import { modelReservation,taskConsumption,verifyModelReservation } from '../../s
import { fileContinuation } from './read-continuation.mjs';
import { prefixAudit } from './prefix-audit.mjs';
import { requestContractAudit } from '../models/request-contract-audit.mjs';
import { providerStateAudit } from '../../shared/contracts/model-provider-state.mjs';
import { observeRequest, providerHistory, requestPath } from './request-observation.mjs';
import { verifyToolSurface } from './tool-surface.mjs';
import { isPassthrough } from '../../shared/contracts/model-capacity.mjs';
@@ -425,6 +426,7 @@ export class RequestPlanner {
requestArtifactId: requestArtifact.id,
prefixAudit: prefix,
...(contractAudit ? { requestContractAudit: contractAudit } : {}),
...(config.mode === 'compatible' ? { nativeStateAudit: providerStateAudit(config, messages) } : {}),
requestObservation: observation,
...(progressReminder ? { progressReminder } : {}),
...(preserve ? { contextLayout: 'stable-prefix-1', historyPolicy: 'preserve', contextTailArtifactId: tailArtifact?.id ?? null, contextTailSha256: tailArtifact?.sha256 ?? null } : {}),
@@ -499,10 +501,17 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
historyGroups(requestHistory(body));
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestContractAudit', 'requestObservation', 'progressReminder']) {
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestContractAudit', 'requestObservation', 'progressReminder', 'nativeStateAudit']) {
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
}
verifyReminderMessage(store, session, plan, body);
if (plan.nativeStateAudit) {
const run = store.owned('run', plan.runId, session.id);
const original = providerHistory(session, run).slice(0, plan.originalMessages);
const retained = historyGroups(original).filter(group => plan.retainedGroups.includes(group.index)).flatMap(group => group.messages);
const expected = providerStateAudit({ ...run.model, modelRouting: run.model.routing }, retained);
if (JSON.stringify(expected) !== JSON.stringify(plan.nativeStateAudit)) throw new Error('原生历史状态与冻结来源或供应商身份不匹配。');
}
if (plan.requestObservation) {
const run = store.owned('run', plan.runId, session.id);
const expected = observeRequest(store, session, run, providerHistory(session, run).slice(0, plan.originalMessages), plan.requestObservation.toolSurface);
+44
View File
@@ -0,0 +1,44 @@
import { providerStateBinding } from '../../shared/contracts/model-provider-state.mjs';
export const affinityScope = routing => routing.sticky === false ? 'none' : routing.affinityScope ?? 'run';
const memberScope = member => providerStateBinding({ ...member, modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision });
export function savedAffinity(store, routing, plan) {
const scope = affinityScope(routing);
if (!['task', 'session'].includes(scope) || !plan?.sessionId || !plan?.runId) return { scope, record: null };
const session = store.session(plan.sessionId), run = store.core.run.get(plan.runId);
if (run?.purpose === 'diagnostic' || !run || run.sessionId !== session.id) return { scope: 'run', record: null, reason: 'independent-run-path' };
const scopeId = scope === 'task' ? plan.taskId : session.id;
const original = session.modelAffinity;
if (original != null && (original.schemaVersion !== 1 || !Array.isArray(original.bindings)
|| original.bindings.some(value => !value || typeof value !== 'object' || Array.isArray(value))))
return { scope, scopeId, session, record: null, reason: 'unknown-affinity-state', retainedUnknown: true };
const record = original?.bindings.find(value => value.scope === scope && value.scopeId === scopeId
&& value.routingType === routing.type && value.routingId === routing.id) ?? null;
return { scope, scopeId, session, record };
}
export function affinityPreference(store, routing, plan, members) {
const saved = savedAffinity(store, routing, plan), record = saved.record;
if (!record) return { ...saved, preferredId: null, reason: saved.reason ?? (saved.scope === 'none' ? 'disabled' : 'no-saved-affinity') };
const member = members.find(value => value.id === record.connectionId);
return member && memberScope(member).fingerprint === record.providerScopeFingerprint
? { ...saved, preferredId: member.id, reason: 'saved-provider-scope-match' }
: { ...saved, preferredId: null, reason: member ? 'saved-provider-scope-changed' : 'saved-member-not-eligible' };
}
export function rememberAffinity(store, routing, member, plan) {
const saved = savedAffinity(store, routing, plan);
if (!saved.session || !saved.scopeId) return;
if (saved.retainedUnknown) return { status: 'retained-unknown', reason: saved.reason };
const record = { scope: saved.scope, scopeId: saved.scopeId, routingType: routing.type, routingId: routing.id,
connectionId: member.id, model: member.model, protocol: member.protocol ?? 'chat-completions',
providerScopeFingerprint: memberScope(member).fingerprint, sourceRunId: plan.runId,
lastRequestId: plan.id, updatedAt: new Date().toISOString(), source: 'completed-model-response' };
const original = saved.session.modelAffinity ?? { schemaVersion: 1, bindings: [] };
saved.session.modelAffinity = { ...original, schemaVersion: 1, bindings: [...original.bindings.filter(value => !(value.scope === record.scope && value.scopeId === record.scopeId
&& value.routingType === record.routingType && value.routingId === record.routingId)), record] };
store.save(saved.session, { type: 'model.affinity_recorded', detail: { scope: record.scope, sourceRunId: plan.runId, connectionId: member.id,
previous: saved.record, current: record } });
return { status: 'recorded', scope: record.scope, sourceRunId: plan.runId };
}
+21 -6
View File
@@ -19,6 +19,7 @@ import { capacitySettings, routedCapacity } from '../../shared/contracts/model-c
import { ModelRequestLedger } from './request-ledger.mjs';
import { modelOverrideSettings, resolveModelSpecification } from '../../shared/contracts/official-model-registry.mjs';
import { defaultMessagesAuth, effectiveRequestContract, requestContractSettings, requestCredentialIdentity } from '../../shared/contracts/model-request-contract.mjs';
import { affinityScope, affinityPreference, rememberAffinity } from './model-affinity.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -325,8 +326,10 @@ export class ModelHub {
seen.add(value.connectionId); return { connectionId: value.connectionId, weight: bounded(value.weight, 1, 1, 10) };
});
if (!['round-robin', 'weighted'].includes(input.strategy || 'round-robin')) throw error('请选择轮询或权重策略。');
const scope = input.affinityScope ?? (previous ? previous.affinityScope ?? 'run' : 'session');
if (!['none', 'run', 'task', 'session'].includes(scope)) throw error('请选择关闭、当前运行、当前任务或当前会话的连接保持范围。');
const value = { id: previous?.id ?? randomUUID(), name: label(input.name, ceiling(this.store, 100)), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
affinityScope: scope, maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
}
select(input, config = null) {
@@ -363,7 +366,7 @@ export class ModelHub {
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
...routedCapacity(config, members),
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, affinityScope: pool?.affinityScope ?? 'run', maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
}
available(member) {
const current = this.connections().find(value => value.id === member.id);
@@ -372,7 +375,7 @@ export class ModelHub {
const health = this.health.get(this.identity(member));
return unrestricted(this.store) || (!member.requiresKey || !!this.credential(member)?.key) && !health?.blocked && !(health?.cooldownUntil > Date.now());
}
async acquire(routing, runId, excluded, signal, deadline, requirements = [], { probe = false } = {}) {
async acquire(routing, runId, excluded, signal, deadline, requirements = [], { probe = false, plan = null } = {}) {
if (!unrestricted(this.store) && this.waiting >= 100) throw error('模型请求队列已满,请稍后继续任务。');
this.waiting++;
try {
@@ -386,17 +389,21 @@ export class ModelHub {
: '模型池暂时没有可用成员;已完成操作保留,请核对凭据、停用状态和冷却时间。'), { routingDecision: decision });
const ready = healthy.filter(value => unrestricted(this.store) || (value.concurrency === 0 || (this.leases.get(value.id) ?? 0) < value.concurrency));
if (ready.length) {
const remembered = routing.sticky && this.sticky.get(runId);
const affinity = affinityPreference(this.store, routing, plan, ready);
const remembered = affinityScope(routing) !== 'none' && (this.sticky.get(runId) ?? affinity.preferredId);
let selected = ready.find(value => value.id === remembered);
if (!selected) {
const weighted = ready.flatMap(value => Array(routing.strategy === 'weighted' ? value.weight : 1).fill(value));
const cursor = this.cursors.get(routing.id) ?? 0; selected = weighted[cursor % weighted.length]; this.cursors.set(routing.id, cursor + 1);
}
this.leases.set(selected.id, (this.leases.get(selected.id) ?? 0) + 1);
this.sticky.set(runId, selected.id); if (this.sticky.size > 1000) this.sticky.delete(this.sticky.keys().next().value);
if (affinityScope(routing) !== 'none') this.sticky.set(runId, selected.id);
let released = false;
decision.selectedConnectionId = selected.id;
decision.selectedBy = remembered === selected.id ? 'sticky' : routing.strategy;
decision.affinity = { scope: affinity.scope, reason: affinity.reason, previousConnectionId: affinity.record?.connectionId ?? null,
sourceRunId: affinity.record?.sourceRunId ?? null, selectedConnectionId: selected.id,
continued: remembered === selected.id, source: affinity.preferredId === selected.id ? 'saved-completed-response' : remembered === selected.id ? 'current-run' : 'routing-strategy' };
decision.candidates.find(value => value.connectionId === selected.id).disposition = 'selected';
return { member: selected, decision, release: () => { if (!released) { released = true; this.leases.set(selected.id, Math.max(0, (this.leases.get(selected.id) ?? 0) - 1)); } } };
}
@@ -420,7 +427,7 @@ export class ModelHub {
signal?.throwIfAborted();
beforeDispatch?.({previousFailure:lastError?.diagnostic});
let lease;
try { lease = await this.acquire(routing, runId, excluded, signal, deadline, requirements, { probe: config.capabilityProbe === true }); }
try { lease = await this.acquire(routing, runId, excluded, signal, deadline, requirements, { probe: config.capabilityProbe === true, plan }); }
catch (cause) {
if (!lastError && cause.routingDecision) {
this.addAttempt({ id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
@@ -439,6 +446,8 @@ export class ModelHub {
requestBytes: Buffer.byteLength(bytes, 'utf8'), requirements, routingDecision: lease.decision,
rejections: lease.decision.candidates.filter(value => value.disposition === 'excluded').flatMap(value => value.reasons.map(reason => ({ connectionId: value.connectionId, connectionName: value.connectionName, ...reason }))),
requestSha256: createHash('sha256').update(bytes).digest('hex'), usage: null, usageStatus: 'unknown' };
if (plan?.nativeStateAudit) attempt.nativeStateAudit = { source: 'frozen-plan-provider-scope-for-selected-request', requestPlanId: plan.id,
...structuredClone(plan.nativeStateAudit.variants.find(value => value.connectionId === member.id) ?? {}) };
try {
if (plan?.sessionId) {
const session = this.store.session(plan.sessionId), run = this.store.owned('run', plan.runId, session.id);
@@ -490,6 +499,12 @@ export class ModelHub {
attempt.status = 'completed'; attempt.usage = result.usage ?? attempt.usage; attempt.usageStatus = attempt.usage ? 'reported' : 'unknown';
if (result.compatibility?.length) attempt.compatibility = result.compatibility;
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
if (!config.capabilityProbe) {
// Continuity is optional metadata. A persistence failure cannot turn a
// completed upstream response into a failed/replayed model request.
try { const saved = rememberAffinity(this.store, routing, member, plan); if (saved) attempt.affinityPersistence = saved; }
catch (cause) { attempt.affinityPersistence = { status: 'unknown', reason: this.provider.redact(cause.message) }; }
}
return result;
} catch (cause) {
const diagnostic = cause.diagnostic;
+8 -6
View File
@@ -1,6 +1,7 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { withTokenAccounting } from '../../shared/contracts/model-usage.mjs';
import { bindProviderState } from '../../shared/contracts/model-provider-state.mjs';
export const protocolFailure = (message, kind = 'protocol', extra = null) => new ModelRequestError({ kind, source: 'model_connection', origin: 'local', stage: 'model_request',
title: '模型响应未通过完整性核对', message, retryable: false, occurredAt: new Date().toISOString(), ...(extra ? extra : {}) });
@@ -94,18 +95,19 @@ export function normalizeProtocolResponse(config, value) {
if ((value.stop_reason === 'tool_use') !== (calls.length > 0)) throw protocolFailure('Messages 停止原因与工具内容不一致。');
if (!calls.length && !texts.join('').trim()) throw protocolFailure('Messages 返回为空:没有可用文本或工具调用。原响应及用量已保留,请核对供应商响应。');
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
providerState: { protocol: 'anthropic-messages', endpoint: config.baseUrl, model: config.model, responseId: value.id, content: structuredClone(value.content) } },
providerState: bindProviderState(config, { protocol: 'anthropic-messages', endpoint: config.baseUrl, model: config.model, responseId: value.id, content: structuredClone(value.content) }) },
finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: reportedUsage(config, value) };
}
if (config.protocol !== 'responses') {
const received = value?.choices?.[0]?.message;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return { ...value, usage: reportedUsage(config, value) };
const normalized = structuredClone(value), target = normalized?.choices?.[0]?.message;
if (target) { delete target.providerState; delete target.providerInput; }
if (received?.reasoning_content === undefined || received.reasoning_content === null) return { ...normalized, usage: reportedUsage(config, value) };
if (typeof received.reasoning_content !== 'string') throw protocolFailure('Chat reasoning_content必须为字符串,原响应未用于执行工具。');
const normalized = structuredClone(value), target = normalized.choices[0].message;
normalized.usage = reportedUsage(config, value);
delete target.reasoning_content;
target.providerState = { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content };
target.providerState = bindProviderState(config, { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content });
return normalized;
}
if (value.status === 'incomplete' && value.incomplete_details?.reason === 'max_output_tokens') throw outputTruncatedFailure();
@@ -127,5 +129,5 @@ export function normalizeProtocolResponse(config, value) {
}
const usage = reportedUsage(config, value);
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
providerState: { protocol: 'responses', endpoint: config.baseUrl, model: config.model, responseId: value.id ?? null, items: value.output } }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage };
providerState: bindProviderState(config, { protocol: 'responses', endpoint: config.baseUrl, model: config.model, responseId: value.id ?? null, items: structuredClone(value.output) }) }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage };
}
+38 -12
View File
@@ -1,4 +1,5 @@
import { isPassthrough, messagesOutputSetting } from './model-capacity.mjs';
import { providerStateCompatibility } from './model-provider-state.mjs';
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const fail = message => { throw new Error('Messages 请求未发送:' + message); };
@@ -6,9 +7,12 @@ function contentBlocks(content) {
if (typeof content === 'string') return content ? [{ type: 'text', text: content }] : [];
if (!Array.isArray(content)) fail('消息内容必须为文本或已接入的内容块。');
return content.map(part => {
if (['text', 'input_text', 'output_text'].includes(part.type) && typeof part.text === 'string') return { type: 'text', text: part.text };
if (['text', 'input_text', 'output_text'].includes(part.type) && typeof part.text === 'string') return { ...structuredClone(part), type: 'text' };
const url = part.type === 'image_url' ? part.image_url?.url : part.type === 'input_image' ? part.image_url : null;
if (typeof url === 'string' && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(url)) return { type: 'image', source: { type: 'base64', media_type: 'image/png', data: url.slice(22) } };
if (typeof url === 'string' && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(url)) {
const { image_url, ...metadata } = structuredClone(part);
return { ...metadata, type: 'image', source: { type: 'base64', media_type: 'image/png', data: url.slice(22) } };
}
fail('未接入的输入内容块 ' + String(part?.type ?? '未知') + '。');
});
}
@@ -23,14 +27,23 @@ export function messagesBody(config, messages, tools, native) {
else wire.push({ role, content });
};
for (const message of messages) {
if (message.providerInput?.protocol === 'anthropic-messages') {
const original = message.providerInput;
if (message.role === 'system') system.push(...structuredClone(original.content));
else if (message.role === 'tool') append('user', [structuredClone(original.toolResult)]);
else append(message.role, structuredClone(original.content));
continue;
}
if (message.role === 'system') { system.push(...contentBlocks(message.content)); continue; }
if (message.role === 'tool') {
if (typeof message.tool_call_id !== 'string' || !message.tool_call_id || typeof message.content !== 'string') fail('工具结果缺少原调用身份或文本。');
append('user', [{ type: 'tool_result', tool_use_id: message.tool_call_id, content: message.content }]);
append('user', [{ type: 'tool_result', tool_use_id: message.tool_call_id, content: message.content,
...(message.cache_control !== undefined ? { cache_control: structuredClone(message.cache_control) } : {}),
...(message.is_error !== undefined ? { is_error: message.is_error } : {}) }]);
} else if (message.role === 'user') append('user', contentBlocks(message.content));
else if (message.role === 'assistant') {
const state = message.providerState;
if (state?.protocol === 'anthropic-messages' && state.endpoint === config.baseUrl && state.model === config.model) {
if (state?.protocol === 'anthropic-messages' && providerStateCompatibility(config, state).applicable) {
if (!Array.isArray(state.content)) fail('原生助手历史格式无效。');
append('assistant', structuredClone(state.content));
continue;
@@ -46,8 +59,10 @@ export function messagesBody(config, messages, tools, native) {
}
if (system.some(block => block.type !== 'text')) fail('系统消息只支持文本。');
const definitions = (tools ?? []).map(tool => {
if (typeof tool.name === 'string' && object(tool.input_schema)) return structuredClone(tool);
if (tool.type !== 'function' || !tool.function?.name || !object(tool.function.parameters)) fail('工具定义格式无效。');
return { name: tool.function.name, ...(tool.function.description ? { description: tool.function.description } : {}), input_schema: tool.function.parameters };
const { type, function: definition, ...metadata } = structuredClone(tool), { parameters, ...fields } = definition;
return { ...fields, ...metadata, name: definition.name, input_schema: parameters };
});
return { model: config.model, ...(system.length ? { system } : {}), messages: wire,
...(definitions.length ? { tools: definitions, tool_choice: { type: 'auto' } } : {}),
@@ -61,14 +76,25 @@ export function messagesBody(config, messages, tools, native) {
export function messagesHistory(body) {
const history = [];
if (typeof body.system === 'string') history.push({ role: 'system', content: body.system });
else for (const part of body.system ?? []) history.push({ role: 'system', content: part.text });
else if (body.system?.length) history.push({ role: 'system', content: body.system.filter(part => part.type === 'text').map(part => part.text).join(''),
providerInput: { protocol: 'anthropic-messages', content: structuredClone(body.system) } });
for (const message of body.messages) {
if (!Array.isArray(message.content)) { history.push(message); continue; }
const blocks = message.content, text = blocks.filter(block => block.type === 'text').map(block => block.text).join('');
const calls = blocks.filter(block => block.type === 'tool_use').map(block => ({ id: block.id, type: 'function', function: { name: block.name, arguments: JSON.stringify(block.input) } }));
const results = blocks.filter(block => block.type === 'tool_result');
for (const result of results) history.push({ role: 'tool', tool_call_id: result.tool_use_id, content: result.content });
if (message.role === 'assistant' || text || blocks.some(block => block.type === 'image')) history.push({ role: message.role, content: text, ...(calls.length ? { tool_calls: calls } : {}) });
if (!Array.isArray(message.content)) { history.push(structuredClone(message)); continue; }
let pending = [];
const flush = () => {
if (!pending.length) return;
const text = pending.filter(block => block.type === 'text').map(block => block.text).join('');
const calls = pending.filter(block => block.type === 'tool_use').map(block => ({ id: block.id, type: 'function', function: { name: block.name, arguments: JSON.stringify(block.input) } }));
history.push({ role: message.role, content: text, ...(calls.length ? { tool_calls: calls } : {}),
providerInput: { protocol: 'anthropic-messages', content: structuredClone(pending) } });
pending = [];
};
for (const block of message.content) {
if (block.type !== 'tool_result') { pending.push(block); continue; }
flush(); history.push({ role: 'tool', tool_call_id: block.tool_use_id, content: typeof block.content === 'string' ? block.content : JSON.stringify(block.content),
providerInput: { protocol: 'anthropic-messages', toolResult: structuredClone(block) } });
}
flush();
}
return history;
}
@@ -0,0 +1,46 @@
import { createHash } from 'node:crypto';
import { modelProtocol } from './model-capabilities.mjs';
import { modelRequestUrl } from './model-endpoint.mjs';
import { requestHeaders } from './model-request-contract.mjs';
const sha = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
export function providerStateBinding(config) {
const protocol = modelProtocol(config.protocol), connection = { ...config, protocol };
const identity = { protocol, endpoint: config.baseUrl ?? null, requestUrl: config.baseUrl ? modelRequestUrl(connection) : null,
model: config.model ?? null, connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null,
headers: [...requestHeaders(connection, '{{credential}}')] };
return { schemaVersion: 1, ...identity, fingerprint: sha(identity), representation: 'provider-state-scope-credential-template-v1' };
}
export const bindProviderState = (config, payload) => ({ ...payload, schemaVersion: 2, binding: providerStateBinding(config) });
export function providerStateCompatibility(config, state) {
if (!state) return { applicable: false, reason: 'no-state' };
const binding = providerStateBinding(config);
if (state.schemaVersion !== undefined && ![1, 2].includes(state.schemaVersion)) return { applicable: false, reason: 'unknown-state-schema', binding };
if (state.schemaVersion === 2) return state.binding?.fingerprint === binding.fingerprint
? { applicable: true, reason: 'same-provider-scope', binding }
: { applicable: false, reason: 'provider-scope-changed', binding, previousFingerprint: state.binding?.fingerprint ?? null };
if (state.protocol !== binding.protocol || state.endpoint !== binding.endpoint || state.model !== binding.model)
return { applicable: false, reason: 'legacy-provider-changed', binding };
if (state.protocol === 'chat-completions') return state.connectionId === binding.connectionId && state.credentialRevision === binding.credentialRevision
? { applicable: true, reason: 'legacy-chat-identity-match', binding }
: { applicable: false, reason: 'legacy-provider-changed', binding };
// Original unbound direct-protocol histories remain readable. A named current
// connection cannot infer authentication/version scope from an old bare state.
return binding.connectionId === null && binding.credentialRevision === null
? { applicable: true, reason: 'legacy-direct-protocol', binding }
: { applicable: false, reason: 'legacy-identity-unavailable', binding };
}
export function providerStateAudit(config, messages) {
const variants = config.modelRouting?.members ?? [config];
return { schemaVersion: 1, source: 'frozen-history-provider-scope', variants: variants.map(member => {
const route = config.modelRouting ? { ...config, ...member, modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision } : config;
const states = messages.flatMap(message => message.providerState ? [{ protocol: message.providerState.protocol,
responseId: message.providerState.responseId ?? null, stateSchemaVersion: message.providerState.schemaVersion ?? 1,
...providerStateCompatibility(route, message.providerState), stateSha256: sha(message.providerState) }] : []);
return { connectionId: route.modelConnectionId ?? null, model: route.model, protocol: modelProtocol(route.protocol),
applied: states.filter(value => value.applicable).length, retainedOnly: states.filter(value => !value.applicable).length,
states: states.map(({ binding, ...value }, index) => ({ index, ...value })), binding: providerStateBinding(route) };
}) };
}
+12 -6
View File
@@ -3,6 +3,7 @@ import { modelProtocol } from './model-capabilities.mjs';
import { nativeParameterSettings } from './native-parameters.mjs';
import { messagesBody, messagesHistory } from './anthropic-messages.mjs';
import { isPassthrough } from './model-capacity.mjs';
import { providerStateCompatibility } from './model-provider-state.mjs';
function wireBody(config, messages, tools) {
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
@@ -10,10 +11,9 @@ function wireBody(config, messages, tools) {
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, reasoning_content, ...message }) => {
const cleanMessages = messages.map(({ providerState, providerInput, reasoning_content, ...message }) => {
if (protocol === 'chat-completions' && message.role === 'assistant' && providerState?.protocol === 'chat-completions'
&& providerState.endpoint === config.baseUrl && providerState.model === config.model
&& providerState.connectionId === (config.modelConnectionId ?? null) && providerState.credentialRevision === (config.modelCredentialRevision ?? null)
&& providerStateCompatibility(config, providerState).applicable
&& typeof providerState.reasoningContent === 'string') return { ...message, reasoning_content: providerState.reasoningContent };
return message;
});
@@ -23,19 +23,25 @@ function wireBody(config, messages, tools) {
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;
if (message.providerState?.protocol === 'responses' && providerStateCompatibility(config, message.providerState).applicable) return structuredClone(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 })),
return { model: config.model, input, tools: (tools ?? []).map(tool => tool.function
? { ...structuredClone(tool.function), ...Object.fromEntries(Object.entries(structuredClone(tool)).filter(([key]) => key !== 'function')), strict: tool.strict ?? tool.function.strict ?? false }
: structuredClone(tool)),
tool_choice: 'auto', ...(!isPassthrough(config) ? { 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?.length && (config.capacityMode === 'model' || members.some(member => member.protocol && member.protocol !== 'chat-completions' || member.streaming === true || member.nativeParameters || member.outputTokenField))) {
// Even plain Chat members need separate projections when an opaque history
// exists. Replacing only body.model would reuse the first member's reasoning
// on another connection, credential or model.
if (members?.length && (config.capacityMode === 'model' || messages.some(message => message.providerState)
|| members.some(member => member.protocol && member.protocol !== 'chat-completions' || 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,
modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision,
+4
View File
@@ -1,5 +1,9 @@
# Agent Workbench:核心代理能力研究与产品计划
M2 I09/I11阶段1–4完成:来源71f18055/核心9e1feeeb/界面ee97aaae,见[验收](docs/QA-M2-NATIVE-CACHE-STATE.md)。880输入/29编译/74runtime、两端各8组/10图、原metadata/cipher/snapshot/history exact,5126原件已封存;source-5为16/16,首127/129与两文件26/26按SHA分别保留。阶段5文档/普通GitAtlas增量推送收尾,下一I27/I28 CI,后续M3实际schema2迁移增量及新处理器结果后回退,不删除新账本或移除原保持守卫。正式/真实Key/模型/旧实验/历史unknown不动。
M2第五批I09/I11已从bdfeb29c干净基线开始,见[原生缓存与状态计划](docs/M2-NATIVE-CACHE-STATE-PLAN.md):保留Messages块/工具注解及原生历史,配置会话/Task/Run亲和,状态按实际协议/地址/型号/凭据/版本身份核对;旧历史不改写,亲和/同指纹不当作缓存命中。随后CI及M3真实迁移增量/结果后回退。无真实模型/Key/正式写入/委派,历史unknown保持。
I14/I12阶段1–4完成:来源337d1bc9/核心f95507ab/界面26472d28,最后相关38/38和首候选143/143后端输入未变;最终871输入/29编译/74runtime、网页与实际Electron各8组/8图/三配色/1280及390,原metadata/cipher/存储快照exact、原I13/I15原件只读一致、自有进程/已知监听0。原失败与验收器错误保持。阶段5已完成封存/回顾/授权普通GitAtlas增量推送,源码与验收04c0556c远端逐SHA一致,回执及完成接续最后提交再核对,见[请求契约计划](docs/M2-REQUEST-CONTRACT-PLAN.md)和[验收](docs/QA-M2-REQUEST-CONTRACT.md)。下一I09/I11/CI、M3真实迁移增量及新处理器结果后回退,真实收益和Purge unknown保持。
M2第四批I14/I12从c7d1ad5e干净/远端一致基线开始,见[请求契约计划](docs/M2-REQUEST-CONTRACT-PLAN.md)。已实际取得官方OpenAI overview与Anthropic版本/头说明,先固定来源和旧/新默认分离,再请求版本/头/路径/快照与去凭据指纹。I15原根只读,0真实Key/模型/正式写入,不委派或重启;I09/I11/CI/M3与历史unknown保持。
+113
View File
@@ -0,0 +1,113 @@
{
"schemaVersion": 1,
"baseline": "bdfeb29c85b3231bfd7bc24b8b5f49d40a3beebf",
"sources": [
{
"id": "openai-conversation-state",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/conversation-state",
"checkedAt": "2026-11-07",
"file": "sources/openai-conversation-state.md",
"sha256": "8a62162c2ef6ff7e94dfdad5ba06f417f5a6c00ea6521e6466d462ff2fcd9b96",
"bytes": 24788,
"captureSha256": "df7776f8ac54a84b55cbc0d42bc2b80192428921d96b2e272d21754e2f3d5f8b",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true
},
{
"id": "openai-prompt-caching",
"provider": "openai",
"url": "https://developers.openai.com/api/docs/guides/prompt-caching",
"checkedAt": "2026-11-07",
"file": "sources/openai-prompt-caching.md",
"sha256": "01e57dacc2e5c0fb881b2d1909649983e9e327a5d6c17a98bb1183ee00e9d334",
"bytes": 56425,
"captureSha256": "ed312ad7e34d4de7f5861317481ae82b1bc3b9a1ae78d525c916a0d94231d522",
"representation": "official-docs-mcp-markdown-utf8",
"scope": "complete-captured-page",
"reusedReadOnly": true
},
{
"id": "claude-build-with-claude__prompt-caching",
"provider": "anthropic",
"url": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
"checkedAt": "2026-11-06",
"sha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"file": "../official-model-registry/sources/claude-build-with-claude-prompt-caching.md",
"originalSha256": "ff35232788f3f7fbd0f9aae002351567a9ea8e68e5b749069d96dab52882747d",
"representation": "extracted-official-markdown",
"scope": "complete-captured-source",
"bytes": 164465,
"reusedReadOnly": true
},
{
"id": "deepseek-create",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-chat-completion",
"checkedAt": "2026-11-06",
"sha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"file": "../official-model-registry/sources/deepseek-create.body",
"originalSha256": "b43ca950bd04ae7f6f537b42e6cb729f543d942dcd848ec43ad4e9bfe059fe1f",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 129498,
"reusedReadOnly": true
},
{
"id": "deepseek-thinking",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/thinking_mode",
"checkedAt": "2026-11-06",
"sha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"file": "../official-model-registry/sources/deepseek-thinking.body",
"originalSha256": "42151b5f86827bff663a61693080a61cdbf99074dee94af756c9fce855baa7cd",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 117778,
"reusedReadOnly": true
},
{
"id": "deepseek-cache",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/guides/kv_cache",
"checkedAt": "2026-11-06",
"sha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"file": "../official-model-registry/sources/deepseek-cache.body",
"originalSha256": "061c0c7055ceb96d0a522ae1829ff5f7126ff08f26af217643e371abb740a081",
"representation": "received-html-bytes",
"scope": "complete-captured-source",
"bytes": 35850,
"reusedReadOnly": true
},
{
"id": "deepseek-response",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-response.md",
"checkedAt": "2026-11-07",
"sha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"file": "../official-model-registry/sources/deepseek-response.md",
"originalSha256": "5e56e45d25db47f2b6966bbb0b2471d324035c33f0c8f81eaaf8fc444e6869da",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 33870,
"reusedReadOnly": true
},
{
"id": "deepseek-message",
"provider": "deepseek",
"url": "https://api-docs.deepseek.com/api/create-message.md",
"checkedAt": "2026-11-07",
"sha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"file": "../official-model-registry/sources/deepseek-message.md",
"originalSha256": "46b31d10f429910bf93ea2166537fb803cd2f49f7c5b4ad2ee4f08257b2e17e8",
"representation": "received-document-bytes",
"scope": "complete-captured-source",
"bytes": 51134,
"reusedReadOnly": true
}
],
"newRealModelRequests": 0,
"previousEvidenceRootsWritten": 0,
"scope": "request-block-fidelity-provider-state-and-affinity-contracts-not-live-cache-benefit"
}
@@ -0,0 +1,795 @@
# Conversation state
OpenAI provides a few ways to manage conversation state, which is important for preserving information across multiple messages or turns in a conversation.
When troubleshooting cases where GPT-5.5 treats an intermediate update as
the final answer, verify your integration preserves the assistant message
`phase` field correctly. See [Phase
parameter](https://developers.openai.com/api/docs/guides/reasoning#phase-parameter) for details.
## Manually manage conversation state
While each text generation request is independent and stateless, you can still implement **multi-turn conversations** by providing additional messages as parameters to your text generation request. Consider a knock-knock joke:
Manually construct a past conversation
```javascript
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input: [
{ role: "user", content: "knock knock." },
{ role: "assistant", content: "Who's there?" },
{ role: "user", content: "Orange." },
],
});
console.log(response.output_text);
```
```python
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input=[
{"role": "user", "content": "knock knock."},
{"role": "assistant", "content": "Who's there?"},
{"role": "user", "content": "Orange."},
],
)
print(response.output_text)
```
```go
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("Knock knock.", responses.EasyInputMessageRoleUser),
responses.ResponseInputItemParamOfMessage("Who's there?", responses.EasyInputMessageRoleAssistant),
responses.ResponseInputItemParamOfMessage("Orange.", responses.EasyInputMessageRoleUser),
},
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
```
```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Knock knock.")
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.ASSISTANT)
.content("Who's there?")
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Orange.")
.build())))
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
```
```csharp
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult response = await client.CreateResponseAsync(
"gpt-6-astra",
[
ResponseItem.CreateUserMessageItem("Knock knock."),
ResponseItem.CreateAssistantMessageItem("Who's there?"),
ResponseItem.CreateUserMessageItem("Orange."),
]
);
Console.WriteLine(response.GetOutputText());
```
```ruby
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: [
{
role: :user,
content: "Knock knock."
},
{
role: :assistant,
content: "Who's there?"
},
{
role: :user,
content: "Orange."
}
]
)
puts(response.output_text)
```
By using alternating `user` and `assistant` messages, you capture the previous state of a conversation in one request to the model.
To manually share context across generated responses, include the model's previous response output as input, and append that input to your next request.
For stateless reasoning-model requests, preserve every item in the response's `output` array. The Responses API returns encrypted reasoning items by default. Replaying the complete output keeps reasoning items and assistant `phase` values intact. Models that support persisted reasoning can use `reasoning.context: "all_turns"` to render the available reasoning from earlier turns into the next sample. See [preserve reasoning across calls](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls).
In the following example, we ask the model to tell a joke, followed by a request for another joke. Appending previous responses to new requests in this way helps ensure conversations feel natural and retain the context of previous interactions.
Manually manage conversation state with the Responses API.
```javascript
import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
const openai = new OpenAI();
let history = [
{
role: "user",
content: "tell me a joke",
},
];
const response = await openai.responses.create({
model: "gpt-6-astra",
input: history,
store: false,
});
console.log(response.output_text);
// Add replayable output items, including reasoning items, to the history
history.push(...toResponseInputItems(response.output));
history.push({
role: "user",
content: "tell me another",
});
const secondResponse = await openai.responses.create({
model: "gpt-6-astra",
input: history,
store: false,
});
console.log(secondResponse.output_text);
```
```python
from openai import OpenAI
client = OpenAI()
history = [{"role": "user", "content": "tell me a joke"}]
response = client.responses.create(
model="gpt-6-astra",
input=history,
store=False,
)
print(response.output_text)
# Add all response output items, including encrypted reasoning items, to the conversation
history += response.output
history.append({"role": "user", "content": "tell me another"})
second_response = client.responses.create(
model="gpt-6-astra",
input=history,
store=False,
)
print(second_response.output_text)
```
```go
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
history := responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("tell me a joke", responses.EasyInputMessageRoleUser),
}
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},
Store: openai.Bool(false),
})
if err != nil {
panic(err)
}
fmt.Println(first.OutputText())
history = append(history, outputAsInput(first.Output)...)
history = append(history, responses.ResponseInputItemParamOfMessage("tell me another", responses.EasyInputMessageRoleUser))
second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},
Store: openai.Bool(false),
})
if err != nil {
panic(err)
}
fmt.Println(second.OutputText())
}
func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {
input := make([]responses.ResponseInputItemUnionParam, 0, len(output))
for _, item := range output {
var converted responses.ResponseInputItemUnion
if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
panic(err)
}
input = append(input, converted.ToParam())
}
return input
}
```
```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;
var history = new ArrayList<ResponseInputItem>();
history.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Tell me a joke.")
.build()));
var first =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(history)
.store(false)
.build());
first.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
first.output().stream()
.map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
.forEach(history::add);
history.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Tell me another.")
.build()));
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(history)
.store(false)
.build())
.output()
.stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
```
```csharp
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
List<ResponseItem> history =
[
ResponseItem.CreateUserMessageItem("Tell me a joke."),
];
CreateResponseOptions options = new("gpt-6-astra", history)
{
StoredOutputEnabled = false,
IncludedProperties =
{
IncludedResponseProperty.ReasoningEncryptedContent,
},
};
ResponseResult first = await client.CreateResponseAsync(options);
Console.WriteLine(first.GetOutputText());
history.AddRange(first.OutputItems);
history.Add(ResponseItem.CreateUserMessageItem("Tell me another."));
options = new("gpt-6-astra", history)
{
StoredOutputEnabled = false,
IncludedProperties =
{
IncludedResponseProperty.ReasoningEncryptedContent,
},
};
ResponseResult second = await client.CreateResponseAsync(options);
Console.WriteLine(second.GetOutputText());
```
```ruby
require "openai"
client = OpenAI::Client.new
history = [
{
role: :user,
content: "Tell me a joke."
}
]
first = client.responses.create(
model: "gpt-6-astra",
input: history,
store: false
)
puts(first.output_text)
history.concat(first.output)
history << {
role: :user,
content: "Tell me another."
}
second = client.responses.create(
model: "gpt-6-astra",
input: history,
store: false
)
puts(second.output_text)
```
## OpenAI APIs for conversation state
Our APIs make it easier to manage conversation state automatically, so you don't have to pass inputs manually with each turn of a conversation.
### Using the Conversations API
The [Conversations API](https://developers.openai.com/api/reference/resources/conversations/methods/create) works with the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) to persist conversation state as a long-running object with its own durable identifier. After creating a conversation object, you can keep using it across sessions, devices, or jobs.
Conversations store items, which can be messages, tool calls, tool outputs, and other data.
Create a conversation
```javascript
const conversation = await client.conversations.create();
```
```python
conversation = openai.conversations.create()
```
```go
conversation, err := client.Conversations.New(context.Background(), conversations.ConversationNewParams{})
if err != nil {
panic(err)
}
```
```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
var conversation = client.conversations().create();
System.out.println(conversation.id());
```
```ruby
conversation = client.conversations.create
```
In a multi-turn interaction, you can pass the `conversation` into subsequent responses to persist state and share context across subsequent responses, rather than having to chain multiple response items together.
Manage conversation state with Conversations and Responses APIs
```javascript
const response = await client.responses.create({
model: "gpt-6-astra",
input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
conversation: conversation.id,
});
console.log(response.output_text);
```
```python
response = openai.responses.create(
model="gpt-6-astra",
input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],
conversation=conversation.id,
)
```
```go
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Conversation: responses.ResponseNewParamsConversationUnion{
OfString: openai.String(conversation.ID),
},
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What are the five Ds of dodgeball?"),
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
```
```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
var conversation = client.conversations().create();
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.conversation(conversation.id())
.input("What are the five Ds of dodgeball?")
.build());
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
```
```ruby
response = client.responses.create(
model: "gpt-6-astra",
conversation: conversation.id,
input: "What are the five Ds of dodgeball?"
)
puts(response.output_text)
```
### Passing context from the previous response
Another way to manage conversation state is to share context across generated responses with the `previous_response_id` parameter. This parameter lets you chain responses and create a threaded conversation.
Chain responses across turns by passing the previous response ID
```javascript
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input: "tell me a joke",
store: true,
});
console.log(response.output_text);
const secondResponse = await openai.responses.create({
model: "gpt-6-astra",
previous_response_id: response.id,
input: [{ role: "user", content: "explain why this is funny." }],
store: true,
});
console.log(secondResponse.output_text);
```
```python
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="tell me a joke",
)
print(response.output_text)
second_response = client.responses.create(
model="gpt-6-astra",
previous_response_id=response.id,
input=[{"role": "user", "content": "explain why this is funny."}],
)
print(second_response.output_text)
```
```go
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Tell me a joke."),
},
})
if err != nil {
panic(err)
}
fmt.Println(first.OutputText())
second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
PreviousResponseID: openai.String(first.ID),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Explain why this is funny."),
},
})
if err != nil {
panic(err)
}
fmt.Println(second.OutputText())
}
```
```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
var first =
client
.responses()
.create(
ResponseCreateParams.builder().model("gpt-6-astra").input("Tell me a joke.").build());
first.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
var second =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Explain why this is funny.")
.previousResponseId(first.id())
.build());
second.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
```
```csharp
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult first = await client.CreateResponseAsync(
"gpt-6-astra",
"Tell me a joke."
);
Console.WriteLine(first.GetOutputText());
ResponseResult second = await client.CreateResponseAsync(
"gpt-6-astra",
"Explain why this is funny.",
previousResponseId: first.Id
);
Console.WriteLine(second.GetOutputText());
```
```ruby
require "openai"
client = OpenAI::Client.new
first = client.responses.create(
model: "gpt-6-astra",
input: "Tell me a joke."
)
puts(first.output_text)
second = client.responses.create(
model: "gpt-6-astra",
previous_response_id: first.id,
input: "Explain why this is funny."
)
puts(second.output_text)
```
#### `previous_response_id` in WebSocket mode
If you are using [the Responses API WebSocket mode](https://developers.openai.com/api/docs/guides/websocket-mode), continuation uses the same `previous_response_id` semantics as HTTP mode, but over a persistent socket with repeated `response.create` events.
The connection-local cache keeps recent previous responses in memory for low-latency continuation. When you use `stream_id`, each lane can retain its latest response; `previous_response_id` still controls lineage, so a new lane can fork from a response on another lane while that response remains available. If an uncached ID cannot be resolved, send a new turn with `previous_response_id` set to `null` and pass full input context.
##### Data retention for model responses
Response objects are saved for 30 days by default. They can be viewed in the dashboard
[logs](https://platform.openai.com/logs?api=responses) page or
[retrieved](https://developers.openai.com/api/reference/resources/responses/methods/retrieve) via the API.
You can disable this behavior by setting `store` to `false`
when creating a Response.
Conversation objects and items in them are not subject to the 30 day TTL. Any response attached to a conversation will have its items persisted with no 30 day TTL.
OpenAI does not use data sent via API to train our models without your explicit consent—[learn more](https://developers.openai.com/api/docs/guides/your-data).
Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.
## Managing the context window
Understanding context windows will help you successfully create threaded conversations and manage state across model interactions.
The **context window** is the maximum number of tokens that can be used in a single request. This max tokens number includes input, output, and reasoning tokens. To learn your model's context window, see [model details](https://developers.openai.com/api/docs/models).
### Managing context for text generation
As your inputs become more complex, or you include more turns in a conversation, you'll need to consider both **output token** and **context window** limits. Model inputs and outputs are metered in [**tokens**](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them), which are parsed from inputs to analyze their content and intent and assembled to render logical outputs. Models have limits on token usage during the lifecycle of a text generation request.
- **Output tokens** are the tokens generated by a model in response to a prompt. Each model has different [limits for output tokens](https://developers.openai.com/api/docs/models). For example, `gpt-4o-2024-08-06` can generate a maximum of 16,384 output tokens.
- A **context window** describes the total tokens that can be used for both input and output tokens (and for some models, [reasoning tokens](https://developers.openai.com/api/docs/guides/reasoning)). Compare the [context window limits](https://developers.openai.com/api/docs/models) of our models. For example, `gpt-4o-2024-08-06` has a total context window of 128k tokens.
If you create a large prompt—often by including extra context, data, or examples for the model—you run the risk of exceeding the allocated context window for a model, which might result in truncated outputs.
Use the [tokenizer tool](https://platform.openai.com/tokenizer), built with the [tiktoken library](https://github.com/openai/tiktoken), to see how many tokens are in a particular string of text.
For example, when making an API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) with a reasoning enabled model, like the [o1 model](https://developers.openai.com/api/docs/guides/reasoning), the following token counts will apply toward the context window total:
- Input tokens (inputs you include in the `input` array for the [Responses API](https://developers.openai.com/api/reference/resources/responses))
- Output tokens (tokens generated in response to your prompt)
- Reasoning tokens (used by the model to plan a response)
Tokens generated in excess of the context window limit may be truncated in API responses.
![context window visualization](https://cdn.openai.com/API/docs/images/context-window.png)
You can estimate the number of tokens your messages will use with the [tokenizer tool](https://platform.openai.com/tokenizer).
<a id="compaction-advanced"></a>
### Compaction
Detailed compaction guidance now lives in
[Compaction](https://developers.openai.com/api/docs/guides/compaction).
- For `/responses` with `context_management` and `compact_threshold`, see
[Server-side compaction](https://developers.openai.com/api/docs/guides/compaction#server-side-compaction).
- For explicit compaction control, see
[Standalone compact endpoint](https://developers.openai.com/api/docs/guides/compaction#standalone-compact-endpoint)
and the [`/responses/compact` API reference](https://developers.openai.com/api/reference/resources/responses/methods/compact).
## Next steps
For more specific examples and use cases, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), or learn more about using the APIs to extend model capabilities:
- [Receive JSON responses with Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs)
- [Extend the models with function calling](https://developers.openai.com/api/docs/guides/function-calling)
- [Enable streaming for real-time responses](https://developers.openai.com/api/docs/guides/streaming-responses)
- [Build a computer-using agent](https://developers.openai.com/api/docs/guides/tools-computer-use)
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -82,10 +82,10 @@ test('real HTTP pool fails over 429 to another model and never repeats completed
assert.equal(bad.requests[0].headers.authorization, 'Bearer owned-rate-limited');
});
test('pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests', async t => {
test('explicit Run affinity rotates weighted pool members on new Runs; disabled and missing credentials are excluded without requests', async t => {
const f = fixture(t), a = await compatibleFixture(t, () => completion()), b = await compatibleFixture(t, () => completion());
const provider = new Provider(), hub = provider.modelHub(f.store), first = add(hub, a, 'A'), second = add(hub, b, 'B');
const pool = hub.pool({ name: 'Weighted', strategy: 'weighted', members: [{ connectionId: first.id, weight: 2 }, { connectionId: second.id, weight: 1 }] });
const pool = hub.pool({ name: 'Weighted', strategy: 'weighted', affinityScope: 'run', members: [{ connectionId: first.id, weight: 2 }, { connectionId: second.id, weight: 1 }] });
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
for (let index = 0; index < 3; index++) { runtime.start(f.session.id, 'Finish ' + index); await until(() => !runtime.isActive(f.session.id)); }
assert.equal(a.requests.length, 2); assert.equal(b.requests.length, 1);
+4 -1
View File
@@ -51,7 +51,10 @@ test('automatic requirement ranking includes each member stream choice and respe
const choices = [];
for (let i = 0; i < 3; i++) { const lease = await f.acquire(config); choices.push(lease.member.id); assert.equal(lease.decision.candidates[0].reasons[0].capability, 'streaming'); lease.release(); }
assert.deepEqual(choices, [a.id, a.id, b.id]);
config.modelRouting.sticky = true; const lease = await f.acquire(config); assert.equal(lease.member.id, b.id); assert.equal(lease.decision.selectedBy, 'sticky'); lease.release();
assert.equal(f.hub.sticky.has('owned-run'), false, 'disabled affinity does not remember a hidden connection');
config.modelRouting.sticky = true; config.modelRouting.affinityScope = 'run';
const first = await f.acquire(config); assert.equal(first.member.id, a.id); assert.notEqual(first.decision.selectedBy, 'sticky'); first.release();
const continued = await f.acquire(config); assert.equal(continued.member.id, a.id); assert.equal(continued.decision.selectedBy, 'sticky'); continued.release();
});
test('matching upstream negative/retired metadata excludes automatic candidates, stale model/endpoint metadata does not', async t => {
+248
View File
@@ -0,0 +1,248 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { completionBody, requestHistory, actualRequest } from '../src/shared/contracts/model-request.mjs';
import { messagesBody, messagesHistory } from '../src/shared/contracts/anthropic-messages.mjs';
import { normalizeProtocolResponse } from '../src/core/models/protocols.mjs';
import { providerStateAudit, providerStateCompatibility } from '../src/shared/contracts/model-provider-state.mjs';
import { fixture, completion, call } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
const open = { mode: 'compatible', executionMode: 'unrestricted', approvalMode: 'full', capacityMode: 'passthrough', historyPolicy: 'preserve', maxSteps: 0, maxDurationMs: 0, maxTokens: 0, maxTaskTokens: 0 };
const messagesConfig = { ...open, protocol: 'anthropic-messages', model: 'claude-opus-5-5', baseUrl: 'https://api.anthropic.com', modelConnectionId: 'a', modelCredentialRevision: 2 };
const cache = { type: 'ephemeral', ttl: '1h', vendor_unknown: { keep: true } };
const tool = { type: 'function', cache_control: cache, defer_loading: true, function: { name: 'owned', description: '原工具描述', strict: true, parameters: { type: 'object', properties: {} } } };
const response = protocol => protocol === 'anthropic-messages'
? { id: 'owned-message', type: 'message', role: 'assistant', model: 'claude-opus-5-5', content: [{ type: 'thinking', thinking: 'private', signature: 'owned-signature' }, { type: 'text', text: '完成', cache_control: cache }], stop_reason: 'end_turn', usage: { input_tokens: 1, output_tokens: 1 } }
: { id: 'owned-response', status: 'completed', output: [{ type: 'reasoning', id: 'owned-reasoning', encrypted_content: 'owned-encrypted' }, { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: '完成' }] }], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } };
test('Messages preserves system/user text cache annotations and complete native tool metadata without mutating the canonical inputs', () => {
const messages = [{ role: 'system', content: [{ type: 'text', text: '固定规则', cache_control: cache, citations: [] }] }, { role: 'user', content: [{ type: 'input_text', text: '问题', cache_control: cache, source: { kind: 'owned' } }] }];
const original = structuredClone({ messages, tool });
const body = completionBody(messagesConfig, messages, [tool]);
assert.deepEqual(body.system[0], messages[0].content[0]); assert.deepEqual(body.messages[0].content[0], { ...messages[1].content[0], type: 'text' });
assert.deepEqual(body.tools[0], { name: 'owned', description: '原工具描述', strict: true, defer_loading: true, cache_control: cache, input_schema: tool.function.parameters });
assert.deepEqual({ messages, tool }, original); assert.equal(body.cache_control, undefined);
});
test('Messages request history round-trip preserves native block order, tool_result metadata and independent TTLs', () => {
const body = { ...completionBody(messagesConfig, [], []), system: [{ type: 'text', text: '规则', cache_control: cache }], tools: [{ name: 'owned', input_schema: { type: 'object' }, cache_control: cache }],
messages: [{ role: 'assistant', content: [{ type: 'thinking', thinking: 'opaque', signature: 'sig' }, { type: 'tool_use', id: 'call-own', name: 'owned', input: {}, cache_control: { type: 'ephemeral', ttl: '5m' } }] },
{ role: 'user', content: [{ type: 'tool_result', tool_use_id: 'call-own', content: [{ type: 'text', text: '原结果', cache_control: cache }], is_error: true, cache_control: cache }, { type: 'text', text: '补充', cache_control: { type: 'ephemeral', ttl: '5m' } }] }] };
const history = messagesHistory(body), original = structuredClone(history);
const restored = messagesBody(messagesConfig, history, body.tools, { nativeParameters: {} });
assert.deepEqual(restored.system, body.system); assert.deepEqual(restored.messages, body.messages); assert.deepEqual(restored.tools, body.tools); assert.deepEqual(history, original);
const chat = completionBody({ ...messagesConfig, protocol: 'chat-completions' }, history, []);
assert.ok(chat.messages.every(value => value.providerInput === undefined && value.providerState === undefined)); assert.ok(!JSON.stringify(chat).includes('opaque'));
});
test('Responses explicit cache breakpoints, tool metadata and top-level controls keep independent upstream fields', () => {
const config = { ...open, model: 'gpt-6.1-sol', protocol: 'responses', baseUrl: 'https://api.openai.com/v1', nativeParameters: { prompt_cache_options: { mode: 'explicit', ttl: '30m' }, prompt_cache_key: 'owned-session', store: false } };
const messages = [{ role: 'developer', content: [{ type: 'input_text', text: '固定规则', prompt_cache_breakpoint: { mode: 'explicit', ttl: '12h' } }] }];
const body = completionBody(config, messages, [tool]); assert.deepEqual(body.input[0], messages[0]); assert.deepEqual(body.prompt_cache_options, config.nativeParameters.prompt_cache_options);
assert.equal(body.tools[0].strict, true); assert.deepEqual(body.tools[0].cache_control, cache); assert.equal(body.tools[0].defer_loading, true); assert.equal(body.max_output_tokens, undefined);
});
test('plain Chat pool members with the same model project opaque history by their own credential and request scope', () => {
const config = { ...open, protocol: 'chat-completions', model: 'same-model', baseUrl: 'https://owned.invalid/v1', modelConnectionId: 'a', modelCredentialRevision: 2 };
const members = [{ id: 'a', model: config.model, protocol: config.protocol, baseUrl: config.baseUrl, credentialRevision: 2 },
{ id: 'b', model: config.model, protocol: config.protocol, baseUrl: config.baseUrl, credentialRevision: 3 }];
const message = normalizeProtocolResponse(config, { choices: [{ message: { role: 'assistant', content: '原答复', reasoning_content: 'opaque-owned-first' }, finish_reason: 'stop' }] }).choices[0].message;
const original = structuredClone(message), body = completionBody({ ...config, modelRouting: { members } }, [message], []);
assert.equal(actualRequest(body, members[0]).messages[0].reasoning_content, 'opaque-owned-first');
assert.equal(actualRequest(body, members[1]).messages[0].reasoning_content, undefined);
assert.equal(actualRequest(body, members[1]).messages[0].content, '原答复'); assert.deepEqual(message, original);
});
for (const protocol of ['anthropic-messages', 'responses', 'chat-completions']) test(protocol + ' opaque output state binds actual URL, version/headers, model, connection and credential without discarding historical data', () => {
const config = { ...messagesConfig, protocol, requestContract: { schemaVersion: 1, defaultsVersion: '2026-11-07.1', anthropicVersion: '2023-06-01', anthropicBetas: [], headers: { 'OpenAI-Project': 'owned-original' }, auth: 'default', completionPath: null, modelsPath: null, versionSource: 'explicit' } };
const raw = protocol === 'chat-completions' ? { ...completion([], '完成'), choices: [{ message: { role: 'assistant', content: '完成', reasoning_content: 'owned-private' }, finish_reason: 'stop' }] } : response(protocol);
const message = normalizeProtocolResponse(config, raw).choices[0].message, original = structuredClone(message);
assert.equal(message.providerState.schemaVersion, 2); assert.equal(providerStateCompatibility(config, message.providerState).applicable, true);
const same = completionBody(config, [message], []); assert.ok(JSON.stringify(same).includes(protocol === 'anthropic-messages' ? 'owned-signature' : protocol === 'responses' ? 'owned-encrypted' : 'owned-private'));
for (const patch of [{ model: 'different' }, { modelConnectionId: 'b' }, { modelCredentialRevision: 3 }, { baseUrl: 'https://other.invalid/v1' },
{ requestContract: { ...config.requestContract, completionPath: '/different/messages' } }, { requestContract: { ...config.requestContract, headers: { 'OpenAI-Project': 'different' } } },
...(protocol === 'anthropic-messages' ? [{ requestContract: { ...config.requestContract, anthropicVersion: '2026-10-21' } }] : [])]) {
const changed = { ...config, ...patch }; assert.equal(providerStateCompatibility(changed, message.providerState).applicable, false);
const body = completionBody(changed, [message], []); assert.ok(!/owned-(signature|encrypted|private)/.test(JSON.stringify(body)));
assert.equal(providerStateAudit(changed, [message]).variants[0].retainedOnly, 1);
}
assert.deepEqual(message, original); assert.deepEqual(raw, protocol === 'chat-completions' ? raw : response(protocol));
});
const untilIdle = async (runtime, session) => { const deadline = Date.now() + 25000; while (runtime.isActive(session.id)) { if (Date.now() > deadline) throw Error('Owned runtime did not finish'); await new Promise(resolve => setTimeout(resolve, 25)); } };
async function ownedServer(t, fn) {
const requests = [], server = http.createServer(async (req, res) => { const chunks=[]; for await (const chunk of req) chunks.push(chunk); const body=JSON.parse(Buffer.concat(chunks)); requests.push({ path:req.url,headers:req.headers,body }); await fn(body,res,requests.length); });
await new Promise(resolve => server.listen(0,'127.0.0.1',resolve)); t.after(()=>new Promise(resolve=>{server.closeAllConnections();server.close(resolve);}));
return { requests, baseUrl:'http://127.0.0.1:'+server.address().port+'/v1' };
}
test('session affinity survives actual independent Runs and Store/Provider restart while raw reasoning and completed tool IDs remain exact', async t => {
const f=fixture(t); f.store.saveConfig(open);
let firstCall=true;
const a=await ownedServer(t,(body,res)=>{const output=completion(firstCall?[call('owned-original-call','list_files',{path:'',depth:1})]:[],'完成'); firstCall=false; output.choices[0].message.reasoning_content='owned-reasoning-'+body.messages.length; res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(output));});
const b=await ownedServer(t,(body,res)=>{res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(completion([],'备用完成')));});
const provider=new Provider(),hub=provider.modelHub(f.store),memberA=hub.upsert({name:'Owned A',model:'owned-a',baseUrl:a.baseUrl,requiresKey:false}),memberB=hub.upsert({name:'Owned B',model:'owned-b',baseUrl:b.baseUrl,requiresKey:false});
const pool=hub.pool({name:'Owned session affinity',members:[{connectionId:memberA.id,weight:1},{connectionId:memberB.id,weight:1}],sticky:true}); assert.equal(pool.affinityScope,'session'); hub.select({type:'pool',id:pool.id});
const runtime=new Runtime(f.store,provider); t.after(()=>runtime.stopAll()); runtime.start(f.session.id,'读取工程'); await untilIdle(runtime,f.session); assert.equal(f.session.status,'completed',JSON.stringify(f.session.failure));
assert.equal(a.requests.length,2); assert.equal(b.requests.length,0); const toolCount=f.store.core.tool.size,history=structuredClone(f.session.providerMessages),firstRun=f.session.runId;
runtime.start(f.session.id,'继续检查原结果'); await untilIdle(runtime,f.session); assert.equal(a.requests.length,3); assert.equal(b.requests.length,0); assert.notEqual(f.session.runId,firstRun); assert.equal(f.store.core.tool.size,toolCount);
assert.deepEqual(f.session.providerMessages.slice(0,history.length),history);
for(const plan of f.store.core.context_plan.values()) assert.doesNotThrow(()=>verifyPlanEvidence(f.store,f.session,plan));
const affinity=structuredClone(f.session.modelAffinity),storedHistory=structuredClone(f.session.providerMessages);f.store.close();const reopened=new Store(f.data);f.onCleanup(()=>reopened.close()); const session=reopened.session(f.session.id); assert.deepEqual(session.providerMessages,storedHistory);assert.deepEqual(session.modelAffinity,affinity);
const restoredProvider=new Provider(),restoredHub=restoredProvider.modelHub(reopened),restoredRuntime=new Runtime(reopened,restoredProvider);t.after(()=>restoredRuntime.stopAll());
restoredHub.cursors.set(pool.id,1);restoredRuntime.start(session.id,'继续核对原记录');await untilIdle(restoredRuntime,session);assert.equal(a.requests.length,4);assert.equal(b.requests.length,0);assert.equal(reopened.core.tool.size,toolCount);
const latest=restoredHub.view().attempts.find(value=>value.runId===session.runId);assert.equal(latest.routingDecision.affinity.source,'saved-completed-response');assert.equal(latest.routingDecision.affinity.continued,true);
for(const plan of reopened.core.context_plan.values()) assert.doesNotThrow(()=>verifyPlanEvidence(reopened,session,plan));
});
test('task affinity ends with its Task; explicit manual selection wins and old pools keep their original Run scope', async t => {
const f=fixture(t);f.store.saveConfig(open);const model=await ownedServer(t,(body,res)=>{res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(completion([],'完成')));});
const provider=new Provider(),hub=provider.modelHub(f.store),a=hub.upsert({name:'A',model:'a',baseUrl:model.baseUrl,requiresKey:false}),b=hub.upsert({name:'B',model:'b',baseUrl:model.baseUrl,requiresKey:false});
const pool=hub.pool({name:'Task',members:[{connectionId:a.id},{connectionId:b.id}],affinityScope:'task'});hub.select({type:'pool',id:pool.id});const runtime=new Runtime(f.store,provider);t.after(()=>runtime.stopAll());
runtime.start(f.session.id,'完成第一个独立任务');await untilIdle(runtime,f.session);const oldTask=f.session.taskId;
runtime.start(f.session.id,'完成另一个独立目标');await untilIdle(runtime,f.session);assert.notEqual(f.session.taskId,oldTask);assert.deepEqual(model.requests.map(value=>value.body.model),['a','b']);
hub.select({type:'connection',id:a.id});runtime.start(f.session.id,'继续原检查');await untilIdle(runtime,f.session);assert.equal(model.requests.at(-1).body.model,'a');
const legacy=hub.state.pools.find(value=>value.id===pool.id);delete legacy.affinityScope;hub.save();const prepared=hub.prepare(f.store.config,{type:'pool',id:pool.id});assert.equal(prepared.modelRouting.affinityScope,'run');
const before=structuredClone(hub.state.pools);assert.throws(()=>hub.pool({...legacy,affinityScope:'invalid'}),/保持范围/);assert.deepEqual(hub.state.pools,before);
});
test('native state sidecars are created by the adapter; raw extensions and unknown schema cannot impersonate a saved provider scope', () => {
const config={...open,protocol:'chat-completions',model:'owned',baseUrl:'https://owned.invalid/v1',modelConnectionId:'owned',modelCredentialRevision:1};
const native=normalizeProtocolResponse(config,{choices:[{message:{role:'assistant',content:'OK',reasoning_content:'owned-private'},finish_reason:'stop'}]}).choices[0].message;
const raw={choices:[{message:{role:'assistant',content:'OK',providerState:native.providerState,providerInput:{protocol:'anthropic-messages',content:[]}},finish_reason:'stop'}]};
const normalized=normalizeProtocolResponse(config,raw);assert.equal(normalized.choices[0].message.providerState,undefined);assert.equal(normalized.choices[0].message.providerInput,undefined);assert.ok(raw.choices[0].message.providerState);
assert.equal(providerStateCompatibility(config,{...native.providerState,schemaVersion:999}).reason,'unknown-state-schema');
});
test('disabled remembered members and changed request scopes select current eligible routes while old opaque history stays saved', async t => {
const f=fixture(t);f.store.saveConfig(open);
const model=await ownedServer(t,(body,res)=>{const output=completion([],'完成');output.choices[0].message.reasoning_content='opaque-reasoning-for-'+body.model;res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(output));});
const provider=new Provider(),hub=provider.modelHub(f.store),a=hub.upsert({name:'A',model:'a',baseUrl:model.baseUrl,requiresKey:false}),b=hub.upsert({name:'B',model:'b',baseUrl:model.baseUrl,requiresKey:false});
const pool=hub.pool({name:'Session',members:[{connectionId:a.id},{connectionId:b.id}],affinityScope:'session'});hub.select({type:'pool',id:pool.id});const runtime=new Runtime(f.store,provider);t.after(()=>runtime.stopAll());
runtime.start(f.session.id,'记录第一个状态');await untilIdle(runtime,f.session);const old=structuredClone(f.session.providerMessages);assert.equal(model.requests[0].body.model,'a');
hub.toggle(a.id,false);runtime.start(f.session.id,'继续已有任务');await untilIdle(runtime,f.session);assert.equal(model.requests[1].body.model,'b');assert.ok(model.requests[1].body.messages.every(message=>message.reasoning_content===undefined));
assert.deepEqual(f.session.providerMessages.slice(0,old.length),old);
const switched=hub.view().attempts.find(value=>value.runId===f.session.runId);assert.equal(switched.routingDecision.affinity.reason,'saved-member-not-eligible');assert.equal(switched.nativeStateAudit.retainedOnly,1);
const previous=hub.connection(b.id);hub.upsert({...previous,requestContract:{...previous.requestContract,headers:{'OpenAI-Project':'new-owned'}}});
runtime.start(f.session.id,'继续在新项目头下核对');await untilIdle(runtime,f.session);const last=model.requests.at(-1);assert.equal(last.headers['openai-project'],'new-owned');assert.ok(last.body.messages.every(message=>message.reasoning_content===undefined));
const changed=hub.view().attempts.find(value=>value.runId===f.session.runId);assert.equal(changed.routingDecision.affinity.reason,'saved-provider-scope-changed');assert.equal(changed.nativeStateAudit.retainedOnly,2);
for(const plan of f.store.core.context_plan.values())assert.doesNotThrow(()=>verifyPlanEvidence(f.store,f.session,plan));
});
test('failed and unknown upstream requests keep a single original attempt and do not overwrite completed session affinity or dispatch tools', async t => {
const f=fixture(t);f.store.saveConfig(open);let fail=false;
const model=await ownedServer(t,(body,res)=>{if(fail){res.writeHead(400,{'Content-Type':'application/json','x-request-id':'owned-original-400'});res.end(JSON.stringify({error:{type:'invalid_request_error',message:'owned-original-rejection'}}));}else{res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(completion([],'完成')));}});
const provider=new Provider(),hub=provider.modelHub(f.store),a=hub.upsert({name:'Owned',model:'owned',baseUrl:model.baseUrl,requiresKey:false}),pool=hub.pool({name:'Session',members:[{connectionId:a.id}],affinityScope:'session'});hub.select({type:'pool',id:pool.id});const runtime=new Runtime(f.store,provider);t.after(()=>runtime.stopAll());
runtime.start(f.session.id,'取得原完成结果');await untilIdle(runtime,f.session);const saved=structuredClone(f.session.modelAffinity),history=structuredClone(f.session.providerMessages),tools=f.store.core.tool.size;
fail=true;runtime.start(f.session.id,'继续观察上游错误');await untilIdle(runtime,f.session);assert.equal(model.requests.length,2);assert.deepEqual(f.session.modelAffinity,saved);assert.equal(f.store.core.tool.size,tools);assert.deepEqual(f.session.providerMessages.slice(0,history.length),history);
const attempt=hub.view().attempts.find(value=>value.runId===f.session.runId);assert.equal(attempt.status,'failed');assert.equal(attempt.httpStatus,400);assert.match(JSON.stringify(attempt.diagnostic),/owned-original-rejection/);
assert.equal(attempt.routingDecision.affinity.continued,true);
});
test('unknown saved affinity is retained and optional affinity persistence cannot change a completed upstream response into an error', async t => {
const f = fixture(t); f.store.saveConfig(open);
const model = await ownedServer(t, (body, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(completion([], '完成'))); });
const provider = new Provider(), hub = provider.modelHub(f.store);
const member = hub.upsert({ name: 'Owned', model: 'owned', baseUrl: model.baseUrl, requiresKey: false });
const pool = hub.pool({ name: 'Session', members: [{ connectionId: member.id }], affinityScope: 'session' }); hub.select({ type: 'pool', id: pool.id });
const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
const unknown = { schemaVersion: 999, bindings: { original: true }, extension: ['keep-original'] };
f.session.modelAffinity = structuredClone(unknown); f.store.save(f.session);
runtime.start(f.session.id, '完成独立请求'); await untilIdle(runtime, f.session);
assert.equal(f.session.status, 'completed'); assert.deepEqual(f.session.modelAffinity, unknown); assert.equal(model.requests.length, 1);
let attempt = hub.view().attempts.find(value => value.runId === f.session.runId);
assert.equal(attempt.routingDecision.affinity.reason, 'unknown-affinity-state'); assert.equal(attempt.affinityPersistence.status, 'retained-unknown');
delete f.session.modelAffinity; f.store.save(f.session);
const save = f.store.save.bind(f.store);
f.store.save = (session, event) => { if (event?.type === 'model.affinity_recorded') throw new Error('owned-optional-affinity-write-failed'); return save(session, event); };
runtime.start(f.session.id, '继续实际请求'); await untilIdle(runtime, f.session); f.store.save = save;
attempt = hub.view().attempts.find(value => value.runId === f.session.runId);
assert.equal(f.session.status, 'completed'); assert.equal(attempt.status, 'completed'); assert.equal(attempt.affinityPersistence.status, 'unknown');
assert.match(attempt.affinityPersistence.reason, /owned-optional-affinity-write-failed/); assert.equal(model.requests.length, 2);
});
test('task affinity survives a stopped response and explicit same-Task continuation without dispatching the interrupted request again', async t => {
const f = fixture(t); f.store.saveConfig(open); let block = false;
const a = await ownedServer(t, (body, res) => {
if (block) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write('{'); return; }
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(completion([], '完成')));
});
const b = await ownedServer(t, (body, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(completion([], '备用完成'))); });
const provider = new Provider(), hub = provider.modelHub(f.store);
const memberA = hub.upsert({ name: 'A', model: 'a', baseUrl: a.baseUrl, requiresKey: false });
const memberB = hub.upsert({ name: 'B', model: 'b', baseUrl: b.baseUrl, requiresKey: false });
const pool = hub.pool({ name: 'Task', members: [{ connectionId: memberA.id }, { connectionId: memberB.id }], affinityScope: 'task' });
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, '完成任务'); await untilIdle(runtime, f.session);
const taskId = f.session.taskId, original = structuredClone(f.session.modelAffinity), tools = f.store.core.tool.size;
block = true; runtime.start(f.session.id, '', true);
const deadline = Date.now() + 20000; while (a.requests.length < 2) { assert.ok(Date.now() < deadline); await new Promise(resolve => setTimeout(resolve, 25)); }
await runtime.stop(f.session.id); await untilIdle(runtime, f.session);
assert.equal(f.session.taskId, taskId); assert.deepEqual(f.session.modelAffinity, original); assert.equal(b.requests.length, 0);
const interrupted = hub.view().attempts.find(value => value.runId === f.session.runId); assert.equal(interrupted.status, 'interrupted');
block = false; runtime.resume(f.session.id); await untilIdle(runtime, f.session);
assert.equal(f.session.taskId, taskId); assert.equal(a.requests.length, 3); assert.equal(b.requests.length, 0); assert.equal(f.store.core.tool.size, tools);
const resumed = hub.view().attempts.find(value => value.runId === f.session.runId);
assert.equal(resumed.routingDecision.affinity.source, 'saved-completed-response');
});
for (const protocol of ['anthropic-messages', 'responses']) test(protocol + ' real owned SSE retains native cache blocks and opaque output across turns, then projects ordinary history after a header change', async t => {
const f = fixture(t); f.store.saveConfig(open);
const model = await ownedServer(t, (body, res, index) => {
const tools = index === 1;
const value = protocol === 'anthropic-messages'
? { id: 'owned-native-' + index, type: 'message', role: 'assistant', model: body.model,
content: [{ type: 'thinking', thinking: 'opaque-native', signature: 'owned-native-signature-' + index },
{ type: 'text', text: '完成', cache_control: cache },
...(tools ? [{ type: 'tool_use', id: 'owned-native-tool', name: 'list_files', input: { path: '', depth: 1 }, cache_control: { type: 'ephemeral', ttl: '5m' } }] : [])],
stop_reason: tools ? 'tool_use' : 'end_turn', usage: { input_tokens: 10, output_tokens: 3, cache_read_input_tokens: 2, cache_creation_input_tokens: 1 } }
: { id: 'owned-native-' + index, model: body.model, status: 'completed',
output: [{ type: 'reasoning', id: 'owned-reasoning-' + index, encrypted_content: 'owned-encrypted-' + index, summary: [] },
{ type: 'message', id: 'owned-message-' + index, role: 'assistant', phase: 'final_answer', content: [{ type: 'output_text', text: '完成', annotations: [] }] },
...(tools ? [{ type: 'function_call', id: 'owned-call-item', call_id: 'owned-native-tool', name: 'list_files', arguments: JSON.stringify({ path: '', depth: 1 }), status: 'completed' }] : [])],
usage: { input_tokens: 10, output_tokens: 3, input_tokens_details: { cached_tokens: 2 } } };
const event = value => 'data: ' + JSON.stringify(value) + '\n\n';
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
if (protocol === 'anthropic-messages') {
res.write(event({ type: 'message_start', message: { ...value, content: [], stop_reason: null } }));
value.content.forEach((block, index) => { res.write(event({ type: 'content_block_start', index, content_block: block })); res.write(event({ type: 'content_block_stop', index })); });
res.write(event({ type: 'message_delta', delta: { stop_reason: value.stop_reason }, usage: value.usage })); res.end(event({ type: 'message_stop' }));
} else {
res.write(event({ type: 'response.created', sequence_number: 0, response: { ...value, status: 'in_progress', output: [] } }));
res.end(event({ type: 'response.completed', sequence_number: 1, response: value }));
}
});
const provider = new Provider(), hub = provider.modelHub(f.store);
const member = hub.upsert({ name: 'Owned native', model: protocol === 'anthropic-messages' ? 'claude-opus-5-5' : 'gpt-6.1-sol',
protocol, streaming: true, baseUrl: model.baseUrl, requiresKey: false });
const pool = hub.pool({ name: 'Native session', members: [{ connectionId: member.id }], affinityScope: 'session' }); hub.select({ type: 'pool', id: pool.id });
const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, '读取工程然后结束'); await untilIdle(runtime, f.session);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.equal(model.requests.length, 2);
const second = model.requests[1].body;
if (protocol === 'anthropic-messages') {
const blocks = second.messages.filter(message => message.role === 'assistant').flatMap(message => message.content);
assert.ok(blocks.some(block => block.signature === 'owned-native-signature-1'));
assert.deepEqual(blocks.find(block => block.type === 'text' && block.text === '完成').cache_control, cache);
assert.equal(blocks.find(block => block.type === 'tool_use').cache_control.ttl, '5m');
} else {
assert.ok(second.input.some(item => item.encrypted_content === 'owned-encrypted-1'));
assert.equal(second.input.find(item => item.type === 'message' && item.role === 'assistant').phase, 'final_answer');
assert.ok(second.input.some(item => item.type === 'function_call_output' && item.call_id === 'owned-native-tool'));
assert.equal(second.max_output_tokens, undefined);
}
const old = structuredClone(f.session.providerMessages), tools = f.store.core.tool.size;
hub.upsert({ ...hub.connection(member.id), requestContract: { ...hub.connection(member.id).requestContract, headers: { 'X-Owned-Scope': 'changed' } } });
runtime.start(f.session.id, '追加说明然后结束'); await untilIdle(runtime, f.session);
assert.equal(model.requests.length, 3); assert.equal(f.store.core.tool.size, tools); assert.deepEqual(f.session.providerMessages.slice(0, old.length), old);
const changed = model.requests.at(-1).body;
if (protocol === 'anthropic-messages') assert.ok(changed.messages.flatMap(message => message.content).every(block => !['thinking', 'redacted_thinking'].includes(block.type)));
else assert.ok(changed.input.every(item => item.type !== 'reasoning'));
const attempt = hub.view().attempts.find(value => value.runId === f.session.runId); assert.equal(attempt.nativeStateAudit.retainedOnly, 2);
for (const plan of f.store.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan));
});