feat(vision): bind task screenshots, route vision and resume budget pauses

This commit is contained in:
Agent Workbench Dev
2026-11-01 00:48:38 +08:00
parent 0d1ab743f1
commit 96a7ed19c7
79 changed files with 1721 additions and 36 deletions
+8 -4
View File
@@ -17,6 +17,8 @@ import { WorkerPanel } from './WorkerPanel';
import { DesktopPanel } from './DesktopPanel';
import { CompanionPanel } from './CompanionPanel';
import { desktop } from './desktop';
import { AttachmentComposer,InputImage } from './InputAttachments';
import { BudgetPausePanel } from './BudgetPausePanel';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const activeMcpStates = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
@@ -53,6 +55,7 @@ export default function App() {
const [draft, setDraft] = useState('');
const [composer, setComposer] = useState('');
const [sending, setSending] = useState(false);
const [imageSelection,setImageSelection]=useState<{sessionId:string;ids:string[]}>({sessionId:'',ids:[]});
const [creatingSession, setCreatingSession] = useState(false);
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task' | 'index'>('file');
const [changeId, setChangeId] = useState('');
@@ -249,9 +252,9 @@ export default function App() {
try {
const target = session || await newSession();
if (!target) return;
acceptSession(await api<Session>('/sessions/' + target.id + '/messages', { content }));
acceptSession(await api<Session>('/sessions/' + target.id + '/messages', { content,attachmentIds:imageSelection.sessionId===target.id?imageSelection.ids:[] }));
if (selectedSessionRef.current === target.id) {
setComposer(previous => previous.trim() === content ? '' : previous); composerRef.current?.focus();
setComposer(previous => previous.trim() === content ? '' : previous); setImageSelection({sessionId:target.id,ids:[]}); composerRef.current?.focus();
}
} catch (error) { failure(error); }
finally { setSending(false); }
@@ -557,9 +560,10 @@ export default function App() {
{session?.recoveryNotice && <div className="recovery-note"><ShieldCheck size={16} /><div><strong>已恢复会话记录</strong><p>{session.recoveryNotice}</p></div></div>}
{entries.map(entry => 'message' in entry && entry.message ? <div key={entry.id} className={'message message-' + entry.message.role}><span className="message-avatar">{entry.message.role === 'user' ? '你' : entry.message.role === 'assistant' ? 'AW' : '·'}</span><div className="message-body"><div className="message-label">{entry.message.role === 'user' ? '你的任务' : entry.message.role === 'assistant' ? session?.executionMode === 'demo' ? '演示执行器' : '编程助手' : '工作台'}<time>{new Date(entry.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></div><div className="message-text">{entry.message.role === 'system' && failureForMessage(entry.message)
? <FailureCard failure={failureForMessage(entry.message)!} onDiagnose={() => openDiagnostics()} onRetry={session?.status === 'failed' && session?.failure?.messageId === entry.message.id ? () => resumeSession() : undefined} busy={resuming || isRunning} />
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div></div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <><ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /><ModelStreamPreview event={entry.event} /></> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div>{entry.message.attachmentIds?.map(id=>{const image=session?.inputAttachments?.find(value=>value.id===id);return image&&session?<InputImage key={id} sessionId={session.id} image={image} onError={failure}/>:null;})}</div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <><ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /><ModelStreamPreview event={entry.event} /></> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
</div>}
{session&&<BudgetPausePanel key={session.id+session.execution?.run?.id} session={session} config={config} onSession={acceptSession}/>}
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
{approval.checkScripts?.filter(check => check.python).map(check => <p className="approval-shell" key={check.name}>Python {check.python!.runtime.version || '执行时核对版本'} · {check.python!.runtime.logicalExecutable || check.python!.runtime.executable || '解释器缺失'}</p>)}
<div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">{approval.browserPlanId ? '按封存步骤操作当前构建,保存页面原结果。' : '确认后以你的系统权限执行。'}</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
@@ -567,7 +571,7 @@ export default function App() {
{canContinueReview && <button type="button" aria-label="继续检查与交付" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续检查与交付</strong><small>改动已应用,沿用原任务继续实际测试和修复。</small></span><ArrowRight size={17} /></button>}
<div ref={chatEnd} />
</section>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : modelSelection.type !== 'legacy' ? modelSelection.name : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><AttachmentComposer session={session} selectedIds={imageSelection.sessionId===session?.id?imageSelection.ids:[]} onSelection={(id,ids)=>setImageSelection({sessionId:id,ids})} onEnsureSession={newSession} onSession={acceptSession} onError={failure} disabled={isRunning||sending||creatingSession||!ready||restrictedWorker} routeName={modelSelection.type==='legacy'?'原模型连接':modelSelection.name} onModels={()=>setModelCenterOpen(true)}/><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : modelSelection.type !== 'legacy' ? modelSelection.name : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
+27
View File
@@ -0,0 +1,27 @@
import { useState } from 'react';
import { RotateCw } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { Config,Session } from './types';
import './input-attachments.css';
type Fields={contextLimit:number;maxOutputTokens:number;maxRunTokens:number;maxTaskTokens:number;maxSteps:number;maxRunDurationMs:number};
type Preview={id:string;sha256:string;taskId:string;runId:string;config:Fields&{model:string};eligibleConnections:{id:string;name:string;model:string}[];budget:{inputBudget:number;contextLimit:number};completedToolIds:string[];unknownToolIds:string[];attachmentIds:string[];note:string};
const reasons:Record<string,string>={context_limit:'上下文窗口不足',token_limit:'本次运行预算不足',task_token_limit:'任务累计预算不足',time_limit:'本次运行时间已用完'};
const labels:Record<string,string>={transportAndImageFramingTokens:'请求格式与图片说明',goalAndContextTextTokens:'目标、全部要求及工程上下文',toolDefinitionTokens:'工具定义',historyAndEvidenceTokens:'必需历史及实际依据',imageReservationTokens:'图像本地预留'};
export function BudgetPausePanel({session,config,onSession}:{session:Session;config:Config;onSession:(value:Session)=>void}){
const [open,setOpen]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState(''),[plan,setPlan]=useState<Preview|null>(null);
const [fields,setFields]=useState<Fields>({contextLimit:session.execution?.run?.model.contextLimit??config.contextLimit,maxOutputTokens:session.execution?.run?.model.maxOutputTokens??config.maxOutputTokens,
maxRunTokens:config.maxRunTokens,maxTaskTokens:session.execution?.task?.budget.maxTokens??config.maxTaskTokens,maxSteps:config.maxSteps,maxRunDurationMs:config.maxRunDurationMs});
const [selection,setSelection]=useState(''),[options,setOptions]=useState<{value:string;name:string}[]>([]);
const run=session.execution?.run,pause=run?.budgetPause,reason=pause?.reason??run?.stopReason??'';
if(!['paused','failed'].includes(session.status)||!reasons[reason])return null;
async function start(){setOpen(true);setError('');setPlan(null);try{const center=await api<{selected:{type:string;id:string};connections:{id:string;name:string;contextLimit:number}[];pools:{id:string;name:string}[]}>('/model-center');setSelection(center.selected.type+':'+center.selected.id);setOptions([...center.connections.map(row=>({value:(row.id==='legacy-default'?'legacy':'connection')+':'+row.id,name:row.name+' · '+row.contextLimit.toLocaleString()+' 上下文'})),...center.pools.map(row=>({value:'pool:'+row.id,name:row.name+' · 按成员最小容量'}))]);}catch(cause){setError((cause as Error).message);}}
async function preview(){setBusy(true);setError('');setPlan(null);try{const [type,id]=selection.split(':');const value=await api<Preview>('/sessions/'+session.id+'/resume-preview',{...fields,...(selection?{selection:{type,id}}:{})});setPlan(value);onSession(await api<Session>('/sessions/'+session.id));}catch(cause){setError((cause as Error).message);}finally{setBusy(false);}}
async function confirm(){if(!plan)return;setBusy(true);setError('');try{onSession(await api<Session>('/sessions/'+session.id+'/resume-budget',{planId:plan.id,sha256:plan.sha256}));setOpen(false);}catch(cause){setError((cause as Error).message);}finally{setBusy(false);}}
return <aside className="budget-pause" aria-label="任务预算诊断"><h3>{reasons[reason]}</h3>{pause?.requiredInputTokens!==undefined?<><p>完整要求与必需输入估算 <strong>{pause.requiredInputTokens.toLocaleString()}</strong> tokens;当前可用输入 <strong>{pause.inputBudget?.toLocaleString()}</strong>。请求已暂停,原任务和工具结果保留。</p><dl className="budget-facts">{Object.entries(pause.breakdown??{}).map(([key,value])=><div key={key} style={{display:'contents'}}><dt>{labels[key]??key}</dt><dd>{value.toLocaleString()}</dd></div>)}<dt>所选上下文窗口</dt><dd>{pause.contextLimit?.toLocaleString()}</dd><dt>响应预留 / 安全余量</dt><dd>{pause.outputReservation?.toLocaleString()} / {pause.safetyTokens?.toLocaleString()}</dd><dt>运行 / 任务剩余</dt><dd>{pause.runRemainingTokens?.toLocaleString()??'不限'} / {pause.taskRemainingTokens?.toLocaleString()??'不限'}</dd></dl></>:<p>原 Task 已保存。可核对剩余预算和模型容量,再准备同一任务的新 Run;旧记录没有的预算分解不补造。</p>}
{!!pause?.imageReservationTokens&&<p>图像使用单独的本地预留,属于容量估算;实际计费与服务报告用量分列。</p>}<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>}
</aside>;
}
+35
View File
@@ -0,0 +1,35 @@
import { useEffect,useRef,useState } from 'react';
import { ImagePlus,Download,X,LoaderCircle } from 'lucide-react';
import { api,downloadBlob,inputImageBlob } from './api';
import { Modal } from './components';
import type { InputAttachment,Session } from './types';
import './input-attachments.css';
export function InputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(error:unknown)=>void}){
const [url,setUrl]=useState(''),[open,setOpen]=useState(false),[error,setError]=useState('');
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void inputImageBlob(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive)setError(cause.message);});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
return <div className="input-receipt"><button type="button" className="input-thumbnail" aria-label={'查看截图 '+image.name} disabled={!url} onClick={()=>setOpen(true)}>{url?<img src={url} alt={image.name} width={72} height={48}/>:<span>{error?'读取失败':'核对中'}</span>}</button><div><strong>{image.name}</strong><span>发送副本 {image.sentWidth} × {image.sentHeight} · {Math.ceil(image.sentBytes/1024)} KB</span><small>{error|| (url?'SHA-256 已核对':'核对原字节…')}</small></div>
{open&&<Modal title="任务截图" description={image.name+' · 原图 '+image.width+' × '+image.height} onClose={()=>setOpen(false)} wide><img className="input-preview" src={url} alt={image.name}/><p className="input-sha">原图 SHA-256 {image.sha256}<br/>发送副本 SHA-256 {image.sentSha256}</p><p>发送副本已去除元数据并归正方向,最长边不超过1024像素、768KB。细小文字请先裁剪;原图完整保留。</p><div className="modal-actions"><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image,true).then(blob=>downloadBlob(blob,image.name)).catch(onError)}><Download size={14}/>下载原图</button><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image).then(blob=>downloadBlob(blob,'sent-'+image.id+'.png')).catch(onError)}>下载发送副本</button></div></Modal>}
</div>;
}
export function AttachmentComposer({session,selectedIds,onSelection,onEnsureSession,onSession,onError,disabled,routeName,onModels}:{session:Session|null;selectedIds:string[];onSelection:(id:string,ids:string[])=>void;onEnsureSession:()=>Promise<Session|null>;onSession:(value:Session)=>void;onError:(error:unknown)=>void;disabled:boolean;routeName:string;onModels:()=>void}){
const input=useRef<HTMLInputElement>(null),[busy,setBusy]=useState(false);
const drafts=session?.inputAttachments?.filter(value=>value.status==='draft')??[];
async function upload(file:File){
setBusy(true);
try{
if(file.size>2*1024*1024)throw new Error('单张截图最多2MB,请裁剪后添加。');
if(!['image/png','image/jpeg'].includes(file.type))throw new Error('请选择静态PNG或JPEG截图。');
const target=session??await onEnsureSession();if(!target)return;
const bytes=new Uint8Array(await file.arrayBuffer());let binary='';for(let p=0;p<bytes.length;p+=8192)binary+=String.fromCharCode(...bytes.subarray(p,p+8192));
const row=await api<InputAttachment>('/sessions/'+target.id+'/input-attachments',{name:file.name,mediaType:file.type,base64:btoa(binary)});
onSession(await api<Session>('/sessions/'+target.id));onSelection(target.id,[row.id]);
}catch(error){onError(error);}finally{setBusy(false);if(input.current)input.current.value='';}
}
async function remove(id:string){if(!session)return;setBusy(true);try{await api('/sessions/'+session.id+'/input-attachments/'+id,{},'DELETE');onSession(await api<Session>('/sessions/'+session.id));if(selectedIds.includes(id))onSelection(session.id,[]);}catch(error){onError(error);}finally{setBusy(false);}}
return <div className="input-composer"><div className="input-composer-tools"><button type="button" className="input-add" disabled={disabled||busy} onClick={()=>input.current?.click()}>{busy?<LoaderCircle size={15} className="spin"/>:<ImagePlus size={15}/>}添加截图</button><span>每任务1张 · PNG/JPEG · 原图≤2MB</span><input ref={input} type="file" accept="image/png,image/jpeg" aria-label="选择工程截图" hidden onChange={event=>{const file=event.target.files?.[0];if(file)void upload(file);}}/></div>
{!!drafts.length&&<div className="input-drafts">{drafts.map(image=><div className={'input-draft '+(selectedIds.includes(image.id)?'selected':'')} key={image.id}><label><input type="checkbox" checked={selectedIds.includes(image.id)} disabled={disabled||busy} onChange={event=>onSelection(session!.id,event.target.checked?[image.id]:[])}/><span>随任务发送</span></label><InputImage sessionId={session!.id} image={image} onError={onError}/><button type="button" className="input-remove" aria-label={'移除截图 '+image.name} disabled={disabled||busy} onClick={()=>void remove(image.id)}><X size={15}/></button></div>)}</div>}
{!!selectedIds.length&&<p className="input-route">将随文字发送至 <strong>{routeName}</strong>,池仅使用声明或检测支持视觉的成员。<button type="button" onClick={onModels}>核对模型能力</button><span>发送副本≤1024像素/768KB;图片预留单独估算,实际用量以服务返回为准。</span></p>}
</div>;
}
+2 -1
View File
@@ -77,7 +77,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft({ ...initial, ...value, streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option></select></label>
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
@@ -87,6 +87,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label>视觉能力<select aria-label="视觉能力" value={draft.capabilityDeclarations.vision} onChange={event=>setDraft({...draft,capabilityDeclarations:{...draft.capabilityDeclarations,vision:event.target.value}})}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<label>实际模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
+10 -2
View File
@@ -1,8 +1,8 @@
let accessToken = '';
export function setToken(token: string) { accessToken = token; }
export async function api<T>(path: string, input?: unknown): Promise<T> {
export async function api<T>(path: string, input?: unknown,method?:string): Promise<T> {
const response = await fetch('/api' + path, {
method: input === undefined ? 'GET' : 'POST',
method: method??(input === undefined ? 'GET' : 'POST'),
headers: { 'Content-Type': 'application/json', ...(accessToken ? { 'X-Workbench-Token': accessToken } : {}) },
...(input === undefined ? {} : { body: JSON.stringify(input) }),
});
@@ -56,3 +56,11 @@ export async function browserImageBlob(sessionId: string, jobId: string, artifac
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '页面截图读取失败。'); }
return response.blob();
}
export async function inputImageBlob(sessionId:string,image:import('./types').InputAttachment,original=false):Promise<Blob>{
const response=await fetch('/api/sessions/'+sessionId+'/input-attachments/'+image.id+'/'+(original?'original':'image'),{headers:{'X-Workbench-Token':accessToken},cache:'no-store'});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new Error(value.error||'截图读取失败,请刷新核对。');}
const bytes=await response.arrayBuffer(),digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
if(digest!==(original?image.sha256:image.sentSha256))throw new Error('截图SHA-256核对失败,未展示或下载。');
return new Blob([bytes],{type:original?image.mediaType:'image/png'});
}
+2
View File
@@ -9,6 +9,8 @@ export interface CompanionStatus {
export interface MobileBrief { id: string; projectId: string; taskId?: string; runId?: string; title: string; status: string; revision: number; eventSeq: number; updatedAt: string }
export interface MobileUsage { totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface MobileTask extends MobileBrief {
inputAttachments?: import('./types').InputAttachment[];
budgetPause?: import('./types').BudgetPause|null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
+3
View File
@@ -0,0 +1,3 @@
.input-composer{border-bottom:1px solid var(--line,#dce7e2);padding:8px 12px}.input-composer-tools{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.input-composer-tools>span{font-size:11px;color:var(--muted,#52665f)}.input-add,.input-remove,.input-route button{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;color:inherit;padding:6px;cursor:pointer}.input-add:hover,.input-remove:hover{background:#edf3f1;border-radius:4px}.input-drafts{display:grid;gap:8px;margin-top:8px;max-height:220px;overflow:auto}.input-draft{display:flex;gap:10px;align-items:center;padding:8px;border:1px solid var(--line,#dce7e2);border-radius:5px;min-width:0}.input-draft.selected{border-color:var(--teal,#154b4a)}.input-draft>label{display:flex;gap:6px;font-size:11px;align-items:center;white-space:nowrap}.input-receipt{display:flex;gap:10px;align-items:center;min-width:0;margin:8px 0}.input-receipt>div{min-width:0;display:grid;gap:3px}.input-receipt strong{font-size:12px;overflow-wrap:anywhere}.input-receipt span,.input-receipt small{font-size:11px;color:var(--muted,#52665f)}.input-thumbnail{flex-shrink:0;border:1px solid var(--line,#dce7e2);background:transparent;cursor:pointer;padding:2px;width:78px;height:54px;border-radius:3px}.input-thumbnail img{object-fit:contain;display:block}.input-route{font-size:11px;line-height:1.7;margin:8px 0 2px;overflow-wrap:anywhere}.input-route button{color:var(--blue,#4664d9);text-decoration:underline}.input-route>span{display:block;color:var(--muted,#52665f)}.input-preview{display:block;max-width:100%;max-height:60vh;object-fit:contain;margin:auto}.input-sha{font-family:var(--font-mono,monospace);font-size:11px;overflow-wrap:anywhere;line-height:1.8}.input-remove{margin-left:auto}.budget-pause{margin:16px 24px;border-left:3px solid #cba760;padding:12px 16px;background:var(--paper,#fcfdfc);font-size:12px}.budget-pause h3{font-size:14px;margin:0 0 8px}.budget-pause p{line-height:1.7;overflow-wrap:anywhere}.budget-facts{display:grid;grid-template-columns:1fr auto;gap:6px 18px;margin:12px 0}.budget-facts dt{color:var(--muted,#52665f)}.budget-facts dd{margin:0;font-variant-numeric:tabular-nums}.budget-resume-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px}.budget-resume-fields label{display:grid;gap:6px;font-size:12px}.budget-resume-fields input,.budget-resume-fields select{width:100%;min-width:0;padding:9px;border:1px solid var(--line,#dce7e2);border-radius:4px;background:var(--paper,#fcfdfc);color:inherit}.budget-preview{border-top:1px solid var(--line,#dce7e2);padding-top:12px;margin-top:16px}.budget-error{color:#87500b;line-height:1.7}
@media(max-width:620px){.input-draft{flex-wrap:wrap;gap:4px 10px}.input-draft>.input-receipt{width:calc(100% - 28px)}.input-draft>label{width:100%}.input-composer{padding:8px}.budget-pause{margin:12px}.budget-resume-fields{grid-template-columns:1fr}.budget-pause .button{width:100%;justify-content:center}}
@media(max-width:620px){.input-remove{min-width:44px;min-height:44px;justify-content:center}.input-draft>label{min-height:44px}.input-add{min-height:40px}}
+3
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, RefreshCw, ShieldCheck, Square, Terminal, Wifi, WifiOff, X } from 'lucide-react';
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
import { MobileInputImage } from './MobileInputImage';
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
@@ -116,6 +117,8 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
{me && selected && <main className="mobile-task-detail"><button className="mobile-back" onClick={() => { chosen.current = ''; setSelected(''); setTask(null); setDocument(null); }}><ArrowLeft size={18} />项目任务</button>{!selectedTask ? <div className="mobile-empty" role="status">正在读取原任务…</div> : <>
<div className="mobile-task-title"><span className="mobile-eyebrow">{projectName(selectedTask.projectId)}</span><h1>{selectedTask.title}</h1><div><span className={'mobile-state state-' + selectedTask.status}>{stateLabel(selectedTask.status)}</span><span>修订 {selectedTask.revision}</span></div><details className="mobile-goal"><summary>完整任务目标</summary><p>{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}</p></details><details><summary>原任务与运行</summary><code>Task {selectedTask.taskId ?? '未开始'}<br />Run {selectedTask.runId ?? '未开始'}</code></details></div>
{receipt && <p className="mobile-receipt" role="status">{receipt}</p>}
{selectedTask.inputAttachments?.map(image=><MobileInputImage key={image.id} sessionId={selectedTask.id} image={image} onError={cause=>{if(cause instanceof MobileError&&[401,403].includes(cause.status))revoke(cause.message);else setError(cause instanceof Error?cause.message:'截图读取失败。');}}/>)}
{selectedTask.budgetPause&&<aside className="mobile-unknown"><strong>原任务因预算暂停</strong><p>必需输入 {selectedTask.budgetPause.requiredInputTokens?.toLocaleString()??'旧记录未分解'};可用输入 {selectedTask.budgetPause.inputBudget?.toLocaleString()??'未记录'} tokens。请在电脑核对预算并预览续接,原工具结果保留。</p></aside>}
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
+21
View File
@@ -0,0 +1,21 @@
import { useEffect,useState } from 'react';
import type { InputAttachment } from '../types';
import { MobileError } from './api';
async function readImage(sessionId:string,image:InputAttachment,original=false){
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);
try{
const response=await fetch('/mobile-api/sessions/'+sessionId+'/input-attachments/'+image.id+'/'+(original?'original':'image'),{credentials:'same-origin',cache:'no-store',signal:controller.signal});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new MobileError(value.error||'截图读取失败。',response.status);}
const bytes=await response.arrayBuffer();if(bytes.byteLength>(original?2*1024*1024:768*1024))throw new MobileError('截图超出允许大小。');
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
if(digest!==(original?image.sha256:image.sentSha256))throw new MobileError('截图SHA-256核对失败,请在电脑核对。');
return new Blob([bytes],{type:original?image.mediaType:'image/png'});
}finally{clearTimeout(timer);}
}
export function MobileInputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(cause:unknown)=>void}){
const [url,setUrl]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void readImage(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive){setError(cause.message);onError(cause);}});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
async function download(){setBusy(true);try{const blob=await readImage(sessionId,image,true),href=URL.createObjectURL(blob),link=document.createElement('a');link.href=href;link.download=image.name;link.click();setTimeout(()=>URL.revokeObjectURL(href),1000);}catch(cause){onError(cause);}finally{setBusy(false);}}
return <section className="mobile-input-image"><h2>本任务截图</h2><strong>{image.name}</strong><p>{url?'SHA-256 已核对':error||'正在核对截图…'} · 发送副本 {image.sentWidth} × {image.sentHeight}</p>{url&&<details><summary>查看发送给模型的截图</summary><img src={url} alt={image.name}/><code>{image.sentSha256}</code></details>}<button disabled={busy||!url} onClick={()=>void download()}>核对并下载原图</button><p className="mobile-muted">原图 {image.width} × {image.height}。手机按现有项目观察权限读取;添加截图与预算续接在电脑操作。</p></section>;
}
+1
View File
@@ -6,3 +6,4 @@
.mobile-stream strong, .mobile-stream span { display: block; }
.mobile-stream span { color: #526658; font-size: 11px; margin-top: 6px; }
.mobile-stream pre { max-height: 240px; overflow-y: auto; margin-bottom: 0; }
.mobile-input-image{padding:18px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin-top:18px}.mobile-input-image>strong{font-size:13px;overflow-wrap:anywhere}.mobile-input-image p{font-size:12px;color:var(--muted)}.mobile-input-image img{display:block;width:100%;max-height:60dvh;object-fit:contain}.mobile-input-image code{display:block;overflow-wrap:anywhere;font-size:10px;margin:10px 0}.mobile-input-image>button{margin-top:10px}.mobile-input-image details{font-size:13px}
+5 -1
View File
@@ -16,7 +16,10 @@ export interface WorkspaceRecord {
observation?: { rootState: string; branchHead: string | null; workspaceHead: string | null; workspaceBranch: string | null; registered: boolean; clean: boolean; contentsVerified: boolean; sourcePreserved: boolean; ready: boolean; fingerprint: string; observedAt: string; problems: string[] } | null;
}
export interface SessionBrief { id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; changeCount: number }
export interface Message { id: string; role: string; content: string; createdAt: string }
export interface Message { id: string; role: string; content: string; createdAt: string; attachmentIds?: string[] }
export interface InputAttachment { id:string;name:string;status:string;mediaType:string;taskId:string|null;runId:string|null;sha256:string;bytes:number;sentSha256:string;sentBytes:number;width:number;height:number;sentWidth:number;sentHeight:number;orientation:number }
export interface BudgetPause { reason:string;requiredInputTokens?:number;contextLimit?:number;inputBudget?:number;outputReservation?:number;safetyTokens?:number;runRemainingTokens?:number|null;taskRemainingTokens?:number|null;imageReservationTokens?:number;breakdown?:Record<string,number> }
export interface Run { budgetPause?:BudgetPause }
export interface ToolEvent {
id: string; kind: string; label: string; phase: string; createdAt: string; tool?: string;
input?: Record<string, unknown>; output?: string; durationMs?: number; startedAt?: string; finishedAt?: string;
@@ -42,6 +45,7 @@ export interface Session {
archived: boolean; recoveryNotice?: string | null; executionMode?: string;
failure?: RuntimeFailure | null; lastFailure?: RuntimeFailure | null;
execution?: ExecutionSnapshot;
inputAttachments?: InputAttachment[];
}
export interface RuntimeFailure {
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
+3
View File
@@ -9,6 +9,9 @@ export function mobileSession(store, runtime, session, redact = String) {
const checks = [...store.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
const result = {
...sessionBrief(session, redact),
inputAttachments:[...store.core.input_attachment.values()].filter(row=>row.sessionId===session.id&&row.taskId===session.taskId&&row.status==='attached')
.map(row=>pick(row,['id','name','status','mediaType','taskId','runId','sha256','bytes','sentSha256','sentBytes','width','height','sentWidth','sentHeight','orientation'])),
budgetPause:run?.budgetPause?pick(run.budgetPause,['reason','requiredInputTokens','contextLimit','inputBudget','outputReservation','safetyTokens','imageReservationTokens','breakdown']):null,
task: task ? { ...pick(task, ['id', 'status', 'budget', 'usage', 'verification']), goal: String(task.goal).slice(0, 12000) } : null,
run: run ? pick(run, ['id', 'taskId', 'status', 'budget', 'usage', 'steps', 'toolCalls', 'stopReason', 'startedAt', 'finishedAt']) : null,
progress: { total: tools.length, completed: tools.filter(value => value.state === 'completed').length,
+66
View File
@@ -0,0 +1,66 @@
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';
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]};
export class BudgetResume {
constructor(store,provider,runtime){this.store=store;this.provider=provider;this.runtime=runtime;}
current(session){
const task=this.store.core.task.get(session.taskId),run=this.store.core.run.get(session.runId);
if(!task||!run||run.taskId!==task.id||!['paused','failed'].includes(session.status)||this.runtime.projectHasActivity(session.projectId))throw fail('请等待原任务暂停后再准备续接。');
if([...this.store.core.worker.values()].some(row=>row.sessionId===session.id))throw fail('受限子任务请在父协作中处理预算。');
return {task,run};
}
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};
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];
}
if(config.maxTaskTokens<task.budget.maxTokens||config.maxTaskTokens<=accountedTokens(task.usage))throw fail('任务累计预算只能保留或明确增加,并须高于已记账用量。',400);
const hub=this.provider.modelHub(this.store),selection=input.selection??hub.state.selected;
if(!selection||Object.keys(selection).some(key=>!['type','id'].includes(key))||!['connection','pool','legacy'].includes(selection.type)||typeof selection.id!=='string')throw fail('请选择原连接或模型中心已有连接/池。',400);
if(selection.type!=='legacy')config.mode='compatible';
const prepared=hub.prepare(config,selection);this.provider.validate(prepared);
if(prepared.contextLimit!==config.contextLimit||prepared.maxOutputTokens!==config.maxOutputTokens)throw fail('所选连接或池的容量小于填写值,请按实际最小容量修改预览。',400);
const images=this.runtime.inputAttachments().images(session,task),requirements=['text','tools',...(images.length?['vision']:[])];
if(images.length&&!prepared.modelRouting)throw fail('原任务有截图,请选模型中心支持视觉的连接。',400);
const members=prepared.modelRouting?.members??[],eligible=members.filter(member=>!capabilityRejections(member,[...requirements,...(member.streaming?['streaming']:[])],member.credentialRevision).length);
if(members.length&&!eligible.length)throw fail('所选连接没有满足原任务所需能力的成员。',400);
const budget=budgetFor(prepared,{budget:{maxTokens:prepared.maxRunTokens},usage:emptyUsage()},{...task,budget:{maxTokens:prepared.maxTaskTokens}});
if(budget.inputBudget<=0||run.budgetPause?.requiredInputTokens>budget.inputBudget)throw fail('预览预算仍容不下原暂停时的必需输入和响应预留,请调整后再准备。',400);
const record={schema:1,id:randomUUID(),sessionId:session.id,projectId:session.projectId,taskId:task.id,runId:run.id,status:'prepared',createdAt:new Date().toISOString(),
expiresAt:new Date(Date.now()+15*60000).toISOString(),expectedSessionRevision:session.revision+1,configRevision:this.store.config.configRevision,
registryRevision:hub.state.revision,selection:structuredClone(selection),config:structuredClone(prepared),budget,
eligibleConnections:eligible.map(member=>({id:member.id,name:member.name,model:member.model,protocol:member.protocol})),
before:{model:structuredClone(run.model),runBudget:structuredClone(run.budget),taskBudget:structuredClone(task.budget),taskUsage:structuredClone(task.usage)},
attachmentIds:[...(task.attachmentIds??[])],completedToolIds:[...this.store.core.tool.values()].filter(row=>row.taskId===task.id&&row.state==='completed').map(row=>row.id),
unknownToolIds:[...this.store.core.tool.values()].filter(row=>row.taskId===task.id&&row.requiresVerification).map(row=>row.id),
historySha256:hash(session.providerMessages),previousPause:structuredClone(run.budgetPause??null),
note:'仅作用于原Task的新Run;保留全部用户要求、附件及实际工具结果。不会改全局连接、重放完成工具或自动批准命令。'};
const artifact=this.store.artifactStore.write(session,run,JSON.stringify(record),{kind:'budget-resume-plan',mediaType:'application/json'});
this.store.core.artifact.set(artifact.id,artifact);record.artifactId=artifact.id;record.sha256=artifact.sha256;
this.store.putRecord('resume_plan',session,record,'budget.resume_prepared');return structuredClone(record);
}
verify(session,input){
this.current(session);
if(!input||Object.keys(input).some(key=>!['planId','sha256'].includes(key)))throw fail('确认需要原续接预览身份。',400);
const plan=this.store.owned('resume_plan',input.planId,session.id),artifact=this.store.owned('artifact',plan.artifactId,session.id);
const frozen=JSON.parse(this.store.artifactStore.read(artifact)),{artifactId,sha256,...identity}=plan;
if(plan.status!=='prepared'||input.sha256!==sha256||artifact.sha256!==sha256||hash(identity)!==hash(frozen)
||session.taskId!==plan.taskId||session.runId!==plan.runId||session.revision!==plan.expectedSessionRevision||Date.parse(plan.expiresAt)<Date.now()
||plan.configRevision!==this.store.config.configRevision||this.provider.modelHub(this.store).state.revision!==plan.registryRevision||hash(session.providerMessages)!==plan.historySha256)throw fail('原任务、连接或预算预览已变化,请重新准备后确认。');
for(const member of plan.config.modelRouting?.members??[]){
const current=this.provider.hub.connection(member.id);
if(current.revision!==member.revision||(this.provider.hub.credential(current)?.revision??0)!==member.credentialRevision)throw fail('模型连接身份已变化,请重新预览。');
}
this.runtime.inputAttachments().images(session,this.store.core.task.get(plan.taskId));
return plan;
}
}
+141
View File
@@ -0,0 +1,141 @@
import { randomUUID } from 'node:crypto';
import { PNG } from 'pngjs';
import jpeg from 'jpeg-js';
export const IMAGE_LIMITS = { bytes: 2 * 1024 * 1024, pixels: 16 * 1024 * 1024, dimension: 8192, sentDimension: 1024, sentBytes: 768 * 1024, perTask: 1, drafts: 8 };
const reject = (message, status = 400) => Object.assign(new Error(message), { status });
function dimensions(bytes, type) {
if (type === 'image/png' && bytes.length >= 33 && bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))
&& bytes.readUInt32BE(8) === 13 && bytes.toString('ascii', 12, 16) === 'IHDR') {
let ended = false;
for (let offset = 8; offset < bytes.length;) {
if (offset + 12 > bytes.length) throw reject('PNG区块不完整。');
const length = bytes.readUInt32BE(offset), name = bytes.toString('ascii', offset + 4, offset + 8);
if (offset + length + 12 > bytes.length || ['acTL','fcTL','fdAT'].includes(name)) throw reject('只支持完整的静态PNG图片。');
offset += length + 12;
if (name === 'IEND') { ended = length === 0 && offset === bytes.length; break; }
}
if (!ended) throw reject('PNG结束区块或尾部内容无效。');
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), orientation: 1 };
}
if (type === 'image/jpeg' && bytes[0] === 255 && bytes[1] === 216 && bytes.at(-2) === 255 && bytes.at(-1) === 217) {
let size, orientation = 1;
for (let p = 2; p < bytes.length;) {
if (bytes[p++] !== 255) break;
while (bytes[p] === 255) p++;
const marker = bytes[p++];
if (marker === 217 && p === bytes.length && size) return { ...size, orientation };
if (p + 2 > bytes.length || marker === 216 || marker === 217) break;
const length = bytes.readUInt16BE(p);
if (length < 2 || p + length > bytes.length) break;
if ([192,193,194].includes(marker) && length >= 8) size = { width: bytes.readUInt16BE(p + 5), height: bytes.readUInt16BE(p + 3) };
if (marker === 225 && bytes.toString('ascii',p+2,p+8) === 'Exif\0\0') orientation = exifOrientation(bytes.subarray(p+8,p+length));
p += length;
if (marker === 218) {
// Scan data may contain escaped FF bytes and restart markers; the next
// real marker must still be parsed, including progressive scan headers.
while (p < bytes.length) {
if (bytes[p++] !== 255) continue;
const start = p - 1;
while (bytes[p] === 255) p++;
if (bytes[p] === 0 || bytes[p] >= 208 && bytes[p] <= 215) { p++; continue; }
p = start; break;
}
}
}
}
throw reject('图片内容与PNG/JPEG类型不符,或图片已损坏。');
}
function exifOrientation(bytes) {
try {
const little = bytes.toString('ascii',0,2) === 'II';
if (!little && bytes.toString('ascii',0,2) !== 'MM') throw new Error();
const u16 = offset => little ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset);
const u32 = offset => little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
if (u16(2) !== 42) throw new Error();
const offset = u32(4), count = u16(offset);
if (offset < 8 || offset + 2 + count * 12 + 4 > bytes.length) throw new Error();
for (let i=0;i<count;i++) {
const entry=offset+2+i*12;
if (u16(entry)!==274) continue;
if(u16(entry+2)!==3 || u32(entry+4)!==1) throw new Error();
const value=u16(entry+8); if(value<1 || value>8) throw new Error(); return value;
}
return 1;
} catch { throw reject('JPEG方向元数据已损坏,请重新导出图片。'); }
}
function sentImage(decoded, orientation, maximum) {
const rotated = orientation >= 5;
const w = rotated ? decoded.height : decoded.width, h = rotated ? decoded.width : decoded.height;
const ratio = Math.min(1,maximum/Math.max(w,h)), width=Math.max(1,Math.round(w*ratio)), height=Math.max(1,Math.round(h*ratio));
const output = new PNG({width,height});
for(let y=0;y<height;y++) for(let x=0;x<width;x++) {
const u=Math.min(w-1,Math.floor(x*w/width)),v=Math.min(h-1,Math.floor(y*h/height));
const [sx,sy] = orientation===2 ? [decoded.width-1-u,v] : orientation===3 ? [decoded.width-1-u,decoded.height-1-v]
: orientation===4 ? [u,decoded.height-1-v] : orientation===5 ? [v,u] : orientation===6 ? [v,decoded.height-1-u]
: orientation===7 ? [decoded.width-1-v,decoded.height-1-u] : orientation===8 ? [decoded.width-1-v,u] : [u,v];
output.data.set(decoded.data.subarray((sy*decoded.width+sx)*4,(sy*decoded.width+sx)*4+4),(y*width+x)*4);
}
return { bytes:PNG.sync.write(output),width,height };
}
export function validateImage(input) {
if (!input || Object.keys(input).some(key => !['name','mediaType','base64'].includes(key)) || typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160
|| /[\\/\x00-\x1f]/.test(input.name) || !['image/png','image/jpeg'].includes(input.mediaType) || typeof input.base64 !== 'string') throw reject('请选择PNG或JPEG图片,文件名不能包含路径。');
if (input.base64.length > Math.ceil(IMAGE_LIMITS.bytes / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.base64)) throw reject('图片编码无效。');
const bytes = Buffer.from(input.base64,'base64');
if (bytes.length > IMAGE_LIMITS.bytes) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!bytes.length || bytes.toString('base64') !== input.base64) throw reject('图片编码或大小无效。');
const size = dimensions(bytes,input.mediaType);
if (!size.width || !size.height || Math.max(size.width,size.height)>IMAGE_LIMITS.dimension || size.width*size.height>IMAGE_LIMITS.pixels) throw reject('图片尺寸过大,请裁剪后再添加。',413);
let decoded;
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:16.8,maxMemoryUsageInMB:160}); }
catch { throw reject('图片无法完整解码,请重新导出PNG/JPEG。'); }
if (decoded.width!==size.width || decoded.height!==size.height) throw reject('图片实际尺寸不一致。');
let maximum = IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>IMAGE_LIMITS.sentBytes && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>IMAGE_LIMITS.sentBytes)throw reject('图片发送副本超过大小限制,请先裁剪。',413);
return { bytes, sent:sent.bytes, width:size.width,height:size.height,orientation:size.orientation,sentWidth:sent.width,sentHeight:sent.height };
}
export class InputAttachments {
constructor(store, { busy=()=>false }={}) { this.store=store;this.busy=busy; }
list(session) { return [...this.store.core.input_attachment.values()].filter(row=>row.sessionId===session.id && ['draft','attached'].includes(row.status)).map(row=>structuredClone(row)); }
upload(session,input) {
if(this.busy(session.projectId))throw reject('请等待当前项目执行结束后再添加附件。',409);
if(this.list(session).filter(row=>row.status==='draft').length>=IMAGE_LIMITS.drafts)throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
const original=this.store.artifactStore.write(identity,null,value.bytes,{kind:'input-image-original',mediaType:input.mediaType});
const sent=this.store.artifactStore.write(identity,null,value.sent,{kind:'input-image-sent',mediaType:'image/png'});
this.store.core.artifact.set(original.id,original);this.store.core.artifact.set(sent.id,sent);
const record={id:randomUUID(),sessionId:session.id,projectId:session.projectId,taskId:null,runId:null,status:'draft',name:input.name.trim(),mediaType:input.mediaType,
originalArtifactId:original.id,sentArtifactId:sent.id,sha256:original.sha256,bytes:original.bytes,sentSha256:sent.sha256,sentBytes:sent.bytes,
width:value.width,height:value.height,orientation:value.orientation,sentWidth:value.sentWidth,sentHeight:value.sentHeight,createdAt:new Date().toISOString()};
this.store.putRecord('input_attachment',session,record,'input_attachment.uploaded');return structuredClone(record);
}
get(session,id) { return this.store.owned('input_attachment',id,session.id); }
remove(session,id) {
const row=this.get(session,id);
if(row.status!=='draft'||this.busy(session.projectId))throw reject('已发送附件保留在原任务中;只能移除尚未发送的图片。',409);
row.status='withdrawn';this.store.save(session,{type:'input_attachment.withdrawn'});return this.list(session);
}
validateSelection(session,ids) {
if(!Array.isArray(ids)||ids.length>IMAGE_LIMITS.perTask||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
return ids.map(id=>{const row=this.get(session,id);if(row.status!=='draft')throw reject('图片已发送或移除,请重新选择。',409);this.read(session,id);this.read(session,id,{original:true});return row;});
}
read(session,id,{original=false}={}) {
const row=this.get(session,id);if(row.status==='withdrawn')throw reject('这张待发送图片已移除。',410);
const artifact=this.store.owned('artifact',original?row.originalArtifactId:row.sentArtifactId,session.id);
if(row.projectId!==session.projectId || artifact.taskId!==row.taskId||artifact.runId!==row.runId||artifact.sha256!==(original?row.sha256:row.sentSha256)
||artifact.kind!==(original?'input-image-original':'input-image-sent') || artifact.mediaType!==(original?row.mediaType:'image/png') || artifact.bytes!==(original?row.bytes:row.sentBytes))throw reject('附件身份已变化,请核对原记录。',409);
if(row.status==='attached'){
const task=this.store.owned('task',row.taskId,session.id),run=this.store.owned('run',row.runId,session.id);
if(run.taskId!==task.id||!task.attachmentIds?.includes(row.id))throw reject('附件不属于原Task/Run。',409);
}
return {row,artifact,bytes:this.store.artifactStore.readBytes(artifact)};
}
images(session,task) {
return (task.attachmentIds??[]).map(id=>{const {row,bytes}=this.read(session,id);this.read(session,id,{original:true});if(row.taskId!==task.id||row.status!=='attached')throw reject('附件不属于当前任务。',409);
return {id:row.id,sha256:row.sentSha256,width:row.sentWidth,height:row.sentHeight,dataUrl:'data:image/png;base64,'+bytes.toString('base64')};});
}
}
+37 -6
View File
@@ -1,6 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
import { BudgetExceeded, accountedTokens } from '../../shared/contracts/execution.mjs';
import { completionBody, requestMetrics, requestVariants, requestHistory, outputReservation } from '../../shared/contracts/model-request.mjs';
import { completionBody, requestMetrics, requestVariants, requestHistory, outputReservation, requestImages } from '../../shared/contracts/model-request.mjs';
import { workingCandidates, workingDocument, workingEntry, workingMessage, verifyWorkingDocument } from './working-set.mjs';
import { latestToolDocument, latestToolMessage, verifyLatestToolDocument } from './tool-feedback.mjs';
import { projectMemoryMessage, MEMORY_CONTEXT_LIMITS } from '../memory/project-memory.mjs';
@@ -48,7 +48,7 @@ export function historyGroups(messages) {
return groups;
}
function budgetFor(config, run, task) {
export function budgetFor(config, run, task) {
const outputReservation = config.maxOutputTokens;
const safetyTokens = Math.max(512, Math.ceil(Math.min(config.contextLimit, 24000) * 0.1));
const remaining = (maximum, usage) => maximum > 0 ? Math.max(0, maximum - accountedTokens(usage)) : null;
@@ -118,11 +118,12 @@ function notice(reference, omitted, descriptions, evidence = []) {
].join('\n') };
}
function pause(budget, metrics) {
function pause(budget, metrics, breakdown) {
const error = new BudgetExceeded(budget.limitingReason,
'任务目标、完整追加要求与必需请求开销超过' + (budget.limitingReason === 'context_limit' ? '上下文窗口' : '剩余token预算') +
'。完整历史已保留;请核对模型上下文或任务预算后继续。');
error.contextBudget = { ...budget, requiredInputTokens: metrics.estimatedInputTokens };
error.contextBudget = { ...budget, requiredInputTokens: metrics.estimatedInputTokens, imageReservationTokens:metrics.imageReservationTokens??0,
imageEstimate:metrics.imageEstimate??null,breakdown:breakdown(metrics) };
return error;
}
@@ -162,6 +163,14 @@ export class RequestPlanner {
const groups = historyGroups(session.providerMessages), budget = budgetFor(config, run, task);
const lastUser = groups.findLast(group => group.messages[0].role === 'user');
const fixed = { role: 'system', content: system };
const breakdown = metrics => {
const empty=requestMetrics(completionBody(config,[],[])).estimatedInputTokens;
const fixedText=requestMetrics(completionBody(config,[fixed],[])).estimatedInputTokens;
const fixedTools=requestMetrics(completionBody(config,[fixed],tools)).estimatedInputTokens;
return {transportAndImageFramingTokens:empty-(metrics.imageReservationTokens??0),goalAndContextTextTokens:fixedText-empty,
toolDefinitionTokens:fixedTools-fixedText,historyAndEvidenceTokens:metrics.estimatedInputTokens-fixedTools,
imageReservationTokens:metrics.imageReservationTokens??0};
};
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.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);
@@ -181,7 +190,7 @@ export class RequestPlanner {
if (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);
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
const observed = workingCandidates(this.store, session, run, groups);
// Reserve other small source files before admitting a new result group.
// Historical locator pages are optional; they cannot evict actual code.
@@ -295,7 +304,7 @@ export class RequestPlanner {
}
}
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics, breakdown);
const requestArtifact = this.artifact(session, run, body, 'model-request');
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,
@@ -303,6 +312,8 @@ export class RequestPlanner {
requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens,
requestArtifactId: requestArtifact.id,
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
...(metrics.imageCount?{imageCount:metrics.imageCount,imageReservationTokens:metrics.imageReservationTokens,imageEstimate:metrics.imageEstimate,
inputImages:config.inputImages.map(({dataUrl,...identity})=>identity)}:{}),
mandatoryInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens,
// The next result replaces the current latest-result feedback. Do not
// reserve both views when sizing that result's actual protocol page.
@@ -353,6 +364,26 @@ 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 ['imageCount','imageReservationTokens','imageEstimate','inputImages']) {
if(JSON.stringify(frozen[key]??null)!==JSON.stringify(plan[key]??null))throw new Error('图片身份或预算与发送前封存不匹配。');
}
if(metrics.imageCount) {
if(metrics.imageCount!==plan.imageCount||metrics.imageReservationTokens!==plan.imageReservationTokens||metrics.imageEstimate!==plan.imageEstimate
||plan.inputImages?.length!==metrics.imageCount)throw new Error('图片预算与实际正文不匹配。');
for(const variant of requestVariants(body)) {
const images=requestImages(variant);
if(images.length!==plan.inputImages.length)throw new Error('图片请求线路不一致。');
for(const [index,url] of images.entries()) {
const identity=plan.inputImages[index],row=store.owned('input_attachment',identity.id,session.id);
const artifact=get(row.sentArtifactId,'input-image-sent',identity.sha256),bytes=store.artifactStore.readBytes(artifact);
const original=get(row.originalArtifactId,'input-image-original',row.sha256);store.artifactStore.readBytes(original);
if(row.taskId!==plan.taskId||row.status!=='attached'||artifact.taskId!==plan.taskId||artifact.runId!==row.runId
||original.taskId!==plan.taskId||original.runId!==row.runId
||row.sentSha256!==identity.sha256||row.sentWidth!==identity.width||row.sentHeight!==identity.height
||url!=='data:image/png;base64,'+bytes.toString('base64'))throw new Error('图片原字节或任务归属与实际正文不匹配。');
}
}
} else if(plan.imageCount||plan.inputImages?.length)throw new Error('请求缺少封存的图像。');
if (frozen.id !== plan.id || frozen.requestSha256 !== plan.requestSha256 || frozen.requestArtifactId !== plan.requestArtifactId
|| JSON.stringify(frozen.budget) !== JSON.stringify(plan.budget)) throw new Error('请求计划与发送前的封存记录不匹配。');
if ((frozen.workingSetArtifactId ?? null) !== (plan.workingSetArtifactId ?? null)
+10 -6
View File
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { CredentialVault } from './credential-vault.mjs';
import { visionProbe } from './vision-probe.mjs';
import { modelProtocol, capabilityDeclarations, capabilityView, capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
import { actualRequest, requestVariants } from '../../shared/contracts/model-request.mjs';
@@ -118,7 +119,7 @@ export class ModelHub {
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: 1000 } }; }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
async probe(id, scope = 'text') {
if (!['text', 'tools', 'streaming'].includes(scope)) throw error('请选择文本、工具调用或流式检测。');
if (!['text', 'tools', 'streaming', 'vision'].includes(scope)) throw error('请选择文本、工具调用、流式或图像检测。');
if (this.probing) throw error('已有模型能力检测正在执行,请等待结束。', 409);
this.probing = true;
try {
@@ -131,13 +132,16 @@ export class ModelHub {
const config = { ...this.store.config, mode: 'compatible', model: connection.model, baseUrl: connection.baseUrl,
protocol: modelProtocol(connection.protocol), maxOutputTokens: 256, capabilityProbe: true, modelRouting: { type: 'connection', id: connection.id, revision: connection.revision,
strategy: 'round-robin', sticky: false, maxAttempts: 1, queueTimeoutMs: 1000, members: [member] } };
const visual=scope==='vision'?visionProbe():null;
if(visual)config.inputImages=[visual.image];
let attemptId;
const result = await this.provider.complete(config, [{ role: 'user', content: scope === 'tools' ? 'Call workbench_capability_echo with nonce ' + nonce + '. Do not reply with plain text.' : 'Reply OK.' }], null, undefined,
const result = await this.provider.complete(config, [{ role: 'user', content: visual?.prompt ?? (scope === 'tools' ? 'Call workbench_capability_echo with nonce ' + nonce + '. Do not reply with plain text.' : 'Reply OK.') }], null, undefined,
event => { if (event.modelAttemptId) attemptId = event.modelAttemptId; }, null, tools, { attempts: 1 });
if (scope === 'tools') {
const calls = result.message.tool_calls;
if (calls?.length !== 1 || calls[0].function.name !== 'workbench_capability_echo' || JSON.parse(calls[0].function.arguments).nonce !== nonce) throw error('服务没有返回要求的原工具调用;未标为已验证。');
} else if (!result.message.content.trim() || result.message.tool_calls?.length) throw error('服务没有返回纯文本响应;未标为已验证。');
if(visual&&result.message.content.trim().toUpperCase().replace(/\s/g,'')!==visual.expected)throw error('服务未正确识别合成图像的四色顺序,原请求保留,未标为视觉已验证。');
if (this.connection(id).revision !== connection.revision || (this.credential(connection)?.revision ?? 0) !== member.credentialRevision) throw error('检测期间连接已变化,原结果保留但不更新能力结论。', 409);
this.editRegistry(() => {
this.state.capabilityResults ??= {};
@@ -217,9 +221,8 @@ export class ModelHub {
this.save(config ?? (input.type !== 'legacy' ? { mode: 'compatible' } : null));
return this.view();
}
prepare(config) {
if (config.mode === 'demo' || this.state.selected.type === 'legacy') return config;
const selection = this.state.selected;
prepare(config, selection = this.state.selected) {
if (config.mode === 'demo' || selection.type === 'legacy') return config;
const pool = selection.type === 'pool' ? this.state.pools.find(value => value.id === selection.id) : null;
if (selection.type === 'pool' && !pool) throw error('选中的模型池不存在。');
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight,
@@ -272,7 +275,8 @@ export class ModelHub {
async completeOwned(config, body, signal, onProgress, plan, execute) {
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
const requirements = config.capabilityProbe ? [] : ['text', ...(requestVariants(body).some(value => value.tools?.length) ? ['tools'] : [])];
const requirements = config.capabilityProbe ? [] : ['text', ...(requestVariants(body).some(value => value.tools?.length) ? ['tools'] : []),
...(requestVariants(body).some(value => (value.messages??value.input??[]).some(message=>Array.isArray(message.content)&&message.content.some(part=>['image_url','input_image'].includes(part.type))))?['vision']:[])];
const rejections = config.capabilityProbe ? [] : routing.members.flatMap(value => capabilityRejections(value, [...requirements, ...(value.streaming ? ['streaming'] : [])], value.credentialRevision));
const eligibleRouting = { ...routing, members: routing.members.filter(value => !rejections.some(item => item.connectionId === value.id)) };
if (!eligibleRouting.members.length) {
+13
View File
@@ -0,0 +1,13 @@
import { randomInt, createHash, randomUUID } from 'node:crypto';
import { PNG } from 'pngjs';
// Synthetic pixels only. The expected order is never placed in the prompt.
export function visionProbe() {
const colors = [{name:'RED',rgb:[230,0,0]},{name:'GREEN',rgb:[0,180,0]},{name:'BLUE',rgb:[0,0,230]},{name:'YELLOW',rgb:[240,220,0]}];
for (let i=colors.length-1;i>0;i--) { const j=randomInt(i+1);[colors[i],colors[j]]=[colors[j],colors[i]]; }
const png=new PNG({width:128,height:128});
for(let y=0;y<128;y++)for(let x=0;x<128;x++)png.data.set([...colors[(y>=64?2:0)+(x>=64?1:0)].rgb,255],(y*128+x)*4);
const bytes=PNG.sync.write(png);
return {expected:colors.map(value=>value.name).join(','),prompt:'Read the four colored squares in this attached synthetic image in order: top-left, top-right, bottom-left, bottom-right. Reply only with four comma-separated English color names, using RED, GREEN, BLUE, YELLOW. Do not call tools.',
image:{id:randomUUID(),sha256:createHash('sha256').update(bytes).digest('hex'),width:128,height:128,dataUrl:'data:image/png;base64,'+bytes.toString('base64')}};
}
+22 -3
View File
@@ -48,12 +48,12 @@ function json(response, value, status = 200) {
'X-Content-Type-Options': 'nosniff' });
response.end(JSON.stringify(value));
}
async function body(request) {
async function body(request, maximum=2*1024*1024) {
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw Object.assign(new Error('请求需要 JSON。'), { status: 415 });
const chunks = []; let length = 0;
for await (const chunk of request) {
length += chunk.length;
if (length > 2 * 1024 * 1024) throw Object.assign(new Error('请求超过 2 MB。'), { status: 413 });
if (length > maximum) throw Object.assign(new Error('请求超过允许大小。'), { status: 413 });
chunks.push(chunk);
}
let input;
@@ -269,6 +269,23 @@ return async (request, response) => {
if (sessionMatch) {
const id = sessionMatch[1], action = sessionMatch[2] ?? '';
const session = store.session(id);
if (action === 'input-attachments') {
if (method === 'GET') return json(response,runtime.inputAttachments().list(session));
if (workerForProject(store,session.projectId)) throw workerConflict('截图附件请在父任务中添加。');
if (method === 'POST') return json(response,runtime.inputAttachments().upload(session,await body(request,3*1024*1024)),201);
}
const inputImage = action.match(/^input-attachments\/([a-f0-9-]+)(?:\/(image|original))?$/);
if (inputImage) {
const manager=runtime.inputAttachments();
if(method==='DELETE'&&!inputImage[2]) { await body(request);return json(response,manager.remove(session,inputImage[1])); }
if(method==='GET'&&inputImage[2]) {
const {row,artifact,bytes}=manager.read(session,inputImage[1],{original:inputImage[2]==='original'});
const download=inputImage[2]==='original'||url.searchParams.get('download')==='1';
response.writeHead(200,{'Content-Type':artifact.mediaType,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Content-SHA256':artifact.sha256,
...(download?{'Content-Disposition':'attachment; filename="workbench-input-'+row.id+(artifact.mediaType==='image/png'?'.png':'.jpg')+'"'}:{})});
response.end(bytes);return;
}
}
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|task-plans|task-proofs|task-checkpoints|collaborations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
if (method === 'GET' && action === 'collaborations') return json(response, runtime.workerManager().view(session));
@@ -574,7 +591,7 @@ return async (request, response) => {
}
if (method === 'POST' && action === 'messages') {
const input = await body(request);
runtime.start(id, input.content);
runtime.start(id, input.content,false,{attachmentIds:input.attachmentIds??[]});
return json(response, store.publicSession(session), 202);
}
if (method === 'POST' && action === 'resume') {
@@ -582,6 +599,8 @@ return async (request, response) => {
runtime.resume(id, input.content);
return json(response, store.publicSession(session), 202);
}
if(method==='POST'&&action==='resume-preview')return json(response,runtime.budgetResumes().prepare(session,await body(request)),201);
if(method==='POST'&&action==='resume-budget'){runtime.resumeBudget(id,await body(request));return json(response,store.publicSession(session),202);}
if (method === 'POST' && action === 'continue-reviewed') {
await body(request); runtime.continueReviewed(id);
return json(response, store.publicSession(session), 202);
+10 -1
View File
@@ -9,6 +9,7 @@ import { CompanionTLS } from '../core/companion/tls-authority.mjs';
import { fields, companionError, companionHash, approvalBinding, operationInput } from '../shared/contracts/companion.mjs';
import { isId } from '../shared/contracts/execution.mjs';
import { mobileSession, sessionBrief, reportKinds } from '../core/companion/projection.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
export function companionGateway(context) {
@@ -179,7 +180,7 @@ export class CompanionGateway {
async handle(request, response) {
response.setHeader('Cache-Control', 'no-store'); response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Referrer-Policy', 'no-referrer'); response.setHeader('X-Frame-Options', 'DENY');
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
try {
this.registry.assertHost();
if (!this.server?.listening || !this.origin || request.headers.host !== new URL(this.origin).host) throw companionError('手机网关地址已变化,请重新连接。', 421);
@@ -220,6 +221,14 @@ export class CompanionGateway {
if (limit < 1 || limit > 200) throw companionError('手机事件每页需要1至200条。');
return reply(response, this.events(device, after, limit));
}
const attachment=route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)\/input-attachments\/([a-f0-9-]+)\/(image|original)$/);
if(attachment&&method==='GET'){
const session=this.session(device,attachment[1]),manager=new InputAttachments(this.store),row=manager.get(session,attachment[2]);
if(row.taskId!==session.taskId||row.status!=='attached'||!(this.store.core.task.get(session.taskId)?.attachmentIds??[]).includes(row.id))throw companionError('当前任务没有这张截图。',404);
const {artifact,bytes}=manager.read(session,row.id,{original:attachment[3]==='original'});
response.writeHead(200,{'Content-Type':artifact.mediaType,'Content-Length':bytes.length,'X-Content-SHA256':artifact.sha256,
...(attachment[3]==='original'?{'Content-Disposition':'attachment; filename="workbench-input-'+row.id+(row.mediaType==='image/png'?'.png':'.jpg')+'"'}:{})});response.end(bytes);return;
}
const match = route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)(?:\/(approve|stop|changes\/([a-f0-9-]+)|reports\/([a-f0-9-]+)))?$/);
if (match) {
const session = this.session(device, match[1]);
+6
View File
@@ -34,6 +34,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
const oldInputs = runtime.inputs;
const oldResumes = runtime.resumes;
const closeStorage = () => store.close();
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
const handler = createRequestHandler({ appDirectory: root, server, store, provider, runtime, token, clients, started,
@@ -49,6 +51,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
}
runtime.appDirectory = root; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
delete server.workbenchCompanion;
runtime.inputs = null;
runtime.resumes = null;
store.ensureStorage();
// A SQLite host can retain an artifact object from an earlier bundle.
// Reopen the same blobs through the new API without mutating that object;
@@ -80,6 +84,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
for (const key of Object.keys(store)) if (!Object.hasOwn(oldStoreProperties, key)) delete store[key];
Object.assign(store, oldStoreProperties);
Object.assign(runtime, oldRuntimeProperties);
if (oldInputs === undefined) delete runtime.inputs; else runtime.inputs = oldInputs;
if (oldResumes === undefined) delete runtime.resumes; else runtime.resumes = oldResumes;
Object.setPrototypeOf(store, oldPrototypes[0]); Object.setPrototypeOf(provider, oldPrototypes[1]); Object.setPrototypeOf(runtime, oldPrototypes[2]);
if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub);
if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer);
+1
View File
@@ -210,6 +210,7 @@ export class Provider {
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions, requestPolicy = {}) {
const body = completionBody(config, messages, tools);
assertPlannedRequest(body, requestPlan);
if (config.inputImages?.length && (!config.modelRouting || !this.hub || config.mode==='demo')) throw new Error('图片请求必须通过模型中心的视觉能力选路,尚未发送。');
if (config.mode === 'demo') return this.demo(messages, project);
this.validate(config);
const execute = async (selected, key, input, progress) => {
+21 -5
View File
@@ -14,6 +14,8 @@ import { projectEnvironment } from '../core/process-environment.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { BudgetResume } from '../core/context/budget-resume.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, clearReadStreak, recordSessionInspection, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -119,6 +121,9 @@ export class Runtime {
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
}
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
inputAttachments() { return this.inputs ??= new InputAttachments(this.store,{busy:projectId=>this.projectHasActivity(projectId)}); }
budgetResumes(){return this.resumes??=new BudgetResume(this.store,this.provider,this);}
resumeBudget(id,input){const session=this.store.session(id),plan=this.budgetResumes().verify(session,input);return this.start(id,'',true,{resumePlan:plan});}
engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); }
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); }
checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, {
@@ -159,7 +164,7 @@ export class Runtime {
|| this.store.core.collaboration.get(worker.collaborationId)?.status !== 'running') throw workerConflict('子任务只能由所属父协作启动。');
return this.start(session.id, worker.goal, true, { workerAuthorization: workerAuthority, worker, workerConfig: config });
}
start(id, content, resume = false, { instructionSource = null, workerAuthorization = null, worker = null, workerConfig = null } = {}) {
start(id, content, resume = false, { instructionSource = null, workerAuthorization = null, worker = null, workerConfig = null, attachmentIds=[],resumePlan=null } = {}) {
const session = this.store.session(id);
assertWorkersResolved(this.store, session.projectId);
const boundWorker = workerForSession(this.store, session);
@@ -174,19 +179,24 @@ export class Runtime {
if ([...this.store.core.delivery_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw Object.assign(new Error('项目有结果未知的Git交付,请先在所属任务中核对提交结果。'), { status: 409 });
if (!resume && (typeof content !== 'string' || !content.trim() || content.length > 20000)) throw new Error('任务内容不能为空,也不能超过 20,000 字符。');
const project = this.store.project(session.projectId);
const attachments=this.inputAttachments().validateSelection(session,attachmentIds);
if(attachments.length&&this.store.core.task.get(session.taskId)?.attachmentIds?.length&&!['completed','idle'].includes(this.store.core.task.get(session.taskId).status))throw Object.assign(new Error('当前任务已有截图,请新建任务再添加。'),{status:409});
safePath(project);
const controller = new AbortController();
const initialConfig = structuredClone(workerConfig ?? this.store.config);
const config = workerConfig ? initialConfig : this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig;
const initialConfig = structuredClone(resumePlan?.config ?? workerConfig ?? this.store.config);
const config = resumePlan || workerConfig ? initialConfig : this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig;
if (config.mode !== 'demo') this.provider.validate(config);
const record = this.store.beginRun(session, content, resume, config, { instructionSource });
if (attachments.length && config.mode==='demo') throw Object.assign(new Error('演示执行器不会读取图片,请先选择支持视觉的模型连接。'),{status:409});
if (attachments.length && !config.modelRouting) throw Object.assign(new Error('请在模型中心添加并声明支持视觉的连接,再发送图片。'),{status:409});
const record = this.store.beginRun(session, content, resume, config, { instructionSource, inputAttachments:attachments,resumePlan });
const run = { controller, id: record.id, taskId: record.taskId, project, record, config, ...(worker ? { worker } : {}) };
this.active.set(id, run);
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
session.runId = run.id;
if (session.title === '新任务') session.title = String(content).replace(/\s+/g, ' ').slice(0, 28);
if (!resume || content) {
this.store.message(session, 'user', String(content));
const userMessage=this.store.message(session, 'user', String(content));
if(attachments.length)userMessage.attachmentIds=attachments.map(row=>row.boundAttachmentId);
session.providerMessages.push({ role: 'user', content: String(content) });
}
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
@@ -231,6 +241,8 @@ export class Runtime {
checkBudget(run.record, this.store.core.task.get(run.taskId));
const stepRecord = this.store.beginStep(session, run.record);
const task = this.store.core.task.get(run.taskId);
config.inputImages=this.inputAttachments().images(session,task);
if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。');
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
@@ -408,6 +420,10 @@ export class Runtime {
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
if (signal.aborted || budget) {
run.stopReason = budget?.reason ?? 'cancelled';
if(budget)run.record.budgetPause={schema:1,reason:budget.reason,createdAt:now(),taskId:run.taskId,runId:run.id,
...(budget.contextBudget??{}),runUsage:structuredClone(run.record.usage),taskUsage:structuredClone(this.store.core.task.get(run.taskId).usage),
runBudget:structuredClone(run.record.budget),taskBudget:structuredClone(this.store.core.task.get(run.taskId).budget),
note:'本地预留估算与服务实际用量分开记录;图片预留不是厂商计费或容量保证。'};
for (const event of session.events.filter(item => item.kind === 'model' && item.runId === run.id && ['running', 'retrying'].includes(item.phase))) {
event.phase = 'interrupted'; event.finishedAt = now(); event.output = '模型请求已停止,已完成的工具结果保留。';
}
+19 -1
View File
@@ -450,8 +450,15 @@ export class Store extends EventEmitter {
return session;
}
beginRun(session, content, resume, config, { instructionSource = null, forceNewTask = false } = {}) {
beginRun(session, content, resume, config, { instructionSource = null, forceNewTask = false, inputAttachments = [],resumePlan=null } = {}) {
let task = this.core.task.get(session.taskId);
if(resumePlan&&(!resume||!task||resumePlan.taskId!==task.id||this.owned('resume_plan',resumePlan.id,session.id)!==resumePlan||resumePlan.status!=='prepared'))throw new Error('续接预览不属于原任务。');
// Bind inputs in the same session transaction as run.started.
const inputs = inputAttachments.map(row => {
if (this.owned('input_attachment',row.id,session.id) !== row || row.status !== 'draft') throw new Error('附件选择已变化。');
return {row,artifacts:[row.originalArtifactId,row.sentArtifactId].map(id=>this.owned('artifact',id,session.id))};
});
if (inputs.length>1 || inputs.length && !forceNewTask && task?.attachmentIds?.length && (resume || !['completed','idle'].includes(task.status))) throw new Error('当前任务已有截图,请新建任务再添加。');
const previousRunId = session.runId ?? null;
if (forceNewTask || !task || !resume && ['completed', 'idle'].includes(task.status)) {
const previous = task?.id ?? null;
@@ -466,8 +473,18 @@ export class Store extends EventEmitter {
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
const run = createRun(session, task, config, resume ? previousRunId : null);
if(resumePlan){task.budget.maxTokens=config.maxTaskTokens;run.resumePlanId=resumePlan.id;resumePlan.status='consumed';resumePlan.newRunId=run.id;}
run.workspaceIdentity = structuredClone(workspaceIdentity);
this.core.run.set(run.id, run); task.activeRunId = run.id;
for (const {row,artifacts} of inputs) {
const copies=artifacts.map(artifact=>({...artifact,id:randomUUID(),taskId:task.id,runId:run.id}));
for(const artifact of copies)this.core.artifact.set(artifact.id,artifact);
const bound={...row,id:randomUUID(),taskId:task.id,runId:run.id,status:'attached',sourceDraftId:row.id,
originalArtifactId:copies[0].id,sentArtifactId:copies[1].id};
this.core.input_attachment.set(bound.id,bound);
row.status='consumed';row.boundAttachmentId=bound.id;
}
if (inputs.length) task.attachmentIds=inputs.map(({row})=>row.boundAttachmentId);
session.taskId = task.id; session.runId = run.id; session.status = 'running';
this.save(session, { type: 'run.started', detail: { resumeOf: run.resumeOf } });
return run;
@@ -682,6 +699,7 @@ export class Store extends EventEmitter {
publicSession(session) {
const { providerMessages, ...visible } = session;
visible.inputAttachments=[...this.core.input_attachment.values()].filter(row=>row.sessionId===session.id&&['draft','attached'].includes(row.status));
visible.execution = this.executionSnapshot(session);
visible.lastFailure = lastSessionFailure(session);
if (session.status === 'failed' && !visible.failure && visible.lastFailure) {
+2 -1
View File
@@ -2,7 +2,8 @@ import { randomUUID } from 'node:crypto';
export const EXECUTION_SCHEMA = 1;
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'engine_run', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint', 'mcp_job', 'collaboration', 'worker'];
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'engine_run', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint', 'mcp_job', 'collaboration', 'worker', 'input_attachment'];
CORE_KINDS.push('resume_plan');
export const timestamp = () => new Date().toISOString();
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
+23
View File
@@ -3,6 +3,9 @@ import { modelProtocol } from './model-capabilities.mjs';
function wireBody(config, messages, tools) {
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
if(config.inputImages?.length) messages=[...messages,{role:'user',content:protocol==='responses'
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
const cleanMessages = messages.map(({ providerState, ...message }) => message);
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', max_tokens: config.maxOutputTokens, stream,
...(stream ? { stream_options: { include_usage: true } } : {}) };
@@ -59,12 +62,32 @@ export function requestMetrics(body) {
const serialized = JSON.stringify(body);
const bytes = Buffer.byteLength(serialized, 'utf8');
const variants = requestVariants(body);
const images=requestImages(body);
const imageReserve=imageTokenReserve(body);
const estimates=variants.map(value=>Math.ceil(Buffer.byteLength(JSON.stringify(value, (key,item)=>typeof item==='string'&&item.startsWith('data:image/')?'[bounded image bytes]':item),'utf8')/3)
+ (value.messages?.length ?? value.input?.length ?? 0)*8+(value.tools?.length??0)*16+imageTokenReserve(value));
if(images.length)return {bytes,sha256:createHash('sha256').update(serialized,'utf8').digest('hex'),estimatedInputTokens:Math.max(...estimates),
imageReservationTokens:imageReserve,imageCount:Math.max(...variants.map(value=>requestImages(value).length)),estimateMethod:'text-utf8-plus-image-reservation-v1',imageEstimate:'local-reservation-not-provider-billing'};
return { bytes, sha256: createHash('sha256').update(serialized, 'utf8').digest('hex'),
estimatedInputTokens: Math.max(...variants.map(value => Math.ceil(Buffer.byteLength(JSON.stringify(value), 'utf8') / 3)
+ (value.messages?.length ?? value.input?.length ?? 0) * 8 + (value.tools?.length ?? 0) * 16)),
estimateMethod: body.kind === 'model-route-plan' ? 'maximum-wire-variant-utf8-v1' : 'utf8-third-plus-framing-v1' };
}
export function requestImages(body) {
return requestVariants(body).flatMap(value=>(value.messages??value.input??[]).flatMap(message=>Array.isArray(message.content)?message.content.filter(part=>['image_url','input_image'].includes(part.type)).map(part=>part.type==='image_url'?part.image_url?.url:part.image_url):[]));
}
export function imageTokenReserve(body){
return Math.max(0,...requestVariants(body).map(value=>requestImages(value).reduce((total,url)=>{
if(typeof url!=='string'||!url.startsWith('data:image/png;base64,'))throw new Error('视觉请求只允许已校验的PNG发送副本。');
const bytes=Buffer.from(url.slice(22,70),'base64');
if(bytes.length<24||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||bytes.readUInt32BE(8)!==13||bytes.toString('ascii',12,16)!=='IHDR')throw new Error('视觉请求图像头不完整或类型不符。');
const width=bytes.readUInt32BE(16),height=bytes.readUInt32BE(20);
if(!width||!height||Math.max(width,height)>1024)throw new Error('视觉请求超过已校验副本范围。');
return total+Math.max(4096,Math.ceil(width/32)*Math.ceil(height/32)*4);
},0)));
}
export function assertPlannedRequest(body, plan) {
if (!plan) return;
const metrics = requestMetrics(body);