fix: retain source continuation and explain request reservation pauses

This commit is contained in:
Agent Workbench Dev
2026-11-04 00:45:53 +08:00
parent fbedb7381b
commit 5dcd6d7c3f
30 changed files with 439 additions and 81 deletions
+7
View File
@@ -1,5 +1,12 @@
# Agent Workbench 更新记录
## 1.24.7 · 文件续读与预算解释(发行验收中)
- 文件续读入口携带原行范围、偏移和可选 SHA-256 核对;读取版本变化会拒绝拼接,已返回页工件与未读原文件后文有明确区别。
- 纯文件读取依据实际可用消息容量分配,同批小文件用剩的空间可供后续读取;紧张容量下优先保证完整页能进入下一请求。混合操作和工件读取保留原保守策略。
- 下一请求预留超过运行/任务余额时,明确显示余额原因、所需预留与原用量;上下文不足及旧记录仍独立解释,续接需显式预览。
- 保留旧历史发送视图、原上游报告、16K/输出/安全预留和任务约束。隔离回放改善与真实模型交付、原版 Purge 收益分别验收。
## 1.24.6 · 所属连接网络诊断(已本地交付)
- 模型中心新增“连接诊断”,连接卡可直接进入;显示 DNS、TCP、TLS 耗时、地址族和证书结果。
@@ -0,0 +1,33 @@
# S:文件续读与预算暂停修复
本切片接续 R 原失败,产品版本 1.24.7,发行验收中。正式升级前仍以 1.24.6 为准。后续发行身份、保留状态与原始检查结果另见最终 QA,不用开发回放代替上线或真实模型交付。
## 文件读取
`read_file` 接受可选 `expected_sha256`。续读入口来自原工具结果中的 path、原 range_start_line/range_end_line、next_offset 与 SHA,读取前核对原文件字节摘要。若 SHA 改变,拒绝拼接;原范围已读完时才使用 next_start_line。`truncated=true` 也可能只表示读的是文件中间范围,不能单凭它决定继续同一偏移。
历史索引、最近反馈及工作依据明确区分“恢复已返回页”与“读取从未返回的原文件”。result_artifact_id 只能恢复原页包装,不能冒充完整原文件。原工具/Run/Task/SHA/范围来源仍保存在原工件。重复文件定位在已有实际视图携带时不再次塞入历史提示,工件导航保持原 artifact_id。
新工作依据观察版本2/发送视图3、最近反馈发送视图2、分页策略2均参与封存;旧工作依据发送视图1/2和最近反馈视图1仍按原字节核验。没有原范围的旧结果不补造续读坐标。
## 分页容量
纯 read_file 批次从当前下一请求固定开销、保留源码、实际 assistant 参数及完整转义消息计算容量,增长预留为512tokens,加每项额外读取256(附加最多2048)。混合命令/计划/其它工具及 read_artifact 保留原2560tokens增长预留,旧计划亦保持原解释。这个增长预留与原上下文1600tokens安全余量分开,后者未降低。
同批小文件用剩的实际转义消息字节分给后续页。固定开销和保留源码后不足4096tokens时,单页最多2000字符,匹配原完整小源码保留边界;宽裕时仍按原文件页和实际消息字节容纳。这样不靠提高1024底限、删工具或扩大上下文制造吞吐。UTF-16代理对边界、完整转义JSON字节、原行号及CRLF均保持。
完整下一请求、工具配对、全部目标/约束和观察用量预留仍分别检查。该分配不是对任意未知未来状态均能携带整页的数学承诺;明确场景由实际发送正文核对,无法容纳时原文和工件保持。
## 暂停解释
`token_limit`/`task_token_limit` 保持原枚举,新 `pauseKind=request_reservation` 说明下一请求预留超过剩余额度。窗口容纳与余额分别解释;原预算、上游报告、未知用量及来源不改写。旧已存记录若有预留和余额可直接准确展示,没有这些字段则保留旧泛化解释,不猜测原因。
R的12352输入/12352窗口可用、29623下一请求预留/17429余额由新展示正确分列。上游27164输入tokens及24192缓存报告保持,原因未知,不能替换成本地估算。续接仍需准备并确认原Task的新Run,不自动补预算、切池或重放已完成操作。
## 隔离回放与边界
R前三次原assistant消息在隔离本机模型夹具回放;只将run_checks的原计划ID映射为新所属ID,然后使用固定的原文件续读策略。原目标、三源码、九测试、16K/2048/1600和8轮/90000tokens约束保持,无真实模型调用。
旧实现8轮仍step_limit,发送可见覆盖至2173/2584;修复后6轮覆盖完整2584,纯文件新页完整进入下一请求,最终verification_incomplete。原9测试仍全部失败,baseline build通过,0提案/源码修改/Git交付;不能写成原R重新成功或自主工程已通过。首驱动计划ID/混合视图判据错误、首回归容量/历史视图问题及后续修正日志保留。
后续先完成独立源码/便携/安装与正式保留PID/Provider升级,再单独冻结新预检/Node真实模型样本。React/Python和原版PurgeAB/BA保持原前置顺序,1.25与更新重复核验性能另列。
+8
View File
@@ -1,5 +1,13 @@
# 汇总发现
## S:从R原件定位读取可靠性
S重新只读取正式基线:1.24.6/原PID36552/hasKey、63项目79会话6262记录13279事件及outbox/3660工件,idle。全表/逐行/全导出/全部工件摘要已保存在.qa/reading-reliability-s/production-before.json。R六次调用先inspect_project,随后plan_checks/index,第三批混合run_checks、4次文件读取与plan_task;新分页策略限纯文件/工件读取批次,混合副作用/计划批次保留原保守策略,不能把未来未知结果当已知容量。纯读取单轮的实际上下文增量及完整下一请求需离线验证;16K/2048/1600安全预算与观察用量预留不变。文件续读加入可选原SHA核对与明确入口,历史发送视图保留旧版本。
本轮工具准备错误已记录:顶层.qa搜索递归遍历巨大历史目录,停止4个本轮rg搜索后改为顶层文件枚举;一次补丁标题锚点不符被整体拒绝,无部分写入。两次只读路径猜测失败已改按实际import和文件清单定位,无模型/用户工程副作用。
基线fbedb738干净,建立feat/reading-reliability-s。R已封存,测试2584字符仅返回1271,包装工件不能继续未读原文件;第7次输入可容纳而观察用量预留29623大于剩余17429,现有文字不区分。S先在隔离宿主复现和修复,阶段真实模型预算0,保留正式PID/Provider/原凭据及高性能池,原R结果不改写。产品UI工作流用于现有暂停/恢复流程,不重做产品外观。
## R:接续连接诊断后的真实验收边界
R最终178份/75944723字节封存,manifest 4d8dcc2199da2b61c512d45e8c27a62e53f499f239dbb35df4eae264ecf570df,独立离线核对原字节/身份/账本/分页/预算暂停/归属/恢复全部通过;含清单179份/75980516字节Git索引逐SHA一致。下一S计划、J样本入口及集中后续/验收文档已同步,本轮不制造新产品发行。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.24.6",
"version": "1.24.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.24.6",
"version": "1.24.7",
"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.6",
"version": "1.24.7",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+8
View File
@@ -1,5 +1,13 @@
# 统一执行进度
## S:读取可靠性与暂停解释
最终96相关(含三协议实际HTTP、原O回放/小源码/Unicode/CRLF/预算/记忆/原生模型预算)及18安装/升级检查通过,最终构建通过。源码新UI10组/1440与390截图实际回看、上下文/历史预算/模型选择相关UI通过。首通用2000字符上限使宽裕场景长文件轮次回归,已按固定开销与原保留后的4096tokens余量选择紧张模式,完整长文件场景复验通过;原失败保持。阶段真实模型0调用,下一范围提交、不可变候选与独立发行。
正式只读新基线完成:1.24.6/原PID36552、63项目79会话6262记录13279事件/outbox/3660工件、idle/hasKey。已实现原SHA续读、分版本反馈/工作依据、文件定位去重、纯文件批次有界容量和余额预留诊断;工件/混合批次保留原策略。首回归暴露新增定位重复/历史视图兼容和过大页被裁剪,保留失败后收敛为纯文件、完整小源码保留边界2000字符及去重,未削弱原上下文/安全/观察用量guard。原R三轮消息的新隔离回放:旧实现8轮step_limit仅观察至2173(末轮工具后另页未发送),新实现6轮读完2584/下一请求全页可见;原九测试仍失败且0提案/修改,不是工程交付。首回放验收器误识check plan ID/要求混合结果整页而报本机500,原件保留后按原实际字段和纯读取保留判据修正;不触碰正式任务。
用户要求继续全量推进并回顾总结。接续fbedb738,建立feat/reading-reliability-s,已读取S计划和现行规范,沿用planning-with-files/product-ui-ux,不委派。先冻结新正式基线和R只读原件,完成离线重现/修复/相关验证,再独立发行和保留原PID/Provider升级。本阶段真实模型0调用,不续跑R、不改变原预算或上游报告;真实交付另立后续样本。
## R:新的有界预检与工程交付
R封存与独立离线核验完成:178份/75944723字节,manifest 4d8dcc2199da2b61c512d45e8c27a62e53f499f239dbb35df4eae264ecf570df;含清单179份/75980516字节Git索引逐原SHA通过。原记录、每次调用、分页/预留停止、61自有工件和全部声明恢复均已核对;QA/回顾/S计划及集中计划验收入口已同步,本地范围提交收尾。正式仍1.24.6,真实Node未交付,未开启React/Python/Purge或新发行。
+1
View File
@@ -24,6 +24,7 @@ const prefixes = Object.freeze({
'1.24.3': 'model-selection',
'1.24.5': 'live-context-o',
'1.24.6': 'network-q',
'1.24.7': 'reading-s',
});
export function releaseEvidencePrefix(version) {
const prefix = prefixes[version];
+1 -1
View File
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '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.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', '1.24.5', '1.24.6'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '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.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', '1.24.5', '1.24.6', '1.24.7'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
let protocol, socket, enabledHere = false, paused = false;
const breakpoints = [];
+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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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']);
+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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].includes(version)) {
if (['1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5', '1.24.6', '1.24.7'].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 = [];
+76
View File
@@ -0,0 +1,76 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium } from 'playwright';
import { Store } from '../src/server/store.mjs';
import { launchWorkbench } from '../tests/helpers.mjs';
const root = path.resolve('.qa', 'reading-s-ui-' + randomUUID()), data = path.join(root, 'data');
fs.mkdirSync(root, { recursive: true });
const store = new Store(data), cases = [], checks = [], errors = [], disposers = [];
const t = { after: fn => disposers.push(fn) };
const appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT ?? '.');
const receipt = { schemaVersion: 1, reservedTokens: 29623, routes: [{ sources: [{ runId: 'owned-fixture', attemptId: 'owned-observation' }] }] };
for (const kind of ['run', 'task', 'context', 'historical']) {
const directory = path.join(root, 'fixture-' + kind); fs.mkdirSync(directory); fs.writeFileSync(path.join(directory, 'README.md'), 'Owned UI fixture\n');
const project = store.addProject(directory), session = store.createSession(project.id);
const goal = '自有界面验收样例:核对已保存的暂停原因。没有请求真实模型。';
const run = store.beginRun(session, goal, false, { ...store.config, contextLimit: 16000, maxOutputTokens: 2048 });
store.message(session, 'user', goal); session.providerMessages.push({ role: 'user', content: goal });
const reason = kind === 'task' ? 'task_token_limit' : kind === 'context' ? 'context_limit' : 'token_limit';
if (kind !== 'historical') run.budgetPause = { schema: 1, reason, taskId: run.taskId, runId: run.id,
requiredInputTokens: kind === 'context' ? 13300 : 12352, inputBudget: 12352, contextLimit: 16000, outputReservation: 2048, safetyTokens: 1600,
runRemainingTokens: kind === 'task' ? 50000 : 17429, taskRemainingTokens: kind === 'task' ? 17429 : 200000,
...(kind !== 'context' ? { pauseKind: 'request_reservation', remainingTokens: 17429, tokenReservation: receipt } : {}) };
session.status = 'paused'; store.message(session, 'system', '自有样例原暂停记录,历史未改写。'); store.finishRun(session, run, reason);
cases.push({ kind, projectId: project.id, sessionId: session.id, taskId: run.taskId, runId: run.id });
}
store.close();
let browser, host, report;
const visible = async locator => { await locator.waitFor({ state: 'visible', timeout: 15000 }); assert.ok(await locator.isVisible()); };
try {
host = await launchWorkbench(t, data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
browser = await chromium.launch({ channel: 'msedge', headless: true });
for (const width of [1440, 390]) {
const page = await browser.newPage({ viewport: { width, height: 1000 } }); page.on('pageerror', error => errors.push(error.message));
await page.goto(host.url, { waitUntil: 'networkidle' });
for (const item of cases) {
const project = page.getByLabel('当前项目', { exact: true });
if (!await project.isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await project.selectOption(item.projectId);
const panel = page.getByLabel('任务预算诊断', { exact: true }); await visible(panel);
const title = item.kind === 'run' ? '下一次请求超出运行余额' : item.kind === 'task' ? '下一次请求超出任务余额'
: item.kind === 'context' ? '上下文窗口不足' : '本次运行预算不足';
await visible(panel.getByRole('heading', { name: title, exact: true }));
const text = await panel.innerText();
if (['run', 'task'].includes(item.kind)) { assert.match(text, /输入可容纳/); assert.match(text, /29,623/); assert.match(text, /17,429/); assert.match(text, /12,352/); }
if (item.kind === 'historical') { assert.match(text, /旧记录没有的预算分解不补造/); assert.ok(!text.includes('输入可容纳')); }
await panel.scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(root, item.kind + '-' + width + '.png'), fullPage: true });
fs.writeFileSync(path.join(root, item.kind + '-' + width + '.txt'), text);
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); assert.ok(overflow <= 1, String(overflow));
if (item.kind === 'run') {
await panel.getByRole('button', { name: '核对预算并续接原任务', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '续接原任务', exact: true }); await visible(dialog);
await dialog.getByRole('button', { name: '准备续接预览', exact: true }).click();
await visible(dialog.getByRole('status')); assert.match(await dialog.getByRole('status').innerText(), /将创建原Task的新Run/);
const box = await dialog.boundingBox(); assert.ok(box.x >= 0 && box.x + box.width <= width + 1);
await page.screenshot({ path: path.join(root, 'preview-' + width + '.png'), fullPage: true });
await dialog.getByRole('button', { name: '关闭窗口', exact: true }).click();
const current = await host.api('/sessions/' + item.sessionId);
assert.equal(current.taskId, item.taskId); assert.equal(current.runId, item.runId); assert.equal(current.execution.task.usage.requests, 0);
await page.reload({ waitUntil: 'networkidle' }); await visible(panel.getByRole('heading', { name: title, exact: true }));
checks.push(width + ': preview and cancel preserve original Task/Run and do not dispatch');
}
checks.push(width + ': ' + item.kind + ' diagnosis and persistence');
}
await page.close();
}
assert.deepEqual(errors, []);
report = { success: true, appRoot, checks, cases, errors, realModelRequests: 0, fixtureModelRequests: 0 };
} catch (error) { report = { success: false, appRoot, checks, cases, errors, error: error.stack, realModelRequests: 0 }; process.exitCode = 1; }
finally {
await browser?.close(); await host?.close(); for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ ...report, root }));
}
+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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.5', '1.24.6', '1.24.7'].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', '1.24.4', '1.24.5', '1.24.6'].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', '1.24.5', '1.24.6', '1.24.7'].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 -1
View File
@@ -47,7 +47,7 @@ export interface InputAttachment { id:string;name:string;status:string;mediaType
export interface BudgetPause { reason:string;requiredInputTokens?:number;contextLimit?:number;inputBudget?:number;outputReservation?:number;safetyTokens?:number;runRemainingTokens?:number|null;taskRemainingTokens?:number|null;imageReservationTokens?:number;breakdown?:Record<string,number> }
export interface Run { budgetPause?:BudgetPause }
export interface BudgetPause { originalInputTokens?:number;transportReservationTokens?:number }
export interface BudgetPause { limitingReason?:string }
export interface BudgetPause { limitingReason?:string;pauseKind?:string }
export interface BudgetPause { modelFailure?:RuntimeFailure }
export interface TokenBudgetCounter { maximumTokens:number;reportedTokens:number;unknownRequests:number;estimatedUnknownTokens:number;accountedTokens:number;remainingTokens:number|null;exceededTokens:number }
export interface BudgetPause { remainingTokens?:number;tokenReservation?:{schemaVersion:number;reservedTokens:number;routes:{sources:{runId:string;attemptId:string}[]}[]};tokenAccounting?:{schemaVersion:number;singleInFlightResponseMayExceed:boolean;run:TokenBudgetCounter;task:TokenBudgetCounter} }
+24 -3
View File
@@ -36,11 +36,32 @@ export function readMessageBudget(plan, message) {
// The next request also gains bounded read coverage and route observations.
// Reserve their growth before returning a page, rather than dropping that
// new page or enlarging the request budget afterwards.
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - 512 - 2048;
const pureReads = plan.readBudgetPolicyVersion === 2 && message.tool_calls?.length
&& message.tool_calls.every(call => call.function.name === 'read_file');
// A pure read batch cannot create a plan, command output or change set. Its
// bounded state/coverage growth uses 512 tokens plus 256 for each additional
// read. Mixed batches and historical plans retain the original 2560 reserve.
// This is page sizing, never dispatch authorization: the complete next wire
// request and observed-usage reservation are still checked independently.
const growth = pureReads ? 512 + Math.min(2048, Math.max(0, calls - 1) * 256) : 2560;
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - growth;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
export function filePage(file, args, { maximumMessageBytes = 16000, callId = '' } = {}) {
export function readBatchBudget(plan, message) {
const maximum = readMessageBudget(plan, message);
if (plan.readBudgetPolicyVersion !== 2 || !message.tool_calls?.length
|| !message.tool_calls.every(call => call.function.name === 'read_file')) return null;
return { remainingBytes: maximum * message.tool_calls.length, remainingCalls: message.tool_calls.length };
}
export function spendReadBudget(batch, call, result) {
if (!batch) return;
batch.remainingBytes = Math.max(0, batch.remainingBytes - messageBytes(result, call.id));
batch.remainingCalls = Math.max(0, batch.remainingCalls - 1);
}
export function filePage(file, args, { maximumMessageBytes = 16000, callId = '', maximumPageCharacters = Infinity } = {}) {
const text = file.content, requestedOffset = args.offset ?? 0;
let offset = Math.min(requestedOffset, text.length);
if (offset > 0 && /[\uDC00-\uDFFF]/.test(text[offset]) && /[\uD800-\uDBFF]/.test(text[offset - 1])) offset--;
@@ -55,7 +76,7 @@ export function filePage(file, args, { maximumMessageBytes = 16000, callId = ''
requested_offset: requestedOffset, next_start_line: end < text.length ? null : file.end_line < file.total_lines ? file.end_line + 1 : null,
truncated: file.truncated || offset > 0 || end < text.length, budget_limited: end < maximumEnd,
maximum_message_bytes: maximumMessageBytes });
let low = offset, high = maximumEnd;
let low = offset, high = Math.min(maximumEnd, boundary(text, offset + maximumPageCharacters));
if (messageBytes(make(low), callId) > maximumMessageBytes) throw new Error('当前请求预算无法容纳文件读取元数据,请先核对任务预算。');
while (low < high) {
const middle = Math.ceil((low + high) / 2), end = boundary(text, middle);
+13
View File
@@ -0,0 +1,13 @@
// Only a recorded source page can supply a continuation. A tool-result
// artifact restores that page, not bytes that have never been read.
export function fileContinuation(value) {
if (typeof value?.path !== 'string' || !/^[a-f0-9]{64}$/i.test(value.sha256 ?? '')
|| !Number.isSafeInteger(value.range_start_line) || !Number.isSafeInteger(value.range_end_line)
|| !Number.isSafeInteger(value.next_offset) || !Number.isSafeInteger(value.total_characters)) return null;
const more = value.next_offset < value.total_characters;
const next = more ? { path: value.path, start_line: value.range_start_line, end_line: value.range_end_line,
offset: value.next_offset, expected_sha256: value.sha256 }
: Number.isSafeInteger(value.next_start_line) ? { path: value.path, start_line: value.next_start_line,
expected_sha256: value.sha256 } : null;
return { range_complete: !more, next_read_file: next };
}
+39 -19
View File
@@ -7,6 +7,7 @@ import { projectMemoryMessage, MEMORY_CONTEXT_LIMITS } from '../memory/project-m
import { skillCatalogMessage, SKILL_LIMITS } from '../skills/skill-registry.mjs';
import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs';
import { modelReservation,taskConsumption,verifyModelReservation } from '../../shared/contracts/model-reservation.mjs';
import { fileContinuation } from './read-continuation.mjs';
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
@@ -70,7 +71,8 @@ function compactResult(result) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return { format: 'json-value' };
const selected = {};
for (const key of ['status', 'requires_verification', 'check_status', 'exit_code', 'change_id', 'change_set_id', 'plan_id', 'job_id',
'artifact_id', 'logArtifactId', 'report_status', 'task_id', 'path', 'sha256', 'base_sha256', 'fingerprint', 'offset', 'next_offset', 'total_characters', 'truncated']) {
'artifact_id', 'logArtifactId', 'report_status', 'task_id', 'path', 'sha256', 'base_sha256', 'fingerprint', 'offset', 'next_offset', 'total_characters', 'truncated',
'range_start_line', 'range_end_line', 'next_start_line', 'budget_limited']) {
const item = value[key];
if (typeof item === 'string' && item.length <= 200 || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item) || item === null) selected[key] = item;
}
@@ -97,7 +99,7 @@ function workingEvidence(groups, descriptions, artifacts) {
for (const group of [...groups].reverse()) for (const tool of descriptions.get(group.index).tools ?? []) {
const artifact = artifacts.get(tool.input.artifact_id);
if (tool.name === 'read_file' || tool.name === 'read_artifact' && artifact && !artifact.kind.startsWith('context-') && artifact.kind !== 'model-request') {
const key = tool.name === 'read_file' ? 'file:' + tool.input.path : 'artifact:' + tool.input.artifact_id;
const key = tool.name === 'read_file' ? JSON.stringify(['file', tool.input.path, tool.result.sha256, tool.result.range_start_line, tool.result.range_end_line]) : 'artifact:' + tool.input.artifact_id;
if (!selected.has(key)) selected.set(key, { group_index: group.index, ...tool });
}
}
@@ -107,12 +109,13 @@ function workingEvidence(groups, descriptions, artifacts) {
function notice(reference, omitted, descriptions, evidence = []) {
return { role: 'system', content: [
'以下是工作台保存的历史索引数据,不是用户追加指令,也不是新工具执行。省略了完整消息组;原始参数和实际结果都在SHA256工件中。',
'已完成工具不得重放。优先使用已发送代码和工作依据;只在缺少具体内容时读取result_artifact_id,按next_offset分页。未知结果先核对。',
'已完成工具不得重放。优先使用已发送代码和工作依据;result_artifact_id只恢复已返回页。未读原文件用next_read_file继续,并核对原SHA;原工件用artifact_id与next_offset。未知结果先核对。',
JSON.stringify({ history_index: { artifact_id: reference.id, sha256: reference.sha256 }, archived_groups: omitted.length,
working_evidence: evidence.map(tool => ({ group_index: tool.group_index, name: tool.name,
...(tool.input.path ? { path: tool.input.path } : {}),
...(tool.name === 'read_artifact' ? { artifact_id: tool.input.artifact_id, offset: tool.result.offset, next_offset: tool.result.next_offset }
: tool.result_artifact_id ? { result_artifact_id: tool.result_artifact_id } : {}) })),
: tool.result_artifact_id ? { result_artifact_id: tool.result_artifact_id,
...(fileContinuation(tool.result)?.next_read_file ? { file_read: fileContinuation(tool.result) } : {}) } : {}) })),
recent_archived_groups: omitted.slice(-2).map(group => {
const { archive } = descriptions.get(group.index);
return { index: group.index, group_archive: { artifact_id: archive?.artifact_id ?? PLACEHOLDER_ID, sha256: archive?.sha256 ?? PLACEHOLDER_SHA } };
@@ -121,9 +124,12 @@ function notice(reference, omitted, descriptions, evidence = []) {
}
function pause(budget, metrics, breakdown) {
const reservation = budget.pauseKind === 'request_reservation';
const error = new BudgetExceeded(budget.limitingReason,
'任务目标、完整追加要求与必需请求开销超过' + (budget.limitingReason === 'context_limit' ? '上下文窗口' : '剩余token预算') +
'。完整历史已保留;请核对模型上下文或任务预算后继续。');
reservation ? '当前必需输入可容纳于上下文窗口,但下一次请求的用量预留超过' + (budget.limitingReason === 'task_token_limit' ? '任务累计' : '本次运行') +
'剩余预算。已在发送前暂停;原用量、任务与工具结果保留,请核对预算后显式续接。'
: '任务目标、完整追加要求与必需请求开销超过' + (budget.limitingReason === 'context_limit' ? '上下文窗口' : '剩余token预算') +
'。完整历史已保留;请核对模型上下文或任务预算后继续。');
error.contextBudget = { ...budget, requiredInputTokens: metrics.estimatedInputTokens, imageReservationTokens:metrics.imageReservationTokens??0,
imageEstimate:metrics.imageEstimate??null,breakdown:breakdown(metrics) };
return error;
@@ -173,20 +179,30 @@ export class RequestPlanner {
toolDefinitionTokens:fixedTools-fixedText,historyAndEvidenceTokens:metrics.estimatedInputTokens-fixedTools,
imageReservationTokens:metrics.imageReservationTokens??0};
};
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id).map(tool => [tool.callId, tool]));
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.taskId === task.id).map(tool => [tool.callId, tool]));
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
const selected = new Set(groups.map(group => group.index));
let omitted = [], reference = null, workingReference = null, latestReference = null;
const latestDocument = latestToolDocument(this.store, session, run, groups);
const latestDocument = latestToolDocument(this.store, session, run, groups, 2);
const entries = [];
let retainedSources = [];
// A read locator already carried in raw history, latest feedback or the
// working view need not be repeated in the history notice. Original group
// and result artifacts still contain the complete provenance.
const unsentEvidence = (indices, currentEntries, includeLatest) => {
const sentCalls = new Set(currentEntries.map(entry => entry.source.call_id));
if (includeLatest && latestDocument && !indices.has(latestDocument.group_index)) {
for (const entry of latestDocument.entries) sentCalls.add(entry.source.call_id);
}
return evidence.filter(tool => tool.name !== 'read_file' || !indices.has(tool.group_index) && !sentCalls.has(tool.call_id));
};
const metricsFor = (indices, includeNotice = true, currentEntries = entries, includeLatest = true) => {
const missing = groups.filter(group => !indices.has(group.index));
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []),
...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument)] : []),
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries))] : []),
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, unsentEvidence(indices, currentEntries, includeLatest))] : []),
...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument, 2)] : []),
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries, 2), 3)] : []),
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
return requestMetrics(completionBody(config, messages, tools));
};
@@ -194,7 +210,7 @@ export class RequestPlanner {
selected.clear(); if (lastUser) selected.add(lastUser.index);
const mandatory = metricsFor(selected);
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
const observed = workingCandidates(this.store, session, run, groups);
const observed = workingCandidates(this.store, session, run, groups, 2);
// Admit complete small source observations before optional raw history.
// A reservation alone does not keep code in the actual sent request.
const newest = groups.at(-1);
@@ -259,11 +275,11 @@ export class RequestPlanner {
note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index');
}
}
if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries), 'context-working-set');
if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries, 2), 'context-working-set');
if (latestDocument && !selected.has(latestDocument.group_index)) latestReference = this.artifact(session, run, latestDocument, 'context-latest-tools');
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []),
...(latestReference ? [latestToolMessage(latestReference, latestDocument)] : []),
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries))] : []),
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, unsentEvidence(selected, entries, true))] : []),
...(latestReference ? [latestToolMessage(latestReference, latestDocument, 2)] : []),
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries, 2), 3)] : []),
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
let mcpReference = null, mcpDocument = null;
if (mcpCatalog?.projectId === session.projectId && mcpCatalog.entries?.length) {
@@ -315,7 +331,7 @@ export class RequestPlanner {
const tokenReservation=engineStepOnly?null:modelReservation(config,body,taskConsumption(this.store,task.id));
const runCredit=budget.runRemainingTokens??Infinity,taskCredit=budget.taskRemainingTokens??Infinity,credit=Math.min(runCredit,taskCredit);
if(tokenReservation&&tokenReservation.reservedTokens>credit)throw pause({...budget,limitingReason:runCredit<=taskCredit?'token_limit':'task_token_limit',
tokenReservation,remainingTokens:credit},metrics,breakdown);
tokenReservation,remainingTokens:credit,pauseKind:'request_reservation'},metrics,breakdown);
const requestArtifact = this.artifact(session, run, body, 'model-request');
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
runId: run.id, stepId, requestIndex: [...this.store.core.context_plan.values()].filter(plan => plan.runId === run.id).length + 1,
@@ -333,11 +349,13 @@ export class RequestPlanner {
workingRetentionTokens: Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true, retainedSources).estimatedInputTokens
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens),
workingRetentionPolicyVersion: 1,
readBudgetPolicyVersion: 2,
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
workingSetArtifactId: workingReference?.id ?? null, workingSetSha256: workingReference?.sha256 ?? null, workingSetEntries: entries.length,
workingSetViewVersion: 2,
workingSetViewVersion: 3,
latestToolsViewVersion: 2,
latestToolsArtifactId: latestReference?.id ?? null, latestToolsSha256: latestReference?.sha256 ?? null, latestToolsEntries: latestReference ? latestDocument.entries.length : 0,
projectMemoryArtifactId: memoryReference?.id ?? null, projectMemorySha256: memoryReference?.sha256 ?? null,
projectMemoryEntries: memoryReference ? memoryDocument.entries.length : 0,
@@ -408,6 +426,8 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| (frozen.workingRetentionTokens ?? 0) !== (plan.workingRetentionTokens ?? 0)
|| (frozen.workingRetentionPolicyVersion ?? 0) !== (plan.workingRetentionPolicyVersion ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。');
if ((frozen.nextReadFixedInputTokens ?? null) !== (plan.nextReadFixedInputTokens ?? null)) throw new Error('下一工具页的固定预算与封存记录不匹配。');
if ((frozen.readBudgetPolicyVersion ?? 1) !== (plan.readBudgetPolicyVersion ?? 1)
|| (frozen.latestToolsViewVersion ?? 1) !== (plan.latestToolsViewVersion ?? 1)) throw new Error('读取或最新反馈视图版本与封存记录不匹配。');
if ((frozen.latestToolsArtifactId ?? null) !== (plan.latestToolsArtifactId ?? null)
|| (frozen.latestToolsSha256 ?? null) !== (plan.latestToolsSha256 ?? null)
|| (frozen.latestToolsEntries ?? 0) !== (plan.latestToolsEntries ?? 0)) throw new Error('最新工具反馈与发送前的封存记录不匹配。');
@@ -457,7 +477,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
const document = JSON.parse(store.artifactStore.read(artifact));
if (artifact.taskId !== plan.taskId) throw new Error('最新工具反馈的工件任务归属不匹配。');
verifyLatestToolDocument(store, session, plan, document, historyGroups(session.providerMessages.slice(0, plan.originalMessages)));
const message = latestToolMessage(artifact, document);
const message = latestToolMessage(artifact, document, plan.latestToolsViewVersion ?? 1);
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('最新工具反馈与实际发送内容不匹配。');
}
if (plan.workingSetArtifactId) {
+10 -6
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { fileContinuation } from './read-continuation.mjs';
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
const excerpt = (text, maximum = 400) => {
@@ -23,7 +24,7 @@ const checkJob = value => ({ ...fields(value, ['id', 'status', 'taskId', 'runId'
// These are deterministic selected fields from a saved result, never a new
// execution or an inferred success. Full JSON/text remains in its own artifact.
export function compactToolFeedback(content) {
export function compactToolFeedback(content, viewVersion = 1) {
let value;
try { value = JSON.parse(content); } catch { return { format: 'text-excerpt', excerpt: excerpt(content) }; }
if (!value || typeof value !== 'object' || Array.isArray(value)) return { format: 'json-excerpt', excerpt: excerpt(content) };
@@ -33,6 +34,7 @@ export function compactToolFeedback(content) {
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note', 'unchanged_action_count', 'reading_hint',
'browser_status', 'browser_job_id', 'result_artifact_id', 'evidence_verified', 'source_fingerprint', 'build_sha256', 'section', 'view_sha256', 'source_artifact_id', 'source_sha256',
'tool_invocation_id', 'proof_id', 'proof_artifact_id', 'step_key', 'revision', 'all_verified', 'verified_steps', 'total_steps', 'requirements_current', 'contract_artifact_id', 'binding_sha256']);
if (viewVersion === 2 && fileContinuation(value)?.next_read_file) result.file_read = fileContinuation(value);
if (value.assertions) result.assertions = stats(value.assertions);
if (Array.isArray(value.failed_steps)) result.failed_steps = value.failed_steps.slice(0, 3).map(step => fields(step, ['index', 'action', 'selector', 'status', 'error', 'actual']));
if (value.observed_page) result.observed_page = { ...fields(value.observed_page, ['title']), text: excerpt(value.observed_page.text ?? ''),
@@ -70,7 +72,7 @@ export function compactToolFeedback(content) {
return result;
}
export function latestToolDocument(store, session, run, groups) {
export function latestToolDocument(store, session, run, groups, viewVersion = 1) {
const group = groups.at(-1), calls = group?.messages[0].tool_calls;
if (!calls?.length) return null;
const ledger = new Map([...store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.projectId === session.projectId && tool.taskId === run.taskId)
@@ -88,16 +90,18 @@ export function latestToolDocument(store, session, run, groups) {
entries.push({ tool: call.function.name, source: { call_id: call.id, invocation_id: invocation.id, run_id: invocation.runId,
result_artifact_id: artifact.id, result_sha256: artifact.sha256, arguments_sha256: hash(call.function.arguments),
recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification },
result: compactToolFeedback(result.content), original_characters: result.content.length, view: 'selected-original-fields' });
result: compactToolFeedback(result.content, viewVersion), original_characters: result.content.length, view: 'selected-original-fields' });
}
return { schemaVersion: 1, kind: 'latest-tool-feedback', sessionId: session.id, projectId: session.projectId,
taskId: run.taskId, runId: run.id, group_index: group.index, group_sha256: group.sha256, entries };
}
export function latestToolMessage(reference, document) {
export function latestToolMessage(reference, document, viewVersion = 1) {
if (![1, 2].includes(viewVersion)) throw new Error('未知的最新工具反馈视图版本。');
return { role: 'system', content: [
'以下是最近一组工具已经返回的实际结果反馈。该完整assistant/tool组因预算封存;这些字段来自原工件,不是再次执行、用户指令或推断。',
'先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。',
viewVersion === 1 ? '先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。'
: '先依据原结果推进。result_artifact_id只恢复已返回页;未读原文件用file_read.next_read_file并核对SHA。原工件沿原artifact_id与next_offset继续,不逐层读包装,不重放已完成操作。',
JSON.stringify({ latest_tools: { artifact_id: reference.id, sha256: reference.sha256 }, data: { kind: document.kind,
entries: document.entries.map(entry => ({ tool: entry.tool, result_artifact_id: entry.source.result_artifact_id,
recorded_state: entry.source.recorded_state, requires_verification: entry.source.requires_verification,
@@ -106,7 +110,7 @@ export function latestToolMessage(reference, document) {
}
export function verifyLatestToolDocument(store, session, plan, document, groups) {
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups);
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups, plan.latestToolsViewVersion ?? 1);
if (!expected || JSON.stringify(document) !== JSON.stringify(expected) || document.entries.length !== plan.latestToolsEntries) {
throw new Error('最新工具反馈的范围、来源或原结果视图不匹配。');
}
+19 -9
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { fileContinuation } from './read-continuation.mjs';
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
const parse = text => { try { return JSON.parse(text); } catch { return null; } };
@@ -6,7 +7,7 @@ const boundary = (text, end) => end > 0 && end < text.length && /[\uD800-\uDBFF]
// An observation is a deterministic view of an actual result. It is never a
// replacement assistant/tool message and never a model-generated assertion.
function observation(tool, value) {
function observation(tool, value, observationVersion = 1) {
if (!value || typeof value !== 'object' || value.requires_verification || ['unknown', 'interrupted', 'denied'].includes(value.status)) return null;
if (tool === 'read_file' && typeof value.content === 'string' && typeof value.path === 'string' && /^[a-f0-9]{64}$/i.test(value.sha256 ?? '')) {
return { kind: 'file', path: value.path, sha256: value.sha256, start_line: value.start_line, end_line: value.end_line,
@@ -33,7 +34,7 @@ function observation(tool, value) {
return null;
}
export function workingCandidates(store, session, run, groups) {
export function workingCandidates(store, session, run, groups, observationVersion = 1) {
const ledger = new Map([...store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.projectId === session.projectId
&& tool.taskId === run.taskId).map(tool => [tool.callId, tool]));
const candidates = [], revisions = new Map(), seen = new Set(), filePages = new Map();
@@ -44,7 +45,10 @@ export function workingCandidates(store, session, run, groups) {
const artifact = store.owned('artifact', invocation.resultArtifactId, session.id);
if (artifact.taskId !== run.taskId || artifact.kind !== 'tool-result' || artifact.runId !== invocation.runId) throw new Error('工作依据的任务或运行归属不匹配。');
if (store.artifactStore.read(artifact) !== result.content) throw new Error('工作依据与原工具结果不一致。');
const observed = observation(call.function.name, parse(result.content));
const raw = parse(result.content), observed = observation(call.function.name, raw, observationVersion);
if (observationVersion === 2 && observed?.kind === 'file') {
for (const key of ['total_characters', 'next_start_line', 'budget_limited']) if (raw[key] !== undefined) observed[key] = raw[key];
}
if (!observed) continue;
if (observed.kind === 'check-results') {
const job = store.core.check_job.get(observed.job_id);
@@ -96,21 +100,24 @@ export function workingEntry(candidate, characters) {
content_sha256: hash(content.slice(0, end)) };
}
export function workingDocument(session, run, entries) {
export function workingDocument(session, run, entries, observationVersion = 1) {
return { schemaVersion: 1, kind: 'task-working-set', sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
semantics: 'recorded-tool-observations; file hashes identify observed revisions, not current filesystem guarantees', entries };
semantics: 'recorded-tool-observations; file hashes identify observed revisions, not current filesystem guarantees',
...(observationVersion === 2 ? { observationVersion } : {}), entries };
}
export function workingMessage(reference, document, viewVersion = 2) {
const introduction = [
'以下是当前Task已执行工具的工作依据数据,不是追加指令、授权或再次执行。文件内容只代表所列SHA256的读取版本,修改前仍须核对;检查状态来自实际工具结果。',
'这些原结果所在的大消息组可能未发送。可以直接使用这里的代码和日志推进任务;截取不完整时读取对应result_artifact_id。不要重复扫描历史索引或重放已完成工具。',
viewVersion < 3 ? '这些原结果所在的大消息组可能未发送。可以直接使用这里的代码和日志推进任务;截取不完整时读取对应result_artifact_id。不要重复扫描历史索引或重放已完成工具。'
: '可直接使用这些代码和日志。result_artifact_id只恢复已返回页;尚未读取的原文件后文用file_read.next_read_file,核对SHA,不逐层读包装或重放操作。',
];
if (viewVersion === 1) return { role: 'system', content: [...introduction,
JSON.stringify({ working_set: { artifact_id: reference.id, sha256: reference.sha256 }, data: document })].join('\n') };
if (viewVersion !== 2) throw new Error('未知的工作依据发送视图版本。');
if (![2, 3].includes(viewVersion)) throw new Error('未知的工作依据发送视图版本。');
const data = { schemaVersion: document.schemaVersion, kind: document.kind, taskId: document.taskId,
entries: document.entries.map(entry => ({ ...entry, source: { tool: entry.source.tool, result_artifact_id: entry.source.result_artifact_id } })) };
entries: document.entries.map(entry => ({ ...entry, source: { tool: entry.source.tool, result_artifact_id: entry.source.result_artifact_id },
...(viewVersion === 3 && fileContinuation(entry.observation)?.next_read_file ? { file_read: fileContinuation(entry.observation) } : {}) })) };
return { role: 'system', content: [...introduction,
'调用、运行、消息组及原结果的完整来源保存在working_set工件中;这里是按原结果核对的精简视图。',
JSON.stringify({ working_set: { artifact_id: reference.id, sha256: reference.sha256 }, data }),
@@ -130,7 +137,10 @@ export function verifyWorkingDocument(store, session, plan, document, groups) {
if (artifact.kind !== 'tool-result' || artifact.sha256 !== source.result_sha256 || artifact.taskId !== plan.taskId || artifact.runId !== source.run_id) throw new Error('工作依据原结果身份不匹配。');
const text = store.artifactStore.read(artifact), message = group.messages.find(value => value.role === 'tool' && value.tool_call_id === source.call_id);
if (text !== message?.content) throw new Error('工作依据原消息内容不匹配。');
const observed = observation(source.tool, parse(text));
const raw = parse(text), observed = observation(source.tool, raw, document.observationVersion ?? 1);
if (document.observationVersion === 2 && observed?.kind === 'file') {
for (const key of ['total_characters', 'next_start_line', 'budget_limited']) if (raw[key] !== undefined) observed[key] = raw[key];
}
if (!observed || !Number.isInteger(entry.next_content_offset) || entry.next_content_offset < 0 || entry.next_content_offset > observed.content.length
|| JSON.stringify(workingEntry({ source, observation: observed }, entry.next_content_offset)) !== JSON.stringify(entry)) throw new Error('工作依据摘录与实际工具结果不匹配。');
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.24.6';
export const APP_VERSION = '1.24.7';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+1
View File
@@ -95,6 +95,7 @@ export function readText(project, relative) {
export function readLines(project, args) {
const file = readText(project, args.path);
if (args.expected_sha256 !== undefined && args.expected_sha256.toLowerCase() !== file.sha256) throw new Error('文件SHA256已变化,原分页不能继续拼接;请从新版本重新读取并核对。');
const lines = file.content.split('\n');
const start = Math.max(1, Number(args.start_line) || 1);
const end = Math.min(lines.length, start + 299, Math.max(start, Number(args.end_line) || start + 199));
+3 -3
View File
@@ -45,9 +45,9 @@ export const toolDefinitions = [
parameters: { type: 'object', properties: {}, required: [] } } },
{ type: 'function', function: { name: 'list_files', description: '查看当前项目的相对文件路径。依赖、版本目录、链接及常见凭据文件不会加入列表。',
parameters: { type: 'object', properties: { path: { type: 'string' }, depth: { type: 'integer', minimum: 0, maximum: 10 } }, required: ['path'] } } },
{ type: 'function', function: { name: 'read_file', description: '读取当前项目UTF-8文本与文件SHA256,行范围最多300行;实际页按当前请求预算缩小。分页用同一range_start_line/range_end_line和next_offset作为offset;此范围读完后用next_start_line继续。完整文件和原字节不变。',
{ type: 'function', function: { name: 'read_file', description: '读取项目UTF-8行与SHA256(最多300行),按预算分页。续读保持range_start_line/range_end_line,以next_offset为offset并传expected_sha256核对版本;范围读完用next_start_line。',
parameters: { type: 'object', properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' },
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['path'] } } },
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 }, expected_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' } }, required: ['path'] } } },
{ type: 'function', function: { name: 'search_files', description: '在当前项目的文本文件中按字面内容检索。结果声明已搜索文件数与数量上限。',
parameters: { type: 'object', properties: { query: { type: 'string' }, case_sensitive: { type: 'boolean' } }, required: ['query'] } } },
{ type: 'function', function: { name: 'propose_file', description: '提出一个文本文件的完整新内容。只产生待审查提案,不写入项目;由用户查看差异后应用。',
@@ -78,7 +78,7 @@ export function projectContext(project) {
'浏览器实际观察的controls.selector已在该DOM核对仅匹配一个元素,优先使用此定位并核对当前页面变化。按钮的nth-of-type可能在多个父元素各匹配一次,不能假定唯一。浏览器失败返回原错误;根据实际字段修正新计划,不重复读完的同一页。',
'检查结果含实际日志摘录及logArtifactId;需要更多失败信息时用read_artifact分段读取完整工件,不要要求用户重复提供工作台已有的日志。',
'若能力表提供浏览器工具,页面任务在构建后先用plan_browser/run_browser取得真实DOM与错误,按实际CSS定位交互和断言;观察或截图不代表通过。修复后重新构建并准备新计划验证,已有浏览器验收未通过时先处理再准备Git交付。',
'工作台会保留当前Task的代码与执行依据视图,绑定原工具结果和读取版本;可直接据此推进,不必反复恢复历史索引。内容有截取标记时按原结果工件取得缺少部分。',
'可直接使用当前Task的代码与执行依据视图。result_artifact_id只恢复已返回页;未读文件用read_file按原行范围和next_offset续读,expected_sha256核对版本,不拼接不同SHA。',
'最新完整工具组过大时,工作台发送可核验的最近工具反馈。先使用已返回状态继续;同一工程状态连续核对三次而未推进任务会暂停,不能把查询次数当成完成工作。',
'读取工件继续使用原artifact_id与next_offset;read_artifact这次返回的包装工具结果不是下一页入口。不要逐层读取包装或为了恢复已有代码而反复扫描历史索引。',
'文件已审核应用且实际检查通过后,可用plan_delivery准备Git提交预览。成功后工作台停止模型请求,等待用户在任务记录中审查并确认;不要继续查询提交状态,不把预览说成已提交。用delivery_report保存阶段证据;正式提交后的报告由工作台自动生成。',
+14 -3
View File
@@ -27,7 +27,7 @@ import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { BudgetResume } from '../core/context/budget-resume.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { artifactPage, filePage, readMessageBudget, readBatchBudget, spendReadBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { taskDeliveryProgress } from '../core/context/delivery-progress.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -119,6 +119,7 @@ export function validateToolArgs(tool, args) {
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
if (tool === 'read_file' && args.limit !== undefined && (args.limit < 1 || args.limit > 16000)) throw new Error('文件分页limit需要1到16000个字符。');
if (tool === 'read_file' && args.expected_sha256 !== undefined && (typeof args.expected_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.expected_sha256))) throw new Error('文件续读expected_sha256需要64位SHA256。');
if (args.case_sensitive !== undefined && typeof args.case_sensitive !== 'boolean') throw new Error('case_sensitive 必须是布尔值。');
if (tool === 'plan_checks' && args.names !== undefined && (!Array.isArray(args.names) || args.names.some(name => typeof name !== 'string'))) throw new Error('检查脚本名称需要文本数组。');
if (tool === 'plan_delivery' && args.message !== undefined && typeof args.message !== 'string') throw new Error('提交说明需要文本。');
@@ -464,6 +465,9 @@ export class Runtime {
const calls = message.tool_calls ?? [];
if (run.worker && (calls.length > 16 || workerUsage(this.store, run.worker).toolCalls + calls.length > run.worker.budget.maxToolCalls)) throw new BudgetExceeded('worker_tool_limit', '子任务工具次数超出固定累计预算或单次16项上限;这批工具未执行,原响应和用量已保存。');
run.readMessageBytes = readMessageBudget(planned.record, message);
run.readBatchBudget = readBatchBudget(planned.record, message);
run.readPageCharacters = planned.record.budget.inputBudget - planned.record.nextReadFixedInputTokens
- (planned.record.workingRetentionTokens ?? 0) < 4096 ? 2000 : Infinity;
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
session.providerMessages.push(message);
@@ -526,6 +530,7 @@ export class Runtime {
}
else if (signal.aborted) result = { status: 'interrupted', message: '用户停止了任务,这次调用没有执行。' };
else result = await this.executeTool(session, call, run);
spendReadBudget(run.readBatchBudget, call, result);
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id);
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
@@ -625,7 +630,9 @@ export class Runtime {
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
...(tool === 'read_browser_result' ? { repeated_read_count: Number.MAX_SAFE_INTEGER, reading_hint: BROWSER_READ_HINT } : {}) };
const maximumMessageBytes = Math.max(1, (run.readMessageBytes ?? 16000) - readMetadataReserve(readMetadata));
const batch = run.readBatchBudget;
const pageBytes = batch?.remainingCalls ? Math.floor(batch.remainingBytes / batch.remainingCalls) : run.readMessageBytes ?? 16000;
const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata));
if (!['act_browser_tab','prepare_environment','run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
@@ -765,7 +772,11 @@ export class Runtime {
}
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
else if (tool === 'read_file') {
result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes });
result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes,
// Match the planner's complete-small-source retention boundary;
// returning a larger page that is immediately trimmed adds no useful
// throughput. The escaped JSON budget can still make this smaller.
...(run.readBatchBudget ? { maximumPageCharacters: run.readPageCharacters } : {}) });
recordFileRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
}
else if (tool === 'search_files') result = searchFiles(run.project, args);
+1 -1
View File
@@ -1,4 +1,4 @@
export interface BudgetPauseSource { reason?: string; limitingReason?: string }
export interface BudgetPauseSource { reason?: string; limitingReason?: string; pauseKind?: string; tokenReservation?: { reservedTokens: number }; remainingTokens?: number; requiredInputTokens?: number; inputBudget?: number }
export function budgetPausePresentation(pause?: BudgetPauseSource, stopReason?: string): {
title: string; inputLabel: string; guidance: string;
} | null;
+7
View File
@@ -6,6 +6,13 @@ const reasons = {
export function budgetPausePresentation(pause, stopReason = '') {
const reason = pause?.reason ?? stopReason;
if (!reasons[reason]) return null;
if (['token_limit', 'task_token_limit'].includes(reason) && (pause?.pauseKind === 'request_reservation'
|| pause?.tokenReservation?.reservedTokens > pause?.remainingTokens)) return {
title: reason === 'task_token_limit' ? '下一次请求超出任务余额' : '下一次请求超出运行余额', inputLabel: '当前窗口可用输入',
guidance: pause?.requiredInputTokens !== undefined && pause.requiredInputTokens <= pause.inputBudget
? '必需输入可容纳于当前窗口;下一次请求的用量预留超过剩余预算。原上游用量保持,请核对运行和任务预算后显式续接。'
: '下一次请求的用量预留超过剩余预算。原上游用量保持;没有窗口分解的旧记录不补造输入结论,请核对预算后显式续接。',
};
if (reason === 'engine_input_budget' && pause?.limitingReason === 'remaining_token_budget') return {
title: '原生引擎剩余预算不足', inputLabel: '当前窗口可用输入',
guidance: '输入可容纳于当前上下文窗口;下一次请求的用量预留超过剩余预算。请核对运行和任务预算。',
+1 -1
View File
@@ -23,7 +23,7 @@ export function checkModelDispatchBudget(store,session,run,config,body,overheadT
const runRemainingTokens=remaining(run),taskRemainingTokens=remaining(task),remainingTokens=Math.min(runRemainingTokens,taskRemainingTokens);
if(tokenReservation.reservedTokens>remainingTokens){
const error=new BudgetExceeded(runRemainingTokens<=taskRemainingTokens?'token_limit':'task_token_limit','下一次模型请求的用量预留超过剩余预算,已在发送前暂停。原用量和已完成工具结果保留。');
error.contextBudget={tokenReservation,remainingTokens,runRemainingTokens:Number.isFinite(runRemainingTokens)?runRemainingTokens:null,
error.contextBudget={pauseKind:'request_reservation',tokenReservation,remainingTokens,runRemainingTokens:Number.isFinite(runRemainingTokens)?runRemainingTokens:null,
taskRemainingTokens:Number.isFinite(taskRemainingTokens)?taskRemainingTokens:null};
throw error;
}
+12
View File
@@ -1,5 +1,17 @@
# Agent Workbench:核心代理能力研究与产品计划
## 当前 S:读取可靠性修复与独立发行
接续fbedb738及docs/READING-RELIABILITY-S-PLAN.md,沿用planning-with-files、product-ui-ux,保留现有界面和React/Node技术栈,不委派。正式1.24.6/source54dbe3d6/原PID36552与Provider保持,正式状态重新取基线;R/P/O旧失败不续跑。本阶段模型请求预算0,真实交付另立后续预算,不提取/复制/重存Key、不重启原Provider、不推送。
1. [complete] 冻结原R页/上下文/用量证据及新正式基线;63项目79会话/3660工件、原PID36552/Provider保持,隔离重现续读和低吞吐问题。
2. [complete] 实现准确文件续读入口、可选原SHA核对和历史版本,纯文件批次容量/未用份额分配;保留16K/2048/1600安全、完整目标/工具配对/历史。
3. [complete] 区分上下文和Run/Task余额/观察用量预留;桌面1440及窄屏390实际四类诊断/刷新/续接预览取消10组通过,0模型请求,原Task/Run保持。
4. [complete] 原R前三轮+固定续读前后回放:旧8轮未完,新6轮读完2584且新纯读页实际可见,原检查仍失败/0修改。96相关及18安装/升级检查通过;源码新UI10组、历史预算/模型选择/上下文UI通过,原失败和修正保留,范围审查提交。
5. [in_progress] 冻结1.24.7不可变新候选,独立源码输入/重建/归档/便携/隔离安装和正式保留PID/Provider升级;原数据核对、实际入口/原生回看、证据封存/离线核验/回顾与Git收尾。
仅有隔离回放改善不能宣称真实工程或Purge收益;S产品交付后,再按原前置关系另立新的单次预检/Node预算。更新重复目录核验性能及1.25其余能力单列,保持完整性/防篡改和故障回退门槛。
## 当前 R:连接诊断后的新真实模型交付验收
接续 Q 的 8cf152e3;正式产品保持 1.24.6/source54dbe3d6、原 PID36552/Provider。沿用 planning-with-files,不委派、不重启、不提取/复制/重存 Key、不推送。固定启用 jojocode/5b4daed9(GPT/Chat JSON、16K/2048、连接修订5/凭据1),高性能默认池和旧09b停用状态保留;P/O 原失败不续跑。本轮先冻结脚本和契约,再发送新的有界请求,不以不断开样本掩盖失败。
+11
View File
@@ -18,3 +18,14 @@ test('window overflow and historical pauses retain distinct and honest diagnoses
assert.equal(budgetPausePresentation(undefined, 'token_limit').title, '本次运行预算不足');
assert.equal(budgetPausePresentation(undefined, 'change_set_review'), null);
});
test('R observed reservation shortage keeps the window-fit diagnosis separate from Run/Task credit', () => {
const pause = { reason: 'token_limit', requiredInputTokens: 12352, inputBudget: 12352,
remainingTokens: 17429, tokenReservation: { reservedTokens: 29623 } };
assert.equal(budgetPausePresentation(pause).title, '下一次请求超出运行余额');
assert.match(budgetPausePresentation(pause).guidance, /输入可容纳/);
assert.equal(budgetPausePresentation({ ...pause, reason: 'task_token_limit' }).title, '下一次请求超出任务余额');
const withoutWindow = budgetPausePresentation({ reason: 'token_limit', pauseKind: 'request_reservation' });
assert.match(withoutWindow.guidance, /不补造输入结论/);
assert.equal(budgetPausePresentation({ reason: 'token_limit', requiredInputTokens: 100, inputBudget: 100 }).title, '本次运行预算不足');
});
+115
View File
@@ -0,0 +1,115 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { fileContinuation } from '../src/core/context/read-continuation.mjs';
import { filePage, readMessageBudget, readBatchBudget, spendReadBudget } from '../src/core/context/read-budget.mjs';
import { readLines } from '../src/server/files.mjs';
import { Runtime, validateToolArgs } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { requestHistory, requestMetrics } from '../src/shared/contracts/model-request.mjs';
import { RequestPlanner, verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { fixture, compatibleFixture, call, completion, until, assertToolPairs } from './helpers.mjs';
const sha = text => createHash('sha256').update(text).digest('hex');
test('continuations distinguish unread source, later original line ranges and already returned result wrappers', t => {
const f = fixture(t), content = Array.from({ length: 310 }, (_, i) => '行' + i + '🙂').join('\r\n');
fs.writeFileSync(path.join(f.projectRoot, 'source.txt'), content);
const selected = readLines(f.project, { path: 'source.txt', start_line: 2, end_line: 301 });
const first = filePage(selected, {}, { maximumMessageBytes: 1500 });
const next = fileContinuation(first); assert.equal(next.range_complete, false);
assert.deepEqual(next.next_read_file, { path: 'source.txt', start_line: 2, end_line: 301, offset: first.next_offset, expected_sha256: sha(content) });
const tail = filePage(selected, { offset: selected.content.length - 3 });
assert.equal(tail.truncated, true, 'truncated can remain true after reaching the end of a selected range');
assert.equal(fileContinuation(tail).range_complete, true);
assert.deepEqual(fileContinuation(tail).next_read_file, { path: 'source.txt', start_line: 302, expected_sha256: sha(content) });
const entire = filePage(readLines(f.project, { path: 'source.txt', start_line: 302 }), {});
assert.equal(fileContinuation(entire).next_read_file, null);
assert.equal(fileContinuation({ path: 'source.txt', sha256: sha(content), truncated: true }), null, 'Legacy missing range is not invented');
assert.equal(readLines(f.project, next.next_read_file).sha256, first.sha256);
fs.appendFileSync(path.join(f.projectRoot, 'source.txt'), '\nchanged');
assert.throws(() => readLines(f.project, next.next_read_file), /SHA256已变化/);
assert.throws(() => validateToolArgs('read_file', { path: 'source.txt', expected_sha256: 'invalid' }), /SHA256/);
});
test('pure-file batch returns unused small-page space while mixed and historical allocation stays conservative', () => {
const plan = { readBudgetPolicyVersion: 2, budget: { inputBudget: 12352 }, nextReadFixedInputTokens: 9000, workingRetentionTokens: 600 };
const message = { role: 'assistant', content: '', tool_calls: [call('small', 'read_file', { path: 'small' }), call('large', 'read_file', { path: 'large' })] };
const batch = readBatchBudget(plan, message), before = batch.remainingBytes / 2;
spendReadBudget(batch, message.tool_calls[0], { path: 'small', content: 'x' });
assert.ok(batch.remainingBytes > before); assert.equal(batch.remainingCalls, 1);
assert.ok(readMessageBudget(plan, message) > readMessageBudget({ ...plan, readBudgetPolicyVersion: undefined }, message));
const mixed = { ...message, tool_calls: [...message.tool_calls, call('plan', 'plan_checks', {})] };
assert.equal(readBatchBudget(plan, mixed), null);
assert.equal(readMessageBudget(plan, mixed), readMessageBudget({ ...plan, readBudgetPolicyVersion: undefined }, mixed));
assert.equal(readBatchBudget(plan, { ...message, tool_calls: [call('artifact', 'read_artifact', { artifact_id: 'raw' })] }), null);
});
test('observed upstream high input pauses before a new request, preserves reported usage and distinguishes the limiting ledger', t => {
const f = fixture(t), config = { ...f.store.config, model: 'owned', contextLimit: 16000, maxOutputTokens: 2048,
maxRunTokens: 90000, maxTaskTokens: 90000 };
const run = f.store.beginRun(f.session, 'Original goal and all requirements remain.', false, config), task = f.store.core.task.get(run.taskId);
f.session.providerMessages.push({ role: 'user', content: task.goal });
run.usage.totalTokens = 72571; task.usage.totalTokens = 72571;
run.consumption = [{ runId: run.id, attemptId: 'owned-high-input', model: config.model, protocol: 'chat-completions', endpoint: config.baseUrl,
usageStatus: 'reported', usage: { prompt_tokens: 27164, completion_tokens: 303, total_tokens: 27467 },
localEstimate: { schemaVersion: 1, inputTokens: 12168, outputTokens: 2048 } }];
const original = structuredClone(run.consumption), planner = new RequestPlanner(f.store);
const prepare = system => planner.prepare(f.session, run, config, { system, tools: [], stepId: 'owned-step' });
for (const expected of ['token_limit', 'task_token_limit']) {
if (expected === 'task_token_limit') task.usage.totalTokens++;
assert.throws(() => prepare('Read only original input.'), error => {
assert.equal(error.reason, expected); assert.equal(error.contextBudget.pauseKind, 'request_reservation');
assert.ok(error.contextBudget.requiredInputTokens <= error.contextBudget.inputBudget);
assert.ok(error.contextBudget.tokenReservation.reservedTokens > error.contextBudget.remainingTokens);
assert.match(error.message, /输入可容纳/); return true;
});
}
assert.throws(() => prepare('完整原目标'.repeat(10000)), error => { assert.equal(error.reason, 'context_limit'); assert.equal(error.contextBudget.pauseKind, undefined); return true; });
assert.deepEqual(run.consumption, original); assert.equal(f.store.core.context_plan.size, 0, 'No unaffordable request plan is dispatched');
});
for (const protocol of ['chat-completions', 'responses', 'anthropic-messages']) {
test(protocol + ': complete actual Unicode/CRLF pages and small source survive the next bounded wire request', { timeout: 30000 }, async t => {
const f = fixture(t), text = ('long single line 雪🙂"\\'.repeat(100) + '\r\n').repeat(3), small = 'export const value = "原文🙂";\r\n';
fs.writeFileSync(path.join(f.projectRoot, 'long.txt'), text); fs.writeFileSync(path.join(f.projectRoot, 'small.mjs'), small);
let n = 0, next = 0, reconstructed = '', sawSmall = false;
const server = await compatibleFixture(t, (_route, body) => {
n++; const messages = requestHistory(body); assertToolPairs(messages);
const actual = messages.filter(m => m.role === 'tool').map(m => JSON.parse(m.content));
const page = actual.filter(value => value.path === 'long.txt').at(-1);
if (n > 1) {
assert.ok(page, 'The actual newest page must reach the model in full'); assert.equal(page.offset, next);
assert.equal(page.content, text.slice(page.offset, page.next_offset));
assert.ok(page.content.isWellFormed());
reconstructed += page.content; next = page.next_offset;
sawSmall ||= actual.some(value => value.path === 'small.mjs' && value.content === small);
}
const calls = n === 1 ? [call('small-first', 'read_file', { path: 'small.mjs' }), call('long-first', 'read_file', { path: 'long.txt', limit: 16000 })]
: next < text.length ? [call('long-next-' + n, 'read_file', { path: 'long.txt', offset: next, start_line: 1, end_line: 4, limit: 16000, expected_sha256: sha(text) })] : [];
if (protocol === 'chat-completions') return { body: completion(calls, calls.length ? '' : 'Done') };
if (protocol === 'responses') return { body: { id: 'resp_' + n, status: 'completed',
output: calls.length ? calls.map(c => ({ type: 'function_call', id: 'fc_' + c.id, call_id: c.id, name: c.function.name, arguments: c.function.arguments, status: 'completed' }))
: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Done' }] }], usage: { input_tokens: 123, output_tokens: 45 } } };
return { body: { id: 'msg_' + n, type: 'message', role: 'assistant', model: 'owned-pages', stop_reason: calls.length ? 'tool_use' : 'end_turn',
content: calls.length ? calls.map(c => ({ type: 'tool_use', id: c.id, name: c.function.name, input: JSON.parse(c.function.arguments) })) : [{ type: 'text', text: 'Done' }], usage: { input_tokens: 123, output_tokens: 45 } } };
});
f.store.saveConfig({ contextLimit: 16000, maxOutputTokens: 2048, maxSteps: 12 });
const provider = new Provider({ retryPolicy: { attempts: 1 } }), hub = provider.modelHub(f.store);
const connection = hub.upsert({ name: 'Owned pages', protocol, baseUrl: server.baseUrl, model: 'owned-pages', requiresKey: false, contextLimit: 16000, maxOutputTokens: 2048 });
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Read these two original source files exactly.');
await until(() => !runtime.isActive(f.session.id), 25000);
assert.equal(f.session.status, 'completed', JSON.stringify({ failure: f.session.failure, run: f.store.core.run.get(f.session.runId), next, expected: text.length }));
assert.equal(reconstructed, text); assert.ok(sawSmall);
for (const plan of f.store.core.context_plan.values()) {
verifyPlanEvidence(f.store, f.session, plan);
const body = JSON.parse(f.store.artifactStore.read(f.store.core.artifact.get(plan.requestArtifactId)));
assert.ok(requestMetrics(body).estimatedInputTokens <= 12352); assert.equal(plan.budget.safetyTokens, 1600);
assert.equal(plan.readBudgetPolicyVersion, 2);
}
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'long.txt'), 'utf8'), text);
});
}
+1 -1
View File
@@ -278,7 +278,7 @@ test('a 1.6.1 full-provenance sent view remains verifiable after introducing the
const workingArtifact = f.store.owned('artifact', record.workingSetArtifactId, f.session.id);
const document = JSON.parse(f.store.artifactStore.read(workingArtifact));
const oldMessage = workingMessage(workingArtifact, document, 1), body = structuredClone(prepared.body);
const currentMessage = workingMessage(workingArtifact, document, 2);
const currentMessage = workingMessage(workingArtifact, document, prepared.record.workingSetViewVersion);
body.messages = body.messages.map(message => message.content === currentMessage.content ? oldMessage : message);
const metrics = requestMetrics(body), request = f.planner.artifact(f.session, f.run, body, 'model-request');
Object.assign(record, { requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens, requestArtifactId: request.id });