fix: complete unrestricted waits catalog and network flows

This commit is contained in:
Agent Workbench Dev
2026-11-06 06:21:59 +08:00
parent c93c434808
commit c9c77c7ee6
32 changed files with 295 additions and 84 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ export function messagesStream(config = {}) {
message = structuredClone(start);
} else if (!message) fail('事件缺少原 message_start。');
else if (event.type === 'content_block_start') {
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || config.executionMode !== 'unrestricted' && blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
const block = event.content_block;
if (!object(block) || !['text', 'tool_use', 'thinking', 'redacted_thinking'].includes(block.type)) fail('未接入的内容块类型。');
if (block.type === 'text' && typeof block.text !== 'string' || block.type === 'tool_use' && (!object(block.input) || typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name)
+7 -7
View File
@@ -75,11 +75,11 @@ export class ModelCatalog {
this.current({ binding });
if (!unrestricted(this.hub.store) && (Date.now() >= deadline)) throw fail('获取模型目录超过60秒,请稍后重试。');
const query = cursor ? '?after_id=' + encodeURIComponent(cursor) + '&limit=100' : connection.protocol === 'anthropic-messages' ? '?limit=100' : '';
const raw = await this.hub.provider.request({ ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined,
const raw = await this.hub.provider.request({ ...this.hub.store.config, ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined,
{ attempts: 1, timeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()), totalTimeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()) });
const encoded = this.hub.provider.redact(JSON.stringify(raw), key); bytes += Buffer.byteLength(encoded);
if (bytes > 4 * 1024 * 1024) throw fail('模型目录超过4MB上限,请使用供应商筛选接口或手动添加。');
const page = catalogPage(JSON.parse(encoded)); pages++;
if (bytes > ceiling(this.hub.store, 4 * 1024 * 1024)) throw fail('模型目录超过4MB上限,请使用供应商筛选接口或手动添加。');
const page = catalogPage(JSON.parse(encoded), this.hub.store.config); pages++;
if (!unrestricted(this.hub.store) && (page.entries.length > 1000)) throw fail('单页模型超过1000项,请核对上游分页。');
for (const item of page.entries) {
if (entries.has(item.id) && JSON.stringify(entries.get(item.id)) !== JSON.stringify(item)) throw fail('上游目录包含相同型号的冲突定义,请核对后重试。');
@@ -92,10 +92,10 @@ export class ModelCatalog {
if (!unrestricted(this.hub.store) && (pages === 20 || entries.size === 1000)) { complete = false; warning = '目录仍有后续页,已达到本次获取上限;当前只显示部分模型。'; break; }
} while (true);
controller.signal.throwIfAborted(); this.current({ binding }); this.prune();
if (this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value);
if (!unrestricted(this.hub.store) && this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value);
const fetchedAt = stamp(), expires = Date.now() + 5 * 60000;
const preview = { id, entries: [...entries.values()], fetchedAt, expiresAt: new Date(expires).toISOString(), complete, warning,
source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol }, limits: { connections: 100, poolMembers: 32, catalog: 1000 } };
source: { name: connection.name, baseUrl: connection.baseUrl, protocol: connection.protocol }, limits: unrestricted(this.hub.store) ? { connections: null, poolMembers: null, catalog: null } : { connections: 100, poolMembers: 32, catalog: 1000 } };
this.previews.set(id, { preview, connection, binding, explicitKey, expires });
return preview;
} finally { this.active.delete(id); }
@@ -107,8 +107,8 @@ export class ModelCatalog {
if (!Array.isArray(input.models) || !input.models.length || !unrestricted(this.hub.store) && input.models.length > 100 || new Set(input.models).size !== input.models.length) throw fail('请选择1–100个不重复的上游模型。');
const selected = input.models.map(id => value.preview.entries.find(model => model.id === id));
if (selected.some(model => !model)) throw fail('所选模型不属于本次上游目录。');
if (selected.some(model => model.lifecycle === 'retired')) throw fail('已退役型号不能新增使用,请选择其它模型。');
if (selected.some(model => model.contextLimit && model.contextLimit < 1000 || model.maxOutputTokens && model.maxOutputTokens < 256)) throw fail('所选型号的上游容量低于当前接入下限(上下文1000 / 输出256),请选择其它型号。');
if (!unrestricted(this.hub.store) && selected.some(model => model.lifecycle === 'retired')) throw fail('已退役型号不能新增使用,请选择其它模型。');
if (!unrestricted(this.hub.store) && selected.some(model => model.contextLimit && model.contextLimit < 1000 || model.maxOutputTokens && model.maxOutputTokens < 256)) throw fail('所选型号的上游容量低于当前接入下限(上下文1000 / 输出256),请选择其它型号。');
const declarations = capabilityDeclarations(input.declarations, { text: 'unknown', tools: 'unknown', streaming: 'unknown', vision: 'unknown', audio: 'unknown' });
if (!['keep', 'manual', 'auto'].includes(input.routing ?? 'keep')) throw fail('请选择保留当前选择、手动指定或自动适配。');
if (input.routing === 'manual' && !input.models.includes(input.defaultModel)) throw fail('请在勾选的模型中指定默认型号。');
+4 -4
View File
@@ -213,13 +213,13 @@ export class ModelHub {
if (input.streaming !== undefined && typeof input.streaming !== 'boolean') throw error('流式选项必须为开启或关闭。');
const streaming = input.streaming ?? previous?.streaming ?? false;
if (!unrestricted(this.store) && streaming && declarations.streaming !== 'supported') throw error('请先声明服务支持流式输出,再开启流式请求。');
const name = label(input.name), model = label(input.model, 200);
const name = label(input.name, ceiling(this.store, 100)), model = label(input.model, ceiling(this.store, 200));
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol, model,
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', ceiling(this.store, 40)), protocol, model,
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
...capacitySettings(input, previous ?? undefined),
...capacitySettings(input, previous ?? undefined, this.store.config),
concurrency: unrestricted(this.store) ? (input.concurrency ?? 0) : bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
@@ -267,7 +267,7 @@ export class ModelHub {
seen.add(value.connectionId); return { connectionId: value.connectionId, weight: bounded(value.weight, 1, 1, 10) };
});
if (!['round-robin', 'weighted'].includes(input.strategy || 'round-robin')) throw error('请选择轮询或权重策略。');
const value = { id: previous?.id ?? randomUUID(), name: label(input.name), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
const value = { id: previous?.id ?? randomUUID(), name: label(input.name, ceiling(this.store, 100)), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
}
+1 -1
View File
@@ -97,7 +97,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (delta.refusal) text += delta.refusal;
if (delta.tool_calls !== undefined && !Array.isArray(delta.tool_calls)) throw protocolFailure('Chat流工具片段格式无效。');
for (const item of delta.tool_calls ?? []) {
if (!Number.isSafeInteger(item.index) || item.index < 0 || item.index >= 12) throw protocolFailure('Chat流工具索引无效。');
if (!Number.isSafeInteger(item.index) || item.index < 0 || config.executionMode !== 'unrestricted' && item.index >= 12) throw protocolFailure('Chat流工具索引无效。');
const call = calls.get(item.index) ?? { id: '', type: 'function', function: { name: '', arguments: '' } };
if (item.id) { if (call.id && call.id !== item.id) throw protocolFailure('Chat流工具身份发生变化。'); call.id = item.id; }
if (item.type && item.type !== 'function') throw protocolFailure('Chat流工具类型未接入。');
+9 -6
View File
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import { ModelTransport } from './transport.mjs';
import { probeNetwork } from './network-probe.mjs';
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
const problem = (message, status = 409) => Object.assign(new Error(message), { status });
const terminal = new Set(['passed', 'partial', 'failed', 'cancelled', 'interrupted']);
@@ -23,7 +24,7 @@ export class NetworkDiagnostics {
const connection = this.hub.connections().find(row => row.id === job.connectionId);
return { ...structuredClone(job), stale: !connection || connection.revision !== job.connectionRevision,
currentConnectionRevision: connection?.revision ?? null };
}).reverse(), active: this.active.size, retained: 30, httpRequests: 0, modelRequests: 0 };
}).reverse(), active: this.active.size, retained: unrestricted(this.hub.store) ? null : 30, httpRequests: 0, modelRequests: 0 };
}
start(input) {
if (!input || Object.keys(input).length !== 2 || Object.keys(input).some(key => !['id', 'revision'].includes(key)) || !Number.isSafeInteger(input.revision)) throw problem('连接诊断需要所选连接及其原修订。', 400);
@@ -38,20 +39,22 @@ export class NetworkDiagnostics {
const profile = structuredClone(transport.profile);
const target = { endpoint: connection.baseUrl, origin: url.origin, host: url.hostname.replace(/^\[|\]$/g, ''),
port: Number(url.port || (url.protocol === 'https:' ? 443 : 80)), scheme: url.protocol };
const budgetMs = this.options.budgetMs ?? Math.min(12000, profile.connectTimeoutMs + 2000);
const open = unrestricted(this.hub.store);
const stageTimeoutMs = this.options.stageTimeoutMs ?? (profile.connectTimeoutMs || (open ? 0 : 10000));
const budgetMs = this.options.budgetMs ?? (open ? 0 : Math.min(12000, (profile.connectTimeoutMs || 10000) + 2000));
const job = { schemaVersion: 1, id: randomUUID(), connectionId: connection.id, connectionRevision: connection.revision,
connectionName: connection.name, status: 'running', startedAt: new Date().toISOString(), finishedAt: null,
target, transport: profile, route: { kind: 'direct-endpoint-only', proxyConfigured: profile.httpProxyConfigured || profile.httpsProxyConfigured,
noProxyConfigured: profile.noProxyConfigured, customTransport, modelApiRouteVerified: false },
budgetMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false };
budgetMs, stageTimeoutMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false };
const previous = this.jobs;
this.jobs = [...this.jobs.slice(-29), job];
this.jobs = [...(open ? this.jobs : this.jobs.slice(-29)), job];
try { this.save(); } catch (error) { this.jobs = previous; throw error; }
const controller = new AbortController(), operation = { job, controller, promise: null };
this.active.set(job.id, operation);
const timer = setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs);
const timer = budgetMs > 0 ? setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs) : null;
operation.promise = Promise.resolve().then(async () => {
const result = await probeNetwork(target, profile, { ...this.options,
const result = await probeNetwork(target, profile, { ...this.options, stageTimeoutMs, maxAddresses: ceiling(this.hub.store, 32),
...(transport.connect?.lookup ? { lookup: transport.connect.lookup } : {}), signal: controller.signal,
update: result => { Object.assign(job, result); this.save(); } });
Object.assign(job, result);
+4 -4
View File
@@ -7,7 +7,7 @@ const elapsed = start => Math.max(0, Math.round(performance.now() - start));
const code = error => /^[A-Z0-9_]{1,80}$/.test(error?.code ?? '') ? error.code : 'NETWORK_CHECK_FAILED';
const cancelled = signal => Object.assign(new Error('连接诊断已停止。'), { code: signal.reason?.code ?? 'DIAGNOSTIC_CANCELLED' });
export async function probeNetwork(target, profile, { signal, update, lookup = dns.lookup, ca, stageTimeoutMs = profile.connectTimeoutMs } = {}) {
export async function probeNetwork(target, profile, { signal, update, lookup = dns.lookup, ca, stageTimeoutMs = profile.connectTimeoutMs, maxAddresses = 32 } = {}) {
const started = performance.now(), stages = { dns: { status: 'running', startedAt: new Date().toISOString() } };
const trials = ['auto', 'ipv4', 'ipv6'].map(mode => ({ mode, status: 'pending', stage: 'dns', attempts: [] }));
let updateError;
@@ -26,7 +26,7 @@ export async function probeNetwork(target, profile, { signal, update, lookup = d
try { lookup(target.host, { all: true, verbatim: true }, (error, rows) => finish(error, rows)); }
catch (error) { finish(error); }
});
addresses = addresses.filter(row => [4, 6].includes(row.family) && net.isIP(row.address) === row.family).slice(0, 32);
addresses = addresses.filter(row => [4, 6].includes(row.family) && net.isIP(row.address) === row.family).slice(0, maxAddresses);
if (!addresses.length) throw Object.assign(new Error('没有可用地址。'), { code: 'DNS_NO_ADDRESSES' });
stages.dns = { ...stages.dns, status: 'passed', elapsedMs: elapsed(lookupStart), addresses };
} catch (error) {
@@ -54,14 +54,14 @@ export async function probeNetwork(target, profile, { signal, update, lookup = d
if (signal?.aborted) { abort(); return; }
signal?.addEventListener('abort', abort, { once: true });
trial.status = 'running'; trial.stage = 'tcp'; publish();
timer = setTimeout(() => finish('failed', { code: trial.stage === 'tcp' ? 'TCP_CONNECT_TIMEOUT' : 'TLS_HANDSHAKE_TIMEOUT' }), stageTimeoutMs);
if (stageTimeoutMs > 0) timer = setTimeout(() => finish('failed', { code: trial.stage === 'tcp' ? 'TCP_CONNECT_TIMEOUT' : 'TLS_HANDSHAKE_TIMEOUT' }), stageTimeoutMs);
const frozenLookup = (_host, options, callback) => options.all ? callback(null, candidates)
: callback(null, candidates[0].address, candidates[0].family);
try {
tcp = net.createConnection({ host: target.host, port: target.port, lookup: frozenLookup,
autoSelectFamily: profile.autoSelectFamily, autoSelectFamilyAttemptTimeout: profile.familyAttemptTimeoutMs });
tcp.on('error', error => finish('failed', error));
tcp.on('connectionAttempt', (address, port, family) => { if (trial.attempts.length < 32) trial.attempts.push({ address, port, family }); });
tcp.on('connectionAttempt', (address, port, family) => { if (trial.attempts.length < maxAddresses) trial.attempts.push({ address, port, family }); });
tcp.on('connectionAttemptFailed', (address, _port, _family, error) => {
const attempt = trial.attempts.findLast(row => row.address === address); if (attempt) attempt.code = code(error);
});
+25 -11
View File
@@ -2,21 +2,37 @@ export const DEFAULT_MODEL_TIMEOUT_MS = 300000;
export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 120000;
export function modelWaitSettings(config = {}) {
const bounded = (value, fallback, minimum, maximum) => Number.isSafeInteger(value) && (value === 0 || value >= minimum && value <= maximum) ? value : fallback;
return { modelResponseTimeoutMs: bounded(config.modelResponseTimeoutMs, DEFAULT_MODEL_TIMEOUT_MS, 15000, 900000),
modelStreamIdleTimeoutMs: bounded(config.modelStreamIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS, 5000, 300000) };
const setting = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback;
return { modelResponseTimeoutMs: setting(config.modelResponseTimeoutMs, DEFAULT_MODEL_TIMEOUT_MS),
modelStreamIdleTimeoutMs: setting(config.modelStreamIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS) };
}
export function validateModelWaitSettings(input, previous = {}) {
const next = modelWaitSettings(previous);
for (const [key, minimum, maximum] of [['modelResponseTimeoutMs', 15000, 900000], ['modelStreamIdleTimeoutMs', 5000, 300000]]) {
for (const key of ['modelResponseTimeoutMs', 'modelStreamIdleTimeoutMs']) {
if (!Object.hasOwn(input, key)) continue;
if (!Number.isSafeInteger(input[key]) || input[key] !== 0 && (input[key] < minimum || input[key] > maximum)) throw Object.assign(new Error('模型等待时限必须为范围内的整数毫秒。'), { status: 400 });
if (!Number.isSafeInteger(input[key]) || input[key] < 0) throw Object.assign(new Error('模型等待时限必须为大于等于0的安全整数毫秒;0表示不限。'), { status: 400 });
next[key] = input[key];
}
return next;
}
// Node timers overflow beyond 2^31-1 ms. Honor a user's longer explicit wait
// by scheduling consecutive portions instead of turning it into a 1 ms timer.
export function scheduleDeadline(callback, milliseconds) {
if (!(milliseconds > 0)) return null;
let remaining = milliseconds, timer;
const arm = () => {
const portion = Math.min(remaining, 2147483647), began = Date.now();
timer = setTimeout(() => {
remaining -= Math.max(portion, Date.now() - began);
if (remaining > 0) arm(); else callback();
}, portion);
timer.unref?.();
};
arm(); return () => clearTimeout(timer);
}
// An active stream may outlive the old one-minute deadline. Idle time never
// extends the absolute limit, and the caller's stop/budget signal always wins.
export function requestDeadline({ signal, timeoutMs, idleTimeoutMs }) {
@@ -29,18 +45,16 @@ export function requestDeadline({ signal, timeoutMs, idleTimeoutMs }) {
controller.abort(new DOMException('Model response deadline exceeded', 'TimeoutError'));
};
let bytes = 0;
if (timeoutMs > 0) absoluteTimer = setTimeout(() => abort('total'), Math.max(1, timeoutMs));
absoluteTimer?.unref?.();
absoluteTimer = scheduleDeadline(() => abort('total'), timeoutMs);
const armIdle = () => {
clearTimeout(idleTimer);
idleTimer?.();
if (idleTimeoutMs > 0 && !controller.signal.aborted && !signal?.aborted) {
idleTimer = setTimeout(() => abort('idle'), idleTimeoutMs);
idleTimer.unref?.();
idleTimer = scheduleDeadline(() => abort('idle'), idleTimeoutMs);
}
};
return { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
get timeout() { return detail; },
beginStream() { stage = 'stream'; lastData = Date.now(); armIdle(); },
receive(length) { if (length > 0) { bytes += length; lastData = Date.now(); armIdle(); } },
close() { clearTimeout(absoluteTimer); clearTimeout(idleTimer); } };
close() { absoluteTimer?.(); idleTimer?.(); } };
}