feat(models): expose request contracts and actual request metadata

This commit is contained in:
Agent Workbench Dev
2026-11-07 16:08:47 +08:00
parent f95507ab25
commit 26472d2866
11 changed files with 365 additions and 14 deletions
+246
View File
@@ -0,0 +1,246 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import net from 'node:net';
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 { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.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';
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
const desktop = process.argv.includes('--desktop');
assert.ok(process.argv.slice(2).every(value => value === '--desktop'));
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate build');
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
const directory = path.resolve(process.env.AGENT_WORKBENCH_QA_EVIDENCE_ROOT ?? '.qa/m2-request-contract-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true });
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [], contrast = [];
const native = { temperature: 0.7, top_p: 0.8, top_k: 5, thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, metadata: { preserve: ['owned', { nested: true }] } };
const legacyAttempt = { id: 'owned-old-request', status: 'unknown', model: 'owned-old', usage: null, legacy_extension: { preserve: ['failed network', 'repeated reads', 'unknown usage'] } };
const raw = model => ({ id: model, context_window: 1000000, max_output_tokens: 128000, capabilities: { text: true, tools: true }, vendor_extension: { complete: ['owned', { preserved: true }] } });
const model = http.createServer(async (request, response) => {
try {
const chunks = []; for await (const chunk of request) chunks.push(chunk);
const body = chunks.length ? JSON.parse(Buffer.concat(chunks)) : null;
requests.push({ method: request.method, route: request.url, body, headers: Object.fromEntries(Object.entries(request.headers).map(([name, value]) => [name, credentialHeader(name) ? '{{credential}}' : value])) });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(request.url.includes('pageToken=') ? { data: [raw('claude-sonnet-5-5')] } : { data: [raw('claude-opus-5-5')], nextPageToken: 'owned-page-two' }));
} else if (request.url === '/owned/messages') {
response.writeHead(400, { 'Content-Type': 'application/json', 'anthropic-version': '2026-10-21', 'x-request-id': 'owned-invalid-version' });
response.end(JSON.stringify({ error: { type: 'invalid_request_error', message: 'temperature is removed in 2026-10-21', param: 'temperature' } }));
} else if (request.url === '/owned/responses') {
response.writeHead(200, { 'Content-Type': 'application/json', 'openai-version': '2020-10-01', 'openai-project': 'project-owned', 'x-request-id': 'owned-responses-id' });
response.end(JSON.stringify({ id: 'owned-response', model: body.model, status: 'completed', output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'OK' }] }], usage: { input_tokens: 11, output_tokens: 1 } }));
} else if (request.url === '/owned/chat') {
response.writeHead(200, { 'Content-Type': 'application/json', 'openai-organization': 'org-owned', 'x-request-id': 'owned-chat-id' });
response.end(JSON.stringify({ id: 'owned-chat', model: body.model, choices: [{ message: { role: 'assistant', content: 'OK' }, finish_reason: 'stop' }], usage: { prompt_tokens: 11, completion_tokens: 1, total_tokens: 12 } }));
} else { response.writeHead(500); response.end('Unexpected owned route'); }
} catch (cause) { response.writeHead(500); response.end(cause.message); }
});
let host, browser, application, controller, page, window, result, claude, responses, chat, childId, originalMetadata, originalCipher, originalSnapshotMetadata, originalSnapshot, desktopStdout = '', desktopStderr = '';
const center = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const form = () => page.getByRole('form', { name: '编辑模型连接', exact: true });
const card = id => page.locator('.mc-connection[data-connection-id="' + id + '"]');
const settings = () => form().locator('.mc-request-settings');
const field = label => form().getByLabel(label, { exact: true });
const current = async id => (await host.api('/model-center')).connections.find(value => value.id === id);
const mark = name => { checks.push(name); console.log('PASS ' + name); };
async function resize(width, height = 960) {
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 open() { await openWorkbenchTool(page, '打开模型中心'); await expect(center()).toBeVisible(); }
async function edit(id) { if (!await center().count()) await open(); await card(id).getByRole('button', { name: '编辑', exact: true }).click(); await expect(form()).toBeVisible(); await settings().locator(':scope > summary').click(); }
async function capture(file) {
if (!window) { await page.screenshot({ path: file, scale: 'css' }); return { method: 'playwright-page' }; }
const captured = await window.evaluate(async win => {
const [width, height] = win.getContentSize(), picture = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true });
return { png: picture.toPNG().toString('base64'), empty: picture.isEmpty(), size: picture.getSize(), hidden: !win.isVisible() };
});
assert.equal(captured.empty, false); assert.equal(captured.hidden, true); fs.writeFileSync(file, Buffer.from(captured.png, 'base64'));
return { method: 'electron-native-stay-hidden', size: captured.size };
}
async function shot(name, anchor) {
if (anchor) await anchor.scrollIntoViewIfNeeded();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow');
const file = path.join(directory, name + '.png'), captured = await capture(file);
screenshots.push({ file: path.basename(file), sha256: sha(fs.readFileSync(file)), ...captured });
fs.writeFileSync(path.join(directory, name + '.txt'), await center().innerText(), { flag: 'wx' });
}
async function sampleContrast(locator, label) {
const sampled = await locator.evaluate(element => {
const style = getComputedStyle(element); let ancestor = element, background;
while (ancestor) { const color = getComputedStyle(ancestor).backgroundColor; if (color !== 'rgba(0, 0, 0, 0)' && color !== 'transparent') { background = color; break; } ancestor = ancestor.parentElement; }
return { color: style.color, background, fontSize: style.fontSize };
});
const luminance = value => value.match(/[\d.]+/g).slice(0, 3).map(Number).map(c => c / 255).map(c => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);
const a = luminance(sampled.color), b = luminance(sampled.background), ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
contrast.push({ label, ...sampled, ratio }); assert.ok(ratio >= 4.5, label + ' contrast ' + ratio);
}
async function probe(id, count) {
await card(id).getByRole('button', { name: '验证响应(调用模型)', exact: true }).click();
await until(async () => { const state = await host.api('/model-center'); return state.attemptCount === count + 1 && state.attempts.filter(value => value.connectionId === id).every(value => value.status !== 'running'); }, 30000);
await expect(card(id).getByRole('button', { name: '验证响应(调用模型)', exact: true })).toBeEnabled();
}
try {
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
const baseUrl = 'http://127.0.0.1:' + model.address().port + '/v1';
f.store.storage.setMeta('modelAttempts', [legacyAttempt]);
originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store);
claude = hub.upsert({ name: '自有验证 · Claude 请求契约', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl, apiKey: 'owned-ui-contract-key-only', persistKey: true, nativeParameters: native,
requestContract: { anthropicVersion: '2023-06-01', anthropicBetas: ['owned-old'], completionPath: '/owned/messages', modelsPath: '/owned/models?catalog=one', headers: { 'anthropic-workspace-id': 'workspace-owned-old' } } });
responses = hub.upsert({ name: '自有验证 · Responses 请求', model: 'gpt-6.1-sol', protocol: 'responses', baseUrl, requiresKey: false,
nativeParameters: { reasoning: { effort: 'high', summary: 'auto' }, metadata: { stable: 'owned' } },
requestContract: { completionPath: '/owned/responses', headers: { 'OpenAI-Project': 'project-owned', 'X-Client-Request-Id': 'owned-client-id' } } });
chat = hub.upsert({ name: '自有验证 · Chat 请求', model: 'gpt-6-sol', protocol: 'chat-completions', baseUrl, requiresKey: false,
nativeParameters: { reasoning_effort: 'none', metadata: { stable: ['owned', { nested: true }] } }, requestContract: { completionPath: '/owned/chat', headers: { 'OpenAI-Organization': 'org-owned' } } });
hub.select({ type: 'connection', id: claude.id });
originalSnapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' }, { type: 'connection', id: claude.id }));
f.store.storage.setMeta('ownedModelSnapshot', originalSnapshot);
originalSnapshotMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
originalCipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
fs.writeFileSync(path.join(directory, 'retention-before.json'), JSON.stringify({ modelAttempts: originalMetadata, modelCredentials: originalCipher, modelSnapshot: originalSnapshotMetadata }, null, 2));
hub.save(); f.store.close();
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 = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
args: [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({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
page = await application.firstWindow(); window = await application.browserWindow(page);
} 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();
}
page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message));
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); });
await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle'); await open();
await center().getByRole('button', { name: '手动填写(兼容)', exact: true }).click();
await form().getByLabel('服务品牌').selectOption('Anthropic'); await settings().locator(':scope > summary').click();
await expect(field('API 请求版本')).toHaveValue('2026-10-21'); await expect(field('Messages 鉴权').locator('option:checked')).toContainText('Bearer');
await expect(field('省略版本头')).not.toBeChecked(); await shot('official-default-1280', settings().locator(':scope > summary'));
await form().getByRole('button', { name: '取消', exact: true }).click(); assert.equal(requests.length, 0);
mark('New official Anthropic defaults show the recommended version and Bearer without saving or making an external request');
await edit(claude.id); await expect(field('API 请求版本')).toHaveValue('2023-06-01');
await field('API 请求版本').fill('2026-10-21'); await field('Beta 功能').fill('owned-beta,unknown-beta,owned-beta');
const headers = { 'anthropic-workspace-id': 'workspace-owned-new', 'X-Client-Request-Id': 'owned-long-' + 'x'.repeat(200) };
await field('额外请求头 JSON').fill('{ invalid'); await expect(settings().getByRole('alert')).toBeVisible();
await form().getByRole('button', { name: '保存模型连接', exact: true }).click(); assert.equal((await current(claude.id)).revision, claude.revision);
await expect(field('额外请求头 JSON')).toHaveValue('{ invalid'); assert.equal(await form().evaluate(element => element.checkValidity()), false);
await field('额外请求头 JSON').fill(JSON.stringify(headers, null, 2)); await shot('edited-contract-1280', settings().locator(':scope > summary'));
await form().getByRole('button', { name: '保存模型连接', exact: true }).click(); await expect(form()).toHaveCount(0);
let saved = await current(claude.id); assert.deepEqual(saved.nativeParameters, native); assert.equal(saved.savedCredential.status, 'saved');
assert.equal(saved.requestContract.anthropicVersion, '2026-10-21'); assert.deepEqual(saved.requestContract.anthropicBetas, ['owned-beta', 'unknown-beta', 'owned-beta']); assert.deepEqual(saved.requestContract.headers, headers);
await edit(claude.id); await expect(field('API 请求版本')).toHaveValue('2026-10-21'); await expect(field('模型目录路径')).toHaveValue('/owned/models?catalog=one');
await form().getByRole('button', { name: '取消', exact: true }).click();
mark('Invalid header JSON stays visible and saves nothing; valid version/Beta/non-auth edits persist with native siblings and the original encrypted binding');
await probe(claude.id, 1);
const failure = center().locator('.mc-notice .model-error-details'); await failure.locator(':scope > summary').click();
await expect(failure.getByLabel('上游错误原文')).toContainText('temperature is removed in 2026-10-21');
await failure.locator('.mc-request-details > summary').click(); await expect(failure.getByLabel('实际请求头')).toContainText('{{credential}}');
await expect(failure.getByLabel('实际请求头')).toContainText('2026-10-21'); await expect(failure.getByLabel('实际请求头')).toContainText('owned-beta,unknown-beta,owned-beta');
await shot('upstream-error-1280', failure.getByLabel('实际请求头'));
let sent = requests.filter(value => value.method === 'POST')[0]; assert.equal(sent.route, '/owned/messages');
for (const [name, value] of Object.entries(native)) assert.deepEqual(sent.body[name], value);
assert.equal(sent.headers['anthropic-version'], '2026-10-21'); assert.equal(sent.headers['anthropic-workspace-id'], 'workspace-owned-new'); assert.equal(sent.body.max_tokens, 128000);
assert.doesNotMatch(await failure.innerText(), /owned-ui-contract-key-only/); assert.equal(requests.filter(value => value.method === 'POST').length, 1);
mark('One actual owned 400 keeps the original sampling parameters, upstream text, request version/Beta and credential references without replay');
await probe(responses.id, 2); await probe(chat.id, 3);
const posts = requests.filter(value => value.method === 'POST'); assert.equal(posts.length, 3);
assert.equal(posts[1].route, '/owned/responses'); assert.equal(posts[1].headers['openai-project'], 'project-owned'); assert.equal(posts[1].headers['anthropic-version'], undefined);
assert.equal(posts[2].route, '/owned/chat'); assert.equal(posts[2].headers['openai-organization'], 'org-owned'); assert.equal(posts[2].headers['openai-project'], undefined);
assert.deepEqual(posts[1].body.reasoning, responses.nativeParameters.reasoning); assert.deepEqual(posts[2].body.metadata, chat.nativeParameters.metadata);
assert.equal(Object.hasOwn(posts[1].body, 'max_output_tokens'), false); assert.equal(Object.hasOwn(posts[2].body, 'max_tokens'), false);
mark('Responses and Chat send separate paths and headers on actual owned wires; nested native parameters and optional-output omission remain');
await card(claude.id).getByRole('button', { name: '获取同源模型', exact: true }).click();
const catalog = center().getByRole('region', { name: '上游模型目录', exact: true });
await catalog.getByLabel('目录上游连接').selectOption(''); await catalog.locator('.mc-request-settings > summary').click();
await catalog.getByLabel('上游名称').fill('自有新上游草稿'); await catalog.getByLabel('目录接口根地址').fill((await current(claude.id)).baseUrl);
await catalog.getByLabel('目录 API Key').fill('owned-draft-contract-key'); await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeEnabled();
await catalog.getByLabel('额外请求头 JSON').fill('{ invalid');
await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeDisabled(); await expect(catalog.getByLabel('额外请求头 JSON')).toHaveValue('{ invalid');
await catalog.getByLabel('目录上游连接').selectOption(claude.id); await expect(catalog.getByRole('button', { name: '获取上游模型', exact: true })).toBeEnabled();
await catalog.getByRole('button', { name: '获取上游模型', exact: true }).click();
await expect(catalog.getByLabel('选择模型 claude-sonnet-5-5', { exact: true })).toBeVisible();
await catalog.getByLabel('选择模型 claude-opus-5-5', { exact: true }).check(); await catalog.getByLabel('选择模型 claude-sonnet-5-5', { exact: true }).check();
await catalog.getByRole('button', { name: '保存所选 2 个模型', exact: true }).click(); await expect(catalog).toContainText('已新增 1 个模型,沿用 1 个已有模型');
const state = await host.api('/model-center'), child = state.connections.find(value => value.model === 'claude-sonnet-5-5'); childId = child.id;
saved = state.connections.find(value => value.id === claude.id); assert.deepEqual(child.requestContract, saved.requestContract); assert.equal(child.credentialSource.connectionId, claude.id); assert.equal(child.hasKey, true);
const gets = requests.filter(value => value.method === 'GET'); assert.equal(gets.length, 2);
assert.ok(gets.every(value => value.route.startsWith('/owned/models?catalog=one') && value.headers['anthropic-version'] === '2026-10-21' && value.headers['anthropic-workspace-id'] === 'workspace-owned-new'));
assert.equal(saved.upstreamModel.requestBinding.credentialRevision, saved.credentialRevision); assert.deepEqual(saved.nativeParameters, native);
await catalog.getByRole('button', { name: '关闭目录', exact: true }).click();
mark('Invalid new-source headers cannot send stale settings; switching to a saved source fetches all same-origin pages and shares its contract and credential');
await center().getByRole('button', { name: '请求账本', exact: true }).click();
const ledger = center().getByRole('region', { name: '完整请求账本', exact: true }); await expect(ledger).toContainText('4 条已保存');
const responseEntry = ledger.locator('article').filter({ has: page.getByText('gpt-6.1-sol', { exact: true }) });
await responseEntry.locator('.mc-request-details > summary').first().click(); await expect(responseEntry).toContainText('响应 openai-version 2020-10-01');
await expect(responseEntry.getByLabel('实际请求头')).toContainText('project-owned'); await shot('request-ledger-1280', responseEntry.locator('.mc-request-details'));
const oldEntry = ledger.locator('article').filter({ has: page.getByText('owned-old', { exact: true }) }); await expect(oldEntry).toContainText('用量未知');
assert.equal(await oldEntry.locator('.mc-request-details').count(), 0); assert.doesNotMatch(await ledger.innerText(), /owned-ui-contract-key-only/);
await resize(390, 844); await shot('request-ledger-390', responseEntry.locator('.mc-request-details'));
mark('The complete ledger shows actual request and response versions and header fingerprints; original unknown records receive no invented metadata');
for (const [palette, name] of [['green', '深青绿'], ['blue', '雾蓝'], ['purple', '鸢尾紫']]) {
await page.keyboard.press('Escape'); await page.getByRole('button', { name: '外观', exact: true }).click();
await page.getByRole('dialog', { name: '外观', exact: true }).getByRole('radio', { name, exact: true }).check(); await page.keyboard.press('Escape');
await open(); await center().getByRole('button', { name: '模型连接', exact: true }).click(); await edit(claude.id);
await expect(field('API 请求版本')).toHaveValue('2026-10-21');
await sampleContrast(settings().locator(':scope > summary'), palette + ' request summary'); await sampleContrast(settings().locator('.mc-help').first(), palette + ' request help');
await sampleContrast(field('API 请求版本'), palette + ' version input'); await shot('request-' + palette + '-390', field('额外请求头 JSON'));
await form().getByRole('button', { name: '取消', exact: true }).click();
}
mark('The existing three palettes keep version/header settings readable at 390px with measured text contrast and no page overflow');
const finalCenter = await host.api('/model-center'); assert.equal(finalCenter.attemptCount, 4); assert.deepEqual(finalCenter.attempts.find(value => value.id === legacyAttempt.id), legacyAttempt);
assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []); fs.writeFileSync(path.join(directory, 'center-final.json'), JSON.stringify(finalCenter, null, 2));
if (application) { await application.close(); application = null; } if (browser) { await browser.close(); browser = null; }
if (controller) { await controller.stop(); controller = null; } await host.close?.(); host = null;
host = await launchWorkbench(t, f.data, {}, { appRoot });
const restored = await host.api('/model-center'), restoredClaude = restored.connections.find(value => value.id === claude.id);
assert.equal(restoredClaude.hasKey, true); assert.equal(restoredClaude.savedCredential.status, 'saved'); assert.deepEqual(restoredClaude.requestContract, saved.requestContract); assert.deepEqual(restoredClaude.nativeParameters, native);
assert.equal(restored.connections.find(value => value.id === childId).hasKey, true); assert.equal(restored.attemptCount, 4); assert.equal(requests.filter(value => value.method === 'POST').length, 3);
const restoredHostUrl = host.url; await host.close(); host = null;
const storage = new Store(f.data); try {
const retainedCipher = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
const retainedMetadata = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const retainedSnapshot = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
fs.writeFileSync(path.join(directory, 'retention-after.json'), JSON.stringify({ modelAttempts: retainedMetadata, modelCredentials: retainedCipher, modelSnapshot: retainedSnapshot }, null, 2));
assert.equal(retainedCipher, originalCipher); assert.equal(retainedMetadata, originalMetadata); assert.equal(retainedSnapshot, originalSnapshotMetadata);
assert.deepEqual(storage.storage.meta('ownedModelSnapshot'), JSON.parse(originalSnapshotMetadata)); assert.deepEqual(storage.storage.meta('modelAttempts').find(value => value.id === legacyAttempt.id), legacyAttempt);
} finally { storage.close(); }
mark('An independent candidate host restart restores the original DPAPI cipher and shared credentials; original metadata and frozen snapshot bytes remain exact without replay');
result = { success: true, appRoot, actualElectron: desktop, hostUrl: restoredHostUrl, checks, screenshots, contrast, errors, externalBlocked, syntheticRequests: 3, catalogRequests: 2,
originalUnknownAttempts: 1, originalMetadataExact: true, originalMetadataSha256: sha(originalMetadata), originalCipherExact: true, originalCipherSha256: sha(originalCipher), originalSnapshotExact: true, originalSnapshotSha256: sha(originalSnapshotMetadata),
realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
} catch (cause) {
if (page) { await capture(path.join(directory, 'failure.png')).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, contrast, errors, externalBlocked, error: cause.stack, syntheticRequests: requests.filter(value => value.method === 'POST').length, catalogRequests: requests.filter(value => value.method === 'GET').length, realModelRequests: 0 };
} finally {
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
if (application) await application.close(); if (browser) await browser.close();
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
if (model.listening) await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); });
for (const dispose of disposers.reverse()) await dispose();
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
+8 -3
View File
@@ -4,15 +4,19 @@ import type { CatalogPreview } from '../shared/contracts/model-catalog.mjs';
import { ModelErrorDetails } from './ModelErrorDetails';
import type { RuntimeFailure } from './types';
import { resolveModelSpecification } from '../shared/contracts/official-model-registry.mjs';
import { RequestContractSettings } from './RequestContractSettings';
import { defaultMessagesAuth } from '../shared/contracts/model-request-contract.mjs';
import type { RequestContract } from '../shared/contracts/model-request-contract.mjs';
type Source = { id: string; revision: number; name: string; protocol: string; baseUrl: string; brand: string; enabled: boolean; credentialSource?: { connectionId: string } };
const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: 'api-key', requiresKey: true };
const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: undefined as string | undefined, requestContract: undefined as RequestContract | undefined, requiresKey: true };
const capabilityNames: Record<string, string> = { text: '文本', tools: '工具调用', streaming: '流式输出', vision: '图像输入', audio: '语音' };
export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }: {
sources: Source[]; sourceId?: string; busy: boolean; onSaved: () => Promise<void>; onClose: () => void;
}) {
const [source, setSource] = useState(sourceId), [draft, setDraft] = useState(initial);
const [key, setKey] = useState(''), [persistKey, setPersistKey] = useState(false);
const [requestValid, setRequestValid] = useState(true);
const [preview, setPreview] = useState<CatalogPreview | null>(null), [chosen, setChosen] = useState<string[]>([]), [query, setQuery] = useState('');
const [routing, setRouting] = useState('keep'), [defaultModel, setDefaultModel] = useState('');
const [declare, setDeclare] = useState(false), [working, setWorking] = useState(false), [saving, setSaving] = useState(false);
@@ -74,14 +78,15 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
setDraft({ ...draft, brand, ...(brand === 'OpenAI' ? { baseUrl: 'https://api.openai.com/v1', protocol: 'responses' } : brand === 'Anthropic' ? { baseUrl: 'https://api.anthropic.com', protocol: 'anthropic-messages' } : brand === 'DeepSeek' ? { baseUrl: 'https://api.deepseek.com', protocol: 'chat-completions' } : {}) });
}}>{['自定义', 'OpenAI', 'Anthropic', 'DeepSeek', 'Claude 兼容代理', 'Ollama', 'vLLM', '兼容服务'].map(value => <option key={value}>{value}</option>)}</select></label>
<label>接口协议<select aria-label="目录接口协议" value={draft.protocol} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, protocol: event.target.value }); }}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="目录 Messages 鉴权" value={draft.messagesAuth} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, messagesAuth: event.target.value }); }}><option value="api-key">x-api-key</option><option value="bearer">Bearer</option></select></label>}
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="目录 Messages 鉴权" value={draft.messagesAuth ?? ''} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, messagesAuth: event.target.value || undefined }); }}><option value="">连接默认({defaultMessagesAuth(draft, { existing: false }) === 'bearer' ? 'Bearer' : 'x-api-key'})</option><option value="api-key">x-api-key</option><option value="bearer">Bearer</option></select></label>}
<RequestContractSettings connection={draft} value={draft.requestContract} busy={locked || working} existing={false} onValidityChange={setRequestValid} onChange={value => { invalidate(); setDraft({ ...draft, requestContract: value }); }} />
<label className="mc-full">接口根地址<input aria-label="目录接口根地址" type="url" value={draft.baseUrl} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, baseUrl: event.target.value }); }} /></label>
<label>API Key<input aria-label="目录 API Key" type="password" autoComplete="new-password" value={key} disabled={locked || working} onChange={event => { invalidate(); setKey(event.target.value); }} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={!draft.requiresKey} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, requiresKey: !event.target.checked }); }} />此上游不需要 Key</label>
<label className="mc-checkbox mc-full"><input type="checkbox" checked={persistKey} disabled={locked || working || !key} onChange={event => setPersistKey(event.target.checked)} />保存模型时,将本次新填写的 Key 在本机加密保存</label>
</> : <p className="mc-help mc-full">使用该连接当前的凭据获取目录;新增型号引用同一凭据来源。</p>}
</div>
<div className="mc-row-actions"><button className="button primary" disabled={locked || working || !!source && !current || !source && (!draft.name.trim() || !draft.baseUrl || draft.requiresKey && !key)} onClick={() => void fetchModels()}>{working ? '正在获取模型…' : preview ? '重新获取模型目录' : '获取上游模型'}</button>
<div className="mc-row-actions"><button className="button primary" disabled={locked || working || !!source && !current || !source && (!requestValid || !draft.name.trim() || !draft.baseUrl || draft.requiresKey && !key)} onClick={() => void fetchModels()}>{working ? '正在获取模型…' : preview ? '重新获取模型目录' : '获取上游模型'}</button>
{working && <button className="button secondary" onClick={() => { invalidate(); setNotice('已取消获取。可修改上游后重新获取。'); }}>取消获取</button>}</div>
<p className="mc-help">只访问模型目录,不发起推理请求。兼容服务未开放目录时,可返回“手动填写(兼容)”。</p>
{error && <p className="mc-card-warning" role="alert">{error}</p>}{diagnostic && <ModelErrorDetails failure={diagnostic} />}
+8
View File
@@ -31,6 +31,14 @@
.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-request-settings,.mc-request-details{min-width:0;border-top:1px solid var(--line);margin-top:14px;padding-top:10px;color:var(--ink);font-size:12px;line-height:1.75;overflow-wrap:anywhere}
.mc-request-settings>summary,.mc-request-details>summary{cursor:pointer;min-height:42px;display:list-item;padding:10px 0;font-weight:600;color:var(--ink)}
.mc-request-settings .mc-form-grid{margin:12px 0}.mc-request-settings textarea{font-family:var(--font-mono,Consolas,monospace);resize:vertical;min-width:0}
.mc-request-details dl{display:grid;grid-template-columns:minmax(96px,auto) minmax(0,1fr);gap:7px 14px;margin:12px 0}.mc-request-details dt{color:var(--muted)}.mc-request-details dd{margin:0;min-width:0;overflow-wrap:anywhere}
.mc-request-details pre{white-space:pre-wrap;overflow-wrap:anywhere;min-width:0;max-height:360px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px;font:12px/1.75 var(--font-mono,Consolas,monospace);color:var(--ink);background:var(--panel)}
.mc-request-details code{overflow-wrap:anywhere;font:11px/1.7 var(--font-mono,Consolas,monospace)}.mc-request-settings a{color:var(--accent)}
.mc-request-settings summary:focus-visible,.mc-request-details summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
@media(max-width:620px){.mc-request-details dl{grid-template-columns:1fr;gap:4px}.mc-request-details dd{margin-bottom:8px}}
.mc-section-title .mc-row-actions,.mc-catalog .mc-row-actions{display:flex;flex-wrap:wrap;gap:8px}.mc-catalog{margin-bottom:24px;border-top:3px solid #2560a3;min-width:0}.mc-catalog-heading{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin:18px 0 12px}.mc-catalog-heading label{display:grid;gap:7px;flex:1;min-width:180px}.mc-catalog-heading input{padding:10px;border:1px solid #a9bdcf;border-radius:5px;width:100%;min-width:0;background:#fff}.mc-catalog-heading>span{font-size:12px;color:#40566e;padding:10px 0}.mc-catalog-list{margin:12px 0;max-height:440px;overflow:auto;border:1px solid #b8cadb;border-radius:5px;background:#fff;overscroll-behavior:contain}.mc-catalog-model{display:flex;gap:12px;align-items:start;padding:13px 14px;border-bottom:1px solid #d3dde7;cursor:pointer;min-width:0}.mc-catalog-model:last-child{border-bottom:0}.mc-catalog-model.is-selected{background:#eaf2fa}.mc-catalog-model>input{margin-top:4px;flex:0 0 auto;width:18px;height:18px;accent-color:#2560a3}.mc-catalog-model>span{display:grid;gap:5px;min-width:0;overflow-wrap:anywhere;line-height:1.6}.mc-catalog-model strong{font-family:Consolas,"Microsoft YaHei",monospace;font-size:13px}.mc-catalog-model small{font-size:12px;color:#40566e}.mc-catalog input:focus-visible{outline:2px solid #2560a3;outline-offset:2px}.mc-catalog>.mc-checkbox{display:flex;align-items:start;gap:9px;line-height:1.8;margin:16px 0;color:#40566e;font-size:12px}.mc-catalog>.mc-checkbox>input{flex:0 0 auto;margin-top:4px}
@media(max-width:620px){.mc-catalog-heading{align-items:stretch}.mc-catalog-heading>span{padding:0}.mc-catalog-model{padding:12px 10px;gap:10px}.mc-catalog-model>input{width:22px;height:22px}.mc-catalog-list{max-height:380px}.mc-catalog .mc-section-title>.button{align-self:flex-end}}
.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}
+15 -7
View File
@@ -14,6 +14,8 @@ import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
import { ModelCatalog } from './ModelCatalog';
import type { CatalogModel } from '../shared/contracts/model-catalog.mjs';
import type { ModelSpecConnection } from '../shared/contracts/official-model-registry.mjs';
import { RequestContractSettings, requestVersionLabel } from './RequestContractSettings';
import { defaultMessagesAuth } from '../shared/contracts/model-request-contract.mjs';
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
const upstreamCapacity = (value: ModelSpecConnection, field: 'contextLimit' | 'maxOutputTokens') => {
@@ -56,6 +58,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const [noticeFailure, setNoticeFailure] = useState<RuntimeFailure | null>(null);
const noticeRef = useRef<HTMLDivElement>(null);
const [probeScopes, setProbeScopes] = useState<Record<string, string>>({});
const [networkTarget, setNetworkTarget] = useState('');
const [operations, setOperations] = useState<Operations | null>(null), [autoInspect, setAutoInspect] = useState(false);
@@ -89,6 +92,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]);
useEffect(() => { setCredentialKey(''); if (tab === 'credentials') void refreshCredentials().catch(error => { if (alive.current) setNotice(error.message); }); }, [tab]);
useEffect(() => { if (!editing) return; const frame = requestAnimationFrame(() => document.querySelector('.mc-editor[aria-label="编辑模型连接"]')?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [editing]);
useEffect(() => { if (!notice) return; const frame = requestAnimationFrame(() => noticeRef.current?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [notice]);
useEffect(() => {
const ensureVisible = () => { const nav = tabsRef.current, button = nav?.querySelector<HTMLButtonElement>('button[aria-current]'); if (!nav || !button) return;
const area = nav.getBoundingClientRect(), target = button.getBoundingClientRect(), start = target.left - area.left;
@@ -107,9 +111,10 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<nav ref={tabsRef} className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['network', '连接诊断', Activity], ['pools', '模型池', Layers3], ['budgets', '运行预算', Settings2], ['waits', '等待时限', Settings2], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
const Symbol = Icon as typeof Server; return <button key={id as string} type="button" aria-current={tab === id ? 'page' : undefined} onClick={() => { setTab(id as string); setNotice(''); }}><Symbol size={16} />{title as string}</button>;
})}<button className="mc-refresh" type="button" disabled={working} onClick={() => void act(refresh)} aria-label="刷新模型中心"><RefreshCw size={16} /></button></nav>
{notice && <div className="mc-notice" role="status">{notice}{noticeFailure && <ModelErrorDetails failure={noticeFailure} />}</div>}
{busy && <p className="mc-notice">有任务正在执行;连接可停用,其他配置请在任务结束后修改。</p>}
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
<div className="mc-content">
{notice && <div ref={noticeRef} className="mc-notice" role="status">{notice}{noticeFailure && <ModelErrorDetails failure={noticeFailure} />}</div>}
{busy && <p className="mc-notice">{runtimeConfig?.executionMode === 'unrestricted' ? '当前任务使用已冻结的模型设置;新设置用于新任务。' : '有任务正在执行;连接可停用,其他配置请在任务结束后修改。'}</p>}
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <>
{tab === 'connections' && <> <section className="mc-route-control" aria-label="默认模型选择">
<div className="mc-route-heading"><div><h3>新任务默认模型</h3><p>选择已保存的连接,或使用模型池调度。切换本身不请求模型。</p></div><button className="button secondary" disabled={locked} onClick={addConnection}><Plus size={15} />添加模型</button></div>
<label className="mc-route-select">当前选择<select aria-label="新任务默认模型" disabled={locked || !runtimeConfig} value={runtimeConfig?.mode === 'demo' || !connections.some(value => value.id === selected?.id) && selected?.type !== 'pool' ? '' : selected?.type + ':' + selected?.id} onChange={event => void selectRoute(event.target.value)}>
@@ -131,7 +136,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
{!connections.length && catalogSource === null && !editing && <div className="mc-empty"><strong>还没有模型连接</strong><p>从上游获取可用型号,选择后即可开始开发。</p></div>}
<div className="mc-connections">{connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id} data-connection-id={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.requestContract?.auth === 'none' ? '未自动添加' : value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · {requestVersionLabel(value)}</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
{value.upstreamModel && <p className="mc-help">型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。</p>}
{!!value.modelSpecification?.conflicts.length && <p className="mc-help">有 {value.modelSpecification.conflicts.length} 项规格声明差异,可在“推理与能力”的“模型规格与来源”查看。原目录与显式设置分别保留。</p>}
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
@@ -147,7 +152,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
{nativeTarget && <NativeParameters executionMode={runtimeConfig?.executionMode} 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 value={draft.brand} onChange={event => { const brand = event.target.value; setDraft({ ...draft, brand,
...(!draft.id ? brand === 'Anthropic' ? { baseUrl: 'https://api.anthropic.com', protocol: 'anthropic-messages' } : brand === 'OpenAI' ? { baseUrl: 'https://api.openai.com/v1', protocol: 'responses' } : brand === 'DeepSeek' ? { baseUrl: 'https://api.deepseek.com', protocol: 'chat-completions' } : {} : {}) }); }}>{['自定义', 'OpenAI', 'Anthropic', '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, 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>
@@ -155,7 +161,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={runtimeConfig?.executionMode !== 'unrestricted' && draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<p className="mc-help mc-full" aria-label="请求地址预览">POST {previewUrl(draft)}<br />{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。</p>
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="Messages 鉴权" value={draft.messagesAuth ?? 'api-key'} onChange={event => setDraft({ ...draft, messagesAuth: event.target.value })}><option value="api-key">x-api-key(Anthropic 标准)</option><option value="bearer">Bearer(兼容服务)</option></select></label>}
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="Messages 鉴权" value={draft.messagesAuth ?? ''} onChange={event => setDraft({ ...draft, messagesAuth: event.target.value || undefined })}><option value="">连接默认({defaultMessagesAuth(draft, { existing: !!draft.id }) === 'bearer' ? 'Bearer' : 'x-api-key'})</option><option value="api-key">x-api-key(官方仍支持)</option><option value="bearer">Bearer(官方与兼容服务)</option></select></label>}
<RequestContractSettings connection={draft} value={draft.requestContract} busy={locked} existing={!!draft.id} onChange={value => setDraft({ ...draft, requestContract: value })} />
<label>请求模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
<label>型号核对<select aria-label="型号核对" value={draft.modelIdentityPolicy} onChange={event => setDraft({ ...draft, modelIdentityPolicy: event.target.value })}><option value="record">记录请求与返回型号</option><option value="require-match">严格核对型号</option></select></label>
<p className="mc-help mc-full">{runtimeConfig?.executionMode === 'unrestricted' ? '当前完全开放执行:记录型号差异后继续;所选核对策略仍会保存。' : '严格核对时,型号不一致或无法核对会暂停并保留原响应。'}</p>
@@ -219,6 +226,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对宿主、任务、来源与数据,按页检查历史工件。</p></div><button className="button primary" disabled={working} onClick={() => void act(() => inspect())}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div>{operations.artifacts && <div className="mc-operations-pages" aria-label="历史工件巡检分页"><p className="mc-help">本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项</p><div className="mc-row-actions"><button className="button" disabled={working || operations.artifacts.olderOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.olderOffset!))}>检查更早工件</button><button className="button" disabled={working || operations.artifacts.newerOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.newerOffset!))}>检查较新工件</button></div>{operations.artifacts.results.filter(value => !value.passed).map(value => <p className="mc-help error" key={value.id}>工件 {value.id}:{value.error}</p>)}</div>}<p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</div>}
</>}
</div>
</section>;
}
+2
View File
@@ -3,6 +3,7 @@ import { useState } from 'react';
import type { RuntimeFailure } from './types';
import { downloadArtifact } from './api';
import './ModelErrorDetails.css';
import { ModelRequestDetails } from './ModelRequestDetails';
const decisions: Record<string, string> = { retry_after_wait: '按等待时间重试', stream_not_replayed: '流式响应已开始,保留原片段并停止自动重发',
not_retryable: '该错误不在同一线路自动重试', attempt_limit: '达到本次尝试上限', wait_budget: '剩余等待预算不足,保持上游建议时间并结束本次请求', passthrough: '透传模式保留本次上游错误,等待手动处理' };
@@ -31,6 +32,7 @@ export function ModelErrorDetails({ failure }: { failure: RuntimeFailure }) {
{failure.retryDecision && <><dt>重试处理</dt><dd>{decisions[failure.retryDecision] ?? failure.retryDecision}</dd></>}
</dl>
{!upstream && failure.detail && <p>{failure.detail}</p>}
{failure.requestMetadata && <ModelRequestDetails request={failure.requestMetadata} responseHeaders={upstream?.headers} />}
{upstream?.rawPreview !== undefined && <><p className="model-error-caption">上游原文{upstream.scope === 'sse-event' ? ' · 失败事件' : ' · 响应正文'}{upstream.capture?.redacted ? ' · 已脱敏' : ''}{upstream.previewTruncated ? ' · 此处显示前 8000 字符' : ''}</p>
<pre tabIndex={0} aria-label="上游错误原文">{upstream.rawPreview || '(空响应)'}</pre>
{upstream.capture && <p className="model-error-caption">已接收 {upstream.capture.receivedBytes.toLocaleString()} 字节,保留前 {upstream.capture.capturedBytes.toLocaleString()} 字节。{upstream.capture.complete ? '该范围完整接收。' : upstream.capture.truncated ? '已达到保存上限,仅保留前缀;完整长度未知。' : '接收中断,原文可能不完整。'}{upstream.artifactScope === 'sse-stream' ? '下载文件包含已保存的整段事件流。' : ''}</p>}
+16
View File
@@ -0,0 +1,16 @@
import type { PreparedRequestMetadata } from './types';
const fields: Record<string, string> = { model: '型号', requestUrl: '地址', headers: '请求头', identity: '连接或凭据修订', nonPromptParameters: '非提示参数' };
export function ModelRequestDetails({ request, responseHeaders }: { request: PreparedRequestMetadata; responseHeaders?: Record<string, string> }) {
const headers = Object.fromEntries(request.headers);
const frozen = request.source === 'frozen-run-contract';
return <details className="mc-request-details"><summary>{frozen ? '冻结请求版本与请求头' : '实际请求版本与请求头'}</summary>
<dl><dt>{frozen ? '冻结 API 版本' : '实际 API 版本'}</dt><dd>{headers['anthropic-version'] ?? (request.protocol === 'anthropic-messages' ? '未附加版本头' : '由接口决定')}{responseHeaders?.['openai-version'] && ' · 响应 openai-version ' + responseHeaders['openai-version']}{responseHeaders?.['anthropic-version'] && ' · 响应 anthropic-version ' + responseHeaders['anthropic-version']}</dd>
<dt>Beta</dt><dd>{headers['anthropic-beta'] ?? '未附加'}</dd><dt>请求资料版本</dt><dd>{request.contract.defaultsVersion}</dd>
<dt>请求设置指纹</dt><dd><code>{request.fingerprint}</code></dd><dt>请求体 SHA256</dt><dd><code>{request.bodySha256 ?? '无请求体'}</code></dd>
{request.previousFingerprint !== undefined && <><dt>与前次比较</dt><dd>{request.previousFingerprint === null ? '首次请求或新路线' : request.previousFingerprint === request.fingerprint ? '观察设置相同' : '观察设置变化:' + (request.changed ?? []).map(field => fields[field] ?? field).join('、')}</dd></>}
</dl>
<p className="mc-help">{frozen ? '按原运行快照核对设置;鉴权头以凭据模板表示,实际发送以请求账本为准。' : '记录准备提交的请求设置,凭据以引用显示;传输层可能补充 HTTP 头。'}指纹只用于核对变化,缓存命中以上游实际用量为准。</p>
<pre aria-label={frozen ? '冻结请求头' : '实际请求头'}>{JSON.stringify(headers, null, 2)}</pre>
{!!Object.keys(responseHeaders ?? {}).length && <details><summary>上游响应头</summary><pre aria-label="上游响应头">{JSON.stringify(responseHeaders, null, 2)}</pre></details>}
</details>;
}
+5 -2
View File
@@ -9,9 +9,11 @@ import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
import type { RuntimeFailure } from './types';
import './ModelRequestLedger.css';
import { ModelRequestDetails } from './ModelRequestDetails';
import type { PreparedRequestMetadata } from './types';
export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string;
upstreamResponse?: { requestId?: string | null; responseUrl?: string | null }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean;
export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; requestMetadata?: PreparedRequestMetadata;
upstreamResponse?: { requestId?: string | null; responseUrl?: string | null; headers?: Record<string, string> }; id: string; connectionId?: string; 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?: TokenUsage | null };
@@ -68,6 +70,7 @@ export function ModelRequestLedger({ connections, refreshVersion }: { connection
{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? '(已脱敏)' : ''}</code>}
{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={disabled} onClick={() => void act(() => downloadArtifact(value.sessionId!, value.responseArtifactId!, 'model-response-' + value.id + (value.streaming ? '.sse' : '.json')))}>下载已保存的响应</button>}
{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}
{value.requestMetadata && <ModelRequestDetails request={value.requestMetadata} responseHeaders={value.upstreamResponse?.headers} />}
{value.reason && <p className="mc-card-warning">{value.reason}</p>}
<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model ?? '原记录未保存'} />
{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}
+2
View File
@@ -4,6 +4,7 @@ import { api } from './api';
import { Modal } from './components';
import { ModelUsageDetails } from './ModelUsageDetails';
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
import { ModelRequestDetails } from './ModelRequestDetails';
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
@@ -47,6 +48,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
<dt>历史记录</dt><dd>保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录</dd>
<dt>已报告输出</dt><dd>{plan.actualUsage?.completion_tokens === undefined ? '服务未返回' : number(plan.actualUsage.completion_tokens) + ' tokens'}</dd>
{plan.prefixAudit && <><dt>缓存前缀核对</dt><dd>{plan.prefixAudit.variants.map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.previousPromptBytes === null ? '首次请求或新路线' : '共同前缀 ' + number(variant.commonPrefixBytes) + ' B'}{variant.reason === 'tool_surface_changed' ? ' · 可用工具已变化' : ''}</div>)}<small>共同前缀用于核对稳定性,不等于上游命中。</small></dd></>}
{plan.requestContractAudit && <><dt>版本与非提示参数</dt><dd>{plan.requestContractAudit.variants.map((variant, index) => <ModelRequestDetails key={index} request={variant} />)}</dd></>}
{observation && <><dt>请求归属</dt><dd>{({ main: '主任务', diagnostic: '独立诊断', worker: '子任务' } as Record<string, string>)[observation.path.kind] ?? observation.path.kind}</dd></>}
{userMessage && <><dt>用户消息实例</dt><dd><code title={userMessage.id}>{userMessage.id.slice(0, 12)}</code><small>同样的文字分别记录,不按文本合并。</small></dd></>}
{plan.prefixAudit?.variants.some(variant => variant.firstChange && variant.previousPromptBytes !== null) && <><dt>首次变化位置</dt><dd>{plan.prefixAudit.variants.filter(variant => variant.previousPromptBytes !== null).map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.firstChange ? changeLabel(variant.firstChange.path) : '前缀内容相同'}</div>)}</dd></>}
+53
View File
@@ -0,0 +1,53 @@
import { useEffect, useRef, useState } from 'react';
import { requestHeaders, requestContractSettings, REQUEST_CONTRACT_SOURCES } from '../shared/contracts/model-request-contract.mjs';
import type { RequestConnection, RequestContract } from '../shared/contracts/model-request-contract.mjs';
export function RequestContractSettings({ connection, value, busy, existing, onChange, onValidityChange }: { connection: RequestConnection; value?: RequestContract; busy: boolean; existing: boolean; onChange: (value: RequestContract) => void; onValidityChange?: (valid: boolean) => void }) {
const defaults = requestContractSettings(undefined, connection, { existing });
const contract = value ?? defaults;
const [headers, setHeaders] = useState(JSON.stringify(contract.headers, null, 2));
const appliedHeaders = useRef(JSON.stringify(contract.headers));
const [error, setError] = useState('');
const headerEditor = useRef<HTMLTextAreaElement>(null);
useEffect(() => { onValidityChange?.(true); }, []);
useEffect(() => {
const serialized = JSON.stringify(contract.headers);
if (serialized !== appliedHeaders.current) { appliedHeaders.current = serialized; setHeaders(JSON.stringify(contract.headers, null, 2)); setError(''); headerEditor.current?.setCustomValidity(''); onValidityChange?.(true); }
}, [JSON.stringify(contract.headers)]);
const update = (patch: Partial<RequestContract>) => onChange({ ...contract, ...patch });
return <details className="mc-request-settings mc-full"><summary>请求协议 · 版本、认证与请求头</summary>
<p className="mc-help">按供应商官方配置发送。已有连接保留原版本;修改从新任务生效,原运行与原生参数保持。</p>
<div className="mc-form-grid">
{connection.protocol === 'anthropic-messages' && <>
<label>API 请求版本<input aria-label="API 请求版本" disabled={busy || contract.anthropicVersion === null} value={contract.anthropicVersion ?? ''} onChange={event => update({ anthropicVersion: event.target.value, versionSource: 'explicit' })} /></label>
<label className="mc-checkbox"><input aria-label="省略版本头" type="checkbox" disabled={busy} checked={contract.anthropicVersion === null} onChange={event => update({ anthropicVersion: event.target.checked ? null : defaults.anthropicVersion ?? '', versionSource: 'explicit' })} />省略版本头(须接口允许)</label>
<label className="mc-full">Beta 功能(逗号分隔)<input aria-label="Beta 功能" disabled={busy} value={contract.anthropicBetas.join(',')} placeholder="按功能文档填写,默认不开启" onChange={event => update({ anthropicBetas: event.target.value ? event.target.value.split(',') : [] })} /></label>
<p className="mc-help mc-full">Anthropic 当前官方版本为 2026-10-21,发送 temperature / top_p / top_k 会收到上游 400;原参数不会自动删除。DeepSeek 的版本头可选。<a href={REQUEST_CONTRACT_SOURCES.anthropicVersion.url} target="_blank" rel="noreferrer">查看官方版本说明</a></p>
</>}
<label>自动鉴权<select aria-label="自动鉴权" disabled={busy} value={contract.auth} onChange={event => update({ auth: event.target.value as RequestContract['auth'] })}><option value="default">使用连接的鉴权方式</option><option value="none">不自动添加鉴权头</option></select></label>
<p className="mc-help">自定义鉴权可在下方用 {'{{credential}}'} 引用本连接 Key。额外头同名时覆盖默认值;null 移除该头。</p>
<label className="mc-full">额外请求头 JSON<textarea ref={headerEditor} aria-label="额外请求头 JSON" rows={5} spellCheck={false} disabled={busy} value={headers} onChange={event => {
const text = event.target.value; setHeaders(text);
try { const parsed = JSON.parse(text), normalized = requestContractSettings({ ...contract, headers: parsed }, connection, { previous: contract });
appliedHeaders.current = JSON.stringify(normalized.headers); onChange(normalized); setError(''); event.target.setCustomValidity(''); onValidityChange?.(true); }
catch (cause) { const message = cause instanceof Error ? cause.message : '请求头 JSON 格式无效。'; setError(message); event.target.setCustomValidity(message); onValidityChange?.(false); }
}} /></label>
<p className="mc-help mc-full">可填写 OpenAI-Organization、OpenAI-Project、anthropic-workspace-id 或代理要求的其他头。凭据在独立 API Key 输入中填写,不进入普通设置;版本或头不被上游接受时保留原错误。</p>
<label>模型请求路径<input aria-label="模型请求路径" disabled={busy} value={contract.completionPath ?? ''} placeholder="留空使用协议默认" onChange={event => update({ completionPath: event.target.value || null })} /></label>
<label>模型目录路径<input aria-label="模型目录路径" disabled={busy} value={contract.modelsPath ?? ''} placeholder="留空使用协议默认" onChange={event => update({ modelsPath: event.target.value || null })} /></label>
<p className="mc-help mc-full">自定义路径从 / 开始,基于当前服务域名;默认路径继续基于接口根地址。资料版本 {contract.defaultsVersion} 与实际 API 版本分别记录。</p>
</div>
{error && <p className="mc-card-warning" role="alert">{error}</p>}
<button type="button" className="button secondary" disabled={busy} onClick={() => {
const next = requestContractSettings(undefined, { ...connection, requestContract: undefined }, { existing: false });
onChange(next); setHeaders('{}'); appliedHeaders.current = '{}'; setError('');
headerEditor.current?.setCustomValidity('');
onValidityChange?.(true);
}}>采用当前请求默认</button>
</details>;
}
export const requestVersionLabel = (connection: RequestConnection) => {
const version = requestHeaders(connection).get('anthropic-version');
return version === null ? '未附加版本头' : 'anthropic-version ' + version;
};
+1 -2
View File
@@ -327,8 +327,7 @@ button { touch-action: manipulation; }
.mc-tabs .mc-refresh { margin: auto 0 0; justify-content: flex-start; }
.mc-tabs .mc-refresh::after { content: '刷新连接状态'; font-size: 11px; }
.mc-content { grid-column: 2; grid-row: 2; background: #fff; padding: 24px 26px; }
.mc-notice { grid-column: 2; grid-row: 2; z-index: 1; align-self: start; box-shadow: 0 5px 20px rgb(var(--orven-shadow-rgb) / 7%); }
.model-center:has(> .mc-notice) .mc-content { padding-top: 96px; }
.mc-content > .mc-notice { margin: 0 0 20px; box-shadow: 0 5px 20px rgb(var(--orven-shadow-rgb) / 7%); }
.model-center > .mc-empty { grid-column: 2; grid-row: 2; align-self: start; margin: 24px; }
.mc-connections { grid-template-columns: 1fr; }
}
+9
View File
@@ -87,6 +87,7 @@ export interface Session {
inputAttachments?: InputAttachment[];
}
export interface RuntimeFailure {
requestMetadata?: PreparedRequestMetadata;
modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity;
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
detail?: string; suggestion?: string; attempts?: number; httpStatus?: number; code?: string | null;
@@ -144,6 +145,13 @@ export interface CodeResult {
export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeResult[]; totalMatches: number; truncated: boolean; index: CodeIndexSummary }
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: number; routing?: { type: string; name: string; members: { id: string; name: string; model: string; baseUrl: string }[] } }
export interface ModelSnapshot { requestContract?: import('../shared/contracts/model-request-contract.mjs').RequestContract }
export interface PreparedRequestMetadata {
schemaVersion: number; representation: string; method: string; protocol: string; model: string | null; requestUrl: string; headers: [string, string][];
identity: { connectionId: string | null; connectionRevision: number | null; credentialRevision: number | null };
contract: import('../shared/contracts/model-request-contract.mjs').RequestContract; bodySha256: string | null; nonPromptParameters: Record<string, unknown>; nonPromptSha256: string;
fingerprint: string; fingerprintMethod: string; source: string; upstreamCache: string; previousFingerprint?: string | null; reason?: string; changed?: string[];
}
export interface ModelConsumption { modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity; attemptId: string; requestId: string | null; connectionId: string | null; connectionName: string | null; model: string; endpoint: string; protocol: string; usageStatus: string; outcome: string; usage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; estimatedUnknownTokens: number }
export interface Usage { requests: number; inputTokens: number; outputTokens: number; totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }
@@ -201,6 +209,7 @@ export interface ContextPlan {
firstChange?: { path: string; kind: string; sha256: string | null; previousSha256: string | null } | null;
blocks?: { path: string; role: string | null; sha256: string; bytes: number }[];
}[] };
requestContractAudit?: { schemaVersion: number; previousPlanId: string | null; variants: PreparedRequestMetadata[] };
requestObservation?: { schemaVersion: number; path: { kind: string; key: string }; providerHistorySha256: string;
userMessageInstances: { id: string; providerIndex: number; origin: string; sha256: string }[];
toolSurface: { generation: string; execution: string; entries: { name: string; group: string; registered: boolean; assembled: boolean; visible: boolean; reason: string; schemaSha256: string; definitionSha256: string; definitionBytes: number; generation: string }[] } | null };