From 9d3c2e93f2fe1c39d84b2aee3ddbb1e25843b9bf Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Sat, 5 Dec 2026 15:52:03 +0800 Subject: [PATCH] feat(detail-agent-pi): thin harness speedups, single-source slots, and role model routing --- apps/detail-agent-pi/src/agent.mjs | 42 +++- apps/detail-agent-pi/src/context-usage.mjs | 49 +++- .../src/image-wait-summary.mjs | 6 +- .../src/production-delegate.mjs | 29 ++- .../src/production-image-worker.mjs | 79 +++++- .../src/production-operations.mjs | 189 +++++++++------ apps/detail-agent-pi/src/production-tools.mjs | 6 +- .../test/thin-harness-wave2a.test.mjs | 4 +- .../test/thin-speed-124.test.mjs | 229 ++++++++++++++++++ 9 files changed, 522 insertions(+), 111 deletions(-) create mode 100644 apps/detail-agent-pi/test/thin-speed-124.test.mjs diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index d5212603..0f6b0704 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -42,6 +42,23 @@ import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs'; const MAIN_CONTEXT_BUDGET = 150_000; + +export function resolveRoleModelSelection(info, role = 'main') { + const base = info?.model; + if (!base) return base; + const overrides = info?.roleModels ?? info?.models; + if (!overrides || typeof overrides !== 'object') return base; + const candidate = role === 'review' + ? (overrides.review ?? overrides.main) + : overrides[role]; + if (!candidate || typeof candidate !== 'object' || !candidate.id) return base; + const sameId = candidate.id === base.id; + return { + ...base, + ...candidate, + ...(!sameId && candidate.contextWindow === undefined ? { contextWindow: undefined, contextWindowSource: undefined } : null), + }; +} const protocolPaths = { 'openai-chat':'/v1/chat/completions', 'openai-responses':'/v1/responses', @@ -513,6 +530,11 @@ function toolsFor(host) { candidateId: Type.Optional(Type.String({ minLength:1, maxLength:120 })), instruction: Type.Optional(string(500)), }), async ({variantId,productVariantId,id,...args}, signal) => { if (args.intent === 'adopt_candidate' && !args.candidateId) throw Error('请明确要采纳的候选'); + if (host.productionContext && args.intent === 'adopt_candidate') { + return callProductionTool(host, 'adopt_production_image', { + outputId: args.outputId, variantId: variantId ?? productVariantId, slotId: args.slotId, candidateId: args.candidateId, + }, signal); + } return executeWorkflow(host, {...args,productVariantId:variantId??productVariantId}, signal); })); tools.push(make('workflow_propose', '按实时 version 创建待审核建议。instruction 仅用于 selling_points 的表达方向或 generate_candidate 的画面要求。画布生成用 slotId、variantId,candidateId 可指定父版本;旧项目保留 variant A/B。adopt_candidate 指定完成候选。export_psd 导出成品分层副本。', Type.Object({ @@ -621,11 +643,12 @@ export class DetailPiAgent { } const requestBroker = worker ? worker.broker : host.goalBroker ?? broker; const selection = host.routeInfo; + const selectionModel = worker?.modelSelection ?? selection.model; const candidates = authorizedCandidates(selection.candidates ?? requestBroker.candidates); - const selectedId = selection.model.routeId ?? selection.invocationHeaders?.['X-Relay-Route-Option']; - const selectedRoute = candidates.find(route => route.protocol === selection.model.protocol && + const selectedId = selectionModel.routeId ?? selection.invocationHeaders?.['X-Relay-Route-Option']; + const selectedRoute = candidates.find(route => route.protocol === selectionModel.protocol && (selectedId === undefined || (route.routeId ?? route.headers?.['X-Relay-Route-Option']) === selectedId)); - const primary = {...selectedRoute,...selection.model,headers:selection.invocationHeaders ?? selectedRoute?.headers}; + const primary = {...selectedRoute,...selectionModel,headers:selection.invocationHeaders ?? selectedRoute?.headers}; const routes = new Map([[routeKey(primary),primary]]); for (const candidate of candidates) { const route = {...candidate,id:candidate.id ?? primary.id}; @@ -895,15 +918,22 @@ export class DetailPiAgent { } const resourceLoader = await (workerResources ??= loadWorkerResources()); const sessionManager = SessionManager.inMemory(files.cwd); + const role = requestScope?.startsWith('review/') || requestScope?.includes('screen') ? 'review' : 'imageDelegate'; + const roleSelection = resolveRoleModelSelection(host.info, role); + const workerModel = roleSelection && roleSelection !== host.info.model ? host.registerModel(roleSelection) : session.model; + const supportedWorkerThinking = getSupportedThinkingLevels(workerModel); + const workerThinking = supportedWorkerThinking.includes(session.thinkingLevel) + ? session.thinkingLevel + : (supportedWorkerThinking[0] ?? 'off'); const {session:workerSession} = await createAgentSession({ - cwd:files.cwd, agentDir:store.dir, modelRuntime:runtime, model:session.model, - thinkingLevel:session.thinkingLevel, settingsManager:workerSettings, sessionManager, resourceLoader, + cwd:files.cwd, agentDir:store.dir, modelRuntime:runtime, model:workerModel, + thinkingLevel:workerThinking, settingsManager:workerSettings, sessionManager, resourceLoader, customTools:tools, tools:tools.map(tool=>tool.name), }); const sessionId = sessionManager.getSessionId(); const [kind,step] = requestScope.split('/'); const budget = workerTurnBudget(slotId); - const worker = {budget,slotId,requestScope,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE, + const worker = {budget,slotId,requestScope,role,modelSelection:roleSelection,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE, cacheKey:host.manager.getSessionId()+':'+(kind==='product'?step:tools[0]?.name??'detail')}; const abort = () => { void workerSession.abort(); }; workers.set(sessionId,worker); diff --git a/apps/detail-agent-pi/src/context-usage.mjs b/apps/detail-agent-pi/src/context-usage.mjs index f1e7ddd6..d23e9538 100644 --- a/apps/detail-agent-pi/src/context-usage.mjs +++ b/apps/detail-agent-pi/src/context-usage.mjs @@ -151,13 +151,46 @@ export function foldSupersededProductionReads(messages) { } const projected=folded ?? messages; let newestResult=-1; + let newestScreenRead=-1; for (let index=projected.length-1;index>=0;index--) { const message=projected[index]; if (message.role!=='toolResult') continue; if (newestResult<0) newestResult=index; + if (newestScreenRead<0 && message.toolName==='read_output_screen') newestScreenRead=index; const {toolName,toolCallId,details,content}=message; - if (!details || message.isError || details.detailsOmitted || details.receiptId || - content.length!==1 || content[0].type!=='text' || content[0].text.length<=10_000) continue; + if (!details || message.isError || details.detailsOmitted || details.receiptId) continue; + + if (toolName==='read_output_screen' && index!==newestScreenRead) { + let screenChanged=false; + const nextContent=content.map(block=>{ + if (block.type!=='text' || block.text.length<=1_500) return block; + if (extractUserCanvasChangeBlocks([block]).length) return block; + try { + const parsed=JSON.parse(block.text); + if (parsed && typeof parsed==='object') { + screenChanged=true; + const compact={ + ...(parsed.page!==undefined?{page:parsed.page}:null), + ...(parsed.screenFingerprint?{screenFingerprint:parsed.screenFingerprint}:null), + ...(parsed.textClipping!==undefined?{textClipping:parsed.textClipping}:null), + receiptId:toolCallId,detailHint:oldReceipt(toolCallId), + }; + return {type:'text',text:JSON.stringify(compact)}; + } + } catch { /* keep non-JSON text */ } + return block; + }); + if (screenChanged) { + folded ??= projected.slice(); + folded[index]={...message,content:nextContent}; + } + continue; + } + + const preservedChanges=extractUserCanvasChangeBlocks(content); + const primaryBlock=content[0]; + if (primaryBlock?.type!=='text' || primaryBlock.text.length<=3_000) continue; + if (content.length>1 && content.slice(1).some(b=>!preservedChanges.includes(b))) continue; let summary; if (['read_archived_images','list_project_images'].includes(toolName) && Array.isArray(details.candidates) && @@ -165,8 +198,12 @@ export function foldSupersededProductionReads(messages) { const {candidates,...scope}=details; summary=candidateReceipt(candidates,{...scope,receiptId:toolCallId,receiptHint:oldReceipt(toolCallId)}); } else if (index!==newestResult && ['plan_production','review_image_slots'].includes(toolName)) { - const {knowledgeFiles,progressSummary,...decision}=details; - summary={...decision,progressSummary:compactProgress(progressSummary)}; + const {knowledgeFiles,progressSummary,fieldRequirements: _fr,product,...decision}=details; + const productSummary=product?{name:product.name,spu:product.spu,detailBarcode:product.detailBarcode}:undefined; + summary={...decision,...(productSummary?{productSummary}:null),progressSummary:compactProgress(progressSummary)}; + } else if (index!==newestResult && toolName==='read_copy_fields' && Array.isArray(details.fields)) { + summary={outputId:details.outputId,variantId:details.variantId,pageId:details.pageId, + fieldCount:details.fields.length,receiptId:toolCallId,detailHint:oldReceipt(toolCallId)}; } else if (index!==newestResult && toolName==='native_call' && details.result?.resultId && Array.isArray(details.result.items)) { const {items,...result}=details.result; summary={...details,result}; @@ -174,9 +211,9 @@ export function foldSupersededProductionReads(messages) { if (!summary) continue; if (!summary.receiptId) summary={...summary,receiptId:toolCallId,detailHint:oldReceipt(toolCallId)}; const text=JSON.stringify(summary); - if (text.length>=content[0].text.length) continue; + if (text.length>=primaryBlock.text.length) continue; folded ??= projected.slice(); - folded[index]={...message,details:summary,content:[{type:'text',text}]}; + folded[index]={...message,details:summary,content:[{type:'text',text},...preservedChanges]}; } return folded ?? messages; } diff --git a/apps/detail-agent-pi/src/image-wait-summary.mjs b/apps/detail-agent-pi/src/image-wait-summary.mjs index 57b1be8a..2eb33d1b 100644 --- a/apps/detail-agent-pi/src/image-wait-summary.mjs +++ b/apps/detail-agent-pi/src/image-wait-summary.mjs @@ -16,8 +16,10 @@ function screenSummary({page,revision,screenFingerprint,state,verdict,summary,er ...(copyFixes ? {copyFixes:copyFixes.slice(0,1).map(finding)} : null)}; } -export function summarizeImageWait({outputId,variantId,active,checking,timedOut,waitedMs,budget,progressSummary,generation,checks,screenChecks,pendingWork}) { - const result={outputId,variantId,active,checking,timedOut,waitedMs,...(budget?{budget}:null)}; +export function summarizeImageWait({outputId,variantId,active,checking,timedOut,waitedMs,budget,progressSummary,generation,incrementalUpdates,autoAdopted,checks,screenChecks,pendingWork}) { + const result={outputId,variantId,active,checking,timedOut,waitedMs,...(budget?{budget}:null), + ...(incrementalUpdates?.length?{incrementalUpdates:incrementalUpdates.map(({slotId,candidateId,phase,reason})=>({slotId,candidateId,phase,...(reason?{reason:excerpt(reason,80)}:null)}))}:null), + ...(autoAdopted?.length?{autoAdopted}:null)}; if(progressSummary){ const {revision,passedScreens,unreviewedScreens,screensReadyForReview,screensWithOpenIssues,unfilledImageSlots}=progressSummary; result.progressSummary={revision, diff --git a/apps/detail-agent-pi/src/production-delegate.mjs b/apps/detail-agent-pi/src/production-delegate.mjs index 3d9e7354..0792887f 100644 --- a/apps/detail-agent-pi/src/production-delegate.mjs +++ b/apps/detail-agent-pi/src/production-delegate.mjs @@ -6,17 +6,24 @@ export function allocateWorkerNumber(used) { const delegatePools=new WeakMap(); -export function delegatePool(host,limit){ +export function delegatePool(host,initialLimit){ if(delegatePools.has(host))return delegatePools.get(host); const queue=[]; let active=0; + let limit=initialLimit; function startNext(){ - if(active>=limit||!queue.length)return; - active++; - queue.shift()(); + while(active0)active--; + startNext(); + } + function setLimit(nextLimit){ + if(!Number.isSafeInteger(nextLimit)||nextLimit<1)return; + limit=nextLimit; startNext(); } function acquire(signal){ @@ -24,10 +31,16 @@ export function delegatePool(host,limit){ return new Promise((resolve,reject)=>{ const start=()=>{ signal.removeEventListener('abort',cancel); - resolve(release); + let released=false; + resolve(()=>{ + if(released)return; + released=true; + release(); + }); }; const cancel=()=>{ - queue.splice(queue.indexOf(start),1); + const index=queue.indexOf(start); + if(index>=0)queue.splice(index,1); reject(signal.reason); }; signal.addEventListener('abort',cancel,{once:true}); @@ -35,7 +48,7 @@ export function delegatePool(host,limit){ startNext(); }); } - const pool={acquire}; + const pool={acquire,setLimit,activeCount:()=>active}; delegatePools.set(host,pool); return pool; } diff --git a/apps/detail-agent-pi/src/production-image-worker.mjs b/apps/detail-agent-pi/src/production-image-worker.mjs index 71c8f312..e9715430 100644 --- a/apps/detail-agent-pi/src/production-image-worker.mjs +++ b/apps/detail-agent-pi/src/production-image-worker.mjs @@ -7,14 +7,80 @@ import { productionOperationTools } from './production-tools.mjs'; import { validateWorkerArguments } from './worker-receipts.mjs'; import { normalizeToolArgs, toolSchema } from './tool-schema.mjs'; +const DEFAULT_SUBAGENT_KNOWLEDGE_MAX_BYTES = 36 * 1024; + +export function buildSubagentKnowledgeSlice(productionSkills, slot, { maxBytes = DEFAULT_SUBAGENT_KNOWLEDGE_MAX_BYTES } = {}) { + const slotRule = { + ...(slot?.fieldId ? { fieldId: slot.fieldId } : null), + ...(slot?.label ? { label: slot.label } : null), + ...(slot?.aspectRatio ? { aspectRatio: slot.aspectRatio } : null), + ...(slot?.sourcePolicy ? { sourcePolicy: slot.sourcePolicy } : null), + ...(slot?.productionRule ? { productionRule: slot.productionRule } : null), + ...(slot?.requirements ? { requirements: slot.requirements } : null), + ...(slot?.outputSpec ? { outputSpec: slot.outputSpec } : null), + }; + const docs = []; + const slice = { slotRule, docs }; + let usedBytes = Buffer.byteLength(JSON.stringify(slice), 'utf8'); + const memoryFiles = productionSkills?.memoryFiles; + if (!(memoryFiles instanceof Map) || !memoryFiles.size || usedBytes >= maxBytes) { + return slice; + } + const execution = productionSkills.execution ?? {}; + const prioritized = []; + const seen = new Set(); + const pushPath = filePath => { + if (typeof filePath !== 'string' || !filePath.trim() || seen.has(filePath)) return; + if (!filePath.endsWith('.md')) return; + seen.add(filePath); + prioritized.push(filePath); + }; + pushPath(execution.entrypoint); + pushPath(execution.supplement); + for (const override of execution.overrides ?? []) pushPath(override?.supplementPath); + for (const filePath of execution.packageDocs ?? []) pushPath(filePath); + for (const filePath of execution.docPaths ?? []) pushPath(filePath); + for (const filePath of memoryFiles.keys()) pushPath(filePath); + + for (const filePath of prioritized) { + const raw = memoryFiles.get(filePath); + if (!raw) continue; + const text = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw); + if (!text.trim()) continue; + const entry = { path: filePath, content: text }; + const entryBytes = Buffer.byteLength(JSON.stringify(entry), 'utf8') + (docs.length ? 1 : 0); + if (usedBytes + entryBytes <= maxBytes) { + docs.push(entry); + usedBytes += entryBytes; + continue; + } + const remaining = maxBytes - usedBytes - Buffer.byteLength(JSON.stringify({ path: filePath, content: '…' }), 'utf8') - (docs.length ? 1 : 0); + if (remaining > 128) { + let cut = text.slice(0, Math.floor(remaining / 3)); + while (cut.length > 0 && Buffer.byteLength(cut, 'utf8') > remaining) { + cut = cut.slice(0, Math.floor(cut.length * 0.8)); + } + if (cut.trim()) docs.push({ path: filePath, content: cut.toWellFormed() + '…' }); + } + break; + } + return slice; +} + export function productionImageWorker({ slot, goal, reworkCandidateId, pendingCopyFields, outputId, variantId, productTarget, row, - readCandidate, findSlot, current, getReferenceMode, getSlotRecord, readSlot, readImages, listProjectImages, + readCandidate, findSlot, current, getReferenceMode, getProductionSkills, getSlotRecord, readSlot, readImages, listProjectImages, liveSlot, slotDrawStatus, liveSlotCopy, runDetailAgent, notice, recordLocalCandidate, recordNoCandidate, dispatchEnqueued, useProductImage, transformImage, prepareImageRequest, preparedRequest, queueDispatch, }, delegateSignal) { - let rework, latestPrepared, produced=false; + let rework, latestPrepared, produced=false, activePermit=null; + const releasePermit=()=>{ + if(activePermit?.release){ + activePermit.release(); + activePermit.release=null; + } + }; const dispatched=new Set(); const workerTool=(name,execute,terminate=false)=>{ const [,description,schema]=productionOperationTools.find(([toolName])=>toolName===name); @@ -77,6 +143,7 @@ export function productionImageWorker({ const receipt=await queueDispatch(approval,request,activeSignal); const originalId=receipt.requestId??receipt.operationId; if(originalId)dispatched.add(originalId); + releasePermit(); await dispatchEnqueued(receipt.operationId); return receipt; },true), @@ -114,7 +181,8 @@ export function productionImageWorker({ return imageResult({...result,outputId,variantId,slotId:slot.id,fieldId:slot.fieldId, productReferences:productReferences(result.referenceCount,result.referenceBindings)}); }}; - async function run(){ + async function run(permit){ + activePermit=permit??null; row.step='正在准备'; notice('子代理正在制作'); const prior=getSlotRecord(); @@ -141,8 +209,9 @@ export function productionImageWorker({ const live=await liveSlot(); const status=slotDrawStatus(live); const referenceMode=getReferenceMode(); - const instructions='按锁定的企业 Skill 及小壹补充完成委托。完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例。首条消息提供实拍索引(productReferences/productReferenceIndex)与关键参考图;需查看完整实拍原图时调用 read_slot_images。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+ + const instructions='完成主代理委托的图位。knowledgeSlice 已内联当前图位规则、字段要求及核心短规则,无需重复 read 已内联文档。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例。首条消息提供实拍索引(productReferences/productReferenceIndex)与关键参考图;需查看完整实拍原图时调用 read_slot_images。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+ (rework?'\n附件含退回图、验图回执和上次实发提示词。reworkChange 记录改动。':''); + const knowledgeSlice=buildSubagentKnowledgeSlice(getProductionSkills?.(),slot); const screenCopy=await liveSlotCopy(); const references=await readReferences(['template-base','composition-only'].includes(referenceMode)) .catch(error=>({unavailable:error.message})); @@ -180,7 +249,7 @@ export function productionImageWorker({ delegateSignal.throwIfAborted(); await runDetailAgent(instructions, JSON.stringify({rework,goal,referenceMode,screenCopy,pendingCopyFields,target:{outputId,variantId,slotId:slot.id,...slotTarget(live)}, - product,productReferences:productIds,productReferenceIndex,referenceBindings,supplementalBindings,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools], + product,productReferences:productIds,productReferenceIndex,referenceBindings,supplementalBindings,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements,knowledgeSlice}),[readTool,...workerTools], attachments,productRequestScope('slot',slot.id),captions,delegateSignal); if(!produced)recordNoCandidate(); } diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 631a8f31..600298ff 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -56,9 +56,11 @@ export function preparedCandidateId(intent,values,operation){ return adopting?values.candidateId:values.useProductReference!==true?operation.operationId:null; } -export async function openProductionOperations(host,{target=host.productionContext ?? host.productionGoal,maxActiveDelegates=6, +export async function openProductionOperations(host,{target=host.productionContext ?? host.productionGoal,maxActiveDelegates:maxActiveDelegatesOption, maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000, tailWatchClock,callTool,awaitImageSlotsMs=180_000,canvasWaitMs=LOCAL_OPERATION_WAIT_MS,readOnly=false}={}) { + const hasExplicitMaxDelegates=maxActiveDelegatesOption!==undefined; + const maxActiveDelegates=maxActiveDelegatesOption??6; if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数'); if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数'); const {canvas,store}=host; @@ -95,20 +97,8 @@ export async function openProductionOperations(host,{target=host.productionConte } let slots=initialSlots; let plan=initialPlan; - const planRevisionKey=value=>{ - if(!value)return undefined; - const {creation,slots:slotsRev,canvas:canvasRev}=value.revisions??{}; - if(creation==null&&slotsRev==null&&canvasRev==null&&value.version==null)return undefined; - return JSON.stringify([creation??null,slotsRev??null,canvasRev??null,value.version??null]); - }; - const hasSlotRevision=value=>value?.revisions?.slots!=null; - const initialRevisionKey=planRevisionKey(initialPlan); - let slotsCache=initialRevisionKey!==undefined?{slots,revisionKey:initialRevisionKey}:null; - if(slotsCache&&!hasSlotRevision(initialPlan))queueMicrotask(()=>{slotsCache=null;}); - let planCache=initialPlan; - queueMicrotask(()=>{planCache=null;}); - const invalidateSlots=()=>{slotsCache=null;}; - const invalidatePlan=()=>{planCache=null;}; + const invalidateSlots=()=>{}; + const invalidatePlan=()=>{}; if(plan.productVariantId!==variantId)throw Error('当前图位不属于本轮制作花色'); let byId=new Map(slots.map(slot=>[slot.id,slot])); let byField=Map.groupBy(slots,slot=>slot.fieldId); @@ -174,17 +164,13 @@ export async function openProductionOperations(host,{target=host.productionConte }; const seenLayouts=new Set(); let seenProduct=false; - const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map(); + let seenPlanProduct=false; + const jobs=new Map(), generation=new Map(), reviewWork=new Set(); + const reportedCandidates=new Set(); const dispatchingImages=new Map(); const screenChecks=new Map(); - const filled=new Map(); - const refreshFilled=rows=>{ - filled.clear(); - for(const {id,selectedCandidateId,manualImage} of rows){ - if(manualImage || selectedCandidateId)filled.set(id,manualImage ? true : selectedCandidateId); - } - }; - refreshFilled(slots); + const liveFilledMap=rows=>new Map(rows.filter(r=>r.manualImage||r.selectedCandidateId).map(r=>[r.id,r.manualImage?true:r.selectedCandidateId])); + const refreshFilled=()=>{}; const waitingCanvas=new Map(); let suspendedCopy; const stageController=new AbortController(); @@ -261,26 +247,13 @@ export async function openProductionOperations(host,{target=host.productionConte const save=(slot,fields,records)=>update(journal=>{journal.items[slot.id]={...journal.items[slot.id],...fields};},records); let slotsFlight, planFlight; const liveSlots=async()=>{ - if(slotsCache){ - const latestPlan=await current(); - if(slotsCache&&planRevisionKey(latestPlan)===slotsCache.revisionKey){ - return slotsCache.slots; - } - } const live=await (slotsFlight??=readSlots().finally(()=>{slotsFlight=null;})); if(live.plan.productVariantId!==variantId||live.plan.template?.id!==plan.template?.id){ throw Error('当前模板或制作花色已变化,请读取当前项目'); } - const revisionKey=planRevisionKey(live.plan); - slotsCache=revisionKey!==undefined?{slots:live.slots,revisionKey}:null; - if(slotsCache&&!hasSlotRevision(live.plan)){ - const cached=slotsCache; - queueMicrotask(()=>{if(slotsCache===cached)slotsCache=null;}); - } slots=live.slots; byId=new Map(slots.map(slot=>[slot.id,slot])); byField=Map.groupBy(slots,slot=>slot.fieldId); - refreshFilled(slots); return slots; }; const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot; @@ -300,24 +273,19 @@ export async function openProductionOperations(host,{target=host.productionConte const readPlan=()=>canvasReady?scopedPlan():(planFlight??=trackCanvas(canvas.workflowRead({section:'overview',outputId})).finally(()=>{planFlight=null;})); let productUpdate; const current=async()=>{ - if(planCache)return planCache; const value=await readPlan(); if(value.outputId!==outputId||value.productVariantId!==variantId|| value.template?.id!==plan.template?.id){ throw Error('当前模板或制作花色已变化,请读取当前项目'); } - const revisionKey=planRevisionKey(value); - if(slotsCache&&revisionKey!==slotsCache.revisionKey)invalidateSlots(); if(productionInputs(value,variantId,productTarget)!==productionInputs(plan,variantId,productTarget)){ productUpdate={previousVersion:plan.revisions?.creation??plan.version, currentVersion:value.revisions?.creation??value.version,changedFields:changedProductionFields(plan,value,variantId,productTarget)}; seenProduct=false; + seenPlanProduct=false; markProgressDirty(); - invalidateSlots(); } plan=value; - planCache=value; - queueMicrotask(()=>{if(planCache===value)planCache=null;}); return value; }; const copySnapshot=async(options={})=>{ @@ -454,18 +422,25 @@ export async function openProductionOperations(host,{target=host.productionConte if(canvasReady||progressSnapshot.version!==progressVersion||epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return; } const {copyCells,summary}=progressSnapshot; - const {pictureCells,jobProgress}=productionImageProgress(slots,filled,journal,copyCells); + const {pictureCells,jobProgress}=productionImageProgress(slots,liveFilledMap(slots),journal,copyCells); const category=jobs.size?'remote_image':pendingReviews().length||runningScreens().length?'inference':'canvas_read'; await store.appendEvent({type:'production_progress',category,phase:'progress',status:'running',outputId,variantId,jobProgress}); const workers=new Map(); for(const {row} of jobs.values()){ if(!workers.has(row.slotId)||row.step!=='正在准备')workers.set(row.slotId,row); } + const candidateReviews=Object.fromEntries( + Object.entries(journal.items??{}).flatMap(([slotId,item])=>{ + const latest=item?.review; + if(!latest?.candidateId)return []; + return [[latest.candidateId,{slotId,status:latest.decision==='pass'?'passed':'rejected',reason:latest.reason}]]; + }), + ); return canvas.delta('',undefined,{heading,outputId,variantId,category,phase:'progress',status:'running', workers:[...workers.values()], reviews:pendingReviews().map(job=>job.row), checkingScreens:runningScreens().filter(job=>job.receipt.state==='checking').map(job=>job.receipt.page), - candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells,progressSummary:summary, + candidateReviews,pictureCells,copyCells,progressSummary:summary, ...jobProgress}); }; const display=new PresentationBatch(progress); @@ -537,7 +512,6 @@ export async function openProductionOperations(host,{target=host.productionConte throw error; } const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase; - if(state==='applied')filled.set(slot.id,operation.candidateId??values.candidateId); const pending=operation.phase==='unknown' ? {...prepared,candidateId:operation.candidateId??prepared.candidateId} : state==='applied'&&operation.persistence==='session'?prepared:null; @@ -577,8 +551,6 @@ export async function openProductionOperations(host,{target=host.productionConte Object.assign(item,{state:'candidate',candidateId:receipt.id,source}); } },{evidence:[slot.id,receipt.id,'candidate',receipt]}); - candidates.set(receipt.id,{slotId:slot.id,status:'complete'}); - invalidateSlots(); if(action==='transform')notice('画布调整已有候选'); else markProgressDirty(); return result; @@ -722,7 +694,6 @@ export async function openProductionOperations(host,{target=host.productionConte const reportRecoveryError=error=>console.warn('原图片请求核查失败',error.code??error.name); const recoverImage=createImageReconciler(canvas,{outputId,variantId},()=>journal,update,{ projectScope:()=>canvasReady?output:undefined, - onAdopted:(id,candidateId)=>filled.set(id,candidateId), onError:reportRecoveryError, }); const pendingNative=async()=> (await canvas.imageRequest('pending',{})).filter(row=> @@ -754,7 +725,7 @@ export async function openProductionOperations(host,{target=host.productionConte if(!tail)return {slotId:slot.id,phase:'none'}; const {adopting,request:{candidateId,operationId}}=tail; if(dispatchingImages.has(operationId))return {slotId:slot.id,candidateId,operationId,phase:'unknown'}; - const alreadyPlaced=adopting&&filled.get(slot.id)===candidateId; + const alreadyPlaced=adopting&&(byId.get(slot.id)?.selectedCandidateId===candidateId||Boolean(byId.get(slot.id)?.manualImage)); const receipt=await recoverImage(slot,adopting,signal); signal.throwIfAborted(); if(!adopting&&receipt.phase!=='none'){ @@ -765,13 +736,6 @@ export async function openProductionOperations(host,{target=host.productionConte const heading=receipt.resultExpiry?.source==='request_not_found' ? '网关没有原请求记录,按未发起处理' : recoveryNotices[receipt.phase]; if(heading&&!(receipt.phase==='complete'&&alreadyPlaced&&journal.items[slot.id]?.pendingAdoption)){ - if(receipt.candidateId){ - if(adopting&&receipt.phase==='complete'){ - candidates.set(receipt.candidateId,{...candidates.get(receipt.candidateId),slotId:slot.id,status:'adopted'}); - }else if(!adopting&&(!candidates.has(receipt.candidateId)||receipt.phase!=='complete')){ - candidates.set(receipt.candidateId,{slotId:slot.id,status:receipt.phase,reason:receipt.reason}); - } - } invalidateSlots(); markProgressDirty(); notice(heading); @@ -859,7 +823,6 @@ export async function openProductionOperations(host,{target=host.productionConte if((await liveSlot(slot)).selectedCandidateId===candidateId)await reuseCandidateScreen(entry,signal); }); } - candidates.set(candidateId,{slotId:slot.id,status:verdict==='pass'?'passed':'rejected',reason}); const reworkOf=live.candidates?.find(row=>row.id===candidateId)?.reworkOf ?? item?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; await store.appendEvent({type:'whole_detail_review',outputId,variantId,slotId:slot.id,fieldId:slot.fieldId, @@ -959,9 +922,7 @@ export async function openProductionOperations(host,{target=host.productionConte }, async unfinished(){return unfinished((await outstanding()).originals);}, readProjectPlan:async()=>({slots:await liveSlots(),template:plan.template}), - async plan_production({slotIds,includeKnowledge=false}={}){ - invalidatePlan(); - invalidateSlots(); + async plan_production({slotIds,includeKnowledge=false,includeProduct=false}={}){ await current(); const {requested,matched,unmatched}=readSelection(slotIds); const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId,outputId,productTarget); @@ -984,28 +945,63 @@ export async function openProductionOperations(host,{target=host.productionConte const {production,skillSources,resourceSetId,...template}=plan.template; const {outputId:workingOutputId,variantId:workingVariantId}=canvas.productionOutput??context; const snapshot=await copySnapshot({screenReviewFingerprints:screenReviewFingerprints(plan)}); + const omitProduct=seenPlanProduct&&!includeProduct&&!productUpdate&&!requested.size; + if(!omitProduct)seenPlanProduct=true; + const productPayload=omitProduct + ? {productEarlier:true,productSummary:{name,spu,brand,category,...(detailBarcode?{detailBarcode}:null), + variant:variant&&{id:variant.id,colorName:variant.colorName}}} + : {fieldRequirements:fieldRequirements(plan), + product:{name,spu,brand,category,dimensions,note,barcodeEntries,images,intake,barcodes, + variant:variant&&{id:variant.id,colorName:variant.colorName},...(detailBarcode?{detailBarcode}:null), + ...(platformFacts?{platformFacts}:null),...(normalizedProduct?{normalizedProduct}:null)}}; return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, - fieldConflicts:await fieldConflicts(snapshot,plan),fieldRequirements:fieldRequirements(plan), - template,product:{name,spu,brand,category,dimensions,note,barcodeEntries,images,intake,barcodes, - variant:variant&&{id:variant.id,colorName:variant.colorName},...(detailBarcode?{detailBarcode}:null), - ...(platformFacts?{platformFacts}:null),...(normalizedProduct?{normalizedProduct}:null)}, - candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures, + fieldConflicts:await fieldConflicts(snapshot,plan),...productPayload, + template,candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures, inFlightImages:(await pendingNative()).map(row=>row.candidateId), ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null), ...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null), requestedOutputs:context.requestedOutputs, pendingOutputs:context.pendingOutputs??[], - progressSummary:canvasReady?await progressSummary(plannedSlots):snapshot.progressSummary, + progressSummary:compactProgress(canvasReady?await progressSummary(plannedSlots):snapshot.progressSummary), ...(unmatched.length?{unmatched}:null)}; }, async read_copy_fields({pageId,fieldId}){ pageId=pageId?.trim()||undefined; fieldId=fieldId?.trim()||undefined; const snapshot=await trackCanvas(canvas.detailCopyFields({includeFilled:true,pageId,fieldId,targetOutput:output})); + const byFieldId=new Map(); + const byLayer=new Map(); + const skills=host.productionSkills; + const mappingPath=skills?.snapshot?.manifest?.bindings?.[outputId]?.mapping; + const mappingBuf=mappingPath?skills?.memoryFiles?.get(mappingPath):undefined; + if(mappingBuf){ + try { + const parsed=JSON.parse(Buffer.isBuffer(mappingBuf)?mappingBuf.toString('utf8'):String(mappingBuf)); + for(const item of parsed?.fields??[]){ + const req=[item.purpose,item.fill_requirements,item.adaptation_requirements,item.output_spec,item.rules].filter(Boolean).join('\n'); + if(!req)continue; + if(item.field_id)byFieldId.set(item.field_id,req); + const layerId=item.ps_location?.layer_id; + if(layerId!=null)byLayer.set(layerId,req); + } + } catch { /* ignore malformed mapping */ } + } + for(const req of Object.values(journal.fieldRequirements??{})){ + const text=req.requirements??req.basis??req.rules; + if(!text)continue; + if(req.field&&!byFieldId.has(req.field))byFieldId.set(req.field,text); + if(req.layer!=null&&!byLayer.has(req.layer))byLayer.set(req.layer,text); + } const fields=snapshot.fields?.map(row=>{ const {nativeFrame,textSafeFrame,styleRoles,relatedFields,...summary}=row; const field=pageId||fieldId?row:summary; - return field.fieldId===undefined&&field.field!==undefined?{...field,fieldId:field.field}:field; + const resolvedId=field.fieldId??field.field; + const requirements=field.requirements??byFieldId.get(resolvedId)??byLayer.get(field.layer); + return { + ...field, + ...(field.fieldId===undefined&&field.field!==undefined?{fieldId:field.field}:null), + ...(requirements?{requirements}:null), + }; }); return {...snapshot,outputId,variantId,fields}; }, @@ -1114,6 +1110,9 @@ export async function openProductionOperations(host,{target=host.productionConte const liveById=new Map((await liveSlots()).map(slot=>[slot.id,slot])); const statuses=drawStatuses([...liveById.values()]); const resolved=requested.map(job=>({...job,slot:findSlot(job.slotId)})); + if(!hasExplicitMaxDelegates&&resolved.length>8){ + pool.setLimit?.(Math.min(12,Math.max(maxActiveDelegates,Math.ceil(resolved.length/2)))); + } const pendingCopy=await pendingCopyBySlot(resolved.map(job=>job.slot).filter(Boolean)); for(const {slotId,goal,reworkCandidateId,slot} of resolved){ if(!slot){unmatched.push({slotId,reason:slotNotFound});continue;} @@ -1130,6 +1129,7 @@ export async function openProductionOperations(host,{target=host.productionConte slot,goal,reworkCandidateId,pendingCopyFields,outputId,variantId,productTarget,row, readCandidate,findSlot,current,slotDrawStatus,notice, getReferenceMode:()=>productionSettings(store,plan.template.production).referenceMode, + getProductionSkills:()=>host.productionSkills, getSlotRecord:()=>journal.items[slot.id], readSlot:async()=>(await readSlots()).slots.find(next=>next.id===slot.id)??slot, readImages:args=>readImages(slot.id,args), @@ -1175,7 +1175,7 @@ export async function openProductionOperations(host,{target=host.productionConte return {assigned,...(unmatched.length?{unmatched}:null), ...(assigned.some(row=>row.pendingCopyFields)?{copyContext:'待写字段的 templateExample 是模板样例。子代理收到 goal 和本屏实时文案。'}:null)}; }, - async await_image_slots({slotIds,requestId,requestIds,operationId,operationIds,waitForAll},signal){ + async await_image_slots({slotIds,requestId,requestIds,operationId,operationIds,waitForAll,autoAdopt},signal){ signal?.throwIfAborted(); const startedAt=performance.now(); const wanted=new Set(selections(slotIds).map(slot=>slot.id)); @@ -1225,9 +1225,33 @@ export async function openProductionOperations(host,{target=host.productionConte const key=row.candidateId?JSON.stringify([row.slotId,row.candidateId,row.phase]):row; if(!distinct.has(key))distinct.set(key,row); } - return summarizeImageWait({...output,budget:{remainingMinutes,reached},active:jobs.size,checking:pendingReviews().length,progressSummary:summary, - generation:[...distinct.values()] - .map(row=>({...row,target:targets.get(row.slotId)??row.target})), + const generationList=[...distinct.values()].map(row=>({...row,target:targets.get(row.slotId)??row.target})); + const incrementalUpdates=generationList.filter(row=> + row.candidateId&&settledImagePhases.includes(row.phase)&&!reportedCandidates.has(row.candidateId)); + for(const row of incrementalUpdates)reportedCandidates.add(row.candidateId); + const shouldAutoAdopt=autoAdopt===true||(autoAdopt!==false&&(context.autoAdopt===true||productionSettings(store,plan.template?.production).autoAdopt===true)); + const autoAdopted=[]; + if(shouldAutoAdopt&&!canvasReady){ + const liveBySlot=new Map(live.map(s=>[s.id,s])); + for(const row of incrementalUpdates){ + if(row.phase!=='complete')continue; + const targetSlot=liveBySlot.get(row.slotId); + if(!targetSlot||targetSlot.selectedCandidateId||targetSlot.manualImage)continue; + const completeCandidates=(targetSlot.candidates??[]).filter(c=>c.status==='complete'); + const record=journal.items[targetSlot.id]; + const passed=record?.review?.candidateId===row.candidateId&&record?.review?.decision==='pass'|| + record?.approvals?.some(a=>a.candidateId===row.candidateId); + if(completeCandidates.length===1||passed){ + const adopted=await operations.adopt_production_image({slotId:targetSlot.id,candidateId:row.candidateId,reason:passed?'自动落位:验图通过':'自动落位:单一明确候选'},signal) + .catch(error=>({slotId:targetSlot.id,candidateId:row.candidateId,phase:'failed',reason:error.message})); + autoAdopted.push({slotId:targetSlot.id,candidateId:row.candidateId,phase:adopted.phase,reason:adopted.reason}); + } + } + } + return summarizeImageWait({...output,budget:{remainingMinutes,reached},active:jobs.size,checking:pendingReviews().length,progressSummary:compactProgress(summary), + generation:generationList, + ...(incrementalUpdates.length?{incrementalUpdates}:null), + ...(autoAdopted.length?{autoAdopted}:null), checks:ids?[]:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt), ...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null), ...(pending.length||timedOut?{pendingWork:pendingWork()}:null), @@ -1325,11 +1349,12 @@ export async function openProductionOperations(host,{target=host.productionConte return receipt; }); }, - async check_image_slots({candidates:requested,wait=false},signal){ + async check_image_slots({candidates:requested,wait=false,autoAdopt},signal){ const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal; activeSignal.throwIfAborted(); const live=await liveSlots(); const statuses=drawStatuses(live); + const shouldAutoAdopt=autoAdopt===true||(autoAdopt!==false&&(context.autoAdopt===true||productionSettings(store,plan.template?.production).autoAdopt===true)); const batch=requested.map(({slotId,candidateId,adopted,fit})=>{ if(canvasReady&&adopted)return {receipt:{slotId,candidateId,accepted:false,reason:'canvas_inactive'}}; const slot=findLiveSlot(live,slotId); @@ -1343,8 +1368,17 @@ export async function openProductionOperations(host,{target=host.productionConte row.step='正在验图'; return check(slot,candidateId,adopted,fit,activeSignal,row); }) - .catch(error=>({slotId:slot.id,candidateId,error:error.message})).then(receipt=>{ - job.receipt={...receipt,...slotDrawStatus(slot)}; + .catch(error=>({slotId:slot.id,candidateId,error:error.message})).then(async receipt=>{ + let autoAdopted; + if(shouldAutoAdopt&&!canvasReady&&!adopted&&(receipt.verdict==='pass'||receipt.accepted===true)){ + const latestSlot=await liveSlot(slot).catch(()=>slot); + if(!latestSlot.selectedCandidateId&&!latestSlot.manualImage){ + const res=await operations.adopt_production_image({slotId:slot.id,candidateId,reason:'自动落位:验图通过'},activeSignal) + .catch(error=>({phase:'failed',reason:error.message})); + autoAdopted={slotId:slot.id,candidateId,phase:res.phase,reason:res.reason}; + } + } + job.receipt={...receipt,...(autoAdopted?{autoAdopted}:null),...slotDrawStatus(slot)}; return job.receipt; }).finally(()=>{ job.run=null; @@ -1365,13 +1399,12 @@ export async function openProductionOperations(host,{target=host.productionConte const entry=journal.items[slot.id]?.reviewHistory?.findLast(row=>row.candidateId===candidateId&&row.screenReview); try { const screenReview=await reuseCandidateScreen(entry,signal); - const summary=await progressSummary(); + const summary=compactProgress(await progressSummary()); return {...adopted,...(screenReview?{screenReview}:null),progressSummary:summary,screensReadyForReview:summary?.screensReadyForReview??[]}; } catch(error) { return {...adopted,screenReviewError:error.message}; } }),undefined,{slotId:slot.id,label:slot.label}); - if(result.phase==='complete'&&candidates.has(candidateId))candidates.get(candidateId).status='adopted'; invalidateSlots(); invalidatePlan(); markProgressDirty(); @@ -1394,10 +1427,8 @@ export async function openProductionOperations(host,{target=host.productionConte if(item.candidateReviews)delete item.candidateReviews[candidateId]; if(item.candidateId===candidateId&&!item.pendingOperation&&!item.pendingAdoption){ item.state='retired'; - if(result.canvasLayerId)filled.delete(slot.id); } },{evidence:[slot.id,candidateId,'retirement',{...result,reason}]}); - candidates.delete(candidateId); host.generatedCandidates?.delete(candidateId); markProgressDirty(); await store.appendEvent({type:'production_image_retired',slotId:slot.id,candidateId,reason,requestId:result.requestId}); diff --git a/apps/detail-agent-pi/src/production-tools.mjs b/apps/detail-agent-pi/src/production-tools.mjs index 47ca62dc..4aeacdad 100644 --- a/apps/detail-agent-pi/src/production-tools.mjs +++ b/apps/detail-agent-pi/src/production-tools.mjs @@ -16,7 +16,7 @@ export const productionOperationTools = [ referenceMode:optional(StringEnum(['template-base', 'composition-only', 'none'])), mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1})), })], - ['plan_production','读取商品、模板、进度和设置,默认当前工作画布。projectSlots 按成品和花色列出屏、图框像素、模板主体和候选号。framePending 表示图框像素暂取模板值。adoptionRecorded 为采用记录,selectedCandidateId 为画布当前采用。用回执的 slotId 填入 slotIds 查询图位发布要求。includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。mode、budget、limits 分别是制作模式、预算时间(含已用和剩余)和候选上限。candidateCount、candidatesRemaining 为已用及剩余候选数,copyReady 为关联文案就绪状态。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})], + ['plan_production','读取商品、模板、进度和设置,默认当前工作画布。projectSlots 按成品和花色列出屏、图框像素、模板主体和候选号。framePending 表示图框像素暂取模板值。adoptionRecorded 为采用记录,selectedCandidateId 为画布当前采用。用回执的 slotId 填入 slotIds 查询图位发布要求。includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。mode、budget、limits 分别是制作模式、预算时间(含已用和剩余)和候选上限。candidateCount、candidatesRemaining 为已用及剩余候选数,copyReady 为关联文案就绪状态。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean()),includeProduct:optional(Type.Boolean())})], ['read_copy_fields','省略 pageId 和 fieldId 返回全页字段身份、当前文字、约束及修订号;指定页面或字段可读取图层样式、范围及关联字段。',obj({ ...outputScope, pageId:optional(Type.String()),fieldId:optional(Type.String()), @@ -39,7 +39,7 @@ export const productionOperationTools = [ ...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], ['await_image_slots','按派发回执的 requestId、requestIds 或按 slotIds 等待。主代理可等待制作、验图和生图,子代理查看本次委托的生图请求。waitForAll=true 等待全部匹配的在途工作,单次最多 3 分钟,超时工作继续。主代理不指定编号时也查看整屏复核。未知结果用 reconcile_image_slots。',obj({ - ...outputScope,slotIds:optional(ids),requestId:optional(text),requestIds:optional(ids),waitForAll:optional(Type.Boolean()), + ...outputScope,slotIds:optional(ids),requestId:optional(text),requestIds:optional(ids),waitForAll:optional(Type.Boolean()),autoAdopt:optional(Type.Boolean()), })], ['review_image_slots','查看指定成品和花色的候选、验图、原请求、覆盖及整屏进度。screensReadyForReview 为图位已齐的待验多图位屏。slotIds 查看详情,单图位配合 candidateId 查看像素。按 nextOffset 翻页,单图位看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),candidateId:optional(text),offset:optional(Type.Integer({minimum:0}))})], ['list_project_images','列出本项目已完成且可读的候选,包括已采用图。可按成品和花色筛选。同花色候选可把 candidateId 传给 transform_slot_image 跨成品变换。按 nextOffset 翻页,candidateId 展开单条。',obj({...outputScope,candidateId:optional(Type.String()),offset:optional(Type.Integer({minimum:0}))})], @@ -50,7 +50,7 @@ export const productionOperationTools = [ ...outputScope,slotId:slotRef,projectId:optional(Type.String()),candidateId:text, })], ['check_image_slots','请验图代理按企业 Skill 比较候选原图和放入后的整屏。复核输入包含当前图位关联文案。模板底图候选附固定图位原图,fit 可指定预览放置方式。默认先受理,用 review_image_slots 查看结论。',obj({ - ...outputScope,wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean()),fit:optional(fit)})), + ...outputScope,wait:optional(Type.Boolean()),autoAdopt:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean()),fit:optional(fit)})), })], ['adopt_production_image','采用选定候选,返回画布修订、模板叠层。单图位屏与已有验图画面一致时附复核结论。可用 reason 记录采用理由。screensReadyForReview 列出待验多图位屏,可用 read_output_screen 查看整屏合成画面。',obj({...outputScope,...slotAddress,candidateId:text,fit:optional(fit),reason:optional(text)})], ['retire_production_image','清理已判失败的图位候选,保留原因、提示词及原请求记录。若已上画布,返回应替换的图层。',obj({...outputScope,slotId:slotRef,candidateId:text,reason:text})], diff --git a/apps/detail-agent-pi/test/thin-harness-wave2a.test.mjs b/apps/detail-agent-pi/test/thin-harness-wave2a.test.mjs index 4f2ca889..4f8a4118 100644 --- a/apps/detail-agent-pi/test/thin-harness-wave2a.test.mjs +++ b/apps/detail-agent-pi/test/thin-harness-wave2a.test.mjs @@ -127,7 +127,7 @@ test('Wave 2A: worker session enables context compaction instead of hard-disabli assert.doesNotMatch(agentSource, /workerSettings\s*=\s*SettingsManager\.inMemory\([^)]*compaction:\s*\{\s*enabled:\s*false\s*\}/); }); -test('Wave 2A: production operations cache liveSlots/current/progressSummary across reads and invalidate on write', async t => { +test('Wave 2A: production operations read live slots directly without stale cache and reflect writes immediately', async t => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-w2a-cache-')); t.after(() => cleanup(dir)); @@ -181,7 +181,7 @@ test('Wave 2A: production operations cache liveSlots/current/progressSummary acr await ops.review_image_slots({}); await ops.review_image_slots({ slotIds: ['D01'] }); - assert.equal(slotPageReads, initialSlotPageReads, 'consecutive reads at same revision should reuse cached slots'); + assert.ok(slotPageReads > initialSlotPageReads, 'consecutive reads read live canvas state directly without stale slotsCache'); await ops.plan_production({}); assert.equal(copyReads, 3, 'plan_production should use a single copySnapshot call for fieldConflicts and progressSummary'); diff --git a/apps/detail-agent-pi/test/thin-speed-124.test.mjs b/apps/detail-agent-pi/test/thin-speed-124.test.mjs new file mode 100644 index 00000000..e1f68043 --- /dev/null +++ b/apps/detail-agent-pi/test/thin-speed-124.test.mjs @@ -0,0 +1,229 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { buildSubagentKnowledgeSlice, productionImageWorker } from '../src/production-image-worker.mjs'; +import { foldSupersededProductionReads } from '../src/context-usage.mjs'; +import { openProductionOperations } from '../src/production-operations.mjs'; +import { delegatePool } from '../src/production-delegate.mjs'; +import { resolveRoleModelSelection } from '../src/agent.mjs'; +import { productionStore } from './production-store-fixture.mjs'; + +test('buildSubagentKnowledgeSlice stays under 40KB, includes slot rules and skips huge JSONs', () => { + const memoryFiles = new Map([ + ['规则/SKILL.md', Buffer.from('# 模板指引\n保持木纹一致')], + ['规则/无人值守补充说明.md', Buffer.from('补充:实拍优先')], + ['共用/模板原图换商品.md', Buffer.from('换商品规则:' + '要点。'.repeat(200))], + ['规则/字段映射.json', Buffer.from('{"fields":' + 'x'.repeat(500_000) + '}')], + ['规则/超大文档.md', Buffer.from('冗长说明:' + '段落。'.repeat(25_000))], + ]); + const productionSkills = { + memoryFiles, + execution: { + entrypoint: '规则/SKILL.md', + supplement: '规则/无人值守补充说明.md', + docPaths: ['共用/模板原图换商品.md', '规则/超大文档.md'], + }, + }; + const slot = { + id: 'slot-1', + fieldId: 'S01-I01', + label: '首屏主图', + aspectRatio: '3:4', + sourcePolicy: 'generate', + productionRule: { source: 'generate', focus: '突出实木纹理' }, + requirements: '保持椅背弧度一致', + }; + const slice = buildSubagentKnowledgeSlice(productionSkills, slot); + const bytes = Buffer.byteLength(JSON.stringify(slice), 'utf8'); + assert.ok(bytes < 40 * 1024, `expected < 40KB, got ${bytes}`); + assert.equal(slice.slotRule.fieldId, 'S01-I01'); + assert.equal(slice.slotRule.requirements, '保持椅背弧度一致'); + assert.ok(slice.docs.some(d => d.path === '规则/SKILL.md')); + assert.ok(slice.docs.some(d => d.path === '规则/无人值守补充说明.md')); + assert.ok(!slice.docs.some(d => d.path.endsWith('.json'))); +}); + +test('foldSupersededProductionReads trims historical screens and large tool results under 150KB while preserving userCanvasChanges', () => { + const messages = []; + for (let i = 0; i < 14; i++) { + messages.push({ + role: 'assistant', + content: [{ type: 'toolCall', id: `call-${i}`, name: 'read_output_screen', arguments: { page: i } }], + }); + messages.push({ + role: 'toolResult', + toolCallId: `call-${i}`, + toolName: 'read_output_screen', + details: { outputId: 'detail', variantId: 'oak', page: i, screenFingerprint: `fp-${i}` }, + content: [ + { type: 'text', text: JSON.stringify({ page: i, screenFingerprint: `fp-${i}`, textClipping: 0, payload: 'x'.repeat(12_000) }) }, + ...(i === 3 ? [{ type: 'text', text: JSON.stringify({ userCanvasChanges: [{ slotId: 'S04-I01', manual: true }] }) }] : []), + ], + }); + } + const folded = foldSupersededProductionReads(messages); + const totalBytes = Buffer.byteLength(JSON.stringify(folded), 'utf8'); + assert.ok(totalBytes < 150 * 1024, `expected folded context < 150KB, got ${totalBytes}`); + const preservedTurn = folded.find(m => m.toolCallId === 'call-3'); + assert.ok(preservedTurn.content.some(b => b.text.includes('userCanvasChanges'))); + const newestTurn = folded.find(m => m.toolCallId === 'call-13'); + assert.ok(newestTurn.content[0].text.includes('payload')); +}); + +test('read_copy_fields attaches field requirements and plan_production avoids repeating full product brief', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-copy-')); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const mapping = { + fields: [ + { field_id: 'S01-T01', purpose: '核心卖点', fill_requirements: '不超过12字', ps_location: { layer_id: 101 } }, + ], + }; + const host = { + store: productionStore(dir), + productionGoal: { outputId: 'detail', variantId: 'oak' }, + productionSkills: { + snapshot: { manifest: { bindings: { detail: { mapping: '规则/字段映射.json' } } } }, + memoryFiles: new Map([['规则/字段映射.json', Buffer.from(JSON.stringify(mapping))]]), + }, + canvas: { + workflowRead: async () => ({ + available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', totalSlots: 1, + template: { id: 'tpl', contentHash: 'hash1' }, + productEvidence: { brief: { name: '实木餐椅', spu: 'CHR-01', note: '长备注'.repeat(500) } }, + slots: [{ id: 'slot-1', fieldId: 'S01-I01', label: '主图' }], + }), + detailCopyFields: async () => ({ + revision: 1, + pages: ['P01'], + fields: [{ field: 'S01-T01', layer: 101, label: '标题', currentText: '原样例' }], + }), + imageRequest: async () => [], + }, + }; + const ops = await openProductionOperations(host); + const copyRes = await ops.read_copy_fields({}); + assert.equal(copyRes.fields[0].requirements, '核心卖点\n不超过12字'); + + const firstPlan = await ops.plan_production({}); + assert.ok(firstPlan.product.note); + const secondPlan = await ops.plan_production({}); + assert.equal(secondPlan.productEarlier, true); + assert.equal(secondPlan.product, undefined); + assert.equal(secondPlan.productSummary.name, '实木餐椅'); +}); + +test('delegatePool releases slot during dispatchEnqueued wait and await_image_slots supports incremental updates & autoAdopt', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-pool-')); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const poolHost = {}; + const pool = delegatePool(poolHost, 1); + const ac = new AbortController(); + const release1 = await pool.acquire(ac.signal); + let secondStarted = false; + const p2 = pool.acquire(ac.signal).then(rel => { secondStarted = true; rel(); }); + assert.equal(secondStarted, false); + release1(); + await p2; + assert.equal(secondStarted, true); + + // Test worker permit release before dispatchEnqueued + const enqueueGate = Promise.withResolvers(); + let permitReleased = false; + const worker = productionImageWorker({ + slot: { id: 'slot-1', fieldId: 'S01', label: '主图' }, + goal: '生成主图', + outputId: 'detail', + variantId: 'oak', + row: { step: '正在准备' }, + readCandidate: async () => ({}), + findSlot: () => ({ id: 'slot-1' }), + current: async () => ({ revisions: {} }), + getReferenceMode: () => 'none', + getSlotRecord: () => undefined, + readSlot: async () => ({ id: 'slot-1' }), + readImages: async () => ({ images: [] }), + listProjectImages: async () => [], + liveSlot: async () => ({ id: 'slot-1' }), + slotDrawStatus: () => ({ generationAttempts: 0, maxGenerationAttempts: 4, remainingGenerationAttempts: 4, drawLimitReached: false }), + liveSlotCopy: async () => [], + notice: () => {}, + recordLocalCandidate: () => {}, + recordNoCandidate: () => {}, + dispatchEnqueued: () => enqueueGate.promise, + preparedRequest: async () => ({ requestId: 'req-1', phase: 'prepared' }), + queueDispatch: async () => ({ requestId: 'req-1', operationId: 'req-1', phase: 'accepted' }), + runDetailAgent: async (_inst, _prompt, tools) => { + const dispatchTool = tools.find(t => t.name === 'dispatch_image_request'); + const runPromise = dispatchTool.execute('id', { requestId: 'req-1' }, ac.signal); + await new Promise(r => setTimeout(r, 20)); + assert.equal(permitReleased, true, 'permit should be released before dispatchEnqueued resolves'); + enqueueGate.resolve(); + await runPromise; + }, + }, ac.signal); + await worker.run({ release: () => { permitReleased = true; } }); +}); + +test('liveSlots reads fresh canvas state without stale cache and autoAdopt places sole candidate', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-live-')); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + let currentSlot = { id: 'slot-1', fieldId: 'S01', label: '主图', candidates: [] }; + let adoptedCalls = 0; + const host = { + store: productionStore(dir), + productionGoal: { outputId: 'detail', variantId: 'oak' }, + canvas: { + read: async () => ({ revision: 10 }), + requestWrite: async () => ({ allowed: true, revision: 10 }), + workflowRead: async () => ({ + available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', totalSlots: 1, + revisions: { creation: 1, slots: 1, canvas: 1 }, + template: { id: 'tpl', contentHash: 'hash1' }, + slots: [currentSlot], + }), + detailCopyFields: async () => ({ revision: 1, pages: ['P01'], fields: [] }), + imageRequest: async () => [], + workflowExecute: async args => { + if (args.intent === 'adopt_candidate') { + adoptedCalls++; + currentSlot = { ...currentSlot, selectedCandidateId: args.candidateId }; + return { operationId: args.operationId, phase: 'complete', candidateId: args.candidateId }; + } + return { operationId: args.operationId, phase: 'complete' }; + }, + }, + }; + const ops = await openProductionOperations(host); + // External canvas change without any JS invalidation call + currentSlot = { id: 'slot-1', fieldId: 'S01', label: '主图', candidates: [{ id: 'cand-1', status: 'complete' }] }; + const waited = await ops.await_image_slots({ slotIds: ['slot-1'], autoAdopt: true }); + assert.equal(waited.incrementalUpdates.length, 1); + assert.equal(waited.incrementalUpdates[0].candidateId, 'cand-1'); + assert.equal(waited.autoAdopted.length, 1); + assert.equal(waited.autoAdopted[0].candidateId, 'cand-1'); + assert.equal(adoptedCalls, 1); +}); + +test('resolveRoleModelSelection falls back transparently and routes configured roles', () => { + const base = { id: 'claude-sonnet', protocol: 'anthropic-messages', contextWindow: 200_000, contextWindowSource: 'catalog' }; + assert.equal(resolveRoleModelSelection({ model: base }, 'imageDelegate'), base); + assert.equal(resolveRoleModelSelection({ model: base, roleModels: {} }, 'review'), base); + + const info = { + model: base, + roleModels: { + imageDelegate: { id: 'glm-flash', protocol: 'openai-chat' }, + review: { id: 'gemini-pro', protocol: 'google-generative-ai', contextWindow: 1_000_000, contextWindowSource: 'explicit' }, + }, + }; + const delegateModel = resolveRoleModelSelection(info, 'imageDelegate'); + assert.equal(delegateModel.id, 'glm-flash'); + assert.equal(delegateModel.protocol, 'openai-chat'); + assert.equal(delegateModel.contextWindow, undefined); + + const reviewModel = resolveRoleModelSelection(info, 'review'); + assert.equal(reviewModel.id, 'gemini-pro'); + assert.equal(reviewModel.contextWindow, 1_000_000); +});