fix: complete unrestricted waits catalog and network flows
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
# Agent Workbench项目执行规范
|
||||
|
||||
1.25.5最终补漏已合回并验证:build-16、相关72/72、worker停止/未发请求/超额四边界4/4、网页10组与实际Electron11组均通过;新等待0不限及长时限、开放目录122选择/121自动成员、4MB以上原目录、完整网络历史/DNS、20 Chat工具/129 Messages块已核对。976项完整源码原轮958通过18失败保持,低负载精确补验与失败根因见QA,不冒称原轮全绿。现在冻结实现准备独立不可变发行/ZIP重建/实际安装,随后正式升级、保存full/open并实际重启;正式仍1.25.4,不能称已部署。真实供应商请求0;旧网络/重复读取/真实自主交付/预留边界/Purge未知保持。不委派/推送/触真实Key、不续跑用户项目。
|
||||
|
||||
当前接续1.25.5默认透传/三操作权限/自动Git与回滚。用户最新要求覆盖下方历史固定额度、每项审查和不重启默认:新安装不设本地上下文/输出/累计/轮数/等待额度,首次ask,用户选择持久保存;正式用户偏好full,已授权实际重启。权限45/45、网页7组/实际Electron8组与扩大回归补验已过;最新实际原生SDK4组/6本机模型请求、33文件大于2MB无检查worker自动父合并、多图9张及同Task续接第10张补验通过,首失败/中断全部保留。当前完成新UI复核后冻结本地实现,完整源码/不可变发行/安装/正式升级重启仍待完成,不能称已部署。正式仍1.25.4;不委派/推送,不读取/复制/解密/重存真实Key。重启会丢失未持久保存的内存Key,只公开核对hasKey。自主交付/网络间歇/普遍重复读取/真实预留边界/Purge收益未知保持,不续跑历史或用户原项目。见docs/QA-OPEN-PERMISSIONS-1.25.5.md。
|
||||
|
||||
1.25.5补验发现并修复混合池和16K小源码正文丢失:共同输入按成员自身context/output配对,累计仍预留最大输出;仅包装超预算时用latest反馈v4保留完整小读取原文,常规v3和旧历史投影不改。原16K/2048/90000两响应回放最终11998/12352保留三源码/目标/六工具事实,分页按1536状态增长预留和真实字节核算,短分页不再当完整小文件优先保留;四关键边界4/4、池原证据2/2通过,不靠放宽预算。相关回归与独立发行仍在进行。用户已在模型中心补好三条Key,仅公开hasKey核对,当前选择legacy-default保持;正式仍1.25.4/PID55352/instance029df044,后续升级保留这个新Provider。首全量中断、两轮修复回归失败和不完整候选都保留;真实推理0,自主交付/网络/重复读取/真实预留/Purge未知保持,不续跑原项目、不委派/推送、不触Key。
|
||||
|
||||
@@ -71,3 +71,19 @@
|
||||
完整源码第2轮在修改产品源码前主动取消:169顶层通过标记、无断言失败,结束时两个正在运行的测试文件被取消进程产生✖文件标记,不是已完成整轮。open-full-source-2-cancellation.json保存所属PID/创建时间/树;初次取消驱动空子列表循环也保留,已停止该驱动后用有界遍历只终止所属3个测试进程,未停止正式机。重新冻结后跑第3轮。
|
||||
|
||||
实际安装验收增加新权限/多图网页8组与Electron9组,既有界面检查继续保留。正式仍未升级。
|
||||
|
||||
## 最终完整回归与实际补漏
|
||||
|
||||
完整源码第3轮实际来源c93c4348:976项958通过18失败、0取消/跳过,耗时约63分钟。原`.qa/open-full-source-3.log`与receipt保持,不能将后续补验倒写成原轮全绿。
|
||||
|
||||
18项包含:历史engine owner缺model;混合协议池与截断恢复的等待;运行设置和0不限的过时断言;6项网络诊断0期限被当成立即超时;4项旧输出上限诊断文案;完整前缀测试仍用默认透传断言有限窗口;HTTP evaluations等待;worker旧夹具发送前预算不足。最后两项单独低负载诊断保留在`open-idle-failures-diagnostic-1.log`:评测原20秒等待16.7秒内通过,worker继续失败。
|
||||
|
||||
worker补充诊断`open-worker-accounting-diagnostic.json`证实2个子任务均在token_limit发送前停止,0请求/0用量,没有漏记计费。旧每子10,000额度已容纳不下增长后的完整工具契约。测试改为每子20,000、真实夹具响应20,001,保留超额1 token、0工具/改动、续接不重置断言,并新增必须发出2请求;独立副本1/1通过。此处只修显式restricted测试,不恢复默认额度。
|
||||
|
||||
独立副本27文件按主源码before SHA合回,清单`.qa/open-final-draft-merged.json`逐项保存实际after SHA。补漏包括:0等待不设timer、长等待分段避免Node溢出;开放网络完整DNS/历史与主动取消;开放GET等待和目录策略继承;4MB以上目录、长型号、95参数、121自动成员及小容量声明;Chat20完整工具、Messages129内容块;旧engine owner继续核对原有限契约。旧非法索引、格式完整性、取消和来源检查保持。4项实际本机边界通过,所有真实供应商请求仍为0。
|
||||
|
||||
主源码build-16及8文件相关回归72/72通过。最终网页10组通过(`open-web-f34d2c8c-9d43-43bb-95d3-b0dc6f1dc453`),包含等待0及旧上限外设置保存刷新、122目录选择/自动适配、真实TCP不限诊断、三权限持久化/在途切换、原错误下载、自动写入/回滚和9图。1440权限与390诊断截图已实际回看,窄屏无页面横向溢出。首副本Electron因依赖junction越出所属目录被正确拒绝,改在主依赖/正式候选上验收,未放宽产品路径核验。
|
||||
|
||||
主源码最终实际Electron11组全部通过(`open-electron-e7cb1fe9-2c1e-4b36-a0d4-b7b7211f1073`),含完整长DOM/133控件、密码/select输入及跨来源导航,不需要手动批准;原生回看第二来源及390目录122已选截图。网页7/Electron13次均为自有本机HTTP模型夹具请求,未使用真实Key。worker停止后迟到用量、请求中断未知、发送前超时0用量及真实超额响应记账四边界4/4通过,`open-final-worker-boundaries-1.log`。
|
||||
|
||||
本阶段回顾:第三遍行为复核揭示0值在定时器/诊断/前端的跨层含义未完全同步,已按实际调用链修复并验证。旧测试只有在仍检验原有事实时才更正默认/文案与容量;worker补充必须真实派发的断言,避免将发送前停止误作记账证明。未改写976项原失败或历史16K/2048数据。下一不可变发行与真实安装,不继续扩大功能范围。
|
||||
|
||||
@@ -1270,6 +1270,12 @@ V调用前检查:新增11文件SHA断言首语法检查发现多一个右括
|
||||
|
||||
## 开放权限:跨层null语义与真实完成状态
|
||||
|
||||
最终976项回归原轮958通过18失败,完整终态保留。低负载补验HTTP evaluations在16.7秒通过,原20秒等待未放宽。worker原10,000/子额度在发送前token_limit、0个context_plan、两个worker0请求0用量,明确不是漏记计费;测试改为20,000/子且响应20,001,保留超额1 token、无工具/改动、续接不重置等断言,新增必须真的发出2请求,独立副本通过。此调整只涉及显式restricted历史测试,不恢复默认额度。
|
||||
|
||||
主源码网页10组全部通过(open-web-f34d2c8c):实际回看1440权限与390连接诊断截图。权限位于输入框上方并自动保存,三栏原工作台品牌保持;窄屏诊断表按列换行、无页面横向溢出,0期限显示不限、IPv6缺失明确未检查。目录122选项/自动适配及真实TCP无模型检查、原错误下载、自动文件落地与回滚、多图流程均有原收据;本轮网页7个本机模型夹具请求、2目录GET、0真实供应商请求。
|
||||
|
||||
独立副本的27份明确修复已按主c93c4348原SHA逐项核对后合回;没有复制副本依赖junction、构建或历史原件。主源码build-16通过,最终相关补验与网页10/Electron11路径进行中。用户附件为三权限选择示例,已核对ask/auto/full文字及持久使用要求;原生专用鼠标键盘工具未新增,不夸大电脑控制覆盖。
|
||||
|
||||
原生SDK要求正整数defaultMaxTokens,需使用内部规划哨兵并在桥/HTTP省略输出上限;任何有限输入比较必须先判断inputBudget非null。父合并不能在自动应用前暴露最终merge_prepared,否则客户端会把半途状态当完成。多图的数量策略在上传/选择/Store绑定三个入口各有独立校验,需要一起修复;同Task续接须追加原附件ID而非替换。浏览器读取不增加文件页覆盖,不能机械扣源文件页状态预留。以上均由实际失败定位并保留。
|
||||
|
||||
## 续接策略必须覆盖当前Task的后续额度
|
||||
|
||||
@@ -1901,3 +1901,11 @@ Y阶段结束:预检110tokens通过;Node8请求64500tokens全部matched,
|
||||
## 旧Task续接的额度遗留修正
|
||||
|
||||
2fa22073提交后第三遍检查复现:开放新Run仍被旧Task累计额度阻止。新Run采用当前开放策略时只更新后续Task额度为0,旧Run和原消费保持,实际本机HTTP专项通过。原完整源码第2轮因修改前取消保留169通过与两个终止文件标记,不作整轮通过。网页8/Electron9最终通过并回看;4轮SDK645份21197319字节全保留。增加安装副本的8/9权限检查,下一重建/提交后完整源码第3轮。
|
||||
|
||||
## 开放权限最终补漏与发行接续
|
||||
|
||||
完整源码第3轮实际来源c93c4348,976项958通过18失败、0取消/跳过,原日志与收据保持。独立修复副本open-final-draft-1补齐等待0不限、长时限分段定时器、网络诊断0不限/完整历史、目录策略继承与大目录、工具流数量、旧engine owner兼容;4项实际本机边界通过,网页10组通过,Electron副本因依赖junction超出所属目录拒绝,必须合回后用真实主依赖验收,不放宽路径核验。
|
||||
|
||||
低负载精确诊断97770已结束:HTTP evaluations通过;worker累计预算测试仍失败。新增不改主源码的只读诊断确认两个worker均0请求/0用量,不能记作账本漏记,继续定位发送前停止原因。原失败、旧不完整候选和主动取消收据均保留;正式仍1.25.4,尚无升级/重启或真实供应商请求。
|
||||
|
||||
最终主源码build-16、相关72/72、worker四边界4/4、网页10组和实际Electron11组全部通过并回看。worker旧10,000/子不足发送,改20,000/子、20,001实际回执继续检验超额1 token且无副作用,新增实际两请求断言。27修复文件按before SHA合回、diff逐项回顾;准备本地提交冻结,另制不可变候选。上一次工具只读工作目录少字被拒绝,已用真实目录更正,没有产品或正式写入。
|
||||
|
||||
@@ -15,6 +15,7 @@ async function until(predicate, timeout = 20000) {
|
||||
}
|
||||
|
||||
export async function verifyBrowserApi({ api, url, token, directory, appRoot, contained = false }) {
|
||||
const open = (await api('/bootstrap')).config.executionMode === 'unrestricted';
|
||||
const projectRoot = path.join(directory, 'browser-project'); fs.mkdirSync(path.join(projectRoot, 'dist'), { recursive: true });
|
||||
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned portable browser acceptance\n');
|
||||
fs.writeFileSync(path.join(projectRoot, 'dist', 'index.html'), '<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>随包页面验收</title>'
|
||||
@@ -27,8 +28,12 @@ export async function verifyBrowserApi({ api, url, token, directory, appRoot, co
|
||||
await until(async () => { current = await api(route); return current.status === 'awaiting_approval'; });
|
||||
const approval = current.approvals.find(value => value.status === 'pending'); assert.equal(approval.command, 'node --version');
|
||||
await api(route + '/approvals/' + approval.id, { allow: true });
|
||||
await until(async () => { current = await api(route); return current.status === 'needs_review'; });
|
||||
await until(async () => { current = await api(route); return current.status === (open ? 'completed' : 'needs_review'); });
|
||||
for (const change of current.changes.filter(value => value.status === 'pending')) await api(route + '/changes/' + change.id + '/reject', {});
|
||||
if (open) {
|
||||
assert.ok(current.changes.some(value => value.status === 'applied'));
|
||||
for (const change of current.changes.filter(value => value.status === 'applied')) await api(route + '/changes/' + change.id + '/rollback', {});
|
||||
}
|
||||
const taskId = (await api(route)).execution.task.id, availability = (await api(route + '/browser')).availability;
|
||||
assert.equal(availability.status, 'available', availability.message); assert.equal(availability.playwrightVersion, '1.64.1');
|
||||
const steps = [{ action: 'fill', selector: '#query', value: '本地页面验收' }, { action: 'select', selector: '#filter', value: 'pending' },
|
||||
|
||||
@@ -158,7 +158,7 @@ try {
|
||||
...(['1.24.9', '1.25.0', '1.25.1', '1.25.2', '1.25.3', '1.25.5'].includes(version) ? [['verify-requirements-ui.mjs', [], 7], ['verify-requirements-desktop.mjs', [], 3], ['verify-turn-progress-ui.mjs', [], 9], ['verify-turn-progress-ui.mjs', ['--desktop'], 9]] : []),
|
||||
...(['1.25.0', '1.25.1', '1.25.2', '1.25.3', '1.25.5'].includes(version) ? [['verify-task-agreement-ui.mjs', [], 6], ['verify-task-agreement-ui.mjs', ['--desktop'], 6], ['verify-task-follow-up-ui.mjs', [], 5], ['verify-task-follow-up-ui.mjs', ['--desktop'], 5]] : []),
|
||||
...(['1.25.3', '1.25.5'].includes(version) ? [['verify-reasoning-settings-ui.mjs', [], 6], ['verify-reasoning-settings-ui.mjs', ['--desktop'], 6], ['verify-model-catalog-ui.mjs', [], 8], ['verify-model-catalog-ui.mjs', ['--desktop'], 8]] : []),
|
||||
...(version === '1.25.5' ? [['verify-model-capacity-ui.mjs', [], 3], ['verify-model-capacity-ui.mjs', ['--desktop'], 3], ['verify-unrestricted-ui.mjs', [], 8], ['verify-unrestricted-ui.mjs', ['--desktop'], 9]] : []),
|
||||
...(version === '1.25.5' ? [['verify-model-capacity-ui.mjs', [], 3], ['verify-model-capacity-ui.mjs', ['--desktop'], 3], ['verify-unrestricted-ui.mjs', [], 10], ['verify-unrestricted-ui.mjs', ['--desktop'], 11]] : []),
|
||||
];
|
||||
for (const [script, args, expected] of suites) {
|
||||
const output = await run(process.execPath, [path.join(appRoot, 'scripts', script), ...args], { cwd: appRoot,
|
||||
|
||||
@@ -100,7 +100,7 @@ try {
|
||||
let current;
|
||||
await until(async () => { current = await api('/sessions/' + session.id); return current.status === 'awaiting_approval'; });
|
||||
assert.equal(current.approvals[0].command, 'node --version');
|
||||
assert.equal(fs.existsSync(path.join(example.root, 'WORKBENCH-NOTES.md')), false);
|
||||
assert.equal(fs.existsSync(path.join(example.root, 'WORKBENCH-NOTES.md')), bootstrap.config.executionMode === 'unrestricted');
|
||||
await api('/sessions/' + session.id + '/approvals/' + current.approvals[0].id, { allow: true });
|
||||
await until(async () => { current = await api('/sessions/' + session.id); return current.status === 'completed'; });
|
||||
const command = current.events.find(event => event.tool === 'run_command');
|
||||
|
||||
@@ -55,7 +55,7 @@ try {
|
||||
}
|
||||
return completion([], 'Owned full browser flow complete.');
|
||||
};
|
||||
const model = await compatibleFixture(t, (url, body) => ownedFailure ? { status: 429, body: { error: { code: 'owned_rate', type: 'owned_original', message: 'UI-UPSTREAM-ORIGINAL', detail: '原始上游正文'.repeat(6000) } }, headers: { 'x-request-id': 'owned-ui-error-id' } } : url.endsWith('/models') ? { data: [{ id: 'owned-capacity', context_length: 131072, max_output_tokens: 32768, capabilities: { text: true, tools: true } }] }
|
||||
const model = await compatibleFixture(t, (url, body) => ownedFailure ? { status: 429, body: { error: { code: 'owned_rate', type: 'owned_original', message: 'UI-UPSTREAM-ORIGINAL', detail: '原始上游正文'.repeat(6000) } }, headers: { 'x-request-id': 'owned-ui-error-id' } } : url.endsWith('/models') ? { data: [{ id: 'owned-capacity', context_length: 131072, max_output_tokens: 32768, capabilities: { text: true, tools: true } }, ...Array.from({ length: 121 }, (_, index) => ({ id: 'owned-bulk-' + index, capabilities: { text: true, tools: true } }))] }
|
||||
: body.messages.some(row => row.role === 'user' && row.content.includes('FULL-BROWSER-FLOW')) ? browserReply(body)
|
||||
: body.messages.some(row => row.role === 'user' && row.content.includes('PERMISSION-FLOW')) ? completion(body.messages.some(row => row.role === 'tool') ? [] : [call('owned-permission', 'run_command', { command: process.platform === 'win32' ? 'Write-Output "OWNED-PERMISSION-MARKER"' : 'printf OWNED-PERMISSION-MARKER', reason: 'Verify permission switching in the actual UI.' })], 'Permission flow complete.')
|
||||
: body.messages.some(row => row.role === 'user' && row.content.includes('AUTO-WRITE-FLOW')) ? completion(body.messages.some(row => row.role === 'tool') ? [] : [call('owned-write', 'propose_file', { path: 'ui-auto.txt', content: 'OWNED-APPLIED\n', reason: 'Verify automatic writes and exact rollback.' })], 'File flow complete.')
|
||||
@@ -112,6 +112,50 @@ try {
|
||||
await expect(budgets().getByLabel('额度策略', { exact: true })).toHaveValue('unrestricted');
|
||||
for (const width of [1440,390]) { await resize(width); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); await shot('open-settings-' + width); }
|
||||
mark('open defaults save as real zeros, survive reload, hide local quotas and retain model selection at 1440 and 390 pixels');
|
||||
await resize(1440); await dialog().getByRole('button', { name: '等待时限', exact: true }).click();
|
||||
const waits = () => dialog().getByRole('form', { name: '模型等待时限', exact: true });
|
||||
await expect(waits().getByLabel('单次模型响应上限(秒)', { exact: true })).toHaveValue('0');
|
||||
await expect(waits().getByLabel('流式无数据上限(秒)', { exact: true })).toHaveValue('0');
|
||||
await waits().getByLabel('单次模型响应上限(秒)', { exact: true }).fill('960');
|
||||
await waits().getByLabel('流式无数据上限(秒)', { exact: true }).fill('901');
|
||||
await waits().getByRole('button', { name: '保存等待时限', exact: true }).click();
|
||||
await expect(dialog().getByRole('status').filter({ hasText: '等待时限已保存' })).toBeVisible();
|
||||
await page.reload(); await open(); await dialog().getByRole('button', { name: '等待时限', exact: true }).click();
|
||||
await expect(waits().getByLabel('单次模型响应上限(秒)', { exact: true })).toHaveValue('960');
|
||||
await expect(waits().getByLabel('流式无数据上限(秒)', { exact: true })).toHaveValue('901');
|
||||
for (const label of ['单次模型响应上限(秒)', '流式无数据上限(秒)']) await waits().getByLabel(label, { exact: true }).fill('0');
|
||||
await waits().getByRole('button', { name: '保存等待时限', exact: true }).click();
|
||||
await expect(dialog().getByRole('status').filter({ hasText: '等待时限已保存' })).toBeVisible();
|
||||
assert.deepEqual((await host.api('/model-center')).waitSettings, { modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0 });
|
||||
for (const width of [1440,390]) { await resize(width); await shot('unlimited-waits-' + width); }
|
||||
mark('wait settings accept zero and values beyond old ceilings, persist after reload and restore unlimited waits');
|
||||
await resize(1440); await dialog().getByRole('button', { name: '模型连接', exact: true }).click();
|
||||
await dialog().getByRole('button', { name: '从上游添加模型', exact: true }).click();
|
||||
const catalog = () => dialog().getByRole('region', { name: '上游模型目录', exact: true });
|
||||
await catalog().getByLabel('目录上游连接', { exact: true }).selectOption(source.id);
|
||||
await catalog().getByRole('button', { name: '获取上游模型', exact: true }).click();
|
||||
await expect(catalog().getByLabel('上游模型列表', { exact: true }).getByRole('checkbox')).toHaveCount(122);
|
||||
await catalog().getByRole('button', { name: '选中当前筛选', exact: true }).click();
|
||||
await catalog().getByLabel('模型使用方式', { exact: true }).selectOption('auto');
|
||||
await expect(catalog().getByRole('button', { name: '保存所选 122 个模型', exact: true })).toBeEnabled();
|
||||
await expect(catalog()).toContainText('目录、连接和自动池不设本地数量上限');
|
||||
for (const width of [1440,390]) { await resize(width); await shot('open-model-selection-' + width); }
|
||||
await catalog().getByRole('button', { name: '关闭目录', exact: true }).click();
|
||||
assert.deepEqual((await host.api('/model-center')).selected, originalSelection);
|
||||
await dialog().getByRole('navigation', { name: '模型中心分类', exact: true }).getByRole('button', { name: '连接诊断', exact: true }).click();
|
||||
const network = () => dialog().getByRole('region', { name: '模型连接诊断', exact: true });
|
||||
await network().getByLabel('诊断连接', { exact: true }).selectOption(source.id);
|
||||
await network().getByRole('button', { name: '开始直连检查', exact: true }).click();
|
||||
await expect(network().getByRole('status')).toHaveText('直连握手通过');
|
||||
await expect(network()).toContainText('保留全部检查记录');
|
||||
await network().locator('details summary').click();
|
||||
await expect(network().getByText('不限 / 不限', { exact: true })).toBeVisible();
|
||||
const diagnostic = (await host.api('/model-center/network-diagnostics')).jobs[0];
|
||||
assert.equal(diagnostic.status, 'passed'); assert.equal(diagnostic.budgetMs, 0); assert.equal(diagnostic.stageTimeoutMs, 0);
|
||||
assert.equal(diagnostic.httpRequests, 0); assert.equal(diagnostic.modelRequests, 0);
|
||||
for (const width of [1440,390]) { await resize(width); await shot('open-network-diagnostic-' + width); }
|
||||
mark('catalog UI selects 122 models and enables automatic routing; actual TCP diagnostics show unlimited waits and complete history');
|
||||
await resize(1440); await dialog().getByRole('button', { name: '运行预算', exact: true }).click();
|
||||
await budgets().getByLabel('额度策略', { exact: true }).selectOption('restricted');
|
||||
await budgets().getByLabel('容量策略', { exact: true }).selectOption('manual');
|
||||
await budgets().getByLabel('输出上限', { exact: true }).fill('32768');
|
||||
@@ -184,7 +228,7 @@ try {
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal(model.requests.filter(row => row.input).length, desktop ? 13 : 7);
|
||||
result={success:true,version:host.bootstrap.version,appRoot,actualElectron:desktop,checks,screenshots,errors,realModelRequests:0,ownedModelRequests:desktop ? 13 : 7,directoryGets:1,officialServiceTouched:false};
|
||||
result={success:true,version:host.bootstrap.version,appRoot,actualElectron:desktop,checks,screenshots,errors,realModelRequests:0,ownedModelRequests:desktop ? 13 : 7,directoryGets:model.requests.filter(row => !row.input).length,officialServiceTouched:false};
|
||||
} catch(error) {if(page)await shot('failure').catch(()=>{});result={success:false,appRoot,actualElectron:desktop,checks,screenshots,errors,error:error.stack,realModelRequests:0};}
|
||||
finally {if(application)await application.close();if(browser)await browser.close();if(controller&&await controller.health())await controller.stop();await host?.close?.();for(const dispose of disposers.reverse())await dispose();fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify(result,null,2));}
|
||||
console.log(JSON.stringify({directory,...result}));if(!result.success)process.exitCode=1;
|
||||
|
||||
@@ -57,7 +57,9 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
|
||||
finally { if (live.current) setSaving(false); }
|
||||
}
|
||||
const visible = preview?.entries.filter(value => (value.id + ' ' + value.name + ' ' + value.owner).toLowerCase().includes(query.trim().toLowerCase())) ?? [];
|
||||
const selectable = visible.filter(value => value.lifecycle !== 'retired');
|
||||
const open = preview?.limits.connections === null;
|
||||
const selectionLimit = preview?.limits.connections ?? Infinity, poolLimit = preview?.limits.poolMembers ?? Infinity;
|
||||
const selectable = visible.filter(value => open || value.lifecycle !== 'retired');
|
||||
return <section className="mc-editor mc-catalog" aria-label="上游模型目录" ref={region}>
|
||||
<div className="mc-section-title"><div><h3>从上游选择模型</h3><p>获取目录,勾选要用的型号,再决定手动指定或自动适配。</p></div><button className="button secondary" disabled={saving} onClick={onClose}>关闭目录</button></div>
|
||||
<div className="mc-form-grid">
|
||||
@@ -86,11 +88,11 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
|
||||
{preview && <>
|
||||
<div className="mc-catalog-heading"><label>搜索模型<input aria-label="搜索上游模型" value={query} onChange={event => setQuery(event.target.value)} placeholder="型号、显示名称或提供方" /></label><span>显示 {visible.length} / {preview.entries.length} · 已选 {chosen.length}</span></div>
|
||||
{preview.warning && <p className="mc-card-warning">{preview.warning}</p>}
|
||||
<p className="mc-help">以下为上游目录声明,尚未经过模型调用验证。目录最多1000项,本机最多100个模型连接;单个自动池最多32个成员。</p>
|
||||
<div className="mc-row-actions"><button className="button secondary" disabled={locked || !selectable.length || new Set([...chosen, ...selectable.map(value => value.id)]).size > 100} onClick={() => setChosen([...new Set([...chosen, ...selectable.map(value => value.id)])])}>选中当前筛选</button><button className="button secondary" disabled={locked || !chosen.length} onClick={() => setChosen([])}>清空选择</button></div>
|
||||
<p className="mc-help">以下为上游目录声明,尚未经过模型调用验证。{open ? '可选择上游返回的型号,目录、连接和自动池不设本地数量上限。' : `目录最多${preview.limits.catalog}项,本机最多${selectionLimit}个模型连接;单个自动池最多${poolLimit}个成员。`}</p>
|
||||
<div className="mc-row-actions"><button className="button secondary" disabled={locked || !selectable.length || new Set([...chosen, ...selectable.map(value => value.id)]).size > selectionLimit} onClick={() => setChosen([...new Set([...chosen, ...selectable.map(value => value.id)])])}>选中当前筛选</button><button className="button secondary" disabled={locked || !chosen.length} onClick={() => setChosen([])}>清空选择</button></div>
|
||||
<div className="mc-catalog-list" aria-label="上游模型列表">
|
||||
{visible.map(value => <label className={'mc-catalog-model' + (chosen.includes(value.id) ? ' is-selected' : '')} key={value.id}>
|
||||
<input type="checkbox" aria-label={'选择模型 ' + value.id} checked={chosen.includes(value.id)} disabled={locked || value.lifecycle === 'retired' || !chosen.includes(value.id) && chosen.length >= 100} onChange={event => setChosen(event.target.checked ? [...chosen, value.id] : chosen.filter(id => id !== value.id))} />
|
||||
<input type="checkbox" aria-label={'选择模型 ' + value.id} checked={chosen.includes(value.id)} disabled={locked || !open && value.lifecycle === 'retired' || !chosen.includes(value.id) && chosen.length >= selectionLimit} onChange={event => setChosen(event.target.checked ? [...chosen, value.id] : chosen.filter(id => id !== value.id))} />
|
||||
<span><strong>{value.id}</strong>{value.name !== value.id && <span>{value.name}</span>}<small>{[value.owner, value.contextLimit && `上下文 ${value.contextLimit.toLocaleString()} tokens`, value.maxOutputTokens && `输出上限 ${value.maxOutputTokens.toLocaleString()}`, value.lifecycle && value.lifecycle !== 'active' && (value.lifecycle === 'retired' ? '已退役' : '待退役')].filter(Boolean).join(' · ') || '上游未提供详细元数据'}</small>
|
||||
<small>{Object.entries(value.capabilityDeclarations).filter(([, state]) => state !== 'unknown').map(([capability, state]) => `${capabilityNames[capability]}${state === 'supported' ? '支持' : '不支持'}`).join(' · ') || '文本、工具、流式等能力待确认'}{value.efforts.length ? ` · 推理强度 ${value.efforts.join(' / ')}` : ''}</small></span>
|
||||
</label>)}{!visible.length && <p className="mc-empty">{preview.entries.length ? '没有匹配的型号。可更改搜索条件。' : '上游返回了空目录。可核对连接或使用手动兼容入口。'}</p>}
|
||||
@@ -99,7 +101,7 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
|
||||
<div className="mc-form-grid"><label>保存后的使用方式<select aria-label="模型使用方式" value={routing} disabled={locked} onChange={event => setRouting(event.target.value)}><option value="keep">保留当前选择,稍后手动使用</option><option value="manual">手动指定默认模型</option><option value="auto">自动适配所选模型</option></select></label>
|
||||
{routing === 'manual' && <label>默认模型<select aria-label="目录默认模型" value={defaultModel} disabled={locked} onChange={event => setDefaultModel(event.target.value)}><option value="">请选择型号</option>{chosen.map(id => <option key={id}>{id}</option>)}</select></label>}</div>
|
||||
{routing === 'auto' && <p className="mc-help">自动适配复用模型池,按任务所需能力、连接健康和可用并发筛选,再按轮询分配;同一运行优先保持型号。未确认能力的型号不会用于需要该能力的任务。</p>}
|
||||
<div className="mc-actions"><button className="button primary" disabled={locked || !chosen.length || routing === 'manual' && !chosen.includes(defaultModel) || routing === 'auto' && chosen.length > 32} onClick={() => void save()}>{saving ? '正在保存…' : `保存所选 ${chosen.length} 个模型`}</button></div>
|
||||
<div className="mc-actions"><button className="button primary" disabled={locked || !chosen.length || routing === 'manual' && !chosen.includes(defaultModel) || routing === 'auto' && chosen.length > poolLimit} onClick={() => void save()}>{saving ? '正在保存…' : `保存所选 ${chosen.length} 个模型`}</button></div>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ type Connection = { id: string; name: string; baseUrl: string; revision: number
|
||||
type Trial = { mode: string; status: string; stage: string; address?: string; family?: string; code?: string; tcpMs?: number; tlsMs?: number;
|
||||
tls?: string; tlsProtocol?: string; certificateAuthorized?: boolean; attempts: { address: string; code?: string }[] };
|
||||
type Job = { id: string; connectionId: string; connectionRevision: number; connectionName: string; status: string; startedAt: string; finishedAt: string | null;
|
||||
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; target: { endpoint: string; host: string; port: number; scheme: string };
|
||||
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; stageTimeoutMs?: number; target: { endpoint: string; host: string; port: number; scheme: string };
|
||||
transport: { autoSelectFamily: boolean; familyAttemptTimeoutMs: number; connectTimeoutMs: number };
|
||||
route: { proxyConfigured: boolean; noProxyConfigured: boolean; customTransport: boolean };
|
||||
stages: { dns?: { status: string; elapsedMs?: number; code?: string; addresses?: { address: string; family: number }[] } }; trials: Trial[] };
|
||||
type View = { jobs: Job[]; active: number; retained: number };
|
||||
type View = { jobs: Job[]; active: number; retained: number | null };
|
||||
const labels: Record<string, string> = { passed: '通过', partial: '部分路径可连接', failed: '未通过', running: '检查中', pending: '等待',
|
||||
cancelled: '已停止', interrupted: '已中断', skipped: '未检查' };
|
||||
const reasons: Record<string, string> = { ENOTFOUND: '域名没有解析结果', EAI_AGAIN: 'DNS 暂时不可用', DNS_NO_ADDRESSES: '没有可用的 IP 地址',
|
||||
@@ -65,7 +65,7 @@ export function ModelNetworkDiagnostics({ connections, initialId, disabled }: {
|
||||
})}><Square size={14} />停止诊断</button>}
|
||||
</div>
|
||||
{selected && <p className="mn-endpoint">{selected.baseUrl} <span>· 配置修订 {selected.revision}</span></p>}
|
||||
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。检查最多约 12 秒,离开后结果保留。</span></p>
|
||||
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。可随时停止检查,离开后结果保留。</span></p>
|
||||
{error && <p className="mn-error" role="alert">{error}</p>}
|
||||
{activeJob && activeJob.connectionId !== connectionId && <p className="mn-scope">{activeJob.connectionName} 正在检查。<button type="button" className="mn-link" onClick={() => { setConnectionId(activeJob.connectionId); setFocused(activeJob.id); }}>查看正在运行的诊断</button></p>}
|
||||
{!view ? <p className="mc-empty">正在读取诊断记录…</p> : <div className="mn-workspace">
|
||||
@@ -86,11 +86,11 @@ export function ModelNetworkDiagnostics({ connections, initialId, disabled }: {
|
||||
{trial.code && <small>{detail(trial.code)}</small>}{trial.attempts.some(value => value.code) && <small>候选地址失败:{trial.attempts.filter(value => value.code).map(value => value.address + ' · ' + value.code).join(';')}</small>}</td></tr>)}</tbody></table>
|
||||
{job.code && <p className="mn-outcome">{detail(job.code)}</p>}
|
||||
<details className="mn-transport"><summary>查看原诊断范围与运输参数</summary><dl><dt>原端点</dt><dd>{job.target.endpoint}</dd><dt>检查目标</dt><dd>{job.target.host}:{job.target.port}</dd>
|
||||
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>连接 / 总时限</dt><dd>{job.transport.connectTimeoutMs} / {job.budgetMs} ms</dd>
|
||||
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>单路径 / 总时限</dt><dd>{(job.stageTimeoutMs ?? job.transport.connectTimeoutMs) > 0 ? (job.stageTimeoutMs ?? job.transport.connectTimeoutMs) + ' ms' : '不限'} / {job.budgetMs ? job.budgetMs + ' ms' : '不限'}</dd>
|
||||
<dt>模型 API</dt><dd>未请求;能力与连接健康结论保持原记录</dd><dt>记录</dt><dd>{job.id}</dd></dl></details>
|
||||
</>}
|
||||
</div>
|
||||
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>保存最近 {view.retained} 条;点击查看原记录。</p>
|
||||
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>{view.retained === null ? '保留全部检查记录。' : `保存最近 ${view.retained} 条。`}点击查看原记录。</p>
|
||||
{!jobs.length && <p>这条连接还没有检查记录。</p>}{jobs.map(value => <button key={value.id} type="button" aria-pressed={job?.id === value.id} onClick={() => setFocused(value.id)}><span>{new Date(value.startedAt).toLocaleString()}</span><strong>{labels[value.status] ?? value.status}{value.stale ? ' · 旧配置' : ''}</strong><small>修订 {value.connectionRevision} · {duration(value.elapsedMs)}</small></button>)}
|
||||
</aside>
|
||||
</div>}
|
||||
|
||||
@@ -6,13 +6,13 @@ export function ModelWaitSettings({ value, disabled, onSave }: { value: WaitSett
|
||||
const [responseSeconds, setResponseSeconds] = useState(value.modelResponseTimeoutMs / 1000);
|
||||
const [idleSeconds, setIdleSeconds] = useState(value.modelStreamIdleTimeoutMs / 1000);
|
||||
return <form className="mc-editor" aria-label="模型等待时限" onSubmit={event => { event.preventDefault(); onSave({ modelResponseTimeoutMs: responseSeconds * 1000, modelStreamIdleTimeoutMs: idleSeconds * 1000 }); }}>
|
||||
<h3>给模型足够时间,保留等待边界。</h3>
|
||||
<h3>模型等待时间</h3>
|
||||
<p>适用于原模型连接及模型池内的每次请求;从下一次运行生效。保存只调整等待时限,保留当前模型池和连接。</p>
|
||||
<div className="mc-form-grid">
|
||||
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={15} max={900} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>包含服务排队与生成。默认 300 秒,最多 900 秒。</small></label>
|
||||
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={5} max={300} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>开始流式响应后连续没有新数据的等待时间。默认 120 秒。</small></label>
|
||||
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={0} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>默认 0=不限,包含服务排队与生成;可自行填写等待秒数。</small></label>
|
||||
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={0} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>默认 0=不限。可设置开始流式响应后连续没有新数据的等待秒数。</small></label>
|
||||
</div>
|
||||
<p>持续收到数据仍受单次响应上限约束。停止任务立即生效;任务总预算先到时会暂停。不完整的文件或命令参数不会执行。</p>
|
||||
<p>仅在填写正数时使用相应时限;0 不附加本地等待期限。你可以随时停止任务,上游原始错误和实际用量会保留。</p>
|
||||
<div className="mc-actions"><button type="submit" className="button primary" disabled={disabled}>保存等待时限</button></div>
|
||||
</form>;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function messagesStream(config = {}) {
|
||||
message = structuredClone(start);
|
||||
} else if (!message) fail('事件缺少原 message_start。');
|
||||
else if (event.type === 'content_block_start') {
|
||||
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
|
||||
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || config.executionMode !== 'unrestricted' && blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
|
||||
const block = event.content_block;
|
||||
if (!object(block) || !['text', 'tool_use', 'thinking', 'redacted_thinking'].includes(block.type)) fail('未接入的内容块类型。');
|
||||
if (block.type === 'text' && typeof block.text !== 'string' || block.type === 'tool_use' && (!object(block.input) || typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name)
|
||||
|
||||
@@ -75,11 +75,11 @@ export class ModelCatalog {
|
||||
this.current({ binding });
|
||||
if (!unrestricted(this.hub.store) && (Date.now() >= deadline)) throw fail('获取模型目录超过60秒,请稍后重试。');
|
||||
const query = cursor ? '?after_id=' + encodeURIComponent(cursor) + '&limit=100' : connection.protocol === 'anthropic-messages' ? '?limit=100' : '';
|
||||
const raw = await this.hub.provider.request({ ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined,
|
||||
const raw = await this.hub.provider.request({ ...this.hub.store.config, ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined,
|
||||
{ attempts: 1, timeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()), totalTimeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()) });
|
||||
const encoded = this.hub.provider.redact(JSON.stringify(raw), key); bytes += Buffer.byteLength(encoded);
|
||||
if (bytes > 4 * 1024 * 1024) throw fail('模型目录超过4MB上限,请使用供应商筛选接口或手动添加。');
|
||||
const page = catalogPage(JSON.parse(encoded)); pages++;
|
||||
if (bytes > ceiling(this.hub.store, 4 * 1024 * 1024)) throw fail('模型目录超过4MB上限,请使用供应商筛选接口或手动添加。');
|
||||
const page = catalogPage(JSON.parse(encoded), this.hub.store.config); pages++;
|
||||
if (!unrestricted(this.hub.store) && (page.entries.length > 1000)) throw fail('单页模型超过1000项,请核对上游分页。');
|
||||
for (const item of page.entries) {
|
||||
if (entries.has(item.id) && JSON.stringify(entries.get(item.id)) !== JSON.stringify(item)) throw fail('上游目录包含相同型号的冲突定义,请核对后重试。');
|
||||
@@ -92,10 +92,10 @@ export class ModelCatalog {
|
||||
if (!unrestricted(this.hub.store) && (pages === 20 || entries.size === 1000)) { complete = false; warning = '目录仍有后续页,已达到本次获取上限;当前只显示部分模型。'; break; }
|
||||
} while (true);
|
||||
controller.signal.throwIfAborted(); this.current({ binding }); this.prune();
|
||||
if (this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value);
|
||||
if (!unrestricted(this.hub.store) && this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value);
|
||||
const fetchedAt = stamp(), expires = Date.now() + 5 * 60000;
|
||||
const preview = { id, entries: [...entries.values()], fetchedAt, expiresAt: new Date(expires).toISOString(), complete, warning,
|
||||
source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol }, limits: { connections: 100, poolMembers: 32, catalog: 1000 } };
|
||||
source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol }, limits: unrestricted(this.hub.store) ? { connections: null, poolMembers: null, catalog: null } : { connections: 100, poolMembers: 32, catalog: 1000 } };
|
||||
this.previews.set(id, { preview, connection, binding, explicitKey, expires });
|
||||
return preview;
|
||||
} finally { this.active.delete(id); }
|
||||
@@ -107,8 +107,8 @@ export class ModelCatalog {
|
||||
if (!Array.isArray(input.models) || !input.models.length || !unrestricted(this.hub.store) && input.models.length > 100 || new Set(input.models).size !== input.models.length) throw fail('请选择1–100个不重复的上游模型。');
|
||||
const selected = input.models.map(id => value.preview.entries.find(model => model.id === id));
|
||||
if (selected.some(model => !model)) throw fail('所选模型不属于本次上游目录。');
|
||||
if (selected.some(model => model.lifecycle === 'retired')) throw fail('已退役型号不能新增使用,请选择其它模型。');
|
||||
if (selected.some(model => model.contextLimit && model.contextLimit < 1000 || model.maxOutputTokens && model.maxOutputTokens < 256)) throw fail('所选型号的上游容量低于当前接入下限(上下文1000 / 输出256),请选择其它型号。');
|
||||
if (!unrestricted(this.hub.store) && selected.some(model => model.lifecycle === 'retired')) throw fail('已退役型号不能新增使用,请选择其它模型。');
|
||||
if (!unrestricted(this.hub.store) && selected.some(model => model.contextLimit && model.contextLimit < 1000 || model.maxOutputTokens && model.maxOutputTokens < 256)) throw fail('所选型号的上游容量低于当前接入下限(上下文1000 / 输出256),请选择其它型号。');
|
||||
const declarations = capabilityDeclarations(input.declarations, { text: 'unknown', tools: 'unknown', streaming: 'unknown', vision: 'unknown', audio: 'unknown' });
|
||||
if (!['keep', 'manual', 'auto'].includes(input.routing ?? 'keep')) throw fail('请选择保留当前选择、手动指定或自动适配。');
|
||||
if (input.routing === 'manual' && !input.models.includes(input.defaultModel)) throw fail('请在勾选的模型中指定默认型号。');
|
||||
|
||||
@@ -213,13 +213,13 @@ export class ModelHub {
|
||||
if (input.streaming !== undefined && typeof input.streaming !== 'boolean') throw error('流式选项必须为开启或关闭。');
|
||||
const streaming = input.streaming ?? previous?.streaming ?? false;
|
||||
if (!unrestricted(this.store) && streaming && declarations.streaming !== 'supported') throw error('请先声明服务支持流式输出,再开启流式请求。');
|
||||
const name = label(input.name), model = label(input.model, 200);
|
||||
const name = label(input.name, ceiling(this.store, 100)), model = label(input.model, ceiling(this.store, 200));
|
||||
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
|
||||
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol, model,
|
||||
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', ceiling(this.store, 40)), protocol, model,
|
||||
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
|
||||
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
|
||||
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
|
||||
...capacitySettings(input, previous ?? undefined),
|
||||
...capacitySettings(input, previous ?? undefined, this.store.config),
|
||||
concurrency: unrestricted(this.store) ? (input.concurrency ?? 0) : bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
|
||||
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
|
||||
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
|
||||
@@ -267,7 +267,7 @@ export class ModelHub {
|
||||
seen.add(value.connectionId); return { connectionId: value.connectionId, weight: bounded(value.weight, 1, 1, 10) };
|
||||
});
|
||||
if (!['round-robin', 'weighted'].includes(input.strategy || 'round-robin')) throw error('请选择轮询或权重策略。');
|
||||
const value = { id: previous?.id ?? randomUUID(), name: label(input.name), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
|
||||
const value = { id: previous?.id ?? randomUUID(), name: label(input.name, ceiling(this.store, 100)), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
|
||||
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
|
||||
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
if (delta.refusal) text += delta.refusal;
|
||||
if (delta.tool_calls !== undefined && !Array.isArray(delta.tool_calls)) throw protocolFailure('Chat流工具片段格式无效。');
|
||||
for (const item of delta.tool_calls ?? []) {
|
||||
if (!Number.isSafeInteger(item.index) || item.index < 0 || item.index >= 12) throw protocolFailure('Chat流工具索引无效。');
|
||||
if (!Number.isSafeInteger(item.index) || item.index < 0 || config.executionMode !== 'unrestricted' && item.index >= 12) throw protocolFailure('Chat流工具索引无效。');
|
||||
const call = calls.get(item.index) ?? { id: '', type: 'function', function: { name: '', arguments: '' } };
|
||||
if (item.id) { if (call.id && call.id !== item.id) throw protocolFailure('Chat流工具身份发生变化。'); call.id = item.id; }
|
||||
if (item.type && item.type !== 'function') throw protocolFailure('Chat流工具类型未接入。');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { ModelTransport } from './transport.mjs';
|
||||
import { probeNetwork } from './network-probe.mjs';
|
||||
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
|
||||
|
||||
const problem = (message, status = 409) => Object.assign(new Error(message), { status });
|
||||
const terminal = new Set(['passed', 'partial', 'failed', 'cancelled', 'interrupted']);
|
||||
@@ -23,7 +24,7 @@ export class NetworkDiagnostics {
|
||||
const connection = this.hub.connections().find(row => row.id === job.connectionId);
|
||||
return { ...structuredClone(job), stale: !connection || connection.revision !== job.connectionRevision,
|
||||
currentConnectionRevision: connection?.revision ?? null };
|
||||
}).reverse(), active: this.active.size, retained: 30, httpRequests: 0, modelRequests: 0 };
|
||||
}).reverse(), active: this.active.size, retained: unrestricted(this.hub.store) ? null : 30, httpRequests: 0, modelRequests: 0 };
|
||||
}
|
||||
start(input) {
|
||||
if (!input || Object.keys(input).length !== 2 || Object.keys(input).some(key => !['id', 'revision'].includes(key)) || !Number.isSafeInteger(input.revision)) throw problem('连接诊断需要所选连接及其原修订。', 400);
|
||||
@@ -38,20 +39,22 @@ export class NetworkDiagnostics {
|
||||
const profile = structuredClone(transport.profile);
|
||||
const target = { endpoint: connection.baseUrl, origin: url.origin, host: url.hostname.replace(/^\[|\]$/g, ''),
|
||||
port: Number(url.port || (url.protocol === 'https:' ? 443 : 80)), scheme: url.protocol };
|
||||
const budgetMs = this.options.budgetMs ?? Math.min(12000, profile.connectTimeoutMs + 2000);
|
||||
const open = unrestricted(this.hub.store);
|
||||
const stageTimeoutMs = this.options.stageTimeoutMs ?? (profile.connectTimeoutMs || (open ? 0 : 10000));
|
||||
const budgetMs = this.options.budgetMs ?? (open ? 0 : Math.min(12000, (profile.connectTimeoutMs || 10000) + 2000));
|
||||
const job = { schemaVersion: 1, id: randomUUID(), connectionId: connection.id, connectionRevision: connection.revision,
|
||||
connectionName: connection.name, status: 'running', startedAt: new Date().toISOString(), finishedAt: null,
|
||||
target, transport: profile, route: { kind: 'direct-endpoint-only', proxyConfigured: profile.httpProxyConfigured || profile.httpsProxyConfigured,
|
||||
noProxyConfigured: profile.noProxyConfigured, customTransport, modelApiRouteVerified: false },
|
||||
budgetMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false };
|
||||
budgetMs, stageTimeoutMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false };
|
||||
const previous = this.jobs;
|
||||
this.jobs = [...this.jobs.slice(-29), job];
|
||||
this.jobs = [...(open ? this.jobs : this.jobs.slice(-29)), job];
|
||||
try { this.save(); } catch (error) { this.jobs = previous; throw error; }
|
||||
const controller = new AbortController(), operation = { job, controller, promise: null };
|
||||
this.active.set(job.id, operation);
|
||||
const timer = setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs);
|
||||
const timer = budgetMs > 0 ? setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs) : null;
|
||||
operation.promise = Promise.resolve().then(async () => {
|
||||
const result = await probeNetwork(target, profile, { ...this.options,
|
||||
const result = await probeNetwork(target, profile, { ...this.options, stageTimeoutMs, maxAddresses: ceiling(this.hub.store, 32),
|
||||
...(transport.connect?.lookup ? { lookup: transport.connect.lookup } : {}), signal: controller.signal,
|
||||
update: result => { Object.assign(job, result); this.save(); } });
|
||||
Object.assign(job, result);
|
||||
|
||||
@@ -7,7 +7,7 @@ const elapsed = start => Math.max(0, Math.round(performance.now() - start));
|
||||
const code = error => /^[A-Z0-9_]{1,80}$/.test(error?.code ?? '') ? error.code : 'NETWORK_CHECK_FAILED';
|
||||
const cancelled = signal => Object.assign(new Error('连接诊断已停止。'), { code: signal.reason?.code ?? 'DIAGNOSTIC_CANCELLED' });
|
||||
|
||||
export async function probeNetwork(target, profile, { signal, update, lookup = dns.lookup, ca, stageTimeoutMs = profile.connectTimeoutMs } = {}) {
|
||||
export async function probeNetwork(target, profile, { signal, update, lookup = dns.lookup, ca, stageTimeoutMs = profile.connectTimeoutMs, maxAddresses = 32 } = {}) {
|
||||
const started = performance.now(), stages = { dns: { status: 'running', startedAt: new Date().toISOString() } };
|
||||
const trials = ['auto', 'ipv4', 'ipv6'].map(mode => ({ mode, status: 'pending', stage: 'dns', attempts: [] }));
|
||||
let updateError;
|
||||
@@ -26,7 +26,7 @@ export async function probeNetwork(target, profile, { signal, update, lookup = d
|
||||
try { lookup(target.host, { all: true, verbatim: true }, (error, rows) => finish(error, rows)); }
|
||||
catch (error) { finish(error); }
|
||||
});
|
||||
addresses = addresses.filter(row => [4, 6].includes(row.family) && net.isIP(row.address) === row.family).slice(0, 32);
|
||||
addresses = addresses.filter(row => [4, 6].includes(row.family) && net.isIP(row.address) === row.family).slice(0, maxAddresses);
|
||||
if (!addresses.length) throw Object.assign(new Error('没有可用地址。'), { code: 'DNS_NO_ADDRESSES' });
|
||||
stages.dns = { ...stages.dns, status: 'passed', elapsedMs: elapsed(lookupStart), addresses };
|
||||
} catch (error) {
|
||||
@@ -54,14 +54,14 @@ export async function probeNetwork(target, profile, { signal, update, lookup = d
|
||||
if (signal?.aborted) { abort(); return; }
|
||||
signal?.addEventListener('abort', abort, { once: true });
|
||||
trial.status = 'running'; trial.stage = 'tcp'; publish();
|
||||
timer = setTimeout(() => finish('failed', { code: trial.stage === 'tcp' ? 'TCP_CONNECT_TIMEOUT' : 'TLS_HANDSHAKE_TIMEOUT' }), stageTimeoutMs);
|
||||
if (stageTimeoutMs > 0) timer = setTimeout(() => finish('failed', { code: trial.stage === 'tcp' ? 'TCP_CONNECT_TIMEOUT' : 'TLS_HANDSHAKE_TIMEOUT' }), stageTimeoutMs);
|
||||
const frozenLookup = (_host, options, callback) => options.all ? callback(null, candidates)
|
||||
: callback(null, candidates[0].address, candidates[0].family);
|
||||
try {
|
||||
tcp = net.createConnection({ host: target.host, port: target.port, lookup: frozenLookup,
|
||||
autoSelectFamily: profile.autoSelectFamily, autoSelectFamilyAttemptTimeout: profile.familyAttemptTimeoutMs });
|
||||
tcp.on('error', error => finish('failed', error));
|
||||
tcp.on('connectionAttempt', (address, port, family) => { if (trial.attempts.length < 32) trial.attempts.push({ address, port, family }); });
|
||||
tcp.on('connectionAttempt', (address, port, family) => { if (trial.attempts.length < maxAddresses) trial.attempts.push({ address, port, family }); });
|
||||
tcp.on('connectionAttemptFailed', (address, _port, _family, error) => {
|
||||
const attempt = trial.attempts.findLast(row => row.address === address); if (attempt) attempt.code = code(error);
|
||||
});
|
||||
|
||||
@@ -2,21 +2,37 @@ export const DEFAULT_MODEL_TIMEOUT_MS = 300000;
|
||||
export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 120000;
|
||||
|
||||
export function modelWaitSettings(config = {}) {
|
||||
const bounded = (value, fallback, minimum, maximum) => Number.isSafeInteger(value) && (value === 0 || value >= minimum && value <= maximum) ? value : fallback;
|
||||
return { modelResponseTimeoutMs: bounded(config.modelResponseTimeoutMs, DEFAULT_MODEL_TIMEOUT_MS, 15000, 900000),
|
||||
modelStreamIdleTimeoutMs: bounded(config.modelStreamIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS, 5000, 300000) };
|
||||
const setting = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback;
|
||||
return { modelResponseTimeoutMs: setting(config.modelResponseTimeoutMs, DEFAULT_MODEL_TIMEOUT_MS),
|
||||
modelStreamIdleTimeoutMs: setting(config.modelStreamIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS) };
|
||||
}
|
||||
|
||||
export function validateModelWaitSettings(input, previous = {}) {
|
||||
const next = modelWaitSettings(previous);
|
||||
for (const [key, minimum, maximum] of [['modelResponseTimeoutMs', 15000, 900000], ['modelStreamIdleTimeoutMs', 5000, 300000]]) {
|
||||
for (const key of ['modelResponseTimeoutMs', 'modelStreamIdleTimeoutMs']) {
|
||||
if (!Object.hasOwn(input, key)) continue;
|
||||
if (!Number.isSafeInteger(input[key]) || input[key] !== 0 && (input[key] < minimum || input[key] > maximum)) throw Object.assign(new Error('模型等待时限必须为范围内的整数毫秒。'), { status: 400 });
|
||||
if (!Number.isSafeInteger(input[key]) || input[key] < 0) throw Object.assign(new Error('模型等待时限必须为大于等于0的安全整数毫秒;0表示不限。'), { status: 400 });
|
||||
next[key] = input[key];
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
// Node timers overflow beyond 2^31-1 ms. Honor a user's longer explicit wait
|
||||
// by scheduling consecutive portions instead of turning it into a 1 ms timer.
|
||||
export function scheduleDeadline(callback, milliseconds) {
|
||||
if (!(milliseconds > 0)) return null;
|
||||
let remaining = milliseconds, timer;
|
||||
const arm = () => {
|
||||
const portion = Math.min(remaining, 2147483647), began = Date.now();
|
||||
timer = setTimeout(() => {
|
||||
remaining -= Math.max(portion, Date.now() - began);
|
||||
if (remaining > 0) arm(); else callback();
|
||||
}, portion);
|
||||
timer.unref?.();
|
||||
};
|
||||
arm(); return () => clearTimeout(timer);
|
||||
}
|
||||
|
||||
// An active stream may outlive the old one-minute deadline. Idle time never
|
||||
// extends the absolute limit, and the caller's stop/budget signal always wins.
|
||||
export function requestDeadline({ signal, timeoutMs, idleTimeoutMs }) {
|
||||
@@ -29,18 +45,16 @@ export function requestDeadline({ signal, timeoutMs, idleTimeoutMs }) {
|
||||
controller.abort(new DOMException('Model response deadline exceeded', 'TimeoutError'));
|
||||
};
|
||||
let bytes = 0;
|
||||
if (timeoutMs > 0) absoluteTimer = setTimeout(() => abort('total'), Math.max(1, timeoutMs));
|
||||
absoluteTimer?.unref?.();
|
||||
absoluteTimer = scheduleDeadline(() => abort('total'), timeoutMs);
|
||||
const armIdle = () => {
|
||||
clearTimeout(idleTimer);
|
||||
idleTimer?.();
|
||||
if (idleTimeoutMs > 0 && !controller.signal.aborted && !signal?.aborted) {
|
||||
idleTimer = setTimeout(() => abort('idle'), idleTimeoutMs);
|
||||
idleTimer.unref?.();
|
||||
idleTimer = scheduleDeadline(() => abort('idle'), idleTimeoutMs);
|
||||
}
|
||||
};
|
||||
return { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
|
||||
get timeout() { return detail; },
|
||||
beginStream() { stage = 'stream'; lastData = Date.now(); armIdle(); },
|
||||
receive(length) { if (length > 0) { bytes += length; lastData = Date.now(); armIdle(); } },
|
||||
close() { clearTimeout(absoluteTimer); clearTimeout(idleTimer); } };
|
||||
close() { absoluteTimer?.(); idleTimer?.(); } };
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ export class Provider {
|
||||
if (key) headers[messagesAuth === 'bearer' ? 'Authorization' : 'x-api-key'] = messagesAuth === 'bearer' ? 'Bearer ' + key : key;
|
||||
} else if (key) headers.Authorization = 'Bearer ' + key;
|
||||
const requestUrl = base + route;
|
||||
const waits = modelWaitSettings(config), timeoutMs = body ? waits.modelResponseTimeoutMs : 20000;
|
||||
const waits = modelWaitSettings(config), timeoutMs = body || unrestricted(config) ? waits.modelResponseTimeoutMs : 20000;
|
||||
const policy = { attempts: 3, delays: [500, 1500], timeoutMs, totalTimeoutMs: timeoutMs,
|
||||
idleTimeoutMs: waits.modelStreamIdleTimeoutMs, ...this.retryPolicy, ...options };
|
||||
if (config.capacityMode === 'passthrough') policy.attempts = 1;
|
||||
@@ -352,7 +352,7 @@ export class Provider {
|
||||
const body = completionBody(config, messages, tools);
|
||||
assertPlannedRequest(body, requestPlan);
|
||||
if (config.executionMode !== 'unrestricted' && config.inputImages?.length && (!config.modelRouting || !this.hub || config.mode==='demo')) throw new Error('图片请求必须通过模型中心的视觉能力选路,尚未发送。');
|
||||
if (config.mode === 'demo') return this.demo(messages, project);
|
||||
if (config.mode === 'demo') return this.demo(messages, project, config);
|
||||
this.validate(config);
|
||||
const execute = async (selected, key, input, progress) => {
|
||||
return this.request(selected, protocolRoute(selected), input, signal, key, progress, { ...(config.modelRouting ? { attempts: 1 } : {}), ...requestPolicy,
|
||||
@@ -379,7 +379,7 @@ export class Provider {
|
||||
...(calls.length ? { tool_calls: calls } : {}) }, usage: result.usage ?? null, finishReason: result.choices[0].finish_reason ?? null,
|
||||
...(result.compatibility?.length ? { compatibility: result.compatibility } : {}) };
|
||||
}
|
||||
demo(messages, project) {
|
||||
demo(messages, project, config = {}) {
|
||||
const lastUser = messages.findLastIndex(message => message.role === 'user');
|
||||
const results = messages.slice(lastUser + 1).filter(message => message.role === 'tool');
|
||||
const count = results.length;
|
||||
@@ -400,9 +400,9 @@ export class Provider {
|
||||
const user = String(messages[lastUser]?.content ?? '').slice(0, 300);
|
||||
return tool('propose_file', { path: 'WORKBENCH-NOTES.md',
|
||||
content: '# 工作台验证记录\n\n这份记录由离线演示脚本准备,用来验证差异审查与文件写入流程;没有调用大模型。\n\n## 本次任务\n' + user + '\n\n## 项目依据\n' + excerpt.slice(0, 1000) + '\n\n## 下一步\n在工作台查看差异,应用后可继续连接真实模型进行项目开发。\n',
|
||||
reason: '用真实的项目读取结果准备一个可审查的文本提案。' }, '已取得项目依据。我会准备一个文件提案,等待你查看差异后应用。');
|
||||
reason: '用真实的项目读取结果准备一个可审查的文本提案。' }, unrestricted(config) ? '已取得项目依据,接下来直接写入文件并保存差异与回滚资料。' : '已取得项目依据。我会准备一个文件提案,等待你查看差异后应用。');
|
||||
}
|
||||
if (count === 3) return tool('run_command', { command: 'node --version', reason: '只读取本机 Node 版本,演示终端确认与执行记录。' }, '最后请求一次只读的环境验证。确认后会记录实际命令输出。');
|
||||
return { message: { role: 'assistant', content: '离线演示已完成:项目读取、文件提案和终端确认流程都有执行记录。待审查改动可以在右侧查看并应用。\n\n这次没有调用大模型。你可以在“模型连接”中配置自己的兼容服务,随后用同一套工具完成真实开发任务。' }, usage: null, finishReason: 'stop' };
|
||||
return { message: { role: 'assistant', content: (unrestricted(config) ? '离线演示已结束:请在任务记录核对项目读取、文件写入和终端操作的实际结果;文件差异与回滚入口可随时查看。' : '离线演示已完成:项目读取、文件提案和终端确认流程都有执行记录。待审查改动可以在右侧查看并应用。') + '\n\n这次没有调用大模型。你可以在“模型连接”中配置自己的兼容服务,随后用同一套工具完成真实开发任务。' }, usage: null, finishReason: 'stop' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { unrestricted, ceiling, openToolDefinitions, automaticApproval } from '../shared/contracts/execution-policy.mjs';
|
||||
import { scheduleDeadline } from '../core/models/request-deadline.mjs';
|
||||
import { approvalPresentation } from '../shared/approval-presentation.mjs';
|
||||
import { PreviewManager } from '../core/preview/preview-manager.mjs';
|
||||
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
|
||||
@@ -303,9 +304,9 @@ export class Runtime {
|
||||
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
|
||||
session.failure = null;
|
||||
this.store.save(session);
|
||||
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
|
||||
const deadline = scheduleDeadline(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs);
|
||||
run.promise = this.run(session, config, run).finally(() => {
|
||||
clearTimeout(deadline);
|
||||
deadline?.();
|
||||
try {
|
||||
const status = session.status;
|
||||
if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore;
|
||||
|
||||
@@ -73,8 +73,8 @@ export function verifyEngineModelInput(store, session, job, request) {
|
||||
if (input.owner.sessionId !== job.sessionId || input.owner.taskId !== job.taskId || input.owner.runId !== job.runId || input.owner.projectId !== job.projectId
|
||||
|| controlledDigest(input.native) !== request.sourceSha256 || metrics.sha256 !== request.requestSha256 || metrics.bytes !== request.requestBytes
|
||||
|| !Number.isSafeInteger(request.maxAttempts) || request.maxAttempts < 1 || request.maxAttempts > 8
|
||||
|| (job.model.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1))
|
||||
|| !requestVariants(input.body).every(body => outputReservation(body) === (job.model.capacityMode === 'passthrough' ? null : input.native.maxTokens))
|
||||
|| (job.model?.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1))
|
||||
|| !requestVariants(input.body).every(body => outputReservation(body) === (job.model?.capacityMode === 'passthrough' ? null : input.native.maxTokens))
|
||||
|| request.reservedPerAttempt !== (request.reservationVersion===1?request.tokenReservation.reservedTokens:metrics.estimatedInputTokens + 128 + input.native.maxTokens)) throw engineError('原引擎模型输入、归属或预算核对失败。');
|
||||
if(input.view){
|
||||
const view=input.view,source=store.owned('artifact',view.sourceArtifactId,session.id),sourceValue=JSON.parse(store.artifactStore.read(source));
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { unrestricted } from './execution-policy.mjs';
|
||||
|
||||
// Editable fallbacks for upstreams that do not publish capacity. These values
|
||||
// are not verified model capabilities or ceilings on larger models.
|
||||
export const DEFAULT_MODEL_CAPACITY = Object.freeze({ contextLimit: 128000, maxOutputTokens: 16384 });
|
||||
export const CAPACITY_RANGES = Object.freeze({ contextLimit: [1000, Number.MAX_SAFE_INTEGER], maxOutputTokens: [256, Number.MAX_SAFE_INTEGER] });
|
||||
|
||||
export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY) {
|
||||
export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY, config = {}) {
|
||||
return Object.fromEntries(Object.entries(CAPACITY_RANGES).map(([key, [min, max]]) => {
|
||||
const value = input[key] ?? previous[key] ?? DEFAULT_MODEL_CAPACITY[key];
|
||||
if (!Number.isSafeInteger(value) || value < min || value > max) throw Object.assign(new Error(key + ' 需要不小于 ' + min + ' 的安全整数,请核对模型实际容量。'), { status: 400 });
|
||||
const minimum = unrestricted(config) ? 1 : min;
|
||||
if (!Number.isSafeInteger(value) || value < minimum || value > max) throw Object.assign(new Error(key + ' 需要不小于 ' + minimum + ' 的安全整数,请核对模型实际容量。'), { status: 400 });
|
||||
return [key, value];
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ export interface CatalogModel {
|
||||
}
|
||||
export interface CatalogPreview {
|
||||
id: string; entries: CatalogModel[]; fetchedAt: string; expiresAt: string; complete: boolean; warning: string;
|
||||
source: { name: string; baseUrl: string; protocol: string }; limits: { connections: number; poolMembers: number; catalog: number };
|
||||
source: { name: string; baseUrl: string; protocol: string }; limits: { connections: number | null; poolMembers: number | null; catalog: number | null };
|
||||
}
|
||||
export function catalogRoute(config: { protocol?: string; baseUrl: string }): string;
|
||||
export function catalogModel(item: unknown): CatalogModel;
|
||||
export function catalogPage(response: unknown): { entries: CatalogModel[]; hasMore: boolean; cursor: string };
|
||||
export function catalogModel(item: unknown, config?: { executionMode?: string }): CatalogModel;
|
||||
export function catalogPage(response: unknown, config?: { executionMode?: string }): { entries: CatalogModel[]; hasMore: boolean; cursor: string };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { modelProtocol } from './model-capabilities.mjs';
|
||||
import { ceiling, unrestricted } from './execution-policy.mjs';
|
||||
|
||||
const fail = message => Object.assign(new Error(message), { status: 400 });
|
||||
const text = (value, max = 200) => typeof value === 'string' ? value.trim().slice(0, max) : '';
|
||||
@@ -15,10 +16,11 @@ export function catalogRoute(config) {
|
||||
|
||||
// Metadata is an upstream declaration, never capability-test evidence. Keep
|
||||
// unsupported adapter features visible without passing arbitrary vendor fields.
|
||||
export function catalogModel(item) {
|
||||
export function catalogModel(item, config = {}) {
|
||||
if (typeof item === 'string') item = { id: item };
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) throw fail('上游模型目录含无效条目。');
|
||||
const id = text(item.id ?? item.name);
|
||||
const field = (value, maximum = 200) => text(value, ceiling(config, maximum));
|
||||
const id = field(item.id ?? item.name);
|
||||
if (!id || id.length !== String(item.id ?? item.name).trim().length || /[\x00-\x1f\x7f]/.test(id)) throw fail('上游模型名称为空、过长或含控制字符。');
|
||||
const caps = item.capabilities && typeof item.capabilities === 'object' && !Array.isArray(item.capabilities) ? item.capabilities : {};
|
||||
const declarations = Object.fromEntries(['text', 'tools', 'streaming', 'vision', 'audio'].map(key => [key,
|
||||
@@ -30,12 +32,12 @@ export function catalogModel(item) {
|
||||
if (input.includes('audio') && declarations.audio === 'unknown') declarations.audio = 'supported';
|
||||
}
|
||||
if (Array.isArray(output) && output.includes('text') && declarations.text === 'unknown') declarations.text = 'supported';
|
||||
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && value.length <= 80))].slice(0, 80) : [];
|
||||
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && (unrestricted(config) || value.length <= 80)))].slice(0, ceiling(config, 80)) : [];
|
||||
if (declarations.tools === 'unknown' && parameters.includes('tools')) declarations.tools = 'supported';
|
||||
const efforts = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].filter(value => supported(caps.effort?.[value]) === 'supported');
|
||||
const modes = ['disabled', 'enabled', 'adaptive'].filter(value => supported(caps.thinking?.types?.[value]) === 'supported');
|
||||
const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])]));
|
||||
return { id, name: text(item.display_name ?? item.name ?? id), owner: text(item.owned_by ?? item.provider, 100),
|
||||
return { id, name: field(item.display_name ?? item.name ?? id), owner: field(item.owned_by ?? item.provider, 100),
|
||||
lifecycle: ['active', 'deprecated', 'retired'].includes(item.lifecycle) ? item.lifecycle : null,
|
||||
contextLimit: positive(item.context_length ?? item.max_input_tokens ?? item.context_window),
|
||||
maxOutputTokens: positive(item.max_output_tokens ?? item.max_tokens ?? item.top_provider?.max_completion_tokens),
|
||||
@@ -43,12 +45,12 @@ export function catalogModel(item) {
|
||||
metadataSource: 'upstream-model-list' };
|
||||
}
|
||||
|
||||
export function catalogPage(response) {
|
||||
export function catalogPage(response, config = {}) {
|
||||
const data = response?.data ?? response?.models;
|
||||
if (!Array.isArray(data)) throw fail('上游未返回 data 或 models 模型列表;可核对接口或使用手动兼容入口。');
|
||||
const entries = data.map(catalogModel);
|
||||
const entries = data.map(item => catalogModel(item, config));
|
||||
const hasMore = response.has_more === true;
|
||||
const cursor = hasMore ? text(response.last_id ?? entries.at(-1)?.id) : '';
|
||||
const cursor = hasMore ? text(response.last_id ?? entries.at(-1)?.id, ceiling(config, 200)) : '';
|
||||
if (hasMore && !cursor) throw fail('上游声明还有下一页,却未提供有效游标。');
|
||||
return { entries, hasMore, cursor };
|
||||
}
|
||||
|
||||
@@ -989,5 +989,7 @@ F收尾:57d075e修正独立编译QA路径,6d09ac8封存差异;202610302320
|
||||
|
||||
用户最新明确要求取代默认模型容量策略:默认不发送输出 token 上限、完整历史不受本地上下文窗口门控、累计 token 预算 0=不限;上游错误原文/状态/用量保留,不自动恢复截断或换池掩盖首错。保留可选手动模式与历史快照核验,不执行残缺工具。先实现和针对性 HTTP/UI 验证、本地提交,再独立发行并实际重启工作台。正式旧 Key 不读取/复制/重存;重启后公开状态单列,原项目不续跑。旧 full-source 已中止,非全绿;历史自主交付/网络/重复读取/Purge 未验证继续保留。
|
||||
|
||||
最终接续:先完成worker发送前预算诊断,按before SHA只合回26份明确草稿改动;构建、相关补验和网页10/Electron11实际路径,回顾与本地提交。干净来源另制不可变候选,独立ZIP重建/归档/真实隔离安装后,执行正式before→唯一升级→full/open保存→实际重启→只读界面→final对账。976项原轮958/18保持,不将补验倒写成全绿;不委派/推送、不触真实Key、不续跑原项目。
|
||||
|
||||
|
||||
用户追加:全系统复核三遍,取消人为限制。第一遍全量扫描148个服务端/共享模块、434处候选,涵盖模型额度/流/超时、轮次/无进展、命令审批/输出、文件/搜索、协作/评测、连接/技能/记忆/浏览器数量。新增默认完全开放策略,旧运行快照保留。第二遍按实际执行调用链查遗漏,第三遍针对性HTTP/界面/发行复核;未完成不得声称全系统已无限制。
|
||||
|
||||
@@ -43,8 +43,10 @@ test('budget-only API and demo/real selection preserve routes, reject injected e
|
||||
assert.deepEqual(result.modelSelection, { type: 'connection', id: connection.id, name: 'Owned model' });
|
||||
assert.equal(result.config.contextLimit, 32000); assert.equal(result.config.baseUrl, original.config.baseUrl);
|
||||
assert.deepEqual((await host.api('/model-center')).connections.find(c => c.id === connection.id), before.connections.find(c => c.id === connection.id));
|
||||
await assert.rejects(host.api('/model-center/runtime-budgets', { baseUrl: 'http://127.0.0.1:1' }), /只接受运行预算/);
|
||||
await assert.rejects(host.api('/model-center/runtime-budgets', { maxSteps: 0 }), /范围内的整数/);
|
||||
await assert.rejects(host.api('/model-center/runtime-budgets', { baseUrl: 'http://127.0.0.1:1' }), /只接受运行设置/);
|
||||
const unlimitedSteps = await host.api('/model-center/runtime-budgets', { maxSteps: 0 });
|
||||
assert.equal(unlimitedSteps.config.maxSteps, 0); assert.deepEqual(unlimitedSteps.modelSelection, result.modelSelection);
|
||||
await assert.rejects(host.api('/model-center/runtime-budgets', { maxSteps: -1 }), /范围内的整数/);
|
||||
await host.api('/model-center/mode', { mode: 'demo' });
|
||||
assert.deepEqual((await host.api('/model-center')).selected, before.selected);
|
||||
await host.api('/model-center/select', { type: 'legacy', id: 'legacy-default' });
|
||||
|
||||
@@ -11,13 +11,26 @@ test('older configurations receive bounded wait defaults without changing the or
|
||||
const legacy = { model: 'legacy' }, original = structuredClone(legacy);
|
||||
assert.deepEqual(modelWaitSettings(legacy), { modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000 });
|
||||
assert.deepEqual(legacy, original);
|
||||
for (const value of [null, '', -1, Infinity, 0, 2 ** 32, 60000.5]) assert.equal(modelWaitSettings({ modelResponseTimeoutMs: value }).modelResponseTimeoutMs, 300000);
|
||||
for (const value of [null, '', -1, Infinity, Number.MAX_SAFE_INTEGER + 1, 60000.5]) assert.equal(modelWaitSettings({ modelResponseTimeoutMs: value }).modelResponseTimeoutMs, 300000);
|
||||
assert.equal(modelWaitSettings({ modelResponseTimeoutMs: 900000 }).modelResponseTimeoutMs, 900000);
|
||||
assert.throws(() => validateModelWaitSettings({ modelResponseTimeoutMs: '60000' }), /整数/);
|
||||
assert.throws(() => validateModelWaitSettings({ modelStreamIdleTimeoutMs: 0 }), /整数/);
|
||||
assert.equal(validateModelWaitSettings({ modelStreamIdleTimeoutMs: 0 }).modelStreamIdleTimeoutMs, 0);
|
||||
assert.equal(modelWaitSettings({ modelResponseTimeoutMs: 0 }).modelResponseTimeoutMs, 0);
|
||||
assert.equal(modelWaitSettings({ modelResponseTimeoutMs: 2 ** 32 }).modelResponseTimeoutMs, 2 ** 32);
|
||||
assert.equal(validateModelWaitSettings({ modelStreamIdleTimeoutMs: 15000 }, { modelResponseTimeoutMs: 600000 }).modelResponseTimeoutMs, 600000);
|
||||
});
|
||||
|
||||
test('a fresh installation has unlimited waits and explicit long waits do not overflow Node timers', t => {
|
||||
const f = fixture(t, { modernDefaults: true });
|
||||
assert.deepEqual(modelWaitSettings(f.store.config), { modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0 });
|
||||
assert.deepEqual(validateModelWaitSettings({ modelResponseTimeoutMs: 1, modelStreamIdleTimeoutMs: 2 ** 32 }), { modelResponseTimeoutMs: 1, modelStreamIdleTimeoutMs: 2 ** 32 });
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 });
|
||||
const deadline = requestDeadline({ timeoutMs: 2 ** 32, idleTimeoutMs: 0 }); t.after(() => deadline.close());
|
||||
t.mock.timers.tick(2147483647); assert.equal(deadline.signal.aborted, false);
|
||||
t.mock.timers.tick(2147483647); assert.equal(deadline.signal.aborted, false);
|
||||
t.mock.timers.tick(2); assert.equal(deadline.signal.aborted, true); assert.equal(deadline.timeout.limitMs, 2 ** 32);
|
||||
});
|
||||
|
||||
test('active stream survives sixty seconds; byte activity resets idle but cannot extend total deadline', t => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 });
|
||||
const deadline = requestDeadline({ timeoutMs: 300000, idleTimeoutMs: 120000 }); t.after(() => deadline.close());
|
||||
|
||||
@@ -21,7 +21,7 @@ async function listener(f, server) {
|
||||
return server.address().port;
|
||||
}
|
||||
function setup(t, options = {}) {
|
||||
const f = fixture(t), provider = new Provider({ transport: options.transport ?? new ModelTransport({ environment: {} }) });
|
||||
const f = fixture(t, { modernDefaults: options.modernDefaults ?? false }), provider = new Provider({ transport: options.transport ?? new ModelTransport({ environment: {} }) });
|
||||
const hub = provider.modelHub(f.store); hub.networkChecks = new NetworkDiagnostics(hub, options);
|
||||
f.onCleanup(() => provider.abortRequests());
|
||||
const add = baseUrl => hub.upsert({ name: 'Owned network check', model: 'owned-no-model', baseUrl, requiresKey: true });
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import net from 'node:net';
|
||||
import { fixture, compatibleFixture, completion, until } from './helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { NetworkDiagnostics } from '../src/core/models/network-diagnostics.mjs';
|
||||
import { ModelTransport } from '../src/core/models/transport.mjs';
|
||||
import { readModelStream } from '../src/core/models/model-stream.mjs';
|
||||
|
||||
const sse = value => 'data: ' + (typeof value === 'string' ? value : JSON.stringify(value)) + '\n\n';
|
||||
const open = { executionMode: 'unrestricted', capacityMode: 'passthrough' };
|
||||
|
||||
test('open Chat SSE retains twenty complete tools while malformed indexes remain invalid', async () => {
|
||||
const calls = Array.from({ length: 20 }, (_, index) => ({ index, id: 'owned-' + index, type: 'function', function: { name: 'inspect_project', arguments: '{}' } }));
|
||||
const frame = tool_calls => sse({ choices: [{ index: 0, delta: { tool_calls }, finish_reason: 'tool_calls' }] }) + sse('[DONE]');
|
||||
const tools = [{ type: 'function', function: { name: 'inspect_project', parameters: { type: 'object', properties: {} } } }];
|
||||
const response = value => new Response(value, { headers: { 'content-type': 'text/event-stream' } });
|
||||
const result = await readModelStream(response(frame(calls)), { ...open, protocol: 'chat-completions' }, undefined, undefined, tools);
|
||||
assert.equal(result.value.choices[0].message.tool_calls.length, 20);
|
||||
assert.deepEqual(result.value.choices[0].message.tool_calls.map(row => row.id), calls.map(row => row.id));
|
||||
await assert.rejects(readModelStream(response(frame([{ ...calls[0], index: -1 }])), open, undefined, undefined, tools), /索引/);
|
||||
await assert.rejects(readModelStream(response(frame(calls)), { executionMode: 'restricted' }, undefined, undefined, tools), /索引|数量/);
|
||||
});
|
||||
|
||||
test('open Messages SSE preserves 129 ordered content blocks beyond the former 128-block ceiling', async () => {
|
||||
const blocks = Array.from({ length: 129 }, (_, index) => ({ type: 'text', text: 'original-' + index + '\n' }));
|
||||
const bytes = sse({ type: 'message_start', message: { type: 'message', id: 'owned-blocks', role: 'assistant', content: [], stop_reason: null, usage: { input_tokens: 3 } } })
|
||||
+ blocks.map((content_block, index) => sse({ type: 'content_block_start', index, content_block }) + sse({ type: 'content_block_stop', index })).join('')
|
||||
+ sse({ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 129 } }) + sse({ type: 'message_stop' });
|
||||
const response = () => new Response(bytes, { headers: { 'content-type': 'text/event-stream' } });
|
||||
const result = await readModelStream(response(), { ...open, protocol: 'anthropic-messages' });
|
||||
assert.deepEqual(result.value.content, blocks); assert.equal(result.evidence.bytes, Buffer.byteLength(bytes));
|
||||
await assert.rejects(readModelStream(response(), { protocol: 'anthropic-messages', executionMode: 'restricted' }), /内容块/);
|
||||
});
|
||||
|
||||
test('open catalog accepts a 4MB-plus upstream reply, long model IDs, small declared capacities and 121 automatic members without clipping', async t => {
|
||||
const f = fixture(t, { modernDefaults: true }), id = 'owned-' + 'model'.repeat(55);
|
||||
const entries = Array.from({ length: 121 }, (_, index) => ({ id: index ? 'owned-' + index : id,
|
||||
context_length: 128, max_output_tokens: 8, lifecycle: index === 120 ? 'retired' : 'active',
|
||||
capabilities: { text: true, tools: true }, supported_parameters: index ? [] : Array.from({ length: 95 }, (_, n) => 'parameter_' + n) }));
|
||||
const reply = { data: entries, upstream_note: 'x'.repeat(4 * 1024 * 1024 + 1) };
|
||||
const server = await compatibleFixture(t, (url, body) => url.endsWith('/models') ? reply : { ...completion([], 'Owned complete response'), model: body.model });
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store);
|
||||
f.onCleanup(() => provider.abortRequests());
|
||||
const source = hub.upsert({ name: 'Owned large catalog', model: 'source', baseUrl: server.baseUrl, requiresKey: false });
|
||||
const preview = await hub.modelCatalog().fetch({ id: source.id, revision: source.revision });
|
||||
assert.equal(preview.entries.length, 121); assert.equal(preview.entries[0].id, id); assert.equal(preview.entries[0].parameters.length, 95);
|
||||
assert.deepEqual(preview.limits, { connections: null, poolMembers: null, catalog: null });
|
||||
const result = hub.modelCatalog().apply({ previewId: preview.id, models: entries.map(row => row.id), routing: 'auto' });
|
||||
assert.equal(result.added.length, 121); assert.equal(hub.state.pools[0].members.length, 121);
|
||||
const connection = hub.connection(result.added[0]);
|
||||
assert.equal(connection.model, id); assert.equal(connection.contextLimit, 128); assert.equal(connection.maxOutputTokens, 8);
|
||||
hub.select({ type: 'connection', id: connection.id });
|
||||
await provider.complete(hub.prepare(f.store.config), [{ role: 'user', content: 'Reply only.' }], null, undefined, undefined, null, []);
|
||||
assert.equal(server.requests.length, 2); assert.equal(server.requests[1].input.model, id);
|
||||
for (const key of ['max_tokens', 'max_output_tokens', 'max_completion_tokens']) assert.equal(Object.hasOwn(server.requests[1].input, key), false);
|
||||
});
|
||||
|
||||
test('open network diagnostics keep all DNS addresses and history, and unlimited stalled TLS remains explicitly cancellable', async t => {
|
||||
const f = fixture(t, { modernDefaults: true }), sockets = new Set();
|
||||
const server = net.createServer(socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); socket.on('data', () => {}); });
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
f.onCleanup(async () => { for (const socket of sockets) socket.destroy(); await new Promise(resolve => server.close(resolve)); });
|
||||
const provider = new Provider({ transport: new ModelTransport({ environment: {} }) }), hub = provider.modelHub(f.store);
|
||||
const manager = hub.networkChecks = new NetworkDiagnostics(hub, { lookup: (_name, _options, done) => done(null, Array.from({ length: 40 }, () => ({ address: '127.0.0.1', family: 4 }))) });
|
||||
f.onCleanup(() => provider.abortRequests());
|
||||
const connection = hub.upsert({ name: 'Owned unlimited TCP', model: 'unused', baseUrl: 'http://owned-open.invalid:' + server.address().port + '/v1', requiresKey: false });
|
||||
let started = manager.start({ id: connection.id, revision: connection.revision }); await manager.active.get(started.job.id).promise;
|
||||
const first = manager.view().jobs[0]; assert.equal(first.status, 'passed'); assert.equal(first.budgetMs, 0); assert.equal(first.stageTimeoutMs, 0);
|
||||
assert.equal(first.stages.dns.addresses.length, 40); assert.equal(manager.view().retained, null);
|
||||
manager.jobs = Array.from({ length: 35 }, (_, index) => ({ ...first, id: 'owned-history-' + index })); manager.save();
|
||||
const stalled = hub.upsert({ name: 'Owned stalled TLS', model: 'unused', baseUrl: 'https://127.0.0.1:' + server.address().port + '/v1', requiresKey: false });
|
||||
started = manager.start({ id: stalled.id, revision: stalled.revision });
|
||||
await until(() => manager.jobs.at(-1).trials.some(row => row.stage === 'tls'), 15000);
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: Date.now() }); t.mock.timers.tick(120001);
|
||||
assert.equal(manager.jobs.at(-1).status, 'running'); assert.equal(manager.active.get(started.job.id).controller.signal.aborted, false);
|
||||
t.mock.timers.reset();
|
||||
const stopped = await manager.stop(started.job.id, {}); assert.equal(stopped.job.status, 'cancelled');
|
||||
assert.equal(manager.jobs.length, 36); assert.equal(manager.jobs[0].id, 'owned-history-0'); assert.equal(manager.active.size, 0);
|
||||
assert.equal(hub.attempts.length, 0); assert.equal(stopped.job.httpRequests, 0); assert.equal(stopped.job.modelRequests, 0);
|
||||
});
|
||||
@@ -14,7 +14,7 @@ const assertTruncated = error => {
|
||||
assert.ok(error instanceof Error);
|
||||
assert.equal(error.diagnostic.reason, 'output_truncated');
|
||||
assert.equal(error.diagnostic.message, OUTPUT_TRUNCATED_HINT);
|
||||
assert.match(error.diagnostic.message, /output token 上限/);
|
||||
assert.match(error.diagnostic.message, /上游模型.*输出额度/);
|
||||
assert.match(error.diagnostic.message, /拆成每次一个文件|分多轮/);
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@ import { completionBody } from '../src/shared/contracts/model-request.mjs';
|
||||
import { reportedUsage } from '../src/core/models/protocols.mjs';
|
||||
import { prefixAudit } from '../src/core/context/prefix-audit.mjs';
|
||||
|
||||
test('complete history above 16K is retained verbatim; an oversized history pauses without a compacted replacement', t => {
|
||||
test('complete history remains verbatim in passthrough; only an explicitly selected manual capacity can pause it', t => {
|
||||
const f = fixture(t, { modernDefaults: true }), config = { ...f.store.config, contextLimit: 128000 };
|
||||
const run = f.store.beginRun(f.session, 'Keep the complete original text.', false, config);
|
||||
const history = [{ role: 'user', content: 'Keep the original request.' }, { role: 'assistant', content: 'Owned original reference\n'.repeat(3500) }];
|
||||
@@ -17,8 +17,11 @@ test('complete history above 16K is retained verbatim; an oversized history paus
|
||||
assert.equal(plan.record.archivedGroups, 0); assert.ok(plan.record.estimatedInputTokens > 16000);
|
||||
assert.deepEqual(plan.body.messages.slice(1, 3), history); assert.equal(plan.record.retainedMessages, history.length);
|
||||
assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan.record));
|
||||
const open = planner.prepare(f.session, run, { ...config, contextLimit: 18000 }, { system: 'Stable rules', tools: [] });
|
||||
assert.deepEqual(open.body.messages.slice(1), history); assert.equal(open.record.archivedGroups, 0);
|
||||
assert.equal(Object.hasOwn(open.body, 'max_tokens'), false);
|
||||
const before = f.store.core.context_plan.size;
|
||||
assert.throws(() => planner.prepare(f.session, run, { ...config, contextLimit: 18000 }, { system: 'Stable rules', tools: [] }), cause => cause.reason === 'context_limit');
|
||||
assert.throws(() => planner.prepare(f.session, run, { ...config, capacityMode: 'manual', contextLimit: 18000, maxOutputTokens: 2048 }, { system: 'Stable rules', tools: [] }), cause => cause.reason === 'context_limit');
|
||||
assert.equal(f.store.core.context_plan.size, before); assert.deepEqual(f.session.providerMessages, history);
|
||||
});
|
||||
|
||||
|
||||
@@ -93,10 +93,14 @@ test('a deadline before worker request dispatch records no invented usage and ca
|
||||
});
|
||||
|
||||
test('a response exceeding the cumulative token allocation stops before registering or executing its tools', async t => {
|
||||
const { f, manager, group, requests } = await ready(t, { respond: async () => ({ message: { role: 'assistant', tool_calls: [call(randomUUID(), 'propose_file', { path: 'src/a.mjs', content: 'over budget', reason: 'fixture' })] }, usage: { total_tokens: 10001 } }) }, { ...workerDefinition(), budget: { maxTokens: 20000 } });
|
||||
// Keep the request sendable as the tool contract grows; exceed the same explicit
|
||||
// per-worker allocation by one reported token to exercise response accounting.
|
||||
const allocation = 20000;
|
||||
const { f, manager, group, requests } = await ready(t, { respond: async () => ({ message: { role: 'assistant', tool_calls: [call(randomUUID(), 'propose_file', { path: 'src/a.mjs', content: 'over budget', reason: 'fixture' })] }, usage: { total_tokens: allocation + 1 } }) }, { ...workerDefinition(), budget: { maxTokens: allocation * 2 } });
|
||||
await (await manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(group.status, 'paused', group.summary);
|
||||
for (const child of group.children) { const worker = f.store.core.worker.get(child.id); assert.equal(workerUsage(f.store, worker).accountedTokens, 10001); assert.equal(workerUsage(f.store, worker).toolCalls, 0); assert.equal(f.store.session(child.sessionId).changes.length, 0); }
|
||||
assert.equal(requests.length, 2, 'Both responses must actually be dispatched before testing their recorded usage.');
|
||||
for (const child of group.children) { const worker = f.store.core.worker.get(child.id); assert.equal(workerUsage(f.store, worker).accountedTokens, allocation + 1); assert.equal(workerUsage(f.store, worker).toolCalls, 0); assert.equal(f.store.session(child.sessionId).changes.length, 0); }
|
||||
await (await manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(requests.length, 2); assert.match(group.summary, /累计预算/);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user