diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index fee40125..0af4a0de 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -1,8 +1,9 @@ +import { readFileSync } from 'node:fs'; import path from 'node:path'; import { isDeepStrictEqual } from 'node:util'; import { CanvasOperations } from './canvas-operations.mjs'; import { Type } from '@sinclair/typebox'; -import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agent'; +import { formatDimensionNote, parseFrontmatter, resizeImage } from '@earendil-works/pi-coding-agent'; import { productionLedger, recordProductionInputs } from './production-repository.mjs'; import { PresentationBatch } from './stream-presentation.mjs'; import { loadSlots } from './production-slots.mjs'; @@ -15,6 +16,10 @@ import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity import { reviewOutputScreen } from './screen-review.mjs'; import { createTailWatcher } from './tail-watcher.mjs'; +const {frontmatter: {maxGenerationAttempts: defaultGenerationLimit}} = parseFrontmatter( + readFileSync(new URL('./skills/product-image-sources/SKILL.md', import.meta.url), 'utf8'), +); + const obj=fields=>Type.Object(fields,{additionalProperties:false}); const text=Type.String({minLength:1}); const ids=Type.Array(text); @@ -323,7 +328,7 @@ const copyPage=field=>field.page??field.pageId; const slotPage=slot=>slot.documentId??slot.page??slot.pageId; const slotSignatures=slots=>Object.fromEntries(slots.map(slot=>[slot.id,slot.selectedCandidateId??null])); -export async function openProductionOperations(host,{maxActiveDelegates=6,maxGenerationAttempts: configuredLimit, +export async function openProductionOperations(host,{maxActiveDelegates=6, maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000, tailWatchClock}={}) { if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数'); @@ -335,7 +340,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const byId=new Map(slots.map(slot=>[slot.id,slot])); const byField=Map.groupBy(slots,slot=>slot.fieldId); const binding=JSON.stringify([plan.template.contentHash,variantId]); - const maxGenerationAttempts=configuredLimit??plan.template.production?.maxGenerationAttempts??host.productionSkills?.maxGenerationAttempts; + const templateLimit=plan.template.production?.maxGenerationAttempts; + const maxGenerationAttempts=(Number.isSafeInteger(templateLimit)&&templateLimit>0?templateLimit:undefined) + ??host.productionSkills?.maxGenerationAttempts??defaultGenerationLimit; const ledger=productionLedger(store,outputId,variantId); const {repository}=ledger; const previous=ledger.read(); @@ -446,10 +453,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const nativeGenerations=slot=>(slot.candidates??[]).filter(row=> !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id); const drawStatus=generationAttempts=>({ - generationAttempts,...(maxGenerationAttempts===undefined?null:{ - maxGenerationAttempts,remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts), - drawLimitReached:generationAttempts>=maxGenerationAttempts, - }), + generationAttempts,maxGenerationAttempts, + remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts), + drawLimitReached:generationAttempts>=maxGenerationAttempts, }); const drawStatuses=selected=>{ const ids=new Map(selected.map(slot=>[slot.id,nativeGenerations(slot)])); @@ -702,7 +708,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>{ signal?.throwIfAborted(); const claim=repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior, - {maxGenerationAttempts:maxGenerationAttempts??Infinity,nativeIds:nativeGenerations(live)}); + {maxGenerationAttempts,nativeIds:nativeGenerations(live)}); if(claim.claimed){ claimedOperationId=claim.original.operationId; submission=Promise.withResolvers(); diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 8848997a..3382c8da 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -1,6 +1,7 @@ --- name: product-image-sources description: Use product image sources and Image Request tools in PhotoCraft. +maxGenerationAttempts: 4 --- # 商品配图工具 diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 5e6b97f9..bafe99f0 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -9,6 +9,7 @@ import { openProductionOperations } from '../src/production-operations.mjs'; import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; import { bindRecovery } from '../src/desktop-host.mjs'; +import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs'; import { productionStore } from './production-store-fixture.mjs'; function imageBridge(host,dispatch,id=()=>randomUUID()) { @@ -297,9 +298,9 @@ for(const stop of ['abort','close','switch'])test(`${stop} stops queued lookups assert.equal(ledger.read().items.active.state,'unknown'); }); -const drawStatus=(attempts,max)=>({generationAttempts:attempts,...(max===undefined?null:{ +const drawStatus=(attempts,max=4)=>({generationAttempts:attempts, maxGenerationAttempts:max,remainingGenerationAttempts:Math.max(0,max-attempts),drawLimitReached:attempts>=max, -})}); +}); test('canvas advice leaves review, transformation and generation under agent control',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-canvas-adjust-')); @@ -1811,7 +1812,29 @@ test('copy writes forward revisions and optional expected text for the canvas to await ops.close(); }); -test('the fourth draw occupies the last slot while in flight and a rejected candidate can still be exported',async t=>{ +test('template draw limits override the lowest published enterprise Skill limit',async t=>{ + const {host}=await tailFixture(t,['hero']); + host.productionSkills=await openEnterpriseSkills(host.store,host.productionGoal,async()=>({ + skills:[6,5].map((limit,index)=>({ + fileId:`guide-${index}`,revision:'1',kind:'skill',path:`guides/guide-${index}/SKILL.md`, + text:`---\nname: guide-${index}\ndescription: Production guide.\nmaxGenerationAttempts: ${limit}\n---\n`, + })), + rules:[], + })); + const workflowRead=host.canvas.workflowRead; + for(const [production,expected] of [[{},5],[{maxGenerationAttempts:7},7]]){ + host.canvas.workflowRead=async()=>{ + const page=await workflowRead(); + return {...page,template:{...page.template,production}}; + }; + const ops=await openProductionOperations(host); + const {pictures:[picture]}=await ops.plan_production({}); + assert.equal(picture.maxGenerationAttempts,expected); + await ops.close(); + } +}); + +test('the bundled draw limit applies in flight and a rejected candidate can still be exported',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-draw-limit-')); t.after(()=>cleanup(dir)); const store=productionStore(dir); @@ -1848,7 +1871,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand }, }; let spare; - const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'},productionSkills:{maxGenerationAttempts:4}, + const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'}, async runDetailAgent(_slot,_system,prompt,tools){ const {candidateId}=JSON.parse(prompt); if(candidateId){ @@ -1891,12 +1914,12 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand await fourthStarted.promise; const stopped=await ops.dispatch_image_request(approve(spare)); fourthDone.resolve(); - assertStatus(stopped,{limitReached:true,...drawStatus(4,4)}); + assertStatus(stopped,{phase:'draw_limit_reached',limitReached:true,...drawStatus(4,4)}); assert.ok(stopped.candidates.some(row=>row.id===a.requestId)); assert.match(stopped.reason,/已发布的 4 次生图额度/u); await ops.await_image_slots({slotIds:['hero']}); assert.equal(dispatches.length,3); - assertStatus(await ops.prepare_image_request(input),{limitReached:true,...drawStatus(4,4)}); + assertStatus(await ops.prepare_image_request(input),{phase:'draw_limit_reached',limitReached:true,...drawStatus(4,4)}); assertStatus((await ops.review_image_slots({slotIds:['hero']})).pictures[0],drawStatus(4,4)); const [review]=await ops.check_image_slots({wait:true,candidates:[{slotId:'hero',candidateId:a.requestId}]}); assert.equal(review.verdict,'revise'); @@ -1912,7 +1935,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand assert.deepEqual((await callProductionTool(host,'finish_production',{revision:3})).files,['detail.png']); assert.equal(exported[0].canvasRevision,3); await ops.close(); - const reopened=await openProductionOperations(host,{maxGenerationAttempts:5}); - assertStatus((await reopened.plan_production()).pictures[0],drawStatus(4,5)); + const reopened=await openProductionOperations(host); + assertStatus((await reopened.plan_production()).pictures[0],drawStatus(4,4)); await reopened.close(); });