小壹整屏叠层复核与制作请求瘦身

This commit is contained in:
WuYongJie 2026-11-27 18:11:32 +08:00
parent 120ee36597
commit 9c2caf3110
10 changed files with 260 additions and 117 deletions

View File

@ -1,5 +1,6 @@
import {setTimeout as delay} from 'node:timers/promises';
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs';
import { enterpriseTools } from './enterprise-knowledge.mjs';
import { executeWorkflow } from './workflow-execute.mjs';
@ -15,7 +16,7 @@ import { protectSession, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal,
mayContinueProductionGoal } from './production-goal.mjs';
import { productionVideoTools } from './production-operations.mjs';
import { DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
import { COPY_IMAGE_OVERLAY_GUIDANCE, DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
import { Agent, runToolCall } from '@earendil-works/pi-agent-core';
import { createAgentSession, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
import { retryAssistantCall } from '@earendil-works/pi-ai';
@ -31,7 +32,7 @@ import { EnterpriseContext } from './enterprise-context.mjs';
import { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { projectTools } from './project-tools.mjs';
import { responseUsage } from './usage.mjs';
import { contextSnapshot, modelCapacity, contextTextLength } from './context-usage.mjs';
import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs';
import { activityScope, activitySummary, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { nativeTools } from './native-tools.mjs';
@ -83,6 +84,7 @@ ${DRAW_LIMIT_GUIDANCE}
- 指向引线的端点圆点是否落在新商品对应的材质或结构部位,引导文字是否贴边或压线。有偏差就挪正。
- 尺寸标注线、端点、数值与文字是否贴合新商品轮廓且无压边。有偏差就按本款资料改正标注文案,重新对齐标注图层。
- 改字后文案是否溢出位图格子或底框,下划线、角标、圆点、高亮块等重点标识是否仍对准当前文字。有偏差就按需改字和重对齐。
${COPY_IMAGE_OVERLAY_GUIDANCE}
发现问题直接用原生画布工具修正,可用 native_catalog 查命令并用 native_call 直接改冲突文字层、调整结构线、引线与尺寸标注。读取画布找到对应图层;已映射文字也可用 write_copy_fields。图文不一致时,按商品资料自主选择修正文案、裁切或调整构图、围绕卖点重做图片。调整后用 read_output_screen 复看实际像素,确认修正及图文一致性。
需要独立观察结果的工具(如 open_production_output、read_output_screen、await_image_slots、finish_production)单独调用。多项连续查目录、批量采纳、批量回填文案及图层隐藏、选择、变换、样式修正等确定性操作,优先合并在一次 codemode 脚本中依次 await,使用各步实际回执衔接后续操作。
常用原生画布命令:document.inspect、layer.list、layer.select、layer.hideLayers、layer.showLayers、layer.translate、layer.setProps、type.info、type.edit、type.setStyle、edit.transform、layer.layerStyle.colorOverlay。需要参数格式时用 native_catalog({ ids: [...] }) 一次取齐,在本回合和后续回合复用已取得的 parameterDocs,按目录确认命令和字段。
@ -91,6 +93,24 @@ transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同
逐屏复核后用 record_screen_check 登记实际结果,改字或换图后复看受影响的屏。复核后用 finish_production 提交当前画布修订,以工具返回的文件和版本为交付依据。可随时用 open_production_output 切换其它成品或回到此前的草稿。收口时用 finish_production 的 scope=all 核验本轮交付。子代理正在运行时可用 await_image_slots 等待回执。已返回结果未知的生图请求用 reconcile_image_slots 按原编号核查,核查期间可继续其它可做的图位和画布编辑。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
function imageLengthSummary(data, start = 0) {
const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
const bytes = Math.floor((data.length - start - padding) * 3 / 4);
return `[image-base64-omitted:${bytes}B]`;
}
function summarizePayloadImages(value) {
if (typeof value === 'string' && value.startsWith('data:image/')) {
const comma = value.indexOf(',');
if (comma !== -1 && value.startsWith(';base64,', comma - 7)) return imageLengthSummary(value, comma + 1);
}
if (Array.isArray(value)) return value.map(summarizePayloadImages);
if (!value || typeof value !== 'object') return value;
if ((value.type === 'image' || value.type === 'base64' && value.media_type?.startsWith('image/')) && typeof value.data === 'string') {
return {...value, data: imageLengthSummary(value.data)};
}
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, summarizePayloadImages(item)]));
}
// Both shapes are native projections of the frozen request, never the live selection.
const frozenReferences = context => Array.isArray(context?.requestScope?.references)
? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined;
@ -433,11 +453,11 @@ export class DetailPiAgent {
host.currentCanvas = liveCanvas?.context;
const encoded = protocolMode === 'structured-json' && !host.compacting;
const wireContext = encoded ? jsonToolContext(context) : context;
const inputChars = contextTextLength(wireContext);
const {textChars: inputChars, totalChars} = contextLengths(wireContext);
if (!host.compacting) await host.updateContextUsage(null, 'running');
host.rounds++;
if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`);
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: JSON.stringify(context).length });
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: encoded ? contextLengths(context).totalChars : totalChars });
if (transport?.stream) {
const stream = transport.stream(model, wireContext, options);
for await (const event of stream) output.push(event);
@ -475,8 +495,9 @@ export class DetailPiAgent {
if (encoded && api === 'openai-completions') payload.response_format = { type: 'json_object' };
if (encoded && api === 'openai-responses') payload.text = { format: { type: 'json_object' } };
// Private project evidence: BODY ONLY, never the fetch headers or API Key.
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(payload),
const archivedPayload = process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1' ? payload : summarizePayloadImages(payload);
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), archivedPayload);
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(archivedPayload),
promptCacheKeyPresent:typeof payload.prompt_cache_key==='string' });
return payload;
},
@ -596,7 +617,7 @@ export class DetailPiAgent {
/^product\/(review|compare|copy-audit|strategy|strategy-audit)\//.test(requestScope)) ? taskTools[0].name : null;
const autoOnly = productionUsesAutomaticTools(info.model);
const toolChoice = autoOnly ? 'auto' : requiredTool ? (singleTool ? 'required' : namedTool(requiredTool)) : undefined;
const used = new Map();
let previousToolCall, consecutiveToolCalls = 0;
let pendingError;
const [scopeKind, step] = requestScope.split('/');
const workerKind = scopeKind === 'product' ? step : taskTools[0]?.name ?? 'detail';
@ -625,10 +646,10 @@ export class DetailPiAgent {
});
agent.beforeToolCall=async ({toolCall})=>{
if(productionSignal?.aborted)return {block:true,terminate:true,reason:'原制作回合已停止'};
const key=JSON.stringify([toolCall.name,toolCall.arguments]);
const count=(used.get(key)??0)+1;
used.set(key,count);
if(count>2)return {block:true,terminate:true,reason:'同一操作已返回结果,请保留当前图位记录'};
const repeated = toolCall.name === previousToolCall?.name && isDeepStrictEqual(toolCall.arguments,previousToolCall.arguments);
consecutiveToolCalls = repeated ? consecutiveToolCalls + 1 : 1;
previousToolCall = toolCall;
if(consecutiveToolCalls>8)return {block:true,reason:'同一工具和参数已连续调用 8 次,请根据已有回执调整操作或提交当前结果'};
};
agent.streamFunction=(selected,context,options={})=>{
if(transport?.stream) return transport.stream(selected,context,options);

View File

@ -1,5 +1,4 @@
import { Type } from '@sinclair/typebox';
import { knowledgeReadInstruction } from './production-knowledge.mjs';
import { productionUsesAutomaticTools, productRequestScope, ProductionRequestFailed } from './production-recovery.mjs';
import { InvalidToolReply } from './response-audit.mjs';
import { COPY_IMAGE_REVIEW_GUIDANCE, mergeReviewCopy } from './copy-image-alignment.mjs';
@ -36,15 +35,17 @@ export function readAutoAdoptionPolicy(policy) {
}
export function decideCandidateSet(policy, requests, reviews) {
if(requests.length!==policy.candidateCount||requests.some(request=>request.state!=='complete'))return;
const basis=requests.map(({requestId,operationId,prepared})=>{
if(requests.length!==policy.candidateCount||requests.some(request=>
!['complete','failed','retired','expired'].includes(request.state)))return;
const completed=requests.filter(request=>request.state==='complete');
if(completed.some(({requestId})=>!reviews?.[requestId]))return;
const basis=completed.map(({requestId,operationId,prepared})=>{
const review=reviews?.[requestId];
return review?.original&&['pass','revise'].includes(review.decision)&&{
return {
candidateId:requestId,operationId,position:prepared.candidateSet.position,
verdict:review.decision,checks:review.checks,reason:review.reason,original:review.original,
};
});
if(basis.some(row=>!row))return;
const ranked=basis.filter(row=>row.verdict==='pass').sort((a,b)=>{
for(const check of policy.priorityChecks){
const difference=Number(b.checks?.[check]===true)-Number(a.checks?.[check]===true);
@ -59,57 +60,34 @@ export function decideCandidateSet(policy, requests, reviews) {
export async function reviewProductionCandidate({
canvas,host,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
reviewKnowledge,useFramedOriginal=true,refusal,onRequestFailure,requireOriginal=false,
allowCanvasAdjustment=true,liveScreenCopy,
reviewKnowledge,refusal,onRequestFailure,liveScreenCopy,
}) {
const input=await canvas.detailImages(slot.id,candidateId,{
...(adopted?{adopted:true}:null),
...(rule?.actionReviewRegion?{actionReviewDetail:true}:null),
...(requireOriginal||allowCanvasAdjustment&&!adopted?{includeCandidateOriginal:true}:null),
});
if(input.candidateId!==candidateId||!input.referenceCount||
input.images?.length!==input.referenceCount+(input.layoutCount??0)+1||
input.images.some(image=>image?.type!=='image')||adopted&&input.adopted!==true){
throw Error('本次验图未读到同款实拍与对应候选的实际像素');
}
const original=input.candidateFile;
const screenCopy=mergeReviewCopy({copy,relatedCopy:input.relatedCopy,liveScreenCopy});
// 旧版制作按带画面声明的映射文案核对留存回执。
const reviewedCopy=copySignature(allowCanvasAdjustment?screenCopy:copy);
if(requireOriginal&&(!original?.sha256||!(original.width>0)||!(original.height>0)||
input.candidateOriginal?.type!=='image'||!input.candidateOriginal.data)){
throw Error('自动采用须读取并核对候选原文件的实际像素');
}
const reviewedCopy=copySignature(screenCopy);
const referenceCount=input.referenceCount;
const originalIndex=input.originalReferenceIndex;
const originalReference=Number.isInteger(originalIndex)&&originalIndex>=0&&originalIndex<referenceCount
? 'P'+String(originalIndex+1).padStart(2,'0') : null;
const cropFrameOnly=useFramedOriginal&&Boolean(originalReference)&&rule?.crop&&rule.cropMode!=='inside';
const containedOriginal=useFramedOriginal&&!adopted&&source==='product'&&rule?.crop===false&&Boolean(originalReference);
const originalImages=cropFrameOnly||containedOriginal?[]:
originalReference?[input.images[originalIndex]]:input.images.slice(0,referenceCount);
const originalImages=originalReference?[input.images[originalIndex]]:input.images.slice(0,referenceCount);
const layoutImages=input.images.slice(referenceCount,-1);
const extraViews=Object.fromEntries([
['候选动作区域',input.actionReviewDetail],['候选文字区',input.textRegionPreview],
['画布排版叠加前的候选',input.bareCandidate],
['未经图框裁切的候选原图',input.candidateOriginal],
].filter(([,image])=>image?.type==='image'));
const pixelFindings={
whiteSideBands:input.whiteSideBands,hasWhiteTopBand:input.hasWhiteTopBand,hasWhiteBottomBand:input.hasWhiteBottomBand,
hasSwatchBackdrop:input.hasSwatchBackdrop,textRegionEdgeObstructions:input.textRegionEdgeObstructions,
};
const guidePoint=Type.Tuple([Type.Integer({minimum:0,maximum:1000}),Type.Integer({minimum:0,maximum:1000})]);
const guides=adopted?[]:Object.entries(rule?.structureGuides??{});
const issue = {location:Type.String(),problem:Type.String(),suggestion:Type.String()};
const assessment=params({
candidateId:Type.String(),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))),
shownSubject:Type.Optional(Type.String({description:'画面实际突出呈现的部位、景别或场景。'})),
...(allowCanvasAdjustment?{
recommendedAction:Type.Optional(Type.Union(actions.map(value=>Type.Literal(value)))),
canvasTransform:Type.Optional(params(canvasTransformArgs)),
}:null),
recommendedAction:Type.Optional(Type.Union(actions.map(value=>Type.Literal(value)))),
canvasTransform:Type.Optional(params(canvasTransformArgs)),
checks:params({structure:Type.Boolean(),color:Type.Boolean(),
...(allowCanvasAdjustment?{material:Type.Optional(Type.Boolean())}:null),
material:Type.Optional(Type.Boolean()),
templateStyle:Type.Optional(Type.Boolean({description:'按本项目发布的规则判断模板风格'})),
composition:Type.Boolean(),evidence:Type.Boolean(),
copyAlignment:Type.Optional(Type.Boolean({description:'画面主角和本图位承担的实时文案是否一致。'}))}),
@ -130,7 +108,7 @@ export async function reviewProductionCandidate({
if(!['pass','revise','missing'].includes(value.verdict))throw new InvalidToolReply('请明确填写候选的验图结论');
receipt={candidateId,verdict:value.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform,
checks:value.checks,reason:value.reason,shownSubject:value.shownSubject,observation:{
source,shownSubject:value.shownSubject,reviewedCopy,visualEvidence:value.shownFields??[],pixelFindings,
source,shownSubject:value.shownSubject,reviewedCopy,visualEvidence:value.shownFields??[],
mustRedo:value.mustRedo??[],canvasFixes:value.canvasFixes??[],
generationFixes:value.generationFixes??value.mustRedo?.map(issue=>issue.suggestion),structureGuides:value.structureGuides,
...(adopted?{adoptedCanvas:true}:null),...(originalReference?{originalReference}:null),
@ -143,27 +121,25 @@ export async function reviewProductionCandidate({
templateContext:requirements===input.requirements?undefined:input.requirements,
copy:screenCopy,screenCopy,knowledgeFiles:reviewKnowledge.files,
productReferenceCount:originalImages.length,layoutReferenceCount:layoutImages.length,
extraViews:Object.keys(extraViews),originalReference,frame:input.frame,ratio:input.frame?.width>0&&input.frame?.height>0?input.frame.width+':'+input.frame.height:input.aspectRatio,
originalReference,frame:input.frame,ratio:input.frame?.width>0&&input.frame?.height>0?input.frame.width+':'+input.frame.height:input.aspectRatio,
candidateFile:input.candidateFile,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue,
fit,artDirection,textRegions:input.textRegions,pixelFindings});
fit,artDirection,textRegions:input.textRegions});
const instructions=[
'读取本项目发布的验图 Skill 和适用引用,按其标准提交候选结论。第一张是本次唯一受审候选,以其可见内容判断当前图位。后续图片按标注用于对照同款结构、模板构图或检查候选局部。',
'第一张是本次受审候选图框。按当前图位要求审阅,后续图像依标注用于核对同款实拍和模板构图。',
...(adopted?['第一张取自当前画布的实际图框。']:[]),
...(containedOriginal||cropFrameOnly?['第一张是按实际图框和放置方式渲染的预览。']:[]),
'附件是供视觉查看的预览。原件的尺寸和透明通道见 candidateFile,实际图框见 frame。pixelFindings 是像素检查记录。',
'原件尺寸和透明通道见 candidateFile,实际图框见 frame。查看主体是否完整清晰、透视和动作是否自然、接地与光影是否可信,注意异常留边、生成杂字、拼接痕迹及文案区域的可读性。模板有色卡、纯色衬底或透明要求时按当前图位标准检查。',
'requirements 是当前 fieldId 的画面要求。templateContext 提供整屏目标与通用适配规则。整屏要实现的多图对应关系由各图位分别完成,交给整屏复核。',
COPY_IMAGE_REVIEW_GUIDANCE,
'对照关联文案 copy 和同屏上下文核对图文一致性。看清候选实际体现的材质、颜色、款式和结构,以及场景、功能、尺寸、规格、数量和 SKU 花色是否支持本图位的卖点。',
'按发布规则分别记录 mustRedo 和 canvasFixes,填写问题位置、说明及建议。用 shownFields 记录画面可见依据。',
...(allowCanvasAdjustment?['商品主体准确且问题仅涉及构图、裁切、朝向或偏移时,可在 canvasFixes 提出建议,并选填 recommendedAction 或 canvasTransform。裁切坐标以未裁切原图为准。主代理根据画面决定后续操作。']:[]),
'结构、材质、颜色或卖点证据出现实质错误时,在 mustRedo 写明位置、问题和建议。商品主体准确且仅需调整构图、裁切、朝向或偏移时,在 canvasFixes 写明建议,可选填 recommendedAction 或 canvasTransform,裁切坐标以未裁切原图为准。用 shownFields 记录可见依据,主代理根据回执决定采纳或修整。',
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
...(reviewKnowledge.files.length?[knowledgeReadInstruction]:[]),
...(reviewKnowledge.files.length?['当前图位引用了未提供的专项标准且会影响结论时,可按 knowledgeFiles 查阅对应文件。']:[]),
'调用 review_candidate 提交结论。',
].join('\n');
const images=[input.images.at(-1),...originalImages,...layoutImages,...Object.values(extraViews)];
const images=[input.images.at(-1),...originalImages,...layoutImages];
const captions=['受审候选图框',...originalImages.map((_image,index)=>
'同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0'))),
...layoutImages.map(()=> '模板构图参考'),...Object.keys(extraViews)];
...layoutImages.map(()=> '模板构图参考')];
const scope=productRequestScope('review',candidateId);
const model=host.info?.model?.id??null;
const automaticTools=productionUsesAutomaticTools(host.info?.model);
@ -189,5 +165,5 @@ export async function reviewProductionCandidate({
? instructions+'\n请调用本次提供的 review_candidate 工具提交候选号、结论和具体证据。'
: instructions);
}
return {...receipt,referenceCount,...(requireOriginal?{original}:null)};
return {...receipt,referenceCount,...(input.candidateFile?{original:input.candidateFile}:null)};
}

View File

@ -3,7 +3,15 @@ import { calculateContextTokens, getLastAssistantUsage } from '@earendil-works/p
/** Usage is scoped to one model and one project. Never turn a local safety
* budget, a billing tier or a missing receipt into a claimed model capacity. */
export const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
export const contextTextLength = context => JSON.stringify(context, (_key,value)=>value?.type==='image'&&typeof value.data==='string'?{...value,data:''}:value).length;
export function contextLengths(context) {
let imageChars = 0;
const textChars = JSON.stringify(context, (_key, value) => {
if (value?.type !== 'image' || typeof value.data !== 'string') return value;
imageChars += value.data.length;
return {...value, data: ''};
}).length;
return {textChars, totalChars: textChars + imageChars};
}
export function modelCapacity(model) {
const limit = count(model.contextWindow);
return limit > 0 && typeof model.contextWindowSource === 'string' && model.contextWindowSource.length > 0

View File

@ -3,7 +3,8 @@ export const DRAW_LIMIT_GUIDANCE='每个图位最多发起 4 次远端生图。
export const COPY_IMAGE_PROMPT_GUIDANCE='卖点主角就是画面主角。让文案讲的具体部件、动作或结构成为清晰的视觉焦点。模板原图与本屏卖点部位和景别一致时可参考构图,并用本款实拍还原商品。若模板拍的是桌面而文案讲桌腿等不同部位或景别,传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 从本款实拍裁切对应部件。实拍或版式无法可靠呈现时,按资料调整对应文案。'+DRAW_LIMIT_GUIDANCE;
const WOOD_FINISH_GUIDANCE='逐条对照商品资料及画面实际呈现的木材纹理、色泽深浅和涂装观感,核对材质、木种与颜色文案是否自洽。若资料确认深木色来自涂装,文案应客观交代木种与涂装的关系或修正矛盾描述。';
export const COPY_IMAGE_REVIEW_GUIDANCE='先用 shownSubject 客观描述候选图框实际拍到的部位、景别或场景,再逐条对照关联与同屏实时文案,填写 checks.copyAlignment。即使同款、颜色和构图正确,若图位应证明的部位与画面主角不同,或该部位被裁切、遮挡、看不清,图文一致性应判不通过,候选应退回。'+WOOD_FINISH_GUIDANCE+'指出具体不符的文案、画面依据,并建议重做特写、裁切实拍或修正文案。同屏其他图位承担的卖点交由整屏复核。';
export const COPY_IMAGE_SCREEN_GUIDANCE='对照 screenCopy、商品资料与实际画面逐条核对图文一致性,确认对应图位把卖点部位、动作或结构清晰呈现为焦点,并核对材质、颜色、款式和结构是否真实可见,场景或功能卖点是否与实拍及 SKU 花色相符,尺寸、规格、数量是否与画面和标注自洽。'+WOOD_FINISH_GUIDANCE+'图文不一致时,按资料选择裁切实拍、调整构图、重做图片或修正文案,再用 read_output_screen 复看。';
export const COPY_IMAGE_OVERLAY_GUIDANCE='图片回填后,凡图位上方有文字、装饰括号(如「」)、虚线轮廓、尺寸标注或指向引线,必须结合 read_output_screen 的整屏合成切片与 overlayLayers 逐项核对。裸图看不到叠层错位和未映射的旧模板内容。用 overlapsSlots 和 bounds 确认覆盖位置,按 mapped 和 text 找出未映射的残留文字或旧尺寸。检查产品结构线及虚线框是否贴合新商品,指向引线的端点圆点是否悬空,尺寸标注线与数值是否对应本款规格。核对文案是否溢出位图格子、重点标识是否对齐,并检查浅色背景上的文字对比度与可读性。发现问题直接用原生画布工具修正。用 codemode 批量调用 native_call,按 nativeLayerId 清理或修正旧文字和尺寸、挪正端点、隐藏或调整错位虚线框及压字装饰,再用 read_output_screen 复看。';
export const COPY_IMAGE_SCREEN_GUIDANCE='对照 screenCopy、商品资料与实际画面逐条核对图文一致性,确认对应图位把卖点部位、动作或结构清晰呈现为焦点,并核对材质、颜色、款式和结构是否真实可见,场景或功能卖点是否与实拍及 SKU 花色相符,尺寸、规格、数量是否与画面和标注自洽。'+WOOD_FINISH_GUIDANCE+'图文不一致时,按资料选择裁切实拍、调整构图、重做图片或修正文案,再用 read_output_screen 复看。'+COPY_IMAGE_OVERLAY_GUIDANCE;
const fieldId = row => row.field ?? row.fieldId;
const belongsTo = (ids, id) => Array.isArray(ids) && ids.includes(id);

View File

@ -123,6 +123,7 @@ export function nativeTools(host, make) {
terminal = true;
if (settled.executed !== true) throw Error(settled.error || '原生命令未执行,未报告成功');
if (pendingJob !== undefined && (settled.state !== 'done' || settled.applied !== true || settled.applicationVerified !== true)) throw Error(settled.error || '原生任务未完成经验证的文档应用,保留原job核查;禁止重复执行');
if (!readOnly && settled.revision !== args.revision) (await host.productionOperations)?.markProgressDirty?.();
await host.store.appendEvent({ type: 'native_operation_completed', run: host.canvas.run,
method: args.method, command: args.method === 'engine.execute' ? args.params.command : undefined,
revision: settled.revision, receipt: settled.receipt ?? (settled.kind === 'native-operation' ? settled : undefined) });

View File

@ -24,7 +24,7 @@ const page=Type.Integer({minimum:0});
const rev=Type.Integer({minimum:0});
const optional=Type.Optional;
const fit=Type.Union([Type.Literal('cover'),Type.Literal('contain')]);
const screenReviewGuidance=COPY_IMAGE_SCREEN_GUIDANCE+'按实际像素检查换图改字后的产品结构线、指向引线和端点圆点、尺寸标注线与数值,以及文案是否溢出位图格子、重点标识是否对齐。发现问题直接用原生画布工具修正。可用 native_call 修正文字层与标注线,已映射文字也可用 write_copy_fields。';
const screenReviewGuidance=COPY_IMAGE_SCREEN_GUIDANCE+'已映射文字可用 write_copy_fields 修正。';
const productImageArgs={
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
};
@ -253,13 +253,14 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
const expiry=expiryFields(receipt?.id===candidateId?receipt:operation);
if(settledImagePhases.includes(phase)||phase==='not_executed'){
const applied=phase==='complete'&&adoption;
if(applied)onAdopted?.(slot.id);
if(applied)onAdopted?.(slot.id,candidateId);
const decision=original.decision;
await update(journal=>{
const record=journal.items[slot.id];
rememberImageExpiry(record,candidateId,expiry);
Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId,
...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}),
...(applied&&!decision?{autoCandidateSetId:null}:null),
...(!adopting?{heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null}:null)});
if(decision&&applied)record.autoAdoptions[decision.candidateSetId]={...decision,
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
@ -368,7 +369,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
};
const seenLayouts=new Set();
let seenProduct=false;
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map(), filled=new Set(slots.filter(s=>s.selectedCandidateId).map(s=>s.id));
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map();
const filled=new Map(slots.filter(slot=>slot.selectedCandidateId).map(slot=>[slot.id,slot.selectedCandidateId]));
const delegateQueue=[];
let activeDelegates=0;
const startNextDelegate=()=>{
@ -435,7 +437,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
const changed=productionInputs(value,variantId)!==productionInputs(plan,variantId);
if(refresh){
if(changed)seenProduct=false;
if(changed){
seenProduct=false;
markProgressDirty();
}
plan=value;
}else if(changed){
throw Error('当前款式资料已更新,请重新读取制作计划');
@ -451,17 +456,16 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const journalCopy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{});
return resolveLiveSlotCopy({slot,copyFields,pages,journalCopy});
};
let displayEpoch=0;
const progress=async ({heading,epoch})=>{
if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return;
let displayEpoch=0, progressVersion=0, progressSnapshot;
const markProgressDirty=()=>{progressVersion++;};
const readProgressSnapshot=async version=>{
const snapshot=await copySnapshot();
const reviews=(journal.screenReviews??[]).filter(([,review])=>review.issues.length===0&&review.copyTexts);
const verifiedPages=new Map();
if(reviews.length){
const live=await loadSlots(canvas,outputId);
if((live.plan.revisions?.canvas??snapshot.revision)!==snapshot.revision)return;
const slotsByPage=Map.groupBy(live.slots,slotPage);
if(evidenceMatches(live.plan)){
if((live.plan.revisions?.canvas??snapshot.revision)===snapshot.revision&&evidenceMatches(live.plan)){
for(const [page,review] of reviews){
const pageId=snapshot.pages?.[page];
if(pageId!=null&&review.copyInputs===productionInputs(live.plan,variantId)&&
@ -471,13 +475,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
}
}
const pictureCells=slots.map(({id,label})=>{
const item=journal.items[id];
const matched=filled.has(id);
const adopted=item?.autoAdoptions?.[item.autoCandidateSetId];
const checked=adopted?.receipt||item?.review?.decision==='pass';
return {slotId:id,label,state:matched&&checked?'verified':matched?'filled':'empty'};
});
const copyCells=(snapshot.fields??[]).map(field=>{
const {layer,label,currentText,templateSample}=field;
if(templateSample||!currentText?.trim())return {label,state:'empty'};
@ -485,7 +482,24 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
verifiedPages.get(copyPage(field))?.[layer]===currentText;
return {label,state:verified?'verified':'filled'};
});
return {version,revision:snapshot.revision,copyCells};
};
const progress=async ({heading,epoch})=>{
if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return;
if(progressSnapshot?.version!==progressVersion){
progressSnapshot=await readProgressSnapshot(progressVersion);
if(progressSnapshot.version!==progressVersion||epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return;
}
const {copyCells}=progressSnapshot;
const pictureCells=slots.map(({id,label})=>{
const item=journal.items[id];
const candidateId=filled.get(id);
const adopted=item?.autoAdoptions?.[item.autoCandidateSetId];
const checked=adopted?.candidateId===candidateId&&adopted?.receipt||
item?.approvals?.some(review=>review.candidateId===candidateId)||
item?.review?.candidateId===candidateId&&item?.review?.decision==='pass';
return {slotId:id,label,state:candidateId?(checked?'verified':'filled'):'empty'};
});
const jobProgress={total:slots.length,rendered:filled.size,
copy:copyCells.filter(row=>row.state==='verified').length,
copyPending:copyCells.filter(row=>row.state!=='verified').length,
@ -557,20 +571,22 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
throw error;
}
const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase;
if(state==='applied')filled.add(slot.id);
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;
await update(journal=>{
const item=journal.items[slot.id]??={};
Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending,
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null)});
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null),
...(state==='applied'&&!decision?{autoCandidateSetId:null}:null)});
if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision,
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
rememberAttempt(item,operation.candidateId);
rememberImageExpiry(item,operation.candidateId,operation);
},operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate',
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined);
if(state==='applied')markProgressDirty();
return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)};
}
const pendingGeneration=(slot,record=journal,requestId)=>{
@ -728,7 +744,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
});
const recoverImage=createImageReconciler(canvas,{outputId,variantId},()=>journal,update,{
onAdopted:id=>filled.add(id),
onAdopted:(id,candidateId)=>filled.set(id,candidateId),
});
const outstanding=async()=>{
await journalWrite;
@ -760,7 +776,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
JSON.stringify(row.observation.reviewedCopy)===copy));
const selected=decideCandidateSet(policy,requests,currentReviews);
if(!selected||item?.pendingAdoption)return previous;
const assetSha256=selected.basis.find(row=>row.candidateId===selected.candidateId)?.original.sha256;
const assetSha256=selected.basis.find(row=>row.candidateId===selected.candidateId)?.original?.sha256;
const decision={...selected,candidateSetId:id,assetSha256,fieldId:slot.fieldId,outputId,variantId};
const state=decision.candidateId?'selected':'needs_rework';
if(!previous)await update(journal=>{
@ -768,7 +784,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
});
if(!decision.candidateId)return {...decision,state};
const result=await operate(slot,'adopt_candidate',{candidateId:decision.candidateId},signal,undefined,decision);
if(result.phase==='complete'&&candidates.has(decision.candidateId))candidates.get(decision.candidateId).status='adopted';
if(result.phase==='complete'){
if(candidates.has(decision.candidateId))candidates.get(decision.candidateId).status='adopted';
notice('画布回填回执');
}
return journal.items[slot.id].autoAdoptions[id];
});
async function check(slot,candidateId,adopted,signal){
@ -779,7 +798,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
try{
const liveScreenCopy=await liveSlotCopy(slot);
const {referenceCount,...review}=await reviewProductionCandidate({canvas,host,runAgent:host.runDetailAgent,
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews,requireOriginal:Boolean(candidateSet)});
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews});
const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review;
const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform,
evidenceVersion:1,creationRevision:plan.revisions?.creation};
@ -804,6 +823,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
return {
get active(){return jobs.size;},
markProgressDirty,
async close(){
await drain();
await canvasWrite;
@ -905,7 +925,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
for(const {layer,mapping} of result.styleMappings)journal.copyStyleMappings[layer]=mapping;
}
});
if(applied.length)notice('文字已更新');
if(applied.length||result.appliedLayers?.length){
markProgressDirty();
notice('文字已更新');
}
const copyUpdates={
total:applied.length,truncated:applied.length>COPY_UPDATE_LIMIT,
items:applied.slice(0,COPY_UPDATE_LIMIT).map(row=>{
@ -1169,12 +1192,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
},
async adopt_production_image({slotId,candidateId,fit},signal){
const slot=matches(slotId);
const request=repository.readImageRequest(candidateId);
if(request?.slotId===slot.id&&request.prepared.binding===binding&&request.prepared.candidateSet&&
!slotDrawStatus(await liveSlot(slot)).drawLimitReached){
const adoption=await autoAdopt(slot,request.prepared.candidateSet,signal);
return adoption?{...adoption,phase:adoption.receipt?.phase??adoption.state}:{phase:'awaiting_candidate_reviews'};
}
const result=await serialize(()=>operate(slot,'adopt_candidate',{candidateId,fit},signal));
if(result.phase==='complete'&&candidates.has(candidateId))candidates.get(candidateId).status='adopted';
notice('画布回填回执');
@ -1203,6 +1220,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
...(request?{receipt:[candidateId,'retired',result]}:null)});
candidates.delete(candidateId);
host.generatedCandidates?.delete(candidateId);
markProgressDirty();
await store.appendEvent({type:'production_image_retired',slotId:slot.id,candidateId,reason,requestId:result.requestId});
notice('已清理退回的候选图');
}
@ -1235,12 +1253,17 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
if(set)await autoAdopt(slot,set,signal);
}
}
if(results.some(receipt=>receipt.phase==='complete')){
markProgressDirty();
notice('已核查原图片操作');
}
return results;
},
async read_output_screen({page=0,pages},signal){
const render=async page=>{
const {images=[],...details}=await canvas.detailRender({page});
const {images=[],overlayLayers,...details}=await canvas.detailRender({page});
const snapshot=await copySnapshot();
if(progressSnapshot&&snapshot.revision!==progressSnapshot.revision)markProgressDirty();
const {pages:copyPages=[],fields:copyFields=[]}=snapshot;
const pageId=copyPages[page];
const pageFields=pageId==null?[]:copyFields.filter(field=>(field.page??field.pageId)===pageId&&field.currentText?.trim());
@ -1259,7 +1282,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
return {image:{type:'image',data:resized.data,mimeType:resized.mimeType},note:formatDimensionNote(resized)};
}));
const notes=previews.map(preview=>preview.note).filter(Boolean);
return imageResult({...details,...(snapshot.revision!=null&&snapshot.revision!==details.revision?{copyRevision:snapshot.revision}:null),
return imageResult({...details,...(overlayLayers===undefined?null:{overlayLayers}),
...(snapshot.revision!=null&&snapshot.revision!==details.revision?{copyRevision:snapshot.revision}:null),
...(screenCopy.length?{screenCopy}:null),
...(notes.length?{previewDimensions:notes}:null),images:previews.map(preview=>preview.image)});
};
@ -1307,6 +1331,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
reviews.set(page,review);
journal.screenReviews=[...reviews];
});
markProgressDirty();
notice('整屏复核已记录');
return {page,issues};
});

View File

@ -5,7 +5,7 @@ import path from 'node:path';
import test from 'node:test';
import { Value } from '@sinclair/typebox/value';
import { mergeReviewCopy, extractPageLiveCopy, resolveLiveSlotCopy } from '../src/copy-image-alignment.mjs';
import { readAutoAdoptionPolicy, reviewProductionCandidate } from '../src/candidate-review.mjs';
import { decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from '../src/candidate-review.mjs';
import { openProductionOperations } from '../src/production-operations.mjs';
import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs';
import { cleanup } from './cleanup.mjs';
@ -87,12 +87,53 @@ test('candidate review records the observed subject and alignment while acceptin
assert.deepEqual(readAutoAdoptionPolicy(policy),policy);
});
test('candidate review sends the candidate, same-product photo and template composition only',async()=>{
const image=data=>({type:'image',data,mimeType:'image/png'});
const photo=image('photo'), layout=image('layout'), candidate=image('candidate'), extra=image('extra');
const source={candidateId:'candidate',referenceCount:2,originalReferenceIndex:1,layoutCount:1,
images:[image('other shot'),photo,layout,candidate],
candidateOriginal:extra,bareCandidate:extra,textRegionPreview:extra,actionReviewDetail:extra,
hasWhiteTopBand:true,whiteSideBands:['left'],textRegionEdgeObstructions:true};
const result=await reviewProductionCandidate({
canvas:{detailImages:async(_slot,_candidate,options)=>{assert.deepEqual(options,{});return source;}},
host:{},slot,candidateId:'candidate',rule:{crop:true,actionReviewRegion:[0,0,50,50]},
reviewKnowledge:{files:[{fileId:'special-rule'}],tools:[]},
async runAgent(_slot,instructions,prompt,[tool],images,_scope,captions){
assert.deepEqual(images,[candidate,photo,layout]);
assert.deepEqual(captions,['受审候选图框','同款实拍 P02','模板构图参考']);
assert.match(instructions,/接地与光影.*异常留边/u);
assert.match(instructions,/专项标准且会影响结论时/u);
assert.doesNotMatch(prompt,/pixelFindings|hasWhiteTopBand|extraViews/u);
await tool.execute('review',{candidateId:'candidate',verdict:'pass',reason:'清楚呈现桌腿',
checks:{structure:true,color:true,composition:true,evidence:true}});
},
});
assert.equal(result.verdict,'pass');
assert.equal(result.observation.pixelFindings,undefined);
});
test('automatic choice waits for unsettled requests and ranks reviewed images when one draw failed',()=>{
const policy={version:'1',candidateCount:2,priorityChecks:['composition']};
const requests=[
{requestId:'a',state:'complete',prepared:{candidateSet:{position:0}}},
{requestId:'b',state:'unknown',prepared:{candidateSet:{position:1}}},
];
const reviews={a:{decision:'pass',checks:{composition:true},reason:'构图完整'}};
assert.equal(decideCandidateSet(policy,requests,reviews),undefined);
requests[1].state='failed';
assert.equal(decideCandidateSet(policy,requests,reviews).candidateId,'a');
});
test('production delegation and screen rendering use live copy after a direct canvas edit',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-copy-alignment-'));
t.after(()=>cleanup(dir));
const live=structuredClone(fields);
live[0].currentText='圆润桌面';
let delegated;
const overlayLayers=[
{nativeLayerId:41,mapped:false,text:'旧尺寸 140 cm',bounds:[10,20,80,44],overlapsSlots:[slot.id]},
{nativeLayerId:42,mapped:true,text:null,bounds:[32,40,90,130],overlapsSlots:[slot.id]},
];
const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}),
@ -100,7 +141,7 @@ test('production delegation and screen rendering use live copy after a direct ca
assert.equal(options.includeFilled,true);
return {fields:structuredClone(live),pages,revision:2};
},
detailRender:async({page})=>({page,revision:2,images:[]}),
detailRender:async({page})=>({page,revision:2,overlayLayers:page===1?overlayLayers:[],images:[]}),
readCanvas:async({layer})=>({context:{layers:[{id:layer,visible:true,effectiveVisible:layer!==7}]}}),
delta:async()=>{},
},async runDetailAgent(_slot,instructions,prompt){
@ -116,7 +157,11 @@ test('production delegation and screen rendering use live copy after a direct ca
await actions.await_image_slots({slotIds:[slot.id]});
assert.deepEqual(delegated.screenCopy.map(row=>row.text),['加厚桌腿','桌腿与横梁用榫接固定','实木横梁']);
live.push({layer:7,page:'P02',field:'hidden',currentText:'已隐藏分组的旧文案'});
const {details}=await actions.read_output_screen({page:1});
const {details,content}=await actions.read_output_screen({page:1});
assert.deepEqual(details.overlayLayers,overlayLayers);
assert.deepEqual(JSON.parse(content[0].text).overlayLayers,overlayLayers);
const multi=await actions.read_output_screen({pages:[0,1]});
assert.deepEqual(multi.details.screens.map(screen=>screen.overlayLayers),[[],overlayLayers]);
assert.deepEqual(details.screenCopy,extractPageLiveCopy({pageIndex:1,pages,fields}));
assert.deepEqual(details.screenCopy.map(row=>[row.field,row.text,row.templateSample]),[
['title','加厚桌腿',false],['detail','桌腿与横梁用榫接固定',false],['tag','实木横梁',false],['sample','模板样例',true],

View File

@ -768,6 +768,58 @@ test('the model receives prior images and original tool receipts through Pi', as
} finally {await x.close();}
});
test('main request archives summarize image bytes by default and support raw payload opt-in',async t=>{
const setting='XIAOYI_DUMP_RAW_PAYLOADS';
const previous=process.env[setting];
t.after(()=>{if(previous===undefined)delete process.env[setting];else process.env[setting]=previous;});
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
const url=`data:image/png;base64,${image}`;
const x=await setup(()=>sse({content:'已查看。'},'stop'));
t.after(x.close);
const readImageUrl=payload=>payload.messages.flatMap(row=>Array.isArray(row.content)?row.content:[])
.find(part=>part.type==='image_url')?.image_url.url;
for(const raw of [false,true]){
if(raw)process.env[setting]='1';else delete process.env[setting];
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
assert.equal(readImageUrl(x.requests.at(-1)),url);
const stored=await fs.readFile(path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json'),'utf8');
assert.equal(readImageUrl(JSON.parse(stored)),raw?url:`[image-base64-omitted:${Buffer.from(image,'base64').length}B]`);
assert.equal(stored.includes(image),raw);
}
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
const budget=events.find(event=>event.type==='context_budget');
assert.equal(budget.originalChars-budget.inputChars,image.length);
const requests=events.filter(event=>event.type==='serialized_request');
assert.deepEqual(requests.map(event=>event.id),x.ids);
for(const event of requests){
assert.match(event.bodyHash,/^[a-f0-9]{64}$/u);
assert.ok(event.keys.includes('messages'));
assert.ok(Array.isArray(event.tools));
}
});
test('a worker can change course after many identical calls without terminating',async t=>{
const calls=[];
const x=await setup((payload,round)=>{
if(round===10){
const last=payload.messages.findLast(message=>message.role==='tool');
assert.match(last.content,/已连续调用 8 次/u);
}
if(round===12)return sse({content:'核对完成。'},'stop');
return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'inspect_item',
arguments:JSON.stringify({item:round===10?'other':'same'})}}]},'tool_calls');
},undefined,undefined,{canvas:{}});
t.after(x.close);
const tool={name:'inspect_item',description:'Inspect item',parameters:{type:'object',properties:{item:{type:'string'}},required:['item']},
async execute(_id,{item}){
calls.push(item);
return {content:[{type:'text',text:item}],details:{item}};
}};
await x.host.runDetailAgent('slot-a','Inspect the item.','Read the fixture.',[tool],[],'product/slot/slot-a');
assert.deepEqual(calls,[...Array(8).fill('same'),'other','same']);
assert.equal(x.requests.length,12);
});
test('Pi project tools share the same file boundary',async()=>{
const x=await setup(()=>sse({content:'已核对。'},'stop'));
try {

View File

@ -52,7 +52,7 @@ test('canvas advice leaves review, transformation and generation under agent con
template:{contentHash:'studio'},totalSlots:1,slots:[{id:'slot',fieldId:'P05'}]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
detailImages:async(_slot,candidateId,args)=>{
assert.equal(args.includeCandidateOriginal,true);
assert.deepEqual(args,{});
return {candidateId,referenceCount:1,images:[image,image]};
},
async imageRequest(action,args){
@ -321,12 +321,13 @@ test('an unbound production turn checks project originals without opening any wo
assert.equal(goal.outputId,undefined);
});
test('P07 waits for both original images and persists the automatic adoption decision',async t=>{
test('P07 waits for both candidate reviews and persists the automatic adoption decision',async t=>{
for(const scenario of [
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true},
{verdicts:['pass','pass'],winner:1,reason:'policy_priority'},
{verdicts:['revise','revise'],winner:null,reason:'all_rejected'},
{verdicts:['pass','pass'],winner:1,reason:'policy_priority',editCopy:true},
{verdicts:['revise','pass'],manual:true,reason:'honors the explicit choice before the draw cap'},
])await t.test(scenario.editCopy?'rechecks earlier candidates after a live copy edit':scenario.reason,async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-p07-'));
t.after(()=>cleanup(dir));
@ -335,7 +336,6 @@ test('P07 waits for both original images and persists the automatic adoption dec
const ledger=store.ledger('detail','oak');
const slotId='main-photo';
const posts=[],placements=[],seen=[];
const originals=new Map();
const bothStarted=Promise.withResolvers(), complete=Promise.withResolvers();
const image={type:'image',mimeType:'image/png',
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j1f8AAAAASUVORK5CYII='};
@ -352,10 +352,10 @@ test('P07 waits for both original images and persists the automatic adoption dec
return {id:candidateId,status:'complete'};
},
async detailImages(_slot,candidateId,options){
assert.equal(options.includeCandidateOriginal,true);
return {candidateId,referenceCount:1,candidateFile:{width:1,height:1,sha256:digest},
assert.deepEqual(options,{});
return {candidateId,referenceCount:1,candidateFile:{width:1,height:1,...(scenario.recoverA?{sha256:digest}:null)},
prompt:'桌腿接口近景',requirements:'同一屏的各个部位分别用对应图位表现。桌腿接口近景。',
candidateOriginal:originals.get(candidateId),images:[image,image],relatedCopy:[{fieldId:'title',text:currentText}]};
images:[image,image],relatedCopy:[{fieldId:'title',text:currentText}]};
},
read:async()=>({revision:3}),requestWrite:async revision=>({allowed:true,revision}),
async workflowExecute({intent,operationId,candidateId}){
@ -374,8 +374,8 @@ test('P07 waits for both original images and persists the automatic adoption dec
assert.equal(fieldId,'cover');
assert.equal(requirements,'桌腿接口近景');
assert.match(templateContext,/各个部位分别用对应图位/);
assert.equal(images[2],originals.get(candidateId));
assert.deepEqual(captions,['受审候选图框','同款实拍 P01','未经图框裁切的候选原图']);
assert.deepEqual(images,[image,image]);
assert.deepEqual(captions,['受审候选图框','同款实拍 P01']);
seen.push(candidateId);
await tools[0].execute('review-fixture',{candidateId,verdict:scenario.verdicts[index],
checks:{structure:true,color:true,composition:true,evidence:true,templateStyle:index===1},
@ -387,7 +387,6 @@ test('P07 waits for both original images and persists the automatic adoption dec
assert.ok(ledger.read().items[slotId].pendingGenerations[id]);
if(posts.length===2)bothStarted.resolve();
await complete.promise;
originals.set(id,{...image});
return {status:scenario.recoverA&&id===posts[0]?'unknown':'complete',id};
});
let actions=await openProductionOperations(host);
@ -421,13 +420,12 @@ test('P07 waits for both original images and persists the automatic adoption dec
const [first]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:a.requestId}]});
assert.equal(first.adoption,undefined);
assert.deepEqual(placements,[]);
if(scenario.reason==='policy_priority'){
const original=originals.get(b.requestId);
originals.delete(b.requestId);
const [missing]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
assert.match(missing.error,/原文件/u);
assert.deepEqual(placements,[]);
originals.set(b.requestId,original);
if(scenario.manual){
assert.equal((await actions.adopt_production_image({slotId,candidateId:a.requestId})).phase,'complete');
const [later]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
assert.equal(later.adoption,undefined);
assert.deepEqual(placements.map(row=>row.candidateId),[a.requestId]);
return;
}
if(scenario.editCopy)currentText='加厚桌腿与横梁接口';
const [second]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
@ -462,7 +460,7 @@ test('P07 waits for both original images and persists the automatic adoption dec
const adopted=ledger.repository.candidateEvidence(slotId,winner).find(row=>row.kind==='adoption').detail;
assert.equal(adopted.actor,'agent');
assert.equal(adopted.policyVersion,policy.version);
assert.equal(adopted.assetSha256,digest);
assert.equal(adopted.assetSha256,scenario.recoverA?digest:undefined);
assert.equal(adopted.operationId,placements[0].operationId);
assert.equal(adopted.reason,scenario.reason);
}
@ -1299,15 +1297,23 @@ test('copy progress verifies the reviewed text and selected pictures of each scr
{layer:10,page:'P02',label:'规格',currentText:''},
];
let revision=1;
let copyReads=0, slotReads=0;
let progress=Promise.withResolvers();
const store=productionStore(dir);
const canvas={
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
revisions:{canvas:revision,creation:1},template:{contentHash:'studio'},totalSlots:slots.length,
slots:structuredClone(slots)}),
detailCopyFields:async()=>({revision,pages,fields:structuredClone(fields)}),
workflowRead:async({section})=>{
if(section==='slots')slotReads++;
return {available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
revisions:{canvas:revision,creation:1},template:{contentHash:'studio'},totalSlots:slots.length,
slots:structuredClone(slots)};
},
detailCopyFields:async()=>{
copyReads++;
return {revision,pages,fields:structuredClone(fields)};
},
detailRender:async({page})=>({page,revision}),
read:async()=>({revision}),
imageRequest:async()=>({id:'cropped',status:'complete'}),
async commitDetailCopy(items){
for(const {layer,text} of items){
const field=fields.find(field=>field.layer===layer);
@ -1344,11 +1350,15 @@ test('copy progress verifies the reviewed text and selected pictures of each scr
await assert.rejects(actions.record_screen_check({page:0,revision:revision-1,issues:[]}),/本屏已变化/);
await observe(()=>review(0),['verified','verified','filled','empty']);
await observe(()=>review(1),['verified','verified','verified','empty']);
const beforeHeartbeat={copyReads,slotReads};
await observe(()=>actions.transform_slot_image({slotId:'hero',referenceIndex:0}),['verified','verified','verified','empty']);
assert.deepEqual({copyReads,slotReads},beforeHeartbeat);
const saved=store.ledger('detail','oak').read();
const first=new Map(saved.screenReviews).get(0);
assert.deepEqual(first.copyTexts,{7:'橡胶木桌面',8:'深木色涂装'});
assert.deepEqual(first.slotSignatures,{hero:'c1'});
await observe(()=>write([[7,'橡胶木台面']]),['filled','verified','verified','empty']);
assert.equal(slotReads,beforeHeartbeat.slotReads+1);
await observe(()=>review(0),['verified','verified','verified','empty']);
slots[0].selectedCandidateId='replacement';
revision++;
@ -1459,8 +1469,8 @@ test('the fourth draw occupies the last slot while in flight and a rejected batc
template:{contentHash:'studio',production:{autoAdoptionPolicy:policy}},totalSlots:1,slots:[structuredClone(slot)]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},read:async()=>({revision:3}),
requestWrite:async revision=>({allowed:true,revision}),
detailImages:async(_slot,candidateId)=>({candidateId,referenceCount:1,images:[image,image],candidateOriginal:image,
candidateFile:{width:1,height:1,sha256:'a'.repeat(64)}}),
detailImages:async(_slot,candidateId)=>({candidateId,referenceCount:1,images:[image,image],
candidateFile:{width:1,height:1}}),
async detailRetire(_slot,candidateId){
slot.candidates=slot.candidates.filter(row=>row.id!==candidateId);
slot.retiredCandidateIds=[candidateId];

View File

@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { stripTypeScriptTypes } from 'node:module';
import { productionObjective, productionTools } from '../src/production-goal.mjs';
import { COPY_IMAGE_OVERLAY_GUIDANCE } from '../src/copy-image-alignment.mjs';
const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');
const technicalBrand = /(?<![A-Za-z0-9_])(?:Pi(?: Agent)?|PhotoCraft)(?![A-Za-z0-9_])|\bpcraft:/u;
@ -48,7 +49,7 @@ test('both conversation prompts and delegated production share the product voice
test('production review guidance covers copy, images and overlays followed by visual recheck', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
const guidance = [
['PRODUCTION_SYSTEM', prompt],
['PRODUCTION_SYSTEM', prompt?.replace('${COPY_IMAGE_OVERLAY_GUIDANCE}',COPY_IMAGE_OVERLAY_GUIDANCE)],
...['read_output_screen', 'record_screen_check'].map(name => [
name, productionTools.find(([tool]) => tool === name)?.[1],
]),
@ -61,6 +62,9 @@ test('production review guidance covers copy, images and overlays followed by vi
assert.match(copy, /尺寸标注线[^。]*数值/, name);
assert.match(copy, /文案[^。]*溢出位图格子[^。]*重点标识[^。]*(?:对准|对齐)/, name);
assert.match(copy, /直接用原生画布工具修正/, name);
assert.match(copy, /整屏合成切片与 overlayLayers/, name);
assert.match(copy, /浅色背景上的文字对比度与可读性/, name);
assert.match(copy, /codemode[^。]*native_call[^。]*nativeLayerId[^。]*read_output_screen 复看/, name);
assert.match(copy, /图文不一致时[^。]*(?:调整构图[^。]*重做图片[^。]*修正文案|修正文案[^。]*调整构图[^。]*重做图片)。?[^。]*read_output_screen 复看/, name);
assert.doesNotMatch(copy, technicalBrand, name);
}