减少小壹制作主代理的重复工具回执

This commit is contained in:
WuYongJie 2026-11-28 09:05:02 +08:00
parent 3b5e452025
commit b3efeb0a91
6 changed files with 267 additions and 31 deletions

View File

@ -11,7 +11,7 @@ import { productionLedger } from './production-repository.mjs';
import { CanvasOperations } from './canvas-operations.mjs';
import { BridgeError, stoppedCanvas } from './bridge-error.mjs';
import { protectSession, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
import { productionVideoTools } from './production-operations.mjs';
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat';
@ -68,7 +68,7 @@ const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布
${PRODUCT_VOICE}
用 plan_production 查看待交付项,open_production_output 切换可写画布,保留各成品在途工作。用 list_project_images 查询本项目可复用的候选。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。脚本可用 store() 留存需要复用的大对象,只输出本次判断所需的字段、状态和失败原因。查图层树时可用 layer.list,并在脚本内筛选目标。
按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`;
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
@ -129,6 +129,7 @@ function toolsFor(host) {
...productionTools.map(([name, description, schema])=>({
...make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
['read_output_screen','read_slot_images'].includes(name)?result=>result:
name==='open_production_output'?receipt=>({...plain(describeProductionOutput(receipt)),details:receipt}):
name==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain),
...(['read_archived_images','stage_archived_image','retire_production_image','record_screen_check']
.includes(name)?{exposure:'deferred'}:null),

View File

@ -13,34 +13,122 @@ export function contextLengths(context) {
return {textChars, totalChars: textChars + imageChars};
}
const productionReads = new Set(['plan_production', 'read_copy_fields', 'review_image_slots']);
const nativeReads = new Set(['document.inspect', 'type.info', 'layer.list']);
const canvasScope = ({outputId, variantId, documentKey} = {}) =>
outputId && variantId ? [outputId, variantId, documentKey ?? null] : null;
const oldReceipt = id => '旧回执编号:'+id+',可用 memory_search 读取。';
const updatedRead = id => '同范围已有更新回执。'+oldReceipt(id);
function readScope(name, args, details, canvas) {
if (productionReads.has(name) && details.outputId && details.variantId) {
const {slotIds, pageId, fieldId, includeKnowledge} = args;
return [name, details.outputId, details.variantId,
[...new Set(slotIds?.map(id=>id.trim()).filter(Boolean))].sort(),
pageId?.trim()||null,fieldId?.trim()||null,Boolean(includeKnowledge)];
}
if (name === 'open_production_output' && details.accepted !== false) {
const scope = canvasScope(details);
if (scope) return [name, scope];
}
if (name === 'native_catalog' && details.documentId != null) {
const {id, ids, filter, offset, limit} = args;
return [name, canvas, details.documentId, details.matchMode, id?.trim(), ids, filter?.trim(), offset??0, limit??10];
}
if (name === 'native_call' && details.executed === true && details.changed === false &&
args.method === 'engine.execute' && nativeReads.has(args.params?.command)) {
const command = args.params.command;
const {document, layer, ...options} = args.params.params ?? {};
const documentId = details.state?.documentId;
// A document index can address a different document from the active one in state.
if (document != null || documentId == null) return null;
const layerId = command === 'type.info' ? details.result?.layer : layer;
if (command === 'type.info' && layerId == null) return null;
return [name, canvas, documentId, command, layerId, options];
}
return null;
}
function readScriptScope(message, canvas) {
const {nestedCalls, content, details} = message;
if (!nestedCalls?.complete || !nestedCalls.calls.length || details?.fullOutputPath ||
content.some(block=>block.type!=='text')) return null;
if (!nestedCalls.calls.every(({name, arguments:args, status})=>status==='ok' && (
productionReads.has(name) || name==='native_catalog' || name==='read_output_screen' ||
name==='native_call' && args.method==='engine.execute' && nativeReads.has(args.params?.command)
))) return null;
// Scripts can filter, combine, or print derived facts. Only identical displayed text is replaceable.
return ['codemode', canvas, nestedCalls.calls.map(call=>[call.name,call.arguments]),
content.slice(1).map(block=>block.text)];
}
export function foldSupersededProductionReads(messages) {
const calls = new Map();
for (const message of messages) {
if (message.role !== 'assistant') continue;
for (const block of message.content) {
if (block.type === 'toolCall' && productionReads.has(block.name)) calls.set(block.id, block.arguments);
const calls = new Map(), reads = [];
let canvas = null;
for (const [index, message] of messages.entries()) {
if (message.role === 'assistant') {
for (const block of message.content) {
if (block.type === 'toolCall') calls.set(block.id, block.arguments);
}
}
if (message.role === 'custom' && message.customType === 'photocraft-goal-request') canvas = null;
if (message.role !== 'toolResult') continue;
const {toolName:name, isError} = message;
const details = message.details ?? {};
if (name === 'open_production_output') canvas = isError ? null : canvasScope(details);
if (name === 'codemode' && (details.calls ?? message.nestedCalls?.calls)?.some(call=>call.name==='open_production_output'))
canvas = null;
const args = calls.get(message.toolCallId);
if (isError || !args) continue;
if (name === 'read_output_screen') {
const target = canvasScope(details) ?? canvas;
if (!target) continue;
const blocks = new Map(message.content.flatMap((block, i)=>block.type==='text'?[[block.text,i]]:[]));
for (const screen of details.screens ?? [details]) {
const {outputId, variantId, documentKey, ...body} = screen;
const block = blocks.get(JSON.stringify(body));
if (screen.error || screen.screenChanged || !Number.isInteger(screen.page) || block===undefined) continue;
reads.push({index, block, scope:['read_output_screen',target,screen.page], page:screen.page});
}
} else {
const scope = name === 'codemode' ? readScriptScope(message,canvas) : readScope(name,args,details,canvas);
const note = name === 'plan_production' ? details.product?.note : null;
if (scope || note) reads.push({index, scope, note});
}
}
const latest = new Set();
const latest = new Set(), notes = new Set();
let folded;
for (let index = messages.length - 1; index >= 0; index--) {
for (const {index, block, scope, page, note} of reads.reverse()) {
const message = messages[index];
if (message.role !== 'toolResult' || message.isError || !productionReads.has(message.toolName)) continue;
const {outputId, variantId} = message.details ?? {};
const args = calls.get(message.toolCallId);
if (!outputId || !variantId || !args) continue;
const {slotIds, pageId, fieldId, includeKnowledge} = args;
const scope = JSON.stringify([message.toolName,outputId,variantId,
[...new Set(slotIds?.map(id=>id.trim()).filter(Boolean))].sort(),
pageId?.trim()||null,fieldId?.trim()||null,Boolean(includeKnowledge)]);
if (!latest.has(scope)) {
latest.add(scope);
const key = scope && JSON.stringify(scope);
const superseded = key && latest.has(key);
if (key) latest.add(key);
const noteReference = note && notes.has(note)
&& '同份商品备注已在更新的回执中全文列出。'+oldReceipt(message.toolCallId);
if (!superseded && !(noteReference && noteReference.length < note.length)) {
if (note) notes.add(note);
continue;
}
let content, details;
if (block !== undefined) {
content = [...(folded?.[index]?.content ?? message.content)];
content[block] = {type:'text',text:`第 ${page} 屏已有更新回执。`+oldReceipt(message.toolCallId)};
if (message.details.screens) {
const screens = (folded?.[index] ?? message).details?.screens
?.filter(screen=>screen.page!==page || screen.error || screen.screenChanged);
if (screens?.length) details = {...message.details,screens};
}
} else if (superseded) {
const save = message.toolName === 'open_production_output' && message.details?.previousSave;
content = [{type:'text',text:updatedRead(message.toolCallId) +
(save ? '\n'+JSON.stringify({previousSave:save}) : '')}];
} else {
const {note, ...product} = message.details.product;
details = {...message.details,product:{...product,noteReference}};
content = [{type:'text',text:JSON.stringify(details)}];
}
folded ??= messages.slice();
folded[index] = {...message, details:undefined, content:[{type:'text',
text:'同范围已有更新回执。旧回执编号:'+message.toolCallId+',可用 memory_search 读取。'}]};
folded[index] = {...message, details, content};
}
return folded ?? messages;
}

View File

@ -112,6 +112,17 @@ export function unverifiedDeliveryReason(goal) {
export { productionOperationTools as productionTools };
export function describeProductionOutput(binding) {
const {documentKey, switchMs, writeEpoch, ...receipt}=binding;
if (!documentKey) return receipt;
const {outputId,variantId,...identity}=documentKey;
return {...receipt,documentKey:{
...identity,
...(outputId!==receipt.outputId?{outputId}:null),
...(variantId!==receipt.variantId?{variantId}:null),
}};
}
export async function callProductionTool(host, name, args, signal) {
const goal=host.productionGoal;
if (name==='open_production_output') {
@ -139,6 +150,7 @@ export async function callProductionTool(host, name, args, signal) {
return {candidates:await host.canvas.detailHistory({projectImages:true,...args})};
const {outputId=goal.outputId,variantId=goal.variantId,...input}=args;
const target={outputId,variantId};
const documentKey=name==='read_output_screen'?host.canvas.canvasBinding?.documentKey:undefined;
const working=outputId===goal.outputId&&variantId===goal.variantId;
if (!working && !goal.requestedOutputs?.some(row=>row.outputId===outputId&&row.variantId===variantId))
throw Error('所选成品和花色不属于本轮制作');
@ -183,6 +195,8 @@ export async function callProductionTool(host, name, args, signal) {
}
signal?.throwIfAborted();
const result=await operations[name](input,signal);
if (name==='read_output_screen') return {...result,details:{...result.details,...target,
documentKey}};
if ((name==='finish_production'||name==='defer_production_output') && result.production) {
return submitProduction(host,{...result.production,scope:args.scope},signal);
}

View File

@ -79,7 +79,7 @@ const outputScope={outputId:optional(text),variantId:optional(text)};
export const productionOperationTools = [
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。已有工作会保留。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。生图上限及来源适用于所有图位。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
['read_copy_fields','省略 pageId 和 fieldId 返回全页字段身份、当前文字、约束及修订号;指定页面或字段可读取图层样式、范围及关联字段。',obj({
pageId:optional(Type.String()),fieldId:optional(Type.String()),
})],
@ -923,7 +923,9 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const pendingCopy=await pendingCopyBySlot(selected);
const pictures=selected.map(slot=>{
const {id,fieldId,label,productionRule,requirements,sourcePolicy,candidates,selectedCandidateId}=slot;
return {id,fieldId,label,...statuses.get(id),filled:canvasReady?undefined:Boolean(selectedCandidateId),
const {generationAttempts,remainingGenerationAttempts,drawLimitReached}=statuses.get(id);
return {id,fieldId,label,generationAttempts,remainingGenerationAttempts,drawLimitReached,
filled:canvasReady?undefined:Boolean(selectedCandidateId),
completedCandidates:candidates?.filter(row=>row.status==='complete').length??0,copyReady:canvasReady?undefined:!pendingCopy.get(id)?.length,
...(requested.size?{productionRule,requirements,sourcePolicy}:null)};
});
@ -931,7 +933,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const {outputId:workingOutputId,variantId:workingVariantId}=host.productionGoal;
return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null,
template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}},
pictures,inFlightImages:(await pendingNative()).map(row=>row.candidateId),
maxGenerationAttempts,generationLimitSource,pictures,inFlightImages:(await pendingNative()).map(row=>row.candidateId),
...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null),
requestedOutputs:host.productionGoal.requestedOutputs,

View File

@ -0,0 +1,127 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { foldSupersededProductionReads } from '../src/context-usage.mjs';
import { describeProductionOutput } from '../src/production-goal.mjs';
import { ProjectStore } from '../src/store.mjs';
const text = text=>({type:'text',text});
const target={outputId:'detail',variantId:'oak',documentKey:{templateVersion:3}};
const receipt = (id,name,details,args={},content=[text(JSON.stringify(details))],metadata={})=>[
{role:'assistant',content:[{type:'toolCall',id,name,arguments:args}]},
{role:'toolResult',toolName:name,toolCallId:id,content,details,...metadata},
];
const original = (messages,id)=>messages.find(message=>message.toolCallId===id);
const verify = (messages,foldedIds,fullIds)=>{
const projected=foldSupersededProductionReads(messages);
for(const id of foldedIds) {
assert.match(original(projected,id).content.map(block=>block.text).join('\n'),
new RegExp(`旧回执编号:${id},可用 memory_search 读取`));
assert.ok(original(messages,id).details);
}
for(const id of fullIds) assert.equal(original(projected,id),original(messages,id),id);
return projected;
};
test('opening the same output folds an older binding and retains its save result',()=>{
const previousSave={saved:true,path:'saved.psd',revision:8};
const messages=[
...receipt('old','open_production_output',{...target,previousSave}),
...receipt('other','open_production_output',{...target,variantId:'walnut'}),
...receipt('new','open_production_output',{...target,revision:10}),
...receipt('denied','open_production_output',{...target,accepted:false}),
];
const projected=verify(messages,['old'],['other','new','denied']);
assert.match(original(projected,'old').content[0].text,/saved\.psd/);
const manager={getBranch:()=>messages.map(message=>({type:'message',message}))};
assert.equal(ProjectStore.prototype.readToolReceipt(manager,'old',0).text,
original(messages,'old').content[0].text);
});
test('the displayed output binding retains identity and save facts once',()=>{
const binding={...target,documentKey:{...target.documentKey,outputId:'detail',variantId:'oak'},
previousSave:{saved:true,revision:8}, revision:9, switchMs:400, writeEpoch:3};
assert.deepEqual(describeProductionOutput(binding),{...target,previousSave:{saved:true,revision:8},revision:9});
assert.equal(binding.documentKey.variantId,'oak');
assert.equal(describeProductionOutput({...binding,documentKey:{variantId:'walnut'}}).documentKey.variantId,'walnut');
});
test('screen text folds by canvas and page across single and combined reads',()=>{
const page0={page:0,revision:1}, page1={page:1,revision:1}, page2={page:2,error:'画面未就绪'};
const image={type:'image',data:'preview'};
const messages=[
...receipt('open','open_production_output',target),
...receipt('batch','read_output_screen',{screens:[page0,page1,page2]}, {},
[text(JSON.stringify(page0)),image,text(JSON.stringify(page1)),text(JSON.stringify(page2))]),
...receipt('new','read_output_screen',{...page0,...target},{},[text(JSON.stringify(page0)),image]),
...receipt('switch','open_production_output',{...target,variantId:'walnut'}),
...receipt('other','read_output_screen',page1),
...receipt('error','read_output_screen',{...page1,...target,error:'画面未就绪'},{},[text(JSON.stringify({...page1,error:'画面未就绪'}))]),
...receipt('unstable','read_output_screen',{...page1,...target,screenChanged:true},{},[text(JSON.stringify({...page1,screenChanged:true}))]),
];
const projected=verify(messages,['batch'],['new','other','error','unstable']);
assert.deepEqual(original(projected,'batch').content.slice(1),[image,text(JSON.stringify(page1)),text(JSON.stringify(page2))]);
assert.deepEqual(original(projected,'batch').details.screens,[page1,page2]);
});
test('native reads fold only successful equivalent reads on the same document and layer',()=>{
const native=(id,command,documentId,params,result={},extra={})=>
receipt(id,'native_call',{executed:true,changed:false,state:{documentId},result,...extra},
{method:'engine.execute',params:{command,params}});
const messages=[
...native('old','document.inspect',1,{}),
...native('separate','document.inspect',2,{}),
...native('indexed','document.inspect',1,{document:3}),
...native('new','document.inspect',1,{}),
...native('layer-old','type.info',1,{}, {layer:4}),
...native('layer-other','type.info',1,{layer:5}, {layer:5}),
...native('layer-new','type.info',1,{layer:4}, {layer:4}),
...native('edit','type.edit',1,{layer:4,text:'文案'}, {},{changed:true}),
...native('tree-old','layer.list',1,{}),
...receipt('switch','open_production_output',target),
...native('tree-other','layer.list',1,{}),
...native('tree-new','layer.list',1,{}),
];
verify(messages,['old','layer-old','tree-other'],
['separate','indexed','new','layer-other','layer-new','edit','tree-old','tree-new']);
});
test('catalog pages and document scopes retain distinct query results',()=>{
const catalog=(id,documentId,args)=>receipt(id,'native_catalog',{documentId,matchMode:'search',items:[]},args);
verify([
...catalog('old',1,{filter:'type'}),
...catalog('page',1,{filter:'type',offset:10}),
...catalog('other',2,{filter:'type'}),
...catalog('new',1,{filter:'type',limit:10}),
],['old'],['page','other','new']);
});
test('scripts fold only identical displayed output from complete read-only calls',()=>{
const read={name:'type.info',status:'ok',arguments:{}};
const call={...read,name:'native_call',arguments:{method:'engine.execute',params:{command:'type.info',params:{layer:4}}}};
const script=(id,calls,output,complete=true,details={})=>receipt(id,'codemode',details,{},
[text(`Script completed\nWall time ${id} seconds\nOutput:\n`),text(output)],
{nestedCalls:{calls,complete}});
verify([
...script('old',[call],'同一文案'),
...script('modified',[call],'脚本派生事实'),
...script('mixed',[call,{...read,name:'write_copy_fields'}],'同一文案'),
...script('partial',[call],'同一文案',false),
...script('truncated',[call],'同一文案',true,{fullOutputPath:'output.txt'}),
...script('new',[call],'同一文案'),
],['old'],['modified','mixed','partial','truncated','new']);
});
test('duplicate product notes reference the full text and preserve distinct notes and plan scopes',()=>{
const note='商品规格和选购备注。'.repeat(30);
const plan=(id,note,slotIds)=>receipt(id,'plan_production',{...target,product:{note},pictures:slotIds},{slotIds});
const messages=[
...plan('older',note,['A']),
...plan('different','已修改的商品备注',['B']),
...plan('new',note,['C']),
];
const projected=verify(messages,['older'],['different','new']);
const previous=JSON.parse(original(projected,'older').content[0].text);
assert.deepEqual(previous.pictures,['A']);
assert.equal(previous.product.note,undefined);
assert.equal(original(messages,'older').details.product.note,note);
});

View File

@ -1882,9 +1882,11 @@ test('draw limit receipts identify the template value or the bundled default reg
return {...page,template:{...page.template,production}};
};
const ops=await openProductionOperations(host);
const {pictures:[picture]}=await ops.plan_production({});
assert.equal(picture.maxGenerationAttempts,expected);
assert.equal(picture.generationLimitSource,source);
const {maxGenerationAttempts,generationLimitSource,pictures:[picture]}=await ops.plan_production({});
assert.equal(maxGenerationAttempts,expected);
assert.equal(generationLimitSource,source);
assert.equal(picture.maxGenerationAttempts,undefined);
assert.equal(picture.generationLimitSource,undefined);
await ops.close();
}
});
@ -1951,10 +1953,12 @@ test('the bundled draw limit applies in flight and a rejected candidate can stil
for(const [key,value] of Object.entries(expected))assert.equal(row[key],value,key);
};
const plan=()=>ops.plan_production({slotIds:['hero']});
const firstPicture=({pictures:[picture],maxGenerationAttempts,generationLimitSource})=>
({...picture,maxGenerationAttempts,generationLimitSource});
slot.generationRequestIds=['existing'];
assertStatus((await plan()).pictures[0],drawStatus(1,4));
assertStatus(firstPicture(await plan()),drawStatus(1,4));
await ops.retire_production_image({slotId:'hero',candidateId:'existing',reason:'构图不合适'});
assertStatus((await plan()).pictures[0],drawStatus(1,4));
assertStatus(firstPicture(await plan()),drawStatus(1,4));
const input={slotId:'hero',prompt:'同款正面'};
const a=await ops.prepare_image_request(input);
const b=await ops.prepare_image_request({...input,prompt:'同款侧面'});
@ -1962,7 +1966,7 @@ test('the bundled draw limit applies in flight and a rejected candidate can stil
while(ops.active)await ops.await_image_slots({slotIds:['hero']});
await ops.dispatch_image_request(approve(b));
while(ops.active)await ops.await_image_slots({slotIds:['hero']});
assertStatus((await plan()).pictures[0],drawStatus(3,4));
assertStatus(firstPicture(await plan()),drawStatus(3,4));
const fourth=await ops.prepare_image_request({...input,prompt:'同款俯拍'});
spare=await ops.prepare_image_request({...input,prompt:'同款低机位'});
@ -1993,6 +1997,6 @@ test('the bundled draw limit applies in flight and a rejected candidate can stil
assert.equal(exported[0].canvasRevision,3);
await ops.close();
const reopened=await openProductionOperations(host);
assertStatus((await reopened.plan_production()).pictures[0],drawStatus(4,4));
assertStatus(firstPicture(await reopened.plan_production()),drawStatus(4,4));
await reopened.close();
});