feat(models): pair reasoning controls with provider profiles and tool history

This commit is contained in:
Agent Workbench Dev
2026-11-05 00:13:53 +08:00
parent 3ab3a6e46a
commit f1242ee800
22 changed files with 546 additions and 34 deletions
+29
View File
@@ -0,0 +1,29 @@
# 推理与能力配套:开发阶段验收
状态:源码已实现并验证,正式仍1.25.2;独立发行验收另记。本阶段真实模型请求0,未改正式连接、Provider或真实Key。来源为b74e5edc后的本地开发切片,先提交空响应修复3ab3a6e4。
用户要求推理可开启、选择强度,并与品牌或自定义兼容连接配套。模型中心现有入口改为“推理与能力”,新增一份共享配置档贯通自动匹配、手动覆盖、保存、导入、Run快照及实际请求。原JSON仍是同一份参数,可与控件双向编辑;其它参数、凭据引用、旧记录和池保持。导入保留推理字段、输出字段和能力声明,来源变更需重新预览,本地编辑冲突保留。
| 兼容格式 | 推理开关 | 强度 | 工具历史 |
| --- | --- | --- | --- |
| OpenAI Chat | reasoning_effort=none(需型号支持) | minimal/low/medium/high/xhigh/max | 既有工具调用 |
| OpenAI Responses | reasoning.effort=none(需型号支持) | minimal/low/medium/high/xhigh/max | 既有原生reasoning/encrypted items |
| Claude Messages | disabled / enabled+budget_tokens / adaptive | output_config.effort=low/medium/high/xhigh/max | 保留原thinking/signature块 |
| DeepSeek Chat | thinking.type=enabled/disabled | reasoning_effort=low/high/max | JSON/SSE的reasoning_content只回传原endpoint/model/连接/凭据修订 |
| 自定义代理 | 用户选择上述兼容格式 | 按所选格式 | 与对应协议一致 |
格式接入不能证明具体型号或代理接受全部值。界面保留声明支持/已验证/待确认区别,并列出未接入的音视频、服务端工具和结构化输出约束。/models通常只提供型号,不会被当完整能力目录。后续能力接入继续走同一份契约与验收,不把“品牌配套”写成所有模型功能均已验证。
推理和答复共用原输出预算。Messages指定预算至少1024且小于实际输出上限,普通256检测不够时使用已有任务/连接输出上限的较小值,并在界面说明消费;不自动增加预算。Chat opaque历史的实际字节进入请求预算,不作为可见答复或进展评分。
完整但无文字/工具的Messages JSON/SSE明确protocol错误,空数组/空白/仅thinking均不当完成;忠实复现6692输入/0输出,原文SHA、用量与身份保持,0工具/重试,避免误报“检查未完成”。这项修复不能使供应商空响应变为成功。
## 实际验证
- Messages专项28/28,新增空响应JSON/SSE原文和6692/0用量核对。
- 模型中心/参数/流式/Messages/推理相关85/85;补旧Run冻结、原连接重开及凭据引用保持后推理专项8/8。首联合夹具清理挂起和单项超时保持,修fixture清理次序后通过。
- TypeScript/Vite/mobile/server构建通过;首缺契约声明失败保留。
- 新推理网页6组、实际Electron6组(各9自有HTTP请求、0真实模型),1440/390px保存/刷新/默认/关闭/开启/强度/手动预算/JSON错误/保护字段/空响应反馈通过,原图实际回看。
- 旧原生参数/上游错误网页6组、Messages网页7组通过;来源日志在.qa/reasoning-controls/,旧证据目录未写入。
阶段回顾:已修本地参数、状态回传与诊断缺口,尚未证明真实供应商稳定、自主Node交付、网络间歇唯一根因、重复读取收益或Purge AB/BA。Z3原空响应、DeepSeek原length、全部旧失败及预算保持,不续跑旧实验、不推送、不委派。下一独立版本冻结、归档重建/实际安装及保留状态升级。
+2
View File
@@ -15,3 +15,5 @@
- 起步:读取AGENTS与两份采用计划,确认现有表单只有JSON;Chat尚不接受thinking,Messages已有thinking历史但没有output_config.effort;Chat流式/历史路径待核对。一次猜测不存在的chat-stream.mjs读取失败,无文件变化,后续用rg定位。
- 阶段一通过:Messages JSON/SSE真实本机HTTP复现空响应,原6692输入/0输出完整保留,单次protocol错误、0工具/重发。空数组、空白与仅opaque thinking拒绝,合法文字/工具保留;Messages相关28/28通过,日志.qa/reasoning-controls/messages-tests.txt。修复尚未部署。
- 官方来源:DeepSeek既有Thinking Mode原HTML保持;OpenAI Docs查阅Chat与reasoning-effort;Claude文档重定向地区不可用页,已保存原失败,随后官方SDK原始类型取得HTTP200,确认output_config.effort支持low/medium/high/xhigh/max。一次node_repl网络等待超时、几次不存在的可选路径读取错误均无产品影响,后续改curl有界及已有实际文件定位。
- 阶段二:参数配置档、可视推理设置、导入同步、所属Chat opaque状态回传/流式聚合及原预算约束已实现。相关85/85,补充冻结/旧连接恢复后专项8/8;完整构建通过。网页与真实Electron各6组、原参数错误UI6组/Messages UI7组通过;1440/390原图已回看。新控件未读取Key,保存本身不发请求,HTTP夹具均自有。
- 首失败保留:首构建缺新共享契约声明,补d.mts后通过;首联合测试在新增重开SQLite夹具清理时挂起(reopened用t.after,夹具先删目录),有界单项诊断超时与所属测试进程终止保留。改用fixture.onCleanup先关数据库,不改产品断言/期限;随后专项/相关全部通过。一次对整个.qa的递归定位过慢,停止所属rg,改为已有发行目录的有界定位。
+2
View File
@@ -2,6 +2,8 @@
## 推理控制与空响应修复
- 配置档/可视推理/导入和Run冻结/Chat原生状态回传实现;85/85相关+最终8/8专项,构建通过。网页/实际Electron各6组及旧参数6组/Messages7组通过,1440/390原图回看。首构建声明缺失、重开DB夹具清理超时和所属进程终止保留,修清理顺序后通过。正式仍1.25.2,待独立发行。见docs/QA-REASONING-CONTROLS.md。
- 阶段一:Messages空响应诊断与JSON/SSE原6692/0用量回归28/28通过;用户补充品牌/自定义兼容的整套能力同步,纳入版本化参数配置档/导入/请求/界面与能力状态说明。正式尚未变更,真实请求0。
- b74e5edc干净接续。用户明确补充推理可开启/选择强度,扩展原disabled单项范围;沿用product-ui-ux/frontend-design/planning-with-files,查官方参数和工具历史。一次不存在的chat-stream.mjs读取失败已记计划,后续rg定位。正式仍1.25.2,本阶段不发真实模型请求。
+1 -1
View File
@@ -75,7 +75,7 @@ try {
await card.getByRole('button', { name: '用于新任务', exact: true }).click(); assert.equal(requests.length, 0); await page.reload(); await open();
await expect(dialog().getByLabel('新任务默认模型', { exact: true })).toHaveValue('connection:' + connection.id); await shot('narrow-saved');
mark('saved protocol, auth and selected connection survive reload and remain operable at 390px');
await page.setViewportSize({ width: 1440, height: 1000 }); await card.getByRole('button', { name: '原生参数', exact: true }).click();
await page.setViewportSize({ width: 1440, height: 1000 }); await card.getByRole('button', { name: '推理与能力', exact: true }).click();
const native = dialog().getByRole('form', { name: '原生请求参数', exact: true }); await expect(native.getByLabel('输出上限字段')).toHaveValue('max_tokens');
await expect(native.getByLabel('输出上限字段').locator('option')).toHaveCount(1); await native.getByLabel('原生参数 JSON').fill('{"reasoning_effort":"high"}');
await native.getByRole('button', { name: '保存原生参数', exact: true }).click(); await expect(native.getByRole('alert')).toContainText('尚未接入');
+2 -2
View File
@@ -47,12 +47,12 @@ try {
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', error => errors.push(error.message)); await page.goto(host.url); await page.getByLabel('当前项目').selectOption(f.project.id);
let dialog = await openCenter(); const card = dialog.locator('.mc-connection').filter({ has: page.getByRole('heading', { name: 'Owned UI 模型', exact: true }) });
await card.getByRole('button', { name: '原生参数', exact: true }).click();
await card.getByRole('button', { name: '推理与能力', exact: true }).click();
await page.getByLabel('原生参数 JSON', { exact: true }).fill('{"reasoning_effort":"high","temperature":0.4,"parallel_tool_calls":false}');
await page.getByLabel('输出上限字段', { exact: true }).selectOption('max_completion_tokens');
await page.getByRole('button', { name: '保存原生参数', exact: true }).click(); await expect(dialog.getByRole('status')).toContainText('原生参数已保存');
assert.equal(requests.length, 0); await page.reload(); dialog = await openCenter();
await dialog.locator('.mc-connection').filter({ has: page.getByRole('heading', { name: 'Owned UI 模型', exact: true }) }).getByRole('button', { name: '原生参数', exact: true }).click();
await dialog.locator('.mc-connection').filter({ has: page.getByRole('heading', { name: 'Owned UI 模型', exact: true }) }).getByRole('button', { name: '推理与能力', exact: true }).click();
await expect(page.getByLabel('原生参数 JSON', { exact: true })).toContainText('reasoning_effort');
await capture('native-desktop'); await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole('button', { name: '保存原生参数', exact: true }).scrollIntoViewIfNeeded();
+146
View File
@@ -0,0 +1,146 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import http from 'node:http';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
const desktop = process.argv.includes('--desktop'), appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.');
assert.ok(process.argv.slice(2).every(value => value === '--desktop'));
const directory = path.resolve('.qa/reasoning-controls', (desktop ? 'electron-' : 'web-') + randomUUID()); fs.mkdirSync(directory, { recursive: true });
console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t); f.store.close();
const requests = [], checks = [], screenshots = [], errors = []; let empty = false;
const server = http.createServer(async (req, res) => {
const parts = []; for await (const part of req) parts.push(part); const body = JSON.parse(Buffer.concat(parts)); requests.push({ route: req.url, body });
const usage = { input_tokens: 338, cache_creation_input_tokens: 331, cache_read_input_tokens: 6023, output_tokens: 0 };
if (req.url.endsWith('/messages')) {
const value = { id: 'msg_owned', type: 'message', role: 'assistant', model: body.model, content: empty ? [] : [{ type: 'text', text: 'OK' }], stop_reason: 'end_turn', usage: empty ? usage : { input_tokens: 20, output_tokens: 1 } };
if (body.stream) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
const event = (type, fields = {}) => 'event: ' + type + '\ndata: ' + JSON.stringify({ type, ...fields }) + '\n\n';
res.end(event('message_start', { message: { ...value, content: [], stop_reason: null } }) + event('message_delta', { delta: { stop_reason: 'end_turn' }, usage }) + event('message_stop'));
} else { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(value)); }
} else if (req.url.endsWith('/responses')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 'resp_owned', model: body.model, status: 'completed', output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'OK' }] }], usage: { input_tokens: 20, output_tokens: 1 } }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ model: body.model, choices: [{ message: { role: 'assistant', content: 'OK' }, finish_reason: 'stop' }], usage: { prompt_tokens: 20, completion_tokens: 1 } }));
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let browser, application, controller, host, page, window, result;
const mark = name => { checks.push(name); console.log('PASS ' + name); };
const dialog = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const form = () => page.getByRole('form', { name: '原生请求参数', exact: true });
async function resize(width, height) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
else await page.setViewportSize({ width, height });
}
async function shot(name) {
const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' });
screenshots.push({ path: file, sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex') });
fs.writeFileSync(path.join(directory, name + '.txt'), await page.locator('body').innerText());
}
async function edit(name) {
if (!await dialog().count()) await page.getByRole('button', { name: '打开模型中心', exact: true }).click();
await dialog().locator('.mc-connection').filter({ has: page.getByRole('heading', { name, exact: true }) }).getByRole('button', { name: '推理与能力', exact: true }).click();
await form().waitFor();
}
async function save() {
await form().getByRole('button', { name: '保存原生参数', exact: true }).click();
await expect(form()).toHaveCount(0); await expect(dialog().getByRole('status')).toContainText('原生参数已保存');
}
async function current(id) { return (await host.api('/model-center')).connections.find(c => c.id === id); }
async function probe(member) { await host.api('/model-center/probe', { id: member.id, scope: 'text' }); return requests.at(-1).body; }
try {
if (desktop) {
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
host = { api: (route, input) => controller.api(route, input ? { method: 'POST', input } : {}), bootstrap: await controller.api('/bootstrap') };
const executable = desktopExecutableIdentity(appRoot).path;
application = await _electron.launch({ executablePath: executable, args: [...(executable.toLowerCase().endsWith('agentworkbench.exe') ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]),
'--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive()); await resize(1440, 1080);
} else {
host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1080 } }); await page.goto(host.url);
}
page.on('pageerror', error => errors.push(error.message));
const baseUrl = 'http://127.0.0.1:' + server.address().port + '/v1';
const members = [];
for (const [name, protocol, model] of [['自定义兼容线路', 'chat-completions', 'owned-custom'], ['Responses 线路', 'responses', 'owned-responses'], ['Claude 线路', 'anthropic-messages', 'owned-claude']]) {
members.push(await host.api('/model-center/connections', { name, protocol, model, baseUrl, brand: '自定义', requiresKey: false }));
}
await page.reload(); await page.locator('.connection.connected').waitFor();
await edit(members[0].name); await expect(form().getByLabel('推理模式', { exact: true })).toHaveValue('default');
await form().getByLabel('原生参数 JSON', { exact: true }).fill('{"temperature":0.4,"seed":3}');
await form().getByLabel('参数配置档', { exact: true }).selectOption('deepseek'); await form().getByLabel('推理模式', { exact: true }).selectOption('enabled');
await form().getByLabel('推理强度', { exact: true }).selectOption('low'); await save();
assert.equal(requests.length, 0); await page.reload(); await edit(members[0].name);
await expect(form().getByLabel('参数配置档', { exact: true })).toHaveValue('deepseek'); await expect(form().getByLabel('推理模式', { exact: true })).toHaveValue('enabled');
await expect(form().getByLabel('推理强度', { exact: true })).toHaveValue('low');
await form().getByText('推理设置', { exact: true }).scrollIntoViewIfNeeded(); await shot('deepseek-desktop');
assert.deepEqual((await current(members[0].id)).nativeParameters, { temperature: 0.4, seed: 3, thinking: { type: 'enabled' }, reasoning_effort: 'low' });
mark('custom-compatible profile and enabled/low controls save and reload without requests or losing unrelated parameters');
await form().getByLabel('推理模式', { exact: true }).selectOption('disabled'); await expect(form().getByLabel('推理强度', { exact: true })).toBeDisabled(); await save();
let wire = await probe(members[0]); assert.deepEqual(wire.thinking, { type: 'disabled' }); assert.equal(wire.reasoning_effort, undefined);
await edit(members[0].name); await form().getByLabel('推理模式', { exact: true }).selectOption('enabled'); await form().getByLabel('推理强度', { exact: true }).selectOption('max'); await save();
wire = await probe(members[0]); assert.deepEqual(wire.thinking, { type: 'enabled' }); assert.equal(wire.reasoning_effort, 'max');
await edit(members[0].name); await form().getByLabel('推理模式', { exact: true }).selectOption('default'); await save();
wire = await probe(members[0]); assert.equal(wire.thinking, undefined); assert.equal(wire.reasoning_effort, undefined); assert.equal(wire.seed, 3);
mark('DeepSeek off/on/max/default reach actual HTTP with no stale fields and preserve the original output reservation');
await edit(members[0].name); await form().getByLabel('原生参数 JSON', { exact: true }).fill('{"reasoning_effort":"high","seed":3}');
await expect(form().getByLabel('推理强度', { exact: true })).toHaveValue('high');
await form().getByLabel('原生参数 JSON', { exact: true }).fill('{'); await expect(form().getByLabel('推理模式', { exact: true })).toBeDisabled();
await form().getByLabel('原生参数 JSON', { exact: true }).fill('{"tools":[]}'); await form().getByRole('button', { name: '保存原生参数', exact: true }).click();
await expect(form().getByRole('alert')).toContainText('尚未接入原生参数:tools'); assert.equal(requests.length, 3); await shot('invalid-json');
await form().getByLabel('原生参数 JSON', { exact: true }).fill('{"seed":3}'); await form().getByLabel('参数配置档', { exact: true }).selectOption('openai');
await form().getByLabel('推理模式', { exact: true }).selectOption('enabled'); await form().getByLabel('推理强度', { exact: true }).selectOption('medium'); await save();
wire = await probe(members[0]); assert.equal(wire.reasoning_effort, 'medium'); assert.equal(wire.thinking, undefined);
mark('JSON and controls edit one value; malformed JSON and protected fields fail visibly; changing custom dialect uses the matching wire format');
await edit(members[1].name); await form().getByLabel('推理强度', { exact: true }).selectOption('max'); await save(); wire = await probe(members[1]);
assert.deepEqual(wire.reasoning, { effort: 'max' }); assert.equal(wire.reasoning_effort, undefined);
await edit(members[1].name); await form().getByLabel('推理模式', { exact: true }).selectOption('disabled'); await save(); wire = await probe(members[1]); assert.deepEqual(wire.reasoning, { effort: 'none' });
mark('Responses strength and disable controls send reasoning.effort using their own protocol');
await edit(members[2].name); await form().getByLabel('推理模式', { exact: true }).selectOption('adaptive'); await form().getByLabel('推理强度', { exact: true }).selectOption('high'); await save();
wire = await probe(members[2]); assert.deepEqual(wire.thinking, { type: 'adaptive' }); assert.deepEqual(wire.output_config, { effort: 'high' });
await edit(members[2].name); await form().getByLabel('推理模式', { exact: true }).selectOption('enabled'); await form().getByLabel('推理预算 tokens', { exact: true }).fill('1024'); await save();
const manual = await current(members[2].id); assert.deepEqual(manual.nativeParameters.thinking, { type: 'enabled', budget_tokens: 1024 });
wire = await probe(members[2]); assert.deepEqual(wire.thinking, { type: 'enabled', budget_tokens: 1024 }); assert.equal(wire.max_tokens, 2048);
await page.reload(); await edit(members[2].name); await expect(form().getByLabel('推理预算 tokens', { exact: true })).toHaveValue('1024');
await resize(390, 844); await form().getByLabel('推理强度', { exact: true }).scrollIntoViewIfNeeded(); await shot('messages-390');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true);
await form().getByText('查看接口能力与接入范围', { exact: true }).click(); await form().locator('table').scrollIntoViewIfNeeded(); await shot('features-390');
await expect(form().locator('table')).toContainText('尚未接入'); await expect(form().locator('table')).toContainText('待确认');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true);
await form().getByRole('button', { name: '保存原生参数', exact: true }).scrollIntoViewIfNeeded(); const bounds = await form().getByRole('button', { name: '保存原生参数', exact: true }).boundingBox();
assert.ok(bounds && bounds.x >= 0 && bounds.x + bounds.width <= 391); await save();
mark('Messages adaptive/effort and manual budget persist; 390px controls, capability scope and save action remain readable and usable');
await resize(1440, 1080); await page.keyboard.press('Escape');
await host.api('/model-center/native-parameters', { id: manual.id, revision: (await current(manual.id)).revision, parameterProfile: 'anthropic', nativeParameters: { thinking: { type: 'disabled' } } });
const selected = await current(manual.id); await host.api('/model-center/connections', { ...selected, streaming: true, capabilityDeclarations: { ...selected.capabilityDeclarations, streaming: 'supported' } });
await host.api('/model-center/select', { type: 'connection', id: selected.id }); empty = true; await page.reload();
await page.getByLabel('当前项目').selectOption(f.project.id); await page.getByLabel('任务内容').fill('检查当前工程,保留实际失败。'); await page.getByRole('button', { name: '发送任务', exact: true }).click();
let failed; await until(async () => { const rows = await host.api('/sessions'); const row = rows.find(s => s.title === '检查当前工程,保留实际失败。'); failed = row && await host.api('/sessions/' + row.id); return failed?.status === 'failed'; }, 15000);
assert.equal(failed.failure.kind, 'protocol'); assert.match(failed.failure.message, /返回为空/); assert.equal(failed.execution.run.usage.totalTokens, 6692);
await expect(page.locator('.failure-card').last()).toContainText('返回为空'); await shot('empty-response-desktop'); await resize(390, 844); await page.locator('.failure-card').last().scrollIntoViewIfNeeded(); await shot('empty-response-390');
assert.equal(failed.execution.run.usage.requests, 1); assert.equal(failed.changes.length, 0); assert.equal(requests.length, 9);
mark('actual Messages empty SSE is diagnosed explicitly in the task at both widths with 6692/0 use, zero tools and one request');
assert.deepEqual(errors, []); fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
result = { success: true, version: host.bootstrap.version, appRoot, actualElectron: desktop, checks, screenshots, errors, syntheticRequests: requests.length, realModelRequests: 0, 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 new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }); 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;
+1
View File
@@ -25,3 +25,4 @@
.mc-route-control{margin-bottom:24px;padding:18px 20px;background:#fff;border:1px solid #b8cadb;border-left:3px solid #2560a3;border-radius:6px;min-width:0}.mc-route-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:14px}.mc-route-heading h3{font-size:15px;margin-bottom:5px}.mc-route-heading p,.mc-route-detail{font-size:12px;color:#4b6078;line-height:1.7;overflow-wrap:anywhere}.mc-route-heading>.button{flex-shrink:0}.mc-route-select{display:flex;gap:12px;align-items:center;font-size:12px;color:#425974}.mc-route-select select{min-width:0;flex:1;width:100%;min-height:42px;border:1px solid #a7bbcf;border-radius:5px;background:#fff;padding:10px;color:#15283f;font-size:13px}.mc-route-detail{margin-top:9px}.mc-run-model{display:flex;flex-wrap:wrap;gap:6px 12px;border-top:1px solid #dce4eb;margin-top:13px;padding-top:12px;font-size:12px;line-height:1.7;overflow-wrap:anywhere}.mc-run-model strong{color:#344c67}.mc-run-model span{color:#405670}.mc-run-model small{width:100%;color:#566b81;font-size:11px}.mc-route-select select:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
@media(max-width:620px){.mc-route-control{padding:14px}.mc-route-heading{align-items:flex-start;gap:10px}.mc-route-heading p{font-size:11px}.mc-route-heading>.button{padding:8px;font-size:11px}.mc-route-select{align-items:stretch;flex-direction:column;gap:7px}.mc-route-select select{font-size:12px}.mc-run-model{display:block}.mc-run-model strong,.mc-run-model span,.mc-run-model small{display:block}.mc-run-model span{margin-top:4px}}
.mc-request-url { overflow-wrap: anywhere; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; }
.mc-reasoning .mc-form-grid{margin-top:12px}.mc-reasoning .mc-help{color:#40566e;font-size:12px}.mc-feature-scope{font-size:12px;line-height:1.7;margin:12px 0;overflow-wrap:anywhere}.mc-feature-scope summary{cursor:pointer;color:#245b92;padding:8px 0;min-height:40px}.mc-feature-scope table{width:100%;table-layout:fixed;border-collapse:collapse;margin-top:10px}.mc-feature-scope th,.mc-feature-scope td{text-align:left;vertical-align:top;border-bottom:1px solid #d3dde7;padding:9px 7px;font-size:12px;color:#40566e}.mc-feature-scope th{font-weight:600}.mc-reasoning input:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
+4 -4
View File
@@ -14,7 +14,7 @@ import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
type Connection = { id: string; name: string; brand: string; protocol: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
type Connection = { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
@@ -34,7 +34,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; messagesAuth?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
@@ -122,13 +122,13 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>原生参数</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>推理与能力</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{nativeTarget && <NativeParameters key={nativeTarget.id + ":" + nativeTarget.revision} connection={nativeTarget} busy={locked} onCancel={() => setNativeTarget(null)} onSave={async input => { await act(async () => { const result = await api<{ config: Config }>("/model-center/native-parameters", input); if (alive.current) { onConfig(result.config); setNativeTarget(null); setNotice("原生参数已保存;新任务按所选协议发送,旧请求保持原记录。"); } }); }} />}{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, modelIdentityAliases: draft.modelIdentityAliasesText.split(',').map(v=>v.trim()).filter(Boolean), ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value, nativeParameters: {}, outputTokenField: undefined })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value, parameterProfile: 'auto', nativeParameters: {}, outputTokenField: undefined })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label>视觉能力<select aria-label="视觉能力" value={draft.capabilityDeclarations.vision} onChange={event=>setDraft({...draft,capabilityDeclarations:{...draft.capabilityDeclarations,vision:event.target.value}})}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
+20 -5
View File
@@ -1,25 +1,40 @@
import { useEffect, useRef, useState } from 'react';
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
import { changeReasoningSetting, modelParameterProfile, reasoningSetting } from '../shared/contracts/model-parameter-profiles.mjs';
import { ReasoningSettings } from './ReasoningSettings';
export type NativeConnection = { id: string; revision: number; name: string; protocol: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string };
export type NativeConnection = { id: string; revision: number; name: string; protocol: string; model?: string; brand?: string; baseUrl?: string; parameterProfile?: string; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; nativeParameters?: Record<string, unknown>; outputTokenField?: string };
export function NativeParameters({ connection, busy, onCancel, onSave }: { connection: NativeConnection; busy: boolean; onCancel: () => void;
onSave: (input: { id: string; revision: number; nativeParameters: Record<string, unknown>; outputTokenField: string }) => Promise<void> }) {
onSave: (input: { id: string; revision: number; nativeParameters: Record<string, unknown>; outputTokenField: string; parameterProfile?: string }) => Promise<void> }) {
const [text, setText] = useState(JSON.stringify(connection.nativeParameters ?? {}, null, 2));
const [field, setField] = useState(connection.outputTokenField ?? (connection.protocol === 'responses' ? 'max_output_tokens' : 'max_tokens'));
const [error, setError] = useState('');
const [profile, setProfile] = useState(connection.parameterProfile ?? 'auto');
let parameters: Record<string, unknown> | null = null;
try { const parsed = JSON.parse(text); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) parameters = parsed; } catch { /* The original editor content remains editable. */ }
const updateParameters = (value: Record<string, unknown>) => { setText(JSON.stringify(value, null, 2)); setError(''); };
const form = useRef<HTMLFormElement>(null);
useEffect(() => { form.current?.scrollIntoView({ block: 'nearest' }); }, []);
return <form ref={form} className="mc-editor mc-native" aria-label="原生请求参数" onSubmit={async event => {
event.preventDefault(); setError('');
try { const settings = nativeParameterSettings(connection.protocol, JSON.parse(text), field); await onSave({ id: connection.id, revision: connection.revision, ...settings }); }
try { const settings = nativeParameterSettings(connection.protocol, JSON.parse(text), field, profile); await onSave({ id: connection.id, revision: connection.revision, ...settings }); }
catch (cause) { setError(cause instanceof Error ? cause.message : '参数格式无效。'); }
}}>
<h3>{connection.name} · 原生请求参数</h3>
<h3>{connection.name} · 推理与原生参数</h3>
<p className="mc-help">参数按所选协议原字段发送,并封存在实际请求中。具体模型是否接受这些选项,以服务响应为准;未填写的选项采用上游默认值。</p>
<ReasoningSettings connection={connection} parameters={parameters} profile={profile} busy={busy} onChange={updateParameters} onProfile={value => {
if (parameters) {
const before = { ...connection, parameterProfile: profile }, after = { ...connection, parameterProfile: value };
if (modelParameterProfile(before).thinking !== modelParameterProfile(after).thinking) {
updateParameters(changeReasoningSetting(after, parameters, 'mode', reasoningSetting(before, parameters).mode));
}
}
setProfile(value);
}} />
<label>输出上限字段<select aria-label="输出上限字段" value={field} disabled={busy} onChange={event => setField(event.target.value)}>{(connection.protocol === 'responses' ? ['max_output_tokens'] : connection.protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).map(value => <option key={value}>{value}</option>)}</select></label>
<p className="mc-help">数值沿用当前任务和连接的输出预算,不允许原生参数覆盖预算、消息、工具或接口。</p>
<label>原生参数 JSON<textarea aria-label="原生参数 JSON" rows={7} maxLength={8192} spellCheck={false} value={text} disabled={busy} onChange={event => setText(event.target.value)} /></label>
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? '已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking。启用 thinking 时 budget_tokens 至少1024且小于本次输出预算;具体型号支持情况以上游响应为准。' : connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity。'}其他字段保存时会给出具体提示。语音、视频和服务端内置工具尚未接入。</p>
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? '已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking、output_config.effort。' : connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity、DeepSeek thinking。'}推理控件与 JSON 编辑同一份参数,其他字段保存时会给出具体提示。</p>
{error && <p className="mc-card-warning" role="alert">{error}</p>}
<div className="mc-actions"><button className="button secondary" type="button" disabled={busy} onClick={onCancel}>取消</button><button className="button primary" disabled={busy} type="submit">保存原生参数</button></div>
</form>;
+40
View File
@@ -0,0 +1,40 @@
import { changeReasoningSetting, modelFeatureRows, modelParameterProfile, parameterProfiles, reasoningSetting } from '../shared/contracts/model-parameter-profiles.mjs';
import type { NativeConnection } from './NativeParameters';
const effortLabels: Record<string, string> = { minimal: '最低', low: '低', medium: '中', high: '高', xhigh: '很高', max: '最高' };
export function ReasoningSettings({ connection, parameters, profile, busy, onProfile, onChange }: {
connection: NativeConnection; parameters: Record<string, unknown> | null; profile: string; busy: boolean;
onProfile: (value: string) => void; onChange: (value: Record<string, unknown>) => void;
}) {
const configured = { ...connection, parameterProfile: profile }, resolved = modelParameterProfile(configured);
const setting = reasoningSetting(configured, parameters ?? {}), disabled = busy || !parameters;
const change = (field: string, value: string | number) => { if (parameters) onChange(changeReasoningSetting(configured, parameters, field, value)); };
const efforts = [...new Set([...resolved.efforts, ...(setting.effort ? [setting.effort] : [])])];
return <fieldset className="mc-reasoning">
<legend>推理设置</legend>
<div className="mc-form-grid">
<label>参数配置档<select aria-label="参数配置档" value={profile} disabled={disabled} onChange={event => onProfile(event.target.value)}>
{parameterProfiles(connection.protocol).map(value => <option key={value.id} value={value.id}>{value.label}</option>)}
</select></label>
<label>推理模式<select aria-label="推理模式" value={setting.mode} disabled={disabled} onChange={event => change('mode', event.target.value)}>
<option value="default">跟随模型默认</option><option value="disabled">关闭推理</option>
<option value="enabled">{connection.protocol === 'anthropic-messages' ? '开启 · 指定推理预算' : '开启推理'}</option>
{connection.protocol === 'anthropic-messages' && <option value="adaptive">开启 · 自适应推理</option>}
</select></label>
<label>推理强度<select aria-label="推理强度" value={setting.effort} disabled={disabled || setting.mode === 'disabled'} onChange={event => change('effort', event.target.value)}>
<option value="">跟随模型默认</option>{efforts.map(value => <option key={value} value={value}>{effortLabels[value] ?? value}({value})</option>)}
</select></label>
{connection.protocol === 'anthropic-messages' && setting.mode === 'enabled' && <label>推理预算 tokens<input aria-label="推理预算 tokens" type="number" min={1024} step={1} value={setting.budget} disabled={disabled} onChange={event => change('budget', Number(event.target.value))} /></label>}
</div>
<p className="mc-help">当前格式:{resolved.label}。{resolved.source}。自定义代理可按实际兼容格式选择配置档,保存后用于新任务。</p>
<p className="mc-help">强度越高通常需要更多时间和输出 tokens;推理与最终答复共用原输出预算。具体型号支持的开关和档位以上游为准,设置不会自动提高预算。</p>
{connection.protocol === 'anthropic-messages' ? <p className="mc-help">指定预算至少 1024 tokens,且须小于本次任务实际输出上限。指定预算的能力检测使用当前输出上限,会消耗模型额度;自适应模式与强度需服务支持。</p>
: resolved.id === 'deepseek' && connection.protocol === 'chat-completions' ? <p className="mc-help">DeepSeek 使用 thinking 开关与 low / high / max 强度;工具往返携带对应的原生推理状态。</p>
: <p className="mc-help">关闭推理发送 none,仅适用于接受该值的型号;GPT-6.1 Sol 不支持 none / minimal。可选择受支持的强度或保留默认。</p>}
{!parameters && <p className="mc-card-warning">请先修正下方 JSON,推理控件会同步恢复。</p>}
<details className="mc-feature-scope"><summary>查看接口能力与接入范围</summary>
<p>品牌、型号与模型列表用于匹配配置,能力声明和单项检测结果按原来源保留。型号列表通常不包含完整功能元数据。</p>
<table><thead><tr><th>功能</th><th>接口能力</th><th>本地接入</th></tr></thead><tbody>{modelFeatureRows(connection).map(row => <tr key={row.name}><th scope="row">{row.name}</th><td>{row.upstream}</td><td>{row.local}</td></tr>)}</tbody></table>
</details>
</fieldset>;
}
+7 -1
View File
@@ -7,6 +7,7 @@ import { parse as parseToml } from 'smol-toml';
import { modelEndpoint } from './model-hub.mjs';
import { MODEL_PROTOCOLS } from '../../shared/contracts/model-capabilities.mjs';
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs';
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
export class ConfigImporter {
@@ -30,6 +31,9 @@ export class ConfigImporter {
if (item.protocol && !MODEL_PROTOCOLS.includes(item.protocol)) { notices.push('第' + (index + 1) + '项协议暂不支持,已跳过。'); continue; }
rows.push({ sourceId: String(item.id ?? index), name: item.name, model: item.model, protocol: item.protocol ?? 'chat-completions',
streaming: item.streaming === true, capabilityDeclarations: item.capabilityDeclarations,
...(item.nativeParameters !== undefined ? { nativeParameters: item.nativeParameters } : {}),
...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}),
...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}),
...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}),
baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
}
@@ -59,7 +63,9 @@ export class ConfigImporter {
try {
if (!String(row.model ?? '').trim() || !String(row.name ?? '').trim()) throw new Error('缺少名称或模型');
if (row.apiKey !== undefined && typeof row.apiKey !== 'string') throw new Error('凭据不是字符串');
entries.push({ ...row, ...messagesAuthSettings(row.protocol, row.messagesAuth), name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: validateProtocolEndpoint(row.protocol, modelEndpoint(row.baseUrl)),
const native = row.nativeParameters !== undefined || row.outputTokenField !== undefined || row.parameterProfile !== undefined
? nativeParameterSettings(row.protocol, row.nativeParameters ?? {}, row.outputTokenField, row.parameterProfile) : {};
entries.push({ ...row, ...native, ...messagesAuthSettings(row.protocol, row.messagesAuth), name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: validateProtocolEndpoint(row.protocol, modelEndpoint(row.baseUrl)),
origin: digest({ source, path: path.resolve(filename), id: row.sourceId }), apiKey: row.apiKey?.trim() ?? '' });
} catch { notices.push(String(row.name ?? '某项配置').slice(0, 100) + '缺少有效的接口或模型,已跳过。'); }
}
+13 -6
View File
@@ -81,6 +81,7 @@ export class ModelHub {
return [{ id: legacyId, name: '原模型连接', brand: '兼容服务', protocol: 'chat-completions', baseUrl: this.store.config.baseUrl,
model: this.store.config.model, enabled: true, requiresKey: false, revision: this.store.config.configRevision ?? 1,
contextLimit: this.store.config.contextLimit, maxOutputTokens: this.store.config.maxOutputTokens, concurrency: 1, source: 'legacy',
...(this.store.config.parameterProfile ? { parameterProfile: this.store.config.parameterProfile } : {}),
...(this.store.config.nativeParameters ? { nativeParameters: this.store.config.nativeParameters, outputTokenField: this.store.config.outputTokenField } : {}) }, ...this.state.connections];
}
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: this.provider.legacyCredentialRevision ?? 1 } : this.provider.credentials.get(connection.id); }
@@ -143,8 +144,12 @@ export class ModelHub {
const nonce = randomUUID(), tools = scope === 'tools' ? [{ type: 'function', function: { name: 'workbench_capability_echo',
description: 'Return the provided nonce in this capability test. No files or commands are available.',
parameters: { type: 'object', properties: { nonce: { type: 'string' } }, required: ['nonce'], additionalProperties: false } } }] : [];
// A manual Messages thinking budget cannot fit the ordinary 256-token
// probe. Keep the chosen parameters and the user's existing output caps.
const probeOutput = connection.protocol === 'anthropic-messages' && connection.nativeParameters?.thinking?.type === 'enabled'
? Math.min(this.store.config.maxOutputTokens, connection.maxOutputTokens) : 256;
const config = { ...this.store.config, mode: 'compatible', model: connection.model, baseUrl: connection.baseUrl,
protocol: modelProtocol(connection.protocol), maxOutputTokens: 256, capabilityProbe: true, modelRouting: { type: 'connection', id: connection.id, revision: connection.revision,
protocol: modelProtocol(connection.protocol), maxOutputTokens: probeOutput, capabilityProbe: true, modelRouting: { type: 'connection', id: connection.id, revision: connection.revision,
strategy: 'round-robin', sticky: false, maxAttempts: 1, queueTimeoutMs: 1000, members: [member] } };
const visual=scope==='vision'?visionProbe():null;
if(visual)config.inputImages=[visual.image];
@@ -179,8 +184,8 @@ export class ModelHub {
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
const protocol = modelProtocol(input.protocol ?? previous?.protocol ?? 'chat-completions');
const native = Object.hasOwn(input, 'nativeParameters') || Object.hasOwn(input, 'outputTokenField') || previous?.nativeParameters
? nativeParameterSettings(protocol, input.nativeParameters ?? previous?.nativeParameters ?? {}, input.outputTokenField ?? previous?.outputTokenField) : null;
const native = Object.hasOwn(input, 'nativeParameters') || Object.hasOwn(input, 'outputTokenField') || Object.hasOwn(input, 'parameterProfile') || previous?.nativeParameters || previous?.parameterProfile
? nativeParameterSettings(protocol, input.nativeParameters ?? previous?.nativeParameters ?? {}, input.outputTokenField ?? previous?.outputTokenField, input.parameterProfile ?? previous?.parameterProfile) : null;
const declarations = capabilityDeclarations(input.capabilityDeclarations, previous?.capabilityDeclarations);
if (input.streaming !== undefined && typeof input.streaming !== 'boolean') throw error('流式选项必须为开启或关闭。');
const streaming = input.streaming ?? previous?.streaming ?? false;
@@ -210,7 +215,7 @@ export class ModelHub {
setNativeParameters(input) {
const connection = this.connection(input.id);
if (connection.revision !== input.revision) throw error('连接已变化,请刷新后核对原生参数。', 409);
const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField);
const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField, input.parameterProfile ?? connection.parameterProfile);
if (connection.id === legacyId) this.save(settings);
else this.upsert({ ...connection, ...settings });
return { center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } };
@@ -254,7 +259,8 @@ export class ModelHub {
credentialRevision: this.credential(this.connection(value.connectionId))?.revision ?? 0 }));
if (!members.some(value => this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。');
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile,
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
@@ -371,7 +377,8 @@ export class ModelHub {
if (event.stream) attempt.stream = event.stream;
onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, protocol: modelProtocol(member.protocol), model: member.model, modelAttemptId: attempt.id });
};
const result = await execute({ ...config, ...modelIdentitySettings(member), ...messagesAuthSettings(member.protocol, member.messagesAuth), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
const result = await execute({ ...config, ...modelIdentitySettings(member), ...messagesAuthSettings(member.protocol, member.messagesAuth), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true,
modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision }, credential?.key ?? '', actualBody, progress);
attempt.status = 'completed'; attempt.usage = result.usage ?? attempt.usage; attempt.usageStatus = attempt.usage ? 'reported' : 'unknown';
if (result.compatibility?.length) attempt.compatibility = result.compatibility;
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
+7 -2
View File
@@ -13,6 +13,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
let buffer = '', data = [], bytes = 0, frames = 0, sequence = -1, text = '', done = false, terminal = null, usage = null, finish = null;
let lastProgress = 0, responseId = null, validated = false, progressTimer = null, progressFailure = null;
let upstreamFailure = null;
let reasoning = '', hasReasoning = false;
const calls = new Map(), responseCalls = new Map();
const messages = config.protocol === 'anthropic-messages' ? messagesStream() : null;
let eventName = '';
@@ -85,7 +86,11 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (choice.index !== 0) throw protocolFailure('当前只接入单个Chat候选流。');
const delta = choice.delta;
if (!delta || typeof delta !== 'object') throw protocolFailure('Chat流缺少delta。');
if (finish && (delta.content || delta.tool_calls?.length)) throw protocolFailure('Chat流在完成后新增了内容。');
if (finish && (delta.content || delta.reasoning_content || delta.tool_calls?.length)) throw protocolFailure('Chat流在完成后新增了内容。');
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (typeof delta.reasoning_content !== 'string') throw protocolFailure('Chat推理状态片段格式无效。');
reasoning += delta.reasoning_content; hasReasoning = true;
}
if (delta.content !== undefined && delta.content !== null) {
if (typeof delta.content !== 'string') throw protocolFailure('Chat文本片段格式无效。'); text += delta.content;
}
@@ -151,7 +156,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
value = terminal;
} else {
if (!done || !['stop', 'tool_calls'].includes(finish)) throw protocolFailure('Chat流未完整终结或达到输出上限,未执行工具。', 'stream_interrupted');
value = { choices: [{ message: { role: 'assistant', content: text, ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
value = { choices: [{ message: { role: 'assistant', content: text, ...(hasReasoning ? { reasoning_content: reasoning } : {}), ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
}
validateModelResponse(config.protocol !== 'chat-completions' && config.protocol ? normalizeProtocolResponse(config, value) : value, tools);
validated = true; progress(true);
+10 -1
View File
@@ -73,7 +73,16 @@ export function normalizeProtocolResponse(config, value) {
providerState: { protocol: 'anthropic-messages', endpoint: config.baseUrl, model: config.model, responseId: value.id, content: structuredClone(value.content) } },
finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: reportedUsage(config, value) };
}
if (config.protocol !== 'responses') return value;
if (config.protocol !== 'responses') {
const received = value?.choices?.[0]?.message;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return value;
if (typeof received.reasoning_content !== 'string') throw protocolFailure('Chat reasoning_content必须为字符串,原响应未用于执行工具。');
const normalized = structuredClone(value), target = normalized.choices[0].message;
delete target.reasoning_content;
target.providerState = { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content };
return normalized;
}
if (value.status !== 'completed' || !Array.isArray(value.output)) throw protocolFailure('Responses未完整结束,原响应未用于执行工具。');
const calls = [], texts = [], ids = new Set();
for (const item of value.output) {
+1 -1
View File
@@ -12,7 +12,7 @@ export const DEFAULT_CONFIG = {
export function cleanConfig(value = {}) {
const result = { ...DEFAULT_CONFIG };
for (const key of Object.keys(result)) if (Object.hasOwn(value, key)) result[key] = value[key];
for (const key of ['nativeParameters', 'outputTokenField']) if (Object.hasOwn(value, key)) result[key] = structuredClone(value[key]);
for (const key of ['nativeParameters', 'outputTokenField', 'parameterProfile']) if (Object.hasOwn(value, key)) result[key] = structuredClone(value[key]);
return result;
}
+2
View File
@@ -25,6 +25,8 @@ export function modelSnapshot(config) {
...(config.protocol ? { protocol: config.protocol, streaming: config.streaming === true } : {}),
...(config.protocol === 'anthropic-messages' ? { messagesAuth: config.messagesAuth ?? 'api-key' } : {}),
...(config.nativeParameters ? { nativeParameters: structuredClone(config.nativeParameters), outputTokenField: config.outputTokenField } : {}),
...(config.parameterProfile ? { parameterProfile: config.parameterProfile } : {}),
...(config.modelConnectionId ? { modelConnectionId: config.modelConnectionId, modelCredentialRevision: config.modelCredentialRevision } : {}),
...(config.modelRouting ? { routing: structuredClone(config.modelRouting) } : {}),
};
}
@@ -0,0 +1,12 @@
export interface ParameterConnection {
protocol?: string; parameterProfile?: string; brand?: string; model?: string; baseUrl?: string;
nativeParameters?: Record<string, unknown>; capabilities?: Record<string, string>; capabilityDeclarations?: Record<string, string>;
}
export const reasoningEfforts: string[];
export const messagesEfforts: string[];
export function parameterProfiles(protocol: string): { id: string; label: string }[];
export function parameterProfileSettings(protocol: string, value?: string): string;
export function modelParameterProfile(connection: ParameterConnection): { id: string; label: string; source: string; efforts: string[]; thinking: boolean };
export function reasoningSetting(connection: ParameterConnection, parameters: Record<string, unknown>): { mode: string; effort: string; budget: number };
export function changeReasoningSetting(connection: ParameterConnection, parameters: Record<string, unknown>, field: string, value: string | number): Record<string, unknown>;
export function modelFeatureRows(connection: ParameterConnection): { name: string; upstream: string; local: string }[];
@@ -0,0 +1,69 @@
export const reasoningEfforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
export const messagesEfforts = ['low', 'medium', 'high', 'xhigh', 'max'];
const labels = { auto: '自动匹配', openai: 'OpenAI 兼容', anthropic: 'Claude Messages 兼容', deepseek: 'DeepSeek 兼容' };
export function parameterProfiles(protocol) {
return (protocol === 'anthropic-messages' ? ['auto', 'anthropic', 'deepseek'] : ['auto', 'openai', 'deepseek'])
.map(id => ({ id, label: labels[id] }));
}
export function parameterProfileSettings(protocol, value = 'auto') {
if (!parameterProfiles(protocol).some(profile => profile.id === value)) throw Object.assign(new Error('参数配置档与所选接口协议不兼容。'), { status: 400 });
return value;
}
// A profile describes the adapter's fields. It is not evidence that a vendor,
// proxy or particular model supports every field in that protocol.
export function modelParameterProfile(connection) {
const protocol = connection.protocol ?? 'chat-completions';
const selected = parameterProfileSettings(protocol, connection.parameterProfile);
const deepseek = connection.brand === 'DeepSeek' || /^deepseek(?:-|$)/i.test(connection.model ?? '')
|| /^https:\/\/api\.deepseek\.com(?:\/|$)/i.test(connection.baseUrl ?? '') || !!connection.nativeParameters?.thinking && protocol === 'chat-completions';
const id = selected !== 'auto' ? selected : deepseek ? 'deepseek' : protocol === 'anthropic-messages' ? 'anthropic' : 'openai';
return { id, label: labels[id], source: selected === 'auto' ? '按品牌、型号与协议匹配,可手动更改' : '用户选择的兼容格式',
efforts: id === 'deepseek' ? ['low', 'high', 'max'] : protocol === 'anthropic-messages' ? messagesEfforts : reasoningEfforts.filter(value => value !== 'none'),
thinking: protocol === 'anthropic-messages' || id === 'deepseek' && protocol === 'chat-completions' };
}
export function reasoningSetting(connection, parameters) {
const profile = modelParameterProfile(connection), protocol = connection.protocol;
const effort = protocol === 'anthropic-messages' ? parameters.output_config?.effort : protocol === 'responses' ? parameters.reasoning?.effort : parameters.reasoning_effort;
return { mode: profile.thinking ? parameters.thinking?.type ?? 'default' : effort === 'none' ? 'disabled' : effort ? 'enabled' : 'default',
effort: effort === 'none' ? '' : effort ?? '', budget: parameters.thinking?.budget_tokens ?? 1024 };
}
export function changeReasoningSetting(connection, parameters, field, value) {
const next = structuredClone(parameters), profile = modelParameterProfile(connection), protocol = connection.protocol;
const effortField = protocol === 'anthropic-messages' ? 'output_config' : protocol === 'responses' ? 'reasoning' : 'reasoning_effort';
const setEffort = effort => {
if (!effort) delete next[effortField];
else next[effortField] = effortField === 'reasoning_effort' ? effort : { effort };
};
if (field === 'effort') setEffort(value);
else if (field === 'budget') next.thinking = { type: 'enabled', budget_tokens: value };
else if (field === 'mode') {
if (value === 'default') { delete next.thinking; setEffort(''); }
else if (profile.thinking) {
next.thinking = value === 'enabled' && protocol === 'anthropic-messages'
? { type: value, budget_tokens: parameters.thinking?.budget_tokens ?? 1024 } : { type: value };
if (value === 'disabled') setEffort('');
} else {
delete next.thinking;
setEffort(value === 'disabled' ? 'none' : reasoningSetting(connection, parameters).effort || 'medium');
}
}
return next;
}
export function modelFeatureRows(connection) {
const states = { supported: '声明支持', unsupported: '声明不支持', unknown: '待确认', verified: '已验证', protocol_declared: '声明支持' };
const declared = key => states[connection.capabilities?.[key] ?? connection.capabilityDeclarations?.[key] ?? 'unknown'] ?? '待确认';
return [
{ name: '文本 / 工具调用', upstream: declared('text') + ' / ' + declared('tools'), local: '已接入,可单独检测' },
{ name: '流式输出', upstream: declared('streaming'), local: '已接入,按连接开关发送' },
{ name: '图像输入', upstream: declared('vision'), local: '已接入 PNG,可单独检测' },
{ name: '推理模式 / 强度', upstream: '依型号与兼容服务支持范围', local: '按配置档发送,受原输出预算约束' },
{ name: '语音 / 视频 / 服务端工具', upstream: '需供应商提供相应协议', local: '尚未接入' },
{ name: '结构化输出约束', upstream: '依型号与兼容服务支持范围', local: '尚未接入,参数保存时明确拒绝' },
];
}
+9 -3
View File
@@ -5,11 +5,17 @@ import { messagesBody, messagesHistory } from './anthropic-messages.mjs';
function wireBody(config, messages, tools) {
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField);
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField, config.parameterProfile);
if(config.inputImages?.length) messages=[...messages,{role:'user',content:protocol==='responses'
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
const cleanMessages = messages.map(({ providerState, ...message }) => message);
const cleanMessages = messages.map(({ providerState, reasoning_content, ...message }) => {
if (protocol === 'chat-completions' && message.role === 'assistant' && providerState?.protocol === 'chat-completions'
&& providerState.endpoint === config.baseUrl && providerState.model === config.model
&& providerState.connectionId === (config.modelConnectionId ?? null) && providerState.credentialRevision === (config.modelCredentialRevision ?? null)
&& typeof providerState.reasoningContent === 'string') return { ...message, reasoning_content: providerState.reasoningContent };
return message;
});
if (protocol === 'anthropic-messages') return messagesBody(config, messages, tools, native);
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', [native.outputTokenField]: config.maxOutputTokens, stream, ...native.nativeParameters,
...(stream ? { stream_options: { include_usage: true } } : {}) };
@@ -31,7 +37,7 @@ export function completionBody(config, messages, tools) {
if (members?.some(member => member.protocol && member.protocol !== 'chat-completions' || member.streaming === true || member.nativeParameters || member.outputTokenField)) {
return { schema: 1, kind: 'model-route-plan', messages, variants: members.map(member => ({ connectionId: member.id,
protocol: modelProtocol(member.protocol), body: wireBody({ ...config, ...member, nativeParameters: member.nativeParameters ?? {}, outputTokenField: member.outputTokenField,
maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision, maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
}
return wireBody(config, messages, tools);
}
+2 -1
View File
@@ -1,4 +1,5 @@
export function nativeParameterSettings(protocol?: string, parameters?: Record<string, unknown>, outputTokenField?: string): {
export function nativeParameterSettings(protocol?: string, parameters?: Record<string, unknown>, outputTokenField?: string, parameterProfile?: string): {
nativeParameters: Record<string, unknown>;
outputTokenField: string;
parameterProfile?: string;
};
+10 -7
View File
@@ -1,29 +1,32 @@
const fail = message => { throw Object.assign(new Error(message), { status: 400 }); };
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const efforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
import { reasoningEfforts as efforts, messagesEfforts, parameterProfileSettings } from './model-parameter-profiles.mjs';
const verbosity = ['low', 'medium', 'high'];
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField) {
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField, parameterProfile) {
if (!object(parameters) || JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
const allowed = protocol === 'anthropic-messages' ? ['temperature', 'top_p', 'top_k', 'stop_sequences', 'thinking'] : protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed'];
const allowed = protocol === 'anthropic-messages' ? ['temperature', 'top_p', 'top_k', 'stop_sequences', 'thinking', 'output_config'] : protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed', 'thinking'];
for (const [key, value] of Object.entries(parameters)) {
if (!allowed.includes(key)) fail('所选协议尚未接入原生参数:' + key + '。参数未保存或发送。');
if (key === 'temperature' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > (protocol === 'anthropic-messages' ? 1 : 2))) fail('temperature超出所选协议范围(Messages 0–1,其它 0–2)。');
if (key === 'top_k' && (!Number.isSafeInteger(value) || value < 0)) fail('Messages top_k应为非负安全整数。');
if (key === 'stop_sequences' && (!Array.isArray(value) || value.length > 32 || value.some(item => typeof item !== 'string' || !item || item.length > 1000))) fail('Messages stop_sequences应为最多32项的非空字符串数组。');
if (key === 'thinking' && (!object(value) || !['enabled', 'disabled', 'adaptive'].includes(value.type)
if (key === 'thinking' && protocol === 'anthropic-messages' && (!object(value) || !['enabled', 'disabled', 'adaptive'].includes(value.type)
|| Object.keys(value).some(field => !['type', 'budget_tokens'].includes(field))
|| (value.type === 'enabled' ? !Number.isSafeInteger(value.budget_tokens) || value.budget_tokens < 1024 : value.budget_tokens !== undefined))) fail('Messages thinking格式为disabled/adaptive,或enabled加至少1024的budget_tokens。');
if (key === 'thinking' && protocol === 'chat-completions' && (!object(value) || Object.keys(value).length !== 1 || !['enabled', 'disabled'].includes(value.type))) fail('Chat thinking格式为{"type":"enabled"}或{"type":"disabled"},需服务支持DeepSeek兼容推理开关。');
if (key === 'output_config' && (!object(value) || Object.keys(value).length !== 1 || !messagesEfforts.includes(value.effort))) fail('Messages output_config当前接入格式为{"effort":"low|medium|high|xhigh|max"}。');
if (key === 'top_p' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) fail('top_p应为0–1之间的数字。');
if (key === 'seed' && !Number.isSafeInteger(value)) fail('seed应为安全整数。');
if (key === 'parallel_tool_calls' && typeof value !== 'boolean') fail('parallel_tool_calls应为布尔值。');
if (key === 'reasoning_effort' && !efforts.includes(value)) fail('reasoning_effort应为none/minimal/low/medium/high/xhigh。');
if (key === 'reasoning_effort' && !efforts.includes(value)) fail('reasoning_effort应为none/minimal/low/medium/high/xhigh/max。');
if (key === 'verbosity' && !verbosity.includes(value)) fail('verbosity应为low/medium/high。');
if (key === 'reasoning' && (!object(value) || Object.keys(value).length !== 1 || !efforts.includes(value.effort))) fail('Responses reasoning当前接入格式为{"effort":"low|medium|high等"}。');
if (key === 'text' && (!object(value) || Object.keys(value).length !== 1 || !verbosity.includes(value.verbosity))) fail('Responses text当前接入格式为{"verbosity":"low|medium|high"}。');
}
const field = outputTokenField ?? (protocol === 'responses' ? 'max_output_tokens' : 'max_tokens');
if (!(protocol === 'responses' ? ['max_output_tokens'] : protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).includes(field)) fail('输出上限字段与所选协议不兼容。');
return { nativeParameters: structuredClone(parameters), outputTokenField: field };
return { nativeParameters: structuredClone(parameters), outputTokenField: field,
...(parameterProfile !== undefined ? { parameterProfile: parameterProfileSettings(protocol, parameterProfile) } : {}) };
}
+157
View File
@@ -0,0 +1,157 @@
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 { fixture, compatibleFixture, completion, call, until, assertToolPairs, launchWorkbench } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Store } from '../src/server/store.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
import { completionBody, actualRequest, outputReservation, requestMetrics } from '../src/shared/contracts/model-request.mjs';
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
import { nativeParameterSettings } from '../src/shared/contracts/native-parameters.mjs';
import { modelParameterProfile } from '../src/shared/contracts/model-parameter-profiles.mjs';
import { normalizeProtocolResponse } from '../src/core/models/protocols.mjs';
import { readModelStream } from '../src/core/models/model-stream.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
const config = { mode: 'compatible', model: 'deepseek-owned', baseUrl: 'http://127.0.0.1:1/v1', protocol: 'chat-completions', maxOutputTokens: 2048 };
const sse = value => 'data: ' + (typeof value === 'string' ? value : JSON.stringify(value)) + '\n\n';
const chunk = (delta, finish_reason = null) => sse({ model: config.model, choices: [{ index: 0, delta, finish_reason }] });
test('brand and custom-compatible profiles send native reasoning controls per protocol without changing output budgets', () => {
const cases = [
{ id: 'chat', protocol: 'chat-completions', parameterProfile: 'openai', nativeParameters: { reasoning_effort: 'max' } },
{ id: 'deepseek', protocol: 'chat-completions', parameterProfile: 'deepseek', nativeParameters: { thinking: { type: 'enabled' }, reasoning_effort: 'low' } },
{ id: 'off', protocol: 'chat-completions', parameterProfile: 'deepseek', nativeParameters: { thinking: { type: 'disabled' } } },
{ id: 'responses', protocol: 'responses', parameterProfile: 'openai', nativeParameters: { reasoning: { effort: 'max' } } },
{ id: 'messages', protocol: 'anthropic-messages', parameterProfile: 'anthropic', nativeParameters: { thinking: { type: 'adaptive' }, output_config: { effort: 'xhigh' } } },
].map(value => ({ ...value, model: value.id, baseUrl: config.baseUrl }));
const plan = completionBody({ ...config, modelRouting: { members: cases } }, [{ role: 'user', content: 'owned' }], []);
for (const member of cases) {
const body = actualRequest(plan, member);
for (const [key, value] of Object.entries(member.nativeParameters)) assert.deepEqual(body[key], value);
assert.equal(body.parameterProfile, undefined); assert.equal(outputReservation(body), 2048);
assert.equal(body.model, member.model);
}
assert.equal(actualRequest(plan, cases[0]).thinking, undefined); assert.equal(actualRequest(plan, cases[4]).reasoning_effort, undefined);
assert.equal(modelParameterProfile({ ...config, brand: '自定义' }).id, 'deepseek');
assert.equal(modelParameterProfile({ ...config, parameterProfile: 'openai' }).id, 'openai');
for (const [protocol, params, profile] of [
['chat-completions', { thinking: { type: 'adaptive' } }], ['chat-completions', { thinking: { type: 'enabled', budget_tokens: 1024 } }],
['anthropic-messages', { output_config: { effort: 'max', format: {} } }], ['anthropic-messages', { output_config: { effort: 'none' } }],
['responses', { thinking: { type: 'enabled' } }], ['chat-completions', {}, 'anthropic'], ['anthropic-messages', {}, 'openai'],
]) assert.throws(() => nativeParameterSettings(protocol, params, undefined, profile), cause => cause.status === 400);
assert.throws(() => completionBody({ ...config, protocol: 'anthropic-messages', maxOutputTokens: 1024, nativeParameters: { thinking: { type: 'enabled', budget_tokens: 1024 } } }, [], []), /小于/);
});
test('opaque Chat reasoning returns only to its original endpoint, model, connection and credential revision; bytes count against the actual request', () => {
const bound = { ...config, modelConnectionId: 'a', modelCredentialRevision: 2 };
const raw = completion([call('owned', 'list_files', {})]); raw.choices[0].message.reasoning_content = 'owned opaque state '.repeat(100);
const received = normalizeProtocolResponse(bound, raw).choices[0].message;
assert.equal(received.reasoning_content, undefined); assert.equal(raw.choices[0].message.reasoning_content.length, 1900);
const history = [received, { role: 'tool', tool_call_id: 'owned', content: '{}' }];
const same = completionBody(bound, history, []); assert.equal(same.messages[0].reasoning_content, raw.choices[0].message.reasoning_content);
for (const other of [{ baseUrl: 'https://elsewhere.test' }, { model: 'other' }, { modelConnectionId: 'b' }, { modelCredentialRevision: 3 }, { protocol: 'responses' }, { protocol: 'anthropic-messages' }]) {
const body = completionBody({ ...bound, ...other }, history, []);
assert.ok(!JSON.stringify(body).includes('owned opaque state'));
}
const stripped = completionBody({ ...bound, modelConnectionId: 'b' }, history, []);
assert.ok(requestMetrics(same).bytes > requestMetrics(stripped).bytes + 1800);
assert.ok(requestMetrics(same).estimatedInputTokens > requestMetrics(stripped).estimatedInputTokens + 500);
});
test('saved profile changes preserve credential references and old frozen Run settings, including the legacy connection after restart', t => {
const f = fixture(t), provider = new Provider(); provider.setKey('owned-legacy'); const hub = provider.modelHub(f.store);
const member = hub.upsert({ ...config, name: 'Owned profile', parameterProfile: 'deepseek', nativeParameters: { thinking: { type: 'enabled' }, reasoning_effort: 'low' }, apiKey: 'owned-profile' });
hub.select({ type: 'connection', id: member.id }); const prepared = hub.prepare(f.store.config), frozen = modelSnapshot(prepared), original = structuredClone(frozen);
const credential = provider.credentials.get(member.id), previousSession = JSON.stringify(f.session), pools = JSON.stringify(hub.state.pools);
hub.setNativeParameters({ id: member.id, revision: member.revision, parameterProfile: 'openai', nativeParameters: { reasoning_effort: 'max' } });
assert.deepEqual(frozen, original); assert.deepEqual(prepared.nativeParameters, { thinking: { type: 'enabled' }, reasoning_effort: 'low' });
assert.equal(provider.credentials.get(member.id), credential); assert.equal(JSON.stringify(f.session), previousSession); assert.equal(JSON.stringify(hub.state.pools), pools);
assert.equal(hub.prepare(f.store.config).parameterProfile, 'openai');
const legacy = hub.connection('legacy-default'); hub.setNativeParameters({ id: legacy.id, revision: legacy.revision, parameterProfile: 'deepseek', nativeParameters: { thinking: { type: 'disabled' } } });
assert.equal(provider.apiKey, 'owned-legacy'); f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
assert.equal(reopened.config.parameterProfile, 'deepseek'); assert.equal(new Provider().modelHub(reopened).connection('legacy-default').parameterProfile, 'deepseek');
assert.equal(new Provider().modelHub(reopened).connection(member.id).parameterProfile, 'openai');
});
for (const streaming of [false, true]) test('DeepSeek ' + (streaming ? 'SSE' : 'JSON') + ' reasoning survives real HTTP tool rounds and restart without entering visible assistant text', async t => {
const f = fixture(t), requests = [], rawResponses = [];
const model = http.createServer(async (req, res) => {
const parts = []; for await (const part of req) parts.push(part); const body = JSON.parse(Buffer.concat(parts)); requests.push(body);
const n = requests.length, calls = n < 3 ? [call('owned-call-' + n, 'list_files', { path: '', depth: 1 })] : [];
const opaque = 'owned opaque step ' + n, answer = n === 3 ? 'Read complete.' : '';
const result = completion(calls, answer); result.model = config.model; result.choices[0].message.reasoning_content = opaque;
res.writeHead(200, { 'Content-Type': streaming ? 'text/event-stream' : 'application/json' });
const raw = streaming ? chunk({ reasoning_content: opaque.slice(0, 7) }) + chunk({ reasoning_content: opaque.slice(7) })
+ chunk({ ...(answer ? { content: answer } : {}), ...(calls.length ? { tool_calls: calls.map((value, index) => ({ ...value, index })) } : {}) }, calls.length ? 'tool_calls' : 'stop')
+ sse({ choices: [], usage: result.usage }) + sse('[DONE]') : JSON.stringify(result);
rawResponses.push(raw); res.end(raw);
});
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise(resolve => { model.closeAllConnections(); model.close(resolve); }));
const provider = new Provider(), hub = provider.modelHub(f.store), member = hub.upsert({ ...config, baseUrl: 'http://127.0.0.1:' + model.address().port + '/v1',
name: 'Owned custom proxy', brand: '自定义', parameterProfile: 'deepseek', requiresKey: false, streaming, capabilityDeclarations: { streaming: 'supported' },
nativeParameters: { thinking: { type: 'enabled' }, reasoning_effort: 'low' } });
hub.select({ type: 'connection', id: member.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the project files.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.equal(requests.length, 3);
for (const [index, body] of requests.entries()) {
assert.deepEqual(body.thinking, { type: 'enabled' }); assert.equal(body.reasoning_effort, 'low'); assert.equal(body.max_tokens, 2048);
assert.deepEqual(body.messages.filter(m => m.role === 'assistant').map(m => m.reasoning_content), Array.from({ length: index }, (_, i) => 'owned opaque step ' + (i + 1)));
}
assertToolPairs(f.session.providerMessages); assert.equal(f.session.events.filter(e => e.tool === 'list_files' && e.phase === 'completed').length, 2);
assert.ok(!f.session.messages.some(m => String(m.content).includes('owned opaque')));
for (const plan of f.store.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(f.store, f.session, plan));
for (const attempt of hub.view().attempts) assert.ok(rawResponses.includes(f.store.artifactStore.read(f.store.owned('artifact', attempt.responseArtifactId, f.session.id))));
const original = structuredClone(f.session.providerMessages), before = modelSnapshot(hub.prepare(f.store.config));
assert.equal(before.parameterProfile, 'deepseek'); f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
assert.deepEqual(reopened.session(f.session.id).providerMessages, original);
const reopenedHub = new Provider().modelHub(reopened); assert.equal(reopenedHub.connection(member.id).parameterProfile, 'deepseek');
assert.equal(requests.length, 3);
});
test('malformed or post-terminal Chat reasoning is rejected with the raw stream retained', async () => {
for (const raw of [chunk({ reasoning_content: {} }) + chunk({ content: 'OK' }, 'stop') + sse('[DONE]'),
chunk({ content: 'OK' }, 'stop') + chunk({ reasoning_content: 'late' }) + sse('[DONE]')]) {
const progress = [];
await assert.rejects(readModelStream(new Response(raw, { headers: { 'Content-Type': 'text/event-stream' } }), config, undefined, e => progress.push(e), []));
assert.equal(progress.find(e => e.streamCapture).streamCapture.toString(), raw);
}
});
test('connection import synchronizes profile, native fields and declared abilities without editing the source or manufacturing verification', t => {
const f = fixture(t), hub = new Provider().modelHub(f.store), importer = new ConfigImporter(hub);
const filename = path.join(f.root, 'owned-models.json');
const write = effort => fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: [{ ...config, id: 'custom', name: 'Owned proxy', brand: '自定义', requiresKey: false,
parameterProfile: 'deepseek', nativeParameters: { thinking: { type: 'enabled' }, reasoning_effort: effort }, capabilityDeclarations: { streaming: 'supported', vision: 'unsupported' } }] }));
write('low'); let bytes = fs.readFileSync(filename), preview = importer.preview('workbench-json', filename);
assert.equal(preview.entries[0].parameterProfile, 'deepseek'); const imported = importer.apply(preview.id, true), member = hub.connection(imported.imported[0]);
assert.equal(hub.status(member).capabilities.streaming, 'protocol_declared'); assert.equal(hub.status(member).capabilities.vision, 'unsupported');
assert.deepEqual(fs.readFileSync(filename), bytes);
write('max'); bytes = fs.readFileSync(filename); preview = importer.preview('workbench-json', filename); importer.apply(preview.id);
assert.equal(hub.connection(member.id).nativeParameters.reasoning_effort, 'max'); assert.deepEqual(fs.readFileSync(filename), bytes);
const current = hub.connection(member.id); hub.setNativeParameters({ id: current.id, revision: current.revision, parameterProfile: 'openai', nativeParameters: { reasoning_effort: 'medium' } });
write('high'); preview = importer.preview('workbench-json', filename); const conflict = importer.apply(preview.id);
assert.deepEqual(conflict.conflicts, ['Owned proxy']); assert.equal(hub.connection(member.id).nativeParameters.reasoning_effort, 'medium');
});
test('compiled HTTP persists profile and reasoning choices for every protocol and rejects incompatible/stale edits atomically', async t => {
const f = fixture(t); f.store.close(); const host = await launchWorkbench(t, f.data);
const cases = [
['chat-completions', 'deepseek', { thinking: { type: 'enabled' }, reasoning_effort: 'low' }],
['responses', 'openai', { reasoning: { effort: 'max' } }],
['anthropic-messages', 'anthropic', { thinking: { type: 'adaptive' }, output_config: { effort: 'high' } }],
];
for (const [protocol, parameterProfile, nativeParameters] of cases) {
const member = await host.api('/model-center/connections', { name: 'Owned ' + protocol, model: 'owned-model', baseUrl: config.baseUrl, protocol, requiresKey: false });
await host.api('/model-center/native-parameters', { id: member.id, revision: member.revision, parameterProfile, nativeParameters });
const current = (await host.api('/model-center')).connections.find(c => c.id === member.id);
assert.equal(current.parameterProfile, parameterProfile); assert.deepEqual(current.nativeParameters, nativeParameters);
await assert.rejects(host.api('/model-center/native-parameters', { id: member.id, revision: member.revision, parameterProfile, nativeParameters: {} }), cause => cause.status === 409);
await assert.rejects(host.api('/model-center/native-parameters', { id: member.id, revision: current.revision, parameterProfile: 'invented', nativeParameters: {} }), cause => cause.status === 400);
assert.deepEqual((await host.api('/model-center')).connections.find(c => c.id === member.id), current);
}
});