diff --git a/apps/detail-agent-pi/scripts/recover.mjs b/apps/detail-agent-pi/scripts/recover.mjs
deleted file mode 100644
index 614c3b80..00000000
--- a/apps/detail-agent-pi/scripts/recover.mjs
+++ /dev/null
@@ -1,17 +0,0 @@
-import fs from 'node:fs/promises';
-import path from 'node:path';
-import { Native98kBroker } from '../src/native-bridge.mjs';
-import { NativeControlClient } from '../src/native-control-client.mjs';
-import { ProjectStore, atomic } from '../src/store.mjs';
-import { DetailPiAgent } from '../src/agent.mjs';
-const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8')), id = process.argv[3];
-if (!id) throw Error('请提供原幂等键;仅查询原请求,不会发起推理');
-const broker = new Native98kBroker(config.broker), info = await broker.info();
-const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, config.canvasBinding || config.binding);
-const canvas = await NativeControlClient.connect(config.canvas);
-const host = await DetailPiAgent.open({ store, broker, canvas, protocolMode: config.protocolMode });
-try {
- const result = await host.recover(id, { executeReadOnly: true });
- await atomic(path.join(config.output, 'recovered-original-sse.json'), { id, ...result, checkedAt: new Date().toISOString() });
- console.log(JSON.stringify(result, null, 2));
-} finally { await host.dispose(); canvas.close(); }
diff --git a/apps/detail-agent-pi/scripts/verify-recovery.mjs b/apps/detail-agent-pi/scripts/verify-recovery.mjs
deleted file mode 100644
index 5d4d749d..00000000
--- a/apps/detail-agent-pi/scripts/verify-recovery.mjs
+++ /dev/null
@@ -1,23 +0,0 @@
-import fs from 'node:fs/promises';
-import path from 'node:path';
-import assert from 'node:assert/strict';
-import { Native98kBroker } from '../src/native-bridge.mjs';
-import { ProjectStore, atomic } from '../src/store.mjs';
-import { DetailPiAgent } from '../src/agent.mjs';
-const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
-const broker = new Native98kBroker(config.broker), info = await broker.info();
-const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, config.binding);
-const dir = path.join(config.broker.profile, 'jiansun/accounts', info.accountScope, 'pi-validation', config.broker.project, 'requests');
-const before = (await fs.readdir(dir)).sort();
-const host = await DetailPiAgent.open({ store, broker, protocolMode: 'native-tools' });
-try {
- const known = await host.recover('61616ad2-b1d4-4281-a63e-32a60876c5e2');
- assert.equal(known.alreadyApplied, true); assert.equal(known.reposted, false);
- const unknown = await host.recover('0447b17b-1c45-4902-a6a5-18357a3e2a3f');
- assert.equal(unknown.phase, 'unknown'); assert.equal(unknown.reposted, false);
- await assert.rejects(host.prompt('核查阻止重复发送的保护,不应真的发给模型'), /未知请求/);
- const after = (await fs.readdir(dir)).sort(); assert.deepEqual(after, before);
- const result = { known, unknown, newPromptBlocked: true, dispatchReceiptsBefore: before.length, dispatchReceiptsAfter: after.length, checkedAt: new Date().toISOString() };
- await atomic(path.join(config.output, 'readonly-recovery.json'), result);
- console.log(JSON.stringify(result, null, 2));
-} finally { await host.dispose(); }
diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs
index 70975f0b..66715dbc 100644
--- a/apps/detail-agent-pi/src/activity-event.mjs
+++ b/apps/detail-agent-pi/src/activity-event.mjs
@@ -9,7 +9,7 @@ const labels = Object.freeze({
canvas_candidate_image: '核对图位和候选', bash: '运行项目终端',
open_production_output: '打开制作画布', produce_current_output: '制作并验收当前输出',
generate_slot_image: '生成候选图片',
- plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
+ plan_production: '读取制作进度', start_production_strategy: '准备制作策划',
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍', transform_slot_image: '调整候选图片',
prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片',
diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs
index cf7cd21d..a27b79ed 100644
--- a/apps/detail-agent-pi/src/agent.mjs
+++ b/apps/detail-agent-pi/src/agent.mjs
@@ -1,5 +1,5 @@
import {setTimeout as delay} from 'node:timers/promises';
-import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, productRequestScope, ProductionOutputLimit, ProductionRequestFailed } from './production-recovery.mjs';
+import { productRequestScope } from './production-recovery.mjs';
import { enterpriseTools } from './enterprise-knowledge.mjs';
import { executeWorkflow } from './workflow-execute.mjs';
import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
@@ -11,29 +11,22 @@ 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,
- mayContinueProductionGoal } from './production-goal.mjs';
+import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
import { productionVideoTools } from './production-operations.mjs';
-import { COPY_IMAGE_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
-import { runToolCall } from '@earendil-works/pi-agent-core';
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';
import { atomic } from './store.mjs';
import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs';
-import { parseReceipt } from './receipt.mjs';
-import { auditResponse, InvalidToolReply } from './response-audit.mjs';
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
-import { requestPurpose } from './request-purpose.mjs';
import { productContext } from './project-context.mjs';
import { workflowContext, workflowResult } from './workflow-context.mjs';
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, contextLengths } from './context-usage.mjs';
import { activityScope, activitySummary, canvasPresence, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
-import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from './native-tools.mjs';
+import { nativeTools } from './native-tools.mjs';
import { NativeExtensionUI } from './native-ui.mjs';
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
@@ -69,22 +62,12 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料
references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
-const PRODUCTION_SYSTEM = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。
+const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布的企业 Skill、商品实拍、资料和模板制作并复核。按需读取适用 Skill 和引用。由你决定工作范围内的顺序、并行和返工。
${PRODUCT_VOICE}
-用 plan_production 读取本轮目标及待交付项。open_production_output 指定当前可写的成品和花色,切换回执包含保存结果和各成品的在途工作。list_project_images 可查询本项目已完成的候选,供跨成品复用。用户查看的页面和制作画布独立。
-${DRAW_LIMIT_GUIDANCE}
-用户附带引用时,按引用的 outputId、productVariantId、slotId、candidateId 或 nativeLayerId、component 定位目标,结合附带图片精修;实时选择不能替代本轮引用。
-企业制作指引中的命令行编修可用等价的画布命令完成。用 read_production_knowledge 时,fileId 取自 knowledgeFiles 列表,模板编号不能当作文件编号。read_copy_fields 省略 pageId 和 fieldId 即可一次读取全页文案字段及修订号。
-子代理生图和验图读取本屏实时文案,候选验图回执绑定当时的文案签名。文案还没写时派图,子代理缺少本款卖点,写入 goal 的模板原文也会变成制作要求。文案改动后要按新文案复核,画面与新卖点不符时需要返工。读清实拍、商品资料和制作规则后,建议每批选 1–3 屏,先用 write_copy_fields 把本批文案写到画布,再用 delegate_image_slots 派这批图位,生图期间写下一批。
-围绕每屏卖点主角定镜头和验收候选。分派 goal 依据本款实拍、商品资料、品牌规则和已确认的卖点,写明画面要重点呈现的部件、动作或结构,避免引用画布上尚未更新的模板原文。模板对应图位的原图符合卖点部位和景别时可参考构图,用本款实拍还原商品。模板原图拍了不同部位或景别时,传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 裁切本款实拍。回填回执列出压在图位上方的模板叠层。整屏成片填充完成后,可用 check_output_screens 并行复核实际成片,pages 从 1 编号,通过时自动登记。
-${COPY_IMAGE_SCREEN_CRITERIA}
-根据 needs_fix 回执中的 nativeLayerId、文案字段或图位定位修正。需要看实际像素时用 read_output_screen(其 page 从 0 编号)。可用 native_catalog 查命令,再用 native_call 移动、缩放、隐藏或改写叠层。映射文案可用 write_copy_fields,图片可用 transform_slot_image 调整或重新生图。结合实际画面和商品资料自行选择处理方式。
-需要独立观察结果的工具(如 open_production_output、read_output_screen、await_image_slots、finish_production)单独调用。多项连续查目录、批量采纳、批量回填文案及图层隐藏、选择、变换、样式修正等确定性操作,优先合并在一次 codemode 脚本中依次 await,使用各步实际回执衔接后续操作。
-${NATIVE_CANVAS_QUICK_REFERENCE}
-其余命令或完整参数说明用 native_catalog({ ids: [...] }) 一次取齐,在本回合和后续回合复用已取得的 parameterDocs。
-用 read_output_screen 复核多屏时,每次按需查看 2–4 屏。后续新读图时会自动释放较早的查看截图,保留文字元数据。
-transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
-独立手动复核时可用 record_screen_check 登记实际结果。复核后用 finish_production 提交当前画布修订,以工具返回的文件和版本为交付依据。可随时用 open_production_output 切换其它成品或回到此前的草稿。收口时用 finish_production 的 scope=all 核验本轮交付。子代理正在运行时可用 await_image_slots 等待回执。已返回结果未知的生图请求用 reconcile_image_slots 按原编号核查,核查期间可继续其它可做的图位和画布编辑。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
+用 plan_production 查看待交付项,open_production_output 切换可写画布,保留各成品在途工作。用 list_project_images 查询本项目可复用的候选。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
+读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
+用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。
+按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`;
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
// Both shapes are native projections of the frozen request, never the live selection.
@@ -92,6 +75,7 @@ const frozenReferences = context => Array.isArray(context?.requestScope?.referen
? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined;
// Only the native owner's explicit inactive-document response detaches display.
// Connection, account/authentication and all other failures must still surface.
+const workflowBindingError = '品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合';
const inactiveDocument = error => error?.category === 'scope_changed';
const sequentialTools = new Set([
'memory_set', 'canvas_edit', 'canvas_preview', 'copywriting_options', 'copywriting_fields',
@@ -111,9 +95,14 @@ function toolsFor(host) {
try {
host.productionSignal?.throwIfAborted();
const value = await execute(args, signal, ctx);
+ if ((name==='finish_production'||name==='defer_production_output') && value.finalized) {
+ if (value.completed) await ctx.executeTool('update_goal',{status:'complete'});
+ else await host.session.prompt('/goal pause');
+ }
return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value);
} catch(error) {
if (!(error instanceof BridgeError)) throw error;
+ if (!host.productionGoal&&host.canvasOperations.writesBlocked) host.canvasOperations.stopReason=error.message;
return {...plain({failure:error.wire()}),isError:true};
}
} });
@@ -135,11 +124,14 @@ function toolsFor(host) {
];
const projectResources = [...commands, ...enterpriseTools(host, make), ...productionVideoTools(host, make)];
if (host.productionGoal) return [
- ...productionTools.map(([name, description, schema])=>
- make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
+ ...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==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain)),
- ...contextTools, ...projectResources,
+ 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),
+ })),
+ ...contextTools.map(tool => ({...tool, exposure:'deferred'})), ...projectResources,
];
const tools = [
...contextTools,
@@ -170,7 +162,7 @@ function toolsFor(host) {
if(host.canvasNotificationsDetached || host.canvasOperations.writesBlocked)throw Error('当前项目已切换或用户已接手,本轮画布写入已停止');
const permission = await host.canvas.requestWrite(revision);
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧画布编辑未派发');
- if (!permission.allowed) throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked');
+ if (!permission.allowed || permission.writeBlocked) throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked');
if (permission.revision !== revision) throw new BridgeError('画布已修改,写入许可已过期,未执行','revision_conflict');
signal?.throwIfAborted();
if (host.canvasNotificationsDetached || host.canvasOperations.writesBlocked) throw Error('当前项目已切换或用户已接手,旧画布编辑未派发');
@@ -409,171 +401,119 @@ export class DetailPiAgent {
const workerFields = worker && {slotId:worker.slotId,requestScope:worker.requestScope};
if (worker?.signal) options = {...options,signal:AbortSignal.any([options.signal,worker.signal].filter(Boolean))};
(async () => {
- let requiredTool;
- let round, sentAt;
+ let round;
const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
try {
- options.signal?.throwIfAborted();
- if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
- if (host.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则');
- const liveCanvas = !worker && host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null;
- if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目');
- if (!worker && !host.compacting && (host.canvasNotificationsDetached || !host.productionGoal &&
- !liveCanvas?.manualEdit && (host.canvasOperations.writesBlocked || liveCanvas?.writeBlocked && host.canvasOperations.writeRequested))) {
- const text=host.canvasNotificationsDetached?'本机:原项目已切换,原回复保留在原项目,后续画布操作已停止。':host.canvasOperations.stopReason?`本次创作已停止:${host.canvasOperations.stopReason}`:'本机:已接手,剩余画布操作已停止。';
- const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } };
- await store.appendEvent({ type: host.canvasNotificationsDetached?'inactive_project_stopped':host.canvasOperations.stopReason?'workflow_operation_stopped':'handover_stopped', modelCallSkipped: true });
- output.push({ type: 'start', partial: message });
- output.push({ type: 'done', reason: 'stop', message }); output.end(message);
- return;
- }
- const completedProduction=!worker&&!host.compacting&&Boolean(host.productionCompletion?.receipt);
- if (completedProduction) {
- const text = host.productionCompletion.text;
- await store.appendEvent({ type:'production_stage_submitted', modelCallSkipped: true });
- const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } };
- output.push({ type: 'start', partial: message });
- output.push({ type: 'done', reason: 'stop', message }); output.end(message);
- return;
- }
- const encoded = !worker && protocolMode === 'structured-json' && !host.compacting;
- const wireContext = encoded ? jsonToolContext(context) : context;
- if (!worker) {
- host.currentCanvas = liveCanvas?.context;
- 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: encoded ? contextLengths(context).totalChars : totalChars });
- }
- if (transport?.stream) {
- const stream = transport.stream(model, wireContext, options);
- for await (const event of stream) output.push(event);
- const result = await stream.result();
- if (!worker && !host.compacting && result.stopReason !== 'error' && result.stopReason !== 'aborted') {
- const u = result.usage;
- await host.updateContextUsage({ inputTokens: u.input + u.cacheRead + u.cacheWrite, outputTokens: u.output, cachedTokens: u.cacheRead, model: info.model.id, at: Date.now(), source: 'sdk-response' }, 'running');
- }
- output.end(result);
- return;
- }
- round = (worker ? worker.broker : host.goalBroker ?? broker).round({inference:true});
- await store.appendEvent({ type: 'provider_prepared', id: round.id, requestId:round.id, model: model.id, bindingHash: store.hash,
- purpose, ...workerFields,
- ...(worker ? {imageCount:context.messages.reduce((count,message)=>count+
- (Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0)} : null) });
- if (!worker) {
- if (!host.compacting) requiredTool = host.requiredTool;
- }
- let wireCapture;
- let requestBytes, promptCacheKeyPresent, headersAt, firstThinkingAt, firstTextAt, firstToolAt;
- const stream = apiImpl.streamSimple(model, wireContext, { ...options,
- ...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
- apiKey: 'native-broker-only', fetch: async (...args) => {
- sentAt = Date.now();
- if (worker && typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
- await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,...workerFields});
- host.productionSignal?.throwIfAborted();
- const response = await round.fetch(...args);
- headersAt = Date.now();
- wireCapture = response.clone().text().then(text => ({ text }), error => ({ error }));
- return response;
- },
- onPayload: async payload => {
- applyOutputContract(payload);
- if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool);
- if (!worker && !encoded && api === 'openai-completions' && payload.tools?.length) {
- payload.tool_choice ||= 'auto';
- payload.parallel_tool_calls = false;
- }
- 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.
- promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
- if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
- await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
- }
- return payload;
- },
- });
- let finalEvent, partial, reply = '';
- for await (const event of stream) {
- if (event.type === 'thinking_delta' && firstThinkingAt === undefined) firstThinkingAt = Date.now();
- if (event.type === 'toolcall_delta' && firstToolAt === undefined) firstToolAt = Date.now();
- if (event.type === 'text_delta' && firstTextAt === undefined) firstTextAt = Date.now();
- // Release the final event only after the transport and wire audit finish.
- if (event.type === 'done' || event.type === 'error') finalEvent = event;
- else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
- else if (!encoded) output.push(event);
- else if (event.type === 'start') {
- partial = { ...event.partial, content: [] };
- output.push({ type: 'start', partial });
- } else if (event.type === 'text_delta' && partial) {
- const raw = event.partial.content.filter(c => c.type === 'text').map(c => c.text).join('');
- const current = parseStreamingJson(raw)?.reply;
- if (typeof current === 'string' && current.startsWith(reply) && current !== reply) {
- if (!reply) output.push({ type: 'text_start', contentIndex: 0, partial });
- const delta = current.slice(reply.length); reply = current;
- partial.content = [{ type: 'text', text: current }];
- output.push({ type: 'text_delta', contentIndex: 0, delta, partial });
- }
- }
- }
- const result = await stream.result();
- const valid = finalEvent?.type === 'done' && (worker
- ? ['stop','toolUse'].includes(result.stopReason) : host.compacting
- ? result.stopReason === 'stop' && !result.content.some(content => content.type === 'toolCall')
- : ['stop', 'toolUse', 'length'].includes(result.stopReason));
- const settled = await round.finish(valid, result.stopReason);
- await store.appendEvent({ type: 'provider_finished', id: round.id, requestId:round.id, ...settled,
- ...(worker ? {...workerFields,requestBytes,promptCacheKeyPresent} : null),
- ...(options.signal?.aborted || host.productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null),
- ...(sentAt === undefined ? {} : {
- ...(headersAt === undefined ? {} : {responseHeadersMs:headersAt-sentAt}),
- ...(firstThinkingAt === undefined ? {} : {firstThinkingMs:firstThinkingAt-sentAt}),
- ...(firstTextAt === undefined ? {} : {firstTextMs:firstTextAt-sentAt}),
- ...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}),
- }) });
- if (broker?.authority?.error) throw broker.authority.error;
- const failure = confirmedProductionFailure(settled, round.id);
- if (failure) throw failure;
- if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) {
- if (worker) throw new ProductionOutputLimit();
- host.productionSignal?.throwIfAborted();
- options.signal?.throwIfAborted();
- const message={...result,content:result.content.filter(block=>block.type!=='toolCall')};
- output.push({type:'done',reason:'length',message});
- output.end(message);
- return;
- }
- if (!valid || settled.phase !== 'complete') throw Error(result.errorMessage ?? 'network error: inference stream did not complete');
- const wire = await wireCapture;
- if (!wire || wire.error) throw Error('network error: incomplete inference receipt, tool was not executed');
- const usage = responseUsage(wire.text);
- await store.appendEvent({ type: 'usage', id: round.id, model: model.id, purpose, ...workerFields, ...usage });
+ options.signal?.throwIfAborted();
+ if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
+ const encoded = !worker && protocolMode === 'structured-json' && !host.compacting;
+ const wireContext = encoded ? jsonToolContext(context) : context;
+ if (!worker) {
+ 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: encoded ? contextLengths(context).totalChars : totalChars });
+ }
+ if (transport?.stream) {
+ const stream = transport.stream(model, wireContext, options);
+ for await (const event of stream) output.push(event);
+ const result = await stream.result();
+ if (!worker && !host.compacting && !['error','aborted'].includes(result.stopReason)) {
+ await host.recordUsage(result, {purpose});
+ }
+ output.end(result);
+ return;
+ }
+ round = (worker ? worker.broker : host.goalBroker ?? broker).round();
+ const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
+ let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
+ const stream = apiImpl.streamSimple(model, wireContext, { ...options,
+ ...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
+ apiKey: 'native-broker-only', fetch: async (...args) => {
+ sentAt=Date.now();
+ if (typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
+ await store.appendEvent({type:'provider_started',id:round.id,...workerFields,requestBytes});
host.productionSignal?.throwIfAborted();
- options.signal?.throwIfAborted();
- await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage });
- if (!worker && !host.compacting) await host.updateContextUsage({ ...usage, id: round.id, model: model.id, at: Date.now(), source: 'provider-response' }, 'running');
- const audit = auditResponse(wire.text, info.model.protocol);
- if (worker && result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回');
- host.productionSignal?.throwIfAborted();
- options.signal?.throwIfAborted();
- if (!encoded && requiredTool && !audit.calls.some(c => c.name === requiredTool)) throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
- if (!host.compacting && requiredTool) host.requiredTool = null;
- if (encoded) {
- const content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id);
- const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' };
- if (!partial) output.push({ type: 'start', partial: message });
- if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message });
- output.push({ type: 'done', reason: message.stopReason, message }); output.end(message);
- } else { output.push(finalEvent); output.end(result); }
+ const response=await round.fetch(...args);
+ headersAt=Date.now();
+ return response;
+ },
+ onPayload: async payload => {
+ applyOutputContract(payload);
+ if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool);
+ if (!worker && !encoded && api === 'openai-completions' && payload.tools?.length) {
+ payload.tool_choice ||= 'auto';
+ payload.parallel_tool_calls = false;
+ }
+ 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.
+ promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
+ if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
+ await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
+ }
+ return payload;
+ },
+ });
+ let finalEvent, partial, reply = '';
+ for await (const event of stream) {
+ if (event.type === 'text_delta') firstTextAt??=Date.now();
+ if (event.type === 'done' || event.type === 'error') finalEvent = event;
+ else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
+ else if (!encoded) output.push(event);
+ else if (event.type === 'start') {
+ partial = { ...event.partial, content: [] };
+ output.push({ type: 'start', partial });
+ } else if (event.type === 'text_delta' && partial) {
+ const raw = event.partial.content.filter(c => c.type === 'text').map(c => c.text).join('');
+ const current = parseStreamingJson(raw)?.reply;
+ if (typeof current === 'string' && current.startsWith(reply) && current !== reply) {
+ if (!reply) output.push({ type: 'text_start', contentIndex: 0, partial });
+ const delta = current.slice(reply.length); reply = current;
+ partial.content = [{ type: 'text', text: current }];
+ output.push({ type: 'text_delta', contentIndex: 0, delta, partial });
+ }
+ }
+ }
+ const result = await stream.result();
+ const {stopReason}=result;
+ await store.appendEvent({type:'provider_finished',id:round.id,stopReason,...workerFields,requestBytes,promptCacheKeyPresent,
+ ...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}),
+ ...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}),
+ ...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
+ if (broker?.authority?.error) throw broker.authority.error;
+ if (['error','aborted'].includes(stopReason)) {
+ result.errorMessage=redactText(result.errorMessage??'');
+ output.push(finalEvent);
+ output.end(result);
+ return;
+ }
+ host.productionSignal?.throwIfAborted();
+ options.signal?.throwIfAborted();
+ await host.recordUsage(result, {id:round.id,purpose,...workerFields}, !worker&&!host.compacting);
+ if (stopReason==='length') {
+ output.push(finalEvent);
+ output.end(result);
+ return;
+ }
+ if (requiredTool && !result.content.some(block=>block.type==='toolCall'&&block.name===requiredTool)) {
+ throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
+ }
+ if (requiredTool) host.requiredTool = null;
+ if (encoded) {
+ const content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id);
+ const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' };
+ if (!partial) output.push({ type: 'start', partial: message });
+ if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message });
+ output.push({ type: 'done', reason: message.stopReason, message }); output.end(message);
+ } else { output.push(finalEvent); output.end(result); }
} catch (error) {
const reason = redactText(String(error.message));
- const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+reason : reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
+ const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: options.signal?.aborted || host.productionSignal?.aborted ? 'aborted' : 'error', errorMessage: reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
await store.appendEvent({ type: 'provider_error', id: round?.id, ...workerFields, reason: message.errorMessage,
...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) });
- output.push({ type: 'error', reason: 'error', error: message }); output.end(message);
+ output.push({ type: 'error', reason: message.stopReason, error: message }); output.end(message);
}
})();
return output;
@@ -584,17 +524,18 @@ export class DetailPiAgent {
: SessionManager.create(store.dir, path.join(store.dir, 'sessions')));
if (typeof canvas?.uiRequest === 'function') host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
const files = await projectTools(host);
- const customTools = [...toolsFor(host),...files.tools];
+ const customTools = [...toolsFor(host), ...files.tools.map(tool =>
+ productionGoal && tool.name !== 'read' ? {...tool, exposure:'deferred'} : tool)];
host.workingDirectory=files.cwd;
const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], {
- includeGoal: !!productionGoal, mayContinueGoal: event => mayContinueProductionGoal(host, event),
+ includeGoal: !!productionGoal,
systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM,
});
host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime,
model: runtime.getModel('jiansun-native-98k', info.model.id),
thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined,
- resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal'] : []),
+ resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal','update_goal'] : []),
settingsManager: SettingsManager.inMemory({retry}), sessionManager: host.manager,
});
const workerSettings = SettingsManager.inMemory({retry,cacheWarming:'off',compaction:{enabled:false},enableSkillCommands:false});
@@ -652,6 +593,7 @@ export class DetailPiAgent {
await workerSession.sendCustomMessage({customType:'photocraft-worker-task',content,display:false},{triggerTurn:true});
activeSignal?.throwIfAborted();
const result = workerSession.messages.findLast(message=>message.role==='assistant');
+ if (result?.stopReason==='length') throw Error('模型回复达到单次输出长度,当前制作步骤未完成');
if (result?.stopReason==='error'||result?.stopReason==='aborted') {
throw Error(result.errorMessage||'当前制作步骤未完成');
}
@@ -663,6 +605,15 @@ export class DetailPiAgent {
await scoped?.close();
}
};
+ const finishTurn=session.agent.finishTurn;
+ session.agent.finishTurn=async (turn, signal)=>{
+ const decision=await finishTurn(turn,signal);
+ if (turn.message.stopReason==='length' || host.productionCompletion || !host.productionGoal &&
+ (host.canvasNotificationsDetached||host.canvasOperations.writesBlocked||host.workflowBindingChanged)) {
+ return {action:'end'};
+ }
+ return decision;
+ };
host.session = session;
session.subscribe(event => {
if (event.type === 'compaction_start') host.compacting = true;
@@ -748,7 +699,7 @@ export class DetailPiAgent {
}
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
const activity = toolActivity(event, host.activityScope || activityScope(store.identity));
- if (canvas) void host.notifyCanvas('activity', activitySummary(event),
+ if (canvas) await host.notifyCanvas('activity', activitySummary(event),
activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
await recordToolEvent(event,activity);
void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});
@@ -779,7 +730,7 @@ export class DetailPiAgent {
async readWorkflowContext(args) {
const epoch = this.turnEpoch;
if (this.canvasNotificationsDetached) throw Error('当前项目已切换,未读取其他项目工作流');
- if (this.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合');
+ if (this.workflowBindingChanged) throw Error(workflowBindingError);
const snapshot = await this.canvas.workflowRead(args);
const latest = workflowContext(snapshot, this.productIdentity);
if (this.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流读取不更新当前回合');
@@ -809,12 +760,14 @@ export class DetailPiAgent {
const {workflow,product}=(!this.productionGoal || this.productionGoal.outputId) && this.canvas?.workflowRead
? await this.readWorkflowContext({section:'overview'})
: {workflow:this.currentWorkflow,product:this.productEvidence};
- const value=await this.store.modelContext({workflow,canvas:this.currentCanvas,...options});
+ const canvas=await this.canvas?.read();
+ if (canvas?.conversationActive===false) throw Error('当前项目已切换,未读取其他项目画布');
+ const value=await this.store.modelContext({workflow,canvas:canvas?.context,...options});
value.currentProduct=product;
if (workflow) value.currentWorkflow=workflow;
if (this.productionSkills && loadKnowledge) {
- const {knowledge,documents}=this.productionSkills;
- value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]};
+ const {execution,files}=this.productionSkills;
+ value.enterpriseKnowledge={execution,sources:files};
value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule));
return value;
}
@@ -854,6 +807,15 @@ export class DetailPiAgent {
if (this.canvasOperations.stopReason) reply += `\n\n后续操作已停止。${this.canvasOperations.stopReason}`;
return reply;
}
+ async recordUsage({model,usage}, fields, updateContext=true) {
+ const {input,output,cacheRead,cacheWrite,totalTokens}=usage;
+ const receipt={model,inputTokens:input+cacheRead+cacheWrite,outputTokens:output,
+ cachedTokens:cacheRead,totalTokens,source:'sdk-response'};
+ const event={type:'usage',...fields,...receipt};
+ await this.store.appendEvent(event);
+ await this.onEvent(event);
+ if (updateContext) await this.updateContextUsage({...receipt,id:fields.id,at:Date.now()},'running');
+ }
async updateContextUsage(receipt = null, phase = 'ready') {
this.contextUsage = contextSnapshot(this.store.identity, this.info.model, this.session, this.contextUsage, receipt, phase);
if (phase === 'ready') {
@@ -866,7 +828,6 @@ export class DetailPiAgent {
return this.contextUsage;
}
async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false } = {}) {
- if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求');
if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求');
text = redactText(text);
const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info);
@@ -922,6 +883,9 @@ export class DetailPiAgent {
}
try {
const production=this.productionGoal;
+ if (!production && (await this.canvas?.read())?.conversationActive===false) {
+ throw Error('当前项目已切换,本轮对话未应用到其他项目');
+ }
if ((!production || production.outputId) && typeof this.canvas?.workflowRead === 'function') await this.readWorkflow({ section: 'overview' });
const template=production?.template??this.productionTemplate;
if (this.productionGoal && template?.enterprise) {
@@ -953,20 +917,20 @@ export class DetailPiAgent {
? undefined : await unfinishedProductionTurn(this);
const remaining=await closeProductionTurn(this);
this.productionSignal?.throwIfAborted();
+ if (this.workflowBindingChanged) throw Error(workflowBindingError);
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
const last = this.session.messages.filter(m => m.role === 'assistant').at(-1);
- const useCompletionReceipt = last?.stopReason === 'error' && this.productionCompletion && !this.canvasOperations.writesBlocked;
- if (last?.stopReason === 'aborted' || last?.stopReason === 'error' && !useCompletionReceipt) {
- throw Error(last.errorMessage || '本轮未完成;保留原请求');
+ if (last?.stopReason === 'aborted' || last?.stopReason === 'error') {
+ throw Error(last.errorMessage || '本轮对话未完成');
}
if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议');
- const resultText = useCompletionReceipt ? this.productionCompletion.text :
+ const resultText = this.productionCompletion?.text ?? this.canvasOperations.stopReason ??
(this.previewCancelled&&!this.previewReceipt
? '已取消本次预览,没有应用这项修改。'
- : presentText(this.session.getLastAssistantText() || this.productionCompletion?.text || ''));
- const textResult=this.productionGoal
- ? stripProductionToolText(resultText).trim()||this.productionCompletion?.text||''
- : resultText;
+ : presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || this.canvasOperations.stopReason || ''));
+ const textResult=this.productionGoal?stripProductionToolText(resultText).trim():
+ this.canvasNotificationsDetached&&last?.stopReason==='toolUse'
+ ? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText;
if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留');
await this.display.flush();
await this.updateContextUsage(null, 'ready');
@@ -1030,86 +994,6 @@ export class DetailPiAgent {
return result;
});
}
- async recover(id, options = {}) { return this.exclusive(() => this.recoverTurn(id, options)); }
- async recoverTurn(id, { executeReadOnly = false } = {}) {
- if (this.session.isStreaming) throw Error('先等待当前操作结束');
- const purpose = await requestPurpose(this, id);
- if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose)) {
- const original=await recoverProductionResponse(this.broker,id,this.session.model,[]);
- const {requestId}=original;
- const phase=['failed','rejected'].includes(original.phase)?'failed':original.phase==='complete'?'complete':'unknown';
- if (phase==='unknown' && original.recoveryError) {
- await this.store.appendEvent({type:'recovery_unknown',id,requestId,reason:original.recoveryError.message});
- }
- return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose==='whole-detail-review'
- ?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)};
- }
- const internalCompaction = ['compaction','legacy-compaction'].includes(purpose);
- let record = { id, ...await this.broker.read(id) };
- if (record.phase === 'unknown' || record.phase === 'dispatched') {
- try { await this.broker.recover(id); }
- catch (error) {
- await this.store.appendEvent({ type: 'recovery_unknown', id, requestId: record.requestId, reason: error.message });
- return { phase: 'unknown', requestId: record.requestId, reason: error.message, reposted: false, internalCompaction };
- }
- record = { id, ...await this.broker.read(id) };
- }
- if (purpose === 'cancelled') {
- const receipt = record.phase === 'received'
- ? await confirmProductionResponse(this.broker, record, this.session.model, this.session.agent.state.tools, this.protocolMode)
- : record;
- const phase = ['failed','rejected'].includes(receipt.phase) ? 'failed' : receipt.phase === 'complete' ? 'complete' : 'unknown';
- return {phase,requestId:receipt.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'};
- }
- if (internalCompaction) {
- return {phase:['complete','received','failed','rejected'].includes(record.phase)?'complete':'unknown',
- requestId:record.requestId,reposted:false,internalCompaction:true,toolsExecuted:0,canvasWrites:0};
- }
- if (record.phase === 'failed') return { phase: 'failed', requestId: record.requestId, reposted: false };
- if (record.phase === 'unavailable') return {phase: 'unknown', requestId: record.requestId, reposted: false,
- needsManualReview: true, reason: '原对话结果不可用,保留待核查,未自动放弃或重发', toolsExecuted: 0, canvasWrites: 0};
- const message = await parseReceipt(record, this.session.model, this.protocolMode, this.session.agent.state.tools);
- if (record.phase === 'received') await this.broker.confirm(id, record.bodyHash, true, message.stopReason);
- if (message.stopReason === 'length') return { phase: 'complete', usable: false, reason: 'output_limit', toolsExecuted: 0, reposted: false };
- const entries = this.manager.getEntries(), calls = message.content.filter(c => c.type === 'toolCall');
- const recorded = message.responseId && entries.some(e => e.type === 'message' && e.message.role === 'assistant' && e.message.responseId === message.responseId);
- const completed = calls.every(call => entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id));
- if (recorded && completed) return { phase: 'complete', requestId: record.requestId, alreadyApplied: true, reposted: false };
- if (calls.length && executeReadOnly && calls.every(call => ['context_read', 'memory_search', 'canvas_read', 'workflow_read'].includes(call.name))) {
- const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1);
- if (!recorded && last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null);
- if (!recorded) this.manager.appendMessage(message);
- if (this.canvas) await this.canvas.begin('取回原请求,恢复只读步骤');
- let recovered = 0;
- try {
- for (const call of calls) {
- if (entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id)) continue;
- const outcome = await runToolCall(call, { tools: this.session.agent.state.tools, assistantMessage: message, context: { messages: this.session.messages, tools: this.session.agent.state.tools }, beforeToolCall: this.session.agent.beforeToolCall, afterToolCall: this.session.agent.afterToolCall });
- this.manager.appendMessage({ role: 'toolResult', toolCallId: call.id, toolName: call.name, content: outcome.result.content, isError: outcome.isError, timestamp: Date.now() });
- recovered++;
- }
- } finally { if (this.canvas) await this.canvas.end('原请求已取回,未重发;画布未被修改。'); }
- const pending = await this.store.get('recovered-tools.json', []);
- await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending.map(t => t.id === id ? { ...t, phase: 'read-only-complete' } : t));
- await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
- this.needsReopen = true;
- return { phase: 'complete', requestId: record.requestId, reposted: false, readOnlyToolsRecovered: recovered, canvasWrites: 0, reopenRequired: true };
- }
- if (calls.length) {
- const pending = await this.store.get('recovered-tools.json', []);
- if (!pending.some(t => t.id === id)) pending.push({ id, requestId: record.requestId, phase: 'review', message });
- await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending);
- return { phase: 'complete', needsToolReview: true, requestId: record.requestId, reposted: false, toolsExecuted: 0 };
- }
- const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1);
- if (last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null);
- this.manager.appendMessage(message);
- this.manager.appendCustomEntry('pi-recovered-receipt', { id, requestId: record.requestId, restoredAt: Date.now() });
- await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
- this.needsReopen = true;
- return { phase: 'complete', requestId: record.requestId, reposted: false, reopenRequired: true, toolsExecuted: 0,
- restoredText: presentText(message.content.filter(c => c.type === 'text').map(c => c.text).join('\n')) };
- }
async dispose() {
this.disposed = true;
if (this.nativeUI) this.nativeUI.active = false;
diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs
index 67cbfcea..ebfbf195 100644
--- a/apps/detail-agent-pi/src/candidate-review.mjs
+++ b/apps/detail-agent-pi/src/candidate-review.mjs
@@ -25,7 +25,7 @@ export const canvasTransformArgs={
export async function reviewProductionCandidate({
canvas,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
- reviewKnowledge,liveScreenCopy,
+ liveScreenCopy,
}) {
const input=await canvas.detailImages(slot.id,candidateId,{
...(adopted?{adopted:true}:null),
@@ -84,7 +84,7 @@ export async function reviewProductionCandidate({
const requirements=rule?.focus??input.prompt??input.requirements;
const prompt=JSON.stringify({candidateId,fieldId:slot.fieldId,slot:slot.label,rule,requirements,
templateContext:requirements===input.requirements?undefined:input.requirements,
- screenCopy,taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files,
+ screenCopy,
productReferenceCount:originalImages.length,layoutReferenceCount:layoutImages.length,
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,
@@ -95,7 +95,6 @@ export async function reviewProductionCandidate({
'原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。',
'用 shownSubject 描述实际画面,用 shownFields 标明与文案对应的画面依据。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。',
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
- ...(reviewKnowledge.files.length?['用 read_production_knowledge 获取 knowledgeFiles 中适用的企业 Skill 和审稿规则。']:[]),
'调用 review_candidate 提交结论。',
].join('\n');
const images=[input.images.at(-1),...originalImages,...layoutImages];
@@ -103,7 +102,7 @@ export async function reviewProductionCandidate({
'同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0'))),
...layoutImages.map(()=> '模板构图参考')];
const scope=productRequestScope('review',candidateId);
- await runAgent(slot.id,instructions,prompt,[review,...reviewKnowledge.tools],images,scope,captions,signal);
+ await runAgent(slot.id,instructions,prompt,[review],images,scope,captions,signal);
signal?.throwIfAborted();
if(!receipt)throw new InvalidToolReply('独立验图未提交结论');
return {...receipt,referenceCount,...(input.candidateFile?{original:input.candidateFile}:null)};
diff --git a/apps/detail-agent-pi/src/context-usage.mjs b/apps/detail-agent-pi/src/context-usage.mjs
index 73df7938..8edb2ffd 100644
--- a/apps/detail-agent-pi/src/context-usage.mjs
+++ b/apps/detail-agent-pi/src/context-usage.mjs
@@ -12,6 +12,39 @@ export function contextLengths(context) {
}).length;
return {textChars, totalChars: textChars + imageChars};
}
+const productionReads = new Set(['plan_production', 'read_copy_fields', 'review_image_slots']);
+
+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 latest = new Set();
+ let folded;
+ for (let index = messages.length - 1; index >= 0; index--) {
+ 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);
+ continue;
+ }
+ folded ??= messages.slice();
+ folded[index] = {...message, details:undefined, content:[{type:'text',
+ text:'同范围已有更新回执。旧回执编号:'+message.toolCallId+',可用 memory_search 读取。'}]};
+ }
+ return folded ?? messages;
+}
+
export function modelCapacity(model) {
const limit = count(model.contextWindow);
return limit > 0 && typeof model.contextWindowSource === 'string' && model.contextWindowSource.length > 0
diff --git a/apps/detail-agent-pi/src/copy-image-alignment.mjs b/apps/detail-agent-pi/src/copy-image-alignment.mjs
index c3522ff9..ac597780 100644
--- a/apps/detail-agent-pi/src/copy-image-alignment.mjs
+++ b/apps/detail-agent-pi/src/copy-image-alignment.mjs
@@ -1,11 +1,7 @@
-export const COPY_IMAGE_PLANNING_GUIDANCE='先看本款实拍和商品资料,结合模板各屏的版式职能与品牌调性策划卖点和文案,再以文案确定画面。只给实拍或资料能支撑的部件安排卖点屏。';
-export const DRAW_LIMIT_GUIDANCE='每个图位最多发起 4 次远端生图。达到上限后,横向比较已有候选,选最合适的一张直接采纳,也可用实拍裁切或画布调整。汇报中简述取舍,后续可由人工通过「引用」定向精修。';
-export const COPY_IMAGE_PROMPT_GUIDANCE='卖点主角就是画面主角。让文案讲的具体部件、动作或结构成为清晰的视觉焦点。模板原图与本屏卖点部位和景别一致时可参考构图,并用本款实拍还原商品。模板原图与当前卖点部位或景别不同时,可传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 从本款实拍裁切对应部件。实拍或版式无法可靠呈现时,按资料调整对应文案。'+DRAW_LIMIT_GUIDANCE;
-export const OVERLAY_SCREEN_CRITERIA='模板尺寸线、虚线轮廓、引线、标注文字和装饰角标沿用旧图与旧文案的位置。换图或改字后,结合整屏合成切片与 overlayLayers 才能看出叠层错位、压字或数值不符。overlapsSlots 对应图位的 fieldId,bounds 是画布像素边界,text 是图层当前文字,mapped 表示是否映射。对照商品资料核对尺寸数值、引线端点、产品结构线和虚线轮廓的贴合情况,也检查装饰对齐、文字溢出、裁切及浅色背景上的可读性。';
-export const OVERLAY_FIX_GUIDANCE='按画面和商品资料自行选择修法。用 native_catalog 查命令,通过 native_call 按 nativeLayerId 移动、缩放、隐藏或改写叠层。映射文案可用 write_copy_fields,图片可用 transform_slot_image 调整或重新生图。用 read_output_screen 复看实际画面。';
-const IMAGE_COPY_CRITERIA='对照 screenCopy、商品资料与实际画面逐条核对图文一致性,确认对应图位把卖点部位、动作或结构清晰呈现为焦点,并核对材质、颜色、款式和结构是否真实可见,场景或功能卖点是否与实拍及 SKU 花色相符,尺寸、规格、数量是否与画面和标注自洽。';
-export const COPY_IMAGE_SCREEN_CRITERIA=IMAGE_COPY_CRITERIA+OVERLAY_SCREEN_CRITERIA;
-export const COPY_IMAGE_SCREEN_GUIDANCE=COPY_IMAGE_SCREEN_CRITERIA+OVERLAY_FIX_GUIDANCE;
+export const COPY_IMAGE_PROMPT_GUIDANCE='让画面清晰呈现关联文案的重点。模板原图与目标画面不符时可设置 useTemplateReference: false,用本款实拍保持商品一致。构图可用 transform_slot_image 调整,具体创作要求见适用企业 Skill。';
+export const COPY_IMAGE_REVIEW_GUIDANCE='用 shownSubject 描述实际可见内容,再对照关联和同屏实时文案,填写 checks.copyAlignment,检查对应部位是否清晰可见,指出不符的文案和可见依据。按适用企业 Skill 判断视觉标准。';
+export const OVERLAY_SCREEN_CRITERIA='核对叠层错位、压字或数值不符。overlayLayers 的 overlapsSlots 对应图位 fieldId,bounds 为像素边界,text 为当前文字,mapped 表示是否已映射。';
+export const COPY_IMAGE_SCREEN_GUIDANCE='对照商品资料、实时文案和适用企业 Skill 核对整屏实际画面。检查材质、颜色、款式、结构、尺寸与标注是否一致,以及文字溢出、裁切和可读性。'+OVERLAY_SCREEN_CRITERIA;
const fieldId = row => row.field ?? row.fieldId;
const belongsTo = (ids, id) => Array.isArray(ids) && ids.includes(id);
@@ -16,15 +12,14 @@ function screenCopyRow(row) {
return {field:fieldId(row),label:row.label,role:row.role,text:row.currentText,templateSample:Boolean(row.templateSample)};
}
-export function resolveLiveSlotCopy({slot,copyFields=[],pages=[],journalCopy=[]}) {
+export function resolveLiveSlotCopy({slot,copyFields=[],journalCopy=[]}) {
const slotIds=[slot.fieldId,slot.id].filter(Boolean);
const directJournal=journalCopy.filter(row=>slotIds.some(id=>belongsTo(row.pictures,id)));
const journalByField=new Map(directJournal.map(row=>[fieldId(row),row]));
const isDirect=row=>journalByField.has(fieldId(row))||
slotIds.some(id=>belongsTo(row.relatedFields,id))||belongsTo(slot.relatedFields,fieldId(row));
const directPage=copyFields.find(row=>isDirect(row)&&fieldPage(row));
- const page=slot.page??slot.pageId??slot.documentId??(directPage&&fieldPage(directPage))??
- pages.find(id=>slot.fieldId?.startsWith(id+'-')||slot.fieldId?.startsWith(id+'_'));
+ const page=slot.page??slot.pageId??slot.documentId??(directPage&&fieldPage(directPage));
const liveFields=new Set(copyFields.map(fieldId));
const resolved=new Map();
for(const row of copyFields){
diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs
index 1a0d1184..b6210b17 100644
--- a/apps/detail-agent-pi/src/desktop-host.mjs
+++ b/apps/detail-agent-pi/src/desktop-host.mjs
@@ -138,7 +138,6 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
}
let host, broker, store, output, atomic, heartbeat;
let releaseRecovery;
- const historical = config.mode==='recover'||config.mode==='review';
const productionGoal=config.mode==='prompt'&&config.productProduction===true
? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs,
pendingOutputs:config.pendingOutputs,drafts:config.productionDrafts,workspaceId:config.workspaceId,template:config.productionTemplate,
@@ -156,7 +155,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
const blocked = productionGoalPreflight(productionGoal);
if (blocked) return blocked;
}
- const modelRole=config.mode==='recover'?config.modelRole||'chat':productionGoal?'detail':'chat';
+ const modelRole=productionGoal?'detail':'chat';
const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole,
dispatchLease:config.dispatchLease,onAuthorizationLost};
broker=sharedBroker??new Native98kBroker(bindingConfig);
@@ -173,8 +172,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true });
signal?.throwIfAborted();
broker.bind(bindingConfig);
- const info = await broker.info(config.mode==='recover'?{original:true,id:config.productionOriginals?.[0]}
- :productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
+ const info = await broker.info(productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
const brokerReadyAt = performance.now();
if (info.accountScope !== config.scope) throw authorityFailure('scope_changed');
store.executionScope={runId:config.runId ?? randomUUID(),outputId:config.outputId,variantId:config.variantId,
@@ -197,47 +195,11 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
host.qaNativeTimeout = command => consumeQaNativeTimeout({scope:info.accountScope, project:config.project, documentId:config.documentId,
accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin}, command);
signal?.throwIfAborted();
- let result;
- if(config.mode==='recover' && (config.productionOriginals?.length ||
- info.pending.length && info.pending.every(request=>typeof request.detailSlot==='string'))){
- const settled=[];
- const originals=config.productionOriginals ?? info.pending.map(request=>request.id);
- for(const id of new Set(originals)){
- signal?.throwIfAborted();
- try {
- const checked=await host.recover(id,{executeReadOnly:false});
- settled.push({id,phase:checked.phase});
- } catch (error) {
- signal?.throwIfAborted();
- await store.appendEvent({type:'production_original_check_failed',id,category:BridgeError.from(error).category});
- settled.push({id,phase:'unknown'});
- }
- }
- const remaining=settled.filter(request=>request.phase==='unknown').length;
- result={phase:remaining?'unknown':'complete',reposted:false,canvasWrites:0,
- settledOriginalIds:settled.filter(request=>request.phase==='complete'||request.phase==='failed').map(request=>request.id),
- text:'已核查 '+settled.length+' 条制作原请求,'+remaining+' 条仍待核查。'};
- } else if (config.mode === 'recover') {
- const pending = info.pending;
- if (pending.length !== 1) throw Error('待核查请求数量异常,请保留项目和请求号');
- result = await host.recover(pending[0].id, { executeReadOnly: false });
- result.text = result.phase === 'unknown' ? `原请求仍待核查(${result.requestId || pending[0].id}),未重发。`
- : result.internalCompaction ? '已核对旧摘要的请求记录。需要时,小壹会整理这段对话。'
- : result.phase === 'failed' ? '已确认这条请求失败。你可以在原对话发送新消息。'
- : result.needsToolReview ? '原响应已取回。画布建议尚待核对,未自动执行。' : '原响应已取回,未重新调用模型。';
- if (result.restoredText) result.text += '\n\n' + result.restoredText;
- } else if (config.mode === 'review') {
- const pending = await store.get('recovered-tools.json', []);
- // Acknowledge/discard recovered mutation proposals. Never replay them.
- await atomic(path.join(store.dir, 'recovered-tools.json'), pending.map(t => t.phase === 'review' ? { ...t, phase: 'discarded', reviewedAt: Date.now() } : t));
- result = { text: '已放弃原响应中的未执行建议;已完成的修改保留。', reposted: false };
- } else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry });
+ const result = await host.prompt(config.text, {referenceContent:config.referenceContent,goalContinuation:!!productionGoal&&!config.goalUserEntry});
signal?.throwIfAborted();
if (broker.authority?.error) throw broker.authority.error;
- const pending = historical?(await broker.status()).pending:[];
- const reviews = historical?(await store.get('recovered-tools.json', [])).filter(t => t.phase === 'review'):[];
- output = { ...result, unknown: pending.length > 0, review: reviews.length > 0, usage, contextUsage: host.contextUsage,
- pending, bindingHash: store.hash, sessionFile: host.manager.getSessionFile() };
+ output = {...result,unknown:false,usage,contextUsage:host.contextUsage,
+ pending:[],bindingHash:store.hash,sessionFile:host.manager.getSessionFile()};
} catch (error) {
const authority = [signal?.reason, broker?.authority?.error, error].find(authorityLost);
if (authority) {
@@ -252,15 +214,10 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
} catch { /* The paused receipt reports the actual draft write outcome. */ }
}
return {phase:'paused', draftSaved, error:authority.message, failure:authority.wire(),
- unknown:broker?.hasUnconfirmedRequest ?? false, reposted:false};
- }
- let pending = [], unknown = false;
- if (historical && broker) {
- try { pending = (await broker.status()).pending; unknown = pending.length > 0; }
- catch { unknown = broker.hasUnconfirmedRequest; }
+ unknown:false,reposted:false};
}
const failure = BridgeError.from(error).wire();
- output = { error:failure.message, failure, unknown, pending, reposted:false, contextUsage:host?.contextUsage };
+ output = {error:failure.message,failure,unknown:false,pending:[],reposted:false,contextUsage:host?.contextUsage};
} finally {
clearInterval(heartbeat);
signal?.removeEventListener('abort',abort);
diff --git a/apps/detail-agent-pi/src/enterprise-context.mjs b/apps/detail-agent-pi/src/enterprise-context.mjs
index 79419765..8062da80 100644
--- a/apps/detail-agent-pi/src/enterprise-context.mjs
+++ b/apps/detail-agent-pi/src/enterprise-context.mjs
@@ -86,12 +86,6 @@ export class EnterpriseContext {
skill=await this.specificDocument(directory,entry.target,'skill',options);
knowledge.skills.push(skill);
}
- const prefix=path.posix.dirname(entry.target)+'/references/';
- const references=new Set(links(skill).filter(({target})=>target.startsWith(prefix)).map(({target})=>target));
- for (const target of references) {
- if (knowledge.rules.some(rule=>rule.path===target)) continue;
- knowledge.rules.push(await this.specificDocument(directory,target,'native-reference',options));
- }
}
async declaredGuides(identity,options) {
@@ -123,11 +117,13 @@ export class EnterpriseContext {
continue;
}
const target=kind==='skill'?skills:rules;
- if (pinned) {
+ if (pinned?.text != null) {
target.push({...pinned,kind});
+ } else if (identity.task === 'production' && kind !== 'skill' && kind !== 'template-reference') {
+ target.push({fileId:pinned?.fileId??fileId,revision:pinned?.revision??revision,path:source,kind});
} else {
- const {result}=await this.client.readDocument(fileId,revision,{signal},read);
- target.push({fileId,revision,path:source,kind,pages:result.pages,text:result.text});
+ const {result}=await this.client.readDocument(pinned?.fileId??fileId,pinned?.revision??revision,{signal},read);
+ target.push({fileId:pinned?.fileId??fileId,revision:pinned?.revision??revision,path:source,kind,pages:result.pages,text:result.text});
}
}
if(!skills.length)throw Error('所选模板未声明制作 Skill 正文');
@@ -141,17 +137,24 @@ export class EnterpriseContext {
const bytes = await fs.readFile(result.localPath, {signal});
return {...source,sha256:result.sha256,kind:'skill-runtime',bytes:bytes.toString('base64')};
}
+ if (source) {
+ const {result}=await this.client.readDocument(source.fileId,source.revision,{signal},read);
+ return {...source,kind:source.kind??'native-reference',text:result.text};
+ }
directory??=(await read(()=>this.client.call('list_libraries',{},{signal}))).result.navigation
?.find(item=>item.name==='Skills')?.path;
if (!directory || !target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录');
- if (!source) return this.specificDocument(directory,target,'native-reference',{signal,read});
- const {result}=await this.client.readDocument(source.fileId,source.revision,{signal},read);
- return {...source,kind:'native-reference',text:result.text};
+ return this.specificDocument(directory,target,'native-reference',{signal,read});
}
async specificDocument(directory,target,kind,{signal,read,pins}) {
if (!target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录');
- if (pins?.has(target)) return {...pins.get(target),kind};
+ const pinned=pins?.get(target);
+ if (pinned) {
+ if (typeof pinned.text === 'string') return {...pinned,kind};
+ const {result}=await this.client.readDocument(pinned.fileId,pinned.revision,{signal},read);
+ return {...pinned,kind,text:result.text};
+ }
let entry, offset=0, revision;
for (;;) {
const found=(await read(()=>this.client.call('search_files',{query:path.posix.basename(target),directory:path.posix.dirname(target),limit:40,offset,...(revision?{revision}:{})},{signal}))).result;
diff --git a/apps/detail-agent-pi/src/enterprise-skill-resources.mjs b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs
index 877cee14..d338fff8 100644
--- a/apps/detail-agent-pi/src/enterprise-skill-resources.mjs
+++ b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs
@@ -1,6 +1,6 @@
import fs from 'node:fs/promises';
import path from 'node:path';
-import { loadSkills } from '@earendil-works/pi-coding-agent';
+import { loadSkills, parseFrontmatter } from '@earendil-works/pi-coding-agent';
import { atomic, digest } from './store.mjs';
import { links } from './enterprise-context.mjs';
@@ -21,7 +21,10 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
for (const source of prior.scriptSources ?? []) {
if (!pins.has(source.path)) pins.set(source.path, source);
}
- for (const source of [...prior.skills, ...prior.rules]) pins.set(source.path, source);
+ for (const source of [...prior.skills, ...prior.rules]) {
+ const pinned = pins.get(source.path);
+ if (!pinned || pinned.text == null && source.text != null) pins.set(source.path, source);
+ }
}
return pins;
}
@@ -68,7 +71,19 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
}
}
- for (const item of [...knowledge.skills, ...knowledge.rules]) await materialize(item);
+ for (const item of knowledge.skills) await materialize(item);
+ for (const item of knowledge.rules) {
+ if (typeof item.text === 'string' || item.kind === 'skill-runtime') await materialize(item);
+ else {
+ if (!validPath(item.path)) throw Error('已发布的规则资源路径无效:' + item.path);
+ references.set(filePath(item.path), {target:item.path,from:'发布资源'});
+ }
+ }
+
+ for (const {path:relative} of knowledge.referenceSources ?? []) {
+ if (!validPath(relative)) throw Error('已发布的规则资源路径无效:' + relative);
+ if (!references.has(filePath(relative))) references.set(filePath(relative), {target:relative,from:'发布资源'});
+ }
const scriptSources = new Map();
for (const source of knowledge.scriptSources ?? []) {
@@ -85,10 +100,11 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
async function resolveReference({target, from}, script, signal) {
try {
const pins = await readPins();
- const source = script ?? knowledge.referenceSources?.find(item => item.path === target);
+ const source = script ?? knowledge.rules.find(item => item.path === target) ??
+ knowledge.referenceSources?.find(item => item.path === target);
const pinned = pins.get(target);
const hasContent = script ? pinned?.kind === 'skill-runtime' : typeof pinned?.text === 'string';
- const item = hasContent ? {...pinned,kind:script ? 'skill-runtime' : 'native-reference'} :
+ const item = hasContent ? {...pinned,kind:source?.kind??pinned.kind} :
await loadReference(target, {source,directory:knowledge.skillDirectory,signal});
if (item.path !== target) throw Error('返回的资源路径与锁定路径不一致');
if (script && (item.fileId !== script.fileId || item.revision !== script.revision)) {
@@ -96,10 +112,12 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
signal?.throwIfAborted();
const save = saving.then(async () => {
- if (knowledge.rules.some(rule => rule.path === target)) return;
- const rules = [...knowledge.rules, item];
+ const index = knowledge.rules.findIndex(rule => rule.path === target);
+ const rules = [...knowledge.rules];
+ if (index === -1) rules.push(item);
+ else rules[index] = item;
await atomic(snapshot, {...knowledge, rules});
- knowledge.rules.push(item);
+ knowledge.rules = rules;
});
saving = save.catch(() => {});
await save;
@@ -122,9 +140,9 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
async function shellFiles(signal) {
- for (const file of scriptSources.keys()) {
+ for (const file of [...scriptSources.keys(), ...knowledge.rules.map(item => filePath(item.path))]) {
signal.throwIfAborted();
- if (!await resolveFile(file, signal)) throw Error('无法读取已发布的脚本资源:' + scriptSources.get(file).path);
+ if (!await resolveFile(file, signal)) throw Error('无法读取已发布的脚本资料:' + path.basename(file));
}
return [...documents].map(([file, source]) => ({file, source}));
}
@@ -139,5 +157,22 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
await store.appendEvent({type:'enterprise_skill_resources_bound', outputId:selection.outputId,
...((knowledge.resourceRevision) ? {resourceRevision:knowledge.resourceRevision} : null),
sources:[...documents.values()]});
- return {knowledge, resource, documents, resolveFile, shellFiles};
+ const limits = knowledge.skills.map(({text}) => parseFrontmatter(text).frontmatter.maxGenerationAttempts)
+ .filter(limit => Number.isSafeInteger(limit) && limit > 0);
+ return {
+ maxGenerationAttempts: limits.length ? Math.min(...limits) : undefined,
+ execution:knowledge.execution,
+ get sources() {
+ return [...knowledge.skills,...knowledge.rules]
+ .map(({fileId,revision,path,kind})=>({fileId,revision,path,kind}));
+ },
+ get files() {
+ const sources=new Map(this.sources.map(source=>[source.path,source]));
+ for (const source of knowledge.referenceSources ?? []) {
+ if (!sources.has(source.path)) sources.set(source.path,source);
+ }
+ return [...sources.values()].map(source=>({...source,path:filePath(source.path)}));
+ },
+ resource, documents, resolveFile, shellFiles,
+ };
}
diff --git a/apps/detail-agent-pi/src/native-bridge.mjs b/apps/detail-agent-pi/src/native-bridge.mjs
index 8fda5d71..0a01195f 100644
--- a/apps/detail-agent-pi/src/native-bridge.mjs
+++ b/apps/detail-agent-pi/src/native-bridge.mjs
@@ -34,8 +34,6 @@ export class Native98kBroker {
}
if(!['chat','copy','detail'].includes(modelRole))throw Error('模型用途无效');
Object.assign(this, { binary, profile, project, modelRole, invocationHeaders, spawnProcess });
- this.potentiallyDispatched = new Set();
- this.dispatchScopes = new Map();
this.children = new Set();
this.authority = {};
}
@@ -50,16 +48,13 @@ export class Native98kBroker {
return worker;
}
bind({ binary, profile, project, scope, modelRole = 'chat', dispatchLease, onAuthorizationLost }) {
- if (this.active || this.closed || this.failed) throw Error('模型桥状态不可复用,未派发新请求');
+ if (this.active || this.closed) throw Error('模型桥状态不可复用,未派发新请求');
if (binary !== this.binary || profile !== this.profile || !/^[a-f0-9-]{36}$/i.test(project) || typeof scope !== 'string' || !scope) throw Error('模型桥账户或项目配置不匹配');
if(!['chat','copy','detail'].includes(modelRole))throw Error('模型用途无效');
this.project = project; this.scope = scope; this.modelRole=modelRole; this.invocationHeaders = {};
this.selectionId = undefined;
this.authority = { onAuthorizationLost };
this.dispatchLease = dispatchLease;
- const identity = JSON.stringify([scope, project]);
- if (!this.dispatchScopes.has(identity)) this.dispatchScopes.set(identity, new Set());
- this.potentiallyDispatched = this.dispatchScopes.get(identity);
}
revoke(error, notify = true) {
if (!this.authority.error) {
@@ -68,7 +63,11 @@ export class Native98kBroker {
}
}
async open(signal) {
- if (this.failed) throw this.failed;
+ if (this.failed) {
+ await this.exited;
+ this.child = null;
+ this.failed = null;
+ }
if (this.closed || this.parent?.closed) throw Error('模型桥已关闭');
if (this.child) return;
let local;
@@ -94,9 +93,8 @@ export class Native98kBroker {
let value;
try { value = JSON.parse(line); } catch { fail(); return; }
const active = this.active;
- if (!active || !value || !['headers', 'chunk', 'result', 'error'].includes(value.type) || (value.type === 'error' && typeof value.error !== 'string') || (value.type === 'result' && (!value.value || typeof value.value !== 'object')) || (['headers', 'chunk'].includes(value.type) && !['request', 'recover'].includes(active.method))) { fail(); return; }
+ if (!active || !value || !['headers', 'chunk', 'result', 'error'].includes(value.type) || (value.type === 'error' && typeof value.error !== 'string') || (value.type === 'result' && (!value.value || typeof value.value !== 'object')) || (['headers', 'chunk'].includes(value.type) && active.method !== 'request')) { fail(); return; }
if (value.type === 'headers' && value.status === 401) {
- if (active.method === 'request') this.potentiallyDispatched.delete(active.requestId);
this.revoke(authorityFailure('auth_revoked', {dispatched:true}));
}
try { active.onEvent(value); } catch { fail(); return; }
@@ -105,10 +103,7 @@ export class Native98kBroker {
if (value.type === 'error') {
const error = new BridgeError(value.error, value.category, value);
if (authorityLost(error)) this.revoke(error);
- if (active.method === 'request' && value.dispatched === false) {
- this.potentiallyDispatched.delete(active.requestId);
- error.retryPreparation = value.retryPreparation === true;
- }
+ error.retryPreparation = value.retryPreparation === true;
active.reject(error);
}
else if (value.value && typeof value.value === 'object') active.resolve(value.value);
@@ -127,39 +122,30 @@ export class Native98kBroker {
const authority = this.authority;
const run = async () => {
signal?.throwIfAborted();
- const needsAuthority = !['status','read','finish'].includes(method);
if (authority !== this.authority) throw authorityFailure('scope_changed');
- if (needsAuthority && authority.error) throw authority.error;
+ if (authority.error) throw authority.error;
await this.open(signal);
signal?.throwIfAborted();
if (authority !== this.authority) throw authorityFailure('scope_changed');
- if (needsAuthority && authority.error) throw authority.error;
+ if (authority.error) throw authority.error;
if (this.failed) throw this.failed;
if (this.closed) throw Error('模型桥已关闭');
return new Promise((resolve, reject) => {
this.active = { resolve, reject, onEvent, method, requestId: args.id };
- if (method === 'request' && args.id && args.inference !== true) this.potentiallyDispatched.add(args.id);
try { this.child.stdin.write(JSON.stringify({ ...args, method, project: this.project, accountScope: this.scope, ...(this.modelRole==='chat'?{}:{modelRole:this.modelRole}), ...(this.detailSlot?{detailSlot:this.detailSlot}:{}), dispatchLease:this.dispatchLease }) + '\n', error => {
- if (error && this.active) { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); const active = this.active; this.active = null; active.reject(this.failed); this.child.kill(); }
- }); } catch { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); this.active = null; reject(this.failed); this.child.kill(); }
+ if (error && this.active) { this.failed = Error('network error: 模型桥连接中断'); const active = this.active; this.active = null; active.reject(this.failed); this.child.kill(); }
+ }); } catch { this.failed = Error('network error: 模型桥连接中断'); this.active = null; reject(this.failed); this.child.kill(); }
});
};
const result = (this.queue || Promise.resolve()).then(run);
this.queue = result.catch(() => {});
- const value = await result;
- if ((['finish', 'recover'].includes(method) && ['complete', 'rejected', 'failed'].includes(value.phase))
- || (method === 'request' && value.phase === 'failed' && value.failureCode === 'rate_limit_exceeded')) {
- this.potentiallyDispatched.delete(args.id);
- }
- return value;
+ return result;
}
- get hasUnconfirmedRequest() { return this.potentiallyDispatched.size > 0; }
- isUnconfirmed(id) { return this.potentiallyDispatched.has(id); }
async close({ force = false } = {}) {
this.closed = true;
const children = [...this.children].map(worker => worker.close({ force }));
const active = this.active;
- if (active) { this.active = null; active.reject(Error('模型桥已关闭,原请求需核查;不会重发')); }
+ if (active) { this.active = null; active.reject(Error('模型桥已关闭')); }
if (this.child) {
if (active || force) this.child.kill();
else this.child.stdin.end();
@@ -169,7 +155,6 @@ export class Native98kBroker {
await Promise.all(children);
this.parent?.children.delete(this);
}
- status() { return this.start('status'); }
async info(args) {
const info = await this.start('info', args);
if (this.scope && info.accountScope !== this.scope) {
@@ -182,12 +167,13 @@ export class Native98kBroker {
this.selectionId = info.selectionId ?? undefined;
return info;
}
- /** A new fetch object for ONE provider request. It refuses all implicit retries. */
- round({ inference = false } = {}) {
+ /** One native request per Pi attempt. */
+ round() {
const id = randomUUID();
- let calls = 0, metadata, completed;
+ let sent = false;
const fetch = async (address, init = {}) => {
- if (++calls !== 1) throw Error('禁止自动重发模型请求');
+ if (sent) throw Error('每次模型调用只接受一个请求');
+ sent = true;
init.signal?.throwIfAborted();
const url = new URL(typeof address === 'string' || address instanceof URL ? address : address.url);
if (url.origin !== 'https://api.vip98k.com' || !['/v1/messages', '/v1/chat/completions', '/v1/responses'].includes(url.pathname) || init.method?.toUpperCase() !== 'POST' || typeof init.body !== 'string') throw Error('模型请求边界无效');
@@ -197,23 +183,17 @@ export class Native98kBroker {
let cancelled = false;
const enqueue = data => { if (!cancelled) { try { controller.enqueue(data); } catch { cancelled = true; } } };
const request = () => this.start('request', { id, body: init.body, invocationPath: url.pathname, invocationHeaders: this.invocationHeaders,
- selectionId: this.selectionId, ...(inference ? { inference:true } : {}) }, event => {
+ selectionId: this.selectionId }, event => {
if (event.type === 'headers') {
- metadata = event;
resolveHeaders(new Response(body, { status: event.status, headers: event.headers }));
} else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64'));
}, init.signal);
- if (inference && this.failed) {
- await this.exited;
- this.child = null;
- this.failed = null;
- }
const abort = () => {
if (!this.authority.error && this.active?.requestId === id) this.child?.kill();
};
init.signal?.addEventListener('abort', abort, {once:true});
- completed = request().catch(error=>{
- if (inference && (error.retryPreparation || /^98k(?:连接|响应)中断/u.test(error.message))) {
+ const completed = request().catch(error=>{
+ if (error.retryPreparation || /^98k(?:连接|响应)中断$/u.test(error.message)) {
throw Error('network error: '+error.message);
}
throw error;
@@ -224,21 +204,8 @@ export class Native98kBroker {
});
return ready;
};
- return {
- id, fetch,
- finish: async (valid, reason) => {
- if (!completed) return { phase: 'not_dispatched' };
- const result = await completed;
- if (inference) return result;
- if (result.phase === 'failed' && result.failureCode === 'rate_limit_exceeded') return result;
- if (result.phase !== 'received') throw Error(`请求 ${id} 结果未知;不会重发`);
- return this.start('finish', { id, bodyHash: metadata.bodyHash, valid, reason });
- },
- };
+ return {id,fetch};
}
- read(id) { return this.start('read', { id }); }
- recover(id) { return this.start('recover', { id }); }
- confirm(id, bodyHash, valid, reason) { return this.start('finish', { id, bodyHash, valid, reason }); }
knowledge(brandId) { return this.start('knowledge', { brandId: brandId ?? null }); }
}
diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs
index de247f3f..6e7bcdc8 100644
--- a/apps/detail-agent-pi/src/photocraft-extension.mjs
+++ b/apps/detail-agent-pi/src/photocraft-extension.mjs
@@ -6,6 +6,8 @@ import {
DefaultResourceLoader,
SettingsManager,
} from '@earendil-works/pi-coding-agent';
+import { foldSupersededProductionReads } from './context-usage.mjs';
+import { settleProductionGoal } from './production-goal.mjs';
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
const sdkToolNames = Object.freeze(['codemode', 'tool_search']);
@@ -30,7 +32,7 @@ export function nativeToolMetadata(name) {
* Instantiate the official factories through the public SDK loader.
*/
export async function createPhotoCraftExtensions(host, existing = [], {
- includeGoal = false, mayContinueGoal, systemPrompt = '', includeProjectResources = true,
+ includeGoal = false, systemPrompt = '', includeProjectResources = true,
} = {}) {
const cwd = host?.workingDirectory ?? host?.store?.dir;
if (typeof cwd !== 'string' || !cwd) throw new TypeError('工作台未能找到制作工具的工作目录');
@@ -63,6 +65,19 @@ export async function createPhotoCraftExtensions(host, existing = [], {
{name: 'photocraft-codemode', factory: createCodemodeExtension({models: false})},
{name: 'photocraft-tool-search', factory: createToolSearchExtension()},
{name: 'photocraft-image-context', factory: createImageContextPruningExtension()},
+ ...(includeGoal ? [{name:'photocraft-production-context', factory: pi => {
+ pi.on('context', event => {
+ const messages = foldSupersededProductionReads(event.messages);
+ const isReminder = message => message.role === 'custom' && message.customType === 'pi-goal-event' &&
+ ['active', 'resumed', 'continuation'].includes(message.details?.kind);
+ const latest = messages.findLast(isReminder);
+ if (!latest) return {messages};
+ return {messages:messages.flatMap(message => message === latest
+ ? [{...message,content:'继续当前制作目标:'+latest.details.goal.objective}]
+ : isReminder(message)?[]:[message])};
+ });
+ if (host.productionGoal) pi.on('agent_end', event => settleProductionGoal(host,event));
+ }}] : []),
],
});
await loader.reload();
@@ -71,23 +86,6 @@ export async function createPhotoCraftExtensions(host, existing = [], {
const cause = new Error(result.errors.map(error => `${error.path}: ${error.error}`).join('; '));
throw new Error('工作台未能加载制作工具,请重新打开客户端后重试', { cause });
}
- if (includeGoal) {
- const goal = result.extensions.findLast(extension => extension.commands.has('goal'));
- if (!goal) throw Error('当前客户端无法继续制作目标,请更新完整客户端');
- goal.handlers.set('context', [...goal.handlers.get('context') ?? [], event => ({
- messages: event.messages.map(message => {
- const {kind,goal:state}=message.details??{};
- if (message.role!=='custom'||message.customType!=='pi-goal-event'||
- !['active','resumed','continuation'].includes(kind)||!state?.objective) return message;
- return {...message,content:'继续当前制作目标:'+state.objective+
- '\n沿用已完成的工作。需要事实或画布状态时按需读取,以实际文件回执确认交付。'};
- }),
- })]);
- // Apply the production gate only when the plugin could queue another turn.
- goal.handlers.set('agent_end', goal.handlers.get('agent_end').map(handler => async (event, ctx) => {
- if (!ctx.hasPendingMessages() && (!mayContinueGoal || await mayContinueGoal(event))) return handler(event, ctx);
- }));
- }
return {...result, resourceLoader: loader};
}
diff --git a/apps/detail-agent-pi/src/product-copy-evidence.mjs b/apps/detail-agent-pi/src/product-copy-evidence.mjs
deleted file mode 100644
index 8ee285cb..00000000
--- a/apps/detail-agent-pi/src/product-copy-evidence.mjs
+++ /dev/null
@@ -1,50 +0,0 @@
-export const copyProofInstructions = [
- '先拆分一句话中的各项商品主张,逐项核对当前款式的依据。照片可以证明看得见的颜色、纹理、形状、部件关系,以及画面实际显示的动作和接触。',
- '材质成分、尺寸数值、功能效果、体感、使用难易、耐用性、认证和承诺需要本款资料明确记录。姿态、产品形状和能拍出的使用情景都不能证明这些结论。圆角能从照片核对,触感柔和、手感顺滑等描述需要同款资料。',
- '相邻、分离、环绕或遮挡只能按原片写成可见位置关系。内部固定方式、部件承力路径、成型工艺和手工加工需要本款资料明确记录。照片中的独立轮廓可以写分离或两块,不能据此写分开成型。',
- '同样的颜色或纹理只能证明外观。部件使用同一材料或处在同一平面,需要本款资料明确说明所指部件。按提交文案的实际意思核对,空间不足时改写为短而完整的句子。',
- '一句话只要含有未经证实的结论,即使另半句的外观属实,也应退回或改写为原图可以核对的部件、位置和关系。创意设想仅用于布景。',
- '卖点面向买家,使用自然完整的短语或短句。每段说清哪个部位有什么特点或平时怎么使用。用买家的口吻逐句读一遍,退回重复词、同义叠加和没有主体的部件罗列。机位要求、人物为取景做的避让及验图结论放在制作说明。',
-];
-
-// A finish or colour can be described from a photo, but its composition
-// requires an explicit declaration from the product brief.
-const materialTerms=/真皮|头层牛皮|牛皮|羊皮|皮革|超纤皮|不锈钢|铝合金|碳钢|铁艺|金属(?!色|感|光泽)|实木|橡胶木(?!色|纹)|橡木(?!色|纹)|胡桃木(?!色|纹)/gu;
-const uncertain=/未确认|未登记|未提供|不明确|不确定|不是|并非|待确认|待核实|无法|不能|无依据|缺失|可能|疑似|看起来/u;
-
-export function unsupportedMaterial(text,brief) {
- const declarations=[brief?.name,brief?.note].filter(value=>typeof value==='string')
- .flatMap(value=>value.split(/[。;;\n]+/u)).filter(line=>!uncertain.test(line));
- const verified=new Set(declarations.flatMap(line=>line.match(materialTerms)??[]));
- return [...new Set(text.match(materialTerms)??[])].filter(material=>!verified.has(material));
-}
-
-const assertedTerms = /不硌手|不磕碰|不顶背|不卡|不用绷着|不闷|不勒|透气|亲肤|(?:触感|手感)(?:柔和|柔软|细腻|顺滑|光滑|温润|舒适|偏硬)?|久坐不累|(?:可以|适合|可)久坐|不易侧倾|耐(?:磨|用|刮|久)|防(?:滑|水|潮)|抗菌|阻燃|防霉|环保|甲醛|承重|质保|[0-9]+(?:[..][0-9]+)?\s*(?:毫米|厘米|公分|公斤|千克|kg|mm|cm)|[eE][nN][fF]/gu;
-const assemblyClaim = /(? text.split(/[,,、]+/u).map(part=>part.trim());
-const materialOrPlaneClaim = /(?:同一(?:种|款|批)?|相同)(?:的)?[^、,。]{0,8}(?:面料|材质|材料)|同(?:面料|材质|材料)|(?:面料|材质|材料)(?:完全)?(?:相同|一致)|共面|同一平面/u;
-const manufacturingClaim = /一体成型|分体成型|分开成型|整体成型|一体铸造|分体铸造|一体压铸|整体浇铸|手工打磨|手工缝制/u;
-const incompletePlaneClaim = /(?:与|和|及).+同面$/u;
-const relationClauses = text => text.split(/[,,]+/u).map(part=>part.trim());
-
-export function unsupportedClaims(text, brief) {
- const declarations=[brief?.name,brief?.note,brief?.dimensions]
- .filter(item=>typeof item==='string')
- .flatMap(item=>item.split(/[。;;\n]+/u))
- .filter(line=>!uncertain.test(line)&&!/(模板|样例|示意|参考)/u.test(line));
- const confirmed=new Set(declarations.flatMap(line=>line.match(assertedTerms)??[]));
- const brand=brief?.brandName;
- const templateBrand=brand&&brand.length>1&&text.includes(brand)&&
- !declarations.some(line=>line.includes(brand)&&(line===brief.name||/(?:商品|产品|实物)?品牌\s*[::]/u.test(line)))?[brand]:[];
- const statements=text.split(/[。;;\n]+/u).filter(line=>!/(?:未|待|请|以).{0,16}(?:核实|核对|确认|为准)/u.test(line));
- const documentedAssembly=new Set(declarations.flatMap(clauses));
- const unprovenAssembly=statements.flatMap(clauses).filter(clause=>{
- const claim=assemblyClaim.exec(clause);
- return claim&&(claim.index===0||!documentedAssembly.has(clause));
- });
- const documentedRelations=new Set(declarations.flatMap(relationClauses));
- const unprovenRelations=statements.flatMap(relationClauses).filter(clause=>
- incompletePlaneClaim.test(clause)||((materialOrPlaneClaim.test(clause)||manufacturingClaim.test(clause))&&!documentedRelations.has(clause)));
- return [...new Set([...unsupportedMaterial(text,brief),...templateBrand,...unprovenAssembly,...unprovenRelations,...statements.flatMap(line=>line.match(assertedTerms)??[])
- .filter(term=>!confirmed.has(term))])];
-}
diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs
index 6828b89b..79957e79 100644
--- a/apps/detail-agent-pi/src/production-goal.mjs
+++ b/apps/detail-agent-pi/src/production-goal.mjs
@@ -1,12 +1,11 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import lockfile from 'proper-lockfile';
-import { productionKnowledge } from './production-knowledge.mjs';
-import { SessionManager } from '@earendil-works/pi-coding-agent';
+import { createAgentSession, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
import { imageResult, openProductionOperations, productionOperationTools, reconcileProjectImageSlots } from './production-operations.mjs';
+import { createPhotoCraftExtensions } from './photocraft-extension.mjs';
import { BridgeError } from './bridge-error.mjs';
import { checkOutputCapabilities } from './output-capabilities.mjs';
-import { COPY_IMAGE_PLANNING_GUIDANCE, COPY_IMAGE_PROMPT_GUIDANCE } from './copy-image-alignment.mjs';
export function productionGoalPreflight(goal) {
const outputPreflight = checkOutputCapabilities(goal.requestedOutputs);
@@ -18,7 +17,7 @@ export function productionGoalPreflight(goal) {
export function productionObjective(requestedOutputs) {
const outputs = [...new Set(requestedOutputs.map(row=>row.label || row.outputId))].join('、');
- return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。当前由小壹原生画布自动合成并导出,无需询问制作软件或合成方式。${COPY_IMAGE_PLANNING_GUIDANCE}${COPY_IMAGE_PROMPT_GUIDANCE}验图和整屏复核时自主核对图文一致性,用 read_output_screen 逐条核对实时文案与对应图位的画面主角。发现不符时,依据商品资料用原生工具修图或改字,再看屏确认。`;
+ return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。`;
}
export function piGoalState(manager) {
@@ -31,10 +30,20 @@ export async function recordProductionExport(dir, goalId) {
try {
const saved = JSON.parse(await fs.readFile(path.join(dir, 'session.json'), 'utf8'));
const manager = SessionManager.open(path.join(dir, 'sessions', path.basename(saved.file)), dir, dir);
- const entry = manager.getBranch().findLast(row => row.type === 'custom' && row.customType === 'pi-goal');
- if (entry?.data?.goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致');
- if (entry.data.goal.status !== 'complete') {
- manager.appendCustomEntry('pi-goal', {...entry.data, goal:{...entry.data.goal, status:'complete', updatedAt:Date.now()}});
+ const goal = piGoalState(manager);
+ if (goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致');
+ if (goal.status !== 'complete') {
+ const host = {store:{dir}};
+ const {resourceLoader} = await createPhotoCraftExtensions(host, [], { includeGoal:true, includeProjectResources:false });
+ const modelRuntime = await ModelRuntime.create({ modelsPath:null, allowModelNetwork:false, refreshOnCreate:false,
+ authPath:path.join(dir,'pi-runtime-auth.json'), modelsStorePath:path.join(dir,'pi-model-cache') });
+ const {session} = await createAgentSession({cwd:dir, agentDir:dir, modelRuntime, resourceLoader,
+ settingsManager:SettingsManager.inMemory({}), sessionManager:manager, tools:['update_goal']});
+ try {
+ await session.bindExtensions({mode:'rpc'});
+ session.setActiveToolsByName(['update_goal']);
+ await session.agent.state.tools.find(tool=>tool.name==='update_goal').execute(goalId,{status:'complete'});
+ } finally { session.dispose(); }
}
return {recorded:true, goalId};
} finally { await unlock(); }
@@ -45,7 +54,7 @@ export async function runPiProductionGoal(host, text, continuation, images=[]) {
watchBoundOutput(host);
const current = piGoalState(host.manager);
const objective = productionObjective(host.productionGoal.requestedOutputs);
- const continuing = current && current.status !== 'complete' && current.objective === objective;
+ const continuing = current && current.status !== 'complete' && current.objective.startsWith(objective);
if (!continuation || !continuing) {
const request = JSON.stringify({request:text,
requestedOutputs:host.productionGoal.requestedOutputs,product:host.productEvidence?.product});
@@ -59,28 +68,34 @@ export async function runPiProductionGoal(host, text, continuation, images=[]) {
await host.session.prompt('/goal resume');
}
await host.session.waitForIdle();
- if (host.productionPause) await host.session.prompt('/goal pause');
- if (host.productionCompletion?.receipt.completed === true) {
- const entry = host.manager.getBranch().findLast(row => row.type === 'custom' && row.customType === 'pi-goal');
- if (entry) host.manager.appendCustomEntry('pi-goal', {...entry.data,
- goal:{...entry.data.goal,status:'complete',updatedAt:Date.now()}});
+ const end = host.session.messages.findLast(message=>message.role==='assistant');
+ if (['error','aborted','length'].includes(end?.stopReason) && piGoalState(host.manager)?.status==='active') {
+ await host.session.prompt('/goal pause');
}
}
-export async function mayContinueProductionGoal(host, event) {
- const messages=event?.messages??[];
+export async function settleProductionGoal(host, {messages}) {
+ const active=piGoalState(host.manager)?.status==='active';
+ if (host.productionCompletion) {
+ if (active) await host.session.prompt('/goal pause');
+ host.session.clearQueue();
+ return;
+ }
+ if (!active) return;
const end=messages.findLast(message=>message.role==='assistant');
- if(end?.stopReason==='error'||end?.stopReason==='aborted')return false;
- if(host.productionSignal?.aborted||host.compacting||host.canvasNotificationsDetached||host.productionCompletion)return false;
+ if (['error','aborted','length'].includes(end?.stopReason)) {
+ host.session.clearQueue();
+ return;
+ }
const start=messages.findLastIndex(message=>message.role==='custom'&&message.customType==='pi-goal-event'
&& ['continuation','resumed'].includes(message.details?.kind));
- if(start===-1||!end||piGoalState(host.manager)?.status!=='active')return true;
- if(messages.slice(start+1).some(message=>message.role==='toolResult'))return true;
+ if(start===-1||!end||messages.slice(start+1).some(message=>message.role==='toolResult'))return;
const blocker=host.productionGoal.drafts?.findLast(draft=>draft.blocker)?.blocker;
host.productionPause=blocker
? {reason:blocker.reason,requiredAction:blocker.requiredAction}
: {reason:end.content.filter(part=>part.type==='text').map(part=>part.text).join('\n').trim()};
- return false;
+ await host.session.prompt('/goal pause');
+ host.session.clearQueue();
}
export { productionOperationTools as productionTools };
@@ -91,20 +106,22 @@ export async function callProductionTool(host, name, args, signal) {
const started=performance.now();
const previous=await currentProductionOperations(host)?.catch(()=>undefined);
const switched=goal.outputId!==args.outputId||goal.variantId!==args.variantId;
- if(switched)await previous?.suspendCanvas();
+ let binding;
try {
- const previousImageRequests=switched?previous?.workStatus().inFlightImages:undefined;
- const binding=await host.canvas.openProductionOutput(previousImageRequests?.length
+ const previousImageRequests=switched?await previous?.suspendCanvas():undefined;
+ binding=await host.canvas.openProductionOutput(previousImageRequests?.length
?{...args,previousImageRequests}:args,signal);
- const switchMs=Math.round(performance.now()-started);
- if(binding.accepted===false)previous?.resumeCanvas();
- else await bindProductionOutput(host,binding);
- return {...binding,switchMs,work:(await productionWork(host)).map(operations=>operations.workStatus())};
} catch(error) {
if (Object.hasOwn(error,'productionCanvas')) await bindProductionOutput(host,error.productionCanvas);
else previous?.resumeCanvas();
throw error;
}
+ const switchMs=Math.round(performance.now()-started);
+ if(binding.accepted===false)previous?.resumeCanvas();
+ else await bindProductionOutput(host,binding);
+ const work=await productionWork(host);
+ const originals=work.length?await host.canvas.imageRequest('pending',{}):[];
+ return {...binding,switchMs,work:work.map(operations=>operations.workStatus(originals))};
}
if (name==='list_project_images')
return {candidates:await host.canvas.detailHistory({projectImages:true,...args})};
@@ -118,7 +135,6 @@ export async function callProductionTool(host, name, args, signal) {
const options={targetOutput:target,...(input.candidateId&&!input.includeReferences
?{includeProductReferences:false,includeTemplateReference:false}:null)};
return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)});
-
}
if(!working&&!['plan_production','review_image_slots','await_image_slots','reconcile_image_slots','check_image_slots'].includes(name))
return {...target,accepted:false,reason:'canvas_inactive',workingOutput:goal.outputId?{
@@ -133,14 +149,9 @@ export async function callProductionTool(host, name, args, signal) {
if (name==='plan_production') {
const {id,name,version,productionRoute}=goal.template??{};
const {product,dimensions,note}=host.productEvidence??{};
- const knowledge=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext);
return {requestedOutputs:goal.requestedOutputs,pendingOutputs:goal.pendingOutputs,
workingOutput:null,template:{id,name,version,productionRoute},product:{...product,dimensions,note},
- knowledgeFiles:knowledge.files};
- }
- if (name==='read_production_knowledge') {
- const knowledge=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext);
- return knowledge.tools[0]? (await knowledge.tools[0].execute('',args,signal)).details:{files:[]};
+ ...(args.includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null)};
}
throw Error('请先用 open_production_output 打开本轮工作画布');
}
diff --git a/apps/detail-agent-pi/src/production-knowledge.mjs b/apps/detail-agent-pi/src/production-knowledge.mjs
deleted file mode 100644
index d60a6056..00000000
--- a/apps/detail-agent-pi/src/production-knowledge.mjs
+++ /dev/null
@@ -1,55 +0,0 @@
-import { Type } from '@sinclair/typebox';
-
-const stageRules = {
- strategy: ['selling-points', 'evidence', 'brand', 'product-visual', 'template-reference'],
- copy: ['selling-points', 'content-planning', 'evidence', 'brand', 'output'],
- image: ['image-production', 'image-prompt', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
- review: ['review', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
-};
-
-export const knowledgeFileIdInstruction = 'fileId 必须取自 knowledgeFiles 列表,不能传模板编号。';
-
-const pageSize = 6000;
-export function productionKnowledge(knowledge, stage) {
- const documents = [...(knowledge?.skills ?? []), ...(knowledge?.rules ?? [])]
- .filter(document => document.fileId && document.revision && (typeof document.text === 'string'||typeof document.loadText === 'function')
- && (!stage || document.kind === 'skill' || stageRules[stage].includes(document.kind)));
- const files = documents.map(({fileId,revision,path,kind}) => ({fileId,revision,path,kind}));
- const brief = documents.find(document=>document.kind===(stage==='image'?'image-production':stage));
- let taskGuidance;
- const guidance = () => taskGuidance ??= brief && readPage(brief,0);
- async function readPage(document,offset) {
- const {fileId,revision}=document;
- const body=document.text??await document.loadText();
- const text=body.slice(offset,offset+pageSize);
- const nextOffset=offset+text.length;
- return {fileId,revision,text,nextOffset:nextOffset
{
- signal?.throwIfAborted();
- const document=documents.find(entry=>entry.fileId===fileId);
- if(!document)throw Error('该文件不属于当前制作阶段使用的知识资料');
- const details=await readPage(document,offset);
- signal?.throwIfAborted();
- return {content:[{type:'text',text:JSON.stringify(details)}],details};
- },
- }]};
-}
-
-export function productionRuleText(knowledge, kind, limit, headings) {
- const text=knowledge?.rules?.find(document=>document.kind===kind)?.text;
- if(typeof text!=='string')return undefined;
- const sections=text.split(/\n(?=#{1,5}\s)/u);
- const selected=headings&§ions.length>1
- ? sections.filter(section=>headings.test(section.split('\n',1)[0])).join('\n')
- : text;
- return selected.trim().slice(0,limit)||undefined;
-}
diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs
index 20f7616a..1f333798 100644
--- a/apps/detail-agent-pi/src/production-operations.mjs
+++ b/apps/detail-agent-pi/src/production-operations.mjs
@@ -1,26 +1,29 @@
+import { readFileSync } from 'node:fs';
import path from 'node:path';
import { isDeepStrictEqual } from 'node:util';
import { CanvasOperations } from './canvas-operations.mjs';
-import { setTimeout as delay } from 'node:timers/promises';
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';
-import { productionKnowledge, knowledgeFileIdInstruction } from './production-knowledge.mjs';
import { productRequestScope } from './production-recovery.mjs';
import { canvasTransformArgs, reviewProductionCandidate } from './candidate-review.mjs';
-import { COPY_IMAGE_PROMPT_GUIDANCE, COPY_IMAGE_SCREEN_GUIDANCE, DRAW_LIMIT_GUIDANCE, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
+import { COPY_IMAGE_PROMPT_GUIDANCE, COPY_IMAGE_SCREEN_GUIDANCE, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
import { executeWorkflow, LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } from './workflow-execute.mjs';
import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs';
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);
-const slotRef=Type.String({minLength:1,description:'优先填写 plan_production 返回的目标成品 fieldId;字段编号重复时使用对应的完整 id。'});
+const slotRef=text;
const layer=Type.Integer({minimum:1});
const page=Type.Integer({minimum:0});
const rev=Type.Integer({minimum:0});
@@ -42,9 +45,8 @@ const recoveryNotices={
expired:'原请求结果已过期',
not_executed:'原操作已确认未执行',
};
-const MAX_SLOT_GENERATIONS=4;
const expiryFields=receipt=>receipt?.resultExpiry?
- {requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
+ {requestId:receipt.resultExpiry.requestId??receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
function rememberImageExpiry(item,candidateId,receipt){
const expiry=expiryFields(receipt);
if(!expiry.resultExpiry)return;
@@ -77,13 +79,12 @@ const outputScope={outputId:optional(text),variantId:optional(text)};
export const productionOperationTools = [
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。已有工作会保留。',obj({outputId:text,variantId:text})],
- ['plan_production','读取商品规格、模板、图位及成品进度。可指定输出和花色,省略时读取当前工作画布。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。pictures 中的 copyReady 表示关联字段没有待写文案。调用图位工具时优先使用 pictures 中的 fieldId。',obj({...outputScope,slotIds:optional(ids)})],
- ['read_production_knowledge','读取当前阶段固定版本的制作规则,按回执的 nextOffset 翻页。'+knowledgeFileIdInstruction,obj({fileId:text,offset:optional(page)})],
- ['read_copy_fields','省略 pageId 和 fieldId 可一次读取全页文案字段、当前文字及修订号。需要模板样稿与发布要求时,指定 pageId 或 fieldId 读取对应范围。',obj({
+ ['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()),
})],
- ['write_copy_fields','使用最近一次读文案、写文案或复看整屏返回的文案修订号写入已读文字格。每个 layer 只传一次。可按屏或模块分批写入,原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
- revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),sources:ids,pictures:ids,reason:optional(Type.String())}))),
+ ['write_copy_fields','按 revision 原位写入指定文字格。可传 expectedText 让画布核对原文,修订已变化时用于匹配未改动的字段。每个 layer 只传一次。可按屏或模块分批写入,原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
+ revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),expectedText:optional(Type.String()),sources:ids,pictures:ids,reason:optional(Type.String())}))),
})],
['read_slot_images','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
...outputScope,slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
@@ -91,13 +92,13 @@ export const productionOperationTools = [
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({slotId:slotRef,...productImageArgs})],
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选,返回新候选和像素清晰度指标。',obj({...outputScope,slotId:slotRef,...transformImageArgs})],
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({...outputScope,slotId:slotRef,...preparationArgs})],
- ['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。'+DRAW_LIMIT_GUIDANCE,obj({...outputScope,...dispatchArgs})],
+ ['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj({...outputScope,...dispatchArgs})],
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
})],
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已返回结果未知的原请求用 reconcile_image_slots 核查。可指定成品和花色,非当前可写成品直接返回已有回执和在途状态。',obj({...outputScope,slotIds:optional(ids)})],
- ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求、验图详细结论与提示词。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})],
- ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)],
+ ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})],
+ ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)],
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({
slotIds:optional(Type.Array(Type.String())),
})],
@@ -110,7 +111,7 @@ export const productionOperationTools = [
['adopt_production_image','采用你选择的候选,返回画布修订和覆盖该图位的模板叠层。尺寸线、虚线、引线、文字和装饰角标的错位或数值是否匹配本款,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号;expired 表示原结果已过期,可以为同图位另备新请求。可指定成品和花色。',obj({...outputScope,slotIds:optional(ids)})],
- ['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。后续新读图时自动释放较早的截图并保留文字元数据。${COPY_IMAGE_SCREEN_GUIDANCE}`,obj({
+ ['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({
page:optional(page),pages:optional(Type.Array(page)),
})],
['check_output_screens','按企业 Skill 并行复核整屏合成画面、商品实拍、实时文案与叠加图层。pages 从 1 编号,以当前画布实际屏数为准。默认等待结论,通过的屏自动登记。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取文字结论。',obj({
@@ -186,15 +187,18 @@ function slotAttempts(slot, record) {
function originalCandidate(item) {
if(item?.heldOriginalId)return item.heldOriginalId;
const operation=item?.pendingOperation;
+ if(operation?.kind==='frozen-image')return undefined;
+ if(!operation&&item?.pendingGenerations)return undefined;
if(operation&&Object.hasOwn(operation,'candidateId'))return operation.candidateId;
return item?.state==='unknown'&&(!operation||!item.reason)?item.candidateId:undefined;
}
function slotOriginals(item) {
- const originals=Object.values(item?.pendingGenerations??{}).map(frozen=>({frozen,request:frozen}));
+ const originals=[];
const candidateId=originalCandidate(item);
- if(item?.pendingOperation||candidateId){
- originals.push({request:{...item.pendingOperation,candidateId,projectId:item.heldOriginalProjectId}});
+ const operation=item?.pendingOperation?.kind==='frozen-image'?undefined:item?.pendingOperation;
+ if(operation||candidateId){
+ originals.push({request:{...operation,candidateId,projectId:item.heldOriginalProjectId}});
}
if(item?.pendingAdoption)originals.push({adopting:true,request:item.pendingAdoption});
return originals;
@@ -204,35 +208,22 @@ function imageOriginals({items}) {
return Object.entries(items).flatMap(([slotId,item])=>{
const originals=slotOriginals(item).map(({request:{candidateId,operationId,projectId},adopting})=>
({slotId,candidateId,operationId,projectId,adoption:adopting}));
- return !originals.length&&item.state==='unknown'?[{slotId,phase:'unknown'}]:originals;
+ return !originals.length&&item.state==='unknown'&&!item.pendingGenerations&&item.pendingOperation?.kind!=='frozen-image'
+ ?[{slotId,phase:'unknown'}]:originals;
});
}
+async function readNativeOriginal(canvas,original,scope) {
+ const {slotId,candidateId,operationId}=original;
+ const receipt=await canvas.detailRecover(slotId,{candidateId},scope);
+ if(receipt.id!==candidateId)throw Error('原生回执与请求号不一致');
+ const phase=settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
+ return {slotId,candidateId,operationId,phase,reason:receipt.message,...expiryFields(receipt)};
+}
+
function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{projectScope,onAdopted,onError}={}) {
const detailRecover=(slotId,original)=>canvas.detailRecover(slotId,original,
typeof projectScope==='function'?projectScope():projectScope);
- const reconcileImageRequest=async(slot,original,signal)=>{
- const {candidateId,operationId}=original;
- signal?.throwIfAborted();
- const receipt=await detailRecover(slot.id,{candidateId});
- signal?.throwIfAborted();
- const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
- if(phase!=='unknown')await update(journal=>{
- signal?.throwIfAborted();
- const item=journal.items[slot.id];
- const attempts=item.attempts??=[];
- if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate'});
- rememberImageExpiry(item,candidateId,receipt);
- if(item.pendingGenerations?.[candidateId]){
- delete item.pendingGenerations[candidateId];
- Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'});
- }
- },{receipt:[candidateId,phase,receipt],
- evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId}]});
- return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined,
- ...(receipt?.id===candidateId?expiryFields(receipt):null)};
- };
-
const reconcile=async(slot,signal,adopting=false)=>{
const item=readJournal().items[slot.id];
const pendingKey=adopting?'pendingAdoption':'pendingOperation';
@@ -252,7 +243,6 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null,
});
},{
- ...(original?.kind==='frozen-image'?{receipt:[archivedCandidate,phase,receipt]}:null),
evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}],
});
const reason=receipt?.id===archivedCandidate?receipt.message:undefined;
@@ -290,15 +280,15 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message;
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry};
};
- return async (slot,adopting,original,signal)=>{
+ return async (slot,adopting,signal)=>{
try {
- return original?await reconcileImageRequest(slot,original,signal):await reconcile(slot,signal,adopting);
+ return await reconcile(slot,signal,adopting);
} catch(error) {
signal?.throwIfAborted();
onError?.(error);
const item=readJournal().items[slot.id];
- const request=original??item?.[adopting?'pendingAdoption':'pendingOperation'];
- const candidateId=original||adopting?request?.candidateId:originalCandidate(item);
+ const request=item?.[adopting?'pendingAdoption':'pendingOperation'];
+ const candidateId=adopting?request?.candidateId:originalCandidate(item);
return {slotId:slot.id,operationId:request?.operationId,candidateId,phase:'unknown',reason:error.message};
}
};
@@ -307,8 +297,13 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
export async function reconcileProjectImageSlots(host,{slotIds},signal) {
const {canvas,store,productionGoal:goal}=host;
const requested=new Set(slotIds);
- const results=[];
- for(const {outputId,variantId} of goal.pendingOutputs??goal.requestedOutputs){
+ const outputs=goal.pendingOutputs??goal.requestedOutputs;
+ const pending=(await canvas.imageRequest('pending',{})).filter(row=>
+ outputs.some(scope=>scope.outputId===row.outputId&&scope.variantId===row.variantId)
+ &&(!requested.size||requested.has(row.slotId)));
+ const results=await Promise.all(pending.map(async row=>({outputId:row.outputId,variantId:row.variantId,
+ ...await readNativeOriginal(canvas,row,{outputId:row.outputId,variantId:row.variantId})})));
+ for(const {outputId,variantId} of outputs){
signal?.throwIfAborted();
const ledger=productionLedger(store,outputId,variantId);
let journal=ledger.read();
@@ -319,8 +314,8 @@ export async function reconcileProjectImageSlots(host,{slotIds},signal) {
await ledger.publishAudit(journal);
},{projectScope:{outputId,variantId}});
for(const [id,item] of slots){
- for(const {adopting,frozen} of slotOriginals(item)){
- results.push({outputId,variantId,...await recover({id},adopting,frozen,signal)});
+ for(const {adopting} of slotOriginals(item)){
+ results.push({outputId,variantId,...await recover({id},adopting,signal)});
}
}
}
@@ -331,11 +326,10 @@ 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,{target=host.productionGoal,maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS,
+export async function openProductionOperations(host,{target=host.productionGoal,maxActiveDelegates=6,
maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000,
tailWatchClock}={}) {
if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数');
- if(!Number.isSafeInteger(maxGenerationAttempts)||maxGenerationAttempts<1)throw RangeError('图位生图上限必须为正整数');
if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数');
const {canvas,store}=host;
const {outputId,variantId}=target;
@@ -354,11 +348,13 @@ export async function openProductionOperations(host,{target=host.productionGoal,
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 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();
let journal=previous?.binding===binding?previous:{binding,items:{}};
- if(previous)await ledger.publishAudit(previous);
const evidenceMatches=(value,record=journal)=>Object.hasOwn(record,'copyInputs')
?record.copyInputs===productionInputs(value,variantId)
:record.creationRevision===value.revisions?.creation;
@@ -367,10 +363,6 @@ export async function openProductionOperations(host,{target=host.productionGoal,
record.copyInputs=productionInputs(value,variantId);
record.creationRevision=value.revisions?.creation;
};
- const source=host.productionSkills?.knowledge??host.knowledgeContext;
- const knowledge=productionKnowledge(source);
- const delegateKnowledge=productionKnowledge(source,'image');
- const reviews=productionKnowledge(source,'review');
const findSlot=reference=>{
const id=reference.trim();
const named=byField.get(id);
@@ -393,14 +385,6 @@ export async function openProductionOperations(host,{target=host.productionGoal,
}
return {requested,matched,unmatched};
};
- const copyReads=new Map();
- const rememberCopy=({revision,fields=[]})=>{
- if(!Number.isSafeInteger(revision))return;
- const sampled=copyReads.get(revision)??new Map();
- for(const field of fields)sampled.set(field.layer,field.currentText);
- copyReads.delete(revision);
- copyReads.set(revision,sampled);
- };
const seenLayouts=new Set();
let seenProduct=false;
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map();
@@ -484,22 +468,21 @@ export async function openProductionOperations(host,{target=host.productionGoal,
return live.slots;
};
const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot;
- const nativeGenerations=slot=>(slot.candidates??[]).filter(row=>
- !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id);
+ const nativeGenerations=slot=>[
+ ...(slot.generationRequestIds??(slot.candidates??[]).filter(row=>
+ !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id)),
+ ...[...dispatchingImages].filter(([,job])=>job?.slotId===slot.id).map(([id])=>id),
+ ];
const drawStatus=generationAttempts=>({
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)]));
- const counts=repository.countImageGenerations(binding,ids,journal.items);
- return new Map([...counts].map(([id,count])=>[id,drawStatus(count)]));
- };
- const slotDrawStatus=slot=>drawStatuses([slot]).get(slot.id);
+ const slotDrawStatus=slot=>drawStatus(new Set(nativeGenerations(slot)).size);
+ const drawStatuses=selected=>new Map(selected.map(slot=>[slot.id,slotDrawStatus(slot)]));
const drawLimit=(slot,status)=>({slotId:slot.id,phase:'draw_limit_reached',limitReached:true,...status,
candidates:slot.candidates??[],
- reason:`该图位已达到单张最多 ${maxGenerationAttempts} 次生图上限,请从已有候选中择优采纳(或使用实拍裁切/调整),后续可由人工通过引用精修。`,
+ reason:`该图位已用完已发布的 ${maxGenerationAttempts} 次生图额度。`,
});
const current=async({refresh=false}={})=>{
const value=await (canvasReady?scopedPlan():canvas.workflowRead({section:'overview',outputId}));
@@ -532,9 +515,9 @@ export async function openProductionOperations(host,{target=host.productionGoal,
.map(({field,label,currentText})=>({fieldId:field,label,currentText}))]));
};
const liveSlotCopy=async slot=>{
- const {fields:copyFields,pages}=await copySnapshot();
+ const {fields:copyFields}=await copySnapshot();
const journalCopy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{});
- return resolveLiveSlotCopy({slot,copyFields,pages,journalCopy});
+ return resolveLiveSlotCopy({slot,copyFields,journalCopy});
};
function screenReviewRevisions(){
const inputs=productionInputs(plan,variantId);
@@ -591,8 +574,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const jobProgress={total:slots.length,rendered:filled.size,
copy:copyCells.filter(row=>row.state==='verified').length,
copyPending:copyCells.filter(row=>row.state!=='verified').length,
- unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption||
- Object.keys(item.pendingGenerations??{}).length).length};
+ unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption).length};
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();
@@ -684,18 +666,6 @@ export async function openProductionOperations(host,{target=host.productionGoal,
tailWatcher.refresh();
}
}
- const pendingGeneration=(slot,record=journal,requestId)=>{
- const item=record.items[slot.id];
- if(requestId){
- const original=item?.pendingGenerations?.[requestId];
- return original&&{slotId:slot.id,phase:'unknown',...original,pendingOriginal:requestId};
- }
- const original=item?.pendingOperation;
- if (!original&&!item?.heldOriginalId&&item?.state!=='unknown') return null;
- const candidateId=originalCandidate(item);
- return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId,
- pendingOriginal:candidateId??original?.operationId};
- };
const transformImage=async(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>{
signal?.throwIfAborted();
await current();
@@ -704,7 +674,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const result={...receipt,candidateId:receipt.id,phase:'complete'};
await update(journal=>{
const item=journal.items[slot.id]??={};
- if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption&&!Object.keys(item.pendingGenerations??{}).length){
+ if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption){
Object.assign(item,{state:'candidate',candidateId:receipt.id,source:'transform'});
}
},{evidence:[slot.id,receipt.id,'candidate',receipt]});
@@ -715,143 +685,93 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,
referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange},signal)=>{
signal?.throwIfAborted();
- const input=await current();
+ await current();
const live=await liveSlot(slot);
const status=slotDrawStatus(live);
if(status.drawLimitReached)return drawLimit(live,status);
- const versions=recordProductionInputs(repository,input,slots);
const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,useTemplateReference,
prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange,
...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)});
- const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}});
- return {...receipt,operationId:request.operationId};
+ return {...receipt,operationId:receipt.requestId};
};
- const preparedRequest=(requestId,slot)=>{
- const saved=repository.readImageRequest(requestId);
- const request=saved?.prepared.binding===binding
- ? {...saved.prepared,prompt:saved.prepared.spec.prompt,operationId:saved.operationId}
- : journal.preparedRequests?.[requestId];
- if (!request || slot && request.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位');
- return request;
- };
- const claimDispatch=async(slot,approval,request,signal)=>{
- signal?.throwIfAborted();
- await current();
- const live=await liveSlot(slot);
- approval={requestId:approval.requestId,expectedRevision:approval.expectedRevision??request.revision,
- expectedHash:approval.expectedHash??request.requestSpecHash};
- let claimedOperationId, submission;
- const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>{
- signal?.throwIfAborted();
- const claim=repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior,
- {maxGenerationAttempts,nativeIds:nativeGenerations(live)});
- if(claim.claimed){
- claimedOperationId=claim.original.operationId;
- submission=Promise.withResolvers();
- dispatchingImages.set(claimedOperationId,submission.promise);
- }
- return claim;
- }).catch(error=>{
- submission?.resolve();
- dispatchingImages.delete(claimedOperationId);
- tailWatcher.refresh();
- throw error;
- });
- const {requestId:candidateId}=approval;
- if(generationAttempts!==undefined){
- const status=drawStatus(generationAttempts);
- return {receipt:drawLimit(await liveSlot(slot),status)};
+ const preparedRequest=async(requestId,slot)=>{
+ const receipt=await canvas.imageRequest('read',{requestId});
+ if(receipt.requestId!==requestId||receipt.templateHash!==plan.template.contentHash||
+ receipt.outputId!==outputId||receipt.variantId!==variantId||slot&&receipt.slotId!==slot.id){
+ throw Error('生图请求不属于本轮工作画布或委托图位');
}
- if(!claimed){
- if(pending)return {receipt:{phase:'unknown',...pending,pendingOriginal:pending.candidateId??pending.operationId}};
- const {state,operationId,receipt}=record;
- const phase=settledImagePhases.includes(state)?state:'unknown';
- return {receipt:{phase,candidateId,operationId,reason:receipt?.message,...expiryFields(receipt),
- ...(phase==='unknown'?{pendingOriginal:candidateId}:null)}};
- }
- return {approval,original,onEnqueued:submission.resolve};
- };
- const dispatchImageRequest=async(slot,approval,request,original,workerNumber,onEnqueued)=>{
- const {requestId:candidateId}=approval;
- const {operationId}=original;
- let receipt;
- try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id,workerNumber},{operationId,requestId:candidateId,onEnqueued}); }
- catch(error) {
- if (error.dispatched===false) {
- await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];},
- {receipt:[candidateId,'prepared',{dispatched:false,message:error.message}]});
- return {phase:'failed',candidateId,operationId,reason:error.message};
- }
- await update(()=>{},{receipt:[candidateId,'unknown',{message:error.message}]});
- throw error;
- }
- const phase=receipt.status??receipt.phase;
- const settled=settledImagePhases.includes(phase);
- const late=host.productionSignal?.aborted;
- const evidence={...receipt,requestId:candidateId,operationId,reworkOf:request.reworkOf,
- ...(late?{consumption:'archived_after_cancel'}:null)};
- await update(journal=>{
- const item=journal.items[slot.id]??={};
- if(settled)delete item.pendingGenerations[candidateId];
- const attempts=item.attempts??=[];
- if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate',
- prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange});
- if(late)return;
- if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase});
- Object.assign(item,{prompt:request.prompt,source:'generate'});
- rememberImageExpiry(item,candidateId,receipt);
- },{receipt:[candidateId,settled?phase:'unknown',evidence],
- evidence:[slot.id,candidateId,'candidate',evidence]});
- await store.appendEvent({type:'image_request_receipt',operationId,requestId:candidateId,outputId,variantId,slotId:slot.id,
- category:'remote_image',phase:'archive',status:late?'cancelled':settled?phase:'unknown',consumption:evidence.consumption})
- .catch(error=>console.warn('小壹生图事件写入失败',error.code ?? error.name));
- if(late)return {candidateId,operationId,phase:'cancelled',consumption:evidence.consumption};
- return {candidateId,operationId,phase:settled?phase:'unknown',reason:receipt.message,
- requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null),
- ...(!settled?{pendingOriginal:candidateId}:null),
- ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)};
- };
- const launchImage=(slot,key,operation,requestId,workerNumber)=>{
- if(jobs.has(key))return {...generation.get(key),phase:'already_running'};
- const pending=!requestId&&pendingGeneration(slot);
- if(pending)return pending;
- const receipt={slotId:slot.id,phase:'accepted',...(requestId?{candidateId:requestId,operationId:key}:null)};
- const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:requestId?'正在生图':'生成',active:true};
- generation.delete(key);
- generation.set(key,receipt);
- const run=Promise.resolve().then(()=>operation(row.number))
- .catch(error=>({...pendingGeneration(slot,journal,requestId)??{phase:'failed',candidateId:requestId},reason:error.message}))
- .then(result=>{
- const receipt={slotId:slot.id,...result};
- generation.set(key,receipt);
- return receipt;
- })
- .finally(()=>{jobs.delete(key);return notice('候选图片回执');});
- jobs.set(key,{row,run});
- if(workerNumber===undefined)notice(requestId?'正在生图':'正在制作候选图片');
return receipt;
};
+ const dispatchImageRequest=async(slot,approval,request,workerNumber,onEnqueued)=>{
+ const {requestId:candidateId}=approval;
+ const receipt=await canvas.imageRequest('dispatch',{requestId:candidateId,slotId:slot.id,workerNumber,
+ expectedRevision:approval.expectedRevision??request.revision,expectedHash:approval.expectedHash??request.requestSpecHash},
+ {operationId:candidateId,requestId:candidateId,onEnqueued});
+ if(host.productionSignal?.aborted)return {candidateId,operationId:candidateId,phase:'cancelled'};
+ const phase=receipt.status??receipt.phase;
+ return {candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message,
+ requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null),
+ ...(!settledImagePhases.includes(phase)?{pendingOriginal:candidateId}:null),
+ ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)};
+ };
const queueDispatch=async(slot,approval,request,signal,workerNumber)=>{
- const key=request.operationId??approval.requestId;
- if(jobs.has(key))return {...generation.get(key),phase:'already_running'};
- const claim=await claimDispatch(slot,approval,request,signal).catch(error=>({error}));
- if(claim.receipt?.limitReached)return claim.receipt;
- if(claim.receipt?.pendingOriginal&&!jobs.has(key)){
- return {slotId:slot.id,...claim.receipt};
+ await current();
+ const pending=request.phase==='prepared'?await pendingNative():[];
+ const live=await liveSlot(slot);
+ signal.throwIfAborted();
+ const id=approval.requestId;
+ if(jobs.has(id))return {slotId:slot.id,candidateId:id,operationId:id,phase:'already_running'};
+ if(request.phase!=='prepared'){
+ const phase=request.phase==='applied'?'complete':settledImagePhases.includes(request.phase)?request.phase:'unknown';
+ return {slotId:slot.id,candidateId:id,operationId:id,phase,
+ reason:request.message,...(!settledImagePhases.includes(phase)?{pendingOriginal:id}:null),...expiryFields(request)};
}
- return launchImage(slot,key,number=>{
- if(claim.error)throw claim.error;
- return claim.receipt??dispatchImageRequest(slot,claim.approval,request,claim.original,number,claim.onEnqueued).finally(()=>{
- claim.onEnqueued();
- dispatchingImages.delete(claim.original.operationId);
- tailWatcher.refresh();
+ const status=slotDrawStatus(live);
+ if(status.drawLimitReached)return drawLimit(live,status);
+ const original=pending.find(row=>row.slotId===slot.id);
+ if(original)return {...original,phase:'unknown',pendingOriginal:original.candidateId};
+ const sending=[...dispatchingImages].find(([,job])=>job?.slotId===slot.id);
+ if(sending)return {slotId:slot.id,phase:'unknown',candidateId:sending[0],pendingOriginal:sending[0]};
+
+ const submission=Promise.withResolvers();
+ dispatchingImages.set(id,{slotId:slot.id,enqueued:submission.promise});
+ const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'正在生图',active:true};
+ const run=Promise.resolve().then(()=>dispatchImageRequest(slot,approval,request,row.number,submission.resolve))
+ .catch(error=>({candidateId:id,operationId:id,reason:error.message,
+ ...(error.dispatched===false?{phase:'failed'}:{phase:'unknown',pendingOriginal:id})}))
+ .then(result=>({slotId:slot.id,...result}))
+ .finally(()=>{
+ submission.resolve();
+ dispatchingImages.delete(id);
+ jobs.delete(id);
+ notice('候选图片回执');
});
- },approval.requestId,workerNumber);
+ jobs.set(id,{row,run,requestId:id});
+ if(workerNumber===undefined)notice('正在生图');
+ return {slotId:slot.id,phase:'accepted',candidateId:id,operationId:id};
};
const useProductImage=async(slot,options,signal)=>({
...await operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}),
requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。',
});
+ const launchProductImage=(slot,options,signal)=>{
+ const key=slot.id;
+ if(jobs.has(key))return {...generation.get(key),phase:'already_running'};
+ const receipt={slotId:key,phase:'accepted'};
+ const row={number:nextWorkerNumber(),slotId:key,label:slot.label,step:'生成',active:true};
+ generation.set(key,receipt);
+ const run=onCanvas(signal,()=>useProductImage(slot,options,signal))
+ .catch(error=>({phase:'failed',reason:error.message}))
+ .then(result=>{
+ const receipt={slotId:key,...result};
+ generation.set(key,receipt);
+ return receipt;
+ })
+ .finally(()=>{jobs.delete(key);return notice('候选图片回执');});
+ jobs.set(key,{row,run});
+ notice('正在制作候选图片');
+ return receipt;
+ };
const reportRecoveryError=error=>console.warn('原图片请求核查失败',error.code??error.name);
const recoverImage=createImageReconciler(canvas,{outputId,variantId},()=>journal,update,{
@@ -859,9 +779,13 @@ export async function openProductionOperations(host,{target=host.productionGoal,
onAdopted:(id,candidateId)=>filled.set(id,candidateId),
onError:reportRecoveryError,
});
+ const pendingNative=async()=> (await canvas.imageRequest('pending',{})).filter(row=>
+ row.outputId===outputId&&row.variantId===variantId);
+ const dispatchedImages=()=>[...dispatchingImages].flatMap(([candidateId,job])=>
+ job?[{slotId:job.slotId,candidateId,operationId:candidateId}]:[]);
const outstanding=async()=>{
await journalWrite;
- const requests=imageOriginals(journal);
+ const requests=[...imageOriginals(journal),...await pendingNative(),...dispatchedImages()];
const images=[...new Set(requests.filter(row=>!row.projectId&&!row.adoption&&row.candidateId).map(row=>row.candidateId))];
return {requests,originals:{models:[],images}};
};
@@ -882,10 +806,10 @@ export async function openProductionOperations(host,{target=host.productionGoal,
async probe({slot,key},signal){
const tail=tailsFor(slot).find(tail=>tail.key===key);
if(!tail)return {slotId:slot.id,phase:'none'};
- const {adopting,frozen,request:{candidateId,operationId}}=tail;
+ 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 receipt=await recoverImage(slot,adopting,frozen,signal);
+ const receipt=await recoverImage(slot,adopting,signal);
signal.throwIfAborted();
if(!adopting&&receipt.phase!=='none'){
const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&&
@@ -910,15 +834,15 @@ export async function openProductionOperations(host,{target=host.productionGoal,
});
async function check(slot,candidateId,adopted,signal){
const item=journal.items[slot.id];
- const request=repository.readImageRequest(candidateId);
- const source=request?.slotId===slot.id?'generate':item?.candidateId===candidateId?item.source:undefined;
+ const live=await liveSlot(slot);
+ const source=nativeGenerations(live).includes(candidateId)?'generate':item?.candidateId===candidateId?item.source:undefined;
try{
const liveScreenCopy=await liveSlotCopy(slot);
const readCanvas={detailImages:(id,candidate,options)=>canvas.detailImages(id,candidate,{
...options,...(canvasReady?{targetOutput:output}:null),
})};
const {referenceCount,...review}=await reviewProductionCandidate({canvas:readCanvas,runAgent:host.runDetailAgent,
- slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews});
+ slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted});
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};
@@ -931,7 +855,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
history.push({candidateId,verdict,reason,recommendedAction,canvasTransform,mustRedo:observation.mustRedo,generationFixes:observation.generationFixes});
},{evidence:[slot.id,candidateId,'review',row]});
candidates.set(candidateId,{slotId:slot.id,status:verdict==='pass'?'passed':'rejected',reason});
- const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf;
+ 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,
...review,...(reworkOf?{reworkOf}:null)});
return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null)};
@@ -949,21 +874,21 @@ export async function openProductionOperations(host,{target=host.productionGoal,
await Promise.allSettled(canvasTasks);
await canvasWrite;
await journalWrite;
- await Promise.all(dispatchingImages.values());
+ await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued));
+ return (await outstanding()).originals.images;
},
resumeCanvas(){
const suspended=canvasReady;
canvasReady=null;
if(suspended){
- copyReads.clear();
suspended.resolve();
tailWatcher.refresh();
markProgressDirty();
}
},
- workStatus(){
+ workStatus(originals){
return {...output,slots:[...new Set(running().map(job=>job.row.slotId))],
- inFlightImages:imageOriginals(journal).filter(row=>row.candidateId&&!row.projectId&&!row.adoption)
+ inFlightImages:originals.filter(row=>row.outputId===outputId&&row.variantId===variantId)
.map(row=>row.candidateId),
screens:runningScreens().map(job=>job.receipt.page)};
},
@@ -973,20 +898,24 @@ export async function openProductionOperations(host,{target=host.productionGoal,
stageController.abort();
await canvasWrite;
await journalWrite;
+ tailWatcher.close();
// Hand off only after admitted requests have entered the native transport.
- await Promise.all(dispatchingImages.values());
- const inFlightImages=imageOriginals(journal)
+ const dispatches=dispatchedImages();
+ await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued));
+ const native=host.productionCompletion||host.productionSignal?.aborted?[]:await pendingNative();
+ const originalImages=[...imageOriginals(journal),...native,...dispatches];
+ const inFlightImages=[...new Map(originalImages.filter(row=>row.candidateId)
+ .map(row=>[row.candidateId,row])).values()]
.filter(({candidateId,projectId,adoption})=>candidateId&&!projectId&&!adoption)
.map(({slotId,candidateId,operationId})=>({slotId,requestId:candidateId,operationId}));
const inFlightSlots=new Set(inFlightImages.map(image=>image.slotId));
const cancelledSlots=delegates.filter(([key,{row,dispatched}])=>
!inFlightSlots.has(row.slotId)&&!dispatched.size&&!generation.get(key)?.candidateId).map(([,job])=>job.row.slotId);
- tailWatcher.close();
return {outputId,variantId,cancelledSlots,inFlightImages};
},
screenReviewRevisions,
async unfinished(){return unfinished((await outstanding()).originals);},
- async plan_production({slotIds}={}){
+ async plan_production({slotIds,includeKnowledge=false}={}){
await current({refresh:true});
if(!canvasReady)recordProductionInputs(repository,plan,slots);
const {requested,matched,unmatched}=readSelection(slotIds);
@@ -1001,24 +930,24 @@ export async function openProductionOperations(host,{target=host.productionGoal,
completedCandidates:candidates?.filter(row=>row.status==='complete').length??0,copyReady:canvasReady?undefined:!pendingCopy.get(id)?.length,
...(requested.size?{productionRule,requirements,sourcePolicy}:null)};
});
- const {production,...template}=plan.template;
+ const {production,skillSources,resourceSetId,...template}=plan.template;
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:operations.workStatus().inFlightImages,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs,
+ pictures,inFlightImages:(await pendingNative()).map(row=>row.candidateId),
+ ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
+ requestedOutputs:host.productionGoal.requestedOutputs,
pendingOutputs:host.productionGoal.pendingOutputs??[],
progressSummary:await progressSummary(),
...(unmatched.length?{unmatched}:null)};
},
- async read_production_knowledge(args,signal){
- return knowledge.tools[0]? (await knowledge.tools[0].execute('',args,signal)).details:{files:[]};
- },
async read_copy_fields({pageId,fieldId}){
pageId=pageId?.trim()||undefined;
fieldId=fieldId?.trim()||undefined;
const snapshot=await canvas.detailCopyFields({includeFilled:true,pageId,fieldId});
- rememberCopy(snapshot);
- return snapshot;
+ if(pageId||fieldId)return {...snapshot,outputId,variantId};
+ const fields=snapshot.fields?.map(({nativeFrame,textSafeFrame,styleRoles,relatedFields,...field})=>field);
+ return {...snapshot,outputId,variantId,fields};
},
write_copy_fields({revision,recordOnly,items=[]},signal){
return serialize(async()=>{
@@ -1033,37 +962,9 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const inputPlan=await current();
let result={appliedLayers:[]};
if(!recordOnly){
- let sampled=copyReads.get(revision);
- if(!items.every(({layer})=>sampled?.has(layer))){
- const history=[...copyReads.values()];
- sampled=new Map(sampled);
- for(const layer of layers){
- if(sampled.has(layer))continue;
- const previous=history.findLast(fields=>fields.has(layer));
- if(previous)sampled.set(layer,previous.get(layer));
- }
- const snapshot=await canvas.detailCopyFields({includeFilled:true});
- const live=new Map(snapshot.fields.map(field=>[field.layer,field.currentText]));
- const rejected=[...layers].flatMap(layer=>{
- const reason=!live.has(layer)?'当前画布没有这个文字格':
- !sampled.has(layer)?'尚未读取此文字格':live.get(layer)!==sampled.get(layer)?'原文已变化':null;
- return reason?[{layer,reason}]:[];
- });
- if(rejected.length)return {appliedLayers:[],revision:snapshot.revision,copyUpdates:noUpdates,rejected,
- reason:`请重读文字格 layer ${rejected.map(row=>row.layer).join('、')},当前修订号 ${snapshot.revision}。`};
- revision=snapshot.revision;
- }
- const edits=items.map(({layer,text})=>({layer,text,expectedText:sampled.get(layer)}));
- const deadline=Date.now()+LOCAL_OPERATION_WAIT_MS;
+ const edits=items.map(({layer,text,expectedText})=>({layer,text,...(expectedText===undefined?null:{expectedText})}));
result=await canvas.commitDetailCopy(edits,revision,signal);
- while(result.retryWrite&&Date.now()=deadline)break;
- result=await canvas.commitDetailCopy(edits,revision,signal);
- }
- if(result.retryWrite)return {...result,appliedLayers:[],copyUpdates:noUpdates,
- reason:'写入时画布暂不可用。可先处理其他图位,稍后继续写入。'};
+ if(result.retryWrite || !result.appliedLayers?.length)return {...result,appliedLayers:[],copyUpdates:noUpdates};
}
return await registerCopy(result);
@@ -1071,7 +972,6 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const snapshot=await canvas.detailCopyFields({includeFilled:true});
const after=new Map(snapshot.fields.map(field=>[field.layer,field]));
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
- rememberCopy({revision:snapshot.revision,fields:applied.map(row=>after.get(row.layer))});
await update(journal=>{
syncCopyEvidence(journal,inputPlan);
journal.copyEvidence??={};
@@ -1121,7 +1021,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
use_product_image({slotId,...options},signal){
signal?.throwIfAborted();
const slot=matches(slotId);
- return launchImage(slot,slot.id,()=>onCanvas(signal,()=>useProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal)));
+ return launchProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal);
},
transform_slot_image({slotId,...options},signal){
return serialize(()=>transformImage(matches(slotId),options,signal));
@@ -1130,7 +1030,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
return prepareImageRequest(matches(slotId),args,signal);
},
async dispatch_image_request(approval,signal){
- const request=preparedRequest(approval.requestId);
+ const request=await preparedRequest(approval.requestId);
const slot=matches(request.slotId);
return queueDispatch(slot,approval,request,signal?AbortSignal.any([signal,stageSignal]):stageSignal);
},
@@ -1174,12 +1074,12 @@ export async function openProductionOperations(host,{target=host.productionGoal,
(args,activeSignal)=>onCanvas(activeSignal,()=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal))),
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
(approval,activeSignal)=>onCanvas(activeSignal,async()=>{
- const request=preparedRequest(approval.requestId,slot);
+ const request=await preparedRequest(approval.requestId,slot);
row.step='正在生图';
notice('子代理正在生图');
const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number);
if(receipt.operationId)dispatched.add(receipt.operationId);
- await dispatchingImages.get(receipt.operationId);
+ await dispatchingImages.get(receipt.operationId)?.enqueued;
return receipt;
}),result=>!result.limitReached),
];
@@ -1218,14 +1118,11 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const live=await liveSlot(slot);
const status=slotDrawStatus(live);
const instructions='完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+
- (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+
- (delegateKnowledge.files.length?'\n用 read_production_knowledge 获取 knowledgeFiles 中本任务适用的企业 Skill 和制作规则。':'');
+ (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'');
const screenCopy=await liveSlotCopy(slot);
- const taskGuidance=await delegateKnowledge.guidance();
delegateSignal.throwIfAborted();
await host.runDetailAgent(slot.id,instructions,
- JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements,
- taskGuidance,knowledgeFiles:delegateKnowledge.files}),[readTool,...makeTools(),...delegateKnowledge.tools],
+ JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...makeTools()],
rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id),undefined,delegateSignal);
if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'});
}).catch(async error=>{
@@ -1253,9 +1150,14 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const scope=slotIds?.length||!selected.length?wanted:new Set(selected.map(job=>job.row.slotId));
const screens=slotIds?.length?[]:[...screenChecks.values()];
const pending=[...selected,...screens.filter(job=>job.run)].map(job=>job.run);
- if(pending.length&&!canvasReady)await Promise.race(pending);
+ const receipt=pending.length&&!canvasReady?await Promise.race(pending):undefined;
+ const native=(await liveSlots()).filter(slot=>scope.has(slot.id)).flatMap(slot=>
+ (slot.candidates??[]).filter(row=>!row.sourceType&&!row.reusedFrom).map(row=>
+ ({...row,slotId:slot.id,candidateId:row.id,operationId:row.id,phase:row.status,reason:row.message??row.error})))
+ .sort((a,b)=>(b.sequence??0)-(a.sequence??0));
+ const completed=receipt?.operationId&&scope.has(receipt.slotId)?[receipt]:[];
return {...output,active:jobs.size,checking:pendingReviews().length,
- generation:generationReceipts(scope),
+ generation:[...completed,...generationReceipts(scope),...native.filter(row=>row.candidateId!==completed[0]?.candidateId)],
checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt),
...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null)};
},
@@ -1283,8 +1185,13 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const record=journal.items[id];
const {attemptCount,rejections}=slotAttempts(slot,record);
const status=statuses.get(id);
- const latest=candidates?.at(-1);
- const generations=generationReceipts(new Set([id]));
+ const ordered=(candidates??[]).toSorted((a,b)=>(b.sequence??0)-(a.sequence??0));
+ const latest=ordered[0];
+ const sending=[...jobs.values()].filter(job=>job.requestId&&job.row.slotId===id)
+ .map(({requestId})=>({slotId:id,candidateId:requestId,operationId:requestId,phase:'accepted'}));
+ const generations=[...sending,...ordered.filter(row=>!row.sourceType&&!row.reusedFrom&&
+ !sending.some(receipt=>receipt.candidateId===row.id))
+ .map(row=>({...row,candidateId:row.id,phase:row.status})),...generationReceipts(new Set([id]))];
const [generationReceipt]=generations;
const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId;
const reviews=checks.get(id)??[];
@@ -1293,7 +1200,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined;
const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId;
const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking':
- record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)||Object.keys(record?.pendingGenerations??{}).length?'unknown':
+ slotOriginals(record).length?'unknown':
adopted?'applied':
decision??generationReceipt?.phase??latest?.status??record?.state??'empty';
return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,...status,rejectionCount:rejections.length};
@@ -1360,21 +1267,16 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const generated=nativeGenerations(await liveSlot(slot)).includes(candidateId);
const result=await serialize(()=>canvas.detailRetire(slot.id,candidateId,reason));
if(result.status==='retired'){
- const request=repository.readImageRequest(candidateId);
await update(journal=>{
if(!journal.items[slot.id]&&!generated)return;
const item=journal.items[slot.id]??={};
- if(generated&&!(item.attempts??[]).some(row=>row.candidateId===candidateId)){
- (item.attempts??=[]).push({candidateId,source:'generate'});
- }
item.approvals=(item.approvals??[]).filter(row=>row.candidateId!==candidateId);
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}],
- ...(request?{receipt:[candidateId,'retired',result]}:null)});
+ },{evidence:[slot.id,candidateId,'retirement',{...result,reason}]});
candidates.delete(candidateId);
host.generatedCandidates?.delete(candidateId);
markProgressDirty();
@@ -1392,8 +1294,14 @@ export async function openProductionOperations(host,{target=host.productionGoal,
if(tails.every(tail=>tail.adopting))receipts.unshift({slotId:slot.id,phase:'none'});
return receipts;
}));
+ const pending=await pendingNative();
signal?.throwIfAborted();
- return results;
+ const ids=new Set(selected.map(slot=>slot.id));
+ const originals=await Promise.all(pending.filter(row=>ids.has(row.slotId))
+ .map(row=>readNativeOriginal(canvas,row,canvasReady?output:undefined)));
+ signal?.throwIfAborted();
+ const pendingSlots=new Set(originals.map(row=>row.slotId));
+ return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))];
},
async read_output_screen({page=0,pages},signal){
const render=async page=>{
@@ -1410,7 +1318,6 @@ export async function openProductionOperations(host,{target=host.productionGoal,
return {...field,visible:context?.layers?.[0]?.effectiveVisible};
}));
const screenCopy=extractPageLiveCopy({pageIndex:page,pages:copyPages,fields:visibleCopy});
- rememberCopy({revision:snapshot.revision,fields:visibleCopy.filter(field=>field.visible!==false)});
const previews=await Promise.all(images.map(async image=>{
if(image.type!=='image')return {image};
const resized=await resizeImage(Buffer.from(image.data,'base64'),image.mimeType,host.info?.model?.inputLimits?.images?.resize);
@@ -1481,7 +1388,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const screenSlots=slots.filter(slot=>screen.details.fields?.includes(slot.fieldId))
.map(({id,fieldId,label,nativeLayerId})=>({id,fieldId,label,nativeLayerId}));
const receipt=await reviewOutputScreen({runAgent:host.runDetailAgent,page,screen,references,
- slots:screenSlots,outputId,variantId,signal:activeSignal,reviewKnowledge:reviews});
+ slots:screenSlots,outputId,variantId,signal:activeSignal});
job.inputSignature=(await references()).inputSignature;
if(receipt.verdict==='pass'){
await onCanvas(activeSignal,()=>operations.record_screen_check({page:page-1,revision,issues:[]},activeSignal,job.inputSignature));
@@ -1533,15 +1440,11 @@ export async function openProductionOperations(host,{target=host.productionGoal,
});
},
async defer_production_output({blocker}){
- const active=running().map(job=>job.row.slotId);
- const screens=runningScreens().map(job=>job.receipt.page);
- if(active.length||screens.length)return {submitted:false,reason:'work_in_progress',slotIds:[...new Set(active)],
- ...(screens.length?{pages:screens}:null),nextTool:'await_image_slots'};
- const {requests,originals}=await outstanding();
- if(requests.length)return {submitted:false,reason:'originals_pending',requests,originals,
- nextTool:'reconcile_image_slots'};
if(!blocker?.reason?.trim()||!blocker.requiredAction?.trim()){
- return {submitted:false,reason:'work_can_continue',nextTool:'plan_production'};
+ const slotIds=[...new Set(running().map(job=>job.row.slotId))];
+ const pages=runningScreens().map(job=>job.receipt.page);
+ const {requests,originals}=await outstanding();
+ return {submitted:false,slotIds,pages,requests,originals};
}
await journalWrite;
const {reason}=blocker;
diff --git a/apps/detail-agent-pi/src/production-recovery.mjs b/apps/detail-agent-pi/src/production-recovery.mjs
index e10e4d0e..4d364fe6 100644
--- a/apps/detail-agent-pi/src/production-recovery.mjs
+++ b/apps/detail-agent-pi/src/production-recovery.mjs
@@ -1,89 +1,3 @@
-import { parseReceipt } from './receipt.mjs';
-import { retryDelayMs } from '@earendil-works/pi-ai';
-import { SettingsManager } from '@earendil-works/pi-coding-agent';
-
-export const piRetryPolicy = SettingsManager.inMemory().getRetrySettings();
-
-export function gatewayImageRetryDelay(retries, retryAfterSeconds) {
- if (!piRetryPolicy.enabled || retries >= piRetryPolicy.maxRetries) return null;
- return Math.max(retryDelayMs(piRetryPolicy, retries + 1),
- Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1000 : 0);
-}
-
-export class ProductionRequestFailed extends Error {
- constructor(requestId, httpStatus) {
- super('模型服务已确认请求失败(原请求 '+requestId+(httpStatus?',HTTP '+httpStatus:'')+')');
- this.httpStatus=httpStatus;
- this.retryable=![400,401,403,404,422].includes(httpStatus);
- }
-}
-
-export function confirmedProductionFailure(receipt, id) {
- if (receipt.phase !== 'failed') return null;
- if (receipt.failureCode === 'rate_limit_exceeded') {
- return new ProductionRequestFailed(receipt.requestId ?? id, 429);
- }
- return receipt.confirmedFailure
- ? new ProductionRequestFailed(receipt.requestId ?? id, receipt.httpStatus)
- : null;
-}
-
-export class ProductionOutputLimit extends Error {
- constructor() { super('模型回复达到单次输出长度,当前制作步骤未完成'); }
-}
-
export function productRequestScope(step, variant, output) {
return ['product',step,variant,output].filter(Boolean).join('/');
}
-
-// Model refusal is a terminal reply, but it authorizes no tools or canvas writes.
-async function closeProductRefusal(broker,record){
- if(record.phase!=='received'||record.terminal!==true||typeof record.raw!=='string')return false;
- const protocol=record.model?.protocol;
- if(!['anthropic-messages','openai-chat'].includes(protocol))return false;
- const raw=Buffer.from(record.raw,'base64').toString('utf8');
- const refused=raw.split(/\r?\n/u).some(line=>{
- if(!line.startsWith('data:'))return false;
- try{
- const event=JSON.parse(line.slice(5));
- return protocol==='anthropic-messages'
- ? event?.type==='message_delta'&&event.delta?.stop_reason==='refusal'
- : event?.choices?.some(choice=>(choice.index??0)===0&&choice.finish_reason==='content_filter')===true;
- }catch{return false;}
- });
- if(!refused)return false;
- const receipt=await broker.confirm(record.id,record.bodyHash,false,'refusal');
- return receipt.phase==='rejected';
-}
-
-export async function confirmProductionResponse(broker,record,model,tools,protocolMode='native-tools'){
- const {id,requestId}=record;
- if(await closeProductRefusal(broker,record))return {phase:'rejected',requestId};
- const message=await parseReceipt(record,model,protocolMode,tools);
- if(record.phase==='received'){
- const receipt=await broker.confirm(id,record.bodyHash,message.stopReason!=='length',message.stopReason);
- if(receipt.phase!=='complete')return {phase:receipt.phase,requestId};
- }
- return message.stopReason==='length'?{phase:'rejected',requestId}:{phase:'complete',requestId,message};
-}
-
-export async function recoverProductionResponse(broker,id,model,tools) {
- let record=await broker.read(id);
- let recoveryError;
- if (['unknown','dispatched'].includes(record.phase)) {
- try { await broker.recover(id); }
- catch (error) {
- recoveryError=error;
- }
- // The native broker can settle the original journal even when the GET fails.
- record=await broker.read(id);
- }
- if (!['received','complete'].includes(record.phase)) {
- const confirmedFailure=record.phase==='failed'&&record.originalLookup?.verified===true&&
- record.originalLookup.status==='failed'&&record.originalLookup.requestId===record.requestId;
- return {phase:record.phase,requestId:record.requestId,failureCode:record.failureCode,
- ...(recoveryError?{recoveryError}:null),
- ...(confirmedFailure?{confirmedFailure,httpStatus:record.failureHttpStatus??record.httpStatus}:null)};
- }
- return confirmProductionResponse(broker,{id,...record},model,tools);
-}
diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs
index a3622bd4..2bda0d37 100644
--- a/apps/detail-agent-pi/src/production-repository.mjs
+++ b/apps/detail-agent-pi/src/production-repository.mjs
@@ -18,7 +18,11 @@ export function productionLedger(store, outputId, variantId) {
// PhotoCraft consumes this view for adoption, archives and .xiaoyi saves.
// On the original project, SQLite owns all changes after the first import.
const publishAudit = async journal => {
- const view = repository.exportLedger(journal);
+ const {preparedRequests, ...audit} = journal;
+ const view = {...audit, items:Object.fromEntries(Object.entries(journal.items).map(([id, item])=>{
+ const {pendingGenerations, ...record} = item;
+ return [id, record];
+ }))};
const encoded = JSON.stringify(view, null, 2);
if (published === undefined) {
try { published = await fs.readFile(legacyFile, 'utf8'); }
diff --git a/apps/detail-agent-pi/src/project-repository.mjs b/apps/detail-agent-pi/src/project-repository.mjs
index a720ab04..938e326a 100644
--- a/apps/detail-agent-pi/src/project-repository.mjs
+++ b/apps/detail-agent-pi/src/project-repository.mjs
@@ -38,6 +38,7 @@ const schema = `
value_json TEXT NOT NULL,
PRIMARY KEY (${scopeColumns}, kind, record_id, revision)
) STRICT;
+ -- Historical R2/R3 request records. The host owns new image requests.
CREATE TABLE image_requests (
${scopeDefinition},
request_id TEXT NOT NULL,
@@ -170,30 +171,14 @@ export class ProjectRepository {
});
}
- exportLedger(journal) {
- return this.#open(db => {
- const rows = db.prepare(`SELECT request_id, prepared_json FROM image_requests WHERE ${scopeWhere}`).all(...this.scope);
- const requests = rows.map(row => [row.request_id, JSON.parse(row.prepared_json)])
- .filter(([, draft]) => draft.binding === journal.binding);
- if (!requests.length) return journal;
- const preparedRequests = { ...journal.preparedRequests, ...Object.fromEntries(
- requests.map(([id, { slotId, spec, reworkOf, reworkChange }]) =>
- [id, { slotId, prompt: spec.prompt, reworkOf, reworkChange }]),
- ) };
- return { ...journal, preparedRequests };
- });
- }
-
- updateLedger(binding, change, { prepared, policy, candidateSetId, receipt, evidence } = {}) {
+ updateLedger(binding, change, { evidence } = {}) {
return this.#open(db => transaction(db, () => {
const previous = this.#readLedger(db);
const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} };
const result = change(journal);
this.#writeLedger(db, journal, previous);
- const request = prepared && this.#saveImageRequest(db, prepared, policy, candidateSetId);
- if (receipt) this.#recordImageReceipt(db, ...receipt);
if (evidence) this.#recordCandidate(db, ...evidence);
- return { journal, result, request };
+ return { journal, result };
}));
}
@@ -231,39 +216,6 @@ export class ProjectRepository {
});
}
- #saveImageRequest(db, receipt, policy, candidateSetId) {
- const { requestId, operationId = requestId, slotId, requestSpecHash, revision } = receipt;
- if (policy || candidateSetId) {
- const original = this.#readRequest(db, requestId);
- let candidateSet = original?.prepared.candidateSet;
- if (!candidateSet) {
- const first = candidateSetId && this.#readRequest(db, candidateSetId);
- if (candidateSetId && (first?.prepared.candidateSet?.id !== candidateSetId ||
- first.slotId !== slotId || first.prepared.binding !== receipt.binding ||
- first.requestSpecHash !== requestSpecHash || first.prepared.planRevision !== receipt.planRevision ||
- first.prepared.productFactsRevision !== receipt.productFactsRevision)) {
- throw Error('同批候选须使用相同的正式请求和制作依据');
- }
- const setPolicy = first?.prepared.candidateSet.policy ?? policy;
- const position = first ? this.#candidateSet(db, slotId, candidateSetId).length : 0;
- if (position >= setPolicy.candidateCount) throw Error('此批候选已准备齐全');
- candidateSet = { id: candidateSetId ?? requestId, position, policy: setPolicy };
- }
- receipt = { ...receipt, candidateSet };
- }
- db.prepare(`INSERT INTO image_requests (${scopeColumns}, request_id, operation_id, slot_id, request_spec_hash,
- revision, state, prepared_json) VALUES (${scopeValues}, ?, ?, ?, ?, ?, 'prepared', ?)
- ON CONFLICT (${scopeColumns}, request_id) DO NOTHING`).run(
- ...this.scope, requestId, operationId, slotId, requestSpecHash, revision, json(receipt));
- const saved = this.#readRequest(db, requestId);
- if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备新版本');
- return saved;
- }
-
- saveImageRequest(receipt) {
- return this.#open(db => transaction(db, () => this.#saveImageRequest(db, receipt)));
- }
-
#readRequest(db, requestId) {
const row = db.prepare(`SELECT * FROM image_requests WHERE ${scopeWhere} AND request_id = ?`).get(...this.scope, requestId);
if (!row) return null;
@@ -277,113 +229,6 @@ export class ProjectRepository {
return this.#open(db => this.#readRequest(db, requestId));
}
- #candidateSet(db, slotId, id) {
- return db.prepare(`SELECT request_id FROM image_requests WHERE ${scopeWhere} AND slot_id = ?
- AND json_extract(prepared_json, '$.candidateSet.id') = ? ORDER BY rowid`)
- .all(...this.scope, slotId, id).map(row => this.#readRequest(db, row.request_id));
- }
-
- candidateSet(slotId, id) {
- return this.#open(db => this.#candidateSet(db, slotId, id));
- }
-
- #countImageGenerations(requests, nativeIds, item) {
- const ids = new Set(nativeIds);
- for (const {request_id, state, receipt_json} of requests) {
- if (state !== 'prepared') ids.add(request_id);
- else if (receipt_json && JSON.parse(receipt_json).dispatched === false) ids.delete(request_id);
- }
- for (const row of item?.attempts ?? []) if (row.source === 'generate' && row.candidateId) ids.add(row.candidateId);
- for (const id of Object.keys(item?.pendingGenerations ?? {})) ids.add(id);
- const originalId = item?.pendingOperation?.candidateId;
- if (originalId && !item.attempts?.some(row => row.candidateId === originalId && row.source === 'product')) {
- ids.add(originalId);
- }
- return ids.size;
- }
-
- #generationRequests(db, binding, slotId) {
- return db.prepare(`SELECT slot_id, request_id, state, receipt_json FROM image_requests
- WHERE ${scopeWhere} AND json_extract(prepared_json, '$.binding') = ?${slotId ? ' AND slot_id = ?' : ''}`)
- .all(...this.scope, binding, ...(slotId ? [slotId] : []));
- }
-
- countImageGenerations(binding, nativeIdsBySlot, items) {
- if (!nativeIdsBySlot.size) return new Map();
- return this.#open(db => {
- const slotId = nativeIdsBySlot.size === 1 ? nativeIdsBySlot.keys().next().value : undefined;
- const requests = Map.groupBy(this.#generationRequests(db, binding, slotId), row => row.slot_id);
- return new Map([...nativeIdsBySlot].map(([id, nativeIds]) =>
- [id, this.#countImageGenerations(requests.get(id) ?? [], nativeIds, items[id])]));
- });
- }
-
- claimImageRequest({ requestId, expectedRevision, expectedHash }, binding, pendingGeneration, generationLimit) {
- return this.#open(db => transaction(db, () => {
- const request = this.#readRequest(db, requestId);
- if (request && (request.prepared.binding !== binding ||
- request.revision !== expectedRevision || request.requestSpecHash !== expectedHash)) {
- throw Error('生图请求版本已变化,请重新准备');
- }
- const previous = this.#readLedger(db);
- const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} };
- const slotId = request?.slotId ?? journal.preparedRequests?.[requestId]?.slotId;
- if (!slotId) throw Error('生图请求不属于本轮工作画布或委托图位');
- const item = journal.items[slotId] ??= {};
- const sameOperation = item.pendingGenerations?.[requestId];
- const expired = !request && item.attempts?.find(attempt => attempt.candidateId === requestId && attempt.phase === 'expired');
- if (expired) return { journal, request: { state: 'expired', operationId: requestId, receipt: expired }, claimed: false };
- if (sameOperation || request && request.state !== 'prepared') {
- return { journal, pending: sameOperation, request, claimed: false };
- }
- if (generationLimit) {
- const {maxGenerationAttempts, nativeIds} = generationLimit;
- const requests = this.#generationRequests(db, binding, slotId);
- const generationAttempts = this.#countImageGenerations(requests, nativeIds, item);
- if (generationAttempts >= maxGenerationAttempts) return { journal, claimed: false, generationAttempts };
- const set = request?.prepared.candidateSet;
- if (set && this.#candidateSet(db, slotId, set.id).length !== set.policy.candidateCount) {
- throw Error('请先按政策准备齐全同批候选,再分别确认派发');
- }
- }
- const priorGeneration = Object.values(item.pendingGenerations ?? {}).find(original => {
- const prior = this.#readRequest(db, original.candidateId);
- return !request?.prepared.candidateSet ||
- prior?.prepared.candidateSet?.id !== request.prepared.candidateSet.id;
- });
- const priorState = priorGeneration && this.#readRequest(db, priorGeneration.candidateId)?.state;
- const pending = pendingGeneration?.(journal, priorGeneration) ??
- (priorState !== 'dispatching' ? priorGeneration : undefined);
- if (pending) return { journal, pending, request, claimed: false };
- const operationId = request?.operationId ?? requestId;
- if (request) {
- const set = request.prepared.candidateSet;
- if (set && this.#candidateSet(db, slotId, set.id).every(candidate => candidate.frozenAt === null)) {
- item.autoCandidateSetId = set.id;
- }
- db.prepare(`UPDATE image_requests SET state = 'dispatching', frozen_at = COALESCE(frozen_at, ?)
- WHERE ${scopeWhere} AND request_id = ?`).run(Date.now(), ...this.scope, requestId);
- }
- // Old drafts carry only the prompt and still rely on the native revision/hash check.
- const original = { candidateId: requestId, operationId, kind: 'frozen-image' };
- (item.pendingGenerations ??= {})[requestId] = original;
- this.#writeLedger(db, journal, previous);
- return { journal, original, claimed: true };
- }));
- }
-
- #recordImageReceipt(db, requestId, state, receipt) {
- // Expiration is a terminal failure to retrieve the result. Its receipt carries
- // the exact outcome, with the same durable schema as earlier projects.
- db.prepare(`UPDATE image_requests SET state = ?, receipt_json = ?
- WHERE ${scopeWhere} AND request_id = ? AND json_extract(receipt_json, '$.resultExpiry') IS NULL`)
- .run(state === 'expired' ? 'failed' : state, json(receipt), ...this.scope, requestId);
- }
-
- recordImageReceipt(requestId, state, receipt) {
- this.#open(db => this.#recordImageReceipt(db, requestId, state, receipt));
- }
-
#recordCandidate(db, slotId, candidateId, kind, detail) {
db.prepare(`INSERT INTO candidate_evidence (${scopeColumns}, slot_id, candidate_id, kind, detail_json)
VALUES (${scopeValues}, ?, ?, ?, ?)`).run(...this.scope, slotId, candidateId, kind, json(detail));
diff --git a/apps/detail-agent-pi/src/request-purpose.mjs b/apps/detail-agent-pi/src/request-purpose.mjs
deleted file mode 100644
index 9f262898..00000000
--- a/apps/detail-agent-pi/src/request-purpose.mjs
+++ /dev/null
@@ -1,20 +0,0 @@
-import fs from 'node:fs/promises';
-import path from 'node:path';
-
-export async function requestPurpose(host, id) {
- const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;});
- const events = text.split('\n').filter(Boolean).map(line => { try { return JSON.parse(line); } catch { return null; } });
- let legacyCompacting = false;
- for (const event of events) {
- if (event?.type === 'automatic_compaction_started') legacyCompacting = true;
- if (event?.type === 'automatic_compaction_completed') legacyCompacting = false;
- if (event?.type !== 'provider_prepared' || event.id !== id ||
- (event.bindingHash && event.bindingHash !== host.store.hash)) continue;
- if (events.some(row => row?.id === id && row.consumption === 'discarded_after_cancel')) return 'cancelled';
- const {purpose} = event;
- if (['conversation','compaction','whole-detail-review','whole-detail-worker','product-goal'].includes(purpose)) return purpose;
- // Old automatic summaries have no durable cut point.
- return legacyCompacting ? 'legacy-compaction' : 'conversation';
- }
- throw Error('原请求不属于当前店铺/品类会话,未查询或恢复');
-}
diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs
index cfb4f069..f41d24cc 100644
--- a/apps/detail-agent-pi/src/screen-review.mjs
+++ b/apps/detail-agent-pi/src/screen-review.mjs
@@ -25,7 +25,7 @@ const assessment = object({
copyFixes:finding({field:text(200)}),
});
-export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal, reviewKnowledge}) {
+export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) {
const {revision,copyRevision,overlayLayers,screenCopy=[]} = screen.details;
const images = screen.content.filter(item => item.type === 'image');
if (!Number.isSafeInteger(revision) || images.length !== 1) throw Error('未读取到当前屏的实际画面和修订号');
@@ -59,14 +59,12 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
const scope = screenReviewScope(variantId,outputId,page);
const instructions = [
'复核整屏成片。第一张是整屏实际画面,后续是本款实拍。',
- ...(reviewKnowledge.files.length?['用 read_production_knowledge 获取 knowledgeFiles 中适用的企业 Skill 和审稿规则。']:[]),
'用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,正文问题填写 screenCopy 中的 field。',
'有问题时填写 needs_fix 和至少一项问题。通过时三组问题均为空。',
].join('\n');
- const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length,
- taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files});
+ const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length});
const captions = ['当前整屏成片', ...photos.map((_,index) => `本款实拍 ${index + 1}`)];
- await runAgent(`screen-${page}`, instructions, prompt, [tool,...reviewKnowledge.tools], [...images,...photos], scope, captions,signal);
+ await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal);
signal?.throwIfAborted();
if (!receipt) throw new InvalidToolReply('整屏复核未提交结论');
return receipt;
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 962d6a7c..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,11 +1,12 @@
---
name: product-image-sources
description: Use product image sources and Image Request tools in PhotoCraft.
+maxGenerationAttempts: 4
---
# 商品配图工具
-从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。
+从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read` 按路径查看已锁定的文件。
- `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。
- transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
diff --git a/apps/detail-agent-pi/src/template-mapping.mjs b/apps/detail-agent-pi/src/template-mapping.mjs
index 81a01b6a..bda012f5 100644
--- a/apps/detail-agent-pi/src/template-mapping.mjs
+++ b/apps/detail-agent-pi/src/template-mapping.mjs
@@ -65,6 +65,8 @@ function compact(raw,original,key,component) {
const canvas=[template.canvas.width,template.canvas.height];
if(!canvas.every(n=>Number.isInteger(n)&&n>0))fail('字段映射的原稿尺寸无效');
const page=[0,0,...canvas];
+ // Compact mappings publish rules against these generated IDs. Canonical
+ // mappings declare their own screen and field IDs.
const screen=component==='sku_images'?'K01':'M01';
const fields=[];
const append=(id,reference,slot,kind)=>{
diff --git a/apps/detail-agent-pi/test/account-authorization.test.mjs b/apps/detail-agent-pi/test/account-authorization.test.mjs
index 0396d12b..44e0f5c1 100644
--- a/apps/detail-agent-pi/test/account-authorization.test.mjs
+++ b/apps/detail-agent-pi/test/account-authorization.test.mjs
@@ -50,11 +50,10 @@ test('native HTTP 401 revokes the bound broker and all workers without another d
try {
const response = await round.fetch(address, options);
assert.equal(response.status, 401);
- await assert.rejects(round.finish(false), {category:'auth_revoked',dispatched:true});
+ await assert.rejects(response.text(), {category:'auth_revoked',dispatched:true});
await assert.rejects(broker.round().fetch(address, options), {category:'auth_revoked'});
await assert.rejects(formerWorker.round().fetch(address, options), {category:'auth_revoked'});
assert.equal(requests.length, 1);
- assert.equal(broker.hasUnconfirmedRequest, false);
assert.equal(paused.length, 1);
assert.doesNotMatch(JSON.stringify(paused), /never-log-auth-fixture/);
} finally {
diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs
index 8ce57c3b..66995303 100644
--- a/apps/detail-agent-pi/test/conversation.test.mjs
+++ b/apps/detail-agent-pi/test/conversation.test.mjs
@@ -18,7 +18,7 @@ function canvas(){
return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题',
async begin(){this.allowed=false;this.writeBlocked=false;},
async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};},
- async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw Error('用户已接手,写入未获许可');this.allowed=true;return this.read();},
+ async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw new BridgeError('用户已接手,写入未获许可','write_revoked');this.allowed=true;return this.read();},
async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();},
async delta(){},async activity(){},async end(){this.allowed=false;}};
}
@@ -164,14 +164,11 @@ test('a model response arriving after cancellation keeps its receipt and cannot
await assert.rejects(first,/停止/);
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
const finished=journal.find(e=>e.type==='provider_finished');
- assert.equal(finished.phase,'complete');
+ assert.equal(finished.stopReason,'toolUse');
assert.equal(finished.status,'cancelled');
assert.equal(finished.consumption,'discarded_after_cancel');
- assert.equal(finished.operationId,finished.requestId);
x.host.productionSignal=new AbortController().signal;
- x.broker.read=async id=>({phase:'complete',requestId:id});
- assert.equal((await x.host.recover(finished.id,{executeReadOnly:true})).consumption,'discarded_after_cancel');
assert.equal((await x.host.prompt('新回合')).text,'新一轮正常完成。');
assert.equal(x.native.writes,0);
assert.equal(x.requests.length,2);
@@ -268,7 +265,7 @@ test('switching projects in the middle of the original SSE detaches UI delivery
assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full));
assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result');
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse);
- assert.equal(journal.filter(e=>e.type==='provider_prepared').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.phase==='complete'));
+ assert.equal(journal.filter(e=>e.type==='provider_started').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.stopReason==='stop'));
assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end'));
assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full);
}finally{await x.close();}
@@ -290,7 +287,7 @@ test('inactive activity delivery preserves the original assistant/tool transcrip
assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。')));
assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError));
assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error'));
- const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_project_stopped'));
+ const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_ui_delivery'));
}finally{await x.close();}
});
@@ -408,8 +405,7 @@ test('legacy transcript migration retains originals and a new conversation can p
let posts=0;
host=await DetailPiAgent.open({store:stable,broker:{
info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}),
- round:({inference})=>{
- assert.equal(inference,true);
+ round:()=>{
return {id:randomUUID(),fetch:async()=>{
posts++;
return new Response(sse({content:'当前对话可以继续。'}),{headers:{'content-type':'text/event-stream'}});
diff --git a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs
index 7d8a15cd..78ba1436 100644
--- a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs
+++ b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs
@@ -34,13 +34,13 @@ test('live text replaces stale journal copy and includes all supported selling p
assert.deepEqual(resolveLiveSlotCopy({slot,copyFields:[{...fields[0],currentText:''}],journalCopy}),[]);
});
-test('slot page, native document ID and known field prefixes locate a screen without direct copy',()=>{
+test('declared page and native document IDs locate a screen without guessing the field prefix',()=>{
const copyFields=fields.slice(0,2);
- for(const location of [{page:'P02'},{pageId:'P02'},{documentId:'P02'},{fieldId:'P02_leg'},{}]){
+ for(const location of [{page:'P02'},{pageId:'P02'},{documentId:'P02'}]){
const result=resolveLiveSlotCopy({slot:{...slot,...location},copyFields,pages});
assert.deepEqual(result.map(row=>row.binding),['same_screen','same_screen']);
}
- assert.deepEqual(resolveLiveSlotCopy({slot,copyFields}),[]);
+ assert.deepEqual(resolveLiveSlotCopy({slot,copyFields,pages}),[]);
assert.deepEqual(resolveLiveSlotCopy({slot,journalCopy}).map(row=>row.text),['圆润桌面']);
const repeated={...fields[0],page:'P01',currentText:'另一屏的同名文字格'};
const result=resolveLiveSlotCopy({slot:{...slot,page:'P02'},copyFields:[...copyFields,repeated],journalCopy});
@@ -65,7 +65,7 @@ test('candidate review records the observed subject and alignment while acceptin
canvas:{detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image],
relatedCopy:[{fieldId:'tag',text:'实木横梁'}]})},
host:{},slot,candidateId:'candidate',copy:journalCopy,
- liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}],reviewKnowledge:{files:[],tools:[],guidance:()=>undefined},
+ liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}],
async runAgent(_slot,instructions,prompt,[tool]){
assert.match(instructions,/shownSubject.*shownFields/u);
const {screenCopy}=JSON.parse(prompt);
@@ -94,12 +94,10 @@ test('candidate review sends the candidate, same-product photo and template comp
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:[],guidance:()=>({fileId:'special-rule',text:'企业审稿标准'})},
- async runAgent(_slot,instructions,prompt,[tool],images,_scope,captions){
+ async runAgent(_slot,_instructions,prompt,[tool],images,_scope,captions){
assert.deepEqual(images,[candidate,photo,layout]);
assert.deepEqual(captions,['受审候选图框','同款实拍 P02','模板构图参考']);
- assert.match(instructions,/read_production_knowledge.*企业 Skill/u);
- assert.equal(JSON.parse(prompt).taskGuidance.text,'企业审稿标准');
+ assert.equal(JSON.parse(prompt).taskGuidance,undefined);
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}});
@@ -120,6 +118,7 @@ test('production delegation and screen rendering use live copy after a direct ca
{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:{
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}),
detailCopyFields:async options=>{
@@ -134,7 +133,7 @@ test('production delegation and screen rendering use live copy after a direct ca
delegated=JSON.parse(prompt);
}};
const actions=await openProductionOperations(host);
- await actions.write_copy_fields({recordOnly:true,items:[
+ await actions.write_copy_fields({revision:2,recordOnly:true,items:[
{layer:1,text:'圆润桌面',pictures:[slot.fieldId],sources:['P01']},
]});
live[0].currentText='加厚桌腿';
@@ -169,8 +168,9 @@ test('switching outputs discards the prior canvas copy reads and uses the new li
outputId=binding.outputId;
return binding;
},
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId,
- template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}),
+ template:{contentHash:'fixture'},totalSlots:1,slots:[{...slot,documentId:pages[1]}]}),
detailCopyFields:async()=>({revision,pages,fields:[{...fields[0],currentText:copyByOutput[outputId]}]}),
detailRender:async({page})=>({page,revision,images:[]}),
detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image]}),
@@ -191,18 +191,16 @@ test('switching outputs discards the prior canvas copy reads and uses the new li
await action('open_production_output',{outputId:'detail',variantId});
const detail=await action('read_copy_fields');
assert.equal(detail.fields[0].currentText,'加厚桌腿');
- await action('write_copy_fields',{recordOnly:true,items:[
+ await action('write_copy_fields',{revision,recordOnly:true,items:[
{layer:1,text:'加厚桌腿',pictures:[slot.fieldId],sources:['仅详情图使用']},
]});
await action('open_production_output',{outputId:'main_images',variantId});
const write={revision:detail.revision,items:[{layer:1,text:'确认圆角桌面'}]};
- const blocked=await action('write_copy_fields',write);
- assert.deepEqual(blocked.rejected,[{layer:1,reason:'尚未读取此文字格'}]);
- assert.equal(edits,undefined);
const {details}=await action('read_output_screen',{page:1});
assert.deepEqual(details.screenCopy.map(row=>row.text),['圆角桌面']);
- await action('write_copy_fields',{...write,revision:details.copyRevision??details.revision});
+ await action('write_copy_fields',{...write,revision:details.copyRevision??details.revision,
+ items:[{...write.items[0],expectedText:details.screenCopy[0].text}]});
assert.equal(edits[0].expectedText,'圆角桌面');
await action('check_image_slots',{wait:true,candidates:[{slotId:slot.id,candidateId:'candidate'}]});
diff --git a/apps/detail-agent-pi/test/enterprise-context.test.mjs b/apps/detail-agent-pi/test/enterprise-context.test.mjs
index 88f767f1..3efbd78d 100644
--- a/apps/detail-agent-pi/test/enterprise-context.test.mjs
+++ b/apps/detail-agent-pi/test/enterprise-context.test.mjs
@@ -1,9 +1,11 @@
+import {projectTools} from '../src/project-tools.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {EnterpriseContext} from '../src/enterprise-context.mjs';
+import {openEnterpriseSkills} from '../src/enterprise-skill-resources.mjs';
import {EnterpriseKnowledge} from '../src/enterprise-knowledge.mjs';
test('selected resource guides are read completely with their own versions',async t=>{
@@ -35,10 +37,12 @@ test('selected resource guides are read completely with their own versions',asyn
assert.equal(result.rules[0].pages,2);
const production=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
assert.deepEqual(production.skills,result.skills);
+ assert.equal(production.rules[0].text,undefined);
+ assert.equal(documents.length,5);
assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']);
});
-test('explicit template skill sources are read by their published file identity and version', async t => {
+test('published rule bodies load only when read and keep the locked version', async t => {
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-template-guides-'));
t.after(()=>fs.rm(root,{recursive:true}));
const calls=[];
@@ -54,17 +58,32 @@ test('explicit template skill sources are read by their published file identity
},
async readDocument(id,revision) {
docs.push([id,revision]);
- return {result:{text:id+' rules',revision}};
+ return {result:{text:id==='workflow'
+ ? '---\nname: lighting\ndescription: Lighting instructions.\nmaxGenerationAttempts: 3\n---\n[Review](review.md)'
+ : 'rules body',revision}};
},
};
- const ctx=new EnterpriseContext({root,appendEvent:async()=>{}},client);
+ const store={root,dir:root,appendEvent:async()=>{}};
+ const ctx=new EnterpriseContext(store,client);
const input={task:'production',brandName:'Lighting Lab',categoryName:'灯具',releaseId:'release-3'};
- const result=await ctx.load({...input,skillSources});
+ const binding=await openEnterpriseSkills(store,input,pins=>ctx.load({...input,skillSources},{pins}),
+ (relative,lock)=>ctx.loadReference(relative,{...lock,read:execute=>execute()}));
assert.deepEqual(calls,['list_libraries']);
+ assert.deepEqual(docs,[['workflow','7']]);
+ assert.equal(binding.maxGenerationAttempts,3);
+ assert.equal(binding.resource.skills[0].name,'lighting');
+ const {files}=binding;
+ assert.deepEqual(files.map(({fileId,revision})=>[fileId,revision]),[['workflow','7'],['rules','11']]);
+ const reviewPath=files[1].path;
+ const {read}=await projectTools({store,productionSkills:binding});
+ const [result]=await Promise.all([
+ read('main').execute('',{path:reviewPath}),
+ binding.resolveFile(reviewPath),
+ ]);
+ assert.equal(result.content[0].text,'rules body');
assert.deepEqual(docs,[['workflow','7'],['rules','11']]);
- assert.equal(result.resourceRevision,'release-3');
- assert.equal(result.rules[0].text,'rules rules');
- assert.equal(result.skills[0].path,'Skills/Lighting/SKILL.md');
+ const reopened=await openEnterpriseSkills(store,input,()=>assert.fail('use the existing release'));
+ assert.equal(await fs.readFile(reopened.files[1].path,'utf8'),'rules body');
await assert.rejects(ctx.load(input),/尚未发布制作 Skill/u);
});
diff --git a/apps/detail-agent-pi/test/json-codec.test.mjs b/apps/detail-agent-pi/test/json-codec.test.mjs
index 0bb4175c..50d4ac79 100644
--- a/apps/detail-agent-pi/test/json-codec.test.mjs
+++ b/apps/detail-agent-pi/test/json-codec.test.mjs
@@ -25,7 +25,7 @@ test('strict JSON never executes prose, unknown tools, extra fields or malformed
test('actual Pi SDK consumes JSON codec through real OpenAI parser and validates/executes tools', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-json-sdk-'));
const scope = 'c'.repeat(64), store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', version: '1', source: 'qa-fixture', rules: [] });
- let calls = 0, finishes = 0;
+ let calls = 0;
const broker = {
info: async () => ({ accountScope: scope, model: { id: 'qa-model', protocol: 'openai-chat', maxTokens: 65536,
contextWindow: 131072, contextWindowSource: 'pi-model-catalog:qa/qa-model' }, pending: [] }),
@@ -39,13 +39,13 @@ test('actual Pi SDK consumes JSON codec through real OpenAI parser and validates
const chunk = { id, model: 'qa-model', choices: [{ index: 0, delta: { role: 'assistant', content: JSON.stringify(answer) }, finish_reason: null }] };
const finish = { id, model: 'qa-model', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] };
return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: ${JSON.stringify(finish)}\n\ndata: [DONE]\n\n`, { headers: { 'content-type': 'text/event-stream' } });
- }, finish: async valid => { assert.equal(valid, true); finishes++; return { phase: 'complete' }; } };
+ } };
},
};
const host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
const result = await host.prompt('这个测试颜色是浅灰色,请记住。');
assert.equal((await store.context()).confirmedMemory.color.value, '浅灰色');
- assert.equal(result.text, '浅灰色已记录'); assert.equal(calls, 2); assert.equal(finishes, 2);
+ assert.equal(result.text, '浅灰色已记录'); assert.equal(calls, 2);
await host.dispose(); await cleanup(dir);
});
test('output length stop never executes even a syntactically complete JSON tool prefix', async () => {
diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs
index e2fb8be7..0bc88b4c 100644
--- a/apps/detail-agent-pi/test/native-wire.test.mjs
+++ b/apps/detail-agent-pi/test/native-wire.test.mjs
@@ -99,7 +99,6 @@ test('native request validation can prove that no model was dispatched', async t
try {
const round=broker.round();
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/本机拒绝该操作/);
- assert.equal(broker.hasUnconfirmedRequest,!rejectedBeforeDispatch);
} finally { await broker.close(); }
}
});
@@ -125,12 +124,10 @@ test('the native bridge reports a retryable preflight to Pi without replaying it
const broker=new Native98kBroker({project:randomUUID(),profile,spawnProcess:()=>child});
broker.scope='fixture';
try {
- const round=broker.round({inference:true});
+ const round=broker.round();
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/network error/);
assert.equal(requests.length,1);
assert.equal(requests[0].id,round.id);
- assert.equal(requests[0].inference,true);
- assert.equal(broker.hasUnconfirmedRequest,false);
} finally {await broker.close();}
});
@@ -147,7 +144,7 @@ test('the native bridge posts only to the endpoint bound to the selected route',
await round.fetch('https://api.vip98k.com/v1/responses', {method:'POST',body:'{}'});
assert.equal(requests[0].input.invocationPath,'/v1/responses');
assert.deepEqual(requests[0].input.invocationHeaders,{'X-Relay-Route-Option':route});
- await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/禁止自动重发/);
+ await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/只接受一个请求/);
assert.equal(requests.length,1);
});
@@ -199,7 +196,6 @@ test('an exit signal during native broker startup prevents the original request
admit();
await assert.rejects(pending, /退出已停止接单/);
assert.deepEqual(requests, []);
- assert.equal(broker.hasUnconfirmedRequest, false);
});
test('forcing the daemon model bridge closed also closes its goal and slot processes', async t => {
@@ -286,19 +282,6 @@ test('a retained Responses function call is audited and decoded without a networ
await assert.rejects(parseReceipt({...record,raw:Buffer.from(JSON.stringify(response)).toString('base64')},model,'native-tools',[]));
});
-test('an explicit stream rate limit settles the attempt without confirm or replay', async () => {
- const broker = new Native98kBroker({project:randomUUID()});
- const calls = [];
- broker.start = async (method, _input, event) => {
- calls.push(method);
- event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
- return {phase:'failed',failureCode:'rate_limit_exceeded'};
- };
- const round = broker.round();
- await round.fetch('https://api.vip98k.com/v1/chat/completions', {method:'POST',body:'{}'});
- assert.deepEqual(await round.finish(false,'error'),{phase:'failed',failureCode:'rate_limit_exceeded'});
- assert.deepEqual(calls,['request']);
-});
const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`;
async function setup(reply, finish = async valid => { assert.equal(valid, true); return {phase:'complete'}; }, production, recovery = production) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
@@ -311,7 +294,8 @@ async function setup(reply, finish = async valid => { assert.equal(valid, true);
const id=randomUUID();
return { id, fetch: async (_url, init) => {
const p = JSON.parse(init.body); requests.push(p); ids.push(id);
- return new Response(reply(p, requests.length), { headers: { 'content-type': 'text/event-stream' } });
+ const result=reply(p,requests.length);
+ return result instanceof Response ? result : new Response(result,{headers:{'content-type':'text/event-stream'}});
}, finish };
} };
const canvas=(production||recovery?.canvas)&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},
@@ -371,6 +355,7 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi
}
return sse({content:'已核对画册。'},'stop');
},undefined,{outputs,template,callBudget:8,canvas:{
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'gallery',productVariantId:outputs[1].variantId,
template:{contentHash:'fixture'},totalSlots:0,slots:[]}),
requestWrite(){assert.fail('selection should not ask for canvas write access');},
@@ -405,9 +390,9 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi
}finally{await x.close();}
});
-test('ordinary chat resumes the same turn through Pi after a confirmed rate limit', async () => {
+test('ordinary chat resumes the same turn through Pi after a rate limit', async () => {
const x = await setup((_p, n) => n === 1
- ? 'data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n'
+ ? new Response(JSON.stringify({error:{message:'Rate limit exceeded'}}),{status:429,headers:{'retry-after':'0'}})
: sse({content:'可以继续处理。'}, 'stop'),
async valid => valid ? {phase:'complete'} : {phase:'failed',failureCode:'rate_limit_exceeded'});
try {
@@ -443,7 +428,7 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
if(method==='finish'){finished.push(input.id);return {phase:'complete'};}
assert.equal(method,'request');
requests.push(input);
- const success=input.inference===true && requests.length>1;
+ const success=requests.length>1;
emit({type:'headers',status:success?200:503,requestId:success?randomUUID():originalId,
headers:{'content-type':success?'text/event-stream':'application/json'},bodyHash:'native-wire'});
const error=JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}});
@@ -466,9 +451,6 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
assert.deepEqual(finished,[]);
assert.notEqual(requests[0].id,requests[1].id);
assert.equal(requests[0].body,requests[1].body);
- const guarded=broker.round();
- await guarded.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'});
- await assert.rejects(guarded.finish(false,'error'),/结果未知;不会重发/u);
});
test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{
@@ -479,16 +461,20 @@ test('the one-click goal resumes on changed fields at the same count without nam
if(n===5)return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
return sse({content:'本次复核有进展。'},'stop');
},undefined,{
- callBudget:6,plan:()=>({pendingText:1,field:++plans===1?'标题':'规格'}),
+ callBudget:6,plan:()=>({outputId:'detail',variantId:'oak',pendingText:1,field:++plans===1?'标题':'规格'}),
progress:()=>({state:{fields:[plans===1?'标题':'规格']}}),
});
try {
const result=await x.host.prompt('完成整套制作');
assert.equal(result.production.complete,true);
assert.equal(plans,2);
+ assert.match(JSON.stringify(x.requests[4].messages),/同范围已有更新回执/);
+ const oldPlan=x.host.manager.getBranch().find(({message})=>message?.role==='toolResult'&&message?.toolCallId==='plan-1')?.message;
+ assert.equal(JSON.parse(oldPlan.content[0].text).field,'标题');
for(const request of [x.requests[2],x.requests[4]]){
- const continuation=request.messages.findLast(message=>JSON.stringify(message).includes('继续当前制作目标'));
- assert.ok(continuation);
+ const reminders=request.messages.filter(message=>JSON.stringify(message).includes('继续当前制作目标'));
+ assert.equal(reminders.length,1);
+ const [continuation]=reminders;
assert.doesNotMatch(JSON.stringify(request.messages), /prompt-to-artifact checklist|PR state/u);
assert.doesNotMatch(JSON.stringify(continuation),/调用 (?:plan_production|write_copy_fields)/);
}
@@ -520,6 +506,21 @@ test('a managed inference interruption retries without executing its partial too
} finally {await x.close();}
});
+test('a broken model stream stops after the three native retries', async t => {
+ const x=await setup(()=>new Response(new ReadableStream({
+ start(controller) { controller.error(new TypeError('network error: mock stream disconnected')); },
+ }),{headers:{'content-type':'text/event-stream'}}));
+ x.host.callBudget=10;
+ t.after(()=>x.close());
+ const settings=x.host.session.settingsManager;
+ const retry=settings.getRetrySettings();
+ settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1});
+ await assert.rejects(x.host.prompt('核对进度'),/network error|network connection|connection error/i);
+ assert.equal(retry.maxRetries,3);
+ assert.equal(x.requests.length,4);
+ assert.equal(new Set(x.ids).size,4);
+});
+
test('actual native Pi wire sends function schemas, executes typed call and accepts a plain final reply', async () => {
const x = await setup((_p, n) => n === 1 ? sse({ tool_calls: [{ index: 0, id: 'call-memory', type: 'function', function: { name: 'memory_set', arguments: JSON.stringify({ key: 'color', value: '胡桃色', evidence: '测试颜色是胡桃色' }) } }] }, 'tool_calls') : sse({ content: '已记录胡桃色' }, 'stop'));
try {
@@ -576,16 +577,24 @@ test('native Pi preserves a required named tool across a retry on a string-only
} finally { await x.close(); }
});
-test('native partial arguments and length-stopped valid prefixes never execute memory writes', async () => {
- for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) {
- const x = await setup(() => sse({ tool_calls: [{ index: 0, id: 'partial', type: 'function', function: { name: 'memory_set', arguments: args } }] }, finish));
+test('Pi reports malformed tool arguments and never executes a length-stopped write', async () => {
+ for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'],
+ ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) {
+ const x = await setup((payload, n) => {
+ if (n===1) return sse({tool_calls:[{index:0,id:'partial',type:'function',function:{name:'memory_set',arguments:args}}]},finish);
+ assert.equal(finish,'tool_calls');
+ assert.ok(payload.messages.some(message=>message.role==='tool'&&message.tool_call_id==='partial'));
+ return sse({content:'本轮未写入。'},'stop');
+ });
try {
- await assert.rejects(x.host.prompt('测试颜色是红色'), /未完整|达到线路上限/);
+ if (finish === 'length') await assert.rejects(x.host.prompt('测试颜色是红色'), /达到线路上限/);
+ else assert.equal((await x.host.prompt('测试颜色是红色')).text,'本轮未写入。');
assert.deepEqual((await x.store.context()).confirmedMemory, {});
- assert.equal(x.requests.length, 1);
+ assert.equal(x.requests.length,finish==='length'?1:2);
} finally { await x.close(); }
}
});
+
test('required tool returned as prose is a known protocol failure with one POST and no execution', async () => {
const x = await setup(() => sse({ content: 'invoke tool memory_set with color red' }, 'stop'));
try {
@@ -788,9 +797,9 @@ test('main requests keep their original identity without saving a copy of the re
const events=journal.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==='provider_prepared');
+ const requests=events.filter(event=>event.type==='provider_started');
assert.deepEqual(requests.map(event=>event.id),x.ids);
- assert.equal(requests[0].purpose,'conversation');
+ assert.ok(events.some(event=>event.type==='usage' && event.id===x.ids[0] && event.purpose==='conversation'));
assert.ok(events.some(event=>event.type==='provider_finished' && event.id===x.ids[0]));
process.env[setting]='1';
await x.host.prompt('继续核对');
@@ -939,12 +948,13 @@ test('the Pi canvas contract forwards a deeper group summary with the requested
assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0});
});
-test('production exposes direct native tools and Pi file tools',async()=>{
+test('production exposes native controls and reads with other file tools deferred',async()=>{
const x=await setup(payload=>{
const names=payload.tools.map(row=>row.function.name);
- for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read','write','edit','ls','find','grep','bash']){
+ for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read']){
assert.ok(names.includes(name),name);
}
+ for(const name of ['write','edit','ls','find','grep','bash']) assert.ok(!names.includes(name),name);
return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
},undefined,{progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{nativeCatalog(){},nativeCall(){},nativeReconcile(){}}});
@@ -953,7 +963,8 @@ test('production exposes direct native tools and Pi file tools',async()=>{
const names=x.host.session.getActiveToolNames();
assert.ok(names.includes('codemode'));
assert.ok(names.includes('tool_search'));
- assert.ok(names.includes('read')&&names.includes('write'));
+ assert.ok(names.includes('read'));
+ assert.ok(x.host.session.getToolDefinition('write'));
assert.equal((await x.host.prompt('核对制作工具')).production.complete,true);
assert.equal(x.requests.length,1);
} finally {await x.close();}
@@ -993,8 +1004,9 @@ test('Pi runs independent production reads from the same model turn concurrently
test('production publishes direct native commands and no duplicate conversation tools',async()=>{
const executed=[];
const x=await setup((_,request)=>{
- const name=request===1?'native_call':'finish_production';
- const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:{revision:1};
+ const name=request===1?'native_call':request===2?'tool_search':'finish_production';
+ const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:
+ request===2?{query:'bash',limit:1}:{revision:1};
return sse({tool_calls:[{index:0,id:'edit-'+request,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
},undefined,{
progress:()=>({state:{waitingOnOriginals:true}}),
@@ -1018,13 +1030,19 @@ test('production publishes direct native commands and no duplicate conversation
for(const name of ['read_image_request','freeze_image_request']){
assert.equal(x.host.session.getToolDefinition(name),undefined,name);
}
- for(const name of ['plan_production','native_catalog','read_production_knowledge','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){
+ for(const name of ['plan_production','native_catalog','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){
assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
for(const name of ['native_call','prepare_image_request','dispatch_image_request','transform_slot_image','finish_production']){
assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
assert.equal((await x.host.prompt('完成制作')).production.complete,true);
+ const initialNames=x.requests[0].tools.map(tool=>tool.function.name);
+ assert.ok(initialNames.includes('read'));
+ assert.ok(x.requests[2].tools.some(tool=>tool.function.name==='bash'));
+ for (const name of ['bash','edit','write','find','grep','ls','memory_set','memory_search','context_read']) {
+ assert.ok(!initialNames.includes(name),name);
+ }
assert.deepEqual(executed,[{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}]);
const row=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='edit-1')?.message;
assert.equal(JSON.parse(row.content[0].text).executed,true);
@@ -1220,6 +1238,7 @@ test('reading a fresh production goal never starts the strategy, image workers,
fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}].filter(field=>!pageId||field.page===pageId),
}),
read:async()=>({revision:3}),
+ imageRequest: async stage => {assert.equal(stage,'pending');return [];},
detailRender: async () => ({page:0,revision:3,images:[]}),
},
};
diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs
index 169bc80c..998fbfaf 100644
--- a/apps/detail-agent-pi/test/pi.test.mjs
+++ b/apps/detail-agent-pi/test/pi.test.mjs
@@ -13,7 +13,6 @@ import { piGoalState, recordProductionExport } from '../src/production-goal.mjs'
import { EnterpriseContext } from '../src/enterprise-context.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs';
-import { mayContinueProductionGoal } from '../src/production-goal.mjs';
import { cleanup } from './cleanup.mjs';
const identity = () => ({ scope: 'a'.repeat(64), project: randomUUID() });
@@ -36,6 +35,7 @@ test('historical screen images are pruned from model context and retained in the
documentId, detailImages() {}, finishProduction:async input=>productionExportReceipt(input),
begin: async () => ({}), read: async () => ({conversationActive: true, revision: 3}),
delta: async () => {}, activity: async () => {}, end: async () => {},
+ imageRequest:async()=>[],
workflowRead: async () => ({available: true, canvasFirst: true, version: 1, outputId: 'detail',
productVariantId: variantId, template: {contentHash: 'fixture'}, totalSlots: 1,
slots: [{id: 'cover', fieldId: 'cover', label: '主视觉', candidates: []}],
@@ -90,6 +90,7 @@ test('Pi production and its worker read the same locked Skill and its relative r
const canvas={run:'skill-fixture',documentId,detailImages(){},finishProduction:async input=>productionExportReceipt(input),begin:async()=>({run:'skill-fixture',conversationActive:true}),
read:async()=>({conversationActive:true,revision:1}),delta:async()=>{},activity:async()=>{},reply:async()=>{},end:async()=>{},
detailCopyFields:async()=>({fields:[]}),
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:'detail',productVariantId:variantId,totalSlots:1,
slots:[{id:'lighting-slot',fieldId:'lamp',label:'灯罩近景'}],
template:{id:'two-outputs',version:'v4',contentHash:'v4',enterprise:true,resourceSetId:'lighting'},
@@ -166,7 +167,7 @@ test('Pi production and its worker read the same locked Skill and its relative r
assert.equal([...reads.values()].filter(body=>body.includes('PINNED_FINISH')).length,2);
assert.deepEqual(documents,[['finish','r7']]);
const second=await openEnterpriseSkills(store,selection,()=>{throw Error('run must use the first locked version');});
- assert.equal(second.knowledge.rules[0].revision,'r7');
+ assert.equal(second.files.find(file=>file.fileId==='finish').revision,'r7');
const mainSelection={...selection,outputId:'main_images',releaseId:'main-v4'};
const mainBinding=await openEnterpriseSkills(store,mainSelection,pins=>{
assert.equal(pins.get(knowledge.skills[0].path).revision,'r4');
@@ -225,21 +226,6 @@ test('native read reports an unavailable linked document and can read it once pu
assert.deepEqual([searchCalls,reads],[2,1]);
});
-test('Pi continues the goal without a host readiness gate', async () => {
- const host={productionGoal:{deadline:Date.now()/1000+60}};
- for(let turn=0;turn<4;turn++)assert.equal(await mayContinueProductionGoal(host),true);
- for(const stopReason of ['error','aborted']){
- assert.equal(await mayContinueProductionGoal(host,{messages:[{role:'assistant',stopReason}]}),false);
- }
- host.productionCompletion={receipt:{completed:true}};
- assert.equal(await mayContinueProductionGoal(host),false);
- host.productionCompletion=null;
- host.productionGoal.deadline=Date.now()/1000-1;
- assert.equal(await mayContinueProductionGoal(host),true);
- host.productionSignal=AbortSignal.abort();
- assert.equal(await mayContinueProductionGoal(host),false);
-});
-
test('Pi pauses after a continuation without tools and resumes on a new user request', {timeout:10000}, async t=>{
const dir=await root(), id=identity(), documentId=13, variantId=randomUUID();
const store=await ProjectStore.open(dir,id,binding('pause'));
@@ -251,6 +237,7 @@ test('Pi pauses after a continuation without tools and resumes on a new user req
run:'pause-fixture',documentId,detailImages(){},
begin:async()=>({conversationActive:true}),read:async()=>({conversationActive:true,revision:1}),
delta:async()=>{},activity:async()=>{},end:async()=>{},
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage,
productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage},
productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{}}}),
@@ -301,13 +288,14 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
begin:async()=>({run:'goal-fixture',conversationActive:true,context:null}),
read:async()=>({conversationActive:true,revision}),delta:async()=>{},end:async()=>{},
activity:async(_label,event)=>publicActivity.push(event),
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage,
productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage},
productEvidence:{accountScope:id.scope,project:id.project,documentId:13,brief:{}}}),
detailCopyFields:async()=>({fields:structuredClone(fields),revision}),
commitDetailCopy:async(items,expected)=>{
assert.equal(expected,revision);
- assert.equal(items[0].expectedText,fields[0].currentText);
+ assert.equal(items[0].expectedText,undefined);
copyWrites++;
revision++;
fields[0].currentText=items[0].text;
@@ -316,8 +304,8 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
};
const transport={info:info(id.scope),stream(_model,context){
const instructions=getCurrentSystemPrompt(context.messages);
- assert.match(instructions,/由你决定要做什么、顺序、并行和返工/);
- assert.match(instructions,/企业制作指引中的命令行编修可用等价的画布命令完成/);
+ assert.match(instructions,/由你决定[^。]*顺序、并行和返工/);
+ assert.match(instructions,/命令行编修可用等价的画布命令完成/);
const write=context.messages.find(message=>message.role==='toolResult'&&message.toolName==='write_copy_fields');
if(write)assert.deepEqual(JSON.parse(write.content[0].text),{appliedLayers:[1],revision:8});
const call=steps.shift();
@@ -371,6 +359,8 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
const completed=entries.findLast(e=>e.type==='custom'&&e.customType==='pi-goal');
assert.equal(completed.data.goal.status,'complete');
savedGoal=completed.data.goal.id;
+ await host.session.prompt('/goal pause');
+ assert.equal(piGoalState(host.manager).status,'paused');
}finally{await host.dispose();}
assert.equal(copyWrites,1);
assert.ok(publicActivity.every(row=>row.scope.documentId===canvas.documentId&&row.scope.run===canvas.run));
diff --git a/apps/detail-agent-pi/test/production-goal.test.mjs b/apps/detail-agent-pi/test/production-goal.test.mjs
index 5c03f313..d1b890c4 100644
--- a/apps/detail-agent-pi/test/production-goal.test.mjs
+++ b/apps/detail-agent-pi/test/production-goal.test.mjs
@@ -7,6 +7,7 @@ test('an elapsed legacy production deadline allows the goal and its local tool t
let called=0,aborted=0;
const host={manager:{getBranch:()=>[]},productionGoal:{deadline:1,requestedOutputs:[{outputId:'detail'}]},
session:{
+ messages:[],
sendCustomMessage:async()=>{},
prompt:async()=>{called++},
waitForIdle:()=>idle.promise,
diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs
index b3545a83..a97178e7 100644
--- a/apps/detail-agent-pi/test/production-operations.test.mjs
+++ b/apps/detail-agent-pi/test/production-operations.test.mjs
@@ -5,35 +5,81 @@ import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import { openProductionOperations } from '../src/production-operations.mjs';
-import { callProductionTool, closeProductionTurn, currentProductionOperations, mayContinueProductionGoal } from '../src/production-goal.mjs';
+import { openProductionOperations as openOperations } from '../src/production-operations.mjs';
+import { callProductionTool, closeProductionTurn, currentProductionOperations } 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';
+const imageBridges=new WeakSet();
+
+// The fixture models the host journal. Each Pi operations instance reads it anew.
function imageBridge(host,dispatch,id=()=>randomUUID()) {
const prepared=new Map();
- host.canvas.imageRequest=async(action,args,execution)=>{
+ const canvas=host.canvas;
+ imageBridges.add(canvas);
+ const workflowRead=canvas.workflowRead.bind(canvas);
+ const originalRecovery=canvas.detailRecover?.bind(canvas);
+ canvas.workflowRead=async input=>{
+ const view=await workflowRead(input);
+ const matching=[...prepared.values()].filter(({receipt})=>
+ receipt.outputId===view.outputId&&receipt.variantId===view.productVariantId&&receipt.phase!=='prepared');
+ return {...view,slots:view.slots?.map(slot=>({...slot,candidates:[
+ ...(slot.candidates??[]),...matching.filter(({receipt})=>receipt.slotId===slot.id&&
+ !slot.candidates?.some(row=>row.id===receipt.requestId))
+ .map(({receipt,result},index)=>({...result,id:receipt.requestId,status:receipt.phase,sequence:(slot.candidates?.length??0)+index+1,
+ reworkOf:receipt.reworkOf,instructions:receipt.spec.prompt})),
+ ]}))};
+ };
+ const settle=(receipt,result)=>{
+ Object.assign(receipt,{phase:result.status,resultExpiry:result.resultExpiry,message:result.message});
+ prepared.get(receipt.requestId).result=result;
+ };
+ canvas.detailRecover=async(slot,options,scope)=>{
+ const result=await originalRecovery(slot,options,scope);
+ const {receipt}=prepared.get(options.candidateId)??{};
+ if(receipt)settle(receipt,result);
+ return result;
+ };
+ canvas.imageRequest=async(action,args,execution)=>{
+ if(action==='pending')return [...prepared.values()].filter(({receipt})=>
+ ['dispatched','running','unknown'].includes(receipt.phase)).map(({receipt})=>({
+ slotId:receipt.slotId,candidateId:receipt.requestId,operationId:receipt.requestId,
+ phase:receipt.phase,outputId:receipt.outputId,variantId:receipt.variantId,
+ }));
if(action==='prepare'){
const requestId=id();
- const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,
+ const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,phase:'prepared',
+ templateHash:(await workflowRead({section:'overview',outputId:host.productionGoal.outputId})).template.contentHash,
outputId:host.productionGoal.outputId,variantId:host.productionGoal.variantId,slotId:args.slotId,
reworkOf:args.reworkOf,reworkChange:args.reworkChange,spec:{prompt:args.instructions}};
prepared.set(requestId,{receipt,args});
return structuredClone(receipt);
}
- assert.equal(action,'dispatch');
- assert.deepEqual(Object.keys(args),['requestId','expectedRevision','expectedHash','slotId','workerNumber']);
const request=prepared.get(args.requestId);
- assert.ok(request);
+ if(!request)throw Error('未找到原生生图请求');
+ if(action==='read')return structuredClone(request.receipt);
+ assert.equal(action,'dispatch');
assert.equal(args.slotId,request.receipt.slotId);
if(args.expectedHash!==request.receipt.requestSpecHash||args.expectedRevision!==request.receipt.revision){
- throw new BridgeError('生图请求版本已变化,请重新准备');
+ throw Object.assign(new BridgeError('生图请求版本已变化,请重新准备'),{dispatched:false});
}
if(dispatch.length<4)execution?.onEnqueued?.();
- return dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued);
+ request.receipt.phase='dispatched';
+ const result=await dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued);
+ settle(request.receipt,result);
+ return result;
};
+ return {prepared,settle};
}
+function openProductionOperations(host,options){
+ const canvas=host.canvas;
+ const original=canvas.imageRequest?.bind(canvas);
+ canvas.imageRequest=async(action,...args)=> action==='pending'&&!imageBridges.has(canvas) ? [] : original(action,...args);
+ return openOperations(host,options);
+}
+
function approve({requestId,revision,requestSpecHash}) {
return {requestId,expectedRevision:revision,expectedHash:requestSpecHash};
}
@@ -73,7 +119,7 @@ async function tailFixture(t,ids,items={}){
const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
template:{contentHash:'studio'},totalSlots:slots.length,slots}),
- detailCopyFields:async()=>({fields:[]}),
+ imageRequest:async()=>[],detailCopyFields:async()=>({fields:[]}),
async delta(_text,_thinking,{heading}){notices.get(heading)?.resolve();},
}};
if(Object.keys(items).length)ledger.repository.replaceLedger({binding:JSON.stringify(['studio','oak']),items});
@@ -84,50 +130,56 @@ async function tailFixture(t,ids,items={}){
}};
}
-test('a newly uncertain dispatch and a restored frozen request are watched without posting again',{timeout:5000},async t=>{
- for(const reopen of [false,true])await t.test(reopen?'restored from the ledger':'reported during production',async t=>{
- const {dir,host,ledger,clock,notice}=await tailFixture(t,['hero']);
- const posted=[],reads=[];
- const recovered=notice('原请求结果已取回');
- const result=Promise.withResolvers();
- imageBridge(host,async(_args,id)=>{
- posted.push(id);
- return {id,status:'unknown'};
- });
- host.canvas.detailRecover=async(slotId,{candidateId})=>{
- reads.push({slotId,candidateId});
- return result.promise;
- };
- let actions=await openProductionOperations(host,{tailWatchClock:clock});
- assert.equal(clock.nextDue,undefined);
- const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'});
- assert.equal(original.phase,'unknown');
- if(reopen){
- await actions.close();
- assert.equal(clock.nextDue,undefined);
- actions=await openProductionOperations(host,{tailWatchClock:clock});
- }
- t.after(()=>actions.close());
- assert.equal(clock.nextDue,0);
- await clock.advance();
- const manual=actions.reconcile_image_slots({slotIds:['hero']});
- assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]);
- const localImage=path.join(dir,'recovered-image.png');
- await fs.writeFile(localImage,'native image fixture');
- result.resolve({id:original.candidateId,status:'complete',path:localImage});
- const [receipt]=await manual;
- await recovered;
- assert.equal(receipt.phase,'complete');
- assert.equal(receipt.operationId,original.operationId);
- assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]);
- assert.deepEqual(posted,[original.candidateId]);
- assert.deepEqual((await actions.await_image_slots({slotIds:['hero']})).generation,[receipt]);
- assert.equal(ledger.repository.readImageRequest(original.candidateId).receipt.path,localImage);
- const saved=JSON.parse(await fs.readFile(path.join(dir,'production-detail-oak.json'),'utf8'));
- assert.deepEqual(saved.items.hero.pendingGenerations,{});
- assert.equal(saved.items.hero.state,'candidate');
- assert.equal(clock.nextDue,undefined);
+test('a host-owned original survives a Pi restart and is recovered without another POST',async t=>{
+ const {dir,host,ledger,clock}=await tailFixture(t,['hero']);
+ const posted=[],reads=[];
+ host.canvas.detailRecover=async(slotId,{candidateId})=>{
+ reads.push({slotId,candidateId});
+ return {id:candidateId,status:'complete'};
+ };
+ imageBridge(host,async(_args,id)=>{
+ posted.push(id);
+ return {id,status:'unknown'};
});
+ let actions=await openProductionOperations(host,{tailWatchClock:clock});
+ const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'});
+ assert.equal(original.phase,'unknown');
+ const closed=await actions.close();
+ assert.deepEqual(closed.inFlightImages,[{slotId:'hero',requestId:original.candidateId,operationId:original.operationId}]);
+ actions=await openProductionOperations(host,{tailWatchClock:clock});
+ t.after(()=>actions.close());
+ assert.equal(clock.nextDue,undefined);
+ assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).pendingOriginal,original.candidateId);
+ const [receipt]=await actions.reconcile_image_slots({slotIds:['hero']});
+ assert.equal(receipt.phase,'complete');
+ assert.equal(receipt.operationId,original.operationId);
+ assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]);
+ assert.deepEqual(posted,[original.candidateId]);
+ assert.equal(ledger.repository.readImageRequest(original.candidateId),null);
+ assert.equal(ledger.read(),null);
+ await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'});
+});
+
+test('a candidate reserved before POST neither owns the slot nor spends its draw budget',async t=>{
+ const {host}=await tailFixture(t,['hero'],{
+ hero:{state:'unknown',pendingGenerations:{'reserved-before-send':{candidateId:'reserved-before-send'}}},
+ });
+ const workflowRead=host.canvas.workflowRead;
+ host.canvas.workflowRead=async input=>{
+ const view=await workflowRead(input);
+ return {...view,template:{...view.template,production:{maxGenerationAttempts:1}},slots:view.slots.map(slot=>({...slot,generationRequestIds:[],
+ candidates:[{id:'reserved-before-send',status:'dispatched'}]}))};
+ };
+ const posted=[];
+ imageBridge(host,async(_args,id)=>{
+ posted.push(id);
+ return {id,status:'complete'};
+ });
+ const actions=await openProductionOperations(host);
+ const receipt=await generateAndWait(actions,{slotId:'hero',prompt:'本款正面'});
+ assert.equal(receipt.phase,'complete');
+ assert.deepEqual(posted,[receipt.candidateId]);
+ await actions.close();
});
test('six original lookups run while all six generation delegates are posting',{timeout:8000},async t=>{
@@ -287,8 +339,9 @@ for(const stop of ['abort','close'])test(`${stop} stops queued lookups and ignor
assert.equal(ledger.read().items.active.state,'unknown');
});
-const drawStatus=(attempts,max=4)=>({generationAttempts:attempts,maxGenerationAttempts:max,
- remainingGenerationAttempts:Math.max(0,max-attempts),drawLimitReached:attempts>=max});
+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-'));
@@ -427,7 +480,7 @@ test('a late image settles its original request after cancellation without selec
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
workflowExecute:async()=>assert.fail('a cancelled candidate cannot be adopted'),
}};
- imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};});
+ const native=imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};});
const old=await openProductionOperations(host);
const prepared=await old.prepare_image_request({slotId:'photo',prompt:'保留桌面轮廓'});
assert.equal((await old.dispatch_image_request(approve(prepared),abort.signal)).phase,'accepted');
@@ -436,17 +489,10 @@ test('a late image settles its original request after cancellation without selec
done.resolve();
await old.await_image_slots({});
await old.close();
- const receipt=ledger.repository.readImageRequest(prepared.requestId);
- assert.equal(receipt.state,'complete');
- assert.equal(receipt.operationId,prepared.operationId);
- assert.equal(receipt.receipt.consumption,'archived_after_cancel');
- assert.equal(ledger.read().items.photo.candidateId,undefined);
- assert.equal(ledger.read().items.photo.pendingAdoption,undefined);
- assert.deepEqual(events.find(event=>event.type==='image_request_receipt'),{
- type:'image_request_receipt',operationId:prepared.operationId,requestId:prepared.requestId,
- outputId:'detail',variantId:'oak',slotId:'photo',category:'remote_image',phase:'archive',
- status:'cancelled',consumption:'archived_after_cancel',
- });
+ assert.equal(native.prepared.get(prepared.requestId).receipt.phase,'complete');
+ assert.equal(ledger.repository.readImageRequest(prepared.requestId),null);
+ assert.equal(ledger.read(),null);
+ assert.equal(events.some(event=>event.type==='image_request_receipt'),false);
const fresh=await openProductionOperations({...host,productionSignal:new AbortController().signal});
assert.equal((await fresh.plan_production()).outputId,'detail');
await fresh.close();
@@ -456,12 +502,6 @@ test('switch keeps other output workers and their original requests without wait
const {host,ledger,clock}=await tailFixture(t,['active','queued']);
const posted=Promise.withResolvers(), remote=Promise.withResolvers(), queuedStarted=Promise.withResolvers();
const workerStarts=[];
- const archived=Promise.withResolvers();
- const appendEvent=host.store.appendEvent.bind(host.store);
- host.store.appendEvent=async event=>{
- await appendEvent(event);
- if(event.type==='image_request_receipt')archived.resolve();
- };
const localTransport=Promise.withResolvers();
imageBridge(host,async(_args,id,_number,onEnqueued)=>{
posted.resolve(id);
@@ -470,6 +510,13 @@ test('switch keeps other output workers and their original requests without wait
await remote.promise;
return {id,status:'complete'};
});
+ const archived=Promise.withResolvers();
+ const imageRequest=host.canvas.imageRequest;
+ host.canvas.imageRequest=async (action,...args)=>{
+ const receipt=await imageRequest(action,...args);
+ if(action==='dispatch')archived.resolve();
+ return receipt;
+ };
host.runDetailAgent=async(slotId,_instructions,_prompt,tools,_images,_scope,_captions,signal)=>{
workerStarts.push(slotId);
assert.equal(signal.aborted,false);
@@ -523,9 +570,10 @@ test('switch keeps other output workers and their original requests without wait
await queuedStarted.promise;
assert.deepEqual(workerStarts,['active','queued']);
remote.resolve();
- await archived.promise;
assert.equal(host.productionGoal.outputId,'main_images');
- assert.equal(ledger.read().items.active.candidateId,requestId);
+ await archived.promise;
+ assert.equal((await host.canvas.imageRequest('read',{requestId})).phase,'complete');
+ assert.equal(ledger.repository.readImageRequest(requestId),null);
const reopened=await callProductionTool(host,'open_production_output',{outputId:'detail',variantId:'oak'});
assert.equal(reopened.outputId,'detail');
assert.equal(await currentProductionOperations(host),operations);
@@ -538,7 +586,7 @@ test('project image discovery can stage a completed image on another output with
const target={outputId:'detail',variantId:'oak'};
host.productionGoal.requestedOutputs=[source,target];
const candidate={...source,slotId:'source',fieldId:'M01',candidateId:'completed',width:1600,height:1200,
- adoptionRecorded:true,reviewDecision:'pass'};
+ adoptionRecorded:true,reviewDecision:'pass',generationAttempts:2,sourceRequestId:'original'};
const staged=[];
host.canvas.detailHistory=async options=>{
if(options.projectPlan){
@@ -549,7 +597,7 @@ test('project image discovery can stage a completed image on another output with
assert.deepEqual(options,{projectImages:true,...source});
return [candidate];
};
- host.canvas.imageRequest=()=>assert.fail('本地复用不应派发生图');
+ host.canvas.imageRequest=async action=>{assert.equal(action,'pending','本地复用不应派发生图');return [];};
host.canvas.detailArchive=async(slotId,args)=>{
staged.push({slotId,...args});
return {id:'reused',status:'complete',reusedFrom:{candidateId:args.candidateId}};
@@ -566,7 +614,7 @@ test('project image discovery can stage a completed image on another output with
assert.deepEqual(staged,[{slotId:'target',projectId:undefined,candidateId:candidate.candidateId,forReview:true}]);
});
-test('deferral keeps active workers, unknown originals and ordinary rework in production',async t=>{
+test('deferral reports ongoing work and records a supplied blocker without choosing the next action',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-defer-output-'));
t.after(()=>cleanup(dir));
const outputId='main_images', variantId='oak', slotId='main-photo';
@@ -574,10 +622,12 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
const worker=Promise.withResolvers();
const ledger=store.ledger(outputId,variantId);
const binding=JSON.stringify(['template',variantId]);
+ let pending=[];
const host={
store,productionGoal:{outputId,variantId},
runDetailAgent:()=>worker.promise,
canvas:{
+ imageRequest:async()=>pending,
workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId,
template:{contentHash:'template'},totalSlots:1,slots:[{id:slotId,fieldId:'M01'}]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},read:async()=>({revision:1}),
@@ -587,20 +637,22 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
const call=(name,args)=>callProductionTool(host,name,args);
const blocker={kind:'missing_required_input',reason:'缺少官方承重参数',requiredAction:'请产品负责人提供承重规格'};
await call('delegate_image_slots',{jobs:[{slotId,goal:'补齐 M01'}]});
- assert.deepEqual(await call('defer_production_output',{blocker}),
- {submitted:false,reason:'work_in_progress',slotIds:[slotId],nextTool:'await_image_slots'});
+ const active=await call('defer_production_output',{});
+ assert.deepEqual(active.slotIds,[slotId]);
+ assert.equal(active.submitted,false);
+ assert.equal(active.nextTool,undefined);
+ assert.equal((await call('defer_production_output',{blocker})).stageStatus,'hard-blocked');
assert.equal(host.productionCompletion,undefined);
worker.resolve();
await call('await_image_slots',{});
await closeProductionTurn(host);
const original={candidateId:'original-image',operationId:'original-operation'};
- ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'unknown',
- pendingGenerations:{[original.candidateId]:original}}}});
+ pending=[{...original,outputId,variantId,slotId,phase:'unknown'}];
host.productionWork?.clear();
- const deferred=await call('defer_production_output',{blocker});
- assert.equal(deferred.reason,'originals_pending');
- assert.equal(deferred.nextTool,'reconcile_image_slots');
+ const deferred=await call('defer_production_output',{});
+ assert.equal(deferred.submitted,false);
+ assert.equal(deferred.nextTool,undefined);
assert.deepEqual(deferred.originals,{models:[],images:[original.candidateId]});
assert.equal(host.productionCompletion,undefined);
const receipt=await call('finish_production',{revision:1});
@@ -609,12 +661,12 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
assert.deepEqual(receipt.originals,deferred.originals);
assert.equal(host.productionCompletion,undefined);
+ pending=[];
ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'candidate',
review:{candidateId:'rejected-image',decision:'revise',reason:'主体构图需要调整'}}}});
host.productionWork?.clear();
host.productionCompletion=null;
- assert.deepEqual(await call('defer_production_output',{reason:'M01 退回,需要返工'}),
- {submitted:false,reason:'work_can_continue',nextTool:'plan_production'});
+ assert.equal((await call('defer_production_output',{reason:'M01 退回,需要返工'})).submitted,false);
assert.equal(host.productionCompletion,null);
});
@@ -641,7 +693,6 @@ test('deferral records a hard blocker even when the production operations cannot
blocker:{...blocker,requiredAction:' '},
},signal), error=>error===unavailable);
assert.deepEqual(submissions,[]);
- assert.equal(await mayContinueProductionGoal(host),true);
const receipt=await callProductionTool(host,'defer_production_output',{blocker,scope:'current'},signal);
assert.deepEqual(submissions,[{outputId,variantId,complete:false,stageStatus:'hard-blocked',blocker,
@@ -649,7 +700,6 @@ test('deferral records a hard blocker even when the production operations cannot
assert.equal(currentProductionOperations(host),undefined);
assert.deepEqual(host.productionGoal.pendingOutputs,[]);
assert.equal(host.productionCompletion.receipt,receipt);
- assert.equal(await mayContinueProductionGoal(host),false);
});
test('an unbound production turn checks project originals without opening any working canvas',async t=>{
@@ -660,12 +710,14 @@ test('an unbound production turn checks project originals without opening any wo
const main={outputId:'main_images',variantId:'white'};
const ledger=store.ledger(main.outputId,main.variantId);
const goal={requestedOutputs:[detail,main],pendingOutputs:[detail,main]};
- const calls=[];
+ const calls=[],pending=[];
const host={store,productionGoal:goal,canvas:{
openProductionOutput(){assert.fail('project reconciliation must leave canvas selection unchanged');},
- workflowRead(){assert.fail('project reconciliation must use the saved ledger');},
+ workflowRead(){assert.fail('project reconciliation must use the original host records');},
+ imageRequest:async()=>pending,
async detailRecover(slot,request,scope){
calls.push({slot,request,scope});
+ pending.length=0;
return {id:request.candidateId,status:'complete'};
},
}};
@@ -674,6 +726,7 @@ test('an unbound production turn checks project originals without opening any wo
ledger.repository.replaceLedger({binding:JSON.stringify(['main-template','white']),items:{
'original-slot':{state:'unknown',pendingGenerations:{original:{candidateId:'original',operationId:'operation'}}},
}});
+ pending.push({...main,slotId:'original-slot',candidateId:'original',operationId:'operation'});
assert.equal((await callProductionTool(host,'plan_production',{})).workingOutput,null);
assert.deepEqual(await reconcile({slotIds:['other-slot']}),{scope:'project',results:[]});
const result=await reconcile({});
@@ -682,7 +735,7 @@ test('an unbound production turn checks project originals without opening any wo
{...main,slotId:'original-slot',candidateId:'original',operationId:'operation',phase:'complete'},
]);
assert.deepEqual(calls,[{slot:'original-slot',request:{candidateId:'original'},scope:main}]);
- assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{});
+ assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{original:{candidateId:'original',operationId:'operation'}});
assert.deepEqual(await reconcile({}),{scope:'project',results:[]});
assert.equal(goal.outputId,undefined);
});
@@ -691,18 +744,16 @@ test('the unbound production plan lists the same readable knowledge files as the
const {host}=await tailFixture(t,['hero']);
const boundGoal=host.productionGoal;
host.productionGoal={requestedOutputs:[boundGoal],pendingOutputs:[boundGoal]};
- host.productionSkills={knowledge:{skills:[{
- fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill',loadText:async()=>'以本款事实为依据',
- }]}};
- const plan=await callProductionTool(host,'plan_production',{});
+ host.productionSkills={files:[{fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill'}]};
+ assert.equal((await callProductionTool(host,'plan_production',{})).knowledgeFiles,undefined);
+ const plan=await callProductionTool(host,'plan_production',{includeKnowledge:true});
assert.equal(plan.workingOutput,null);
assert.deepEqual(plan.knowledgeFiles,[{fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill'}]);
- const {text}=await callProductionTool(host,'read_production_knowledge',{fileId:plan.knowledgeFiles[0].fileId});
- assert.equal(text,'以本款事实为依据');
host.productionGoal=boundGoal;
const actions=await openProductionOperations(host);
t.after(()=>actions.close());
- assert.deepEqual((await actions.plan_production()).knowledgeFiles,plan.knowledgeFiles);
+ assert.equal((await actions.plan_production()).knowledgeFiles,undefined);
+ assert.deepEqual((await actions.plan_production({includeKnowledge:true})).knowledgeFiles,plan.knowledgeFiles);
});
test('candidate review leaves placement to the main agent, even with an old template policy',async t=>{
@@ -766,7 +817,7 @@ test('candidate review leaves placement to the main agent, even with an old temp
};
imageBridge(host,async(_request,id)=>{
posts.push(id);
- assert.ok(ledger.read().items[slotId].pendingGenerations[id]);
+ assert.equal(ledger.repository.readImageRequest(id),null);
firstStarted.resolve();
await complete.promise;
return {status:recoverA&&id===posts[0]?'unknown':'complete',id};
@@ -783,7 +834,7 @@ test('candidate review leaves placement to the main agent, even with an old temp
await actions.dispatch_image_request(approve(a));
await firstStarted.promise;
assert.equal((await actions.dispatch_image_request(approve(a))).phase,'already_running');
- assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),[a.requestId]);
+ assert.equal(ledger.repository.readImageRequest(a.requestId),null);
complete.resolve();
while(actions.active)await actions.await_image_slots({});
await actions.close();
@@ -976,8 +1027,9 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie
assert.equal(exact.attemptCount,3);
assert.equal(overview.rejectionCount,2);
assert.equal(overview.rejections,undefined);
- assert.deepEqual(exact.record.attempts.at(-1),{candidateId:'replacement',source:'generate',
- prompt:'以同款原片直杆为准,改为单张自然光近景',reworkOf:'old',change:'去掉模板构图并以原片确认支撑形状'});
+ assert.equal(exact.generations?.find(row=>row.candidateId==='replacement')?.reworkOf ??
+ exact.generation.reworkOf,'old');
+ assert.equal(exact.record.attempts.at(-1).candidateId,'old');
await ops.delegate_image_slots({jobs:[{slotId:'front',goal:'核对指定候选',reworkCandidateId:'missing'}]});
await ops.await_image_slots({});
@@ -1129,9 +1181,9 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
variants[1].colorName='暖白色';
creation++;
const prepare=canvas.imageRequest;
- canvas.imageRequest=(action,args)=>{
+ canvas.imageRequest=(action,args,execution)=>{
if(action==='prepare')assert.equal(args.retryOf,undefined);
- return prepare(action,args);
+ return prepare(action,args,execution);
};
const draft=await actions.prepare_image_request({...request,retryOf:''});
assert.equal(draft.spec.prompt,request.prompt);
@@ -1146,7 +1198,6 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
await prepared.promise;
const blocked=await actions.defer_production_output({reason:'等待候选回执',nextOutput});
assert.equal(blocked.submitted,false);
- assert.equal(blocked.reason,'work_in_progress');
assert.deepEqual(blocked.slotIds,[slotId]);
assert.equal((await actions.dispatch_image_request(approved)).phase,'already_running');
assert.equal((await actions.review_image_slots({slotIds:[slotId]})).pictures[0].generation.phase,'accepted');
@@ -1208,9 +1259,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'ink'}};
imageBridge(host,async(_args,operationId)=>{
submissions.push(operationId);
- const pending=journal().items[slotId].pendingGenerations[operationId];
- assert.equal(pending.operationId,operationId);
- assert.equal(pending.candidateId,operationId);
+ assert.equal(journal(),null);
throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true});
});
let actions=await openProductionOperations(host,{tailWatchClock});
@@ -1232,91 +1281,44 @@ test('a lost native acknowledgement can be recovered with the saved generation o
assert.equal(recovered.operationId,originalId);
assert.deepEqual(recoveries,[{slot:slotId,candidateId:originalId},{slot:slotId,candidateId:originalId}]);
assert.deepEqual(submissions,[originalId]);
- assert.deepEqual(journal().items[slotId].pendingGenerations,{});
+ assert.equal(journal(),null);
+ await actions.close();
});
-test('410 settles only the original result and permits an explicitly prepared replacement',async t=>{
- for(const legacy of [false,true])await t.test(legacy?'imported R28 ledger':'frozen SQLite request',async t=>{
- const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-expiry-'));
- t.after(()=>cleanup(dir));
- const store=productionStore(dir);
- const ledger=store.ledger('main_images','ink');
- const {repository}=ledger;
- const slotId='main-photo';
- const originalId=randomUUID(), remoteRequestId=randomUUID();
- const resultExpiry={httpStatus:410,source:'retained-result',requestId:remoteRequestId,observedAt:1795685081};
- const expiry={id:originalId,status:'expired',requestId:remoteRequestId,retryable:false,resultExpiry,message:'原生图结果已过期'};
- let response='timeout';
+test('the host can settle 410, failure and exhausted unresolved, then Pi can prepare another request',async t=>{
+ for(const terminal of ['expired','failed','unresolved'])await t.test(terminal,async t=>{
+ const {host,ledger}=await tailFixture(t,['hero']);
+ let status='unknown';
const posted=[], reads=[];
- const host={store,productionGoal:{outputId:'main_images',variantId:'ink'},canvas:{
- workflowRead:async()=>({available:true,canvasFirst:true,outputId:'main_images',productVariantId:'ink',
- template:{contentHash:'fixture'},totalSlots:1,slots:[{id:slotId,fieldId:'M02-I01'}]}),
- detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
- async detailRecover(slot,{candidateId}){
- reads.push({slot,candidateId});
- if(response==='timeout'||response==='connection lost')throw Error(response);
- return response==='410'?expiry:{id:originalId,status:'unknown',message:'HTTP '+response};
- },
- }};
- if(legacy){
- await fs.writeFile(path.join(dir,'production-main_images-ink.json'),JSON.stringify({
- binding:JSON.stringify(['fixture','ink']),preparedRequests:{[originalId]:{slotId,prompt:'旧提示词'}},
- items:{[slotId]:{state:'unknown',candidateId:originalId,source:'generate',
- pendingOperation:{candidateId:originalId,operationId:originalId,kind:'frozen-image'},
- attempts:[{candidateId:originalId,prompt:'旧提示词',source:'generate'}]}},
- }));
- }
+ const resultExpiry={httpStatus:410,requestId:'original-remote'};
+ host.canvas.detailRecover=async(slotId,{candidateId})=>{
+ reads.push([slotId,candidateId]);
+ return {id:candidateId,status,...(status==='expired'?{resultExpiry}:null)};
+ };
imageBridge(host,async(_args,id)=>{
posted.push(id);
- return {id,status:id===originalId?'unknown':'complete'};
- },()=>!legacy&&!posted.length?originalId:randomUUID());
-
- let actions=await openProductionOperations(host);
- const input={slotId:'M02-I01',source:'generate',prompt:'旧提示词'};
- if(!legacy)assert.equal((await generateAndWait(actions,input)).phase,'unknown');
- const before=legacy?[]:[originalId];
- await actions.close();
- actions=await openProductionOperations(host);
- for(response of ['timeout','connection lost','429','503']){
- const [receipt]=await actions.reconcile_image_slots({slotIds:[slotId]});
- assert.equal(receipt.phase,'unknown');
- assert.equal(receipt.candidateId,originalId);
- assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,originalId);
- assert.deepEqual(posted,before);
- if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'unknown');
- }
-
- response='410';
- const [expired]=await actions.reconcile_image_slots({slotIds:[slotId]});
- assert.deepEqual(expired,{slotId,candidateId:originalId,operationId:originalId,phase:'expired',
- reason:expiry.message,requestId:remoteRequestId,retryable:false,resultExpiry});
- assert.deepEqual(posted,before);
- const replacements=reads.length;
- assert.ok(reads.every(read=>read.slot===slotId&&read.candidateId===originalId));
- if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'expired');
- await actions.close();
-
- actions=await openProductionOperations(host);
- assert.equal((await actions.reconcile_image_slots({slotIds:[slotId]}))[0].phase,'none');
- assert.equal(reads.length,replacements);
- const same=await actions.dispatch_image_request({requestId:originalId,expectedRevision:1,expectedHash:'fixture-digest'});
- assert.equal(same.phase,'accepted');
- assert.equal((await actions.await_image_slots({slotIds:[slotId]})).generation[0].phase,'expired');
- assert.deepEqual(posted,before);
-
- const replacement=await generateAndWait(actions,{...input,prompt:'新提示词'});
- assert.equal(replacement.phase,'complete');
- assert.notEqual(replacement.candidateId,originalId);
- assert.deepEqual(posted,[...before,replacement.candidateId]);
- const {items}=JSON.parse(await fs.readFile(path.join(dir,'production-main_images-ink.json'),'utf8'));
- assert.equal(items[slotId].candidateId,replacement.candidateId);
- assert.equal(items[slotId].pendingOperation??null,null);
- assert.deepEqual(items[slotId].pendingGenerations,{});
- assert.deepEqual(items[slotId].attempts.find(item=>item.candidateId===originalId),{
- candidateId:originalId,source:'generate',prompt:'旧提示词',phase:'expired',
- requestId:remoteRequestId,retryable:false,resultExpiry,
+ return {id,status:posted.length===1?'unknown':'complete'};
});
- assert.deepEqual(repository.candidateEvidence(slotId,originalId).at(-1).detail.resultExpiry,resultExpiry);
+ const actions=await openProductionOperations(host);
+ const input={slotId:'hero',prompt:'原提示词'};
+ const original=await generateAndWait(actions,input);
+ assert.equal(original.phase,'unknown');
+ assert.equal((await actions.reconcile_image_slots({}))[0].candidateId,original.candidateId);
+ assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,original.candidateId);
+ assert.deepEqual(posted,[original.candidateId]);
+ // Exhaustion is a terminal receipt supplied by the Rust recovery owner.
+ status=terminal==='unresolved'?'failed':terminal;
+ const [settled]=await actions.reconcile_image_slots({});
+ assert.equal(settled.phase,status);
+ if(terminal==='expired')assert.deepEqual(settled.resultExpiry,resultExpiry);
+ assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).phase,status);
+ const next=await generateAndWait(actions,{...input,prompt:'新提示词'});
+ assert.equal(next.phase,'complete');
+ assert.notEqual(next.candidateId,original.candidateId);
+ assert.deepEqual(reads,[['hero',original.candidateId],['hero',original.candidateId]]);
+ assert.deepEqual(posted,[original.candidateId,next.candidateId]);
+ assert.equal(ledger.repository.readImageRequest(original.candidateId),null);
+ assert.equal(ledger.repository.readImageRequest(next.candidateId),null);
await actions.close();
});
});
@@ -1369,7 +1371,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
copyAttempts.push({items,expected});
if(copyWaiting){copyWaiting=false;return {retryWrite:true,revision};}
assert.ok(expected<=revision);
- if(items[0].expectedText!==fields[0].currentText)return {revision,appliedLayers:[],rejected:[{layer:7,reason:'原文已变化'}]};
+ if((expected!==revision||items[0].expectedText!==undefined)&&items[0].expectedText!==fields[0].currentText)return {revision,appliedLayers:[],rejected:[{layer:7,reason:'原文已变化'}]};
fields[0].currentText=items[0].text;
revision++;
return {appliedLayers:[7]};
@@ -1455,19 +1457,18 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
const proposal={revision,items:[{layer:7,text:'光线落在桌面',sources:['P01'],pictures:['lamp']}]};
copyWaiting=true;
+ const waiting=await actions.write_copy_fields(proposal);
+ assert.equal(waiting.retryWrite,true);
+ assert.deepEqual(copyAttempts,[{items:[{layer:7,text:'光线落在桌面'}],expected:proposal.revision}]);
assert.deepEqual((await actions.write_copy_fields(proposal)).appliedLayers,[7]);
- assert.deepEqual(copyAttempts,[
- {items:[{layer:7,text:'光线落在桌面',expectedText:''}],expected:proposal.revision},
- {items:[{layer:7,text:'光线落在桌面',expectedText:''}],expected:proposal.revision},
- ]);
assert.equal(fields[0].currentText,'光线落在桌面');
- const beforeIndependentEdit=await actions.read_copy_fields({});
+ const checkedCopy={...proposal,revision,items:[{...proposal.items[0],expectedText:'光线落在桌面'}]};
revision++;
- assert.deepEqual((await actions.write_copy_fields({...proposal,revision:beforeIndependentEdit.revision})).appliedLayers,[7]);
+ assert.deepEqual((await actions.write_copy_fields(checkedCopy)).appliedLayers,[7]);
const beforeUserEdit=await actions.read_copy_fields({});
fields[0].currentText='用户手改';
revision++;
- const rejected=await actions.write_copy_fields({...proposal,revision:beforeUserEdit.revision});
+ const rejected=await actions.write_copy_fields({...checkedCopy,revision:beforeUserEdit.revision});
assert.deepEqual(rejected.appliedLayers,[]);
assert.deepEqual(rejected.rejected,[{layer:7,reason:'原文已变化'}]);
assert.equal(fields[0].currentText,'用户手改');
@@ -1479,12 +1480,12 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
assert.match(submissions[0].instructions,/场景桌面上的一盏灯$/u);
assert.equal(submissions[0].prefer2k,true);
const overview=(await actions.review_image_slots({slotIds:[]})).pictures.find(row=>row.id==='lamp-photo');
- const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0].record;
+ const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0];
assert.equal(overview.state,'unknown');
assert.equal(overview.record,undefined);
assert.equal(overview.candidates,undefined);
- assert.equal(exact.pendingGenerations[first.candidateId].operationId,first.operationId);
- assert.match(exact.prompt,/场景桌面上的一盏灯/u);
+ assert.equal(exact.generation.candidateId,first.candidateId);
+ assert.match(exact.generation.instructions,/场景桌面上的一盏灯/u);
assert.equal((await generateAndWait(actions,{slotId:'lamp',source:'generate',prompt:'更换灯罩角度'})).phase,'unknown');
assert.equal(submissions.length,1);
const ledger=host.store.ledger(outputId,variantId);
@@ -1580,7 +1581,7 @@ test('worker progress shares a number with delegated image dispatch and reuses r
detailImages:async()=>{await reviewRelease.promise; throw Error('测试候选不提供像素');},
async delta(_text,_thinking,progress){
if(progress.heading==='子代理正在制作'&&progress.workers.length===5)started.resolve(progress);
- if(progress.heading==='子代理正在生图')generating.resolve(progress);
+ if(progress.workers.some(row=>row.slotId===first.id&&row.step==='正在生图'))generating.resolve(progress);
if(progress.heading==='子代理正在验图')checking.resolve(progress);
if(progress.heading==='验图已有回执')reviewed.resolve(progress);
},
@@ -1795,7 +1796,7 @@ test('copy update details contain only applied canvas text with a bounded previe
await actions.close();
});
-test('copy writes reuse confirmed revisions and rebase only unchanged, previously read layers',async t=>{
+test('copy writes forward revisions and optional expected text for the canvas to check',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-copy-revision-'));
t.after(()=>cleanup(dir));
let revision=1;
@@ -1813,21 +1814,24 @@ test('copy writes reuse confirmed revisions and rebase only unchanged, previousl
detailRender:async()=>({revision}),
async commitDetailCopy(items,expected){
commits.push(expected);
- assert.equal(expected,revision);
+ const appliedLayers=[],rejected=[];
for(const edit of items){
const field=fields.find(row=>row.layer===edit.layer);
- assert.equal(edit.expectedText,field.currentText);
+ if(!field||(expected!==revision||edit.expectedText!==undefined)&&edit.expectedText!==field.currentText){
+ rejected.push({layer:edit.layer,reason:field?'原文已变化':'当前画布没有这个文字格'});
+ continue;
+ }
field.currentText=edit.text;
+ appliedLayers.push(edit.layer);
}
- revision++;
- return {appliedLayers:items.map(row=>row.layer)};
+ if(appliedLayers.length)revision++;
+ return {appliedLayers,rejected,revision};
},
};
const ops=await openProductionOperations({store:productionStore(dir),canvas,productionGoal:{outputId:'detail',variantId:'oak'}});
const item=(layer,text)=>({layer,text,sources:[],pictures:[]});
const write=(revision,items)=>ops.write_copy_fields({revision,items});
- const start=await ops.read_copy_fields({fieldId:'title'});
- const first=await write(start.revision,[item(7,'标题一')]);
+ const first=await write(revision,[item(7,'标题一')]);
await write(first.revision,[item(7,'标题二')]);
revision++;
@@ -1839,19 +1843,40 @@ test('copy writes reuse confirmed revisions and rebase only unchanged, previousl
fields[0].currentText='用户手改';
revision++;
- const stale=await write(revision,[item(7,'禁止覆盖'),item(9,'未读'),item(99,'不存在')]);
- assert.deepEqual(stale.rejected,[{layer:7,reason:'原文已变化'},{layer:9,reason:'尚未读取此文字格'},
+ const stale=await write(revision-1,[{...item(7,'禁止覆盖'),expectedText:'图片采纳后的标题'},item(99,'不存在')]);
+ assert.deepEqual(stale.rejected,[{layer:7,reason:'原文已变化'},
{layer:99,reason:'当前画布没有这个文字格'}]);
assert.equal(stale.revision,revision);
- assert.match(stale.reason,/layer 7、9、99.*修订号 8/u);
await assert.rejects(write(revision,[item(8,'一'),item(8,'二')]),/layer 8 重复/u);
await assert.rejects(write(revision,[item(-1,'无效')]),/无效的文字格 layer -1/u);
- assert.equal(commits.length,4);
+ assert.deepEqual(commits,[1,2,4,6,7]);
assert.equal(fields[0].currentText,'用户手改');
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);
@@ -1905,6 +1930,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
dispatches.push(id);
if(dispatches.length===3){fourthStarted.resolve();await fourthDone.promise;}
slot.candidates.push({id,status:'complete',sourceType:null});
+ slot.generationRequestIds?.push(id);
return {id,status:'complete'};
});
const ops=await openProductionOperations(host);
@@ -1912,9 +1938,10 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
for(const [key,value] of Object.entries(expected))assert.equal(row[key],value,key);
};
const plan=()=>ops.plan_production({slotIds:['hero']});
- assertStatus((await plan()).pictures[0],drawStatus(1));
+ slot.generationRequestIds=['existing'];
+ assertStatus((await plan()).pictures[0],drawStatus(1,4));
await ops.retire_production_image({slotId:'hero',candidateId:'existing',reason:'构图不合适'});
- assertStatus((await plan()).pictures[0],drawStatus(1));
+ assertStatus((await plan()).pictures[0],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:'同款侧面'});
@@ -1922,7 +1949,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
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));
+ assertStatus((await plan()).pictures[0],drawStatus(3,4));
const fourth=await ops.prepare_image_request({...input,prompt:'同款俯拍'});
spare=await ops.prepare_image_request({...input,prompt:'同款低机位'});
@@ -1931,28 +1958,28 @@ 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)});
+ 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);
+ 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)});
- assertStatus((await ops.review_image_slots({slotIds:['hero']})).pictures[0],drawStatus(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');
- assertStatus(review,drawStatus(4));
+ assertStatus(review,drawStatus(4,4));
const delegated=await ops.delegate_image_slots({jobs:[{slotId:'hero',goal:'比较候选'}]});
- assertStatus(delegated.assigned[0],drawStatus(4));
+ assertStatus(delegated.assigned[0],drawStatus(4,4));
await ops.await_image_slots({slotIds:['hero']});
assert.equal(workerResults.length,2);
- for(const result of workerResults)assertStatus(result,{limitReached:true,...drawStatus(4)});
+ for(const result of workerResults)assertStatus(result,{limitReached:true,...drawStatus(4,4)});
assert.equal((await ops.adopt_production_image({slotId:'hero',candidateId:a.requestId})).phase,'complete');
assert.equal(slot.selectedCandidateId,a.requestId);
host.productionWork=new Map([[JSON.stringify(["detail","oak"]),Promise.resolve(ops)]]);
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();
});
diff --git a/apps/detail-agent-pi/test/production-store-fixture.mjs b/apps/detail-agent-pi/test/production-store-fixture.mjs
index d26ad7d5..9225d265 100644
--- a/apps/detail-agent-pi/test/production-store-fixture.mjs
+++ b/apps/detail-agent-pi/test/production-store-fixture.mjs
@@ -27,9 +27,10 @@ export function productionExportReceipt({outputId,variantId,canvasRevision,compl
export function stubProductionOperations(host, target, operations) {
const {outputId,variantId}=target;
const status={outputId,variantId,inFlightImages:[]};
+ host.canvas.imageRequest??=async()=>[];
const work=host.productionWork??=new Map();
work.set(JSON.stringify([outputId,variantId]),Promise.resolve({
- suspendCanvas:async()=>{},resumeCanvas(){},workStatus:()=>status,
+ suspendCanvas:async()=>[],resumeCanvas(){},workStatus:()=>status,
unfinished:async()=>({}),close:async()=>status,...operations,
}));
}
diff --git a/apps/detail-agent-pi/test/project-repository.test.mjs b/apps/detail-agent-pi/test/project-repository.test.mjs
index 86fec589..409ee75c 100644
--- a/apps/detail-agent-pi/test/project-repository.test.mjs
+++ b/apps/detail-agent-pi/test/project-repository.test.mjs
@@ -5,7 +5,6 @@ import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import test from 'node:test';
-import { Worker } from 'node:worker_threads';
import { openProductionOperations } from '../src/production-operations.mjs';
import { ProjectRepository } from '../src/project-repository.mjs';
import { recordProductionInputs } from '../src/production-repository.mjs';
@@ -22,7 +21,16 @@ const request = (requestId = 'image-a', spec = { prompt: '用同款实拍约束
const approve = draft => ({
requestId: draft.requestId, expectedHash: draft.requestSpecHash, expectedRevision: draft.revision,
});
-const pending = journal => journal.items.front?.pendingOperation;
+function seedLegacyRequest(repo, draft, state='prepared', receipt=null) {
+ repo.readLedger();
+ const db=new DatabaseSync(repo.file);
+ try {
+ db.prepare(`INSERT INTO image_requests
+ (account_id,project_id,output_id,variant_id,request_id,operation_id,slot_id,request_spec_hash,revision,state,prepared_json,receipt_json)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(...repo.scope,draft.requestId,draft.operationId,draft.slotId,draft.requestSpecHash,
+ draft.revision,state,JSON.stringify(draft),receipt&&JSON.stringify(receipt));
+ } finally { db.close(); }
+}
async function fixture(t) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-project-repository-'));
@@ -114,11 +122,11 @@ test('P01 local facts, document evidence and delivery reopen without a collabora
assert.deepEqual(open().readDelivery(), delivery);
});
-test('P02 stores the exact complete prompt and rejects changes at the same revision', async t => {
+test('P02 reopens the exact complete prompt from a legacy request', async t => {
const { file, open, repo } = await fixture(t);
const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' });
assert.ok(draft.spec.prompt.length > 2000);
- repo.saveImageRequest(draft);
+ seedLegacyRequest(repo, draft);
assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt);
assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt);
const db = new DatabaseSync(file, { readOnly:true });
@@ -127,46 +135,40 @@ test('P02 stores the exact complete prompt and rejects changes at the same revis
} finally {
db.close();
}
- assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/);
});
-test('P03 the production bridge sends reviewed identity and the display number after an atomic local freeze', async t => {
+test('P03 dispatches a host-confirmed request once without a Pi request row', async t => {
const { dir } = await fixture(t);
const store = productionStore(dir, { scope: scope.accountId, project: scope.projectId });
const repo = store.ledger('detail', 'oak').repository;
- const draft = request('frozen', { prompt: '原始完整文字\n保留边缘', modelId: 'actual-model',
- parameters: { size: '2048x2048' }, references: [{ position: 1, role: 'product', sha256: hash('reference') }] });
- const calls = [];
- const host = { store, productionGoal: { outputId: 'detail', variantId: 'oak' }, canvas: {
- workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak',
- template: { contentHash: 'template' }, totalSlots: 1, slots: [{ id: 'front', fieldId: 'cover' }] }),
- detailCopyFields: async () => ({ fields: [] }),
- delta: async () => {},
- async imageRequest(action, args) {
- if (action === 'prepare') return draft;
+ const draft = {...request('frozen'),phase:'prepared',outputId:'detail',variantId:'oak',templateHash:'template'};
+ const slot={id:'front',fieldId:'cover',candidates:[]};
+ const calls=[];
+ const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
+ workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
+ template:{contentHash:'template'},totalSlots:1,slots:[slot]}),
+ detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
+ async imageRequest(action,args,execution){
+ if(action==='pending')return [];
+ if(action==='read'||action==='prepare')return {...draft};
calls.push(args);
- const saved = repo.readImageRequest(draft.requestId);
- assert.equal(saved.state, 'dispatching');
- assert.equal(typeof saved.frozenAt, 'number');
- assert.deepEqual(saved.prepared.spec, draft.spec);
- assert.equal(repo.readLedger().items.front.pendingGenerations[draft.requestId].operationId, draft.operationId);
- const portable = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-oak.json'), 'utf8'));
- assert.equal(portable.items.front.pendingGenerations[draft.requestId].operationId, draft.operationId);
- assert.equal(portable.preparedRequests[draft.requestId].prompt, draft.spec.prompt);
- return { status: 'complete', id: draft.requestId, materialTaskId: draft.requestId };
+ assert.equal(args.expectedRevision,draft.revision);
+ assert.equal(args.expectedHash,draft.requestSpecHash);
+ execution.onEnqueued();
+ draft.phase='complete';
+ slot.candidates.push({id:draft.requestId,status:'complete'});
+ return {status:'complete',id:draft.requestId};
},
}};
- const tools = await openProductionOperations(host);
- const prepared = await tools.prepare_image_request({ slotId: 'cover', prompt: draft.spec.prompt });
- await tools.dispatch_image_request({ ...approve(prepared), expectedRevision: 2 });
- assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'failed');
- assert.equal(calls.length, 0);
- for (let attempt = 0; attempt < 2; attempt++) {
- await tools.dispatch_image_request({ requestId: prepared.requestId });
- assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'complete');
- }
- assert.deepEqual(calls, [{ ...approve(draft), slotId: 'front', workerNumber: 1 }]);
- assert.equal(repo.readImageRequest(draft.requestId).receipt.status, 'complete');
+ const tools=await openProductionOperations(host);
+ const prepared=await tools.prepare_image_request({slotId:'cover',prompt:draft.spec.prompt});
+ assert.equal((await tools.dispatch_image_request(approve(prepared))).phase,'accepted');
+ assert.equal((await tools.await_image_slots({})).generation[0].phase,'complete');
+ assert.equal((await tools.dispatch_image_request({requestId:prepared.requestId})).phase,'complete');
+ assert.deepEqual(calls,[{...approve(draft),slotId:'front',workerNumber:1}]);
+ assert.equal(repo.readImageRequest(draft.requestId),null);
+ assert.equal(repo.readLedger(),null);
+ await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'});
await tools.close();
});
@@ -180,7 +182,7 @@ test('P04 keeps original and normalized references, asset identities and send or
position: index + 1, role: 'product', source: 'P1', originalAssetId: original.assetId,
sourceSha256: original.sha256, assetId: input.assetId, sha256: input.sha256,
}));
- repo.saveImageRequest(request('p1', { prompt: '同款两视角。', references }));
+ seedLegacyRequest(repo, request('p1', { prompt: '同款两视角。', references }));
assert.deepEqual(open().readImageRequest('p1').prepared.spec.references, references);
assert.equal(open().readAsset(references[0].originalAssetId).path, original.path);
assert.equal(open().readAsset(references[1].assetId).path, wide.path);
@@ -190,8 +192,8 @@ test('P05 a prompt edit cannot relabel a candidate generated by the old request'
const { repo } = await fixture(t);
const first = request('old', { prompt: '第一版' });
const corrected = { ...request('rework', { prompt: '新取景' }), reworkOf: 'old', reworkChange: '修改机位' };
- repo.saveImageRequest(first);
- repo.saveImageRequest(corrected);
+ seedLegacyRequest(repo, first);
+ seedLegacyRequest(repo, corrected);
repo.recordCandidate('front', 'old', 'candidate', { requestId: 'old', requestSpecHash: first.requestSpecHash });
repo.recordCandidate('side', 'reuse', 'candidate', { reusedFrom: { projectId: 'project', candidateId: 'old' } });
assert.equal(repo.candidateEvidence('front', 'old')[0].detail.requestSpecHash, first.requestSpecHash);
@@ -219,48 +221,22 @@ test('P07 two intentionally equivalent samples keep distinct operations and actu
const b = request('sample-b');
assert.equal(a.requestSpecHash, b.requestSpecHash);
for (const draft of [a, b]) {
- repo.saveImageRequest(draft);
- assert.equal(repo.claimImageRequest(approve(draft), binding, pending).claimed, true);
+ seedLegacyRequest(repo, draft);
}
- assert.deepEqual(Object.keys(open().readLedger().items.front.pendingGenerations), [a.requestId, b.requestId]);
for (const draft of [a, b]) {
- repo.updateLedger(binding, journal => { delete journal.items[draft.slotId].pendingGenerations[draft.requestId]; }, {
- receipt: [draft.requestId, 'complete', { status: 'complete' }],
- evidence: [draft.slotId, draft.requestId, 'review', { candidateId: draft.requestId, decision: 'pass' }],
- });
+ repo.recordCandidate(draft.slotId,draft.requestId,'review',{candidateId:draft.requestId,decision:'pass'});
}
assert.notEqual(open().readImageRequest(a.requestId).operationId, open().readImageRequest(b.requestId).operationId);
assert.deepEqual(repo.candidateEvidence('front', b.requestId).map(row => row.kind), ['review']);
});
-test('P08 concurrent workers claim one operation and a restarted worker retains the original', async t => {
- const { file, open, repo } = await fixture(t);
- const draft = request('interrupted');
- repo.saveImageRequest(draft);
- const start = new SharedArrayBuffer(4);
- const run = () => new Promise((resolve, reject) => {
- const worker = new Worker(`
- const { parentPort, workerData } = require('node:worker_threads');
- (async () => {
- const { ProjectRepository } = await import(workerData.module);
- const repo = new ProjectRepository(workerData.file, workerData.scope);
- const barrier = new Int32Array(workerData.start);
- Atomics.add(barrier, 0, 1);
- Atomics.notify(barrier, 0);
- Atomics.wait(barrier, 0, 1, 5000);
- parentPort.postMessage(repo.claimImageRequest(workerData.approval, workerData.binding,
- journal => journal.items.front?.pendingOperation).claimed);
- })().catch(error => { throw error; });
- `, { eval: true, workerData: { start, file, scope, binding, approval: approve(draft),
- module: new URL('../src/project-repository.mjs', import.meta.url).href } });
- worker.once('message', resolve);
- worker.once('error', reject);
- });
- assert.deepEqual((await Promise.all([run(), run()])).sort(), [false, true]);
- const resumed = open().claimImageRequest(approve(draft), binding, pending);
- assert.equal(resumed.claimed, false);
- assert.equal(resumed.pending.operationId, draft.operationId);
- assert.equal(open().readImageRequest(draft.requestId).state, 'dispatching');
+test('P08 reads the original dispatching state from a historical database after reopening', async t => {
+ const {repo,open}=await fixture(t);
+ const draft=request();
+ seedLegacyRequest(repo,draft,'dispatching');
+ const saved=open().readImageRequest(draft.requestId);
+ assert.equal(saved.state,'dispatching');
+ assert.equal(saved.operationId,draft.operationId);
});
test('P09 output, variant, project and account are independent even when their IDs overlap', async t => {
@@ -268,15 +244,13 @@ test('P09 output, variant, project and account are independent even when their I
const neighbors = [open({ variantId: 'walnut' }), open({ outputId: 'main_images' }),
open({ projectId: 'other' }), open({ accountId: 'other' })];
const draft = request();
- repo.saveImageRequest(draft);
- repo.claimImageRequest(approve(draft), binding, pending);
+ seedLegacyRequest(repo, draft);
for (const other of neighbors) {
assert.equal(other.readImageRequest(draft.requestId), null);
assert.equal(other.readLedger(), null);
other.replaceLedger({ binding: 'independent', items: { front: { candidateId: 'other' } } });
}
- repo.updateLedger(binding, journal => { journal.items.front.candidateId = draft.requestId; },
- { receipt: [draft.requestId, 'complete', { status: 'complete' }] });
+ repo.updateLedger(binding, journal => { journal.items.front = {candidateId:draft.requestId}; });
for (const other of neighbors) assert.equal(other.readLedger().items.front.candidateId, 'other');
});
@@ -301,7 +275,7 @@ test('P11 records the actual background request separately from local compositin
const { repo } = await fixture(t);
const draft = request('background', { prompt: '移除模板中的旧商品。', sceneComposite: true,
references: [{ position: 1, role: 'scene', sha256: hash('template scene') }] });
- repo.saveImageRequest(draft);
+ seedLegacyRequest(repo,draft,'complete',{status:'complete'});
repo.recordCandidate('front', 'composite', 'candidate', { requestId: 'background',
processing: { kind: 'composite', productAssetId: 'actual-product-cutout', placement: [10, 20, 900, 1200] } });
assert.deepEqual(repo.readImageRequest('background').prepared.spec.references.map(row => row.role), ['scene']);
@@ -329,7 +303,7 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve
}, [{ id: 'front', fieldId: 'cover', requirements: '展示圆角' }]);
const draft = { ...request(), productFactsRevision, planRevision,
knowledge: [{ fileId: 'image-prompt', revision: 'r7' }] };
- repo.saveImageRequest(draft);
+ seedLegacyRequest(repo, draft);
const { prepared } = open().readImageRequest(draft.requestId);
assert.equal(open().readVersion('product_facts', 'product', prepared.productFactsRevision).facts.items[0].source, 'P1');
assert.equal(open().readVersion('plan', 'production', prepared.planRevision).slots[0].requirements, '展示圆角');
@@ -337,37 +311,16 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve
assert.deepEqual(prepared.knowledge, draft.knowledge);
});
-test('P14 reads the locked rule on demand and surfaces an unavailable reference', async t => {
- const { dir } = await fixture(t);
- const store = productionStore(dir);
- let available = false;
- const tools = await openProductionOperations({ store, productionGoal: { outputId: 'detail', variantId: 'oak' },
- canvas: { workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak',
- template: { contentHash: 'template' }, totalSlots: 0, slots: [] }) },
- productionSkills: { knowledge: { rules: [{ fileId: 'prompt-framework', revision: 'locked', kind: 'image-prompt',
- loadText: async () => {
- if (!available) throw Error('锁定版本引用暂不可读取');
- return '正式提示词结构';
- } }] } },
- });
- await assert.rejects(tools.read_production_knowledge({ fileId: 'prompt-framework' }), /锁定版本引用暂不可读取/);
- available = true;
- const rule = await tools.read_production_knowledge({ fileId: 'prompt-framework' });
- assert.deepEqual(rule, { fileId: 'prompt-framework', revision: 'locked', text: '正式提示词结构', nextOffset: null });
-});
-
test('P15 execution success and a failed pixel check remain independently traceable', async t => {
const { open, repo } = await fixture(t);
const draft = request('undersize', { prompt: '输出 4K,保留产品结构。' });
- repo.saveImageRequest(draft);
- repo.claimImageRequest(approve(draft), binding, pending);
- repo.recordImageReceipt(draft.requestId, 'complete', { status: 'complete' });
+ seedLegacyRequest(repo,draft,'complete',{status:'complete'});
repo.recordCandidate('front', draft.requestId, 'review', {
decision: 'revise', actualPixels: [1024, 1024], reason: '尺寸不足且接合结构错误',
});
const next = { ...request('corrected'), reworkOf: draft.requestId };
- repo.saveImageRequest(next);
- assert.equal(open().readImageRequest(draft.requestId).state, 'complete');
+ seedLegacyRequest(repo, next);
+ assert.equal(open().readImageRequest(draft.requestId).prepared.spec.prompt,draft.spec.prompt);
assert.equal(open().candidateEvidence('front', draft.requestId)[0].detail.decision, 'revise');
assert.equal(open().readImageRequest(next.requestId).prepared.reworkOf, draft.requestId);
});
diff --git a/apps/detail-agent-pi/test/recovery.test.mjs b/apps/detail-agent-pi/test/recovery.test.mjs
index ea2f0ff4..b712c46f 100644
--- a/apps/detail-agent-pi/test/recovery.test.mjs
+++ b/apps/detail-agent-pi/test/recovery.test.mjs
@@ -1,5 +1,5 @@
-import { stubProductionOperations } from './production-store-fixture.mjs';
-import { productionExportReceipt } from './production-store-fixture.mjs';
+import { BridgeError } from '../src/bridge-error.mjs';
+import { productionExportReceipt, stubProductionOperations } from './production-store-fixture.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
@@ -8,7 +8,6 @@ import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { ProjectStore } from '../src/store.mjs';
import { DetailPiAgent } from '../src/agent.mjs';
-import { recoverProductionResponse } from '../src/production-recovery.mjs';
import { cleanup } from './cleanup.mjs';
const setup = async () => {
@@ -26,69 +25,6 @@ test('project lease rejects another process/session before opening transcript or
const b = await DetailPiAgent.open({ store, transport });
await b.dispose(); await cleanup(root);
});
-test('received final reply recovers from bytes, persists and reopens without inference', async () => {
- const { root, scope, store } = await setup();
- let confirmations = 0, posts = 0;
- const id = randomUUID();
- await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash });
- const original = { id: 'qa-original-response', model: 'qa', choices: [{ message: { role: 'assistant', content: '{"reply":"草稿已保留"}' }, finish_reason: 'stop' }] };
- const broker = {
- info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }),
- read: async () => ({ phase: 'received', terminal: true, model: { id: 'qa', protocol: 'openai-chat' }, raw: Buffer.from(JSON.stringify(original)).toString('base64'), bodyHash: 'qa', requestId: 'retained-qa' }),
- confirm: async () => { confirmations++; return { phase: 'complete' }; },
- round() { posts++; throw Error('must never post'); },
- };
- let host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
- const result = await host.recover(id);
- assert.equal(result.reposted, false); assert.equal(result.reopenRequired, true); assert.equal(confirmations, 1); assert.equal(posts, 0);
- await host.dispose();
- host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
- assert.equal(host.session.getLastAssistantText(), '草稿已保留');
- const again = await host.recover(id);
- assert.equal(again.alreadyApplied, true); assert.equal(posts, 0);
- await host.dispose(); await cleanup(root);
-});
-
-test('recovers structured image review for the original slot without adding it to chat',async()=>{
- const {root,scope,store}=await setup();
- const id=randomUUID();
- const review=JSON.stringify({decision:'generate',reason:'同款产品依据齐备'});
- await store.appendEvent({type:'provider_prepared',id,purpose:'whole-detail-review',bindingHash:store.hash});
- let phase='unknown',posts=0,lookups=0;
- const model={id:'qa',protocol:'openai-chat'};
- const original={id:'review-original',model:'qa',choices:[{message:{role:'assistant',content:review},finish_reason:'stop'}]};
- const broker={info:async()=>({accountScope:scope,model,pending:[]}),
- read:async()=>({phase,terminal:true,model,raw:Buffer.from(JSON.stringify(original)).toString('base64'),bodyHash:'qa',requestId:'review-original'}),
- recover:async request=>{assert.equal(request,id);lookups++;phase='received';},
- confirm:async()=>{phase='complete';return {phase};},round(){posts++;throw Error('must not post');}};
- const host=await DetailPiAgent.open({store,broker,protocolMode:'structured-json'});
- try{
- const result=await host.recover(id);
- assert.equal(result.phase,'complete');
- assert.equal(result.canvasWrites,0);
- assert.equal(lookups,1);
- assert.equal(host.session.messages.length,0);
- assert.match(result.restoredText,/已核查原验图结果/);
- assert.equal(result.reposted,false);
- assert.equal(posts,0);
- }finally{await host.dispose();await cleanup(root);}
-});
-test('explicit text recovery queries the original without submitting inference', async () => {
- const { root, scope, store } = await setup();
- let queries = 0, posts = 0;
- await store.appendEvent({ type: 'provider_prepared', id: 'original', bindingHash: store.hash });
- const broker = {
- info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [{ id: 'original', phase: 'unknown' }] }),
- read: async () => ({ phase: 'unknown', requestId: 'original-qa' }),
- recover: async () => { queries++; throw Error('原请求查询HTTP 410,结果未知;不会重发'); },
- round() { posts++; throw Error('must not post'); },
- };
- const host = await DetailPiAgent.open({ store, broker });
- const result = await host.recover('original');
- assert.equal(result.phase, 'unknown'); assert.equal(result.reposted, false);
- assert.equal(queries, 1); assert.equal(posts, 0);
- await host.dispose(); await cleanup(root);
-});
test('a waiting detail original does not hold independent main image and SKU goals',async t=>{
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
@@ -182,92 +118,6 @@ test('DeepSeek Flash 1017 can receive an optional strategy tool and product imag
}
});
-test('a retained terminal model refusal unblocks production without reposting or running tools', async t => {
- for(const [protocol,body] of [
- ['anthropic-messages','data: {"type":"message_delta","delta":{"stop_reason":"refusal"}}\n\ndata: {"type":"message_stop"}\n\n'],
- ['openai-chat','data: {"choices":[{"index":0,"finish_reason":"content_filter"}]}\n\ndata: [DONE]\n\n'],
- ]){
- const {root,scope,store}=await setup();
- t.after(()=>cleanup(root));
- const id=randomUUID(),requestId=randomUUID();
- const model={id:'fixture',protocol};
- const raw=Buffer.from(body).toString('base64');
- await store.appendEvent({type:'provider_prepared',purpose:'product-goal',id,bindingHash:store.hash});
- const confirmed=[];
- const broker={
- info:async()=>({accountScope:scope,model,pending:[]}),
- read:async originalId=>{
- assert.equal(originalId,id);
- return {phase:'received',terminal:true,model,raw,bodyHash:'same',requestId};
- },
- confirm:async(...args)=>{confirmed.push(args);return {phase:'rejected'};},
- };
- const host=await DetailPiAgent.open({store,broker});
- try {
- assert.deepEqual(await host.recover(id),{phase:'failed',requestId,reposted:false,canvasWrites:0});
- assert.deepEqual(confirmed,[[id,'same',false,'refusal']]);
- } finally {await host.dispose();}
- }
-});
-
-test('original production recovery waits for the durable finish and releases confirmed terminal truncation',async t=>{
- const {root,scope,store}=await setup();
- t.after(()=>cleanup(root));
- const model={id:'qa',protocol:'openai-chat'};
- for(const [finishReason,finishPhase,wanted] of [
- ['length','rejected','failed'],
- ['stop','received','unknown'],
- ['stop','complete','complete'],
- ]){
- const id=randomUUID(),requestId=randomUUID();
- await store.appendEvent({type:'provider_prepared',id,purpose:'product-goal',bindingHash:store.hash});
- const bytes='data: '+JSON.stringify({id:requestId,model:'qa',choices:[{index:0,
- delta:{role:'assistant',content:'部分制作回复'},finish_reason:finishReason}]})+'\n\ndata: [DONE]\n\n';
- let phase='unknown',checks=0;
- const broker={
- info:async()=>({accountScope:scope,model,pending:[]}),
- read:async original=>{
- assert.equal(original,id);
- return {phase,terminal:phase==='received',model,bodyHash:'same',requestId,raw:Buffer.from(bytes).toString('base64')};
- },
- recover:async original=>{assert.equal(original,id);checks++;phase='received';},
- confirm:async(original,hash,valid,reason)=>{
- assert.deepEqual([original,hash,valid,reason],[id,'same',finishReason==='stop',finishReason]);
- return {phase:finishPhase};
- },
- round:()=>assert.fail('recovery must not post'),
- };
- const host=await DetailPiAgent.open({store,broker});
- try {
- assert.deepEqual(await host.recover(id),{phase:wanted,requestId,reposted:false,canvasWrites:0});
- assert.equal(checks,1);
- }finally{await host.dispose();}
- }
-});
-
-test('production recovery reads the original result after the selected chat model changes', async t => {
- const {root,scope,store}=await setup();
- t.after(()=>cleanup(root));
- const id=randomUUID(), requestId=randomUUID();
- const selected={id:'new-text-choice',protocol:'openai-chat',supportsImageInput:false};
- const model={id:'previous-visual-choice',protocol:'openai-chat'};
- const raw=Buffer.from(JSON.stringify({model:model.id,choices:[{
- index:0,message:{role:'assistant',content:'已核对首屏原图。'},finish_reason:'stop',
- }]})).toString('base64');
- await store.appendEvent({type:'provider_prepared',purpose:'whole-detail-worker',id,bindingHash:store.hash});
- const broker={
- info:async()=>({accountScope:scope,model:selected,pending:[]}),
- read:async originalId=>{
- assert.equal(originalId,id);
- return {phase:'complete',terminal:true,model,requestId,raw};
- },
- };
- const host=await DetailPiAgent.open({store,broker});
- try {
- assert.deepEqual(await host.recover(id),{phase:'complete',requestId,reposted:false,canvasWrites:0});
- } finally {await host.dispose();}
-});
-
test('the main Anthropic session serializes short cache markers through the native broker', async t => {
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
@@ -370,32 +220,6 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
}
});
-test('an original request confirmed failed can be closed without replay and followed by a new message', async () => {
- const { root, scope, store } = await setup();
- const id = randomUUID(), requestId = randomUUID();
- let phase = 'unknown', queries = 0, posts = 0;
- await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash });
- const broker = {
- info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: phase === 'unknown' ? [{ id, phase }] : [] }),
- read: async () => ({ phase, requestId }),
- recover: async original => { assert.equal(original, id); queries++; phase = 'failed'; },
- round() {
- return { id: randomUUID(), fetch: async () => {
- posts++;
- const reply = { id: 'next', model: 'qa', choices: [{ index: 0, delta: { content: '可以接着聊。' }, finish_reason: 'stop' }] };
- return new Response(`data: ${JSON.stringify(reply)}\n\ndata: [DONE]\n\n`, { headers: { 'content-type': 'text/event-stream' } });
- }, finish: async () => ({ phase: 'complete' }) };
- },
- };
- const host = await DetailPiAgent.open({ store, broker });
- try {
- assert.deepEqual(await host.recover(id), { phase: 'failed', requestId, reposted: false });
- assert.equal(queries, 1);
- assert.equal(posts, 0);
- assert.equal((await host.prompt('继续讨论已有图片')).text, '可以接着聊。');
- assert.equal(posts, 1);
- } finally { await host.dispose(); await cleanup(root); }
-});
test('handover stops the next model step locally rather than spending another call', async () => {
const { root, scope, store } = await setup(); let posts = 0, ended;
const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), round() {
@@ -404,45 +228,9 @@ test('handover stops the next model step locally rather than spending another ca
const raw=`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{tool_calls:[call]},finish_reason:'tool_calls'}]})}\n\ndata: [DONE]\n\n`;
return {id:randomUUID(),fetch:async()=>new Response(raw,{headers:{'content-type':'text/event-stream'}}),finish:async()=>({phase:'complete'})};
} };
- const canvas = { async begin() {}, async read() { return { conversationActive:true,allowed:false,writeBlocked:true,revision:1 }; },async activity(){},async requestWrite(){throw Error('用户已接手,写入未获许可');},async edit(){throw Error('must never edit');}, async end(text) { ended = text; } };
+ const canvas = { async begin() {}, async read() { return { conversationActive:true,allowed:false,writeBlocked:true,revision:1 }; },async activity(){},async requestWrite(){throw new BridgeError('用户已接手,写入未获许可','write_revoked');},async edit(){throw Error('must never edit');}, async end(text) { ended = text; } };
const host = await DetailPiAgent.open({ store, broker, canvas });
const result = await host.prompt('开始后立即接手');
- assert.match(result.text, /本机:已接手/); assert.match(ended, /停止/); assert.equal(posts, 1);
+ assert.match(result.text, /用户已接手/); assert.equal(ended,result.text); assert.equal(posts, 1);
await host.dispose(); await cleanup(root);
});
-test('original SSE restores read-only tool through SDK schema/hook pipeline, without inference', async () => {
- const { root, scope, store } = await setup(); let phase = 'unknown', posts = 0, queries = 0;
- const id = randomUUID(), answer = JSON.stringify({ toolCalls: [{ name: 'context_read', arguments: {} }] });
- await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash });
- const raw = `data: ${JSON.stringify({ id: 'qa-sse', model: 'qa', choices: [{ index: 0, delta: { content: answer }, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ id: 'qa-sse', model: 'qa', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`;
- const broker = {
- info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: phase === 'complete' ? [] : [{ id, phase }] }),
- read: async () => ({ phase, terminal: phase !== 'unknown', raw: Buffer.from(raw).toString('base64'), model: { id: 'qa', protocol: 'openai-chat' }, requestId: 'qa-request', bodyHash: 'qa' }),
- recover: async () => { queries++; phase = 'received'; }, confirm: async () => { phase = 'complete'; },
- round() { posts++; throw Error('must not post'); },
- };
- let host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
- const result = await host.recover(id, { executeReadOnly: true });
- assert.equal(result.readOnlyToolsRecovered, 1); assert.equal(result.canvasWrites, 0); assert.equal(queries, 1); assert.equal(posts, 0);
- await host.dispose();
- host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
- assert.ok(host.session.messages.some(m => m.role === 'toolResult' && m.toolName === 'context_read'));
- assert.equal((await host.recover(id)).alreadyApplied, true);
- await host.dispose(); await cleanup(root);
-});
-test('a result from another shop cannot be restored or queried into this conversation', async () => {
- const { root, scope, store } = await setup(); let reads = 0;
- const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), read: async () => { reads++; } };
- const host = await DetailPiAgent.open({ store, broker });
- await assert.rejects(host.recover(randomUUID()), /不属于当前/);
- assert.equal(reads, 0);
- await host.dispose(); await cleanup(root);
-});
-
-test('production recovery verifies the original request identity before confirming failure',async()=>{
- const requestId='confirmed-failed-review';
- const settled={phase:'failed',requestId,originalLookup:{verified:true,status:'failed',requestId}};
- assert.equal((await recoverProductionResponse({read:async()=>settled},'local',null,[])).confirmedFailure,true);
- assert.equal((await recoverProductionResponse({read:async()=>({...settled,originalLookup:{...settled.originalLookup,
- requestId:'another-request'}})},'local',null,[])).confirmedFailure,undefined);
-});
diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs
index 2af2724d..aca5b7ad 100644
--- a/apps/detail-agent-pi/test/screen-review.test.mjs
+++ b/apps/detail-agent-pi/test/screen-review.test.mjs
@@ -31,6 +31,7 @@ async function fixture(t) {
const slots=pages.map((documentId,i)=>({documentId,id:`slot-${i+1}`,fieldId:`pic-${i+1}`,selectedCandidateId:'candidate'}));
const state={revision:7,overlay:true,reads:[],referenceReads:0};
const canvas={
+ imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId,
revisions:{canvas:state.revision,creation:1},template:{contentHash:'template'},totalSlots:slots.length,slots,
productEvidence:{brief:{name:'木椅',variants:[{id:variantId,colorName:'深木色'}]}}}),
diff --git a/apps/detail-agent-pi/test/template-mapping.test.mjs b/apps/detail-agent-pi/test/template-mapping.test.mjs
index 2c37d8dd..31363cb6 100644
--- a/apps/detail-agent-pi/test/template-mapping.test.mjs
+++ b/apps/detail-agent-pi/test/template-mapping.test.mjs
@@ -26,3 +26,13 @@ test('existing single-source detail mappings still open and conflicting claims f
assert.throws(()=>normalize({...detail,source:{sha256:'b'.repeat(64),assets:[asset]}}),{status:409});
assert.throws(()=>normalize({...detail,source:{assets:[{...asset,asset_id:'D02'}]}}),{status:409});
});
+
+test('keeps declared field types when identifiers resemble another field type',()=>{
+ const raw={...detail,source:{assets:[asset]},fields:[
+ {field_id:'I01',screen_id:'S01',type:'文案',ps_location:{name:'标题',path:'首屏/标题'},ps_style:{bounds:[20,30,600,90]}},
+ {field_id:'T01',screen_id:'S01',type:'图片',ps_location:{name:'封面',path:'首屏/封面'},ps_style:{coverage_rect:[0,100,1100,900]}}
+ ]};
+ assert.deepEqual(normalize(raw).fields.map(field=>[field.field_id,field.type,field.ps_style.coverage_rect]),[
+ ['I01','文案',[20,30,600,90]],['T01','图片',[0,100,1100,900]]
+ ]);
+});
diff --git a/apps/detail-agent-pi/test/video-tools.test.mjs b/apps/detail-agent-pi/test/video-tools.test.mjs
index d37e21f0..94cca482 100644
--- a/apps/detail-agent-pi/test/video-tools.test.mjs
+++ b/apps/detail-agent-pi/test/video-tools.test.mjs
@@ -237,11 +237,16 @@ test('真实会话按视频输出或显式运行时注册,平面工具清单
const goal = outputIds => ({ variantId, workspaceId: 'qa', requestedOutputs: outputIds.map(outputId => ({ outputId, variantId })) });
async function active(options) {
const host = await DetailPiAgent.open({ store, transport, canvas, ...options });
- try { return host.session.getActiveToolNames(); }
+ try {
+ if (options.productionGoal) {
+ for (const [name] of productionOperationTools) assert.ok(host.session.getToolDefinition(name),name);
+ }
+ return host.session.getActiveToolNames();
+ }
finally { await host.dispose(); }
}
const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) });
- assert.ok(productionOperationTools.every(([name]) => plane.includes(name)));
+ assert.ok(plane.includes('plan_production'));
assert.deepEqual(plane.filter(name => names.includes(name)), []);
assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []);
for (const outputId of ['main_video', 'seeding_video']) {
diff --git a/apps/detail-agent-pi/test/whitelabel.test.mjs b/apps/detail-agent-pi/test/whitelabel.test.mjs
index 174365be..5512e0ae 100644
--- a/apps/detail-agent-pi/test/whitelabel.test.mjs
+++ b/apps/detail-agent-pi/test/whitelabel.test.mjs
@@ -3,7 +3,6 @@ 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_SCREEN_CRITERIA } from '../src/copy-image-alignment.mjs';
import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from '../src/native-tools.mjs';
const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');
@@ -12,7 +11,7 @@ const technicalBrand = /(? {
for (const file of [
'agent.mjs', 'desktop-host.mjs', 'enterprise-skill-resources.mjs', 'native-tools.mjs',
- 'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs', 'production-knowledge.mjs',
+ 'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs',
'production-operations.mjs', 'runtime-policy.mjs',
'screen-review.mjs',
]) {
@@ -26,13 +25,11 @@ test('conversation status, errors and tool guidance use product terminology', ()
test('production guidance batches determined operations and scopes screenshot review', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
- assert.match(prompt, /open_production_output、read_output_screen、await_image_slots、finish_production)单独调用/);
- assert.match(prompt, /批量采纳、批量回填文案[^。]*一次 codemode 脚本中依次 await/);
- assert.match(prompt, /native_catalog\(\{ ids: \[\.\.\.\] \}\)[^。]*后续回合复用/);
- assert.ok(prompt.includes('${NATIVE_CANVAS_QUICK_REFERENCE}'));
- assert.match(prompt, /可用 check_output_screens 并行复核实际成片,pages 从 1 编号,通过时自动登记/);
+ assert.match(prompt, /codemode 依次 await[^。]*真实回执/);
+ assert.match(prompt, /native_catalog[^。]*复用[^。]*parameterDocs/);
+ assert.doesNotMatch(prompt, /NATIVE_CANVAS_QUICK_REFERENCE|2–4 屏/);
const description = productionTools.find(([name]) => name === 'read_output_screen')?.[1];
- for (const copy of [prompt, description]) assert.match(copy, /2–4 屏[^]*释放[^。]*保留文字元数据/);
+ assert.match(description, /2–4 屏[^]*只保留最新一次查看图片/);
});
test('both conversation prompts and delegated production share the product voice rule', () => {
@@ -46,39 +43,24 @@ test('both conversation prompts and delegated production share the product voice
assert.match(agent, /不得向用户暴露底层技术或开源底座名称/);
});
-test('production review guidance covers copy, images and overlays followed by visual recheck', () => {
+test('production prompts refer to the published skill and keep screen semantics with the tool', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
- const guidance = [
- ['PRODUCTION_SYSTEM', prompt?.replace('${COPY_IMAGE_SCREEN_CRITERIA}',COPY_IMAGE_SCREEN_CRITERIA)],
- ['read_output_screen', productionTools.find(([tool]) => tool === 'read_output_screen')?.[1]],
- ];
- for (const [name, copy] of guidance) {
- assert.ok(copy, name);
- assert.match(copy, /图文一致性[^。]*材质、颜色、款式和结构[^。]*场景或功能卖点[^。]*SKU 花色[^。]*尺寸、规格、数量/, name);
- assert.match(copy, /尺寸线、虚线轮廓、引线、标注文字和装饰角标/, name);
- assert.match(copy, /整屏合成切片与 overlayLayers[^。]*错位、压字或数值不符/, name);
- assert.match(copy, /overlapsSlots[^。]*fieldId[^。]*bounds[^。]*text[^。]*mapped/, name);
- assert.match(copy, /native_call[^。]*移动、缩放、隐藏或改写叠层/, name);
- assert.match(copy, /write_copy_fields[^。]*transform_slot_image[^。]*重新生图/, name);
- assert.doesNotMatch(copy, technicalBrand, name);
- }
- const adopt = productionTools.find(([tool]) => tool === 'adopt_production_image')?.[1];
- assert.match(adopt, /放置回执|返回画布修订和覆盖该图位的模板叠层/);
- assert.match(adopt, /read_output_screen 查看整屏合成画面/);
- const review = productionTools.find(([tool]) => tool === 'check_output_screens')?.[1];
- assert.match(review, /按企业 Skill[^]*以当前画布实际屏数为准/);
- assert.match(prompt, /read_copy_fields 省略 pageId 和 fieldId 即可一次读取全页文案字段/);
- assert.match(prompt, /子代理生图和验图读取本屏实时文案[^。]*回执绑定当时的文案签名/);
- assert.match(prompt, /建议每批选 1–3 屏[^。]*write_copy_fields[^。]*delegate_image_slots[^。]*生图期间写下一批/);
- assert.match(prompt, /分派 goal[^。]*避免引用画布上尚未更新的模板原文/);
- const knowledge = productionTools.find(([name]) => name === 'read_production_knowledge')?.[1];
- assert.match(knowledge, /fileId 必须取自 knowledgeFiles/);
- assert.match(prompt, /模板对应图位的原图[^。]*本款实拍/);
- assert.match(prompt, /finish_production 提交当前画布修订[^]*scope=all 核验本轮交付/);
- assert.match(productionTools.find(([name]) => name === 'open_production_output')?.[1], /切换前保存原工程/);
- assert.match(prompt, /native_catalog[^。]*native_call/);
- assert.match(productionTools.find(([name]) => name === 'check_image_slots')?.[1], /对照当前图位关联文案核对图文一致性/);
- assert.match(source('candidate-review.mjs'), /read_production_knowledge[^。]*企业 Skill 和审稿规则/);
+ const tool = name => productionTools.find(([tool]) => tool === name)?.[1];
+ assert.match(prompt, /按需读取适用 Skill 和引用/);
+ assert.match(prompt, /验图回执绑定当时的文案签名/);
+ assert.match(prompt, /避免把模板原文当成当前卖点/);
+ assert.doesNotMatch(prompt, /overlayLayers|NATIVE_CANVAS_QUICK_REFERENCE|每批/);
+ assert.match(tool('read_output_screen'), /整屏合成画面[^]*叠层错位、压字或数值不符/);
+ assert.match(tool('read_output_screen'), /overlapsSlots.*fieldId.*bounds.*text.*mapped/);
+ assert.match(tool('read_output_screen'), /native_call.*write_copy_fields.*transform_slot_image/);
+ assert.match(tool('adopt_production_image'), /read_output_screen 查看整屏合成画面/);
+ assert.match(tool('check_output_screens'), /按企业 Skill[^]*整屏合成画面/);
+ assert.match(tool('read_copy_fields'), /全页字段[^。]*指定页面或字段/);
+ assert.match(tool('plan_production'), /固定版本的规则路径,可用 read 读取/);
+ assert.match(tool('open_production_output'), /切换前保存原工程/);
+ assert.match(tool('finish_production'), /scope=all.*核验本轮交付/);
+ assert.match(tool('check_image_slots'), /对照当前图位关联文案核对图文一致性/);
+ assert.doesNotMatch([prompt,tool('read_output_screen'),source('copy-image-alignment.mjs')].join('\n'), /桌腿|木种|SFY-CHAIR-001/);
});
test('native tooling and production share the documented canvas commands', () => {
@@ -121,14 +103,10 @@ test('native tooling and production share the documented canvas commands', () =>
assert.doesNotMatch(call.description,technicalBrand);
});
-test('the unattended objective uses the native canvas and frames the selling point', () => {
+test('the unattended objective records the intended delivery', () => {
const objective = productionObjective([{ outputId: 'detail', label: '详情图' }]);
- assert.match(objective, /详情图/);
- assert.match(objective, /小壹原生画布自动合成并导出,无需询问制作软件或合成方式/);
- assert.match(objective, /先看本款实拍和商品资料[^。]*策划卖点和文案,再以文案确定画面/);
- assert.match(objective, /模板原图与本屏卖点部位和景别一致时可参考构图/);
- assert.match(objective, /useTemplateReference: false[^。]*从本款实拍裁切对应部件/);
- assert.match(objective, /验图和整屏复核时自主核对图文一致性[^]*用原生工具修图或改字,再看屏确认/);
+ assert.match(objective, /按适用制作指引和模板制作并交付[^。]*详情图/);
+ assert.doesNotMatch(objective, /useTemplateReference|read_output_screen/);
assert.doesNotMatch(objective, technicalBrand);
});
diff --git a/apps/detail-agent-pi/test/workflow.test.mjs b/apps/detail-agent-pi/test/workflow.test.mjs
index 593e7f83..b1869bc9 100644
--- a/apps/detail-agent-pi/test/workflow.test.mjs
+++ b/apps/detail-agent-pi/test/workflow.test.mjs
@@ -353,25 +353,6 @@ test('stdio and socket adapters route only the three typed workflow actions with
assert.deepEqual(calls.map(q=>q.params.action),['pi-workflow-read','pi-workflow-navigate','pi-workflow-propose']);
});
-test('recovery can restore workflow_read but never replays navigation or review proposals',async()=>{
- for(const name of ['workflow_read','workflow_navigate','workflow_propose']){
- const x=await fixture(()=>{throw Error('recovery must never infer');});
- await x.host.dispose();
- const id=randomUUID(),args=name==='workflow_read'?{section:'overview'}:name==='workflow_navigate'?{stage:'plan'}:{version:1,intent:'plan'};
- await x.store.appendEvent({type:'provider_prepared',id,bindingHash:x.store.hash});
- let phase='received',posts=0;
- const original={id:'original-'+name,model:info.model.id,choices:[{message:{role:'assistant',content:'',tool_calls:[{id:'original-tool',type:'function',function:{name,arguments:JSON.stringify(args)}}]},finish_reason:'tool_calls'}]};
- const broker={info:async()=>({...info,pending:[]}),read:async()=>({phase,terminal:true,model:info.model,raw:Buffer.from(JSON.stringify(original)).toString('base64'),bodyHash:'original-body',requestId:'original-request'}),confirm:async()=>{phase='complete';},round(){posts++;throw Error('must never post');}};
- const host=await DetailPiAgent.open({store:x.store,broker,canvas:x.canvas,projectEvidence:evidence(x.project),documentId:7});
- try{
- const result=await host.recover(id,{executeReadOnly:true});assert.equal(result.reposted,false);assert.equal(posts,0);
- if(name==='workflow_read'){assert.equal(result.readOnlyToolsRecovered,1);assert.equal(x.native.reads.length,1);}
- else{assert.equal(result.needsToolReview,true);assert.equal(result.toolsExecuted,0);}
- assert.equal(x.native.navigations.length,0);assert.equal(x.native.proposals.length,0);assert.equal(x.native.generated,0);
- }finally{await host.dispose();await cleanup(x.root);}
- }
-});
-
test('a generated candidate keeps its receipt in the Pi transcript and the model replies', async () => {
let originalOperation;
const x = await fixture((context, round) => {
diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
index f8296297..e31a4e1a 100644
--- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
+++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
@@ -54,8 +54,6 @@ fn authorization_enabled(status: u16, config: &Value) -> R {
}
#[path = "jiansun_canvas_workspace.rs"]
mod canvas_workspace;
-#[path = "jiansun_product_layout.rs"]
-mod product_layout;
#[path = "jiansun_production_profile.rs"]
mod production_profile;
#[path = "jiansun_draft_store.rs"]
@@ -114,6 +112,32 @@ mod template_slots;
#[path = "jiansun_template_workflow.rs"]
mod template_workflow;
+fn draft_objects(project: &Path) -> PathBuf {
+ project.join("draft-objects")
+}
+
+fn load_draft(project: &Path, file: &Path) -> photocraft_format::Result {
+ photocraft_format::load_draft(file, &draft_objects(project))
+}
+
+struct PortableDraft {
+ checkpoint: Vec,
+ archive: Vec,
+}
+
+fn portable_draft(project: &Path, file: &Path, target: &Path) -> R