feat(vision): bind task screenshots, route vision and resume budget pauses
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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')};});
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user