feat(models): add native Anthropic Messages and observed endpoint diagnostics

This commit is contained in:
Agent Workbench Dev
2026-11-03 18:58:59 +08:00
parent b832982d46
commit 65ddee16b0
36 changed files with 751 additions and 87 deletions
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench项目执行规范
M原生Messages开发验收中:1.24.4源码已接入Anthropic请求/工具与PNG历史、JSON/SSE/累计缓存用量、起始型号、严格暂停、两种显式鉴权与实际URL。首23专项、61相关、48旧协议/身份及编译宿主七组两视口新UI/四类历史UI通过;首307诊断漏URL已修正,原失败保留。当前正式仍原1.24.3/PID36552/Provider;新发行独立源码/便携/安装、保留状态正式升级与单次真实Messages身份预检尚未完成。不得把夹具验证当Claude线路已修复或真实工程/Purge通过;原J/K/L证据保持。
L只读调查完成:确认当前1.24.3仅支持Chat/Responses,没有原生Messages;供应商公开Claude示例为/v1/messages,原apikey请求按封存配置拼接为/chat/completions,协议/路径与示例不同。原J原字节GPT、单独选定Claude请求与无切池保持,三组实际localhost回放证明没有客户端默认GPT回填;不把文档差异或匿名GET404当作服务器映射的唯一原因,Key分组/实际权重未知。最终37份/652352字节证据离线通过,截图实际JPEG更正与首封存保持;正式PID36552/Provider/55项目71会话及所有原行导出工件/配置精确保持,本轮0真实模型请求。见docs/APIKEY-ROUTE-L-INVESTIGATION.md。下一优先完整Messages协议适配与实际URL诊断,再新开单次有界预检;该产品修复尚未实现,不重跑J/E/H或伪造型号别名。
K已本地交付:1.24.3/source f53eebb7/候选20261103065830519,左下角与顶部统一模型中心,可直接选择/添加连接或号池;独立预算不覆盖路由、旧Run身份保持、跨窗口同步。30相关后端/25升级安装、六类历史UI、最终源码/便携/安装载荷各七组UI、541源码输入/22编译独立重建、三归档/实际便携/12隔离安装及安装副本16+9组通过。正式原PID36552/Provider、55项目/71会话及每表原行/全导出/工件/模型中心精确保持;正式网页和原生窗口回看及再次核对通过,9229关闭。743份/29747694字节证据离线通过,首验收器/长路径/版本清单失败保留;见docs/QA-MODEL-SELECTION-K.md及docs/model-selection-release-identity.json。本阶段真实模型请求0,原J请求Claude/上游报告GPT仍未解决,当前默认高性能池保持;更正连接后再开独立单次身份预检,不重跑J/E/H。下方旧记录按历史时点理解。
+7
View File
@@ -1,5 +1,12 @@
# Agent Workbench 更新记录
## 1.24.4 · 原生 Anthropic Messages(开发验收中)
- 模型中心增加 Messages 协议和 x-api-key/Bearer 鉴权;预览最终请求地址,支持服务根或 /v1 根地址,保存切换不自动调用模型。
- 接入原生系统/工具/图片历史、JSON/SSE、停止与完整性检查,以及起始事件中的真实返回型号;不完整或身份不符时保留原响应并暂停。
- 保留原生用量和缓存分项,累计流用量只结算一次;账本和错误显示请求/响应地址,模型请求不自动跟随重定向。
- 本机协议、界面与发行验收分别记录;真实连接身份及工程/Purge效果单独判定,未完成项目不宣称已通过。
## 1.24.3 · 统一模型选择入口(已本地交付)
- 左下角和顶部都打开模型中心,可选择已有连接/模型池、添加模型;选中连接与旧会话实际运行分开展示。
+14 -2
View File
@@ -1,11 +1,21 @@
# 模型协议与能力边界
1.17新增OpenAI Responses适配,保留既有Chat Completions。品牌、模型名称与声明不能替代检测。现有API代理可按实际协议添加;未知WorkBuddy登录态、Anthropic原生协议及视觉/音频输入仍未接入。
1.17新增OpenAI Responses适配,1.24.4新增原生Anthropic Messages,保留既有Chat Completions。品牌、模型名称与声明不能替代检测。现有API代理可按实际协议添加;PNG任务图片按各协议发送,未知WorkBuddy登录态、音频和视频输入尚未接入。
## 实际协议
Chat沿用messages与tool_calls/tool_call_id;Responses使用typed input/output Items,function_call.call_id与function_call_output严格配对,保留原用量字段。请求使用store:false,支持同一接口和模型下携带加密reasoning Items,换接口/模型时重新生成普通历史,不泄露私有Items。工具采用strict:false以保持现有可选参数契约。
Messages 使用顶层 system、messages 内容块、tool_use/input_schema 和带原 tool_use_id 的 tool_result。原生 thinking/signature 与 redacted_thinking 只为同地址/型号保留上游历史,不拼成普通助手文本。未知服务端工具和内容块明确暂停;达到输出/上下文上限、pause_turn 或缺少完整终结时不执行工具。
连接选择 Anthropic Messages 后,可填服务根地址或以 /v1 结尾的 API 根地址,界面预览最终 POST 地址;例如 https://api.apikey.fan 和 https://api.apikey.fan/v1 都发送到 https://api.apikey.fan/v1/messages。完整 /messages 端点不作为根地址接受。Chat/Responses 延续原有根地址拼接规则,不自动为其它协议增加 /v1。Messages 默认 x-api-key,可显式选择兼容服务的 Bearer;同时发送 anthropic-version:2023-06-01。保存、选择与切换不自动请求模型。
Messages SSE 必须依次核对 message_start、每个内容块的 start/delta/stop、message_delta 和 message_stop,工具 JSON 必须完整为对象。message_start.message.model 参与原有请求/返回型号核对,严格模式下未知或不一致即暂停,不以注册别名掩盖不一致。原响应和用量保留;相同字符串也不认证底层模型权重。
Messages 的输入计数为 input_tokens + cache_creation_input_tokens + cache_read_input_tokens,message_delta 用量是累计快照,不能把每个快照相加。原字段与缓存分项保留;这是消费记录,不是 Purge 收益证明。原生参数已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking;max_tokens 始终来自工作台硬预算,不能由自定义参数覆盖。
新的请求账本、消费记录和错误信息保存实际请求 URL 与 fetch 观察到的响应 URL。所有模型请求不自动跟随 HTTP 重定向,避免向跳转目标转发任一种凭据;3xx 保留错误并要求核对地址。旧记录没有保存的历史最终 URL 不补造。
混合协议或流式模型池封存每个成员实际请求变体;真正发送的请求另有原字节SHA、长度和Task/Run所属工件。历史纯Chat请求继续按原格式核对。预算按最大变体估算和最小成员容量保守预留;不把多线路变体总和当一次发送量。
SSE只显示有界进展。完整参数和终结核对前不派发工具;Chat须完整finish_reason及[DONE],Responses须completed且身份、参数和文本与原片段一致。收到流后断开、超时或协议失败不自动换成员重发。主动停止关闭原HTTP并释放租约。保存有界原响应工件;已知凭据会脱敏,原流SHA和脱敏后工件SHA分别保留。超过4MB则停止读取并明确标记捕获范围。
@@ -24,4 +34,6 @@ SSE只显示有界进展。完整参数和终结核对前不派发工具;Chat
- [函数调用](https://developers.openai.com/api/docs/guides/function-calling)
- [Responses流式事件](https://developers.openai.com/api/docs/guides/streaming-responses?api-mode=responses)
以上是协议依据,不能证明任意代理完整兼容。专项使用自有loopback服务;真实模型工程效果和Purge收益仍按用户此前选择单独待验。
Messages 实际读取依据为 [Anthropic 官方 TypeScript SDK 的 Messages 契约](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/src/resources/messages/messages.ts) 和 [apikey 公开请求示例](https://apikey.fan/docs/api-scripts)。本次两份官方文档网页实际转到地区不可用页,没有将该 HTTP200 当作文档内容。
以上是协议依据,不能证明任意代理完整兼容。专项使用自有loopback服务;真实连接身份预检、真实模型工程效果和Purge收益分别记录,不借用本机夹具结论。
+7
View File
@@ -1025,3 +1025,10 @@ I正式交付完成:源码1153e19a/候选20261103042107173,179/179相关回
第三轮整表已完成后,额外“兼容 config.json 全字节不变”的错误断言拒绝。实际仅 configRevision 48→52;按真实 atomicJson 序列化重建的原配置 SHA 精确为测试前 e6d8236b99057d8d42cf2e473f0aca272c01a5ec9c07bfb64cf803395048bc3d。第四轮只为该已证明的修订单调增长增加精确归一化,projects.json 仍要求原字节一致;保留全部首失败,未改写磁盘或降低未知差异检查。
用户要求先核对已有 apikey(请求 claude-opus-5-5)。上一阶段没有真实调用;本轮先新建有界身份预检,不读取或复制 Provider 凭据。旧 E/H 返回身份不一致不能证明本次线路状态。本轮批读历史记录的首输出超过上限,已改为精确文件/短段;PowerShell 未展开路径通配符的 rg 查询报错,后续使用实际目录和 -g。
# M 接续:Messages 适配边界
基线只支持 Chat/Responses;需要第三种协议的完整请求/历史/流/身份/用量转换,不能仅改 URL。Messages 的 message_start.message.model 目前不在身份观察对象中;混合池的预构建变体条件也要纳入非 Chat 协议。保留既有 Chat/Responses wire 字节与历史证据语义。下一核对官方契约,再实施。
M 官方来源:Anthropic TypeScript SDK messages.ts(公开 GitHub main,SHA e4a57d12f91fa40aecaa14304e93132eab36b2427741030d720e92cd913c8cb9)确认 /v1/messages、系统独立字段、工具块与 cumulative message_delta、输入量为 input_tokens+cache_creation_input_tokens+cache_read_input_tokens。两份官方文档页面实际重定向到地区不可用页,HTTP200 不作为文档读取成功。供应商公开 api-scripts 页面另存;原始响应和 URL 收据保留 .qa/messages-m/reference。
M 首23专项22通过/1失败:真实 JSON/SSE 两轮原工具与缓存用量、混合池、取消、九类异常流均通过;307确实未跟随且目标零请求,但失败诊断没有保留新 requestUrl。原因是 connectionFailure/httpFailure 显式选取旧字段;已在 Provider catch 绑定本次实际 URL,复验而不更改首日志。已有 Chat/Responses/identity 48项通过,首构建通过。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.24.3",
"version": "1.24.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.24.3",
"version": "1.24.4",
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.24.3",
"version": "1.24.4",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+9
View File
@@ -1552,3 +1552,12 @@ I本地索引1648份/88426738字节批量原字节核对通过。首次cached di
## J:真实连接预检开始
已接收用户选择“先核对现有 apikey Claude 连接”。先按 docs/LIVE-RETEST-J-PLAN.md 封存正式基线和新契约,再单次发送;尚未发出真实请求。Provider 和原始密钥保持在原进程,测试不抽取凭据、不重启服务。
# M 接续:原生 Anthropic Messages(2026-11-03)
已恢复 L 结论与干净基线 b832982d;创建 feat/anthropic-messages-1.24.4。session-catchup 未返回待同步内容。读取执行规范、既有协议与流适配,开始契约核对;尚无源码修改、新发行或真实模型请求。
恢复时宽批读输出截断,已改为按真实文件短段读取;一次 rg 指向不存在的 src/web/src/ui,改用 rg --files 定位,不把截断或缺失输出记为已审查。
M 开发验收:原23专项修正后23/23,补充严格SSE型号与原工具块关闭后仍需message_stop后最终25/25;相关14文件144/144通过。原Chat/Responses/identity48项、另一批相关61项保持。编译宿主新7组两视口UI与模型中心/协议/身份/选择4类历史UI通过;实际回看desktop-editor/narrow-ledger原图,补充账本滚入截图。首307诊断漏URL失败保留,修正catch绑定实际URL;新请求不自动跟随重定向。
正式发行前只读基线再次通过:原1.24.3/PID36552/Provider、hasKey=true、55项目/71全部会话、所有原表行/全导出/工件/公开模型中心均与K最终精确一致;本轮到此真实请求0。独立发行和单次新预检未完成,不将本机夹具当Claude线路通过。
+20 -20
View File
@@ -9,36 +9,36 @@ import { randomUUID } from 'node:crypto';
if (process.argv.slice(2).some(value => value !== '--help')) throw new Error('Unsupported argument; use --help.');
if (process.argv.includes('--help')) { console.log('node scripts/verify-all-ui.mjs - run serial desktop/390px checks in independent local hosts; use explicit QA Python/Harness/Purge source paths for 1.15.'); process.exit(0); }
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version), 'Review evidence paths when introducing the next release.');
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version), 'Review evidence paths when introducing the next release.');
const prefix = releaseEvidencePrefix(version), resultFile = `.qa/${prefix}-all-ui-validation.json`, results = [];
const qaEnvironment = Object.fromEntries(['AGENT_WORKBENCH_TEST_PYTHON', 'AGENT_WORKBENCH_DEEPSEEK_ROOT', 'AGENT_WORKBENCH_PURGE_178_ROOT', 'AGENT_WORKBENCH_PURGE_181_ROOT']
.filter(name => process.env[name]).map(name => [name, process.env[name]]));
for (const [name, value] of Object.entries(qaEnvironment)) assert.ok(path.isAbsolute(value) && fs.existsSync(value), 'Use an existing absolute QA runtime/source path: ' + name);
const cases = [
...(['1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-file-results-ui.mjs', null]] : []),
...(['1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
...(['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-file-results-ui.mjs', null]] : []),
...(['1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
['verify-ui.mjs', '.qa/ui-validation.json'], ['verify-diagnostics-ui.mjs', '.qa/diagnostics-ui-validation.json'],
['verify-execution-ui.mjs', '.qa/execution-ui-validation.json'], ['verify-delivery-ui.mjs', '.qa/delivery-ui-validation.json'],
['verify-index-ui.mjs', '.qa/index-ui-result.json'], ['verify-change-sets-ui.mjs', `docs/${prefix}-batch-ui-validation.json`],
['verify-context-ui.mjs', `.qa/${version === '1.6.0' ? 'workspaces-context' : prefix}-ui-validation.json`],
['verify-workspaces-ui.mjs', `docs/${prefix === 'workspaces' ? prefix : prefix + '-workspaces'}-ui-validation.json`],
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
];
fs.mkdirSync('.qa', { recursive: true });
const externalHost = new Set(['verify-ui.mjs', 'verify-diagnostics-ui.mjs', 'verify-execution-ui.mjs', 'verify-index-ui.mjs']);
+122
View File
@@ -0,0 +1,122 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-anthropic-messages-ui.mjs [--app-root ABS] — isolated Messages editor, actual JSON/SSE, tool roundtrip, identity mismatch, URLs, raw errors, reload and 390px; synthetic credentials only.'); process.exit(0); }
const args = process.argv.slice(2); assert.ok(!args.length || args.length === 2 && args[0] === '--app-root' && path.isAbsolute(args[1]));
const appRoot = fs.realpathSync.native(args[1] ?? process.cwd());
const directory = path.resolve('.qa', 'messages-ui-m-' + randomUUID()); fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t); f.store.close();
const requests = [], sockets = new Set(), checks = [], screenshots = [], errors = [];
let mode = 'ok';
const msg = (content, stop_reason) => ({ id: 'msg_owned_ui', type: 'message', role: 'assistant', model: mode === 'mismatch' ? 'gpt-owned-other' : 'claude-owned-ui', content, stop_reason,
usage: { input_tokens: 40, cache_creation_input_tokens: 10, cache_read_input_tokens: 20, output_tokens: 8 } });
const modelServer = http.createServer(async (req, res) => {
try {
const parts = []; for await (const chunk of req) parts.push(chunk);
const body = JSON.parse(Buffer.concat(parts)), raw = Buffer.concat(parts);
requests.push({ route: req.url, body, auth: req.headers.authorization === 'Bearer owned-ui-key', keyHeaderPresent: req.headers['x-api-key'] !== undefined, version: req.headers['anthropic-version'], sha256: createHash('sha256').update(raw).digest('hex') });
assert.equal(req.url, '/v1/messages'); assert.equal(req.headers.authorization, 'Bearer owned-ui-key'); assert.equal(req.headers['x-api-key'], undefined); assert.equal(req.headers['anthropic-version'], '2023-06-01');
if (mode === 'error') { res.writeHead(429, { 'Content-Type': 'application/json', 'request-id': 'req_owned_limit', 'Retry-After': '1' }); res.end(JSON.stringify({ type: 'error', error: { type: 'rate_limit_error', message: 'owned Messages limit' } })); return; }
const prompt = body.messages.filter(m => m.role === 'user').flatMap(m => m.content).filter(b => b.type === 'text').map(b => b.text).join('\n');
const nonce = prompt.match(/nonce ([a-f0-9-]+)/)?.[1], probe = prompt === 'Reply OK.' || !!nonce;
const completedTool = body.messages.some(m => m.content.some(b => b.type === 'tool_result'));
const tool = { type: 'tool_use', id: 'call_owned_ui', name: nonce ? 'workbench_capability_echo' : 'list_files', input: nonce ? { nonce } : { path: '', depth: 1 } };
const content = mode === 'mismatch' || probe && !nonce || completedTool ? [{ type: 'text', text: '已核对。' }] : [tool];
const final = msg(content, content[0].type === 'tool_use' ? 'tool_use' : 'end_turn');
if (!body.stream) { res.writeHead(200, { 'Content-Type': 'application/json', 'request-id': 'req_owned_native' }); res.end(JSON.stringify(final)); return; }
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'request-id': 'req_owned_native' });
const send = (type, fields = {}) => res.write('event: ' + type + '\ndata: ' + JSON.stringify({ type, ...fields }) + '\n\n');
send('message_start', { message: { ...final, content: [], stop_reason: null, usage: { ...final.usage, output_tokens: 1 } } });
content.forEach((block, index) => {
send('content_block_start', { index, content_block: block.type === 'text' ? { ...block, text: '' } : { ...block, input: {} } });
send('content_block_delta', { index, delta: block.type === 'text' ? { type: 'text_delta', text: block.text } : { type: 'input_json_delta', partial_json: JSON.stringify(block.input) } });
send('content_block_stop', { index });
});
send('message_delta', { delta: { stop_reason: final.stop_reason, stop_sequence: null }, usage: { output_tokens: final.usage.output_tokens } }); send('message_stop'); res.end();
} catch (cause) { errors.push('owned upstream: ' + cause.message); res.destroy(); }
});
modelServer.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
await new Promise(resolve => modelServer.listen(0, '127.0.0.1', resolve));
const baseUrl = 'http://127.0.0.1:' + modelServer.address().port;
const host = await launchWorkbench(t, f.data, {}, { appRoot, nodePath: args.length ? path.join(appRoot, 'runtime/node.exe') : process.execPath });
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', cause => errors.push(cause.message));
const mark = message => { checks.push(message); console.log('PASS ' + message); };
const dialog = () => page.getByRole('dialog', { name: '模型中心', exact: true });
async function open() { if (!await dialog().isVisible()) await page.getByRole('button', { name: '打开模型中心', exact: true }).click(); return dialog(); }
async function shot(name) {
const file = path.join(directory, name + '.png'); await page.screenshot({ path: file }); screenshots.push(file);
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= innerWidth), 'page overflow: ' + name);
assert.ok(await dialog().evaluate(node => node.scrollWidth <= node.clientWidth + 1), 'dialog overflow: ' + name);
}
let result;
try {
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: f.project.id, sessionId: f.session.id });
await page.goto(host.url); await page.waitForLoadState('networkidle'); await open();
await dialog().getByRole('button', { name: '添加连接', exact: true }).click(); const form = dialog().getByRole('form', { name: '编辑模型连接', exact: true });
await form.getByLabel('连接名称', { exact: true }).fill('本机 Messages 验收'); await form.getByLabel('接口协议', { exact: true }).selectOption('anthropic-messages');
await form.getByLabel('接口根地址', { exact: true }).fill(baseUrl); await form.getByLabel('请求模型名称', { exact: true }).fill('claude-owned-ui');
await form.getByLabel('临时 API Key', { exact: true }).fill('owned-ui-key'); await form.getByLabel('Messages 鉴权', { exact: true }).selectOption('bearer');
await form.getByLabel('型号核对', { exact: true }).selectOption('require-match'); await form.getByLabel('流式能力', { exact: true }).selectOption('supported'); await form.getByLabel('使用流式输出', { exact: true }).check();
await expect(form.getByLabel('请求地址预览', { exact: true })).toContainText(baseUrl + '/v1/messages'); await shot('desktop-editor');
await page.setViewportSize({ width: 390, height: 844 }); await form.scrollIntoViewIfNeeded(); await shot('narrow-editor');
await form.getByLabel('接口根地址', { exact: true }).fill(baseUrl + '/v1/messages'); await form.getByRole('button', { name: '保存模型连接', exact: true }).click();
await expect(dialog().locator('.mc-notice')).toContainText('根地址'); await expect(form.getByLabel('连接名称', { exact: true })).toHaveValue('本机 Messages 验收');
await form.getByLabel('接口根地址', { exact: true }).fill(baseUrl + '/v1'); await form.getByRole('button', { name: '保存模型连接', exact: true }).click(); await expect(form).toHaveCount(0);
assert.equal(requests.length, 0); mark('root and /v1 preview agree, full endpoint rejects with input retained; save makes no model request');
await page.reload(); await open(); const card = dialog().locator('.mc-connection').filter({ hasText: '本机 Messages 验收' });
await expect(card).toContainText('Anthropic Messages · 流式开启'); await expect(card).toContainText('Bearer'); await expect(card).toContainText(baseUrl + '/v1/messages');
let center = await host.api('/model-center'), connection = center.connections.find(c => c.name === '本机 Messages 验收'); assert.equal(connection.messagesAuth, 'bearer');
await card.getByRole('button', { name: '用于新任务', exact: true }).click(); assert.equal(requests.length, 0); await page.reload(); await open();
await expect(dialog().getByLabel('新任务默认模型', { exact: true })).toHaveValue('connection:' + connection.id); await shot('narrow-saved');
mark('saved protocol, auth and selected connection survive reload and remain operable at 390px');
await page.setViewportSize({ width: 1440, height: 1000 }); await card.getByRole('button', { name: '原生参数', exact: true }).click();
const native = dialog().getByRole('form', { name: '原生请求参数', exact: true }); await expect(native.getByLabel('输出上限字段')).toHaveValue('max_tokens');
await expect(native.getByLabel('输出上限字段').locator('option')).toHaveCount(1); await native.getByLabel('原生参数 JSON').fill('{"reasoning_effort":"high"}');
await native.getByRole('button', { name: '保存原生参数', exact: true }).click(); await expect(native.getByRole('alert')).toContainText('尚未接入');
await native.getByLabel('原生参数 JSON').fill('{"temperature":0.3,"top_k":12}'); await native.getByRole('button', { name: '保存原生参数', exact: true }).click(); await expect(native).toHaveCount(0);
assert.equal(requests.length, 0); mark('native settings reject other-protocol fields and keep a single hard max_tokens output field');
for (const [scope, title] of [['text', '文本'], ['tools', '工具'], ['streaming', '流式']]) {
await card.getByLabel('本机 Messages 验收检测范围').selectOption(scope); await card.getByRole('button', { name: '验证响应(调用模型)', exact: true }).click();
await expect(dialog().locator('.mc-notice')).toContainText(title + '检测通过');
}
assert.equal(requests.length, 3); assert.ok(requests.every(r => r.body.top_k === 12 && r.body.temperature === 0.3)); mark('actual local JSON text/tool and native SSE capability probes use the saved protocol and auth');
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
await host.api('/sessions/' + f.session.id + '/messages', { content: '读取本项目文件一次后结束。' });
await until(async () => !['running', 'queued'].includes((await host.api('/sessions/' + f.session.id)).status), 20000);
const session = await host.api('/sessions/' + f.session.id); assert.equal(session.status, 'completed');
assert.equal(requests.length, 5); assert.ok(requests[4].body.messages.some(m => m.content.some(b => b.type === 'tool_result' && b.tool_use_id === 'call_owned_ui')));
await open(); await dialog().getByRole('button', { name: '请求账本', exact: true }).click();
await expect(dialog().locator('.mc-attempts')).toContainText('请求与返回型号一致'); await expect(dialog().locator('.mc-attempts')).toContainText(baseUrl + '/v1/messages');
await expect(dialog().locator('.mc-attempts')).toContainText('70 输入 / 8 输出 tokens'); await dialog().locator('.mc-attempts article').first().scrollIntoViewIfNeeded(); await shot('desktop-ledger');
await page.setViewportSize({ width: 390, height: 844 }); await dialog().locator('.mc-attempts article').first().scrollIntoViewIfNeeded(); await shot('narrow-ledger'); mark('compiled native tool roundtrip completes with original call ID, cache-inclusive usage and observed request/response URLs');
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click(); mode = 'mismatch';
const second = await host.api('/sessions', { projectId: f.project.id }); await host.api('/sessions/' + second.id + '/messages', { content: '有界身份异常夹具。' });
await until(async () => !['running', 'queued'].includes((await host.api('/sessions/' + second.id)).status), 20000);
center = await host.api('/model-center'); assert.equal(center.attempts[0].modelIdentity.status, 'mismatch'); assert.equal(requests.length, 6);
await open(); await dialog().getByRole('button', { name: '请求账本', exact: true }).click(); await expect(dialog().locator('.mc-attempts')).toContainText('请求与返回型号不一致'); await shot('narrow-mismatch');
mark('strict mismatch is visible with original GPT identifier and one request, no retry or tool dispatch');
// A separate owned connection avoids bypassing the intentionally blocked identity route.
mode = 'error'; const original = center.connections.find(c => c.id === connection.id);
connection = await host.api('/model-center/connections', { ...original, id: undefined, name: '本机 Messages 错误验收', apiKey: 'owned-ui-key' });
// The API returns the authoritative center; resolve by its explicit owned name.
center = await host.api('/model-center'); connection = center.connections.find(c => c.name === '本机 Messages 错误验收');
await expect(dialog().getByRole('button', { name: '刷新模型中心', exact: true })).toBeEnabled(); await dialog().getByRole('button', { name: '刷新模型中心', exact: true }).click();
await dialog().getByRole('button', { name: '模型连接', exact: true }).click(); const errorCard = dialog().locator('.mc-connection').filter({ hasText: '本机 Messages 错误验收' });
await errorCard.getByRole('button', { name: '验证响应(调用模型)', exact: true }).click(); await expect(dialog().locator('.mc-notice')).toContainText('模型服务请求达到限额');
await dialog().locator('.mc-notice summary').click(); await expect(dialog().getByLabel('上游错误原文')).toContainText('owned Messages limit');
await expect(dialog().locator('.mc-notice')).toContainText('req_owned_limit'); await expect(dialog().locator('.mc-notice')).toContainText(baseUrl + '/v1/messages'); await shot('narrow-error');
assert.equal(requests.length, 7); mark('429 preserves native type, raw message, request ID, URL and inputs without automatic replay');
assert.deepEqual(errors, []);
result = { success: true, appRoot, testedVersion: (await host.api('/health')).version, directory, checks, screenshots, errors, requests, realModelRequests: 0,
scope: 'Compiled UI and actual owned localhost API; no configured-model capability or model-weight claim.' };
} catch (cause) { result = { success: false, directory, checks, screenshots, errors, error: cause.stack, requests, realModelRequests: 0 }; await page.screenshot({ path: path.join(directory, 'failure.png') }).catch(() => {}); process.exitCode = 1; }
finally {
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify({ success: result.success, checks: checks.length, directory, error: result.error }));
await browser.close(); for (const dispose of disposers.reverse()) await dispose(); for (const socket of sockets) socket.destroy(); await new Promise(resolve => modelServer.close(resolve));
}
+1 -1
View File
@@ -22,7 +22,7 @@ export async function verifyControlledApi({ api, url, token, directory, appRoot,
const origin = new URL(url);
assert.equal(origin.hostname, '127.0.0.1'); assert.notEqual(origin.port, '4318');
const expectedVersion = JSON.parse(fs.readFileSync(path.join(appRoot, fs.existsSync(path.join(appRoot, 'MANIFEST.json')) ? 'MANIFEST.json' : 'package.json'), 'utf8')).version;
assert.ok(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(expectedVersion));
assert.ok(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(expectedVersion));
const bootstrap = await api('/bootstrap'); assert.equal(bootstrap.version, expectedVersion);
assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const root = path.join(directory, 'compiled-controlled-node'), hooks = path.join(directory, 'disabled-hooks');
+1 -1
View File
@@ -149,7 +149,7 @@ try {
const beforeRestart = snapshotPersistentData(dataRoot); await controller.stop(); const restarted = (await controller.start()).identity;
assert.notEqual(restarted.pid, original.pid); assert.deepEqual(snapshotPersistentData(dataRoot), beforeRestart);
await controller.api('/model-center/probe', { method: 'POST', input: { id: connectionId } }); assert.equal(authenticated, 3); record(stage, { originalPid: original.pid, restartedPid: restarted.pid, authenticatedRequests: authenticated });
if (['1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(version)) {
if (['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(version)) {
stage = 'actual installed current results and saved HTML user paths';
const pointer = JSON.parse(fs.readFileSync(path.join(installRoot, 'current.json')));
const installedRoot = fs.realpathSync.native(path.join(installRoot, 'versions', pointer.active.directory)), proofs = [];
+7 -7
View File
@@ -34,7 +34,7 @@ for (const name of Object.keys(env)) if (name.toLowerCase() === 'path') delete e
const windowsRoot = process.env.SystemRoot || 'C:\\Windows';
env.PATH = [windowsRoot, path.join(windowsRoot, 'System32'), path.join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0')].join(path.delimiter);
let externalGit = null;
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version)) {
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version)) {
// The controlled project requires external Git. Preserve its observed binary
// directory while keeping system Node/npm unavailable to the packaged host.
const binary = fs.realpathSync.native(execFileSync('where.exe', ['git.exe'], { env: gitEnvironment(), encoding: 'utf8', windowsHide: true, timeout: 10000 }).trim().split(/\r?\n/)[0]);
@@ -88,7 +88,7 @@ try {
console.log((await launch()).trim());
assert.equal(JSON.parse(fs.readFileSync(path.join(data, 'service-info.json'), 'utf8')).pid, firstInfo.pid);
const example = bootstrap.projects.find(project => project.id === bootstrap.exampleProjectId);
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version)) {
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version)) {
assert.equal(path.resolve(example.root).toLowerCase(), path.join(data, 'projects', 'starter-project').toLowerCase());
const compareTemplate = relative => { for (const entry of fs.readdirSync(path.join(appRoot, 'examples/starter-project', relative), { withFileTypes: true })) {
const next = path.join(relative, entry.name); if (entry.isDirectory()) compareTemplate(next);
@@ -114,7 +114,7 @@ try {
const checkLog = await api('/artifacts/' + checked.results[0].logArtifactId + '?session=' + session.id); assert.match(checkLog.content, /tests 4/);
assert.ok(fs.existsSync(path.join(appRoot, 'runtime/node_modules/npm/bin/npm-cli.js')));
const actualRea = [];
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version)) {
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version)) {
const installation = await api('/research/availability'); assert.equal(installation.status, 'available'); assert.equal(installation.version, '6.8.0');
assert.equal(fs.realpathSync.native(installation.packageRoot), fs.realpathSync.native(path.join(appRoot, 'runtime/node_modules/rea-agents')));
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
@@ -146,7 +146,7 @@ try {
console.log('PASS actual contained REA: ASAR, PE imports and PE resources; zero target execution/model requests');
}
let actualEngine = null;
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version) && process.argv.includes('--native-engines')) {
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version) && process.argv.includes('--native-engines')) {
const installation = await api('/engines/deepseek/availability'); assert.equal(installation.status, 'available', installation.message);
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
const engineRoot = path.join(data, 'engine-project'); fs.mkdirSync(engineRoot); fs.writeFileSync(path.join(engineRoot, 'README.md'), '# Owned portable engine connection\n');
@@ -166,8 +166,8 @@ try {
assert.equal((await api('/research')).length, 4);
const page = await fetch(url); assert.equal(page.status, 200);
assert.match(await page.text(), /Agent Workbench/);
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version) ? await verifyControlledApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version) ? await verifyControlledApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
console.log((await stop()).trim()); started = false;
await until(async () => { try { await fetch(url + '/api/health'); return false; } catch { return true; } });
for (const file of manifest.files) {
@@ -176,7 +176,7 @@ try {
}
const result = { success: true, date: new Date().toISOString(), appRoot, version: manifest.version, nodeVersion: manifest.nodeVersion,
verifiedFiles: manifest.files.length, url, reusedPid: firstInfo.pid, checks: { jobId, status: checked.status, tests: checked.results[0].tests }, actualRea, actualEngine, actualBrowser, actualControlled, externalGit,
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
fs.writeFileSync('.qa/release-validation.json', JSON.stringify(result, null, 2));
console.log(JSON.stringify(result, null, 2));
} finally { if (started) { try { await stop(); } catch {} } }
+1
View File
@@ -24,3 +24,4 @@
.mc-native>label{display:flex;flex-direction:column;gap:8px;font-size:12px;color:#40576e;margin:14px 0}.mc-native select,.mc-native textarea{width:100%;min-width:0;padding:10px;border:1px solid #a9bdcf;border-radius:5px;background:white;font-size:12px;line-height:1.75}.mc-native textarea{resize:vertical;font-family:Consolas,"Microsoft YaHei",monospace}.mc-native select:focus-visible,.mc-native textarea:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
.mc-route-control{margin-bottom:24px;padding:18px 20px;background:#fff;border:1px solid #b8cadb;border-left:3px solid #2560a3;border-radius:6px;min-width:0}.mc-route-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:14px}.mc-route-heading h3{font-size:15px;margin-bottom:5px}.mc-route-heading p,.mc-route-detail{font-size:12px;color:#4b6078;line-height:1.7;overflow-wrap:anywhere}.mc-route-heading>.button{flex-shrink:0}.mc-route-select{display:flex;gap:12px;align-items:center;font-size:12px;color:#425974}.mc-route-select select{min-width:0;flex:1;width:100%;min-height:42px;border:1px solid #a7bbcf;border-radius:5px;background:#fff;padding:10px;color:#15283f;font-size:13px}.mc-route-detail{margin-top:9px}.mc-run-model{display:flex;flex-wrap:wrap;gap:6px 12px;border-top:1px solid #dce4eb;margin-top:13px;padding-top:12px;font-size:12px;line-height:1.7;overflow-wrap:anywhere}.mc-run-model strong{color:#344c67}.mc-run-model span{color:#405670}.mc-run-model small{width:100%;color:#566b81;font-size:11px}.mc-route-select select:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
@media(max-width:620px){.mc-route-control{padding:14px}.mc-route-heading{align-items:flex-start;gap:10px}.mc-route-heading p{font-size:11px}.mc-route-heading>.button{padding:8px;font-size:11px}.mc-route-select{align-items:stretch;flex-direction:column;gap:7px}.mc-route-select select{font-size:12px}.mc-run-model{display:block}.mc-run-model strong,.mc-run-model span,.mc-run-model small{display:block}.mc-run-model span{margin-top:4px}}
.mc-request-url { overflow-wrap: anywhere; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; }
+13 -8
View File
@@ -9,11 +9,14 @@ import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
import { ModelBudgetSettings } from './ModelBudgetSettings';
import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoint.mjs';
type Connection = { id: string; name: string; brand: string; protocol: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
type Connection = { id: string; name: string; brand: string; protocol: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
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 Attempt = { modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; upstreamResponse?: { requestId?: string | null }; id: string; connectionId: string; poolId: string | null; 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; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type Attempt = { modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; 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; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
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: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
@@ -30,7 +33,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number }>(initial);
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; messagesAuth?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
@@ -97,7 +100,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<optgroup label="模型连接">{view.connections.map(connection => <option key={connection.id} value={(connection.id === 'legacy-default' ? 'legacy' : 'connection') + ':' + connection.id} disabled={!connection.enabled || connection.requiresKey && !connection.hasKey}>{connection.name} · {connection.model || '尚未填写型号'}{connection.status !== 'configured' ? ' · ' + states[connection.status] : ''}</option>)}</optgroup>
{!!view.pools.length && <optgroup label="模型池">{view.pools.map(pool => <option key={pool.id} value={'pool:' + pool.id}>{pool.name} · {pool.members.length} 个连接</option>)}</optgroup>}
</select></label>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '离线演示使用固定脚本,不调用大模型。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = view.connections.find(c => c.id === selected?.id); return connection ? `${connection.protocol === 'responses' ? 'Responses' : 'Chat Completions'} · ${connection.baseUrl} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '离线演示使用固定脚本,不调用大模型。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = view.connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
{runModel && <div className="mc-run-model"><strong>当前会话最近运行</strong><span>{runModel.mode === 'demo' ? '离线演示' : runModel.routing?.members?.length ? runModel.routing.members.map(member => member.name + ' · ' + member.model).join(';') : runModel.model}</span><small>这是该次运行封存的请求配置;实际返回型号请看请求账本。更改默认选择不会改写旧记录。</small></div>}
</section>
{tab === 'budgets' && runtimeConfig && <ModelBudgetSettings key={JSON.stringify(runtimeConfig)} value={runtimeConfig} disabled={locked} onSave={input => void act(async () => { await api('/model-center/runtime-budgets', input); if (alive.current) setNotice('运行预算已保存,当前模型选择保持。'); })} />}
@@ -108,8 +111,8 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>保存多条连接后可在上方切换;添加连接不会替换当前模型。凭据可选择本机加密保存。</p></div><button className="button primary" disabled={locked} onClick={addConnection}><Plus size={16} />添加连接</button></div>
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {value.protocol === 'responses' ? 'Responses' : 'Chat Completions'}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>接口</dt><dd>{value.baseUrl}</dd><dt>凭据</dt><dd>{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
@@ -122,12 +125,14 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option></select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value, nativeParameters: {}, outputTokenField: undefined })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label>视觉能力<select aria-label="视觉能力" value={draft.capabilityDeclarations.vision} onChange={event=>setDraft({...draft,capabilityDeclarations:{...draft.capabilityDeclarations,vision:event.target.value}})}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<p className="mc-help mc-full" aria-label="请求地址预览">POST {previewUrl(draft)}<br />{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。</p>
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="Messages 鉴权" value={draft.messagesAuth ?? 'api-key'} onChange={event => setDraft({ ...draft, messagesAuth: event.target.value })}><option value="api-key">x-api-key(Anthropic 标准)</option><option value="bearer">Bearer(兼容服务)</option></select></label>}
<label>请求模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
<label>型号核对<select aria-label="型号核对" value={draft.modelIdentityPolicy} onChange={event => setDraft({ ...draft, modelIdentityPolicy: event.target.value })}><option value="record">记录请求与返回型号</option><option value="require-match">无法核对或不一致时暂停</option></select></label>
<label className="mc-full">允许的返回型号(可选,逗号分隔)<input value={draft.modelIdentityAliasesText} onChange={event => setDraft({ ...draft, modelIdentityAliasesText: event.target.value })} /></label>
@@ -177,7 +182,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<fieldset><legend>模型池成员与权重</legend>{view.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>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol === 'responses' ? 'Responses' : value.protocol ? 'Chat Completions' : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{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={working} onClick={() => void act(async () => { await 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 + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{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={working} onClick={() => void act(async () => { await 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 + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
+3 -1
View File
@@ -15,7 +15,9 @@ export function ModelErrorDetails({ failure }: { failure: RuntimeFailure }) {
return <>{failure.modelIdentity && <ModelIdentityDetails identity={failure.modelIdentity} requestedModel={failure.model ?? '未记录'} />}<details className="model-error-details"><summary>{upstream ? '查看上游原文与请求信息' : '查看错误详情'}</summary>
<dl><dt>错误来源</dt><dd>{origin}</dd>
{failure.model && <><dt>请求型号</dt><dd>{failure.model}</dd></>}
{failure.endpoint && <><dt>实际接口</dt><dd>{failure.endpoint}{failure.route}</dd></>}
{(failure.requestUrl || failure.endpoint) && <><dt>请求地址</dt><dd>{failure.requestUrl || (failure.endpoint ?? '') + (failure.route ?? '')}</dd></>}
{failure.responseUrl && <><dt>响应地址</dt><dd>{failure.responseUrl}</dd></>}
{failure.redirectMode === 'manual' && <><dt>重定向</dt><dd>未自动跟随;不会向跳转地址转发凭据</dd></>}
{requestId && <><dt>上游请求 ID</dt><dd><code>{requestId}</code></dd></>}
{upstream?.responseId && <><dt>上游响应 ID</dt><dd><code>{upstream.responseId}</code></dd></>}
{failure.wireAttemptId && <><dt>本地物理尝试 ID</dt><dd><code>{failure.wireAttemptId}</code></dd></>}
+2 -2
View File
@@ -16,10 +16,10 @@ export function NativeParameters({ connection, busy, onCancel, onSave }: { conne
}}>
<h3>{connection.name} · 原生请求参数</h3>
<p className="mc-help">参数按所选协议原字段发送,并封存在实际请求中。具体模型是否接受这些选项,以服务响应为准;未填写的选项采用上游默认值。</p>
<label>输出上限字段<select aria-label="输出上限字段" value={field} disabled={busy} onChange={event => setField(event.target.value)}>{(connection.protocol === 'responses' ? ['max_output_tokens'] : ['max_tokens', 'max_completion_tokens']).map(value => <option key={value}>{value}</option>)}</select></label>
<label>输出上限字段<select aria-label="输出上限字段" value={field} disabled={busy} onChange={event => setField(event.target.value)}>{(connection.protocol === 'responses' ? ['max_output_tokens'] : connection.protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).map(value => <option key={value}>{value}</option>)}</select></label>
<p className="mc-help">数值沿用当前任务和连接的输出预算,不允许原生参数覆盖预算、消息、工具或接口。</p>
<label>原生参数 JSON<textarea aria-label="原生参数 JSON" rows={7} maxLength={8192} spellCheck={false} value={text} disabled={busy} onChange={event => setText(event.target.value)} /></label>
<p className="mc-help">{connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity。'}其他字段保存时会给出具体提示。语音、视频和服务端内置工具尚未接入。</p>
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? '已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking。启用 thinking 时 budget_tokens 至少1024且小于本次输出预算;具体型号支持情况以上游响应为准。' : connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity。'}其他字段保存时会给出具体提示。语音、视频和服务端内置工具尚未接入。</p>
{error && <p className="mc-card-warning" role="alert">{error}</p>}
<div className="mc-actions"><button className="button secondary" type="button" disabled={busy} onClick={onCancel}>取消</button><button className="button primary" disabled={busy} type="submit">保存原生参数</button></div>
</form>;
+1
View File
@@ -84,6 +84,7 @@ export interface RuntimeFailure {
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
detail?: string; suggestion?: string; attempts?: number; httpStatus?: number; code?: string | null;
occurredAt?: string; retryable?: boolean; historical?: boolean; endpoint?: string; model?: string;
requestUrl?: string; responseUrl?: string | null; redirected?: boolean; redirectMode?: string;
origin?: 'upstream' | 'local'; route?: string; type?: string | null; wireAttemptId?: string; upstreamRequestId?: string | null; retryAfterMs?: number; retryDecision?: string; limitReason?: string | null;
upstream?: { schema: number; scope: string; httpStatus?: number; code?: string | null; type?: string | null; message?: string | null; param?: string | null;
requestId?: string | null; responseId?: string | null; eventType?: string | null; reason?: string | null; headers?: Record<string, string>; retryAfter?: string | null;
+4 -2
View File
@@ -6,6 +6,7 @@ import { DatabaseSync } from 'node:sqlite';
import { parse as parseToml } from 'smol-toml';
import { modelEndpoint } from './model-hub.mjs';
import { MODEL_PROTOCOLS } from '../../shared/contracts/model-capabilities.mjs';
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
export class ConfigImporter {
@@ -29,6 +30,7 @@ export class ConfigImporter {
if (item.protocol && !MODEL_PROTOCOLS.includes(item.protocol)) { notices.push('第' + (index + 1) + '项协议暂不支持,已跳过。'); continue; }
rows.push({ sourceId: String(item.id ?? index), name: item.name, model: item.model, protocol: item.protocol ?? 'chat-completions',
streaming: item.streaming === true, capabilityDeclarations: item.capabilityDeclarations,
...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}),
baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
}
} else if (source === 'ccswitch') {
@@ -48,7 +50,7 @@ export class ConfigImporter {
if (!selected?.base_url || !['chat', 'responses'].includes(selected.wire_api)) { notices.push(provider.name + '使用未知协议,需对应的独立适配器。'); continue; }
rows.push({ sourceId: 'codex:' + provider.id, name: provider.name, baseUrl: selected.base_url, model: parsed.model,
protocol: selected.wire_api === 'responses' ? 'responses' : 'chat-completions', apiKey: config.auth?.OPENAI_API_KEY, requiresKey: true, brand: 'CCSwitch' });
} else notices.push(provider.name + '(' + provider.app_type + ')不属于已验证的Chat Completions配置,已跳过。');
} else notices.push(provider.name + '(' + provider.app_type + ')不属于已验证的导入格式,已跳过。');
}
} finally { db.close(); }
} else throw new Error('不支持该来源格式。');
@@ -57,7 +59,7 @@ export class ConfigImporter {
try {
if (!String(row.model ?? '').trim() || !String(row.name ?? '').trim()) throw new Error('缺少名称或模型');
if (row.apiKey !== undefined && typeof row.apiKey !== 'string') throw new Error('凭据不是字符串');
entries.push({ ...row, name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: modelEndpoint(row.baseUrl),
entries.push({ ...row, ...messagesAuthSettings(row.protocol, row.messagesAuth), name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: validateProtocolEndpoint(row.protocol, modelEndpoint(row.baseUrl)),
origin: digest({ source, path: path.resolve(filename), id: row.sourceId }), apiKey: row.apiKey?.trim() ?? '' });
} catch { notices.push(String(row.name ?? '某项配置').slice(0, 100) + '缺少有效的接口或模型,已跳过。'); }
}
+2 -1
View File
@@ -23,7 +23,8 @@ export class CredentialVault {
binding(connection) {
return sha(JSON.stringify(canonicalHost({ app: 'agent-workbench', scope: 'Windows.CurrentUser', userSid: this.userSid,
dataIdentity: this.dataIdentity, connectionId: connection.id, connectionRevision: connection.revision,
protocol: connection.protocol, baseUrl: connection.baseUrl, model: connection.model, requiresKey: connection.requiresKey })));
protocol: connection.protocol, baseUrl: connection.baseUrl, model: connection.model, requiresKey: connection.requiresKey,
...(connection.protocol === 'anthropic-messages' ? { messagesAuth: connection.messagesAuth ?? 'api-key' } : {}) })));
}
status(connection) {
if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' };
+74
View File
@@ -0,0 +1,74 @@
import { protocolFailure } from './protocols.mjs';
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const fail = message => { throw protocolFailure('Messages 流:' + message); };
// Each block and the whole message must close before any tool becomes dispatchable.
export function messagesStream() {
let message = null, active = null, deltaSeen = false, stopped = false, text = '', toolCount = 0;
const blocks = [];
return {
consume(event) {
if (event.type === 'ping') return;
if (stopped) fail('终结后新增了事件。');
if (event.type === 'message_start') {
const start = event.message;
if (message || start?.type !== 'message' || start.role !== 'assistant' || typeof start.id !== 'string' || !start.id
|| !Array.isArray(start.content) || start.content.length || start.stop_reason != null) fail('创建事件重复或消息身份/内容无效。');
message = structuredClone(start);
} else if (!message) fail('事件缺少原 message_start。');
else if (event.type === 'content_block_start') {
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
const block = event.content_block;
if (!object(block) || !['text', 'tool_use', 'thinking', 'redacted_thinking'].includes(block.type)) fail('未接入的内容块类型。');
if (block.type === 'text' && typeof block.text !== 'string' || block.type === 'tool_use' && (!object(block.input) || typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name)
|| block.type === 'thinking' && (typeof block.thinking !== 'string' || typeof block.signature !== 'string') || block.type === 'redacted_thinking' && typeof block.data !== 'string') fail('初始内容块格式无效。');
if (block.type === 'tool_use' && (++toolCount > 12 || blocks.some(item => item.block.id === block.id))) fail('工具数量超限或身份重复。');
blocks.push({ block: structuredClone(block), json: '', jsonSeen: false, closed: false }); active = event.index;
if (block.type === 'text') text += block.text;
} else if (event.type === 'content_block_delta') {
if (active === null || event.index !== active || deltaSeen || !object(event.delta)) fail('内容片段缺少所属未完成块。');
const entry = blocks[active], block = entry.block, delta = event.delta;
if (block.type === 'text' && delta.type === 'text_delta' && typeof delta.text === 'string') { block.text += delta.text; text += delta.text; }
else if (block.type === 'text' && delta.type === 'citations_delta' && object(delta.citation)) (block.citations ??= []).push(structuredClone(delta.citation));
else if (block.type === 'tool_use' && delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
if (Object.keys(block.input).length) fail('工具初始 input 与增量参数同时存在。');
entry.jsonSeen = true; entry.json += delta.partial_json;
} else if (block.type === 'thinking' && delta.type === 'thinking_delta' && typeof delta.thinking === 'string') block.thinking += delta.thinking;
else if (block.type === 'thinking' && delta.type === 'signature_delta' && typeof delta.signature === 'string') block.signature += delta.signature;
else fail('增量类型与原内容块不一致或尚未接入。');
} else if (event.type === 'content_block_stop') {
if (active === null || event.index !== active || deltaSeen) fail('块终结缺少所属原内容。');
const entry = blocks[active];
if (entry.jsonSeen) {
try { entry.block.input = JSON.parse(entry.json); } catch { fail('工具参数不是完整 JSON。'); }
if (!object(entry.block.input)) fail('工具参数必须是对象。');
}
entry.closed = true; active = null;
} else if (event.type === 'message_delta') {
if (active !== null || !object(event.delta) || !object(event.usage)) fail('消息终结前内容块未完成或 delta/usage 无效。');
const reason = event.delta.stop_reason;
if (deltaSeen && reason != null && reason !== message.stop_reason) fail('消息停止原因发生变化。');
if (reason != null) { message.stop_reason = reason; deltaSeen = true; }
message.stop_sequence = event.delta.stop_sequence ?? message.stop_sequence;
message.usage ??= {};
for (const [key, value] of Object.entries(event.usage)) if (value !== null && value !== undefined) {
if (['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens'].includes(key)
&& (!Number.isSafeInteger(value) || value < 0 || typeof message.usage[key] === 'number' && value < message.usage[key])) fail('累计用量无效或倒退。');
message.usage[key] = structuredClone(value);
}
} else if (event.type === 'message_stop') {
if (!deltaSeen || active !== null || blocks.some(entry => !entry.closed)) fail('缺少完整块或停止原因。');
stopped = true; message.content = blocks.map(entry => entry.block);
} else fail('未接入的事件类型 ' + String(event.type).slice(0, 100) + '。');
},
get text() { return text; },
get tools() { return toolCount; },
get usage() { return message?.usage ?? null; },
get stopped() { return stopped; },
finish() {
if (!stopped) throw protocolFailure('Messages 流断开或缺少 message_stop,工具未执行。', 'stream_interrupted');
return message;
},
};
}
+9 -6
View File
@@ -4,7 +4,8 @@ import { ModelRequestError } from '../../server/diagnostics.mjs';
import { CredentialVault } from './credential-vault.mjs';
import { visionProbe } from './vision-probe.mjs';
import { modelProtocol, capabilityDeclarations, capabilityView, capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
import { actualRequest, requestVariants } from '../../shared/contracts/model-request.mjs';
import { actualRequest, requestVariants, requestImages } from '../../shared/contracts/model-request.mjs';
import { messagesAuthSettings, validateProtocolEndpoint, modelRequestUrl } from '../../shared/contracts/model-endpoint.mjs';
import { modelWaitSettings } from './request-deadline.mjs';
import { sanitizeModelText } from './upstream-error.mjs';
import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs';
@@ -186,7 +187,8 @@ export class ModelHub {
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol, model,
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
baseUrl: modelEndpoint(input.baseUrl), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
@@ -249,7 +251,7 @@ export class ModelHub {
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight,
credentialRevision: this.credential(this.connection(value.connectionId))?.revision ?? 0 }));
if (!members.some(value => this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。');
return { ...config, baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField,
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
@@ -298,7 +300,7 @@ export class ModelHub {
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
const requirements = config.capabilityProbe ? [] : ['text', ...(requestVariants(body).some(value => value.tools?.length) ? ['tools'] : []),
...(requestVariants(body).some(value => (value.messages??value.input??[]).some(message=>Array.isArray(message.content)&&message.content.some(part=>['image_url','input_image'].includes(part.type))))?['vision']:[])];
...(requestImages(body).length ? ['vision'] : [])];
const rejections = config.capabilityProbe ? [] : routing.members.flatMap(value => capabilityRejections(value, [...requirements, ...(value.streaming ? ['streaming'] : [])], value.credentialRevision));
const eligibleRouting = { ...routing, members: routing.members.filter(value => !rejections.some(item => item.connectionId === value.id)) };
if (!eligibleRouting.members.length) {
@@ -319,7 +321,8 @@ export class ModelHub {
const bytes = JSON.stringify(actualBody);
const attempt = { id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
connectionId: member.id, connectionRevision: member.revision, credentialRevision: member.credentialRevision, poolId: routing.type === 'pool' ? routing.id : null,
poolRevision: routing.revision, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true, endpoint: member.baseUrl, ordinal: count, status: 'running', startedAt: stamp(),
poolRevision: routing.revision, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true, endpoint: member.baseUrl,
requestUrl: modelRequestUrl(member), ...(member.protocol === 'anthropic-messages' ? messagesAuthSettings(member.protocol, member.messagesAuth) : {}), ordinal: count, status: 'running', startedAt: stamp(),
requestBytes: Buffer.byteLength(bytes, 'utf8'), requirements, rejections,
requestSha256: createHash('sha256').update(bytes).digest('hex'), usage: null, usageStatus: 'unknown' };
try {
@@ -366,7 +369,7 @@ export class ModelHub {
if (event.stream) attempt.stream = event.stream;
onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, protocol: modelProtocol(member.protocol), model: member.model, modelAttemptId: attempt.id });
};
const result = await execute({ ...config, ...modelIdentitySettings(member), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
const result = await execute({ ...config, ...modelIdentitySettings(member), ...messagesAuthSettings(member.protocol, member.messagesAuth), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
attempt.status = 'completed'; attempt.usage = result.usage ?? attempt.usage; attempt.usageStatus = attempt.usage ? 'reported' : 'unknown';
if (result.compatibility?.length) attempt.compatibility = result.compatibility;
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
+20 -10
View File
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
import { protocolFailure, normalizeProtocolResponse, validateModelResponse, reportedUsage } from './protocols.mjs';
import { httpFailure } from '../../server/diagnostics.mjs';
import { upstreamCapture } from './upstream-error.mjs';
import { messagesStream } from './messages-stream.mjs';
// Only a fully terminated and validated stream produces a dispatchable message.
// Progress is cumulative, bounded and explicitly not a tool invocation.
@@ -13,6 +14,8 @@ export async function readModelStream(response, config, signal, onProgress, tool
let lastProgress = 0, responseId = null, validated = false, progressTimer = null, progressFailure = null;
let upstreamFailure = null;
const calls = new Map(), responseCalls = new Map();
const messages = config.protocol === 'anthropic-messages' ? messagesStream() : null;
let eventName = '';
const progress = force => {
if (!force && Date.now() - lastProgress < 100) {
progressTimer ??= setTimeout(() => {
@@ -24,17 +27,19 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
lastProgress = Date.now();
onProgress?.({ phase: 'running', streaming: true, protocol: config.protocol ?? 'chat-completions', streamSequence: frames,
streamBytes: bytes, textPreview: text.slice(0, 8000), textCharacters: text.length, toolFragments: Math.max(calls.size, responseCalls.size) });
streamBytes: bytes, textPreview: text.slice(0, 8000), textCharacters: text.length, toolFragments: Math.max(calls.size, responseCalls.size, messages?.tools ?? 0) });
};
const processData = raw => {
if (terminal || done) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
if (terminal || done || messages?.stopped) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
frames++;
if (frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
if (raw === '[DONE]') { if (config.protocol === 'responses') throw protocolFailure('Responses缺少正式终结事件。'); done = true; return; }
if (raw === '[DONE]') { if (config.protocol !== 'chat-completions' && config.protocol) throw protocolFailure('所选协议缺少正式终结事件。'); done = true; return; }
let event;
try { event = JSON.parse(raw); } catch { throw protocolFailure('模型事件流包含无效JSON。'); }
observeIdentity?.(event);
if (event.usage) usage = event.usage;
if (!event || typeof event !== 'object' || Array.isArray(event)) throw protocolFailure('模型事件格式无效。');
if (messages && eventName && eventName !== event.type) throw protocolFailure('Messages SSE 事件名称与数据类型不一致。');
if (event.usage && !messages) usage = event.usage;
const failUpstream = () => {
usage = event.response?.usage ?? usage;
const { details } = upstreamCapture({ raw: Buffer.from(raw, 'utf8'), event, scope: 'sse-event', status: response.status, headers: response.headers }, redact);
@@ -46,7 +51,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
throw upstreamFailure;
};
if (event.error || event.type === 'error') failUpstream();
if (config.protocol === 'responses') {
if (messages) {
messages.consume(event); text = messages.text; usage = messages.usage;
} else if (config.protocol === 'responses') {
if (event.sequence_number !== undefined) {
if (!Number.isSafeInteger(event.sequence_number) || event.sequence_number <= sequence) throw protocolFailure('Responses事件序列重复或逆序。');
sequence = event.sequence_number;
@@ -102,8 +109,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
progress(false);
};
const line = value => {
if (value === '') { if (data.length) { processData(data.join('\n')); data = []; } }
if (value === '') { if (data.length) { processData(data.join('\n')); data = []; } eventName = ''; }
else if (value.startsWith('data:')) data.push(value.slice(5).replace(/^ /, ''));
else if (value.startsWith('event:')) eventName = value.slice(6).trim();
};
try {
while (true) {
@@ -129,7 +137,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (buffer.endsWith('\r')) { line(buffer.slice(0, -1)); buffer = ''; }
if (buffer || data.length) throw protocolFailure('模型流在完整事件边界前断开,未采用片段。', 'stream_interrupted');
let value;
if (config.protocol === 'responses') {
if (messages) {
value = messages.finish(); terminal = value;
} else if (config.protocol === 'responses') {
if (!terminal) throw protocolFailure('Responses流断开或缺少终结事件。', 'stream_interrupted');
value = normalizeProtocolResponse(config, terminal);
const received = value.choices[0].message;
@@ -143,14 +153,14 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (!done || !['stop', 'tool_calls'].includes(finish)) throw protocolFailure('Chat流未完整终结或达到输出上限,未执行工具。', 'stream_interrupted');
value = { choices: [{ message: { role: 'assistant', content: text, ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
}
validateModelResponse(config.protocol === 'responses' ? normalizeProtocolResponse(config, value) : value, tools);
validateModelResponse(config.protocol !== 'chat-completions' && config.protocol ? normalizeProtocolResponse(config, value) : value, tools);
validated = true; progress(true);
return { value, evidence: { bytes, frames, sha256: hash.copy().digest('hex'), terminal: true, protocol: config.protocol ?? 'chat-completions' } };
} finally {
if (progressTimer) clearTimeout(progressTimer);
try { await reader.cancel(); } catch {} reader.releaseLock();
onProgress?.({ streamCapture: Buffer.concat(chunks), ...(upstreamFailure ? { upstream: upstreamFailure.diagnostic.upstream } : {}),
reportedUsage: reportedUsage(config, { usage: terminal?.usage ?? usage }), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done || !!upstreamFailure, protocol: config.protocol ?? 'chat-completions' } });
reportedUsage: reportedUsage(config, { usage: terminal?.usage ?? messages?.usage ?? usage }), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done || messages?.stopped || !!upstreamFailure, protocol: config.protocol ?? 'chat-completions' } });
}
}
+31 -1
View File
@@ -1,11 +1,20 @@
import { ModelRequestError } from '../../server/diagnostics.mjs';
export const protocolFailure = (message, kind = 'protocol') => new ModelRequestError({ kind, source: 'model_connection', origin: 'local', stage: 'model_request',
title: '模型响应未通过完整性核对', message, retryable: false, occurredAt: new Date().toISOString() });
export const protocolRoute = config => config.protocol === 'responses' ? '/responses' : '/chat/completions';
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
export function reportedUsage(config, value) {
const raw = value?.usage;
if (!raw || typeof raw !== 'object') return null;
if (config.protocol === 'anthropic-messages') {
const valid = number => Number.isSafeInteger(number) && number >= 0;
const cached = raw.cache_read_input_tokens ?? 0, created = raw.cache_creation_input_tokens ?? 0;
if (![raw.input_tokens, raw.output_tokens, cached, created].every(valid)) return null;
const input = raw.input_tokens + cached + created, total = input + raw.output_tokens;
if (!Number.isSafeInteger(total)) return null;
return { prompt_tokens: input, completion_tokens: raw.output_tokens, total_tokens: total,
prompt_tokens_details: { cached_tokens: cached, cache_creation_tokens: created }, raw: structuredClone(raw), protocol: 'anthropic-messages' };
}
const input = config.protocol === 'responses' ? raw.input_tokens : raw.prompt_tokens;
const output = config.protocol === 'responses' ? raw.output_tokens : raw.completion_tokens;
const valid = number => Number.isSafeInteger(number) && number >= 0;
@@ -42,6 +51,27 @@ export function validateModelResponse(value, tools) {
}
export function normalizeProtocolResponse(config, value) {
if (config.protocol === 'anthropic-messages') {
if (value?.type !== 'message' || typeof value.id !== 'string' || !value.id || value.role !== 'assistant' || !Array.isArray(value.content)
|| !['end_turn', 'tool_use', 'stop_sequence', 'refusal'].includes(value.stop_reason)) throw protocolFailure('Messages 未完整结束或停止原因为输出/上下文上限、暂停或未知;原响应未用于执行工具。');
const calls = [], texts = [];
for (const block of value.content) {
if (!block || typeof block !== 'object' || Array.isArray(block)) throw protocolFailure('Messages 内容块格式无效。');
if (block.type === 'text' && typeof block.text === 'string') texts.push(block.text);
else if (block.type === 'tool_use') {
if (typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name || !block.input || typeof block.input !== 'object' || Array.isArray(block.input)) throw protocolFailure('Messages 工具身份或 input 对象无效。');
calls.push({ id: block.id, type: 'function', function: { name: block.name, arguments: JSON.stringify(block.input) } });
} else if (block.type === 'thinking' && typeof block.thinking === 'string' && typeof block.signature === 'string' && block.signature) {
// Opaque provider history is retained for this endpoint/model, not exposed as assistant text.
} else if (block.type === 'redacted_thinking' && typeof block.data === 'string' && block.data) {
// Keep the upstream opaque block unchanged for a subsequent tool round.
} else throw protocolFailure('Messages 包含未接入或不完整的内容块:' + String(block?.type ?? '未知').slice(0, 100) + '。');
}
if ((value.stop_reason === 'tool_use') !== (calls.length > 0)) 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) } },
finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: reportedUsage(config, value) };
}
if (config.protocol !== 'responses') return value;
if (value.status !== 'completed' || !Array.isArray(value.output)) throw protocolFailure('Responses未完整结束,原响应未用于执行工具。');
const calls = [], texts = [], ids = new Set();
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.24.3';
export const APP_VERSION = '1.24.4';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+27 -12
View File
@@ -11,6 +11,7 @@ import { modelWaitSettings, requestDeadline } from '../core/models/request-deadl
import { ModelTransport } from '../core/models/transport.mjs';
import { localModelEstimate } from '../shared/contracts/model-reservation.mjs';
import { ERROR_CAPTURE_LIMIT, readErrorResponse, upstreamCapture } from '../core/models/upstream-error.mjs';
import { messagesAuthSettings } from '../shared/contracts/model-endpoint.mjs';
export const engineToolDefinitions = [
{ type: 'function', function: { name: 'inspect_engine_checks', description: '读取当前Task已经保存的外部引擎连接核验:真实安装版本、启动完成信号、SDK会话、进程关闭、原报告工件和能力限制。不会启动引擎或发送prompt;完整原记录通过已有read_artifact读取。', parameters: { type: 'object', properties: {}, additionalProperties: false } } },
@@ -154,7 +155,12 @@ export class Provider {
async request(config, route, body, signal, key = this.apiKey, onProgress, options = {}) {
const base = this.validate({ ...config, mode: 'demo' });
const headers = { 'Content-Type': 'application/json' };
if (key) headers.Authorization = 'Bearer ' + key;
if (config.protocol === 'anthropic-messages') {
headers['anthropic-version'] = '2023-06-01';
const { messagesAuth } = messagesAuthSettings(config.protocol, config.messagesAuth);
if (key) headers[messagesAuth === 'bearer' ? 'Authorization' : 'x-api-key'] = messagesAuth === 'bearer' ? 'Bearer ' + key : key;
} else if (key) headers.Authorization = 'Bearer ' + key;
const requestUrl = base + route;
const waits = modelWaitSettings(config), timeoutMs = body ? waits.modelResponseTimeoutMs : 20000;
const policy = { attempts: 3, delays: [500, 1500], timeoutMs, totalTimeoutMs: timeoutMs,
idleTimeoutMs: waits.modelStreamIdleTimeoutMs, ...this.retryPolicy, ...options };
@@ -172,10 +178,10 @@ export class Provider {
const timeout = requestDeadline({ signal, timeoutMs: Math.max(1, Math.min(policy.timeoutMs, deadline - Date.now())), idleTimeoutMs: policy.idleTimeoutMs });
const requestSignal = timeout.signal;
let readingStream = false, streamTerminalSeen = false, dispatched = false, usage = null, outcome = 'unknown';
const receipt = { attemptId: randomUUID(), endpoint: base, model: config.model, protocol: config.protocol ?? 'chat-completions', startedAt: new Date().toISOString(),
const receipt = { attemptId: randomUUID(), endpoint: base, requestUrl, model: config.model, protocol: config.protocol ?? 'chat-completions', startedAt: new Date().toISOString(),
...(body?{localEstimate:localModelEstimate(body)}:{}) };
const context = { endpoint: base, model: config.model, route, attempt, attemptId: receipt.attemptId };
onProgress?.({ phase: 'running', attempt, maxAttempts: policy.attempts, endpoint: base, route, wireAttemptId: receipt.attemptId });
const context = { endpoint: base, requestUrl, model: config.model, route, attempt, attemptId: receipt.attemptId };
onProgress?.({ phase: 'running', attempt, maxAttempts: policy.attempts, endpoint: base, route, requestUrl, wireAttemptId: receipt.attemptId });
let responseDetails = null;
const identityObserver = body ? modelIdentityObserver(body.model, { ...config, ...options }) : null;
const publishIdentity = complete => {
@@ -200,11 +206,18 @@ export class Provider {
dispatched = true;
const transport=this.fetcher?null:(this.transport??=new ModelTransport());
if(transport)onProgress?.({phase:'running',transport:transport.profile,attempt,maxAttempts:policy.attempts,wireAttemptId:receipt.attemptId});
const response = await (this.fetcher??transport.fetch.bind(transport))(base + route, { method: body ? 'POST' : 'GET', headers,
body: body ? JSON.stringify(body) : undefined, signal: requestSignal });
const response = await (this.fetcher??transport.fetch.bind(transport))(requestUrl, { method: body ? 'POST' : 'GET', headers,
body: body ? JSON.stringify(body) : undefined, signal: requestSignal, redirect: 'manual' });
// Never forward either credential header to a redirect target. The
// observed response URL is diagnostic data; queries/credentials are removed.
let responseUrl = null;
if (response.url) { const observed = new URL(response.url); observed.username = ''; observed.password = ''; observed.search = ''; observed.hash = ''; responseUrl = this.redact(observed.href, key); }
Object.assign(receipt, { responseUrl, redirected: response.redirected === true, redirectMode: 'manual' });
Object.assign(context, { responseUrl, redirected: receipt.redirected, redirectMode: 'manual' });
const metadata = upstreamCapture({ raw: Buffer.alloc(0), status: response.status, headers: response.headers }, value => this.redact(value, key)).details;
receipt.upstreamRequestId = metadata.requestId; receipt.httpStatus = response.status;
onProgress?.({ phase: 'running', attempt, maxAttempts: policy.attempts, upstreamResponse: { httpStatus: response.status, requestId: metadata.requestId, headers: metadata.headers } });
onProgress?.({ phase: 'running', attempt, maxAttempts: policy.attempts, upstreamResponse: { httpStatus: response.status, requestId: metadata.requestId, headers: metadata.headers,
requestUrl, responseUrl, redirected: receipt.redirected, redirectMode: 'manual' } });
if (!response.ok) {
const received = await readErrorResponse(response, requestSignal);
if (!received.truncated && !received.interrupted) { try { usage = reportedUsage(config, JSON.parse(received.raw.toString('utf8'))); } catch {} }
@@ -225,7 +238,7 @@ export class Provider {
assertIdentity();
const value = options.transformResponse ? options.transformResponse(streamed.value) : streamed.value;
outcome = 'completed';
this.lastRequest = { source: 'model_connection', endpoint: base, route, model: config.model, modelIdentity: receipt.modelIdentity, status: 'completed', attempts: attempt, durationMs: Date.now() - startedAt, stream: streamed.evidence };
this.lastRequest = { source: 'model_connection', ...context, modelIdentity: receipt.modelIdentity, status: 'completed', attempts: attempt, durationMs: Date.now() - startedAt, stream: streamed.evidence };
onProgress?.({ phase: 'completed', attempt, maxAttempts: policy.attempts, durationMs: Date.now() - startedAt, stream: streamed.evidence, modelIdentity: receipt.modelIdentity });
return value;
}
@@ -237,7 +250,7 @@ export class Provider {
throw new ModelRequestError({ ...context, id: randomUUID(), source: 'model_connection', stage: 'model_request',
origin: 'local', upstream,
kind: 'protocol', title: '模型接口响应格式不兼容', message: '模型服务没有返回有效 JSON,请核对兼容接口地址。',
attempts: attempt, retryable: false, occurredAt: new Date().toISOString(), suggestion: '填写服务实际提供的 Chat Completions 接口根地址。' });
attempts: attempt, retryable: false, occurredAt: new Date().toISOString(), suggestion: '核对服务实际提供的协议与本次请求地址。' });
}
if (result.error || config.protocol === 'responses' && ['failed', 'incomplete', 'cancelled'].includes(result.status)) {
const upstream = captureResponse(response, { raw: Buffer.from(text, 'utf8') });
@@ -257,7 +270,7 @@ export class Provider {
throw cause;
}
}
this.lastRequest = { source: 'model_connection', endpoint: base, route, model: config.model, modelIdentity: receipt.modelIdentity, status: 'completed', attempts: attempt, durationMs: Date.now() - startedAt };
this.lastRequest = { source: 'model_connection', ...context, modelIdentity: receipt.modelIdentity, status: 'completed', attempts: attempt, durationMs: Date.now() - startedAt };
outcome = 'completed';
onProgress?.({ phase: 'completed', attempt, maxAttempts: policy.attempts, durationMs: Date.now() - startedAt, modelIdentity: receipt.modelIdentity });
return result;
@@ -266,7 +279,9 @@ export class Provider {
signal?.throwIfAborted();
let diagnostic = connectionFailure(error, { ...context, method:body?'POST':'GET',responseReceived:receipt.httpStatus!==undefined,
transport:this.transport?.profile,timedOut: !!timeout.timeout, timeout: timeout.timeout, redact: value => this.redact(value, key) });
diagnostic = { ...diagnostic, origin: diagnostic.origin ?? 'local', wireAttemptId: receipt.attemptId, upstreamRequestId: diagnostic.upstreamRequestId ?? receipt.upstreamRequestId,
diagnostic = { ...diagnostic, requestUrl, ...(receipt.responseUrl ? { responseUrl: receipt.responseUrl } : {}),
...(receipt.redirectMode ? { redirected: receipt.redirected, redirectMode: receipt.redirectMode } : {}),
origin: diagnostic.origin ?? 'local', wireAttemptId: receipt.attemptId, upstreamRequestId: diagnostic.upstreamRequestId ?? receipt.upstreamRequestId,
...(responseDetails && !diagnostic.upstream ? { upstream: responseDetails } : {}) };
if (readingStream && diagnostic.kind !== 'model_identity') diagnostic = { ...diagnostic, retryable: false, failoverAllowed: false, outcome: streamTerminalSeen ? 'failed' : 'unknown',
kind: diagnostic.origin === 'upstream' ? diagnostic.kind : timeout.timeout ? 'timeout' : streamTerminalSeen || diagnostic.kind === 'protocol' ? 'protocol' : 'stream_interrupted',
@@ -297,7 +312,7 @@ export class Provider {
this.activeRequests--;
operation.finish();
if (signal?.aborted) this.lastRequest = { source: 'model_connection', stage: 'model_request',
endpoint: base, route, model: config.model, status: 'interrupted', attempts,
endpoint: base, route, requestUrl, model: config.model, status: 'interrupted', attempts,
durationMs: Date.now() - startedAt, occurredAt: new Date().toISOString() };
}
}
+1
View File
@@ -552,6 +552,7 @@ export class Store extends EventEmitter {
receipts.push({ attemptId: receipt.attemptId, requestId: receipt.requestId ?? null,
connectionId: receipt.connectionId ?? null, connectionName: receipt.connectionName ?? null,
model: receipt.model, endpoint: receipt.endpoint, protocol: receipt.protocol,
...(receipt.requestUrl ? { requestUrl: receipt.requestUrl, responseUrl: receipt.responseUrl ?? null, redirected: receipt.redirected === true, redirectMode: receipt.redirectMode } : {}),
startedAt: receipt.startedAt, finishedAt: receipt.finishedAt, outcome: receipt.outcome,
usageStatus: receipt.usage ? 'reported' : 'unknown', usage: receipt.usage ?? null,
...(receipt.localEstimate?{localEstimate:structuredClone(receipt.localEstimate)}:{}),
@@ -0,0 +1,68 @@
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const fail = message => { throw new Error('Messages 请求未发送:' + message); };
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 };
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) } };
fail('未接入的输入内容块 ' + String(part?.type ?? '未知') + '。');
});
}
export function messagesBody(config, messages, tools, native) {
if (native.nativeParameters.thinking?.type === 'enabled' && native.nativeParameters.thinking.budget_tokens >= config.maxOutputTokens) fail('thinking.budget_tokens 必须小于本次 max_tokens 输出预算。');
const system = [], wire = [];
const append = (role, content) => {
if (!content.length) return;
if (wire.at(-1)?.role === role) wire.at(-1).content.push(...content);
else wire.push({ role, content });
};
for (const message of messages) {
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 }]);
} 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 (!Array.isArray(state.content)) fail('原生助手历史格式无效。');
append('assistant', structuredClone(state.content));
continue;
}
const blocks = contentBlocks(message.content ?? '');
for (const call of message.tool_calls ?? []) {
let input; try { input = JSON.parse(call.function?.arguments); } catch { fail('工具历史参数不是完整 JSON。'); }
if (!object(input) || typeof call.id !== 'string' || !call.id || typeof call.function?.name !== 'string' || !call.function.name) fail('工具历史身份或参数无效。');
blocks.push({ type: 'tool_use', id: call.id, name: call.function.name, input });
}
append('assistant', blocks);
} else fail('未接入的消息角色 ' + String(message.role) + '。');
}
if (system.some(block => block.type !== 'text')) fail('系统消息只支持文本。');
const definitions = (tools ?? []).map(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 };
});
return { model: config.model, ...(system.length ? { system } : {}), messages: wire,
...(definitions.length ? { tools: definitions, tool_choice: { type: 'auto' } } : {}),
max_tokens: config.maxOutputTokens, stream: config.streaming === true, ...native.nativeParameters };
}
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 });
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 } : {}) });
}
return history;
}
+1
View File
@@ -23,6 +23,7 @@ export function modelSnapshot(config) {
...modelWaitSettings(config),
...modelIdentitySettings(config),
...(config.protocol ? { protocol: config.protocol, streaming: config.streaming === true } : {}),
...(config.protocol === 'anthropic-messages' ? { messagesAuth: config.messagesAuth ?? 'api-key' } : {}),
...(config.nativeParameters ? { nativeParameters: structuredClone(config.nativeParameters), outputTokenField: config.outputTokenField } : {}),
...(config.modelRouting ? { routing: structuredClone(config.modelRouting) } : {}),
};
+2 -2
View File
@@ -1,9 +1,9 @@
export const MODEL_PROTOCOLS = ['chat-completions', 'responses'];
export const MODEL_PROTOCOLS = ['chat-completions', 'responses', 'anthropic-messages'];
export const MODEL_CAPABILITIES = ['text', 'tools', 'streaming', 'vision', 'audio'];
const failure = message => Object.assign(new Error(message), { status: 400 });
export function modelProtocol(value = 'chat-completions') {
if (!MODEL_PROTOCOLS.includes(value)) throw failure('请选择已接入的 Chat Completions 或 Responses 协议。');
if (!MODEL_PROTOCOLS.includes(value)) throw failure('请选择已接入的 Chat Completions、Responses 或 Anthropic Messages 协议。');
return value;
}
@@ -0,0 +1,5 @@
export function protocolLabel(protocol: string): string;
export function protocolRoute(config: { protocol?: string; baseUrl: string }): string;
export function modelRequestUrl(config: { protocol?: string; baseUrl: string }): string;
export function messagesAuthSettings(protocol?: string, value?: string): { messagesAuth?: string };
export function validateProtocolEndpoint(protocol: string, baseUrl: string): string;
+29
View File
@@ -0,0 +1,29 @@
import { modelProtocol } from './model-capabilities.mjs';
export const protocolLabel = protocol => ({ 'chat-completions': 'Chat Completions', responses: 'Responses', 'anthropic-messages': 'Anthropic Messages' }[protocol] ?? protocol);
export function protocolRoute(config) {
const protocol = modelProtocol(config.protocol);
if (protocol === 'responses') return '/responses';
if (protocol === 'anthropic-messages') {
validateProtocolEndpoint(protocol, config.baseUrl);
return /\/v1$/i.test(new URL(config.baseUrl).pathname.replace(/\/+$/, '')) ? '/messages' : '/v1/messages';
}
return '/chat/completions';
}
export function modelRequestUrl(config) { return config.baseUrl.replace(/\/+$/, '') + protocolRoute(config); }
export function messagesAuthSettings(protocol, value) {
if (protocol !== 'anthropic-messages') return {};
const messagesAuth = value ?? 'api-key';
if (!['api-key', 'bearer'].includes(messagesAuth)) throw Object.assign(new Error('Messages 鉴权请选择 x-api-key 或 Bearer。'), { status: 400 });
return { messagesAuth };
}
export function validateProtocolEndpoint(protocol, baseUrl) {
if (protocol === 'anthropic-messages' && /\/(?:messages|responses|chat\/completions)$/i.test(new URL(baseUrl).pathname.replace(/\/+$/, ''))) {
throw Object.assign(new Error('请填写 Messages 服务根地址或 /v1 根地址,不要填写完整的 /messages 或其它协议路径。'), { status: 400 });
}
return baseUrl;
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function modelIdentityObserver(requestedModel, config = {}) {
const settings = modelIdentitySettings(config), models = new Set(); let invalid = false;
return {
observe(value) {
for (const object of [value, value?.response]) {
for (const object of [value, value?.response, ...(value?.type === 'message_start' ? [value.message] : [])]) {
if (!object || !Object.hasOwn(object, 'model')) continue;
if (!validModel(object.model) || models.size >= 16 && !models.has(object.model)) { invalid = true; continue; }
models.add(object.model);
+6 -3
View File
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
import { modelProtocol } from './model-capabilities.mjs';
import { nativeParameterSettings } from './native-parameters.mjs';
import { messagesBody, messagesHistory } from './anthropic-messages.mjs';
function wireBody(config, messages, tools) {
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
@@ -9,6 +10,7 @@ function wireBody(config, messages, tools) {
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
const cleanMessages = messages.map(({ providerState, ...message }) => message);
if (protocol === 'anthropic-messages') return messagesBody(config, messages, tools, native);
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', [native.outputTokenField]: config.maxOutputTokens, stream, ...native.nativeParameters,
...(stream ? { stream_options: { include_usage: true } } : {}) };
const input = messages.flatMap(message => {
@@ -26,7 +28,7 @@ function wireBody(config, messages, tools) {
export function completionBody(config, messages, tools) {
const members = config.modelRouting?.members;
if (members?.some(member => member.protocol === 'responses' || member.streaming === true || member.nativeParameters || member.outputTokenField)) {
if (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,
maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
@@ -48,6 +50,7 @@ export function actualRequest(body, member) {
export const outputReservation = body => body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens;
export function requestHistory(body) {
if (body.system !== undefined || body.tools?.some(tool => tool.input_schema) || body.messages?.some(message => Array.isArray(message.content) && message.content.some(part => ['tool_use', 'tool_result', 'thinking', 'image'].includes(part.type)))) return messagesHistory(body);
if (body.messages) return body.messages;
const messages = [];
for (const item of body.input ?? []) {
@@ -67,7 +70,7 @@ export function requestMetrics(body) {
const variants = requestVariants(body);
const images=requestImages(body);
const imageReserve=imageTokenReserve(body);
const estimates=variants.map(value=>Math.ceil(Buffer.byteLength(JSON.stringify(value, (key,item)=>typeof item==='string'&&item.startsWith('data:image/')?'[bounded image bytes]':item),'utf8')/3)
const estimates=variants.map(value=>Math.ceil(Buffer.byteLength(JSON.stringify(value, (key,item)=>typeof item==='string'&&item.startsWith('data:image/')?'[bounded image bytes]':item?.type==='base64'&&item.media_type==='image/png'?{...item,data:'[bounded image bytes]'}:item),'utf8')/3)
+ (value.messages?.length ?? value.input?.length ?? 0)*8+(value.tools?.length??0)*16+imageTokenReserve(value));
if(images.length)return {bytes,sha256:createHash('sha256').update(serialized,'utf8').digest('hex'),estimatedInputTokens:Math.max(...estimates),
imageReservationTokens:imageReserve,imageCount:Math.max(...variants.map(value=>requestImages(value).length)),estimateMethod:'text-utf8-plus-image-reservation-v1',imageEstimate:'local-reservation-not-provider-billing'};
@@ -78,7 +81,7 @@ export function requestMetrics(body) {
}
export function requestImages(body) {
return requestVariants(body).flatMap(value=>(value.messages??value.input??[]).flatMap(message=>Array.isArray(message.content)?message.content.filter(part=>['image_url','input_image'].includes(part.type)).map(part=>part.type==='image_url'?part.image_url?.url:part.image_url):[]));
return requestVariants(body).flatMap(value=>(value.messages??value.input??[]).flatMap(message=>Array.isArray(message.content)?message.content.filter(part=>['image_url','input_image','image'].includes(part.type)).map(part=>part.type==='image_url'?part.image_url?.url:part.type==='image'?`data:${part.source?.media_type};base64,${part.source?.data}`:part.image_url):[]));
}
export function imageTokenReserve(body){
return Math.max(0,...requestVariants(body).map(value=>requestImages(value).reduce((total,url)=>{
+8 -3
View File
@@ -5,11 +5,16 @@ const verbosity = ['low', 'medium', 'high'];
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField) {
if (!object(parameters) || JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
const allowed = protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
const allowed = protocol === 'anthropic-messages' ? ['temperature', 'top_p', 'top_k', 'stop_sequences', 'thinking'] : protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed'];
for (const [key, value] of Object.entries(parameters)) {
if (!allowed.includes(key)) fail('所选协议尚未接入原生参数:' + key + '。参数未保存或发送。');
if (key === 'temperature' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 2)) fail('temperature应为0–2之间的数字。');
if (key === 'temperature' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > (protocol === 'anthropic-messages' ? 1 : 2))) fail('temperature超出所选协议范围(Messages 0–1,其它 0–2)。');
if (key === 'top_k' && (!Number.isSafeInteger(value) || value < 0)) fail('Messages top_k应为非负安全整数。');
if (key === 'stop_sequences' && (!Array.isArray(value) || value.length > 32 || value.some(item => typeof item !== 'string' || !item || item.length > 1000))) fail('Messages stop_sequences应为最多32项的非空字符串数组。');
if (key === 'thinking' && (!object(value) || !['enabled', 'disabled', 'adaptive'].includes(value.type)
|| Object.keys(value).some(field => !['type', 'budget_tokens'].includes(field))
|| (value.type === 'enabled' ? !Number.isSafeInteger(value.budget_tokens) || value.budget_tokens < 1024 : value.budget_tokens !== undefined))) fail('Messages thinking格式为disabled/adaptive,或enabled加至少1024的budget_tokens。');
if (key === 'top_p' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) fail('top_p应为0–1之间的数字。');
if (key === 'seed' && !Number.isSafeInteger(value)) fail('seed应为安全整数。');
if (key === 'parallel_tool_calls' && typeof value !== 'boolean') fail('parallel_tool_calls应为布尔值。');
@@ -19,6 +24,6 @@ export function nativeParameterSettings(protocol = 'chat-completions', parameter
if (key === 'text' && (!object(value) || Object.keys(value).length !== 1 || !verbosity.includes(value.verbosity))) fail('Responses text当前接入格式为{"verbosity":"low|medium|high"}。');
}
const field = outputTokenField ?? (protocol === 'responses' ? 'max_output_tokens' : 'max_tokens');
if (!(protocol === 'responses' ? ['max_output_tokens'] : ['max_tokens', 'max_completion_tokens']).includes(field)) fail('输出上限字段与所选协议不兼容。');
if (!(protocol === 'responses' ? ['max_output_tokens'] : protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).includes(field)) fail('输出上限字段与所选协议不兼容。');
return { nativeParameters: structuredClone(parameters), outputTokenField: field };
}
+11
View File
@@ -1,5 +1,16 @@
# Agent Workbench:核心代理能力研究与产品计划
## 当前 M:原生 Anthropic Messages 与实际线路诊断
沿用 planning-with-files、product-ui-ux 与 frontend-design;仅修改本次接入流程,不委派子代理。基线 b832982d,分支 feat/anthropic-messages-1.24.4。保留原正式宿主、Provider、内存凭据及 J/K/L 原件,不续跑旧任务。
1. [complete] 核对官方 SDK Messages/供应商契约与现有适配边界;官方网页地区不可用实际收据保留,不能把HTTP200当成功读取。
2. [complete] 实现 Messages 请求/工具历史/图片、JSON/SSE 完整性、身份、缓存用量、错误、取消以及可核对的请求地址;连接保存/刷新和混合池集成。
3. [complete] 最终25专项、144相关及先前61相关/48旧协议身份通过;编译宿主七组两视口新UI与四类历史UI通过。首307漏URL失败保留并修复,源码审查完成,按范围本地提交后冻结发行。
4. [in_progress] 正式只读前基线与K最终精确一致;新不可变发行的独立源码/便携/安装验证,随后保留原宿主升级及正式网页/原生窗口回看,逐原行/全会话/工件/公开配置核对。
5. [pending] 同一 apikey 凭据由原 Provider 使用,单次新 Messages 身份预检(1请求、最多256输出、累计16000 tokens、无工具/重试/切池);如实封存成功或失败,原 J/E/H 不变。
6. [pending] 回顾、证据离线核验与本地 Git 收尾;真实工程/Purge 仍独立判定,不把协议夹具或型号字符串一致当底层权重认证。
## 当前 L:apikey 请求/返回型号差异调查
- [complete] 原J字节与八个发行源码输入核对:Claude请求、poolId=null、GPT原SSE无脱敏;没有客户端GPT回填。实际地址按封存记录为域名根+/chat/completions。
+238
View File
@@ -0,0 +1,238 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { fixture, compatibleFixture, until, assertToolPairs, completion } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { completionBody, actualRequest, requestHistory, requestMetrics, requestImages } from '../src/shared/contracts/model-request.mjs';
import { modelRequestUrl } from '../src/shared/contracts/model-endpoint.mjs';
import { normalizeProtocolResponse, reportedUsage } from '../src/core/models/protocols.mjs';
import { nativeParameterSettings } from '../src/shared/contracts/native-parameters.mjs';
import { readModelStream } from '../src/core/models/model-stream.mjs';
import { visionProbe } from '../src/core/models/vision-probe.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
const protocol = 'anthropic-messages', model = 'claude-owned';
const usage = { input_tokens: 100, output_tokens: 12, cache_creation_input_tokens: 20, cache_read_input_tokens: 30 };
const config = baseUrl => ({ mode: 'compatible', baseUrl, protocol, model, maxOutputTokens: 256 });
const message = (content = [{ type: 'text', text: '完成。' }], extra = {}) => ({ id: 'msg_owned', type: 'message', role: 'assistant', model, content, stop_reason: content.some(b => b.type === 'tool_use') ? 'tool_use' : 'end_turn', stop_sequence: null, usage, ...extra });
const tool = { type: 'tool_use', id: 'call_owned', name: 'list_files', input: { path: '', depth: 1 } };
const definition = { type: 'function', function: { name: 'list_files', description: 'owned fixture only', parameters: { type: 'object', properties: { path: { type: 'string' } } } } };
const event = (type, fields = {}) => `event: ${type}\r\ndata: ${JSON.stringify({ type, ...fields })}\r\n\r\n`;
function stream(content = [{ type: 'text', text: '完成。' }], extra = {}) {
const start = message([], { usage: { ...usage, output_tokens: 1 }, stop_reason: null });
const result = [event('message_start', { message: start }), event('ping')];
content.forEach((block, index) => {
const initial = block.type === 'tool_use' ? { ...block, input: {} } : block.type === 'text' ? { ...block, text: '' }
: block.type === 'thinking' ? { ...block, thinking: '', signature: '' } : block;
result.push(event('content_block_start', { index, content_block: initial }));
if (block.type === 'tool_use') {
const json = JSON.stringify(block.input), at = Math.floor(json.length / 2);
for (const partial_json of [json.slice(0, at), json.slice(at)]) result.push(event('content_block_delta', { index, delta: { type: 'input_json_delta', partial_json } }));
} else if (block.type === 'text') result.push(event('content_block_delta', { index, delta: { type: 'text_delta', text: block.text } }));
else if (block.type === 'thinking') {
result.push(event('content_block_delta', { index, delta: { type: 'thinking_delta', thinking: block.thinking } }));
result.push(event('content_block_delta', { index, delta: { type: 'signature_delta', signature: block.signature } }));
}
result.push(event('content_block_stop', { index }));
});
result.push(event('message_delta', { delta: { stop_reason: content.some(b => b.type === 'tool_use') ? 'tool_use' : 'end_turn', stop_sequence: null, ...extra }, usage: { output_tokens: usage.output_tokens } }));
result.push(event('message_stop'));
return result.join('');
}
async function streamingServer(t, action) {
const requests = [], sockets = new Set();
const server = http.createServer(async (req, res) => {
const parts = []; for await (const chunk of req) parts.push(chunk);
const body = JSON.parse(Buffer.concat(parts)); requests.push({ url: req.url, body, headers: req.headers });
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'request-id': 'req_owned_messages' });
try { await action(res, body); } catch { res.destroy(); }
});
server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise(resolve => { for (const socket of sockets) socket.destroy(); server.close(resolve); }));
return { baseUrl: 'http://127.0.0.1:' + server.address().port, requests };
}
test('Messages builds native system/tool history, bounds images, and seals a distinct mixed-pool variant', () => {
const image = visionProbe().image, cfg = { ...config('https://example.test'), inputImages: [image] };
const history = [{ role: 'system', content: '系统一' }, { role: 'system', content: '系统二' }, { role: 'user', content: '读取' },
{ role: 'assistant', content: '核对', tool_calls: [{ id: tool.id, type: 'function', function: { name: tool.name, arguments: JSON.stringify(tool.input) } }] },
{ role: 'tool', tool_call_id: tool.id, content: '{"files":[]}' }, { role: 'user', content: '继续' }];
const body = completionBody(cfg, history, [definition]);
assert.deepEqual(body.system, [{ type: 'text', text: '系统一' }, { type: 'text', text: '系统二' }]);
assert.equal(body.messages[1].content[1].type, 'tool_use'); assert.equal(body.messages[2].content[0].tool_use_id, tool.id);
assert.equal(body.messages[2].content[1].text, '继续'); assert.equal(body.max_tokens, 256); assert.equal(body.tool_choice.type, 'auto');
assert.deepEqual(body.tools[0].input_schema, definition.function.parameters); assert.equal(body.tools[0].function, undefined);
assert.equal(requestImages(body)[0], image.dataUrl); assert.equal(requestMetrics(body).imageReservationTokens, 4096);
assert.equal(requestHistory(body).filter(m => m.role === 'tool')[0].tool_call_id, tool.id);
assert.deepEqual(requestHistory(body).filter(m => m.role === 'system').map(m => m.content), ['系统一', '系统二']);
assert.equal(completionBody(config('https://example.test'), [{ role: 'user', content: 'OK' }], []).tool_choice, undefined);
const members = [{ id: 'chat', protocol: 'chat-completions', model: 'gpt-owned' }, { id: 'messages', protocol, model, baseUrl: cfg.baseUrl }];
const mixed = completionBody({ ...cfg, modelRouting: { members } }, history, [definition]);
assert.equal(mixed.kind, 'model-route-plan'); assert.deepEqual(actualRequest(mixed, members[1]), body);
assert.ok(actualRequest(mixed, members[0]).messages.some(m => m.role === 'system'));
});
test('Messages URL and native parameter contracts preserve other protocol paths and hard output budget', () => {
for (const root of ['https://example.test', 'https://example.test/v1', 'https://example.test/v1/']) assert.equal(modelRequestUrl(config(root)), 'https://example.test/v1/messages');
assert.equal(modelRequestUrl(config('https://example.test/proxy')), 'https://example.test/proxy/v1/messages');
assert.equal(modelRequestUrl({ ...config('https://example.test'), protocol: 'chat-completions' }), 'https://example.test/chat/completions');
const native = { temperature: 0.5, top_k: 10, stop_sequences: ['END'], thinking: { type: 'enabled', budget_tokens: 1024 } };
assert.deepEqual(completionBody({ ...config('https://example.test'), maxOutputTokens: 2048, nativeParameters: native }, [{ role: 'user', content: 'x' }], []).thinking, native.thinking);
assert.throws(() => completionBody({ ...config('https://example.test'), nativeParameters: native }, [], []), /小于/);
for (const invalid of [{ max_tokens: 9999 }, { temperature: 2 }, { parallel_tool_calls: true }, { thinking: { type: 'enabled', budget_tokens: 1 } }]) assert.throws(() => nativeParameterSettings(protocol, invalid));
assert.throws(() => nativeParameterSettings(protocol, {}, 'max_completion_tokens'));
});
test('native usage includes both cache buckets once, retains raw and rejects invalid counters', () => {
assert.equal(reportedUsage({ protocol }, { usage }).prompt_tokens, 150);
assert.equal(reportedUsage({ protocol }, { usage }).total_tokens, 162);
assert.deepEqual(reportedUsage({ protocol }, { usage }).raw, usage);
assert.equal(reportedUsage({ protocol }, { usage: { ...usage, cache_read_input_tokens: -1 } }), null);
assert.equal(reportedUsage({ protocol }, { usage: { input_tokens: 1 } }), null);
});
for (const streaming of [false, true]) test(`real HTTP Messages ${streaming ? 'SSE' : 'JSON'} executes one tool, retains opaque history, actual URL and cache accounting`, async t => {
const f = fixture(t), thinking = { type: 'thinking', thinking: 'owned fixture reasoning', signature: 'owned-signature' };
const content = [thinking, { type: 'text', text: '开始读取。' }, tool];
const server = streaming ? await streamingServer(t, async (res, body) => {
const raw = Buffer.from(stream(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : content));
for (let at = 0; at < raw.length; at += 7) res.write(raw.subarray(at, at + 7)); res.end();
}) : await compatibleFixture(t, (_url, body) => ({ body: message(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : content), headers: { 'request-id': 'req_owned_messages' } }));
const provider = new Provider(), hub = provider.modelHub(f.store), connection = hub.upsert({ ...config(server.baseUrl), name: 'Owned Messages', requiresKey: false,
streaming, capabilityDeclarations: { streaming: 'supported' }, modelIdentityPolicy: 'require-match' });
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project files once.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.events.slice(-3))); assert.equal(server.requests.length, 2);
const second = server.requests[1].input ?? server.requests[1].body;
assert.deepEqual(second.messages.find(m => m.role === 'assistant').content[0], thinking); assertToolPairs(f.session.providerMessages);
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
const run = f.store.core.run.get(f.session.runId); assert.equal(run.usage.inputTokens, 300); assert.equal(run.usage.outputTokens, 24);
assert.equal(run.consumption.length, 2); assert.equal(run.consumption[0].requestUrl, modelRequestUrl(config(server.baseUrl)));
for (const attempt of hub.view().attempts) {
assert.equal(attempt.modelIdentity.status, 'matched'); assert.equal(attempt.upstreamResponse.responseUrl, attempt.requestUrl);
assert.deepEqual(attempt.usage.raw, usage); assert.equal(attempt.usage.total_tokens, 162);
const artifact = f.store.core.artifact.get(attempt.responseArtifactId); assert.equal(attempt.responseSha256, artifact.sha256);
assert.equal(attempt.modelIdentity.responseSource.sha256, artifact.sha256);
}
for (const plan of f.store.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan));
});
for (const messagesAuth of ['api-key', 'bearer']) test('Messages ' + messagesAuth + ' authentication is explicit; mismatched model remains blocked with original usage', async t => {
const server = await compatibleFixture(t, () => ({ body: message(undefined, { model: 'gpt-other' }) }));
const provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), messagesAuth, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, [], { attempts: 1 }), cause => cause.diagnostic?.modelIdentity?.status === 'mismatch');
assert.equal(server.requests.length, 1); const headers = server.requests[0].headers;
assert.equal(headers['anthropic-version'], '2023-06-01');
const received = progress.find(e => e.consumption).consumption;
assert.equal(received.usage.total_tokens, 162); assert.equal(received.modelIdentity.reportedModels[0], 'gpt-other');
// Use only a synthetic test credential, never any user's saved connection.
provider.setKey('owned-key');
await assert.rejects(provider.complete({ ...config(server.baseUrl), messagesAuth, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, undefined, null, [], { attempts: 1 }));
const keyed = server.requests[1].headers;
assert.equal(keyed['x-api-key'], messagesAuth === 'api-key' ? 'owned-key' : undefined);
assert.equal(keyed.authorization, messagesAuth === 'bearer' ? 'Bearer owned-key' : undefined);
});
test('Messages redirect is not followed, either credential stays at the original server', async t => {
const target = await compatibleFixture(t, () => ({ body: message() })), origin = await compatibleFixture(t, () => ({ status: 307, headers: { location: target.baseUrl + '/messages' }, body: {} }));
const provider = new Provider(); provider.setKey('owned-redirect-key');
await assert.rejects(provider.complete(config(origin.baseUrl), [{ role: 'user', content: 'OK' }], null, undefined, undefined, null, [], { attempts: 1 }));
assert.equal(origin.requests.length, 1); assert.equal(target.requests.length, 0);
assert.equal(provider.lastRequest.requestUrl, modelRequestUrl(config(origin.baseUrl))); assert.equal(provider.lastRequest.redirectMode, 'manual');
});
test('strict native SSE reads the nested start model and retains mismatch source without retries', async t => {
const raw = stream().replace('"model":"claude-owned"', '"model":"gpt-wrong"');
const server = await streamingServer(t, res => res.end(raw)), provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), streaming: true, modelIdentityPolicy: 'require-match' }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, []), cause => cause.diagnostic?.modelIdentity?.status === 'mismatch');
assert.equal(server.requests.length, 1); assert.equal(progress.find(e => e.streamCapture).streamCapture.toString(), raw);
assert.equal(progress.find(e => e.consumption).consumption.usage.total_tokens, 162);
});
test('a closed native tool block cannot execute before message_stop, then executes exactly once', async t => {
const f = fixture(t); let release, ready = false;
const gate = new Promise(resolve => { release = resolve; });
const server = await streamingServer(t, async (res, body) => {
if (body.messages.some(m => m.content.some(b => b.type === 'tool_result'))) { res.end(stream()); return; }
res.write(stream([tool]).replace(event('message_stop'), '')); ready = true;
await gate; res.end(event('message_stop'));
});
const provider = new Provider(), hub = provider.modelHub(f.store), connection = hub.upsert({ ...config(server.baseUrl), name: 'Owned held terminal', requiresKey: false, streaming: true, capabilityDeclarations: { streaming: 'supported' } });
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); t.after(() => { release(); runtime.stopAll(); });
runtime.start(f.session.id, 'Read once.'); await until(() => ready); await delay(150);
assert.equal(f.session.events.filter(e => e.tool === 'list_files').length, 0); release();
await until(() => !runtime.isActive(f.session.id), 15000); assert.equal(f.session.status, 'completed');
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
});
test('mixed Chat/Messages pool seals both variants and preserves one completed tool on failover', async t => {
const f = fixture(t), first = await compatibleFixture(t, () => ({ status: 429, body: { error: { message: 'owned throttling' } } }));
const second = await compatibleFixture(t, (_url, body) => ({ body: message(body.messages.some(m => m.content.some(b => b.type === 'tool_result')) ? undefined : [tool]) }));
const provider = new Provider(), hub = provider.modelHub(f.store);
const chat = hub.upsert({ ...config(first.baseUrl), protocol: 'chat-completions', name: 'Owned Chat', requiresKey: false });
const native = hub.upsert({ ...config(second.baseUrl), name: 'Owned Messages', requiresKey: false });
const pool = hub.pool({ name: 'Owned mixed', members: [{ connectionId: chat.id }, { connectionId: native.id }], maxAttempts: 2 });
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project files once.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'completed'); assert.equal(first.requests.length, 1); assert.equal(second.requests.length, 2);
assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 1);
});
test('native JSON rejects incomplete stops, duplicate tools and hosted content', () => {
for (const value of [message([tool], { stop_reason: 'max_tokens' }), message([tool], { stop_reason: 'pause_turn' }), message([tool], { stop_reason: 'end_turn' }),
message([{ type: 'server_tool_use', name: 'bash' }]), message([{ type: 'tool_use', id: 'x', name: 'list_files', input: [] }]), message([{ type: 'thinking', thinking: 'x', signature: '' }])]) {
assert.throws(() => normalizeProtocolResponse({ protocol }, value));
}
});
test('strict SSE validates all blocks, terminal, event names, UTF8 and tool JSON before dispatch', async t => {
const original = stream([tool]), start = event('message_start', { message: message([], { stop_reason: null }) });
const cases = [original.replace(event('message_stop'), ''), original.replace('"partial_json":"{\\"path', '"partial_json":"!{\\"path'),
original.replace('event: content_block_delta', 'event: message_delta'), original + event('ping'),
original.replace('"index":0', '"index":3'), original.replace('"stop_reason":"tool_use"', '"stop_reason":"max_tokens"'),
start + event('message_stop'), start + event('content_block_delta', { index: 0, delta: { type: 'text_delta', text: 'orphan' } }),
original.replace('event: message_stop\r\ndata: {"type":"message_stop"}', 'data: [DONE]')];
for (let i = 0; i < cases.length; i++) await t.test('reject native stream ' + i, async () => {
assert.notEqual(cases[i], original, 'fixture mutation must change actual bytes');
await assert.rejects(readModelStream(new Response(cases[i], { headers: { 'content-type': 'text/event-stream' } }), { protocol }, undefined, undefined, [definition]));
});
});
test('upstream SSE error retains original type/request ID and initial usage, never retries', async t => {
const raw = event('message_start', { message: message([], { stop_reason: null }) }) + event('error', { error: { type: 'overloaded_error', message: 'owned overload' } });
const server = await streamingServer(t, res => res.end(raw)), provider = new Provider(), progress = [];
await assert.rejects(provider.complete({ ...config(server.baseUrl), streaming: true }, [{ role: 'user', content: 'OK' }], null, undefined, e => progress.push(e), null, []), cause => cause.diagnostic?.upstream?.type === 'overloaded_error');
assert.equal(server.requests.length, 1); assert.equal(progress.find(e => e.streamCapture).streamCapture.toString(), raw);
assert.equal(progress.find(e => e.consumption).consumption.usage.total_tokens, 162);
});
test('stop cancels the owned stream and retains partial consumption without running tool or replaying', async t => {
let closed = false;
const server = await streamingServer(t, res => { res.on('close', () => { closed = true; }); res.write(event('message_start', { message: message([], { stop_reason: null }) })
+ event('content_block_start', { index: 0, content_block: { ...tool, input: {} } })
+ event('content_block_delta', { index: 0, delta: { type: 'input_json_delta', partial_json: '{"path":' } })); });
const provider = new Provider(), controller = new AbortController(), progress = [];
const pending = provider.complete({ ...config(server.baseUrl), streaming: true }, [{ role: 'user', content: 'OK' }], null, controller.signal, e => progress.push(e), null, []);
const rejected = assert.rejects(pending); await until(() => progress.some(e => e.streaming)); controller.abort(); await rejected;
await until(() => closed); assert.equal(server.requests.length, 1);
assert.equal(progress.find(e => e.consumption).consumption.outcome, 'interrupted');
assert.equal(progress.find(e => e.streamCapture).stream.terminal, false);
});
test('saved Messages import preserves auth choice, rejects endpoint duplication, and keeps source file untouched', t => {
const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store), importer = new ConfigImporter(hub);
assert.throws(() => hub.upsert({ ...config('https://example.test/v1/messages'), name: 'invalid root' }), /根地址/);
assert.throws(() => hub.upsert({ ...config('https://example.test'), messagesAuth: 'guess', name: 'invalid auth' }), /鉴权/);
const filename = path.join(f.root, 'connections.json'), input = { schema: 1, connections: [{ ...config('https://example.test'), name: 'Owned import', messagesAuth: 'bearer', requiresKey: false }] };
fs.writeFileSync(filename, JSON.stringify(input)); const before = fs.readFileSync(filename);
const preview = importer.preview('workbench-json', filename), result = importer.apply(preview.id);
assert.equal(hub.connection(result.imported[0]).messagesAuth, 'bearer'); assert.deepEqual(fs.readFileSync(filename), before);
});