feat(models): execute Responses and validated streams with capability routing

This commit is contained in:
Agent Workbench Dev
2026-10-31 22:27:53 +08:00
parent 578cf88eca
commit eeb11d6a76
24 changed files with 856 additions and 52 deletions
+79 -12
View File
@@ -2,7 +2,8 @@ import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { CredentialVault } from './credential-vault.mjs';
import { modelProtocol, capabilityDeclarations, capabilityView } from '../../shared/contracts/model-capabilities.mjs';
import { modelProtocol, capabilityDeclarations, capabilityView, capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
import { actualRequest, requestVariants } from '../../shared/contracts/model-request.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -109,12 +110,50 @@ export class ModelHub {
status: !connection.enabled ? 'disabled' : !ready ? 'needs_key' : health?.blocked ? 'needs_attention' : health?.cooldownUntil > Date.now() ? 'cooling' : 'configured',
activeRequests: this.leases.get(connection.id) ?? 0, health: health ?? { state: 'unverified' },
streaming: connection.streaming === true, capabilitySchema: 1, capabilityDeclarations: capabilityDeclarations(undefined, connection.capabilityDeclarations),
capabilities: capabilityView(connection, credential?.revision ?? 0) };
...(this.state.capabilityResults?.[connection.id] ? { capabilityEvidence: this.state.capabilityResults[connection.id] } : {}),
capabilities: capabilityView({ ...connection, capabilityEvidence: this.state.capabilityResults?.[connection.id] }, credential?.revision ?? 0) };
}
view() { return { revision: this.state.revision, selected: this.state.selected, connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: this.attempts.slice(-100).reverse(), waiting: this.waiting,
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: 1000 } }; }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
async probe(id, scope = 'text') {
if (!['text', 'tools', 'streaming'].includes(scope)) throw error('请选择文本、工具调用或流式检测。');
if (this.probing) throw error('已有模型能力检测正在执行,请等待结束。', 409);
this.probing = true;
try {
const connection = { ...this.connection(id) }, member = { ...connection, credentialRevision: this.credential(connection)?.revision ?? 0 };
if (!this.available(member)) throw error('该连接不可用,请核对凭据、冷却或停用状态。');
member.streaming = scope === 'streaming';
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 } } }] : [];
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,
strategy: 'round-robin', sticky: false, maxAttempts: 1, queueTimeoutMs: 1000, members: [member] } };
let attemptId;
const result = await this.provider.complete(config, [{ role: 'user', content: scope === 'tools' ? 'Call workbench_capability_echo with nonce ' + nonce + '. Do not reply with plain text.' : 'Reply OK.' }], null, undefined,
event => { if (event.modelAttemptId) attemptId = event.modelAttemptId; }, null, tools, { attempts: 1 });
if (scope === 'tools') {
const calls = result.message.tool_calls;
if (calls?.length !== 1 || calls[0].function.name !== 'workbench_capability_echo' || JSON.parse(calls[0].function.arguments).nonce !== nonce) throw error('服务没有返回要求的原工具调用;未标为已验证。');
} else if (!result.message.content.trim() || result.message.tool_calls?.length) throw error('服务没有返回纯文本响应;未标为已验证。');
if (this.connection(id).revision !== connection.revision || (this.credential(connection)?.revision ?? 0) !== member.credentialRevision) throw error('检测期间连接已变化,原结果保留但不更新能力结论。', 409);
this.editRegistry(() => {
this.state.capabilityResults ??= {};
const previous = this.state.capabilityResults[id];
const results = previous?.connectionRevision === connection.revision && previous.credentialRevision === member.credentialRevision ? { ...previous.results } : {};
results[scope] = 'verified';
const attempt = this.attempts.find(value => value.id === attemptId);
if (!attempt || attempt.connectionId !== id || attempt.status !== 'completed') throw error('检测原请求账本不完整,未更新能力结论。');
this.state.capabilityResults[id] = { schema: 1, connectionRevision: connection.revision, credentialRevision: member.credentialRevision, results,
checkedAt: stamp(), protocol: modelProtocol(connection.protocol), attemptId: attempt?.id, source: 'explicit-model-probe',
scope: 'Only the requested synthetic capability; no project files, commands or real-model engineering benefit.' };
this.save();
});
return { ok: true, usage: result.usage, scope, center: this.view() };
} finally { this.probing = false; }
}
upsert(input) {
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input));
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
@@ -183,10 +222,10 @@ export class ModelHub {
const selection = this.state.selected;
const pool = selection.type === 'pool' ? this.state.pools.find(value => value.id === selection.id) : null;
if (selection.type === 'pool' && !pool) throw error('选中的模型池不存在。');
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), weight: value.weight,
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight,
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, baseUrl: members[0].baseUrl, model: members[0].model,
return { ...config, baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
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 } };
@@ -197,13 +236,15 @@ export class ModelHub {
const health = this.health.get(this.identity(member));
return (!member.requiresKey || !!this.credential(member)?.key) && !health?.blocked && !(health?.cooldownUntil > Date.now());
}
async acquire(routing, runId, excluded, signal, deadline) {
async acquire(routing, runId, excluded, signal, deadline, requirements = []) {
if (this.waiting >= 100) throw error('模型请求队列已满,请稍后继续任务。');
this.waiting++;
try {
while (true) {
signal?.throwIfAborted();
const healthy = routing.members.filter(value => this.available(value) && !excluded.has(value.id));
const eligible = routing.members.filter(value => capabilityRejections(value, requirements, value.credentialRevision).length === 0);
if (!eligible.length) throw Object.assign(error('模型池没有满足本次任务能力的成员;请核对工具调用和流式能力声明。'), { rejections: routing.members.flatMap(value => capabilityRejections(value, requirements, value.credentialRevision)) });
const healthy = eligible.filter(value => this.available(value) && !excluded.has(value.id));
const ready = healthy.filter(value => (this.leases.get(value.id) ?? 0) < value.concurrency);
if (ready.length) {
const remembered = routing.sticky && this.sticky.get(runId);
@@ -231,18 +272,28 @@ export class ModelHub {
async completeOwned(config, body, signal, onProgress, plan, execute) {
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
const requirements = config.capabilityProbe ? [] : ['text', ...(requestVariants(body).some(value => value.tools?.length) ? ['tools'] : [])];
const rejections = config.capabilityProbe ? [] : routing.members.flatMap(value => capabilityRejections(value, [...requirements, ...(value.streaming ? ['streaming'] : [])], value.credentialRevision));
const eligibleRouting = { ...routing, members: routing.members.filter(value => !rejections.some(item => item.connectionId === value.id)) };
if (!eligibleRouting.members.length) {
const attempt = { id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
poolId: routing.type === 'pool' ? routing.id : null, status: 'rejected', reason: '所有成员均不满足本次任务所需能力。', rejections, startedAt: stamp(), finishedAt: stamp(), usage: null, usageStatus: 'not_dispatched' };
this.attempts.push(attempt); this.saveAttempts();
throw error('模型池没有满足本次任务能力的成员;请核对能力声明或选择其它连接。');
}
let lastError;
for (let count = 1; count <= routing.maxAttempts; count++) {
signal?.throwIfAborted();
let lease;
try { lease = await this.acquire(routing, runId, excluded, signal, deadline); }
try { lease = await this.acquire(eligibleRouting, runId, excluded, signal, deadline, requirements); }
catch (cause) { throw lastError ?? cause; }
const member = lease.member, credential = this.credential(member);
const actualBody = { ...body, model: member.model };
const actualBody = actualRequest(body, member);
const bytes = JSON.stringify(actualBody);
const attempt = { id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
connectionId: member.id, connectionRevision: member.revision, credentialRevision: member.credentialRevision, poolId: routing.type === 'pool' ? routing.id : null,
poolRevision: routing.revision, model: member.model, endpoint: member.baseUrl, ordinal: count, status: 'running', startedAt: stamp(),
poolRevision: routing.revision, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true, endpoint: member.baseUrl, ordinal: count, status: 'running', startedAt: stamp(),
requestBytes: Buffer.byteLength(bytes, 'utf8'), requirements, rejections,
requestSha256: createHash('sha256').update(bytes).digest('hex'), usage: null, usageStatus: 'unknown' };
try {
if (plan?.sessionId) {
@@ -253,14 +304,30 @@ export class ModelHub {
this.store.save(session);
}
this.attempts.push(attempt); this.saveAttempts();
const progress = event => onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, model: member.model, modelAttemptId: attempt.id });
const result = await execute({ ...config, baseUrl: member.baseUrl, model: member.model }, credential?.key ?? '', actualBody, progress);
const progress = event => {
if (event.streamCapture !== undefined) {
attempt.stream = event.stream;
if (plan?.sessionId) {
const session = this.store.session(plan.sessionId), run = this.store.owned('run', plan.runId, session.id);
const raw = event.streamCapture, decoded = raw.toString('utf8'), redacted = this.provider.redact(decoded);
const captured = redacted === decoded ? raw : Buffer.from(redacted, 'utf8');
const artifact = this.store.artifactStore.write(session, run, captured, { kind: 'model-stream-response', mediaType: 'text/event-stream' });
this.store.core.artifact.set(artifact.id, artifact); attempt.responseArtifactId = artifact.id;
attempt.responseSha256 = artifact.sha256; attempt.responseRedacted = redacted !== decoded; this.store.save(session);
}
return;
}
if (event.streaming) attempt.partial = { sequence: event.streamSequence, bytes: event.streamBytes, textCharacters: event.textCharacters, textPreview: this.provider.redact(event.textPreview ?? '').slice(0, 8000), toolFragments: event.toolFragments };
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, baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
attempt.status = 'completed'; attempt.usage = result.usage ?? null; attempt.usageStatus = result.usage ? 'reported' : 'unknown';
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
return result;
} catch (cause) {
const diagnostic = cause.diagnostic;
attempt.status = signal?.aborted ? 'interrupted' : 'failed';
attempt.status = signal?.aborted ? 'interrupted' : diagnostic?.outcome === 'unknown' ? 'unknown' : 'failed';
attempt.reason = this.provider.redact(cause.message).slice(0, 600); attempt.httpStatus = diagnostic?.status ?? diagnostic?.httpStatus ?? null;
const health = this.health.get(this.identity(member)) ?? {};
if (signal?.aborted) {