Files
Agent-Workbench/src/core/models/model-hub.mjs
T

236 lines
17 KiB
JavaScript

import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
const error = (message, status = 400) => Object.assign(new Error(message), { status });
const bounded = (value, fallback, min, max) => Number.isFinite(Number(value)) ? Math.max(min, Math.min(max, Math.trunc(Number(value)))) : fallback;
const label = (value, maximum = 100) => String(value ?? '').trim().slice(0, maximum);
export function modelEndpoint(value) {
let url;
try { url = new URL(String(value)); } catch { throw error('请输入有效的模型接口根地址。'); }
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.toString().length > 1000) throw error('模型地址只支持不含账号、查询参数的 http/https 地址。');
return url.toString().replace(/\/+$/, '');
}
export class ModelHub {
constructor(store, provider) {
this.store = store; this.provider = provider;
this.state = store.storage.meta('modelRegistry', { schema: 1, revision: 0, selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} });
this.health = new Map(); this.leases = new Map(); this.cursors = new Map(); this.sticky = new Map(); this.waiting = 0;
this.attempts = store.storage.meta('modelAttempts', []);
// A process exit leaves a request outcome unknown; never replay it here.
let recovered = false;
for (const attempt of this.attempts) if (attempt.status === 'running') { attempt.status = 'unknown'; attempt.finishedAt = stamp(); attempt.reason = '宿主重启,请求结果与用量待核对。'; recovered = true; }
if (recovered) this.saveAttempts();
provider.credentials ??= new Map();
}
save(config = null) {
this.state.revision++;
if (this.editingRegistry) {
if (config) throw error('批量连接导入不能修改当前运行模式。');
return;
}
const persist = () => this.store.storage.setMeta('modelRegistry', this.state);
try {
if (config) this.store.saveConfig(config, { beforeSave: persist });
else this.store.storage.transaction(persist);
} catch (cause) {
// Keep runtime routing consistent with the authoritative committed state.
this.state = this.store.storage.meta('modelRegistry', { schema: 1, revision: 0,
selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} });
throw cause;
}
}
editRegistry(action) {
if (this.editingRegistry) return action();
const before = structuredClone(this.state), credentials = new Map(this.provider.credentials);
this.editingRegistry = true;
try {
return this.store.storage.transaction(() => {
const result = action();
this.store.storage.setMeta('modelRegistry', this.state);
return result;
});
} catch (cause) {
this.state = before;
this.provider.credentials.clear();
for (const [id, value] of credentials) this.provider.credentials.set(id, value);
throw cause;
} finally { this.editingRegistry = false; }
}
saveAttempts() { this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
connections() {
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.state.connections];
}
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: 1 } : this.provider.credentials.get(connection.id); }
identity(connection) { return connection.id + ':' + connection.revision + ':' + (this.credential(connection)?.revision ?? 0); }
status(connection) {
const credential = this.credential(connection), health = this.health.get(this.identity(connection));
const ready = connection.enabled && (!connection.requiresKey || !!credential?.key);
return { ...connection, hasKey: !!credential?.key, credentialRevision: credential?.revision ?? 0, credentialStorage: 'memory',
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' },
capabilities: { tools: 'protocol_declared', vision: 'unknown', audio: 'unknown' } };
}
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: 'memory', restart: '临时凭据在宿主退出后需要重新填写。', attemptsRetained: 1000 } }; }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
upsert(input) {
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
const previous = input.id ? this.connection(input.id) : null;
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
if (input.protocol && input.protocol !== 'chat-completions') throw error('当前接入仅支持经过验证的 Chat Completions 协议。');
const name = label(input.name), model = label(input.model, 200);
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol: 'chat-completions', model,
baseUrl: modelEndpoint(input.baseUrl), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
if (Object.hasOwn(input, 'apiKey')) {
if (typeof input.apiKey !== 'string' || input.apiKey.length > 16000) throw error('模型凭据格式无效。');
}
this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
this.save();
if (Object.hasOwn(input, 'apiKey')) this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision: (this.provider.credentials.get(connection.id)?.revision ?? 0) + 1 });
return this.status(connection);
}
toggle(id, enabled) {
if (id === legacyId) throw error('原连接不能停用,请选择离线演示或其他连接。');
const value = this.connection(id); value.enabled = enabled === true; value.revision++; value.updatedAt = stamp(); this.save(); return this.status(value);
}
pool(input) {
const previous = input.id ? this.state.pools.find(value => value.id === input.id) : null;
if (input.id && !previous) throw error('模型池不存在。', 404);
if (previous && input.revision !== previous.revision) throw error('模型池已修改,请刷新后重试。', 409);
if (!previous && this.state.pools.length >= 32) throw error('最多保存32个模型池。');
if (!label(input.name) || !Array.isArray(input.members) || !input.members.length || input.members.length > 32) throw error('模型池需要名称和1–32个成员。');
const seen = new Set();
const members = input.members.map(value => {
this.connection(value.connectionId);
if (seen.has(value.connectionId)) throw error('同一连接不能重复加入模型池。');
seen.add(value.connectionId); return { connectionId: value.connectionId, weight: bounded(value.weight, 1, 1, 10) };
});
if (!['round-robin', 'weighted'].includes(input.strategy || 'round-robin')) throw error('请选择轮询或权重策略。');
const value = { id: previous?.id ?? randomUUID(), name: label(input.name), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
}
select(input, config = null) {
if (input.type === 'connection') this.connection(input.id);
else if (input.type === 'pool') { if (!this.state.pools.some(item => item.id === input.id)) throw error('模型池不存在。'); }
else if (input.type !== 'legacy') throw error('模型选择无效。');
this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id };
// Selection and mode must commit together; the original endpoint/key pair
// stays intact and a Run alone receives its immutable routing snapshot.
this.save(config ?? (input.type !== 'legacy' ? { mode: 'compatible' } : null));
return this.view();
}
prepare(config) {
if (config.mode === 'demo' || this.state.selected.type === 'legacy') return config;
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,
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,
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 } };
}
available(member) {
const current = this.connections().find(value => value.id === member.id);
if (!current?.enabled || current.revision !== member.revision || (this.credential(current)?.revision ?? 0) !== member.credentialRevision) return false;
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) {
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 ready = healthy.filter(value => (this.leases.get(value.id) ?? 0) < value.concurrency);
if (ready.length) {
const remembered = routing.sticky && this.sticky.get(runId);
let selected = ready.find(value => value.id === remembered);
if (!selected) {
const weighted = ready.flatMap(value => Array(routing.strategy === 'weighted' ? value.weight : 1).fill(value));
const cursor = this.cursors.get(routing.id) ?? 0; selected = weighted[cursor % weighted.length]; this.cursors.set(routing.id, cursor + 1);
}
this.leases.set(selected.id, (this.leases.get(selected.id) ?? 0) + 1);
this.sticky.set(runId, selected.id); if (this.sticky.size > 1000) this.sticky.delete(this.sticky.keys().next().value);
let released = false;
return { member: selected, release: () => { if (!released) { released = true; this.leases.set(selected.id, Math.max(0, (this.leases.get(selected.id) ?? 0) - 1)); } } };
}
if (!healthy.length) throw error('模型池暂时没有可用成员;已完成操作保留,请核对凭据、停用状态和冷却时间。');
if (Date.now() >= deadline) throw error('等待模型并发槽位超时,任务已保留。');
await delay(50, undefined, signal ? { signal } : {});
}
} finally { this.waiting--; }
}
async complete(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;
let lastError;
for (let count = 1; count <= routing.maxAttempts; count++) {
signal?.throwIfAborted();
let lease;
try { lease = await this.acquire(routing, runId, excluded, signal, deadline); }
catch (cause) { throw lastError ?? cause; }
const member = lease.member, credential = this.credential(member);
const actualBody = { ...body, model: member.model };
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(),
requestSha256: createHash('sha256').update(bytes).digest('hex'), usage: null, usageStatus: 'unknown' };
try {
if (plan?.sessionId) {
const session = this.store.session(plan.sessionId), run = this.store.owned('run', plan.runId, session.id);
const artifact = this.store.artifactStore.write(session, run, JSON.parse(this.provider.redact(bytes)), { kind: 'model-attempt-request' });
attempt.requestArtifactId = artifact.id;
this.store.core.artifact.set(artifact.id, artifact);
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);
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.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) {
// A user stop is not evidence that the provider is unhealthy. Keep
// the attempt, release its lease, and leave the connection eligible.
this.health.set(this.identity(member), { ...health, state: 'interrupted', lastInterruptedAt: stamp() });
} else {
const blocked = [401, 403].includes(attempt.httpStatus);
const failedAt = Date.now();
this.health.set(this.identity(member), { state: blocked ? 'needs_attention' : 'failed', blocked, lastFailureAt: new Date(failedAt).toISOString(),
failures: (health.failures ?? 0) + 1, cooldownUntil: failedAt + (diagnostic?.retryAfterMs ?? Math.min(60000, 1000 * 2 ** Math.min(health.failures ?? 0, 5))), reason: attempt.reason });
}
lastError = cause; excluded.add(member.id); this.sticky.delete(runId);
signal?.throwIfAborted();
if (!diagnostic?.retryable || count === routing.maxAttempts) throw cause;
onProgress?.({ phase: 'retrying', attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, modelAttemptId: attempt.id,
diagnostic, waitMs: 0, switching: true });
} finally { attempt.finishedAt = stamp(); lease.release(); this.saveAttempts(); }
}
throw lastError ?? new ModelRequestError({ message: '模型池请求未完成。', kind: 'connection' });
}
}