feat: pin controlled Harness profile and verify owned tool and model bridge

This commit is contained in:
Agent Workbench Dev
2026-10-31 04:25:44 +08:00
parent 60b63bc70f
commit a01c41811b
14 changed files with 1928 additions and 0 deletions
+3
View File
@@ -9,3 +9,6 @@ docs/workers-*.tap binary
docs/workers-*.log binary
docs/workers-*-log.txt binary
docs/workers-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
docs/controlled-engine-*.tap binary
docs/controlled-engine-*-log.txt binary
docs/controlled-engine-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
+17
View File
@@ -0,0 +1,17 @@
# 1.14 受控外部引擎验收
2026-10-31,接续60b63bc/正式1.13.0。本阶段按PLAN-1.14开发,当前尚未完成完整发行或正式升级;本地模型夹具、实际工具链、真实模型推理分别判定。
## A:固定版本与协议
受控适配器锁定已有Harness 0.2.1-rc.2、sdk-minimal、原SDK/CLI/Node及七份工具/代理/LLM/Include关键运行器。每个Run生成独立home、agents、叠加插件和JSON patch;禁用原生文件、工作目录工具、持久终端、原生模型与重试插件,实际appReady后再次核对完整工具schema、唯一代理provider、所属PID/nonce/SDK session/Run和工作目录。
原SDK不提供单会话取消或反向审批。受控桥通过独立本地HTTP返回工具/模型请求,原SDK仍使用initialize、session/prompt、session/wait与shutdown;收据必须在所属agent/inbox/spliced原事件中出现,输出来自同一活动的assistant/message,不能用idle或回复文字判工程交付。停止/恢复与真实工程的完整接入仍由后续切片验收。
首轮7/7专项通过:关键运行器变化、Include patch、完整目录与重复schema、进程/Run/SDK身份及Origin/认证、重复/越界/格式错误/来源变化、模型目录/输出预算和停止/超长正文守卫。原TAP为controlled-engine-core-first.tap。
实际Harness加本地固定模型夹具通过:完整启动目录核对、两次代理模型请求、一次原工具调用、prompt入队收据、所属原活动输出与正常退出;0真实模型请求、0stderr。原输入/协议/通知/桥数据与退出保存在controlled-engine-native-first.json及对应-log.txt。本轮只读取独立夹具README,没有开放用户工程或现有真实连接。
## 尚待验收
B:受限桥与自有Task/Run审批/账本接入;C:独立工程、累计预算、进程树和父审查;D:恢复/桌面/390px;E:Purge来源/兼容/同题对照;F:完整回归、独立发行及保留状态升级。正式4318继续使用不可变1.13.0。
+15
View File
@@ -0,0 +1,15 @@
# 1.14 阶段回顾
2026-10-31。每个切片按计划、实现、原证据、限制和本地Git回顾;此文随实际结果更新,阶段尚未完整交付。
| 切片 | 当前实现/验证 | 遗留与下一步 |
| --- | --- | --- |
| A:版本/协议 | 新受控安装身份、七份关键运行器、独立profile叠加/桥;7/7边界专项和实际Harness固定模型2请求/1工具/收据/wait/正常退出通过 | 原SDK没有单会话取消或反向审批;桥不能单凭启动成功宣称工程交付 |
| B:工具桥 | 原生项目/终端/模型/重试插件禁用,appReady核对完整工具schema;原进程/Run/SDK/来源、输入上限和重复ID守卫 | 接入自有执行账本、文件审查及固定检查,保持原工具身份和未知状态 |
| C–F | 尚未完成 | 独立工程/停止恢复/父审查、真实界面、Purge同题对照、完整发行与状态保持升级 |
前置研究确认sdk-minimal仍含danger-full-access策略和本机工具,不能把profile名字当权限边界;采用宿主受限桥和实际目录检查。Harness现有DeepSeek provider使用Messages API,本工作台现有连接是兼容Chat层;自有代理provider保持两层分离,使引擎不取得模型Key,也不把一种协议冒充另一种协议。
查询期间过宽文件枚举、几处推测的不存在路径、一次PowerShell foreach直连管道解析失败已保存计划/发现并修正为已确认文件、明确变量结果;这些查询不当作功能失败或验收结果。首轮实际协议与本地专项成功原记录保留,后续实现变化采用新的结果目录。
正式服务/原模型连接保持,真实模型推理和Purge收益仍按用户既有决定暂缓。每个已完成切片检查diff后本地提交,不把计划或夹具成功登记为整个产品完成。
+52
View File
@@ -0,0 +1,52 @@
TAP version 13
# Subtest: controlled installation pins the native kernel and bridge independently of the existing connection-probe identity
ok 1 - controlled installation pins the native kernel and bridge independently of the existing connection-probe identity
---
duration_ms: 881.612
type: 'test'
...
# Subtest: controlled profiles disable every native project/terminal provider and native model/retry route using the actual include patch contract
ok 2 - controlled profiles disable every native project/terminal provider and native model/retry route using the actual include patch contract
---
duration_ms: 0.5845
type: 'test'
...
# Subtest: owned tool catalogues seal full schemas canonically and reject duplicate or malformed declarations
ok 3 - owned tool catalogues seal full schemas canonically and reject duplicate or malformed declarations
---
duration_ms: 5.3258
type: 'test'
...
# Subtest: bridge authentication, current Run, process, SDK session and browser-origin checks reject before dispatch
ok 4 - bridge authentication, current Run, process, SDK session and browser-origin checks reject before dispatch
---
duration_ms: 756.6592
type: 'test'
...
# Subtest: bridge duplicates, unknown tools, malformed arguments and source changes are refused before a second side effect
ok 5 - bridge duplicates, unknown tools, malformed arguments and source changes are refused before a second side effect
---
duration_ms: 685.1501
type: 'test'
...
# Subtest: bridge model requests bind the exact catalogue, route and output bound and preserve raw request/result identity
ok 6 - bridge model requests bind the exact catalogue, route and output bound and preserve raw request/result identity
---
duration_ms: 655.7846
type: 'test'
...
# Subtest: stopped and oversized bridge requests never reach a local model or tool callback
ok 7 - stopped and oversized bridge requests never reach a local model or tool callback
---
duration_ms: 649.3997
type: 'test'
...
1..7
# tests 7
# suites 0
# pass 7
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 3727.1463
@@ -0,0 +1,4 @@
STATE starting
STATE initializing
STATE ready
{"success":true,"root":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\controlled-native-01e1d8d0-f51a-4799-9d81-3e591267ea11","modelCalls":2,"toolCalls":1,"realModelRequests":0,"status":"closed","error":null,"stderr":""}
@@ -0,0 +1,39 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { resolveControlledInstallation } from '../src/core/engines/controlled-installation.mjs';
import { ControlledDeepSeekSession } from '../src/core/engines/controlled-session.mjs';
const root = path.resolve('.qa/controlled-native-' + randomUUID()), cwd = path.join(root, 'project');
fs.mkdirSync(cwd, { recursive: true }); fs.writeFileSync(path.join(cwd, 'README.md'), '# Owned controlled SDK fixture\n');
const owner = Object.fromEntries(['sessionId', 'projectId', 'taskId', 'runId', 'jobId'].map(key => [key, randomUUID()]));
const installation = resolveControlledInstallation(process.cwd(), process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT);
assert.equal(installation.controlledStatus, 'available', installation.message);
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(new Error('Owned fixture deadline.')), 30000);
const driver = new ControlledDeepSeekSession(installation, { timeoutMs: 10000 }); let success = false, failure = null, modelCalls = 0, toolCalls = 0;
try {
await driver.open({ directory: path.join(root, 'runtime'), cwd, owner, sdkSessionId: randomUUID(), signal: controller.signal,
tools: [{ name: 'read_file', description: 'Read one owned fixture file.', parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } }],
config: { model: 'fixture-controlled', maxOutputTokens: 512, contextLimit: 32000, maxRunDurationMs: 30000 },
onModel: async input => {
modelCalls++;
assert.equal(input.model, 'fixture-controlled');
return { message: { role: 'assistant', content: modelCalls === 1 ? '' : 'Owned fixture inspected.', ...(modelCalls === 1 ? {
tool_calls: [{ id: 'controlled-read-1', type: 'function', function: { name: 'read_file', arguments: JSON.stringify({ path: 'README.md' }) } }],
} : {}) }, usage: { prompt_tokens: 30, completion_tokens: 8, total_tokens: 38 } };
},
onTool: async input => { toolCalls++; assert.equal(input.name, 'read_file'); assert.equal(input.arguments.path, 'README.md'); return { text: fs.readFileSync(path.join(cwd, input.arguments.path), 'utf8') }; },
onState: state => console.log('STATE ' + state),
});
await driver.prompt('Read README.md with the owned tool and report completion.');
assert.equal(await driver.wait(), 'Owned fixture inspected.'); assert.equal(modelCalls, 2); assert.equal(toolCalls, 1);
success = true;
} catch (error) { failure = { name: error.name, message: error.message, stack: error.stack }; }
finally {
const report = await driver.close({ force: !success }); clearTimeout(timeout);
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify({ success, scope: 'actual-harness-scripted-model-controlled-bridge', installation,
owner, modelCalls, toolCalls, realModelRequests: 0, failure, report }, null, 2));
fs.writeFileSync('.qa/controlled-native-first-location.json', JSON.stringify({ root, result: path.join(root, 'result.json') }));
console.log(JSON.stringify({ success, root, modelCalls, toolCalls, realModelRequests: 0, status: report.status, error: failure?.message ?? null, stderr: report.stderr?.slice(-3000) }));
assert.equal(success, true, failure?.message); assert.equal(report.status, 'closed'); assert.equal(report.cleanup.rootExited, true);
}
File diff suppressed because it is too large Load Diff
+9
View File
@@ -1,5 +1,14 @@
# 汇总发现
## 2026-10-31 1.14 受控引擎前置核对
- 原程序验证确认自有Cordis bridge与LLM adapter可在原sdk-minimal通过实际完整目录/唯一provider核对,2次本地模型请求和1次read_file后观测原收据、assistant/message和turn/end(completed),正常退出/空stderr。7/7边界专项通过。原DeepSeek provider使用Messages API,与现有兼容Chat层不同,采用自有代理provider桥保持协议和凭据分层。
- Native RequestMessage实测为system/user/assistant/tool的内容块,原工具结果带toolCallId;后续桥须按原字段转换并用真实调用账本反馈,不能从裁剪后的发送历史拼造原结果。Include patch实测契约为{id,disabled:true},不会使用推测的select/update字段。
- 新查询错误包括几处不存在的lib/types/patch路径与PowerShell foreach后直接管道的解析失败;已按实际目录和先收集变量再管道修正,未启动模型或改变用户资源。
- 已安装Harness 0.2.1-rc.2、Desktop插件1.1.81及独立1.1.78有不同来源;固定sdk-minimal原SDK不提供单会话cancel或反向请求审批,prompt返回入队收据,wait/事件须按实际Session归属核对。
- sdk-minimal并非受限工程沙箱:它包含文件系统、工作目录与持久终端工具,sandbox-policy配置为danger-full-access。不能直接运行用户工程;需禁用原生项目工具、核对实际全目录,再通过自有Task/Run权限和账本桥执行。
- 首轮过宽README/package枚举及不存在的旧路径造成截断/rg错误,后续按已确认的具体目录和文件核对,不反复全库输出。
## 2026-10-31 1.13 隔离worker接续
- 最终Git严格复核曾拒绝被全局*.log忽略的workers-integrated-first.log。既有workers-integrated-first-log.txt与其原字节/SHA一致;封存器修正后115份报告及身份共116文件与Git索引原字节一致,27份当前日志、1份历史日志来源映射及18张原PNG核对通过,原.log保留。身份SHA256为0f3e2f13f25ca9a10126cdeb537b2da45e8b4f488396e5e2fb62ff70300d8f2f。Node/REA/SDK/Edge来源、部署后四表每行和28全部导出再次核对一致,9229关闭。真正的交付边界为两个受限worker、文本审查合并与本地真实工具链;真实模型自主完成率及下一阶段引擎写入/Purge收益不纳入本轮通过。
+7
View File
@@ -1,5 +1,12 @@
# 统一执行进度
## 2026-10-31 1.14 受控外部引擎阶段
- 切片A:受控安装身份/profile/原SDK/桥已实现,7/7边界专项及实际Harness本地固定模型2请求/1次工具/收据/原活动/wait/正常退出通过;0真实模型请求,原模型输入/工具/通知/退出完整保存controlled-native-01e1d8d0及docs副本。正式1.13/连接保持;继续B自有账本、C独立工程和停止恢复。
- 用户授权继续全量开发并及时回顾。接续60b63bc的干净工作区,保留正式1.13/PID23172和当前模型连接,开始PLAN-1.14六切片;本地源码/夹具与独立工程先行,真实模型任务继续暂缓。
- 源码核对确认sdk-minimal是完整Cordis树,仍含本机文件/终端工具、danger-full-access;原SDK只有收据/事件/wait/resume/进程关闭,不能假定原生审批或单会话取消。下一步固定实际profile/工具注册调用链,构建自有受限叠加插件,禁用原生项目写入与终端。
- 首轮文件枚举范围过宽导致输出截断,三处旧runtime/store/server路径不存在,rg返回1;已改为实际core/engine-manager、execution/storage/server目录及SDK/profile具体文件。无产品写入、启动或模型请求;这些查询错误不作为功能验证结果。
## 2026-10-31 1.13 隔离执行阶段
- 最终重新封存与严格Git核对通过:115份报告及身份共116文件与索引原字节一致,27份当前日志、1份历史日志来源映射与18张PNG保持;身份SHA256为0f3e2f13f25ca9a10126cdeb537b2da45e8b4f488396e5e2fb62ff70300d8f2f。四表/全部28导出、正式1.13.0/PID23172及9229关闭再次核对;git diff --cached --check通过。本次提交保存最终发行/部署/证据与回顾,PLAN-1.14六切片保持未实现。
@@ -0,0 +1,55 @@
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { engineDigest, engineError } from '../../shared/contracts/engines.mjs';
import { resolveDeepSeekInstallation, assertDeepSeekInstallation, engineFileIdentity } from './deepseek-installation.mjs';
import { CONTROLLED_BRIDGE_PLUGIN, CONTROLLED_DISABLED_PLUGINS, canonicalEngineValue } from './controlled-plugin.mjs';
export const CONTROLLED_ENGINE_SCOPE = 'deepseek-workbench-engine-v1';
export const CONTROLLED_CRITICAL_FILES = Object.freeze(['packages/core/tools/lib/index.js', 'packages/core/agent/lib/index.js',
'packages/core/agent-loop/lib/index.js', 'packages/core/system-prompt/lib/index.js', 'packages/llm/llm/lib/index.js',
'packages/llm/llm-retry/lib/index.js', 'vendor/include/lib/index.js']);
export const controlledDigest = value => engineDigest(canonicalEngineValue(value));
export function resolveControlledInstallation(appDirectory = process.cwd(), root) {
const base = resolveDeepSeekInstallation(appDirectory, root);
if (base.status !== 'available') return { ...base, scope: CONTROLLED_ENGINE_SCOPE, controlledStatus: 'unavailable' };
try {
const inputs = CONTROLLED_CRITICAL_FILES.map(relative => {
const file = engineFileIdentity(path.join(base.root, relative));
if (!file.path.startsWith(base.root + path.sep)) throw engineError('受控引擎输入不属于当前安装目录。');
return { ...file, relative };
});
const bridgeSha256 = engineDigest(CONTROLLED_BRIDGE_PLUGIN), disabledPlugins = [...CONTROLLED_DISABLED_PLUGINS];
const controlledSha256 = controlledDigest({ schemaVersion: 1, scope: CONTROLLED_ENGINE_SCOPE, installationSha256: base.identitySha256,
inputs, bridgeSha256, disabledPlugins });
return { ...base, scope: CONTROLLED_ENGINE_SCOPE, controlledStatus: 'available', controlledSha256, controlledInputs: inputs,
bridgeSha256, disabledPlugins, llmModule: pathToFileURL(path.join(base.root, 'packages/llm/llm/lib/index.js')).href,
controlledCapabilities: { bridge: true, text: true, nativeProjectTools: false, nativeModelCredentials: false,
singleSessionCancel: false, cancellationUnit: 'owned-process', nativeSessionResume: false, tokenStreaming: false } };
} catch (error) { return { ...base, scope: CONTROLLED_ENGINE_SCOPE, controlledStatus: 'unavailable', message: error.message }; }
}
export function assertControlledInstallation(installation) {
assertDeepSeekInstallation(installation);
const current = resolveControlledInstallation(process.cwd(), installation.root);
if (current.controlledStatus !== 'available' || current.controlledSha256 !== installation.controlledSha256) {
throw engineError('受控引擎入口、工具内核或叠加插件已变化,请重新检测并封存新计划。', 409, 'ENGINE_INPUT_CHANGED');
}
return current;
}
export function controlledToolCatalogue(tools) {
if (!Array.isArray(tools) || !tools.length || tools.length > 32) throw engineError('受控工具目录需要1到32项。', 400);
const result = tools.map(tool => tool.function ?? tool).map(({ name, description, parameters }) => {
if (typeof name !== 'string' || !/^[a-z][a-z0-9_]{0,63}$/.test(name) || typeof description !== 'string'
|| !parameters || parameters.type !== 'object') throw engineError('受控工具目录格式无效。', 400);
return structuredClone({ name, description, parameters });
}).sort((left, right) => left.name.localeCompare(right.name));
if (new Set(result.map(tool => tool.name)).size !== result.length) throw engineError('受控工具目录不能重复。', 400);
return result;
}
export function controlledPatch(plugin, config) {
return [...CONTROLLED_DISABLED_PLUGINS.map(id => ({ id, disabled: true })),
{ insert: [{ id: 'agent-workbench-controlled-bridge', name: plugin, config }] }];
}
+102
View File
@@ -0,0 +1,102 @@
// The literal is copied into each owned runtime. Bundling preserves its bytes;
// no third-party program or currently running release is modified.
export const CONTROLLED_BRIDGE_PLUGIN = String.raw`import fs from 'node:fs';
import { createHash } from 'node:crypto';
export const name = 'agent-workbench-controlled-bridge';
export const inject = ['tools', 'llm', 'appReady'];
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
const digest = value => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
export async function apply(ctx, config) {
const { LlmAdapter } = await import(config.llmModule);
const controller = new AbortController();
ctx.effect(() => () => controller.abort(new Error('Owned engine bridge disposed.')));
const descriptors = config.tools.map(({ name, description, parameters }) => ({ name, description, parameters }));
const names = new Set(descriptors.map(tool => tool.name));
const catalogue = () => ctx.tools.schemas().map(({ name, description, parameters }) => ({ name, description, parameters }))
.sort((left, right) => left.name.localeCompare(right.name));
const assertCatalogue = () => {
if (digest(catalogue()) !== config.catalogueSha256) throw new Error('The owned tool catalogue changed.');
};
const post = async (route, data, signal) => {
controller.signal.throwIfAborted(); signal?.throwIfAborted(); assertCatalogue();
const response = await fetch(config.endpoint + route, { method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.nonce },
signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
body: JSON.stringify({ owner: config.owner, sessionId: config.sdkSessionId, pid: process.pid, data }) });
let size = 0; const chunks = [];
for await (const chunk of response.body) {
size += chunk.length;
if (size > config.maximumFrameBytes) throw new Error('Owned bridge response exceeded its bound.');
chunks.push(chunk);
}
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (!response.ok) throw new Error(value.error || 'Owned bridge rejected the request.');
return value;
};
for (const descriptor of descriptors) ctx.tools.register({ ...descriptor,
output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
async execute(args, execution) {
if (execution.agent?.session?.id !== config.sdkSessionId) throw new Error('Tool caller is not the owned SDK session.');
return post('/tool', { callId: execution.callId, name: descriptor.name, arguments: args }, execution.signal);
},
});
ctx.on('tools/pre-execute', async (execution, next) => {
assertCatalogue();
if (execution.agent?.session?.id !== config.sdkSessionId || !names.has(execution.name)) {
return { kind: 'deny', reason: 'This tool or caller is outside the owned workbench scope.' };
}
return next();
});
class WorkbenchAdapter extends LlmAdapter {
async resolveModel(provider, model) {
if (provider !== 'agent-workbench' || model !== config.model) throw new Error('Owned model route changed.');
return { provider, id: model, name: model, contextWindow: config.contextLimit, defaultMaxTokens: config.maxOutputTokens };
}
async *stream(options) {
if (options.provider !== 'agent-workbench' || options.model !== config.model) throw new Error('Unowned model route.');
const result = await post('/model', { messages: options.messages, system: options.system ?? null,
tools: options.tools ?? [], toolHistory: options.toolHistory ?? null,
model: options.model, maxTokens: options.maxTokens ?? config.maxOutputTokens }, options.signal);
const message = result.message;
if (!message || message.role !== 'assistant' || typeof message.content !== 'string'
|| message.tool_calls !== undefined && !Array.isArray(message.tool_calls)) throw new Error('Invalid owned model result.');
let index = 0;
if (message.content) {
yield { type: 'block-start', index, blockType: 'text' };
yield { type: 'text-delta', index, text: message.content };
yield { type: 'block-end', index, block: { type: 'text', text: message.content } }; index++;
}
for (const call of message.tool_calls ?? []) {
if (typeof call.id !== 'string' || typeof call.function?.name !== 'string'
|| typeof call.function.arguments !== 'string') throw new Error('Incomplete owned tool call.');
JSON.parse(call.function.arguments);
yield { type: 'block-start', index, blockType: 'tool-call' };
yield { type: 'tool-call-delta', index, id: call.id, name: call.function.name, argumentsDelta: call.function.arguments };
yield { type: 'block-end', index, block: { type: 'tool-call', id: call.id, name: call.function.name, arguments: call.function.arguments } }; index++;
}
const usage = result.usage, valid = value => Number.isSafeInteger(value) && value >= 0;
if (valid(usage?.prompt_tokens) && valid(usage?.completion_tokens)) {
yield { type: 'usage', usage: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens } };
}
yield { type: 'finish', reason: { kind: message.tool_calls?.length ? 'tool-calls' : 'stop' } };
}
}
ctx.llm.registerAdapter(['agent-workbench'], new WorkbenchAdapter());
const off = ctx.appReady.onReady(() => {
assertCatalogue();
const providers = ctx.llm.listProviders().map(provider => provider.id).sort();
if (providers.length !== 1 || providers[0] !== 'agent-workbench') throw new Error('Unexpected native model provider.');
const marker = { schemaVersion: 1, nonce: config.nonce, pid: process.pid, signal: 'appReady', readyAt: new Date().toISOString(),
owner: config.owner, sdkSessionId: config.sdkSessionId, catalogue: catalogue(), catalogueSha256: config.catalogueSha256, providers };
fs.writeFileSync(config.marker + '.writing', JSON.stringify(marker), { flag: 'wx' });
fs.renameSync(config.marker + '.writing', config.marker);
});
ctx.effect(() => off, 'workbench.controlled-ready');
}
`;
export const CONTROLLED_DISABLED_PLUGINS = Object.freeze(['tool-fs', 'tool-working-directory', 'persistent-bash', 'persistent-pwsh',
'terminal-bash', 'terminal-pwsh', 'llm-deepseek', 'llm-retry']);
export const canonicalEngineValue = value => Array.isArray(value) ? value.map(canonicalEngineValue) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalEngineValue(value[key])])) : value;
+182
View File
@@ -0,0 +1,182 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID, timingSafeEqual } from 'node:crypto';
import { DeepSeekAdapter } from './deepseek-adapter.mjs';
import { engineFileIdentity } from './deepseek-installation.mjs';
import { engineError } from '../../shared/contracts/engines.mjs';
import { isId } from '../../shared/contracts/execution.mjs';
import { CONTROLLED_BRIDGE_PLUGIN } from './controlled-plugin.mjs';
import { assertControlledInstallation, controlledDigest, controlledPatch, controlledToolCatalogue, CONTROLLED_ENGINE_SCOPE } from './controlled-installation.mjs';
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
const at = () => new Date().toISOString();
const equalSecret = (left, right) => typeof left === 'string' && Buffer.byteLength(left) === Buffer.byteLength(right)
&& timingSafeEqual(Buffer.from(left), Buffer.from(right));
export class ControlledDeepSeekSession extends DeepSeekAdapter {
constructor(installation, options = {}) {
super(installation, options); this.maximumFrameBytes = options.maximumFrameBytes ?? 4 * 1024 * 1024;
this.pending = new Set(); this.closed = false;
}
async open({ directory, cwd, owner, sdkSessionId, tools, config, signal, onModel, onTool, onState = () => {}, onNotification = () => {} }) {
for (const field of ['sessionId', 'projectId', 'taskId', 'runId', 'jobId']) if (!isId(owner?.[field])) throw engineError('受控引擎所属身份无效。', 400);
if (!isId(sdkSessionId) || typeof onModel !== 'function' || typeof onTool !== 'function') throw engineError('受控引擎回调或会话无效。', 400);
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
const catalogue = controlledToolCatalogue(tools), catalogueSha256 = controlledDigest(catalogue);
this.bridgeController = new AbortController();
const bridgeSignal = signal ? AbortSignal.any([signal, this.bridgeController.signal]) : this.bridgeController.signal;
this.owner = structuredClone(owner); this.sdkSessionId = sdkSessionId; this.signal = bridgeSignal; this.parentSignal = signal;
this.catalogueNames = new Set(catalogue.map(tool => tool.name)); this.callIds = new Set();
this.catalogueSha256 = catalogueSha256; this.config = structuredClone(config);
this.report = { schemaVersion: 1, scope: CONTROLLED_ENGINE_SCOPE, owner: this.owner, sdkSessionId,
installationSha256: this.installation.controlledSha256, startedAt: at(), responses: [], notifications: [], unownedNotifications: [],
rejectedServerRequests: [], bridgeRequests: [], cleanup: null, modelRequests: 0, toolRequests: 0 };
fs.mkdirSync(directory, { recursive: false });
const home = path.join(directory, 'home'), agents = path.join(directory, 'agents');
fs.mkdirSync(home); fs.mkdirSync(agents);
const nonce = randomUUID(), marker = path.join(directory, 'ready.json'), plugin = path.join(directory, 'bridge.mjs'), patch = path.join(directory, 'bridge.patch.json');
const authentication = 'Bearer ' + nonce;
this.guard = http.createServer((request, response) => {
const operation = this.handleBridge(request, response, { authentication, onModel, onTool, signal: bridgeSignal }).catch(error => {
if (!response.destroyed && !response.writableEnded) { response.writeHead(error.status ?? 409, { 'Content-Type': 'application/json', Connection: 'close' }); response.end(JSON.stringify({ error: error.message })); }
});
this.pending.add(operation); operation.finally(() => this.pending.delete(operation));
});
await new Promise((resolve, reject) => { this.guard.once('error', reject); this.guard.listen(0, '127.0.0.1', resolve); });
const pluginConfig = { owner: this.owner, sdkSessionId, tools: catalogue, catalogueSha256, nonce, marker,
llmModule: this.installation.llmModule, endpoint: 'http://127.0.0.1:' + this.guard.address().port,
maximumFrameBytes: this.maximumFrameBytes, model: config.model, maxOutputTokens: config.maxOutputTokens, contextLimit: config.contextLimit };
fs.writeFileSync(plugin, CONTROLLED_BRIDGE_PLUGIN, { flag: 'wx' }); fs.writeFileSync(patch, JSON.stringify(controlledPatch(plugin, pluginConfig)), { flag: 'wx' });
this.report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), cwd: fs.realpathSync.native(cwd),
disabledPlugins: this.installation.disabledPlugins, catalogue, catalogueSha256 };
const env = {};
for (const name of Object.keys(process.env)) if (allowedEnvironment.test(name)) env[name] = process.env[name];
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true' });
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
this.client = this.clientFactory({ executable: this.installation.node.path,
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
{ timeoutMs: this.timeoutMs, maximumFrameBytes: this.maximumFrameBytes, cancellationMethod: null });
this.report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-run' };
onState('starting', this.report.process);
this.client.on('server-request', request => {
this.report.rejectedServerRequests.push({ id: request.id, method: request.method, parametersSha256: controlledDigest(request.params ?? {}) });
this.client.fail(engineError('原SDK反向请求未在受控契约中开放。'));
});
let notificationBytes = 0;
this.client.on('notification', value => {
notificationBytes += Buffer.byteLength(JSON.stringify(value));
if (notificationBytes > 16 * 1024 * 1024 || this.report.notifications.length + this.report.unownedNotifications.length >= 8192) {
this.client.fail(engineError('受控引擎事件超过接收范围。')); return;
}
if (!['session.event', 'session.status', 'subagent.started', 'subagent.finished'].includes(value.method)) {
this.client.fail(engineError('受控引擎返回未支持的通知。')); return;
}
if (value.params?.sessionId !== sdkSessionId) { this.report.unownedNotifications.push(value); return; }
this.report.notifications.push(value);
try { onNotification(value); } catch (error) { this.client.fail(error); }
});
this.report.readiness = await this.waitReady(marker, nonce, signal);
const ready = this.report.readiness;
if (controlledDigest(ready.owner) !== controlledDigest(this.owner) || ready.sdkSessionId !== sdkSessionId
|| ready.catalogueSha256 !== catalogueSha256 || controlledDigest(ready.catalogue) !== catalogueSha256
|| JSON.stringify(ready.providers) !== JSON.stringify(['agent-workbench'])) throw engineError('启动后工具、模型或Run目录不符合封存契约。');
this.verifyLaunch(); onState('initializing', { readiness: ready });
const initialized = await this.request('initialize', { cwd, provider: 'agent-workbench', model: config.model, maxTokens: config.maxOutputTokens });
if (controlledDigest(initialized.serverInfo) !== controlledDigest(this.installation.serverInfo)) throw engineError('受控SDK返回身份不符合固定发行。');
const working = await this.request('session/working-directory/get', { sessionId: sdkSessionId });
if (fs.realpathSync.native(working.cwd) !== fs.realpathSync.native(cwd)) throw engineError('原SDK工作目录不属于所封存的工作区。');
onState('ready', { serverInfo: initialized.serverInfo }); return this.report;
}
verifyLaunch() {
assertControlledInstallation(this.installation);
for (const input of [this.report.launchInputs.plugin, this.report.launchInputs.patch]) {
if (engineFileIdentity(input.path).sha256 !== input.sha256) throw engineError('所属叠加插件或启动输入发生变化。');
}
}
async handleBridge(request, response, { authentication, onModel, onTool, signal }) {
if (this.closed || signal?.aborted || request.method !== 'POST' || !['/model', '/tool'].includes(request.url)
|| request.headers.origin !== undefined || request.headers['content-type'] !== 'application/json'
|| !equalSecret(request.headers.authorization, authentication)) throw engineError('桥请求不属于当前受控Run。', 403);
const chunks = []; let size = 0;
for await (const chunk of request) { size += chunk.length; if (size > this.maximumFrameBytes) throw engineError('桥请求超过输入范围。', 413); chunks.push(chunk); }
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (Object.keys(body).some(key => !['owner', 'sessionId', 'pid', 'data'].includes(key)) || body.pid !== this.client?.pid
|| body.sessionId !== this.sdkSessionId || controlledDigest(body.owner) !== controlledDigest(this.owner)) throw engineError('桥请求的进程或任务归属不一致。', 403);
signal?.throwIfAborted(); this.verifyLaunch();
const data = body.data;
if (!data || typeof data !== 'object' || Array.isArray(data)) throw engineError('桥调用正文必须是对象。', 400);
if (request.url === '/tool') {
if (Object.keys(data).some(key => !['callId', 'name', 'arguments'].includes(key))
|| typeof data.callId !== 'string' || !data.callId || data.callId.length > 160 || !this.catalogueNames.has(data.name)
|| !data.arguments || typeof data.arguments !== 'object' || Array.isArray(data.arguments)) throw engineError('工具调用不符合原目录和参数契约。', 400);
if (this.callIds.has(data.callId)) throw engineError('原引擎工具调用ID已接收,不会重复执行。');
this.callIds.add(data.callId);
} else if (Object.keys(data).some(key => !['messages', 'system', 'tools', 'toolHistory', 'model', 'maxTokens'].includes(key))
|| data.model !== this.config.model || !Array.isArray(data.messages) || !Array.isArray(data.tools)
|| controlledDigest(controlledToolCatalogue(data.tools)) !== this.catalogueSha256
|| !Number.isSafeInteger(data.maxTokens) || data.maxTokens < 1 || data.maxTokens > this.config.maxOutputTokens) {
throw engineError('原引擎模型请求与封存的目录、模型或输出预算不一致。', 400);
}
const trace = { id: randomUUID(), route: request.url, requestSha256: controlledDigest(body), requestBytes: size, data: body.data, status: 'received', startedAt: at() };
if (this.report.bridgeRequests.length >= 1024) throw engineError('桥请求次数超过接收范围。');
this.report.bridgeRequests.push(trace);
const callback = request.url === '/model' ? onModel : onTool;
if (request.url === '/model') this.report.modelRequests++; else this.report.toolRequests++;
try {
const result = await callback(body.data, trace, signal);
trace.resultSha256 = controlledDigest(result); trace.status = 'completed'; trace.finishedAt = at();
if (this.closed || signal?.aborted) throw engineError('所属引擎已停止,迟到原结果只保留记录。');
response.writeHead(200, { 'Content-Type': 'application/json', Connection: 'close' }); response.end(JSON.stringify(result));
} catch (error) { trace.status = 'failed'; trace.error = error.message; trace.finishedAt = at(); throw error; }
}
async request(method, params = {}) {
this.signal?.throwIfAborted(); this.verifyLaunch();
const result = await this.client.request(method, params, { signal: this.signal,
...(method === 'session/wait' ? { timeoutMs: this.config.maxRunDurationMs ?? 600000 } : {}) });
this.report.responses.push({ method, params, result, trace: structuredClone(this.client.trace.at(-1)) }); return result;
}
async prompt(content) {
if (typeof content !== 'string' || !content || Buffer.byteLength(content) > this.maximumFrameBytes / 2) throw engineError('受控引擎任务输入超出范围。', 400);
const receipt = await this.request('session/prompt', { sessionId: this.sdkSessionId, contentBlocks: [{ type: 'text', text: content }] });
if (typeof receipt.messageId !== 'string' || !receipt.messageId) throw engineError('SDK没有返回原入队收据。');
this.report.receipt = receipt; return receipt;
}
async wait() {
const result = await this.request('session/wait', { sessionId: this.sdkSessionId });
if (!result || Array.isArray(result) || Object.keys(result).length) throw engineError('SDK等待结果不符合原协议。');
const events = this.report.notifications.filter(value => value.method === 'session.event').map(value => value.params.event);
const receipt = events.findIndex(event => event?.type === 'agent/inbox/spliced'
&& event.data?.inserted?.some(value => value.id === this.report.receipt?.messageId));
if (receipt < 0) throw engineError('未观察到所属prompt收据,不能采纳引擎输出。');
const activity = events.slice(receipt), assistant = activity.findLast(event => event?.type === 'assistant/message');
if (!assistant || !Array.isArray(assistant.data?.message?.content)) throw engineError('所属活动没有完整assistant原消息。');
const ends = activity.filter(event => event?.type === 'turn/end');
this.report.activity = { receiptIndex: receipt, endEvents: ends };
this.report.finalText = assistant.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('');
return this.report.finalText;
}
async close({ force = false } = {}) {
if (this.closePromise) return this.closePromise;
const interrupted = force || this.parentSignal?.aborted === true;
this.closed = true;
this.bridgeController?.abort(new Error('所属引擎正在关闭。'));
return this.closePromise = (async () => {
let failure = null;
if (this.client) {
if (!interrupted && !this.client.exited) {
try { await this.client.request('shutdown', {}, { timeoutMs: 1000 }); } catch (error) { failure = error; }
}
try { this.report.cleanup = await this.client.close({ force: interrupted || !!failure }); } catch (error) { failure ??= error; }
this.report.trace = this.client.trace; this.report.stderr = this.client.stderr;
}
if (this.guard) { this.guard.closeAllConnections(); await new Promise(resolve => this.guard.close(resolve)); }
await Promise.allSettled([...this.pending]);
if (!interrupted && this.report.launchInputs) { try { this.verifyLaunch(); } catch (error) { failure ??= error; } }
if (!interrupted && this.report.cleanup?.exit?.code !== 0) failure ??= engineError('所属引擎未正常退出。');
this.report.finishedAt = at(); this.report.status = failure || !this.report.cleanup?.rootExited ? 'unknown' : interrupted ? 'cancelled' : 'closed';
if (failure) this.report.error = failure.message;
return this.report;
})();
}
}
+13
View File
@@ -1,5 +1,18 @@
# Agent Workbench:核心代理能力研究与产品计划
## 2026-10-31 当前任务:1.14 受控外部引擎与增强策略
用户授权进入下一阶段全量开发并及时回顾。接续60b63bc/正式1.13.0,开发使用新分支feat/controlled-engines-1.14;当前正式PID23172、Provider、连接与全部历史保持。沿用PLAN-1.14的六切片和本地Git,不读取真实Key、不发送真实/付费模型请求、不主动委派助手子代理。
1. [complete] A:新受控安装身份固定原SDK/CLI/Node及七份关键运行器,独立profile叠加禁用原生项目/终端/模型/重试插件。7/7边界专项和实际Harness+本地固定模型2请求/1工具、prompt收据/原活动/wait/正常退出通过;完整原输入和日志封存。原SDK缺失单会话取消/反向审批/安全恢复如实保留,尚不计工程交付。
2. [in_progress] B:受限桥已核对完整schema、原进程/Run/SDK/来源、输入上限和重复ID;继续将项目读取、提案与检查交回自有Task/Run审批和执行账本。来源或目录变化使旧权限失效。
3. [pending] C:独立工程执行、累计预算、原输出/账本、所属进程停止、未知结果核对与父成果审查;自有Provider夹具和真实Node/React/Python工具链分别验收。
4. [pending] D:恢复与桌面/390px界面,展示原安装身份、范围、事件、审批、原结果/差异/报告;完善1.13窄屏标题栏,每个状态按所属Run核对。
5. [pending] E:分别核对Purge 1.1.78/1.1.81来源、兼容性、启停和生效点,建立同题/同预算对照与指标;本地夹具与真实模型收益分开记录,未经重复验证不默认启用。
6. [pending] F:按最终固定代码/基准完成相关与完整回归、真实工程/UI、独立源码/便携、发行与保留状态升级;各切片保存原失败、回顾和本地commit。
初步核对:原SDK没有session/cancel,prompt只给入队收据,client/server反向请求审批未实现;sdk-minimal仍包含本机文件/终端工具及danger-full-access策略,不能直接赋予工程写入。本阶段通过自有版本化叠加插件与受限宿主桥接入,实际工具目录和所属账本是验收门槛。完整公开源码使用普通代码工具;需要发行资源与运行观察时复用REA。
## 2026-10-31 当前任务:1.13 隔离执行与两个受限worker
用户授权的1.13隔离协作阶段已完成,最终证据及Git索引严格核对通过,本次本地提交封存全部收尾。基线f0fcefd/1.12.1保留;feat/isolated-workers-1.13上的实现、独立验收与新不可变发行已正式交付,原PID23172/Provider、模型中心及最新全部历史保持。未普通重启、读取/复制Key或发送真实模型请求;各切片的原失败、检查、回顾与本地Git记录保留。
+109
View File
@@ -0,0 +1,109 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import { fixture } from './helpers.mjs';
import { createEngineFixture } from '../scripts/engine-fixtures.mjs';
import { CONTROLLED_CRITICAL_FILES, resolveControlledInstallation, assertControlledInstallation,
controlledToolCatalogue, controlledDigest, controlledPatch } from '../src/core/engines/controlled-installation.mjs';
import { CONTROLLED_DISABLED_PLUGINS } from '../src/core/engines/controlled-plugin.mjs';
import { ControlledDeepSeekSession } from '../src/core/engines/controlled-session.mjs';
const tools = [{ name: 'read_file', description: 'Read the owned project file.', parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } }];
function installation(t) {
const f = fixture(t), root = createEngineFixture(path.join(f.root, 'harness'));
for (const file of CONTROLLED_CRITICAL_FILES) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.writeFileSync(path.join(root, file), 'export const fixture = true;\n');
}
return { ...f, root, installation: resolveControlledInstallation(f.root, root) };
}
test('controlled installation pins the native kernel and bridge independently of the existing connection-probe identity', t => {
const f = installation(t), original = f.installation;
assert.equal(original.controlledStatus, 'available'); assert.equal(original.controlledInputs.length, CONTROLLED_CRITICAL_FILES.length);
assert.equal(original.controlledCapabilities.nativeModelCredentials, false);
assert.equal(original.controlledCapabilities.singleSessionCancel, false);
fs.appendFileSync(path.join(f.root, CONTROLLED_CRITICAL_FILES[0]), '// changed runtime\n');
const current = resolveControlledInstallation(f.root, f.root);
assert.equal(current.identitySha256, original.identitySha256); assert.notEqual(current.controlledSha256, original.controlledSha256);
assert.throws(() => assertControlledInstallation(original), /工具内核或叠加插件已变化/);
});
test('controlled profiles disable every native project/terminal provider and native model/retry route using the actual include patch contract', () => {
const patch = controlledPatch('owned-plugin.mjs', { fixture: true });
assert.deepEqual(patch.slice(0, -1), CONTROLLED_DISABLED_PLUGINS.map(id => ({ id, disabled: true })));
assert.deepEqual(patch.at(-1).insert[0], { id: 'agent-workbench-controlled-bridge', name: 'owned-plugin.mjs', config: { fixture: true } });
assert.ok(CONTROLLED_DISABLED_PLUGINS.includes('persistent-pwsh')); assert.ok(CONTROLLED_DISABLED_PLUGINS.includes('tool-fs'));
});
test('owned tool catalogues seal full schemas canonically and reject duplicate or malformed declarations', () => {
assert.equal(controlledDigest(controlledToolCatalogue(tools)), controlledDigest(controlledToolCatalogue([{ function: tools[0] }])));
assert.throws(() => controlledToolCatalogue([...tools, tools[0]]), /重复/);
assert.throws(() => controlledToolCatalogue([{ ...tools[0], parameters: { type: 'array' } }]), /格式无效/);
});
async function bridge(t, { onTool = async () => ({ observed: true }), onModel = async () => ({ observed: true }), maximumFrameBytes = 4096 } = {}) {
const f = installation(t), driver = new ControlledDeepSeekSession(f.installation, { maximumFrameBytes });
const owner = Object.fromEntries(['sessionId', 'projectId', 'taskId', 'runId', 'jobId'].map(key => [key, randomUUID()]));
driver.owner = owner; driver.sdkSessionId = randomUUID(); driver.client = { pid: 11717 };
driver.catalogueNames = new Set(['read_file']); driver.callIds = new Set(); driver.catalogueSha256 = controlledDigest(tools);
driver.config = { model: 'fixture-model', maxOutputTokens: 512 }; driver.verifyLaunch = () => {};
driver.report = { bridgeRequests: [], modelRequests: 0, toolRequests: 0 };
const controller = new AbortController(), authentication = 'Bearer owned-test-token';
const server = http.createServer((request, response) => {
driver.handleBridge(request, response, { authentication, onTool, onModel, signal: controller.signal }).catch(error => {
response.writeHead(error.status ?? 409, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: error.message }));
});
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
f.onCleanup(() => new Promise(resolve => { controller.abort(); server.closeAllConnections(); server.close(resolve); }));
const post = (route, data, overrides = {}) => fetch('http://127.0.0.1:' + server.address().port + route, {
method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: authentication, ...overrides.headers },
body: JSON.stringify({ owner, sessionId: driver.sdkSessionId, pid: driver.client.pid, data, ...overrides.body }),
});
return { driver, post, owner, controller };
}
test('bridge authentication, current Run, process, SDK session and browser-origin checks reject before dispatch', async t => {
let calls = 0; const b = await bridge(t, { onTool: async () => { calls++; return {}; } });
const data = { callId: 'owned-call', name: 'read_file', arguments: { path: 'README.md' } };
for (const overrides of [{ headers: { Authorization: 'Bearer foreign' } }, { headers: { Origin: 'http://example.invalid' } },
{ body: { owner: { ...b.owner, runId: randomUUID() } } }, { body: { sessionId: randomUUID() } }, { body: { pid: 31313 } }]) {
assert.equal((await b.post('/tool', data, overrides)).status, 403);
}
assert.equal(calls, 0); assert.equal(b.driver.report.toolRequests, 0);
});
test('bridge duplicates, unknown tools, malformed arguments and source changes are refused before a second side effect', async t => {
let calls = 0; const b = await bridge(t, { onTool: async () => { calls++; return { read: true }; } });
const data = { callId: 'call-1', name: 'read_file', arguments: { path: 'README.md' } };
assert.equal((await b.post('/tool', data)).status, 200);
assert.equal((await b.post('/tool', data)).status, 409);
assert.equal((await b.post('/tool', { ...data, callId: 'call-2', name: 'pwsh' })).status, 400);
assert.equal((await b.post('/tool', { ...data, callId: 'call-3', arguments: [] })).status, 400);
b.driver.verifyLaunch = () => { throw Object.assign(new Error('source changed'), { status: 409 }); };
assert.equal((await b.post('/tool', { ...data, callId: 'call-4' })).status, 409);
assert.equal(calls, 1); assert.equal(b.driver.report.bridgeRequests.length, 1);
});
test('bridge model requests bind the exact catalogue, route and output bound and preserve raw request/result identity', async t => {
let calls = 0; const b = await bridge(t, { onModel: async () => { calls++; return { message: { role: 'assistant', content: 'owned' } }; } });
const data = { messages: [], system: null, tools, toolHistory: null, model: 'fixture-model', maxTokens: 256 };
assert.equal((await b.post('/model', { ...data, maxTokens: 513 })).status, 400);
assert.equal((await b.post('/model', { ...data, model: 'other' })).status, 400);
assert.equal((await b.post('/model', { ...data, tools: [{ ...tools[0], description: 'changed' }] })).status, 400);
const response = await b.post('/model', data); assert.equal(response.status, 200);
assert.equal(calls, 1); assert.equal(b.driver.report.modelRequests, 1);
const trace = b.driver.report.bridgeRequests[0]; assert.equal(trace.status, 'completed');
assert.equal(trace.resultSha256, controlledDigest(await response.json())); assert.deepEqual(trace.data, data);
});
test('stopped and oversized bridge requests never reach a local model or tool callback', async t => {
let calls = 0; const b = await bridge(t, { maximumFrameBytes: 512, onTool: async () => { calls++; return {}; } });
const data = { callId: 'large', name: 'read_file', arguments: { path: 'x'.repeat(1000) } };
assert.equal((await b.post('/tool', data)).status, 413);
b.controller.abort(); assert.equal((await b.post('/tool', { ...data, arguments: {} })).status, 403);
assert.equal(calls, 0);
});