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
+7 -5
View File
@@ -57,7 +57,9 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
finally { if (live.current) setSaving(false); }
}
const visible = preview?.entries.filter(value => (value.id + ' ' + value.name + ' ' + value.owner).toLowerCase().includes(query.trim().toLowerCase())) ?? [];
const selectable = visible.filter(value => value.lifecycle !== 'retired');
const open = preview?.limits.connections === null;
const selectionLimit = preview?.limits.connections ?? Infinity, poolLimit = preview?.limits.poolMembers ?? Infinity;
const selectable = visible.filter(value => open || value.lifecycle !== 'retired');
return <section className="mc-editor mc-catalog" aria-label="上游模型目录" ref={region}>
<div className="mc-section-title"><div><h3>从上游选择模型</h3><p>获取目录,勾选要用的型号,再决定手动指定或自动适配。</p></div><button className="button secondary" disabled={saving} onClick={onClose}>关闭目录</button></div>
<div className="mc-form-grid">
@@ -86,11 +88,11 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
{preview && <>
<div className="mc-catalog-heading"><label>搜索模型<input aria-label="搜索上游模型" value={query} onChange={event => setQuery(event.target.value)} placeholder="型号、显示名称或提供方" /></label><span>显示 {visible.length} / {preview.entries.length} · 已选 {chosen.length}</span></div>
{preview.warning && <p className="mc-card-warning">{preview.warning}</p>}
<p className="mc-help">以下为上游目录声明,尚未经过模型调用验证。目录最多1000项,本机最多100个模型连接;单个自动池最多32个成员。</p>
<div className="mc-row-actions"><button className="button secondary" disabled={locked || !selectable.length || new Set([...chosen, ...selectable.map(value => value.id)]).size > 100} onClick={() => setChosen([...new Set([...chosen, ...selectable.map(value => value.id)])])}>选中当前筛选</button><button className="button secondary" disabled={locked || !chosen.length} onClick={() => setChosen([])}>清空选择</button></div>
<p className="mc-help">以下为上游目录声明,尚未经过模型调用验证。{open ? '可选择上游返回的型号,目录、连接和自动池不设本地数量上限。' : `目录最多${preview.limits.catalog}项,本机最多${selectionLimit}个模型连接;单个自动池最多${poolLimit}个成员。`}</p>
<div className="mc-row-actions"><button className="button secondary" disabled={locked || !selectable.length || new Set([...chosen, ...selectable.map(value => value.id)]).size > selectionLimit} onClick={() => setChosen([...new Set([...chosen, ...selectable.map(value => value.id)])])}>选中当前筛选</button><button className="button secondary" disabled={locked || !chosen.length} onClick={() => setChosen([])}>清空选择</button></div>
<div className="mc-catalog-list" aria-label="上游模型列表">
{visible.map(value => <label className={'mc-catalog-model' + (chosen.includes(value.id) ? ' is-selected' : '')} key={value.id}>
<input type="checkbox" aria-label={'选择模型 ' + value.id} checked={chosen.includes(value.id)} disabled={locked || value.lifecycle === 'retired' || !chosen.includes(value.id) && chosen.length >= 100} onChange={event => setChosen(event.target.checked ? [...chosen, value.id] : chosen.filter(id => id !== value.id))} />
<input type="checkbox" aria-label={'选择模型 ' + value.id} checked={chosen.includes(value.id)} disabled={locked || !open && value.lifecycle === 'retired' || !chosen.includes(value.id) && chosen.length >= selectionLimit} onChange={event => setChosen(event.target.checked ? [...chosen, value.id] : chosen.filter(id => id !== value.id))} />
<span><strong>{value.id}</strong>{value.name !== value.id && <span>{value.name}</span>}<small>{[value.owner, value.contextLimit && `上下文 ${value.contextLimit.toLocaleString()} tokens`, value.maxOutputTokens && `输出上限 ${value.maxOutputTokens.toLocaleString()}`, value.lifecycle && value.lifecycle !== 'active' && (value.lifecycle === 'retired' ? '已退役' : '待退役')].filter(Boolean).join(' · ') || '上游未提供详细元数据'}</small>
<small>{Object.entries(value.capabilityDeclarations).filter(([, state]) => state !== 'unknown').map(([capability, state]) => `${capabilityNames[capability]}${state === 'supported' ? '支持' : '不支持'}`).join(' · ') || '文本、工具、流式等能力待确认'}{value.efforts.length ? ` · 推理强度 ${value.efforts.join(' / ')}` : ''}</small></span>
</label>)}{!visible.length && <p className="mc-empty">{preview.entries.length ? '没有匹配的型号。可更改搜索条件。' : '上游返回了空目录。可核对连接或使用手动兼容入口。'}</p>}
@@ -99,7 +101,7 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
<div className="mc-form-grid"><label>保存后的使用方式<select aria-label="模型使用方式" value={routing} disabled={locked} onChange={event => setRouting(event.target.value)}><option value="keep">保留当前选择,稍后手动使用</option><option value="manual">手动指定默认模型</option><option value="auto">自动适配所选模型</option></select></label>
{routing === 'manual' && <label>默认模型<select aria-label="目录默认模型" value={defaultModel} disabled={locked} onChange={event => setDefaultModel(event.target.value)}><option value="">请选择型号</option>{chosen.map(id => <option key={id}>{id}</option>)}</select></label>}</div>
{routing === 'auto' && <p className="mc-help">自动适配复用模型池,按任务所需能力、连接健康和可用并发筛选,再按轮询分配;同一运行优先保持型号。未确认能力的型号不会用于需要该能力的任务。</p>}
<div className="mc-actions"><button className="button primary" disabled={locked || !chosen.length || routing === 'manual' && !chosen.includes(defaultModel) || routing === 'auto' && chosen.length > 32} onClick={() => void save()}>{saving ? '正在保存…' : `保存所选 ${chosen.length} 个模型`}</button></div>
<div className="mc-actions"><button className="button primary" disabled={locked || !chosen.length || routing === 'manual' && !chosen.includes(defaultModel) || routing === 'auto' && chosen.length > poolLimit} onClick={() => void save()}>{saving ? '正在保存…' : `保存所选 ${chosen.length} 个模型`}</button></div>
</>}
</section>;
}
+5 -5
View File
@@ -7,11 +7,11 @@ type Connection = { id: string; name: string; baseUrl: string; revision: number
type Trial = { mode: string; status: string; stage: string; address?: string; family?: string; code?: string; tcpMs?: number; tlsMs?: number;
tls?: string; tlsProtocol?: string; certificateAuthorized?: boolean; attempts: { address: string; code?: string }[] };
type Job = { id: string; connectionId: string; connectionRevision: number; connectionName: string; status: string; startedAt: string; finishedAt: string | null;
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; target: { endpoint: string; host: string; port: number; scheme: string };
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; stageTimeoutMs?: number; target: { endpoint: string; host: string; port: number; scheme: string };
transport: { autoSelectFamily: boolean; familyAttemptTimeoutMs: number; connectTimeoutMs: number };
route: { proxyConfigured: boolean; noProxyConfigured: boolean; customTransport: boolean };
stages: { dns?: { status: string; elapsedMs?: number; code?: string; addresses?: { address: string; family: number }[] } }; trials: Trial[] };
type View = { jobs: Job[]; active: number; retained: number };
type View = { jobs: Job[]; active: number; retained: number | null };
const labels: Record<string, string> = { passed: '通过', partial: '部分路径可连接', failed: '未通过', running: '检查中', pending: '等待',
cancelled: '已停止', interrupted: '已中断', skipped: '未检查' };
const reasons: Record<string, string> = { ENOTFOUND: '域名没有解析结果', EAI_AGAIN: 'DNS 暂时不可用', DNS_NO_ADDRESSES: '没有可用的 IP 地址',
@@ -65,7 +65,7 @@ export function ModelNetworkDiagnostics({ connections, initialId, disabled }: {
})}><Square size={14} />停止诊断</button>}
</div>
{selected && <p className="mn-endpoint">{selected.baseUrl} <span>· 配置修订 {selected.revision}</span></p>}
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。检查最多约 12 秒,离开后结果保留。</span></p>
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。可随时停止检查,离开后结果保留。</span></p>
{error && <p className="mn-error" role="alert">{error}</p>}
{activeJob && activeJob.connectionId !== connectionId && <p className="mn-scope">{activeJob.connectionName} 正在检查。<button type="button" className="mn-link" onClick={() => { setConnectionId(activeJob.connectionId); setFocused(activeJob.id); }}>查看正在运行的诊断</button></p>}
{!view ? <p className="mc-empty">正在读取诊断记录…</p> : <div className="mn-workspace">
@@ -86,11 +86,11 @@ export function ModelNetworkDiagnostics({ connections, initialId, disabled }: {
{trial.code && <small>{detail(trial.code)}</small>}{trial.attempts.some(value => value.code) && <small>候选地址失败:{trial.attempts.filter(value => value.code).map(value => value.address + ' · ' + value.code).join(';')}</small>}</td></tr>)}</tbody></table>
{job.code && <p className="mn-outcome">{detail(job.code)}</p>}
<details className="mn-transport"><summary>查看原诊断范围与运输参数</summary><dl><dt>原端点</dt><dd>{job.target.endpoint}</dd><dt>检查目标</dt><dd>{job.target.host}:{job.target.port}</dd>
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>连接 / 总时限</dt><dd>{job.transport.connectTimeoutMs} / {job.budgetMs} ms</dd>
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>单路径 / 总时限</dt><dd>{(job.stageTimeoutMs ?? job.transport.connectTimeoutMs) > 0 ? (job.stageTimeoutMs ?? job.transport.connectTimeoutMs) + ' ms' : '不限'} / {job.budgetMs ? job.budgetMs + ' ms' : '不限'}</dd>
<dt>模型 API</dt><dd>未请求;能力与连接健康结论保持原记录</dd><dt>记录</dt><dd>{job.id}</dd></dl></details>
</>}
</div>
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>保存最近 {view.retained} 条;点击查看原记录。</p>
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>{view.retained === null ? '保留全部检查记录。' : `保存最近 ${view.retained} 条。`}点击查看原记录。</p>
{!jobs.length && <p>这条连接还没有检查记录。</p>}{jobs.map(value => <button key={value.id} type="button" aria-pressed={job?.id === value.id} onClick={() => setFocused(value.id)}><span>{new Date(value.startedAt).toLocaleString()}</span><strong>{labels[value.status] ?? value.status}{value.stale ? ' · 旧配置' : ''}</strong><small>修订 {value.connectionRevision} · {duration(value.elapsedMs)}</small></button>)}
</aside>
</div>}
+4 -4
View File
@@ -6,13 +6,13 @@ export function ModelWaitSettings({ value, disabled, onSave }: { value: WaitSett
const [responseSeconds, setResponseSeconds] = useState(value.modelResponseTimeoutMs / 1000);
const [idleSeconds, setIdleSeconds] = useState(value.modelStreamIdleTimeoutMs / 1000);
return <form className="mc-editor" aria-label="模型等待时限" onSubmit={event => { event.preventDefault(); onSave({ modelResponseTimeoutMs: responseSeconds * 1000, modelStreamIdleTimeoutMs: idleSeconds * 1000 }); }}>
<h3>给模型足够时间,保留等待边界。</h3>
<h3>模型等待时间</h3>
<p>适用于原模型连接及模型池内的每次请求;从下一次运行生效。保存只调整等待时限,保留当前模型池和连接。</p>
<div className="mc-form-grid">
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={15} max={900} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>包含服务排队与生成。默认 300 秒,最多 900 秒。</small></label>
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={5} max={300} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>开始流式响应后连续没有新数据的等待时间。默认 120 秒。</small></label>
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={0} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>默认 0=不限,包含服务排队与生成;可自行填写等待秒数。</small></label>
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={0} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>默认 0=不限。可设置开始流式响应后连续没有新数据的等待秒数。</small></label>
</div>
<p>持续收到数据仍受单次响应上限约束。停止任务立即生效;任务总预算先到时会暂停。不完整的文件或命令参数不会执行。</p>
<p>仅在填写正数时使用相应时限;0 不附加本地等待期限。你可以随时停止任务,上游原始错误和实际用量会保留。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={disabled}>保存等待时限</button></div>
</form>;
}
+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?.(); } };
}
+5 -5
View File
@@ -187,7 +187,7 @@ export class Provider {
if (key) headers[messagesAuth === 'bearer' ? 'Authorization' : 'x-api-key'] = messagesAuth === 'bearer' ? 'Bearer ' + key : key;
} else if (key) headers.Authorization = 'Bearer ' + key;
const requestUrl = base + route;
const waits = modelWaitSettings(config), timeoutMs = body ? waits.modelResponseTimeoutMs : 20000;
const waits = modelWaitSettings(config), timeoutMs = body || unrestricted(config) ? waits.modelResponseTimeoutMs : 20000;
const policy = { attempts: 3, delays: [500, 1500], timeoutMs, totalTimeoutMs: timeoutMs,
idleTimeoutMs: waits.modelStreamIdleTimeoutMs, ...this.retryPolicy, ...options };
if (config.capacityMode === 'passthrough') policy.attempts = 1;
@@ -352,7 +352,7 @@ export class Provider {
const body = completionBody(config, messages, tools);
assertPlannedRequest(body, requestPlan);
if (config.executionMode !== 'unrestricted' && config.inputImages?.length && (!config.modelRouting || !this.hub || config.mode==='demo')) throw new Error('图片请求必须通过模型中心的视觉能力选路,尚未发送。');
if (config.mode === 'demo') return this.demo(messages, project);
if (config.mode === 'demo') return this.demo(messages, project, config);
this.validate(config);
const execute = async (selected, key, input, progress) => {
return this.request(selected, protocolRoute(selected), input, signal, key, progress, { ...(config.modelRouting ? { attempts: 1 } : {}), ...requestPolicy,
@@ -379,7 +379,7 @@ export class Provider {
...(calls.length ? { tool_calls: calls } : {}) }, usage: result.usage ?? null, finishReason: result.choices[0].finish_reason ?? null,
...(result.compatibility?.length ? { compatibility: result.compatibility } : {}) };
}
demo(messages, project) {
demo(messages, project, config = {}) {
const lastUser = messages.findLastIndex(message => message.role === 'user');
const results = messages.slice(lastUser + 1).filter(message => message.role === 'tool');
const count = results.length;
@@ -400,9 +400,9 @@ export class Provider {
const user = String(messages[lastUser]?.content ?? '').slice(0, 300);
return tool('propose_file', { path: 'WORKBENCH-NOTES.md',
content: '# 工作台验证记录\n\n这份记录由离线演示脚本准备,用来验证差异审查与文件写入流程;没有调用大模型。\n\n## 本次任务\n' + user + '\n\n## 项目依据\n' + excerpt.slice(0, 1000) + '\n\n## 下一步\n在工作台查看差异,应用后可继续连接真实模型进行项目开发。\n',
reason: '用真实的项目读取结果准备一个可审查的文本提案。' }, '已取得项目依据。我会准备一个文件提案,等待你查看差异后应用。');
reason: '用真实的项目读取结果准备一个可审查的文本提案。' }, unrestricted(config) ? '已取得项目依据,接下来直接写入文件并保存差异与回滚资料。' : '已取得项目依据。我会准备一个文件提案,等待你查看差异后应用。');
}
if (count === 3) return tool('run_command', { command: 'node --version', reason: '只读取本机 Node 版本,演示终端确认与执行记录。' }, '最后请求一次只读的环境验证。确认后会记录实际命令输出。');
return { message: { role: 'assistant', content: '离线演示已完成:项目读取、文件提案和终端确认流程都有执行记录。待审查改动可以在右侧查看并应用。\n\n这次没有调用大模型。你可以在“模型连接”中配置自己的兼容服务,随后用同一套工具完成真实开发任务。' }, usage: null, finishReason: 'stop' };
return { message: { role: 'assistant', content: (unrestricted(config) ? '离线演示已结束:请在任务记录核对项目读取、文件写入和终端操作的实际结果;文件差异与回滚入口可随时查看。' : '离线演示已完成:项目读取、文件提案和终端确认流程都有执行记录。待审查改动可以在右侧查看并应用。') + '\n\n这次没有调用大模型。你可以在“模型连接”中配置自己的兼容服务,随后用同一套工具完成真实开发任务。' }, usage: null, finishReason: 'stop' };
}
}
+3 -2
View File
@@ -1,4 +1,5 @@
import { unrestricted, ceiling, openToolDefinitions, automaticApproval } from '../shared/contracts/execution-policy.mjs';
import { scheduleDeadline } from '../core/models/request-deadline.mjs';
import { approvalPresentation } from '../shared/approval-presentation.mjs';
import { PreviewManager } from '../core/preview/preview-manager.mjs';
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
@@ -303,9 +304,9 @@ export class Runtime {
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
session.failure = null;
this.store.save(session);
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
const deadline = scheduleDeadline(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs);
run.promise = this.run(session, config, run).finally(() => {
clearTimeout(deadline);
deadline?.();
try {
const status = session.status;
if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore;
+2 -2
View File
@@ -73,8 +73,8 @@ export function verifyEngineModelInput(store, session, job, request) {
if (input.owner.sessionId !== job.sessionId || input.owner.taskId !== job.taskId || input.owner.runId !== job.runId || input.owner.projectId !== job.projectId
|| controlledDigest(input.native) !== request.sourceSha256 || metrics.sha256 !== request.requestSha256 || metrics.bytes !== request.requestBytes
|| !Number.isSafeInteger(request.maxAttempts) || request.maxAttempts < 1 || request.maxAttempts > 8
|| (job.model.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1))
|| !requestVariants(input.body).every(body => outputReservation(body) === (job.model.capacityMode === 'passthrough' ? null : input.native.maxTokens))
|| (job.model?.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1))
|| !requestVariants(input.body).every(body => outputReservation(body) === (job.model?.capacityMode === 'passthrough' ? null : input.native.maxTokens))
|| request.reservedPerAttempt !== (request.reservationVersion===1?request.tokenReservation.reservedTokens:metrics.estimatedInputTokens + 128 + input.native.maxTokens)) throw engineError('原引擎模型输入、归属或预算核对失败。');
if(input.view){
const view=input.view,source=store.owned('artifact',view.sourceArtifactId,session.id),sourceValue=JSON.parse(store.artifactStore.read(source));
+5 -2
View File
@@ -1,12 +1,15 @@
import { unrestricted } from './execution-policy.mjs';
// Editable fallbacks for upstreams that do not publish capacity. These values
// are not verified model capabilities or ceilings on larger models.
export const DEFAULT_MODEL_CAPACITY = Object.freeze({ contextLimit: 128000, maxOutputTokens: 16384 });
export const CAPACITY_RANGES = Object.freeze({ contextLimit: [1000, Number.MAX_SAFE_INTEGER], maxOutputTokens: [256, Number.MAX_SAFE_INTEGER] });
export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY) {
export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY, config = {}) {
return Object.fromEntries(Object.entries(CAPACITY_RANGES).map(([key, [min, max]]) => {
const value = input[key] ?? previous[key] ?? DEFAULT_MODEL_CAPACITY[key];
if (!Number.isSafeInteger(value) || value < min || value > max) throw Object.assign(new Error(key + ' 需要不小于 ' + min + ' 的安全整数,请核对模型实际容量。'), { status: 400 });
const minimum = unrestricted(config) ? 1 : min;
if (!Number.isSafeInteger(value) || value < minimum || value > max) throw Object.assign(new Error(key + ' 需要不小于 ' + minimum + ' 的安全整数,请核对模型实际容量。'), { status: 400 });
return [key, value];
}));
}
+3 -3
View File
@@ -4,8 +4,8 @@ export interface CatalogModel {
}
export interface CatalogPreview {
id: string; entries: CatalogModel[]; fetchedAt: string; expiresAt: string; complete: boolean; warning: string;
source: { name: string; baseUrl: string; protocol: string }; limits: { connections: number; poolMembers: number; catalog: number };
source: { name: string; baseUrl: string; protocol: string }; limits: { connections: number | null; poolMembers: number | null; catalog: number | null };
}
export function catalogRoute(config: { protocol?: string; baseUrl: string }): string;
export function catalogModel(item: unknown): CatalogModel;
export function catalogPage(response: unknown): { entries: CatalogModel[]; hasMore: boolean; cursor: string };
export function catalogModel(item: unknown, config?: { executionMode?: string }): CatalogModel;
export function catalogPage(response: unknown, config?: { executionMode?: string }): { entries: CatalogModel[]; hasMore: boolean; cursor: string };
+9 -7
View File
@@ -1,4 +1,5 @@
import { modelProtocol } from './model-capabilities.mjs';
import { ceiling, unrestricted } from './execution-policy.mjs';
const fail = message => Object.assign(new Error(message), { status: 400 });
const text = (value, max = 200) => typeof value === 'string' ? value.trim().slice(0, max) : '';
@@ -15,10 +16,11 @@ export function catalogRoute(config) {
// Metadata is an upstream declaration, never capability-test evidence. Keep
// unsupported adapter features visible without passing arbitrary vendor fields.
export function catalogModel(item) {
export function catalogModel(item, config = {}) {
if (typeof item === 'string') item = { id: item };
if (!item || typeof item !== 'object' || Array.isArray(item)) throw fail('上游模型目录含无效条目。');
const id = text(item.id ?? item.name);
const field = (value, maximum = 200) => text(value, ceiling(config, maximum));
const id = field(item.id ?? item.name);
if (!id || id.length !== String(item.id ?? item.name).trim().length || /[\x00-\x1f\x7f]/.test(id)) throw fail('上游模型名称为空、过长或含控制字符。');
const caps = item.capabilities && typeof item.capabilities === 'object' && !Array.isArray(item.capabilities) ? item.capabilities : {};
const declarations = Object.fromEntries(['text', 'tools', 'streaming', 'vision', 'audio'].map(key => [key,
@@ -30,12 +32,12 @@ export function catalogModel(item) {
if (input.includes('audio') && declarations.audio === 'unknown') declarations.audio = 'supported';
}
if (Array.isArray(output) && output.includes('text') && declarations.text === 'unknown') declarations.text = 'supported';
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && value.length <= 80))].slice(0, 80) : [];
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && (unrestricted(config) || value.length <= 80)))].slice(0, ceiling(config, 80)) : [];
if (declarations.tools === 'unknown' && parameters.includes('tools')) declarations.tools = 'supported';
const efforts = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].filter(value => supported(caps.effort?.[value]) === 'supported');
const modes = ['disabled', 'enabled', 'adaptive'].filter(value => supported(caps.thinking?.types?.[value]) === 'supported');
const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])]));
return { id, name: text(item.display_name ?? item.name ?? id), owner: text(item.owned_by ?? item.provider, 100),
return { id, name: field(item.display_name ?? item.name ?? id), owner: field(item.owned_by ?? item.provider, 100),
lifecycle: ['active', 'deprecated', 'retired'].includes(item.lifecycle) ? item.lifecycle : null,
contextLimit: positive(item.context_length ?? item.max_input_tokens ?? item.context_window),
maxOutputTokens: positive(item.max_output_tokens ?? item.max_tokens ?? item.top_provider?.max_completion_tokens),
@@ -43,12 +45,12 @@ export function catalogModel(item) {
metadataSource: 'upstream-model-list' };
}
export function catalogPage(response) {
export function catalogPage(response, config = {}) {
const data = response?.data ?? response?.models;
if (!Array.isArray(data)) throw fail('上游未返回 data 或 models 模型列表;可核对接口或使用手动兼容入口。');
const entries = data.map(catalogModel);
const entries = data.map(item => catalogModel(item, config));
const hasMore = response.has_more === true;
const cursor = hasMore ? text(response.last_id ?? entries.at(-1)?.id) : '';
const cursor = hasMore ? text(response.last_id ?? entries.at(-1)?.id, ceiling(config, 200)) : '';
if (hasMore && !cursor) throw fail('上游声明还有下一页,却未提供有效游标。');
return { entries, hasMore, cursor };
}