fix(runtime): preserve model capacity history and cache evidence with resumable file proposals

This commit is contained in:
Agent Workbench Dev
2026-11-06 01:18:37 +08:00
parent 2b17821138
commit 72115647d9
39 changed files with 699 additions and 75 deletions
+2 -2
View File
@@ -28,7 +28,7 @@ import { BudgetPausePanel } from './BudgetPausePanel';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const activeMcpStates = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000 };
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 128000, maxSteps: 12, maxOutputTokens: 16384, capacityMode: 'model', hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000 };
export default function App() {
const [token, setAccess] = useState('');
@@ -646,7 +646,7 @@ export default function App() {
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
{settingsOpen && <Modal title="原连接与演示设置" description="此处只编辑原连接。添加、切换模型请使用模型中心;运行预算也可单独保存。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
<details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>上下文预算<input type="number" min={1000} max={200000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={1} max={30} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} max={16000} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={1} max={60} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={1000} max={2000000} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={1000} max={10000000} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。</p></details>{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存并切换原连接</button></div></form></Modal>}
<details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>上下文预算<input type="number" min={1000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={1} max={30} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={1} max={60} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={1000} max={2000000} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={1000} max={10000000} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。</p></details>{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存并切换原连接</button></div></form></Modal>}
{diagnosticsOpen && <Modal title="运行诊断" description="查看工作台的模型连接、终端环境、最近错误和文件实际状态。" wide onClose={() => setDiagnosticsOpen(false)}><DiagnosticsPanel value={diagnostics} busy={diagnosticsBusy} onRefresh={() => openDiagnostics()} /></Modal>}
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} /></Modal>}
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、受控工程运行与原记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onNavigate={async (projectId, sessionId) => { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} /></Modal>}
+1 -1
View File
@@ -32,6 +32,6 @@ export function BudgetPausePanel({session,config,onSession,onRecovery}:{session:
{pause?.tokenReservation&&<p>{calibrationSources?<>依据同一模型线路的 {calibrationSources} 次已知响应校准,</>:'按本地估算,'}下一次请求需预留 <strong>{pause.tokenReservation.reservedTokens.toLocaleString()}</strong> tokens{pause.remainingTokens!==undefined?<>,剩余 <strong>{pause.remainingTokens.toLocaleString()}</strong></>:null}。已在发送前暂停;这项预留用于后续预算,原始用量记录保持。</p>}
{pause?.tokenAccounting&&<><dl className="budget-facts"><dt>本次运行上游报告用量</dt><dd>{pause.tokenAccounting.run.reportedTokens.toLocaleString()}</dd><dt>用量未知请求 / 本地预留</dt><dd>{pause.tokenAccounting.run.unknownRequests.toLocaleString()} / {pause.tokenAccounting.run.estimatedUnknownTokens.toLocaleString()}</dd><dt>本次运行预算 / 记账超出</dt><dd>{pause.tokenAccounting.run.maximumTokens>0?pause.tokenAccounting.run.maximumTokens.toLocaleString():'不限'} / {pause.tokenAccounting.run.exceededTokens.toLocaleString()}</dd><dt>任务累计预算 / 记账超出</dt><dd>{pause.tokenAccounting.task.maximumTokens>0?pause.tokenAccounting.task.maximumTokens.toLocaleString():'不限'} / {pause.tokenAccounting.task.exceededTokens.toLocaleString()}</dd></dl><p>单个在途响应可能超过预估。超额后停止后续请求;用量未知的请求仍按本地预留控制预算,不补造实际计费。</p></>}
{controlled?<><p>受限子任务在隔离协作中处理。当前协作沿用已封存容量与累计预算;若配置不足,先保留现场,再为新目标选择合适配置。已完成工具和原失败不会自动重放。</p>{onRecovery&&<button type="button" className="button secondary" onClick={onRecovery}>打开隔离协作</button>}</>:<button type="button" className="button secondary" onClick={()=>void start()}><RotateCw size={14}/>核对预算并续接原任务</button>}
{open&&<Modal title="续接原任务" description="先核对新Run的容量与预算,再确认执行。" onClose={()=>{if(!busy)setOpen(false);}} wide><p className="input-sha">Task {session.execution?.task?.id}<br/>原 Run {run?.id}</p><div className="budget-resume-fields"><label>本次模型连接或池<select aria-label="续接模型连接" value={selection} disabled={busy} onChange={event=>{setSelection(event.target.value);setPlan(null);}}>{options.map(row=><option key={row.value} value={row.value}>{row.name}</option>)}</select></label>{([['contextLimit','上下文窗口',1000,200000],['maxOutputTokens','响应预留',256,16000],['maxRunTokens','新Run累计tokens',1000,2000000],['maxTaskTokens','原任务累计tokens',1000,10000000],['maxSteps','新Run工具轮次',1,30],['maxRunDurationMs','新Run时间(分钟)',1,60]] as const).map(([key,label,min,max])=><label key={key}>{label}<input aria-label={label} type="number" min={min} max={max} value={key==='maxRunDurationMs'?fields[key]/60000:fields[key]} disabled={busy} onChange={event=>{setFields({...fields,[key]:Number(event.target.value)*(key==='maxRunDurationMs'?60000:1)});setPlan(null);}}/></label>)}</div><p>容量须符合服务实际限制;池按成员最小容量核对。新增预算只用于这次明确续接,不修改全局设置。</p>{error&&<p className="budget-error" role="alert">{error}</p>}<div className="modal-actions"><button type="button" className="button secondary" disabled={busy||!selection} onClick={()=>void preview()}>准备续接预览</button></div>{plan&&<div className="budget-preview" role="status"><strong>将创建原Task的新Run</strong><p>可用模型 {plan.eligibleConnections.length?plan.eligibleConnections.map(row=>row.name+' / '+row.model).join('、'):plan.config.model} · 上下文 {plan.budget.contextLimit.toLocaleString()} · 可用输入 {plan.budget.inputBudget.toLocaleString()} tokens</p><p>保留 {plan.completedToolIds.length} 项完成工具、{plan.attachmentIds.length} 张附件;{plan.unknownToolIds.length} 项未知结果仍须核对。</p><p>{plan.note}</p><p className="input-sha">预览 SHA-256 {plan.sha256}</p><div className="modal-actions"><button type="button" className="button primary" disabled={busy} onClick={()=>void confirm()}>确认预算并续接</button></div></div>}</Modal>}
{open&&<Modal title="续接原任务" description="先核对新Run的容量与预算,再确认执行。" onClose={()=>{if(!busy)setOpen(false);}} wide><p className="input-sha">Task {session.execution?.task?.id}<br/>原 Run {run?.id}</p><div className="budget-resume-fields"><label>本次模型连接或池<select aria-label="续接模型连接" value={selection} disabled={busy} onChange={event=>{setSelection(event.target.value);setPlan(null);}}>{options.map(row=><option key={row.value} value={row.value}>{row.name}</option>)}</select></label>{([['contextLimit','上下文窗口',1000,Number.MAX_SAFE_INTEGER],['maxOutputTokens','响应预留',256,Number.MAX_SAFE_INTEGER],['maxRunTokens','新Run累计tokens',1000,2000000],['maxTaskTokens','原任务累计tokens',1000,10000000],['maxSteps','新Run工具轮次',1,30],['maxRunDurationMs','新Run时间(分钟)',1,60]] as const).map(([key,label,min,max])=><label key={key}>{label}<input aria-label={label} type="number" min={min} max={max} value={key==='maxRunDurationMs'?fields[key]/60000:fields[key]} disabled={busy} onChange={event=>{setFields({...fields,[key]:Number(event.target.value)*(key==='maxRunDurationMs'?60000:1)});setPlan(null);}}/></label>)}</div><p>容量须符合服务实际限制;池按成员最小容量核对。新增预算只用于这次明确续接,不修改全局设置。</p>{error&&<p className="budget-error" role="alert">{error}</p>}<div className="modal-actions"><button type="button" className="button secondary" disabled={busy||!selection} onClick={()=>void preview()}>准备续接预览</button></div>{plan&&<div className="budget-preview" role="status"><strong>将创建原Task的新Run</strong><p>可用模型 {plan.eligibleConnections.length?plan.eligibleConnections.map(row=>row.name+' / '+row.model).join('、'):plan.config.model} · 上下文 {plan.budget.contextLimit.toLocaleString()} · 可用输入 {plan.budget.inputBudget.toLocaleString()} tokens</p><p>保留 {plan.completedToolIds.length} 项完成工具、{plan.attachmentIds.length} 张附件;{plan.unknownToolIds.length} 项未知结果仍须核对。</p><p>{plan.note}</p><p className="input-sha">预览 SHA-256 {plan.sha256}</p><div className="modal-actions"><button type="button" className="button primary" disabled={busy} onClick={()=>void confirm()}>确认预算并续接</button></div></div>}</Modal>}
</aside>;
}
+8 -4
View File
@@ -2,16 +2,20 @@ import { useState } from 'react';
import type { Config } from './types';
export function ModelBudgetSettings({ value, disabled, onSave }: { value: Config; disabled: boolean; onSave: (input: Partial<Config>) => void }) {
const [draft, setDraft] = useState(() => ({ contextLimit: value.contextLimit, maxOutputTokens: value.maxOutputTokens,
const [draft, setDraft] = useState(() => ({ capacityMode: value.capacityMode ?? 'manual', historyPolicy: value.historyPolicy ?? 'compact', contextLimit: value.contextLimit, maxOutputTokens: value.maxOutputTokens,
maxSteps: value.maxSteps, maxRunDurationMs: value.maxRunDurationMs, maxRunTokens: value.maxRunTokens, maxTaskTokens: value.maxTaskTokens }));
const fields = [
['contextLimit', '上下文预算', 1000, 200000], ['maxOutputTokens', '输出上限', 256, 16000],
['contextLimit', '上下文预算', 1000, Number.MAX_SAFE_INTEGER], ['maxOutputTokens', '输出上限', 256, Number.MAX_SAFE_INTEGER],
['maxSteps', '最大工具轮次', 1, 30], ['maxRunDurationMs', '运行时间(秒)', 1, 3600],
['maxRunTokens', '单次运行 tokens', 1000, 2000000], ['maxTaskTokens', '任务累计 tokens', 1000, 10000000],
] as const;
return <form className="mc-editor" aria-label="运行预算设置" onSubmit={event => { event.preventDefault(); onSave(draft); }}>
<h3>运行预算</h3><p>保存仅调整后续运行的预算,保留已选连接或模型池。实际上下文与输出上限还受所选连接限制;旧运行的预算与用量保持原记录。</p>
<div className="mc-form-grid">{fields.map(([key, label, min, max]) => <label key={key}>{label}<input aria-label={label} type="number" required step={1} min={min} max={max} disabled={disabled}
<h3>运行预算</h3><p>保存仅影响后续运行,保留已选连接、模型池与旧运行记录。</p>
<div className="mc-form-grid"><label>容量策略<select aria-label="容量策略" disabled={disabled} value={draft.capacityMode} onChange={event => setDraft({ ...draft, capacityMode: event.target.value as 'model' | 'manual' })}><option value="model">按模型连接容量</option><option value="manual">手动限制上下文与输出</option></select></label>
<label>历史传递<select aria-label="历史传递" disabled={disabled} value={draft.historyPolicy} onChange={event => setDraft({ ...draft, historyPolicy: event.target.value as 'preserve' | 'compact' })}><option value="preserve">完整传递,容量不足时暂停</option><option value="compact">允许整理历史,原记录可检索</option></select></label></div>
<p>完整传递保留历史原文及顺序;固定规则放在前部,动态状态放在末尾,减少缓存前缀变化。缓存是否命中以上游实际报告为准。</p>
<p>{draft.capacityMode === 'model' ? '输出按实际所选连接的额度传递,全局不再额外裁低。上游提供容量时从目录带入;未提供时请在连接中核对。混合池输入按共同窗口、最大输出预留核算,容量不足时暂停。' : '本次手动额度与连接额度取较小值。推理可能占用输出额度;较小输出容易截断代码。'}</p>
<div className="mc-form-grid">{fields.filter(([key]) => draft.capacityMode === 'manual' || !['contextLimit', 'maxOutputTokens'].includes(key)).map(([key, label, min, max]) => <label key={key}>{label}<input aria-label={label} type="number" required step={1} min={min} max={max === Number.MAX_SAFE_INTEGER ? undefined : max} disabled={disabled}
value={key === 'maxRunDurationMs' ? draft[key] / 1000 : draft[key]} onChange={event => setDraft(previous => ({ ...previous, [key]: Number(event.target.value) * (key === 'maxRunDurationMs' ? 1000 : 1) }))} /></label>)}</div>
<div className="mc-actions"><button className="button primary" type="submit" disabled={disabled}>保存运行预算</button></div>
</form>;
+6 -4
View File
@@ -9,6 +9,7 @@ import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
import { ModelBudgetSettings } from './ModelBudgetSettings';
import { DEFAULT_MODEL_CAPACITY } from '../shared/contracts/model-capacity.mjs';
import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoint.mjs';
import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
import { ModelCatalog } from './ModelCatalog';
@@ -28,7 +29,7 @@ type SavedCredential = { id: string; name: string; revision: number; status: str
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { reference: '共用上游凭据', not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', rejected: '能力不匹配', passed: '通过', attention: '待配置' };
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, ...DEFAULT_MODEL_CAPACITY, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
const capabilityStates: Record<string, string> = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
@@ -36,7 +37,7 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; upstreamModel?: CatalogModel; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [catalogSource, setCatalogSource] = useState<string | null>(null);
@@ -147,8 +148,9 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<label className="mc-full">允许的返回型号(可选,逗号分隔)<input value={draft.modelIdentityAliasesText} onChange={event => setDraft({ ...draft, modelIdentityAliasesText: event.target.value })} /></label>
<label className="mc-full">型号映射依据<input required={draft.modelIdentityAliasesText.trim().length > 0} value={draft.modelIdentityAliasSource} placeholder="填写供应商映射说明或可核对的出处" onChange={event => setDraft({ ...draft, modelIdentityAliasSource: event.target.value })} /></label>
<label>临时 API Key<input type="password" autoComplete="off" value={key} placeholder={draft.id ? '留空保留本次凭据' : '按服务要求填写'} onChange={event => setKey(event.target.value)} /></label>
<label>上下文上限<input type="number" min="1000" max="200000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
<label>输出上限<input type="number" min="256" max="16000" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
<label>上下文上限<input type="number" required step="1" min="1000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
<label>输出上限<input type="number" required step="1" min="256" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
<div className="mc-help mc-full">容量优先使用上游目录声明;未提供时,开发初始值需要按供应商核对。推理可能共享输出额度。<button type="button" className="button secondary" onClick={() => setDraft({ ...draft, contextLimit: draft.upstreamModel?.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit, maxOutputTokens: draft.upstreamModel?.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens })}>{draft.upstreamModel?.contextLimit || draft.upstreamModel?.maxOutputTokens ? '采用上游容量' : '填入开发初始值'}</button></div>
<label>并发请求上限<input type="number" min="1" max="8" value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
+3 -1
View File
@@ -38,12 +38,14 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
<dl className="record-fields"><dt>请求输入估算</dt><dd>{number(plan.estimatedInputTokens)} tokens</dd><dt>输出 / 安全余量</dt><dd>{number(plan.budget.outputReservation)} / {number(plan.budget.safetyTokens)} tokens</dd>
<dt>模型上下文窗口</dt><dd>{number(plan.budget.contextLimit)} tokens</dd><dt>已报告输入</dt><dd>{plan.actualUsage?.prompt_tokens === undefined ? '服务未返回' : number(plan.actualUsage.prompt_tokens) + ' tokens'}</dd>
<dt>历史记录</dt><dd>保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录</dd>
<dt>上游缓存命中</dt><dd>{plan.actualUsage?.prompt_tokens_details?.cached_tokens === undefined ? '上游未报告' : number(plan.actualUsage.prompt_tokens_details.cached_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.workingSetEntries && <><dt>当前任务依据</dt><dd>{plan.workingSetEntries} 项代码与执行结果</dd></>}
{!!plan.projectMemoryEntries && <><dt>项目记忆</dt><dd>{plan.projectMemoryEntries} 条来源已核对的记录</dd></>}
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
</dl>
<p className="record-footnote">估算包含系统提示、工具定义和历史。任务要求完整保留;省略的原记录可从本机工件检索。实际用量以模型服务为准。</p>
<p className="record-footnote">估算包含系统提示、工具定义和历史。{plan.historyPolicy === 'preserve' ? '本次完整传递历史,容量不足时暂停。' : '任务要求完整保留;整理过的原记录可从本机工件检索。'}实际用量与缓存命中以模型服务为准。</p>
{plan.error && <p className="run-stop">{plan.error}</p>}
<div className="context-actions"><button type="button" className="text-button" onClick={() => openArtifact(plan.requestArtifactId)}><FileText size={13} />查看发送内容</button>
<button type="button" className="text-button" onClick={() => openArtifact(plan.artifactId)}><FileText size={13} />查看请求计划</button>
+5 -1
View File
@@ -1,6 +1,8 @@
export interface Config {
mode: 'demo' | 'compatible'; baseUrl: string; model: string;
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
capacityMode?: 'model' | 'manual';
historyPolicy?: 'preserve' | 'compact';
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
modelResponseTimeoutMs?: number; modelStreamIdleTimeoutMs?: number;
}
@@ -179,7 +181,9 @@ export interface ContextPlan {
latestToolsArtifactId?: string | null; latestToolsSha256?: string | null; latestToolsEntries?: number;
projectMemoryArtifactId?: string | null; projectMemorySha256?: string | null; projectMemoryEntries?: number;
skillCatalogArtifactId?: string | null; skillCatalogSha256?: string | null; skillCatalogEntries?: number;
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; requestAttempts: number; error?: string;
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number; prompt_tokens_details?: { cached_tokens?: number; cache_creation_tokens?: number } } | null; requestAttempts: number; error?: string;
historyPolicy?: 'preserve' | 'compact'; contextLayout?: string;
prefixAudit?: { variants: { connectionId: string | null; model: string; commonPrefixBytes: number; previousPromptBytes: number | null; reason: string; toolNames: string[]; toolsSha256: string }[] };
budget: { contextLimit: number; outputReservation: number; safetyTokens: number; inputBudget: number; targetInputTokens: number; runRemainingTokens: number | null; taskRemainingTokens: number | null };
}
export interface ContextHistoryGroup {
+3 -2
View File
@@ -2,10 +2,11 @@ import { randomUUID,createHash } from 'node:crypto';
import { budgetFor } from './request-plan.mjs';
import { accountedTokens,emptyUsage } from '../../shared/contracts/execution.mjs';
import { capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
import { CAPACITY_RANGES } from '../../shared/contracts/model-capacity.mjs';
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const ranges={contextLimit:[1000,200000],maxOutputTokens:[256,16000],maxSteps:[1,30],maxRunTokens:[1000,2000000],maxTaskTokens:[1000,10000000],maxRunDurationMs:[1000,3600000]};
const ranges={...CAPACITY_RANGES,maxSteps:[1,30],maxRunTokens:[1000,2000000],maxTaskTokens:[1000,10000000],maxRunDurationMs:[1000,3600000]};
export class BudgetResume {
constructor(store,provider,runtime){this.store=store;this.provider=provider;this.runtime=runtime;}
@@ -18,7 +19,7 @@ export class BudgetResume {
prepare(session,input){
const {task,run}=this.current(session);
if(!input||Object.keys(input).some(key=>![...Object.keys(ranges),'selection'].includes(key)))throw fail('续接预览字段无效。',400);
const config={...this.store.config,maxTaskTokens:task.budget.maxTokens};
const config={...this.store.config,capacityMode:'manual',maxTaskTokens:task.budget.maxTokens};
for(const [key,[minimum,maximum]] of Object.entries(ranges))if(input[key]!==undefined){
if(!Number.isSafeInteger(input[key])||input[key]<minimum||input[key]>maximum)throw fail('续接预算 '+key+' 超出允许范围。',400);
config[key]=input[key];
+23
View File
@@ -0,0 +1,23 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(value).digest('hex');
const variants = body => body.kind === 'model-route-plan' ? body.variants : [{ connectionId: null, protocol: body.input ? 'responses' : Array.isArray(body.system) ? 'anthropic-messages' : 'chat-completions', body }];
const prompt = body => Buffer.from(JSON.stringify({ model: body.model, tools: body.tools ?? [], system: body.system ?? null, messages: body.messages ?? body.input ?? [] }));
// This measures ordered prompt fields, not a supplier cache hit or saved
// tokens. Metadata stays outside the request and cannot invalidate its prefix.
export function prefixAudit(body, previous = null) {
const old = previous ? variants(previous) : [];
return { schemaVersion: 1, method: 'ordered-wire-prompt-fields-utf8', upstreamCache: 'unknown', variants: variants(body).map(current => {
const tools = JSON.stringify(current.body.tools ?? []), bytes = prompt(current.body);
const prior = old.find(value => value.connectionId === current.connectionId && value.protocol === current.protocol && value.body.model === current.body.model);
const previousBytes = prior ? prompt(prior.body) : null;
let common = 0;
if (previousBytes) while (common < Math.min(previousBytes.length, bytes.length) && previousBytes[common] === bytes[common]) common++;
const toolsChanged = !!prior && JSON.stringify(prior.body.tools ?? []) !== tools;
return { connectionId: current.connectionId, protocol: current.protocol, model: current.body.model,
toolsSha256: hash(tools), toolBytes: Buffer.byteLength(tools), toolNames: (current.body.tools ?? []).map(tool => tool.function?.name ?? tool.name),
promptBytes: bytes.length, previousPromptBytes: previousBytes?.length ?? null, commonPrefixBytes: common,
reason: !prior ? 'new_route_or_first_request' : toolsChanged ? 'tool_surface_changed' : bytes.equals(previousBytes) ? 'same_prompt' : 'prompt_append_or_change' };
}) };
}
+45 -16
View File
@@ -8,6 +8,7 @@ import { skillCatalogMessage, SKILL_LIMITS } from '../skills/skill-registry.mjs'
import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs';
import { modelReservation,taskConsumption,verifyModelReservation } from '../../shared/contracts/model-reservation.mjs';
import { fileContinuation } from './read-continuation.mjs';
import { prefixAudit } from './prefix-audit.mjs';
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
@@ -61,7 +62,7 @@ export function budgetFor(config, run, task, transportReservationTokens = 0) {
if (taskRemainingTokens !== null && taskRemainingTokens < limit) { limit = taskRemainingTokens; reason = 'task_token_limit'; }
if(!Number.isSafeInteger(transportReservationTokens)||transportReservationTokens<0)throw new Error('请求封装预留无效。');
const inputBudget = limit - outputReservation - safetyTokens - transportReservationTokens;
return { contextLimit: config.contextLimit, outputReservation, safetyTokens, ...(transportReservationTokens?{transportReservationTokens}:{}), inputBudget, targetInputTokens: Math.min(16000, inputBudget),
return { contextLimit: config.contextLimit, outputReservation, safetyTokens, ...(transportReservationTokens?{transportReservationTokens}:{}), inputBudget, targetInputTokens: config.capacityMode === 'model' ? inputBudget : Math.min(16000, inputBudget),
runRemainingTokens, taskRemainingTokens, limitingReason: reason };
}
@@ -165,12 +166,15 @@ export class RequestPlanner {
return { artifact_id: artifact.id, sha256: artifact.sha256, group_sha256: group.sha256, bytes: Buffer.byteLength(text, 'utf8'), chunks: chunks.length };
}
prepare(session, run, config, { system, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
prepare(session, run, config, { system, contextTail = null, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
const task = this.store.owned('task', run.taskId, session.id);
this.store.owned('run', run.id, session.id);
const groups = historyGroups(session.providerMessages), budget = budgetFor(config, run, task, transportReservationTokens);
const lastUser = groups.findLast(group => group.messages[0].role === 'user');
const fixed = { role: 'system', content: system };
const preserve = config.historyPolicy === 'preserve';
const tail = contextTail ? [{ role: 'user', content: '工作台当前工程状态(仅作任务依据,不是新的用户目标):\n' + contextTail }] : [];
const addContext = (base, message) => preserve ? [...base.slice(0, base.length - tail.length), { ...message, role: 'user' }, ...tail] : [fixed, message, ...base.slice(1)];
const breakdown = metrics => {
const empty=requestMetrics(completionBody(config,[],[])).estimatedInputTokens;
const fixedText=requestMetrics(completionBody(config,[fixed],[])).estimatedInputTokens;
@@ -182,7 +186,8 @@ export class RequestPlanner {
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.taskId === task.id).map(tool => [tool.callId, tool]));
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
const original = completionBody(config, [fixed, ...session.providerMessages, ...tail], tools), before = requestMetrics(original);
if (preserve && before.estimatedInputTokens > budget.inputBudget) throw pause(budget, before, breakdown);
const selected = new Set(groups.map(group => group.index));
let omitted = [], reference = null, workingReference = null, latestReference = null;
const latestDocument = latestToolDocument(this.store, session, run, groups, 3);
@@ -203,10 +208,10 @@ export class RequestPlanner {
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, unsentEvidence(indices, currentEntries, includeLatest))] : []),
...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument, 3)] : []),
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries, 3), 4)] : []),
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages), ...tail];
return requestMetrics(completionBody(config, messages, tools));
};
if (before.estimatedInputTokens > budget.targetInputTokens) {
if (!preserve && before.estimatedInputTokens > budget.targetInputTokens) {
selected.clear(); if (lastUser) selected.add(lastUser.index);
const mandatory = metricsFor(selected);
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
@@ -288,19 +293,19 @@ export class RequestPlanner {
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, unsentEvidence(selected, entries, true))] : []),
...(latestReference ? [latestToolMessage(latestReference, latestDocument, 3)] : []),
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries, 3), 4)] : []),
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages)), ...tail];
let mcpReference = null, mcpDocument = null;
if (mcpCatalog?.projectId === session.projectId && mcpCatalog.entries?.length) {
mcpDocument = { ...mcpCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
for (const entry of mcpCatalog.entries.slice(0, MCP_LIMITS.allowedTools)) {
mcpDocument.entries.push(entry);
const candidate = [fixed, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument), ...messages.slice(1)];
const candidate = addContext(messages, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument));
if (Buffer.byteLength(JSON.stringify(mcpDocument), 'utf8') > 24000
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) mcpDocument.entries.pop();
}
if (mcpDocument.entries.length) {
mcpReference = this.artifact(session, run, mcpDocument, 'context-mcp-catalog');
messages.splice(1, 0, mcpCatalogMessage(mcpReference, mcpDocument));
messages.splice(0, messages.length, ...addContext(messages, mcpCatalogMessage(mcpReference, mcpDocument)));
}
}
let skillReference = null, skillDocument = null;
@@ -308,13 +313,13 @@ export class RequestPlanner {
skillDocument = { ...skillCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
for (const entry of skillCatalog.entries.slice(0, SKILL_LIMITS.enabled)) {
skillDocument.entries.push(entry);
const candidate = [fixed, skillCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, skillDocument), ...messages.slice(1)];
const candidate = addContext(messages, skillCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, skillDocument));
if (Buffer.byteLength(JSON.stringify(skillDocument), 'utf8') > SKILL_LIMITS.catalogBytes
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) skillDocument.entries.pop();
}
if (skillDocument.entries.length) {
skillReference = this.artifact(session, run, skillDocument, 'context-skill-catalog');
messages.splice(1, 0, skillCatalogMessage(skillReference, skillDocument));
messages.splice(0, messages.length, ...addContext(messages, skillCatalogMessage(skillReference, skillDocument)));
}
}
// Optional catalogs and memory use only space left after goals, paired history and current code evidence.
@@ -325,13 +330,13 @@ export class RequestPlanner {
for (const entry of projectMemory.entries.slice(0, MEMORY_CONTEXT_LIMITS.entries)) {
if (entry.sourceFingerprint !== projectMemory.sourceFingerprint) continue;
memoryDocument.entries.push(entry);
const candidate = [fixed, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument), ...messages.slice(1)];
const candidate = addContext(messages, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument));
if (Buffer.byteLength(JSON.stringify(memoryDocument), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > memoryBudget) memoryDocument.entries.pop();
}
if (memoryDocument.entries.length) {
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
messages.splice(1, 0, projectMemoryMessage(memoryReference, memoryDocument));
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
}
}
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
@@ -341,11 +346,18 @@ export class RequestPlanner {
if(tokenReservation&&tokenReservation.reservedTokens>credit)throw pause({...budget,limitingReason:runCredit<=taskCredit?'token_limit':'task_token_limit',
tokenReservation,remainingTokens:credit,pauseKind:'request_reservation'},metrics,breakdown);
const requestArtifact = this.artifact(session, run, body, 'model-request');
const tailArtifact = tail.length ? this.artifact(session, run, tail[0], 'context-state-tail') : null;
const previousPlan = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === task.id && plan.requestAttempts > 0)
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.requestIndex - b.requestIndex).at(-1) ?? null;
const previousBody = previousPlan ? JSON.parse(this.store.artifactStore.read(this.store.owned('artifact', previousPlan.requestArtifactId, session.id))) : null;
const prefix = { ...prefixAudit(body, previousBody), previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null };
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
runId: run.id, stepId, requestIndex: [...this.store.core.context_plan.values()].filter(plan => plan.runId === run.id).length + 1,
status: 'prepared', createdAt: new Date().toISOString(), finishedAt: null,
requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens,
requestArtifactId: requestArtifact.id,
prefixAudit: prefix,
...(preserve ? { contextLayout: 'stable-prefix-1', historyPolicy: 'preserve', contextTailArtifactId: tailArtifact?.id ?? null, contextTailSha256: tailArtifact?.sha256 ?? null } : {}),
...(tokenReservation?{tokenReservation,maxBudgetAttempts:Math.min(8,Math.floor(credit/tokenReservation.reservedTokens))}:{engineStepOnly:true}),
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
...(metrics.imageCount?{imageCount:metrics.imageCount,imageReservationTokens:metrics.imageReservationTokens,imageEstimate:metrics.imageEstimate,
@@ -358,7 +370,7 @@ export class RequestPlanner {
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens),
workingRetentionPolicyVersion: 1,
readBudgetPolicyVersion: 3,
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - tail.length - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
workingSetArtifactId: workingReference?.id ?? null, workingSetSha256: workingReference?.sha256 ?? null, workingSetEntries: entries.length,
@@ -404,6 +416,23 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
historyGroups(requestHistory(body));
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit']) {
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
}
if (plan.prefixAudit) {
const previous = plan.prefixAudit.previousPlanId ? store.owned('context_plan', plan.prefixAudit.previousPlanId, session.id) : null;
if (previous && (previous.taskId !== plan.taskId || previous.id === plan.id || previous.createdAt > plan.createdAt || previous.requestSha256 !== plan.prefixAudit.previousRequestSha256)) throw new Error('前缀对照来源不匹配。');
const previousBody = previous ? JSON.parse(store.artifactStore.read(get(previous.requestArtifactId, 'model-request', previous.requestSha256))) : null;
const expected = { ...prefixAudit(body, previousBody), previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null };
if (JSON.stringify(expected) !== JSON.stringify(plan.prefixAudit)) throw new Error('前缀观测与原请求字节不匹配。');
}
const carriesContext = content => requestHistory(body).filter(value => typeof value.content === 'string'
&& (value.role === 'system' && value.content === content || plan.contextLayout === 'stable-prefix-1' && value.role === 'user' && value.content.includes(content))).length === 1;
if (plan.contextTailArtifactId) {
const artifact = get(plan.contextTailArtifactId, 'context-state-tail', plan.contextTailSha256);
const tail = JSON.parse(store.artifactStore.read(artifact));
if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || tail.role !== 'user' || !carriesContext(tail.content)) throw new Error('动态状态与实际发送内容不匹配。');
}
for(const key of ['tokenReservation','maxBudgetAttempts'])if(JSON.stringify(frozen[key]??null)!==JSON.stringify(plan[key]??null))throw new Error('模型用量预留与发送前封存不一致。');
for(const key of ['imageCount','imageReservationTokens','imageEstimate','inputImages']) {
if(JSON.stringify(frozen[key]??null)!==JSON.stringify(plan[key]??null))throw new Error('图片身份或预算与发送前封存不匹配。');
@@ -451,7 +480,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| document.entries.length > MEMORY_CONTEXT_LIMITS.entries || Buffer.byteLength(JSON.stringify(document), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes
|| document.entries.some(entry => entry.sourceFingerprint !== document.sourceFingerprint)) throw new Error('项目记忆工件归属或范围不匹配。');
const message = projectMemoryMessage(artifact, document);
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('项目记忆与实际发送内容不匹配。');
if (!carriesContext(message.content)) throw new Error('项目记忆与实际发送内容不匹配。');
}
if ((frozen.skillCatalogArtifactId ?? null) !== (plan.skillCatalogArtifactId ?? null)
|| (frozen.skillCatalogSha256 ?? null) !== (plan.skillCatalogSha256 ?? null)
@@ -465,7 +494,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| document.entries.length > SKILL_LIMITS.enabled || Buffer.byteLength(JSON.stringify(document), 'utf8') > SKILL_LIMITS.catalogBytes
|| new Set(document.entries.map(entry => entry.id)).size !== document.entries.length) throw new Error('技能目录归属或范围不匹配。');
const message = skillCatalogMessage(artifact, document);
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('技能目录与实际发送内容不匹配。');
if (!carriesContext(message.content)) throw new Error('技能目录与实际发送内容不匹配。');
}
if ((frozen.mcpCatalogArtifactId ?? null) !== (plan.mcpCatalogArtifactId ?? null)
|| (frozen.mcpCatalogSha256 ?? null) !== (plan.mcpCatalogSha256 ?? null)
@@ -478,7 +507,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| document.kind !== 'registered-mcp-catalog' || !Array.isArray(document.entries) || document.entries.length !== plan.mcpCatalogEntries
|| document.entries.length > MCP_LIMITS.allowedTools || Buffer.byteLength(JSON.stringify(document), 'utf8') > 24000) throw new Error('MCP目录归属或范围不匹配。');
const message = mcpCatalogMessage(artifact, document);
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('MCP目录与实际发送内容不匹配。');
if (!carriesContext(message.content)) throw new Error('MCP目录与实际发送内容不匹配。');
}
if (plan.latestToolsArtifactId) {
const artifact = get(plan.latestToolsArtifactId, 'context-latest-tools', plan.latestToolsSha256);
+1
View File
@@ -204,6 +204,7 @@ export class GitDelivery {
}
async plan(session, options = {}, { source = 'user' } = {}) {
if (session.fileDrafts?.some(row => row.taskId === session.taskId && row.status === 'staging')) throw conflict('分段文件草稿尚未完成,请完成提案或显式放弃后再交付。');
assertWorkersResolved(this.store, session.projectId);
if (workerForProject(this.store, session.projectId)) throw conflict('受限子任务不能独立Git提交;请在父任务审查合并后交付。');
const idleOptions = { exceptSessionId: source === 'agent' ? session.id : null };
+2
View File
@@ -35,6 +35,8 @@ export class ConfigImporter {
...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}),
...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}),
...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}),
...(item.contextLimit !== undefined ? { contextLimit: item.contextLimit } : {}),
...(item.maxOutputTokens !== undefined ? { maxOutputTokens: item.maxOutputTokens } : {}),
baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
}
} else if (source === 'ccswitch') {
+3 -2
View File
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
import { catalogPage, catalogRoute } from '../../shared/contracts/model-catalog.mjs';
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
import { modelProtocol, capabilityDeclarations } from '../../shared/contracts/model-capabilities.mjs';
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
const stamp = () => new Date().toISOString();
@@ -128,8 +129,8 @@ export class ModelCatalog {
protocol: value.connection.protocol, baseUrl: value.connection.baseUrl, brand: value.connection.brand, messagesAuth: value.connection.messagesAuth,
requiresKey: value.connection.requiresKey, concurrency: value.connection.concurrency, parameterProfile: value.connection.parameterProfile ?? 'auto',
capabilityDeclarations: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state === 'unknown' ? declarations[key] : state])), streaming: false,
contextLimit: Math.min(value.connection.contextLimit ?? 16000, model.contextLimit ?? 200000),
maxOutputTokens: Math.min(value.connection.maxOutputTokens ?? 2048, model.maxOutputTokens ?? 16000),
contextLimit: model.contextLimit ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit,
maxOutputTokens: model.maxOutputTokens ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens,
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) });
const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog';
if (!owner) owner = connection;
+3 -2
View File
@@ -13,6 +13,7 @@ import { assertModelParameterSupport } from '../../shared/contracts/model-parame
import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs';
import { NetworkDiagnostics } from './network-diagnostics.mjs';
import { ModelCatalog, credentialScope } from './model-catalog.mjs';
import { capacitySettings, routedCapacity } from '../../shared/contracts/model-capacity.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -217,7 +218,7 @@ export class ModelHub {
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,
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
...capacitySettings(input, previous ?? undefined),
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() };
@@ -291,7 +292,7 @@ export class ModelHub {
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile,
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
...routedCapacity(config, members),
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 } };
}
+14 -6
View File
@@ -6,7 +6,7 @@ export const protocolFailure = (message, kind = 'protocol', extra = null) => new
// even a syntactically complete leading tool call is dropped, because any later call in
// the same turn may be cut mid-argument. The diagnostic must tell the model what happened
// and how to proceed, instead of a generic incompleteness message it cannot act on.
export const OUTPUT_TRUNCATED_HINT = '模型输出达到单次 output token 上限(finish_reason=length),本次响应整体未执行任何工具(即使其中一个工具参数已完整也不执行,避免应用被截断的半成品)。请减少单次响应的工具数量:把多文件提案拆成每次一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。';
export const OUTPUT_TRUNCATED_HINT = '上游模型在本次配置的输出额度处停止(finish_reason=length),本次响应整体未执行工具,原响应和用量已保留。请拆分输出:已有文件使用propose_patch;单个长文件用propose_file_chunk分多轮追加较短的完整片段,最后complete=true生成完整提案。已有成功片段使用原draft_id/next_offset/draft_sha256继续,不从头重复。不要在一个响应中堆叠多个大工具参数。原目标和已读依据保留。';
export const outputTruncatedFailure = (kind = 'protocol') => protocolFailure(OUTPUT_TRUNCATED_HINT, kind, { reason: 'output_truncated' });
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
@@ -20,14 +20,22 @@ export function reportedUsage(config, value) {
const input = raw.input_tokens + cached + created, total = input + raw.output_tokens;
if (!Number.isSafeInteger(total)) return null;
return { prompt_tokens: input, completion_tokens: raw.output_tokens, total_tokens: total,
prompt_tokens_details: { cached_tokens: cached, cache_creation_tokens: created }, raw: structuredClone(raw), protocol: 'anthropic-messages' };
...(raw.cache_read_input_tokens !== undefined || raw.cache_creation_input_tokens !== undefined ? { prompt_tokens_details: {
...(raw.cache_read_input_tokens !== undefined ? { cached_tokens: cached } : {}),
...(raw.cache_creation_input_tokens !== undefined ? { cache_creation_tokens: created } : {}) } } : {}),
raw: structuredClone(raw), protocol: 'anthropic-messages' };
}
const input = config.protocol === 'responses' ? raw.input_tokens : raw.prompt_tokens;
const output = config.protocol === 'responses' ? raw.output_tokens : raw.completion_tokens;
const valid = number => Number.isSafeInteger(number) && number >= 0;
if (!valid(raw.total_tokens) && !(valid(input) && valid(output))) return null;
const cached = config.protocol === 'responses' ? raw.input_tokens_details?.cached_tokens : raw.prompt_tokens_details?.cached_tokens ?? raw.prompt_cache_hit_tokens;
const cacheDetails = valid(cached) && valid(input) && cached <= input ? { cached_tokens: cached } : null;
const reasoning = config.protocol === 'responses' ? raw.output_tokens_details?.reasoning_tokens : raw.completion_tokens_details?.reasoning_tokens;
return { ...(valid(input) ? { prompt_tokens: input } : {}), ...(valid(output) ? { completion_tokens: output } : {}),
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output };
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output,
...(cacheDetails ? { prompt_tokens_details: cacheDetails } : {}), ...(valid(reasoning) && valid(output) && reasoning <= output ? { completion_tokens_details: { reasoning_tokens: reasoning } } : {}),
raw: structuredClone(raw), protocol: config.protocol ?? 'chat-completions' };
}
function acceptsEmptyObject(tools, name) {
@@ -84,9 +92,10 @@ export function normalizeProtocolResponse(config, value) {
}
if (config.protocol !== 'responses') {
const received = value?.choices?.[0]?.message;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return value;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return { ...value, usage: reportedUsage(config, value) };
if (typeof received.reasoning_content !== 'string') throw protocolFailure('Chat reasoning_content必须为字符串,原响应未用于执行工具。');
const normalized = structuredClone(value), target = normalized.choices[0].message;
normalized.usage = reportedUsage(config, value);
delete target.reasoning_content;
target.providerState = { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content };
@@ -109,8 +118,7 @@ export function normalizeProtocolResponse(config, value) {
}
} else if (item.type !== 'reasoning') throw protocolFailure('Responses包含当前尚未接入的服务端工具或输出类型:' + String(item.type ?? '未标注').slice(0, 100) + '。');
}
const raw = value.usage, usage = raw ? { prompt_tokens: raw.input_tokens, completion_tokens: raw.output_tokens,
...(raw.total_tokens !== undefined ? { total_tokens: raw.total_tokens } : {}), raw, protocol: 'responses' } : null;
const usage = reportedUsage(config, value);
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
providerState: { protocol: 'responses', endpoint: config.baseUrl, model: config.model, responseId: value.id ?? null, items: value.output } }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage };
}
+7 -3
View File
@@ -1,15 +1,19 @@
import { CAPACITY_RANGES, capacityMode } from '../../shared/contracts/model-capacity.mjs';
const ranges = {
contextLimit: [1000, 200000], maxOutputTokens: [256, 16000], maxSteps: [1, 30],
...CAPACITY_RANGES, maxSteps: [1, 30],
maxRunDurationMs: [1000, 3600000], maxRunTokens: [1000, 2000000], maxTaskTokens: [1000, 10000000],
};
// Budget-only edits cannot change the selected route, endpoint or credential.
export function validateRuntimeBudgets(input) {
if (!input || typeof input !== 'object' || Array.isArray(input) || !Object.keys(input).length
|| Object.keys(input).some(key => !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
|| Object.keys(input).some(key => !['capacityMode', 'historyPolicy'].includes(key) && !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
for (const [key, value] of Object.entries(input)) {
if (key === 'capacityMode') { capacityMode(value); continue; }
if (key === 'historyPolicy') { if (!['preserve', 'compact'].includes(value)) throw new Error('请选择完整传递或允许整理历史。'); continue; }
const [min, max] = ranges[key];
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(key + ' 需填写范围内的整数。');
}
return { ...input };
return { ...input, ...(!Object.hasOwn(input, 'capacityMode') && ['contextLimit', 'maxOutputTokens'].some(key => Object.hasOwn(input, key)) ? { capacityMode: 'manual' } : {}) };
}
+5 -1
View File
@@ -2,9 +2,10 @@ import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { isId } from '../../shared/contracts/execution.mjs';
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
export const DEFAULT_CONFIG = {
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048,
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', ...DEFAULT_MODEL_CAPACITY, capacityMode: 'model', historyPolicy: 'preserve', maxSteps: 12,
maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, configRevision: 1,
modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000,
};
@@ -12,6 +13,9 @@ export const DEFAULT_CONFIG = {
export function cleanConfig(value = {}) {
const result = { ...DEFAULT_CONFIG };
for (const key of Object.keys(result)) if (Object.hasOwn(value, key)) result[key] = value[key];
// Old settings stay manual. Every saved Run keeps its original snapshot.
if (!Object.hasOwn(value, 'capacityMode') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.capacityMode = 'manual';
if (!Object.hasOwn(value, 'historyPolicy') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.historyPolicy = 'compact';
for (const key of ['nativeParameters', 'outputTokenField', 'parameterProfile']) if (Object.hasOwn(value, key)) result[key] = structuredClone(value[key]);
return result;
}
@@ -0,0 +1,70 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { safePath, readText, hash, proposeFile } from '../../server/files.mjs';
import { assertWorkersResolved, assertWorkerWriteScope } from '../../shared/contracts/workers.mjs';
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
const fail = message => { throw Object.assign(new Error(message), { status: 409 }); };
const emptySha = hash(Buffer.alloc(0));
export const pendingFileDrafts = session => (session.fileDrafts ?? []).filter(row => row.taskId === session.taskId && row.status === 'staging');
// Fragments are immutable artifacts. A partial draft is never a file proposal,
// never a change-set member, and never written into the user's project.
export function proposeFileChunk(store, session, args) {
if (Object.keys(args).some(key => !['path', 'content', 'reason', 'offset', 'complete', 'draft_id', 'expected_sha256', 'base_sha256'].includes(key))
|| typeof args.path !== 'string' || typeof args.content !== 'string' || typeof args.reason !== 'string' || !args.reason.trim()
|| !Number.isSafeInteger(args.offset) || args.offset < 0 || typeof args.complete !== 'boolean'
|| args.content.includes('\0') || !args.content.isWellFormed() || !args.complete && !args.content.length) fail('分段提案需要有效路径、文本、说明、offset和complete;未完成片段不能为空。');
const run = store.owned('run', session.runId, session.id);
if (run.taskId !== session.taskId) fail('分段提案缺少当前Task/Run归属。');
assertWorkersResolved(store, session.projectId); assertWorkerWriteScope(store, session, args.path);
assertMcpResolved(store, session.projectId); assertChangeSetsResolved(store, session.projectId);
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
const project = store.project(session.projectId), target = safePath(project, args.path, true);
const base = fs.existsSync(target) ? readText(project, args.path).sha256 : null;
let draft = args.draft_id ? (session.fileDrafts ?? []).find(row => row.id === args.draft_id) : null;
if (args.draft_id && (!draft || draft.status !== 'staging' || draft.taskId !== session.taskId || draft.projectId !== session.projectId || draft.path !== args.path)) fail('草稿不属于当前Task/路径或已结束,请核对原回执。');
if (!draft) {
if (args.offset !== 0 || args.expected_sha256 !== undefined && args.expected_sha256 !== emptySha) fail('新草稿必须从offset 0开始。');
if (pendingFileDrafts(session).some(row => row.path === args.path) || pendingFileDrafts(session).length >= 16) fail('该路径已有未完成草稿或当前Task已达16份草稿,请继续原草稿或显式放弃。');
if (Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== base) fail('原文件SHA已变化,请重新核对。');
draft = { id: randomUUID(), projectId: session.projectId, taskId: session.taskId, path: args.path, status: 'staging', baseSha256: base,
sha256: emptySha, characters: 0, bytes: 0, chunks: [], createdAt: new Date().toISOString() };
} else if (args.offset !== draft.characters || args.expected_sha256 !== draft.sha256) fail('片段offset或SHA与原草稿不一致,未追加;请使用上一次成功回执,不能从头重复。');
if (draft.baseSha256 !== base || Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== draft.baseSha256) fail('分段期间原文件已变化,草稿不能覆盖新内容;请放弃后按新SHA准备。');
const previous = draft.chunks.map(part => {
const artifact = store.owned('artifact', part.id, session.id);
if (artifact.kind !== 'file-proposal-fragment' || artifact.taskId !== session.taskId || artifact.projectId !== session.projectId || artifact.sha256 !== part.sha256) fail('原片段身份不匹配。');
return store.artifactStore.read(artifact);
}).join('');
if (hash(Buffer.from(previous)) !== draft.sha256 || previous.length !== draft.characters || Buffer.byteLength(previous) !== draft.bytes) fail('原草稿校验失败,未采用任何片段。');
const content = previous + args.content, bytes = Buffer.byteLength(content);
if (bytes > 512000 || draft.chunks.length >= 256) fail('完整文本超过512KB或256段;请按工程模块拆分文件。');
const artifact = store.artifactStore.write(session, run, args.content, { kind: 'file-proposal-fragment', mediaType: 'text/plain' });
store.core.artifact.set(artifact.id, artifact);
const next = { ...draft, sha256: hash(Buffer.from(content)), characters: content.length, bytes, chunks: [...draft.chunks, { id: artifact.id, sha256: artifact.sha256 }] };
const original = session.fileDrafts ?? [];
const originalChanges = [...session.changes], originalStatus = session.status;
session.fileDrafts = [...original.filter(row => row.id !== draft.id), next];
let result;
try {
if (args.complete) {
next.status = 'finalized';
result = proposeFile(store, session, { path: args.path, reason: args.reason, content, base_sha256: next.baseSha256 }, { persist: false });
next.changeId = result.change_id ?? null;
}
store.save(session);
} catch (cause) { session.fileDrafts = original; session.changes = originalChanges; session.status = originalStatus; throw cause; }
return { ...(result ?? { status: 'staged', message: '片段已保存,尚无可应用提案。继续使用draft_id、next_offset和draft_sha256;最后一段complete=true才创建完整审查提案。' }),
draft_id: next.id, path: next.path, next_offset: next.characters, draft_sha256: next.sha256, bytes: next.bytes, complete: args.complete };
}
export function discardFileDraft(store, session, args) {
if (Object.keys(args).some(key => !['draft_id', 'expected_sha256', 'reason'].includes(key)) || typeof args.reason !== 'string' || !args.reason.trim()) fail('放弃草稿需要原身份、SHA与说明。');
const draft = pendingFileDrafts(session).find(row => row.id === args.draft_id);
if (!draft || draft.sha256 !== args.expected_sha256) fail('草稿归属、状态或SHA不匹配。');
draft.status = 'discarded'; draft.discardReason = args.reason.slice(0, 600); store.save(session);
return { status: 'discarded', draft_id: draft.id, path: draft.path, message: '草稿已放弃,原片段保留,项目文件没有改变。' };
}
+2 -2
View File
@@ -1,4 +1,5 @@
import { validateRuntimeBudgets } from '../core/models/runtime-settings.mjs';
import { capacitySettings, capacityMode } from '../shared/contracts/model-capacity.mjs';
import fs from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
@@ -864,9 +865,8 @@ return async (request, response) => {
if (!['demo', 'compatible'].includes(input.mode)) throw new Error('请选择有效运行模式。');
const config = {
mode: input.mode, baseUrl: String(input.baseUrl || '').trim(), model: String(input.model || '').trim(),
contextLimit: Math.trunc(Math.max(1000, Math.min(200000, Number(input.contextLimit) || 16000))),
...capacitySettings(input, store.config), capacityMode: capacityMode(input.capacityMode),
maxSteps: Math.trunc(Math.max(1, Math.min(30, Number(input.maxSteps) || 12))),
maxOutputTokens: Math.trunc(Math.max(256, Math.min(16000, Number(input.maxOutputTokens) || 2048))),
...validateModelWaitSettings(input, store.config),
maxRunDurationMs: Math.trunc(Math.max(1000, Math.min(3600000, Number(input.maxRunDurationMs) || store.config.maxRunDurationMs))),
maxRunTokens: Math.trunc(Math.max(1000, Math.min(2000000, Number(input.maxRunTokens) || store.config.maxRunTokens))),
+2 -2
View File
@@ -129,7 +129,7 @@ export function searchFiles(project, args) {
scope: '有数量/体积上限的文本搜索;无结果不表示所有文件都已搜索。' };
}
export function proposeFile(store, session, args, { patch = null, sourceBinding = null } = {}) {
export function proposeFile(store, session, args, { patch = null, sourceBinding = null, persist = true } = {}) {
assertWorkersResolved(store, session.projectId);
assertWorkerWriteScope(store, session, args.path);
assertMcpResolved(store, session.projectId);
@@ -159,7 +159,7 @@ export function proposeFile(store, session, args, { patch = null, sourceBinding
};
session.changes.push(change);
if (!['running', 'awaiting_approval', 'stopping'].includes(session.status)) session.status = 'needs_review';
store.save(session);
if (persist) store.save(session);
return { status: 'awaiting_review', change_id: change.id, path: change.path,
additions: change.additions, deletions: change.deletions, message: '提案已保存,项目文件尚未改变。等待用户查看差异并应用。' };
}
+5 -4
View File
@@ -12,6 +12,7 @@ import { ModelTransport } from '../core/models/transport.mjs';
import { localModelEstimate } from '../shared/contracts/model-reservation.mjs';
import { ERROR_CAPTURE_LIMIT, readErrorResponse, upstreamCapture } from '../core/models/upstream-error.mjs';
import { messagesAuthSettings } from '../shared/contracts/model-endpoint.mjs';
import { fileDraftToolDefinitions } from '../shared/contracts/file-draft-tools.mjs';
export const engineToolDefinitions = [
{ type: 'function', function: { name: 'inspect_engine_checks', description: '读取当前Task已经保存的外部引擎连接核验:真实安装版本、启动完成信号、SDK会话、进程关闭、原报告工件和能力限制。不会启动引擎或发送prompt;完整原记录通过已有read_artifact读取。', parameters: { type: 'object', properties: {}, additionalProperties: false } } },
@@ -50,6 +51,7 @@ export const toolDefinitions = [
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 }, expected_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' } }, required: ['path'] } } },
{ type: 'function', function: { name: 'search_files', description: '在当前项目的文本文件中按字面内容检索。结果声明已搜索文件数与数量上限。',
parameters: { type: 'object', properties: { query: { type: 'string' }, case_sensitive: { type: 'boolean' } }, required: ['query'] } } },
...fileDraftToolDefinitions,
{ type: 'function', function: { name: 'propose_file', description: '提出一个文本文件的完整新内容。只产生待审查提案,不写入项目;由用户查看差异后应用。',
parameters: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' }, reason: { type: 'string' }, base_sha256: { type: ['string', 'null'], description: '如已读取文件,可传入该文件的 SHA256 检查读取后变化;新文件为 null。' } }, required: ['path', 'content', 'reason'] } } },
{ type: 'function', function: { name: 'run_command', description: '请求在当前项目目录运行终端命令。命令会显示给用户,用户确认后才运行。命令有时间与输出限制。',
@@ -62,8 +64,7 @@ export const researchToolDefinitions = [
{ type: 'function', function: { name: 'read_research_evidence', description: '读取当前会话原完整REA Evidence的实际字段,校验工件、Bundle及Task来源。pointer使用JSON Pointer,默认/normalized_result;按返回available_fields选择下一级字段,offset/limit和next_offset读取预算分页。静态关系是候选,不能当成运行观测;不会再次调用REA。', parameters: { type: 'object', properties: { research_job_id: { type: 'string' }, pointer: { type: 'string', maxLength: 400 }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['research_job_id'] } } },
];
export function projectContext(project) {
const inventory = listFiles(project, '', 3, 160);
export function projectContext(project, { inventory = true } = {}) {
return [
'你是这个本地编程工作台的编程助手。用用户的语言沟通,以实际读取和工具结果为依据。',
'当前项目:' + project.name + '。所有文件路径相对于这个项目。',
@@ -72,6 +73,7 @@ export function projectContext(project) {
'工程任务先用inspect_project识别语言、脚本、规则与Git基线。plan_checks准备已识别npm或Python检查计划,run_checks请求用户确认后执行。Python支持python:test和python:compile,绑定unittest/pytest、实际解释器和源码;混合项目默认保留npm范围,明确选择Python名称才能执行。只凭回答不能声称检查通过。',
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
'单个文件大于本次输出额度时,用propose_file_chunk分多轮追加完整片段,核对draft_id/next_offset/draft_sha256;不要从头重复大文件。最后complete=true才生成可审查完整提案。未完成片段不能应用或交付,放弃用discard_file_draft保留原因。',
'已有文本文件满足当前目标时,完整分页读取后用verify_existing_files登记当前SHA和原read_call_ids,说明采用原因;跨Task须显式选择source_result_id。无需重写相同文件,不把旧成果冒充新写入;明确修改要求、测试和页面验收仍需各自真实证据。',
'跨文件修改的提案准备完整后,用prepare_change_set将本Task的change_id封存成整批审查。准备不表示应用;用户核对整个批次并确认,结果未知时先用工作台恢复入口核对,不重放文件写入。',
'复杂工程任务先了解实际范围,再用plan_task保存有限依赖步骤及真实通过条件;verify_task_step引用原工具调用、已应用批次或当前检查/页面job核验。不能删改原条件掩盖失败;inspect_task_plan核对未完成项,模型文字不代替步骤核验。简单问答无需新建工程计划。',
@@ -87,8 +89,7 @@ export function projectContext(project) {
'当前终端:' + executionEnvironment().shell + '。' + executionEnvironment().shellSyntax + ' 输入和输出使用 UTF-8。',
'任务中断后先核对当前状态,不假定缺少结果的工具已经成功。已有提案可等待用户审核,不要重复提出相同改动。',
'完成必要步骤后直接给出结果。不要无限继续调用工具。',
'当前文件清单(有数量上限):',
inventory.files.filter(file => file.kind === 'file').map(file => file.path).join('\n'),
...(inventory ? ['当前文件清单(有数量上限):', listFiles(project, '', 3, 160).files.filter(file => file.kind === 'file').map(file => file.path).join('\n')] : []),
].join('\n');
}
+22 -5
View File
@@ -9,9 +9,11 @@ import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { sanitizeModelText } from '../core/models/upstream-error.mjs';
import { OUTPUT_TRUNCATED_HINT } from '../core/models/protocols.mjs';
import { StringDecoder } from 'node:string_decoder';
import { setImmediate as yieldExecution } from 'node:timers/promises';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { proposeFileChunk, discardFileDraft, pendingFileDrafts } from '../core/workspaces/file-proposal-drafts.mjs';
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
@@ -82,6 +84,8 @@ labels.plan_task = '保存任务依赖计划';
labels.verify_task_step = '核验任务步骤原证据';
labels.inspect_task_plan = '核对任务计划与未完成项';
labels.verify_existing_files = '核对当前已有成果';
labels.propose_file_chunk = '组装长文件提案';
labels.discard_file_draft = '放弃未完成文件草稿';
labels.read_registered_skill = '读取已登记技能修订';
labels.call_registered_mcp = '请求调用已登记MCP工具';
@@ -122,6 +126,7 @@ export function validateToolArgs(tool, args) {
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
return;
}
if (['propose_file_chunk', 'discard_file_draft'].includes(tool)) return; // The draft contract validates its full input before changing state.
const required = ['diagnose_environment','plan_environment','inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'prepare_environment' ? ['plan_id','fingerprint'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
@@ -148,6 +153,7 @@ export class Runtime {
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
fileResults() { return this.results ??= new FileResults(this.store); }
async fileDelivery(session) {
if (pendingFileDrafts(session).length) return { satisfied: false, stopReason: 'file_draft_incomplete', message: '仍有未完成的分段文件草稿;请继续组装完整提案或显式放弃,片段不能视为交付。' };
const task = this.store.owned('task', session.taskId, session.id), delivery = this.fileResults().completion(session);
if (!delivery.satisfied) return { ...delivery, stopReason: 'delivery_incomplete', message: delivery.requiresChange
? '当前要求包含修改,尚无对应追加要求之后的实际文件改动。已有成果核对不能代替修改。'
@@ -354,16 +360,21 @@ export class Runtime {
// Keep the complete goal once in this request view. The stored contract
// still contains its original goal for intent and evidence verification.
const { goal, ...contract } = taskContract(task);
const context = this.provider.redact(projectContext(run.project) + (run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
const stablePrefix = config.historyPolicy === 'preserve';
const fixedRules = projectContext(run.project, { inventory: false });
const workerContract = run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget,
rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
}) : '') + '\n当前项目/会话/任务身份:' + JSON.stringify({
}) : '';
const fixedContext = fixedRules + workerContract;
const context = this.provider.redact((stablePrefix ? projectContext(run.project).slice(fixedRules.length) : projectContext(run.project) + workerContract) + '\n当前项目/会话/任务身份:' + JSON.stringify({
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract,
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question
+ '\n所属原执行与失败(核对失败时保持未知,不根据其它项目补造原因):' + JSON.stringify(inspectDiagnosticContext(this.store, session, run.record)) : '')
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ (pendingFileDrafts(session).length ? '\n当前未完成分段草稿(未创建可应用提案):' + JSON.stringify(pendingFileDrafts(session).map(row => ({ draft_id: row.id, path: row.path, next_offset: row.characters, draft_sha256: row.sha256 }))) : '')
+ (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '')
+ (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({
revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources,
@@ -392,7 +403,7 @@ export class Runtime {
const tools = availableTools.filter(tool => (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name));
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
signal.throwIfAborted();
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
@@ -486,7 +497,7 @@ export class Runtime {
run.record.outputTruncationRecoveries = (run.record.outputTruncationRecoveries ?? 0) + 1;
if (run.record.outputTruncationRecoveries <= OUTPUT_TRUNCATION_RECOVERY_LIMIT) {
this.store.finishStep(session, stepRecord);
const note = '上一次响应在达到单次输出上限前被截断(finish_reason=length),其中的工具调用整体未执行(即使某个工具参数已完整也未应用,避免落地被截断的半成品)。请把这次改动拆小:每次响应只提交一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。原目标和已读依据都保留。';
const note = OUTPUT_TRUNCATED_HINT;
// The truncated assistant turn was never appended, so the conversation
// stays valid. Feed the instruction to the model as a standalone turn
// in the provider history, and mirror it to the visible chat log.
@@ -533,6 +544,10 @@ export class Runtime {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (run.record.purpose === 'diagnostic') { session.status = 'completed'; run.stopReason = 'diagnostic_answered'; }
else if (pendingFileDrafts(session).length) {
session.status = 'paused'; run.stopReason = 'file_draft_incomplete';
this.store.message(session, 'system', '仍有未完成的分段文件草稿,片段不能作为完整交付;原片段和续接位置已保存。');
}
else if (session.status === 'completed' && taskContract(task).kind === 'file') {
const delivery = await this.fileDelivery(session);
if (!delivery.satisfied) {
@@ -851,13 +866,15 @@ export class Runtime {
}
else if (tool === 'search_files') result = searchFiles(run.project, args);
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
else if (tool === 'propose_file_chunk') result = proposeFileChunk(this.store, session, args);
else if (tool === 'discard_file_draft') result = discardFileDraft(this.store, session, args);
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
if (proofHint) result.tool_invocation_id = event.invocationId;
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : ['failed', 'error'].includes(result.status) ? 'failed' : 'completed';
if (tool === 'inspect_session') recordSessionInspection(this.store.core.task.get(run.taskId), result);
else if (['propose_file', 'propose_patch', 'verify_task_step'].includes(tool)) {
else if (['propose_file', 'propose_patch', 'propose_file_chunk', 'discard_file_draft', 'verify_task_step'].includes(tool)) {
const task=this.store.core.task.get(run.taskId);
if(result.status==='unchanged'||result.reused===true){
result.unchanged_action_count=recordUnchangedAction(task,tool,result,run.id);
+2
View File
@@ -19,6 +19,8 @@ export function modelSnapshot(config) {
return {
mode: config.mode, baseUrl: config.baseUrl, model: config.model,
contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens,
...(config.capacityMode ? { capacityMode: config.capacityMode } : {}),
...(config.historyPolicy ? { historyPolicy: config.historyPolicy } : {}),
configRevision: config.configRevision ?? 1,
...modelWaitSettings(config),
...modelIdentitySettings(config),
+14
View File
@@ -0,0 +1,14 @@
export const fileDraftToolDefinitions = [
{ type: 'function', function: { name: 'propose_file_chunk', description: '长文件不能一次完整输出时,分多轮追加完整文本片段。首次offset=0;后续必须使用回执draft_id/next_offset/draft_sha256作为draft_id/offset/expected_sha256。每段按本次输出额度拆小,最后一段complete=true才创建一个完整待审提案;此前片段不能应用或交付。不修改项目文件,不接收截断JSON。', parameters: {
type: 'object', additionalProperties: false, required: ['path', 'content', 'reason', 'offset', 'complete'], properties: {
path: { type: 'string' }, content: { type: 'string' }, reason: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, complete: { type: 'boolean' },
draft_id: { type: 'string' }, expected_sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' },
base_sha256: { type: ['string', 'null'], description: '首次核对原文件SHA;新文件为null。分段过程中基线不变。' },
},
} } },
{ type: 'function', function: { name: 'discard_file_draft', description: '明确放弃当前Task的未完成分段文件草稿。需要原draft_id/draft_sha256与原因;原片段和失败保留,不更改项目文件。', parameters: {
type: 'object', additionalProperties: false, required: ['draft_id', 'expected_sha256', 'reason'], properties: {
draft_id: { type: 'string' }, expected_sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, reason: { type: 'string' },
},
} } },
];
@@ -0,0 +1,4 @@
export const DEFAULT_MODEL_CAPACITY: Readonly<{ contextLimit: number; maxOutputTokens: number }>;
export const CAPACITY_RANGES: Readonly<Record<'contextLimit' | 'maxOutputTokens', number[]>>;
export function capacitySettings(input?: { contextLimit?: number; maxOutputTokens?: number }, previous?: { contextLimit?: number; maxOutputTokens?: number }): { contextLimit: number; maxOutputTokens: number };
export function capacityMode(value?: string): 'model' | 'manual';
+24
View File
@@ -0,0 +1,24 @@
// 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) {
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 });
return [key, value];
}));
}
export function capacityMode(value = 'manual') {
if (!['model', 'manual'].includes(value)) throw Object.assign(new Error('请选择按模型容量或手动限制。'), { status: 400 });
return value;
}
export function routedCapacity(config, members) {
const mode = capacityMode(config.capacityMode);
return Object.fromEntries(Object.keys(DEFAULT_MODEL_CAPACITY).map(key => [key,
mode === 'model' && key === 'maxOutputTokens' ? Math.max(...members.map(member => member[key]))
: Math.min(...members.map(member => member[key]), ...(mode === 'manual' ? [config[key]] : []))]));
}
+3 -2
View File
@@ -34,10 +34,11 @@ function wireBody(config, messages, tools) {
export function completionBody(config, messages, tools) {
const members = config.modelRouting?.members;
if (members?.some(member => member.protocol && member.protocol !== 'chat-completions' || member.streaming === true || member.nativeParameters || member.outputTokenField)) {
if (members?.length && (config.capacityMode === 'model' || members.some(member => member.protocol && member.protocol !== 'chat-completions' || member.streaming === true || member.nativeParameters || member.outputTokenField))) {
return { schema: 1, kind: 'model-route-plan', messages, variants: members.map(member => ({ connectionId: member.id,
protocol: modelProtocol(member.protocol), body: wireBody({ ...config, ...member, nativeParameters: member.nativeParameters ?? {}, outputTokenField: member.outputTokenField,
modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision, maxOutputTokens: config.maxOutputTokens }, messages, tools) })) };
modelConnectionId: member.id, modelCredentialRevision: member.credentialRevision,
maxOutputTokens: config.capacityMode === 'model' ? member.maxOutputTokens : config.maxOutputTokens }, messages, tools) })) };
}
return wireBody(config, messages, tools);
}
+6 -4
View File
@@ -1,6 +1,8 @@
// Task intent is retained independently of short follow-ups and system actions.
import { changeRequirement, requestedFilePaths, negatedFileAction } from './file-intent.mjs';
export const isContinuation = content => /^(?:请)?(?:继续(?:完成|执行|开发|原任务|这个任务)?|接着(?:完成|执行)?|continue(?:\s+(?:the\s+)?(?:task|work))?)[。.!!\s]*$/i.test(String(content).trim());
const skipChecks = /无需(?:任何)?(?:测试|工程检查)|不(?:需要|用|要)?(?:进行|做|运行|执行)?(?:任何)?(?:测试|工程检查)|\b(?:no (?:tests?|checks?)(?: needed|required)?|without (?:running )?(?:tests?|checks?)|(?:do not|don't|never) (?:[^.,;!?\n]{1,60}\s+(?:or|nor)\s+)?(?:run|execute) (?:tests?|checks?))\b/i;
const requireChecks = /(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i;
export function isDiagnosticQuestion(content) {
const text = String(content).trim();
@@ -19,8 +21,8 @@ export function taskContract(task, lookup = () => null) {
original = previous;
}
const goal = original.contract?.goal ?? original.goal;
const skip = /无需(?:任何)?(?:测试|工程检查)|不(?:需要|用|要)?(?:进行|做|运行|执行)?(?:任何)?(?:测试|工程检查)|\b(?:no (?:tests?|checks?)(?: needed|required)?|without (?:running )?(?:tests?|checks?)|(?:do not|don't|never) (?:run|execute) (?:tests?|checks?))\b/i.test(goal);
const required = !skip && /(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(goal);
const skip = skipChecks.test(goal);
const required = !skip && requireChecks.test(goal);
const file = hasFileDeliveryRequest(goal);
return { schemaVersion: 1, goal, kind: file ? 'file' : 'general', checks: skip ? 'skip' : required ? 'required' : 'unspecified',
...(original.id !== task.id ? { inheritedFromTaskId: original.id } : {}) };
@@ -41,8 +43,8 @@ export function updateTaskContract(task, instruction) {
const current = taskContract(task);
if (hasFileDeliveryRequest(instruction)) current.kind = 'file';
// Only an explicit new user instruction changes the check policy.
if (/无需(?:任何)?测试|不(?:需要|用|要)(?:进行|做|运行)?测试|\b(?:no tests?|without (?:running )?tests?)\b/i.test(instruction)) current.checks = 'skip';
else if (/(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(instruction)) current.checks = 'required';
if (skipChecks.test(instruction)) current.checks = 'skip';
else if (requireChecks.test(instruction)) current.checks = 'required';
task.contract = current;
task.constraints = (task.constraints ?? []).filter(value => value !== '用户明确要求无需测试;不得自动扩大为工程测试任务。');
if (current.checks === 'skip') task.constraints.push('用户明确要求无需测试;不得自动扩大为工程测试任务。');
+2 -2
View File
@@ -3,7 +3,7 @@ import { isId, accountedTokens, emptyUsage } from './execution.mjs';
import { selectedEngineInput } from './engine-execution.mjs';
export const WORKER_TOOLS = new Set(['diagnose_environment','plan_environment','prepare_environment','inspect_session', 'inspect_project', 'index_project', 'query_code', 'read_artifact',
'list_files', 'read_file', 'search_files', 'propose_file', 'propose_patch', 'prepare_change_set', 'plan_checks', 'run_checks']);
'list_files', 'read_file', 'search_files', 'propose_file', 'propose_patch', 'propose_file_chunk', 'discard_file_draft', 'prepare_change_set', 'plan_checks', 'run_checks']);
export const COLLABORATION_ACTIVE = new Set(['preparing', 'starting', 'running', 'stopping', 'collecting', 'merge_preparing', 'reconciling']);
export const COLLABORATION_CLOSED = new Set(['completed', 'discarded', 'resolved_external']);
export const workerConflict = message => Object.assign(new Error(message), { status: 409 });
@@ -109,7 +109,7 @@ export function assertWorkerTool(store, session, tool, args) {
const worker = workerForSession(store, session);
if (!worker) return;
if (!WORKER_TOOLS.has(tool)) throw workerConflict('受限子任务不开放这个工具:' + tool);
if (tool === 'propose_file' || tool === 'propose_patch') assertWorkerWriteScope(store, session, args.path);
if (tool === 'propose_file' || tool === 'propose_patch' || tool === 'propose_file_chunk') assertWorkerWriteScope(store, session, args.path);
}
export function assertWorkersResolved(store, projectId, { recoveryTaskId = null } = {}) {
const group = [...(store.core.collaboration?.values() ?? [])].find(value => value.requiresVerification