合入小壹 R5 最新集成基线

This commit is contained in:
WuYongJie 2026-11-28 01:03:17 +08:00
commit fc67959ec3
45 changed files with 954 additions and 2523 deletions

View File

@ -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(); }

View File

@ -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(); }

View File

@ -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: '生成候选图片',
@ -59,9 +59,10 @@ export const executionCategory = action => operationCategories[action] ?? 'ui_ac
export const activityToolLabel = name => Object.hasOwn(labels, name) ? labels[name] : '工具';
const inferencePhases = Object.freeze({
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
provider_prepared:['prepare','prepared'],
provider_started:['dispatch','running'], provider_finished:['receipt','completed'],
provider_error:['receipt','failed'], response_audit:['inspect','completed'],
provider_error:['receipt','failed'],
subagent_tools:['receipt','completed'],
usage:['usage','completed'], pi_retry:['retry','pending'],
});

View File

@ -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,
mayContinueProductionGoal } from './production-goal.mjs';
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal } 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, digest } from './store.mjs';
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,47 +62,20 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料
references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
const PRODUCTION_SYSTEM = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。
const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布的企业 Skill、商品实拍、资料和模板制作并复核。按需读取适用 Skill 和引用。由你决定工作范围内的顺序、并行和返工。
${PRODUCT_VOICE}
用 plan_production 读取本轮目标及待交付项。单独调用 open_production_output 在同一会话打开或切换到指定成品及花色,收到绑定回执后再查询 native_catalog 或操作画布。切换回执包含前一工程的保存结果、已取消的未派发图位和仍在处理的付费原请求编号。回到原成品时,可重新派发已取消的图位,并复核原请求留下的候选。打开失败时按回执处理,可重新打开或选择另一待制作成品。用户查看的页面和制作画布独立。
${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 切换工作画布。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。
按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`;
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
function imageLengthSummary(data, start = 0) {
const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
const bytes = Math.floor((data.length - start - padding) * 3 / 4);
return `[image-base64-omitted:${bytes}B]`;
}
function summarizePayloadImages(value) {
if (typeof value === 'string' && value.startsWith('data:image/')) {
const comma = value.indexOf(',');
if (comma !== -1 && value.startsWith(';base64,', comma - 7)) return imageLengthSummary(value, comma + 1);
}
if (Array.isArray(value)) return value.map(summarizePayloadImages);
if (!value || typeof value !== 'object') return value;
if ((value.type === 'image' || value.type === 'base64' && value.media_type?.startsWith('image/')) && typeof value.data === 'string') {
return {...value, data: imageLengthSummary(value.data)};
}
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, summarizePayloadImages(item)]));
}
// Both shapes are native projections of the frozen request, never the live selection.
const frozenReferences = context => Array.isArray(context?.requestScope?.references)
? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined;
// 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',
@ -129,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};
}
} });
@ -153,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,
@ -188,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('当前项目已切换或用户已接手,旧画布编辑未派发');
@ -427,176 +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) {
const archivedPayload = process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1' ? payload : summarizePayloadImages(payload);
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), archivedPayload);
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(archivedPayload),
promptCacheKeyPresent });
}
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) {
if (result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回');
} else await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) });
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;
@ -607,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});
@ -675,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||'当前制作步骤未完成');
}
@ -686,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;
@ -771,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(()=>{});
@ -802,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('原回合已结束,旧工作流读取不更新当前回合');
@ -832,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;
}
@ -877,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') {
@ -889,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);
@ -945,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) {
@ -976,20 +917,20 @@ export class DetailPiAgent {
? undefined : await (await this.productionOperations)?.unfinished?.();
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');
@ -1052,86 +993,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;

View File

@ -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)};

View File

@ -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

View File

@ -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);

View File

@ -10,26 +10,28 @@ import { executionCategory } from './activity-event.mjs';
assertPiNodeVersion(process.versions.node);
const canvasTelemetry = new Set(['pi-state', 'pi-context-usage', 'pi-ui-request', 'pi-ui-poll', 'pi-ui-cancel']);
export function observeCanvasCalls(store, call) {
return async (action, input, execution) => {
if (action === 'pi-delta' || action === 'pi-activity') return call(action,input);
const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(),
attempt:execution?.attempt ?? 1,requestId:execution?.requestId,revision:input.revision ?? store.executionScope.revision};
const category=executionCategory(action);
const record=(type,phase,status,extra)=>store.appendEvent({type,action,...identity,phase,status,...extra})
.catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name));
const startedAt = performance.now();
const record = (status, extra) => store.appendEvent({
type:'canvas_receipt', action, ...identity, phase:'receipt', status,
durationMs:Math.round(performance.now() - startedAt), ...extra,
}).catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name));
store.executionHealth.agentHeartbeat=Date.now();
await record('canvas_enqueued','enqueue','pending',{category:'ui_ack'});
let accepted;
let accepted = false;
try {
const reply=call(action,action==='pi-production-finish'?{...input,execution:{...identity,...store.executionHealth}}:input,()=>{
store.executionHealth.uiHeartbeat=Date.now();
accepted=record('canvas_accepted','accept','completed',{category:'ui_ack'})
.then(()=>record('canvas_started','execute','running',{category}));
accepted = true;
});
execution?.onEnqueued?.();
const value=await reply;
await accepted;
if (value?.conversationActive === true) store.executionHealth.uiHeartbeat=Date.now();
const binding=value?.productionCanvas;
if (binding?.documentKey) Object.assign(store.executionScope,{
@ -41,13 +43,12 @@ export function observeCanvasCalls(store, call) {
}
const status=value?.executed===false && value?.error ? 'failed' :
[value?.status,value?.phase].find(v=>typeof v==='string') ?? 'completed';
await record('canvas_receipt','receipt',status,{category,revision:value?.revision ?? identity.revision,
if (!canvasTelemetry.has(action) || status === 'failed') await record(status,{category,revision:value?.revision ?? identity.revision,
...(value?.requestId ? {requestId:value.requestId} : null)});
return value;
} catch(error) {
await accepted;
const status=error.category==='cancelled'?'cancelled':error.category==='transport_interrupted'?'unknown':'failed';
await record('canvas_receipt','receipt',status,{category:accepted?category:'ui_ack',failureCategory:error.category});
await record(status,{category:accepted?category:'ui_ack',failureCategory:error.category});
throw error;
}
};
@ -137,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,
@ -155,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);
@ -172,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,
@ -181,8 +180,6 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
store.executionHealth={agentHeartbeat:Date.now()};
heartbeat=setInterval(()=>{
store.executionHealth.agentHeartbeat=Date.now();
void store.appendEvent({type:'agent_heartbeat',phase:'heartbeat',status:'running',category:'ui_ack'})
.catch(error=>console.warn('小壹心跳事件写入失败',error.code ?? error.name));
},15_000);
heartbeat.unref();
const canvas = new StdioCanvas(observeCanvasCalls(store,call), config.documentId);
@ -198,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) {
@ -253,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);

View File

@ -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;

View File

@ -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,
};
}

View File

@ -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 }); }
}

View File

@ -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};
}

View File

@ -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 { 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 };
@ -112,14 +127,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 打开本轮工作画布');
}

View File

@ -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<body.length?nextOffset:null};
}
if (!files.length) return {files, tools:[], guidance};
return {files, guidance, tools:[{
name:'read_production_knowledge', label:'读取制作规则',
description:'读取当前阶段知识文件的固定版本,可用 nextOffset 继续读取。'+knowledgeFileIdInstruction,
parameters:Type.Object({
fileId:Type.String({minLength:1,maxLength:500}),
offset:Type.Optional(Type.Integer({minimum:0})),
},{additionalProperties:false}),
execute:async (_id,{fileId,offset=0},signal)=>{
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&&sections.length>1
? sections.filter(section=>headings.test(section.split('\n',1)[0])).join('\n')
: text;
return selected.trim().slice(0,limit)||undefined;
}

View File

@ -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,7 +45,6 @@ const recoveryNotices={
expired:'原请求结果已过期',
not_executed:'原操作已确认未执行',
};
const MAX_SLOT_GENERATIONS=4;
const expiryFields=receipt=>receipt?.resultExpiry?
{requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
function rememberImageExpiry(item,candidateId,receipt){
@ -74,14 +76,13 @@ const imagePromptGuidance=COPY_IMAGE_PROMPT_GUIDANCE;
const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:optional(text)};
export const productionOperationTools = [
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及待交付项。用 plan_production 获取输出和花色。收到绑定回执后再操作画布。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。pictures 中的 copyReady 表示关联字段没有待写文案。调用图位工具时优先使用 pictures 中的 fieldId。',obj({slotIds:optional(ids)})],
['read_production_knowledge','读取当前阶段固定版本的制作规则,按回执的 nextOffset 翻页。'+knowledgeFileIdInstruction,obj({fileId:text,offset:optional(page)})],
['read_copy_fields','省略 pageId 和 fieldId 可一次读取全页文案字段、当前文字及修订号。需要模板样稿与发布要求时,指定 pageId 或 fieldId 读取对应范围。',obj({
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回新画布绑定、保存结果、已取消的未派发图位和仍在处理的付费原请求。用 plan_production 获取输出和花色。收到绑定回执后再操作画布。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({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','查看当前图位的同款实拍和模板构图。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
@ -89,8 +90,8 @@ export const productionOperationTools = [
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({slotId:slotRef,...productImageArgs})],
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移同图位或跨图位候选及本款实拍,返回新候选和像素清晰度指标。',obj({slotId:slotRef,...transformImageArgs})],
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({slotId:slotRef,...preparationArgs})],
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。'+DRAW_LIMIT_GUIDANCE,obj(dispatchArgs)],
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj(dispatchArgs)],
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及关联的待写文案字段。',obj({
jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
})],
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已经返回结果未知的原请求用 reconcile_image_slots 核查。',obj({slotIds:optional(ids)})],
@ -107,7 +108,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({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({
@ -327,11 +328,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,{maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS,
export async function openProductionOperations(host,{maxActiveDelegates=6,
maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000,
tailWatchClock}={}) {
if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数');
if(!Number.isSafeInteger(maxGenerationAttempts)||maxGenerationAttempts<1)throw RangeError('图位生图上限必须为正整数');
if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数');
const {canvas,store,productionGoal:{outputId,variantId}}=host;
const {plan:initialPlan,slots}=await loadSlots(canvas,outputId);
@ -340,6 +340,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const byId=new Map(slots.map(slot=>[slot.id,slot]));
const byField=Map.groupBy(slots,slot=>slot.fieldId);
const binding=JSON.stringify([plan.template.contentHash,variantId]);
const 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();
@ -353,10 +356,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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);
@ -379,14 +378,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
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();
@ -474,7 +465,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const slotDrawStatus=slot=>drawStatuses([slot]).get(slot.id);
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 canvas.workflowRead({section:'overview',outputId});
@ -696,7 +687,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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}});
const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:host.productionSkills?.sources??[]}});
return {...receipt,operationId:request.operationId};
};
const preparedRequest=(requestId,slot)=>{
@ -887,7 +878,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
try{
const liveScreenCopy=await liveSlotCopy(slot);
const {referenceCount,...review}=await reviewProductionCandidate({canvas,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};
@ -930,7 +921,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
},
screenReviewRevisions,
async unfinished(){return unfinished((await outstanding()).originals);},
async plan_production({slotIds}={}){
async plan_production({slotIds,includeKnowledge=false}={}){
await current({refresh:true});
recordProductionInputs(repository,plan,slots);
const {requested,matched,unmatched}=readSelection(slotIds);
@ -944,22 +935,20 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
return {id,fieldId,label,...statuses.get(id),copyReady:!pendingCopy.get(id)?.length,
...(requested.size?{productionRule,requirements,sourcePolicy}:null)};
});
const {production,...template}=plan.template;
const {production,skillSources,resourceSetId,...template}=plan.template;
return {outputId,variantId,template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}},
pictures,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs,
pictures,...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
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()=>{
@ -974,37 +963,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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){
await delay(150,undefined,{signal});
signal?.throwIfAborted();
if(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);
@ -1012,7 +973,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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??={};
@ -1159,14 +1119,11 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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=>{
@ -1350,7 +1307,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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);
@ -1421,7 +1377,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
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 operations.record_screen_check({page:page-1,revision,issues:[]},activeSignal,job.inputSignature);
@ -1473,15 +1429,11 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
});
},
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;

View File

@ -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);
}

View File

@ -218,6 +218,13 @@ export class ProjectRepository {
readVersion(kind, id, revision) {
return this.#open(db => {
if (kind === 'prompt') {
const request = this.#readRequest(db, id);
if (request && String(request.revision) === String(revision)) {
const { prompt, promptHash } = request.prepared.spec;
return { slotId:request.slotId, prompt, promptHash };
}
}
const row = db.prepare(`SELECT value_json FROM project_versions WHERE ${scopeWhere} AND kind = ?
AND record_id = ? AND revision = ?`).get(...this.scope, kind, id, String(revision));
return row ? JSON.parse(row.value_json) : null;
@ -225,7 +232,7 @@ export class ProjectRepository {
}
#saveImageRequest(db, receipt, policy, candidateSetId) {
const { requestId, operationId = requestId, slotId, requestSpecHash, revision, spec } = receipt;
const { requestId, operationId = requestId, slotId, requestSpecHash, revision } = receipt;
if (policy || candidateSetId) {
const original = this.#readRequest(db, requestId);
let candidateSet = original?.prepared.candidateSet;
@ -244,13 +251,12 @@ export class ProjectRepository {
}
receipt = { ...receipt, candidateSet };
}
this.#saveVersion(db, 'prompt', requestId, revision, { slotId, prompt: spec.prompt, promptHash: spec.promptHash });
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('生图请求内容已变化,请重新准备');
if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备新版本');
return saved;
}

View File

@ -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('原请求不属于当前店铺/品类会话,未查询或恢复');
}

View File

@ -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;

View File

@ -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。

View File

@ -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 {

View File

@ -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'}});

View File

@ -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}});
@ -134,7 +132,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='加厚桌腿';
@ -191,18 +189,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'}]});

View File

@ -18,7 +18,7 @@ import { BridgeError } from '../src/bridge-error.mjs';
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
const tick = () => new Promise(resolve => setImmediate(resolve));
test('canvas observations join enqueue, acceptance and execution without transferring the viewer identity',async()=>{
test('canvas observations save a single receipt and keep routine telemetry in memory',async()=>{
const records=[];
const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}};
const executionHealth={};
@ -32,12 +32,14 @@ test('canvas observations join enqueue, acceptance and execution without transfe
});
const result=call('pi-detail-copy-apply',{operationId:'copy-1',revision:7},{onEnqueued:enqueued.resolve});
await enqueued.promise;
assert.ok(records.every(event=>event.phase!=='receipt'));
assert.equal(records.length,0);
reply.resolve();
await result;
await call('pi-state',{});
await call('pi-context-usage',{});
await call('pi-ui-poll',{});
assert.deepEqual(records.map(event=>[event.category,event.phase,event.status,event.revision]),[
['ui_ack','enqueue','pending',7],['ui_ack','accept','completed',7],
['canvas_write','execute','running',7],['canvas_write','receipt','completed',8],
['canvas_write','receipt','completed',8],
]);
for(const event of records){
assert.equal(event.projectId,'project');
@ -51,8 +53,9 @@ test('canvas observations join enqueue, acceptance and execution without transfe
assert.equal(event.jobProgress,null);
assert.equal(event.recentDurableCommit,null);
}
assert.equal(records[0].uiHeartbeat,null);
assert.ok(Number.isFinite(records[1].uiHeartbeat));
assert.ok(Number.isFinite(records[0].uiHeartbeat));
assert.ok(records[0].durationMs >= 0);
assert.equal(executionScope.revision,8);
});
test('a retried canvas read keeps its operation ID and records the next attempt',async()=>{

View File

@ -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);
});

View File

@ -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 () => {

View File

@ -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(){},
@ -405,9 +389,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 +427,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 +450,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 +460,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 +505,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 +576,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 {
@ -768,9 +776,10 @@ test('the model receives prior images and original tool receipts through Pi', as
} finally {await x.close();}
});
test('main request archives summarize image bytes by default and support raw payload opt-in',async t=>{
test('main requests keep their original identity without saving a copy of the request body',async t=>{
const setting='XIAOYI_DUMP_RAW_PAYLOADS';
const previous=process.env[setting];
delete process.env[setting];
t.after(()=>{if(previous===undefined)delete process.env[setting];else process.env[setting]=previous;});
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
const url=`data:image/png;base64,${image}`;
@ -778,24 +787,24 @@ test('main request archives summarize image bytes by default and support raw pay
t.after(x.close);
const readImageUrl=payload=>payload.messages.flatMap(row=>Array.isArray(row.content)?row.content:[])
.find(part=>part.type==='image_url')?.image_url.url;
for(const raw of [false,true]){
if(raw)process.env[setting]='1';else delete process.env[setting];
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
assert.equal(readImageUrl(x.requests.at(-1)),url);
const stored=await fs.readFile(path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json'),'utf8');
assert.equal(readImageUrl(JSON.parse(stored)),raw?url:`[image-base64-omitted:${Buffer.from(image,'base64').length}B]`);
assert.equal(stored.includes(image),raw);
}
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
assert.equal(readImageUrl(x.requests.at(-1)),url);
await assert.rejects(fs.access(path.join(x.store.dir,'payloads')), {code:'ENOENT'});
const journal=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');
assert.equal(journal.includes(image),false);
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==='serialized_request');
const requests=events.filter(event=>event.type==='provider_started');
assert.deepEqual(requests.map(event=>event.id),x.ids);
for(const event of requests){
assert.match(event.bodyHash,/^[a-f0-9]{64}$/u);
assert.ok(event.keys.includes('messages'));
assert.ok(Array.isArray(event.tools));
}
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('继续核对');
const debugFile=path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json');
const archived=JSON.parse(await fs.readFile(debugFile,'utf8'));
assert.equal(readImageUrl(archived),url);
assert.equal(Object.hasOwn(archived,'headers'),false);
});
test('a worker can change course after many identical calls without terminating',async t=>{
@ -937,12 +946,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(){}}});
@ -951,7 +961,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();}
@ -991,8 +1002,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}}),
@ -1016,13 +1028,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);

View File

@ -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() });
@ -166,7 +165,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 +224,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'));
@ -307,7 +291,7 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
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 +300,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 +355,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));

View File

@ -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,

View File

@ -6,9 +6,10 @@ 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, mayContinueProductionGoal } from '../src/production-goal.mjs';
import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs';
import { cleanup } from './cleanup.mjs';
import { bindRecovery } from '../src/desktop-host.mjs';
import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs';
import { productionStore } from './production-store-fixture.mjs';
function imageBridge(host,dispatch,id=()=>randomUUID()) {
@ -297,8 +298,9 @@ for(const stop of ['abort','close','switch'])test(`${stop} stops queued lookups
assert.equal(ledger.read().items.active.state,'unknown');
});
const drawStatus=(attempts,max=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-'));
@ -527,7 +529,7 @@ test('switch hands off original requests and cancels queued work without waiting
await closeProductionTurn(host);
});
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';
@ -548,8 +550,11 @@ 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',{});
@ -559,9 +564,9 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'unknown',
pendingGenerations:{[original.candidateId]:original}}}});
host.productionOperations=null;
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});
@ -574,8 +579,7 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
review:{candidateId:'rejected-image',decision:'revise',reason:'主体构图需要调整'}}}});
host.productionOperations=null;
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);
});
@ -602,7 +606,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,
@ -610,7 +613,6 @@ test('deferral records a hard blocker even when the production operations cannot
assert.equal(host.productionOperations,null);
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=>{
@ -652,18 +654,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=>{
@ -1107,7 +1107,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');
@ -1330,7 +1329,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]};
@ -1416,19 +1415,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,'用户手改');
@ -1756,7 +1754,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;
@ -1774,21 +1772,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++;
@ -1800,19 +1801,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);
@ -1873,9 +1895,9 @@ 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));
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:'同款侧面'});
@ -1883,7 +1905,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:'同款低机位'});
@ -1892,28 +1914,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.productionOperations=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();
});

View File

@ -115,12 +115,18 @@ test('P01 local facts, document evidence and delivery reopen without a collabora
});
test('P02 stores the exact complete prompt and rejects changes at the same revision', async t => {
const { open, repo } = await fixture(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);
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 });
try {
assert.equal(db.prepare("SELECT count(*) AS count FROM project_versions WHERE kind = 'prompt'").get().count, 0);
} finally {
db.close();
}
assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/);
});
@ -331,25 +337,6 @@ 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,保留产品结构。' });

View File

@ -1,3 +1,4 @@
import { BridgeError } from '../src/bridge-error.mjs';
import { productionExportReceipt } from './production-store-fixture.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
@ -7,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 () => {
@ -25,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));
@ -181,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));
@ -369,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() {
@ -403,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);
});

View File

@ -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']) {

View File

@ -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 = /(?<![A-Za-z0-9_])(?:Pi(?: Agent)?|PhotoCraft)(?![A-Za-z0
test('conversation status, errors and tool guidance use product terminology', () => {
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);
});

View File

@ -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) => {

View File

@ -188,7 +188,9 @@ fn identifier(s: &str) -> R<&str> {
fn read_json(path: &Path) -> R<Value> {
let mut bytes = Vec::new();
fs::File::open(path).map_err(|error| {
log::warn!("local project record open failed: {}: {error}", path.display());
if error.kind() != std::io::ErrorKind::NotFound {
log::warn!("local project record open failed: {}: {error}", path.display());
}
"本机记录无法读取,请保留文件"
})?.take(2_000_001).read_to_end(&mut bytes).map_err(|_| "本机记录读取中断,请保留文件")?;
if bytes.len() > 2_000_000 {
@ -1120,6 +1122,19 @@ impl Backend {
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "图片保存失败")?;
Ok(json!({"doc":id,"path":path.to_string_lossy(),"reference":reference}))
}
fn serialize_draft(&self, doc: &Document) -> R<Vec<u8>> {
self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")?
.get_or_insert_with(|| {
let mut writer = photocraft_format::PcraftWriter::new();
// Reuse the large compressed PSD blocks across consecutive draft saves.
writer.set_compressed_cache_budget(2304 << 20);
writer
})
.save_zip(doc, &Default::default())
.map(|(bytes, _)| bytes)
.map_err(|_| "原生项目序列化失败,旧草稿已保留".into())
}
fn save_product_view(&self, doc: &Document) -> R<Value> {
self.ensure_owner(doc.id.0)?;
let dir = self.project_dir(doc.id.0)?;
@ -1127,7 +1142,7 @@ impl Backend {
if let Some((first, last)) = missing.first().zip(missing.last()) {
return Err(format!("画布缺少 {first} 至 {last} 的原稿图层,已保留上一份编辑稿"));
}
let bytes = photocraft_format::save_to_bytes(doc, &Default::default()).map_err(|_| "当前输出序列化失败,旧草稿已保留")?;
let bytes = self.serialize_draft(doc)?;
let _guard = sync::context_guard();
self.ensure_owner(doc.id.0)?;
original_project_present(&dir)?;
@ -1166,15 +1181,7 @@ impl Backend {
self.last_saved.insert(doc.id.0, saved_identity.clone());
} else {
let serialize_started = Instant::now();
let (bytes, _) = self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")?
.get_or_insert_with(|| {
let mut writer = photocraft_format::PcraftWriter::new();
// A single large PSD linked-object block can fill most of a local draft.
// Keep its compressed allocation across consecutive document revisions.
writer.set_compressed_cache_budget(2304 << 20);
writer
})
.save_zip(&doc, &Default::default()).map_err(|_| "原生项目序列化失败,旧草稿已保留")?;
let bytes = self.serialize_draft(&doc)?;
let write_started = Instant::now();
let workspace_saved = canvas_workspace::exists(&dir)
&& canvas_workspace::save_edited_output(&dir, &doc, &bytes)?;
@ -1288,12 +1295,6 @@ impl Backend {
if checkpoint.is_file() {
v["productionRun"] = read_json(&checkpoint)?;
}
let pending = pi::unresolved(&self.dir().join("pi-validation").join(project).join("requests"))?;
if !pending.is_empty() {
v["unknown"] = json!(true);
v["unknownKind"] = json!("pi");
v["piPending"] = json!(pending);
}
if dir.join("agent-binding.json").exists() {
v["agentRule"] = read_json(&dir.join("agent-binding.json"))?;
}
@ -2133,8 +2134,6 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
}
} else if method.starts_with("slot-")
|| method == "agent"
|| method == "pi-recover"
|| method == "pi-review"
|| method == "recover"
|| method == "image-recover"
|| matches!(method.as_str(), "creation-facts" | "creation-points" | "creation-plan" | "creation-generate" | "creation-recover")
@ -2161,8 +2160,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
} else if method == "image-recover" {
task_backend.image_job(None, &input, true, &task_events, &task_ctx)
} else {
if matches!(method.as_str(), "agent" | "pi-recover" | "pi-review") {
pi_runtime::run(&mut task_backend, &input, &method, &task_events, &task_ctx)
if method == "agent" {
pi_runtime::run(&mut task_backend, &input, &task_events, &task_ctx)
} else {
task_backend.agent(&input, recover, &task_events, &task_ctx)
}

View File

@ -1431,7 +1431,7 @@ fn check_image_context(dir: &Path, except: Option<&Value>, batch: Option<&Value>
}
fn pending(dir: &Path, state: &Value, creation: &Value, except: Option<&Value>, batch: Option<&Value>) -> R<bool> {
let legacy = if dir.join("template-slots.json").exists() { template_slots::load(dir)? } else { json!({"slots":{}}) };
if template_workflow::other_pending(dir, creation, &legacy, except.or(batch))? {
if template_workflow::other_local_pending(dir, creation, &legacy, except.or(batch))? {
return Ok(true);
}
local_pending(dir, state, except, batch)
@ -3022,11 +3022,9 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>) -> R<Value> {
let other_local = template_workflow::other_local_pending(dir, &current, &legacy, None)?
|| !creation::pending_text_tasks(dir)?.is_empty();
let image_pending: Vec<_> = history.iter().filter(|record| !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))).collect();
let pi = template_workflow::pending_pi(dir)?;
let pending = other_local || !image_pending.is_empty() || !pi.is_empty();
let pending = other_local || !image_pending.is_empty();
let scoped = pending && !other_local
&& image_pending.iter().all(|record| product_slot_binding(&state, &record["binding"]))
&& pi.iter().all(super::pi::scoped_production_request);
&& image_pending.iter().all(|record| product_slot_binding(&state, &record["binding"]));
(pending, scoped, image_pending.iter().map(|record| &record["id"]).collect::<Vec<_>>())
};
let ready = current["brief"] == state["brief"];

View File

@ -455,11 +455,6 @@ impl Backend {
if old.exists() && matches!(read_json(&old)?["phase"].as_str(), Some("dispatched" | "unknown")) {
return Err("原对话请求待核查,未提交新任务".into());
}
if let Some(project) = self.locations.get(&doc)
&& !pi::unresolved(&self.dir().join("pi-validation").join(project).join("requests"))?.is_empty()
{
return Err("Agent原请求待核查,未提交新任务".into());
}
Ok(())
}
pub(super) fn slot_image_guard(&self, doc: u64, dir: &Path) -> R<()> {

View File

@ -209,6 +209,28 @@ fn reference_png(name: &str, bytes: &[u8]) -> R<Vec<u8>> {
// Same bounded RGBA conversion and metadata removal as ordinary references.
png(&rendered.bytes)
}
fn read_staged_image(path: &Path) -> R<Option<Vec<u8>>> {
let file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(_) => return Err("原结果读取失败".into()),
};
let mut bytes = Vec::new();
file.take(IMAGE_BYTES + 1).read_to_end(&mut bytes).map_err(|_| "原结果读取失败")?;
Ok(Some(bytes))
}
fn remove_settled_response(dir: &Path, task: &Value) {
if matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired")) {
for name in ["response-image.bin", "response.json"] {
let file = dir.join(name);
if let Err(error) = fs::remove_file(&file) && error.kind() != std::io::ErrorKind::NotFound {
log::warn!("temporary image response cleanup failed: {}: {error}", file.display());
}
}
}
}
pub(super) fn job_save(dir: &Path, t: &Value) -> R<()> {
let _guard = sync::context_guard();
job_save_locked(dir, t, false)
@ -952,8 +974,12 @@ impl Backend {
};
let result = (|| -> R<()> {
let raw_file = taskdir.join("response.json");
let mut deferred_result_ready = false;
let mut raw = if raw_file.exists() {
let image_file = taskdir.join("response-image.bin");
let saved_image = read_staged_image(&image_file)?;
let mut deferred_result_ready = saved_image.is_some();
let mut raw = if saved_image.is_some() {
Value::Null
} else if raw_file.exists() {
let mut b = Vec::new();
fs::File::open(&raw_file).map_err(|_| "原结果读取失败")?.take(RESPONSE_BYTES + 1).read_to_end(&mut b).map_err(|_| "原结果读取失败")?;
if b.len() as u64 > RESPONSE_BYTES {
@ -1140,39 +1166,49 @@ impl Backend {
if raw["model"].is_string() && raw["model"] != t["modelId"] {
return Err("原结果与任务模型不一致,未应用".into());
}
check()?;
let mut safe_response = raw.clone();
transfer::redact(&mut safe_response);
job_bytes(&dir, &raw_file, &serde_json::to_vec(&safe_response).map_err(|_| "原响应保存失败")?, check).map_err(|_| "原结果保存失败,请保留原请求号")?;
let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?;
let out = &outputs[0];
progress("正在下载并检查图片…", false);
let bytes = if let Some(b) = out["b64_json"].as_str() {
if b.len() > 28 * 1024 * 1024 {
return Err("图片超过20MiB限制".into());
}
STANDARD.decode(b).map_err(|_| "原图片编码无效")?
let bytes = if let Some(bytes) = saved_image {
bytes
} else {
let url = asset_url(out["url"].as_str().ok_or("原响应没有可下载的图片")?)?;
self.image_validate(deadline)?;
check()?;
let r = self
.http
.get(url)
.bearer_auth(key)
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
.send()
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
if r.status() == reqwest::StatusCode::GONE {
retain_result_expiry(&mut t, "image-asset");
return Ok(());
let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?;
let out = &outputs[0];
if let Some(b) = out["b64_json"].as_str() {
if b.len() > 28 * 1024 * 1024 {
return Err("图片超过20MiB限制".into());
}
let bytes = STANDARD.decode(b).map_err(|_| "原图片编码无效")?;
if bytes.len() as u64 > IMAGE_BYTES {
return Err("图片超过20MiB限制".into());
}
job_bytes(&dir, &image_file, &bytes, check).map_err(|_| "原结果保存失败,请保留原请求号")?;
bytes
} else {
let raw_url = out["url"].as_str().ok_or("原响应没有可下载的图片")?;
let url = asset_url(raw_url)?;
if !raw_file.exists() {
job_json(&dir, &raw_file, &json!({"data":[{"url":raw_url}]}), check)
.map_err(|_| "原结果保存失败,请保留原请求号")?;
}
self.image_validate(deadline)?;
check()?;
let r = self
.http
.get(url)
.bearer_auth(key)
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
.send()
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
if r.status() == reqwest::StatusCode::GONE {
retain_result_expiry(&mut t, "image-asset");
return Ok(());
}
if !r.status().is_success() {
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
}
let mut b = Vec::new();
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| "图片下载中断")?;
b
}
if !r.status().is_success() {
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
}
let mut b = Vec::new();
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| "图片下载中断")?;
b
};
if bytes.len() as u64 > IMAGE_BYTES {
return Err("图片超过20MiB限制".into());
@ -1212,6 +1248,7 @@ impl Backend {
// Concurrent late GETs may have settled a stronger terminal outcome.
// Report the durable original journal, never the discarded stale copy.
t = read_json(&taskdir.join("task.json"))?;
remove_settled_response(&taskdir, &t);
Ok(public(&t, id, &self.auth["account"], &self.origin))
}
pub(super) fn image_applied(&self, input: &Value) -> R<Value> {
@ -1245,6 +1282,38 @@ impl Backend {
mod tests {
use super::*;
#[test]
fn response_is_recoverable_until_the_original_request_is_settled() {
let fixture = canvas_post_fixture();
let mut task = fixture.task.clone();
let file = image_request_file(&fixture.dir, task["id"].as_str().unwrap()).unwrap();
let job = file.parent().unwrap();
let response = job.join("response-image.bin");
let request_id = Uuid::new_v4().to_string();
task["requestId"] = json!(request_id);
task["phase"] = json!("unknown");
job_save(&fixture.dir, &task).unwrap();
fs::write(&response, b"original image bytes").unwrap();
let mut reopened = read_json(&file).unwrap();
remove_settled_response(job, &reopened);
assert_eq!(read_staged_image(&response).unwrap().unwrap(), b"original image bytes");
assert_eq!(reopened["requestId"], request_id);
let artifact = job.join("generated.png");
fs::write(&artifact, b"fixture image").unwrap();
reopened["artifact"] = json!(artifact);
reopened["phase"] = json!("complete");
job_save(&fixture.dir, &reopened).unwrap();
let durable = read_json(&file).unwrap();
remove_settled_response(job, &durable);
assert_eq!(read_staged_image(&response).unwrap(), None);
assert!(artifact.is_file());
let receipt = settled_recovery(&read_json(&file).unwrap(), 1, &json!({"id":"local"}), "local").unwrap();
assert_eq!(receipt["requestId"], request_id);
assert_eq!(receipt["phase"], "complete");
}
#[test]
fn prepared_image_request_round_trips_and_freezes_exact_transport_inputs() {
let fixture = canvas_post_fixture();

File diff suppressed because it is too large Load Diff

View File

@ -68,10 +68,8 @@ fn original_rule(dir: &Path) -> R<Option<Value>> {
let old = read_json(&file)?;
Ok(Some(rule_cache::package(old["id"].as_str().ok_or("项目规则编号无效")?, &old, None)?))
}
fn can_change_rule(b: &Backend, doc: u64, dir: &Path) -> R<()> {
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?;
if !super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))?.is_empty()
|| super::creation::unresolved(dir)?
fn can_change_rule(dir: &Path) -> R<()> {
if super::creation::unresolved(dir)?
|| super::images::pending(dir)?
|| !super::projects::creation_barriers(dir)?.is_empty()
{
@ -91,7 +89,7 @@ fn automatic_rule(b: &Backend, doc: u64, index: &Value) -> R<(Option<Value>, Val
if let Some(saved) = original_rule(&dir)?.filter(|saved| rule_cache::matches_project(saved, brand, category)) {
// A catalogue update never rewrites an existing project's fixed snapshot.
if creation["designSnapshot"]["rules"] != saved {
can_change_rule(b, doc, &dir)?;
can_change_rule(&dir)?;
super::creation::attach_agent_rules(&dir, &saved)?;
}
return Ok((
@ -102,11 +100,11 @@ fn automatic_rule(b: &Backend, doc: u64, index: &Value) -> R<(Option<Value>, Val
let Some(item) = item else {
return Ok((None, json!({"state":"unavailable","reason":"此品牌与品类的模板待配置"})));
};
can_change_rule(b, doc, &dir)?;
can_change_rule(&dir)?;
let saved = cached_package(b, item)?;
// Download outside the project write lock; re-read the actual project before
// attaching so a late response cannot replace a newly selected product.
can_change_rule(b, doc, &dir)?;
can_change_rule(&dir)?;
super::creation::attach_agent_rules(&dir, &saved)?;
write_json(&dir.join("agent-binding.json"), &saved)?;
Ok((Some(saved.clone()), json!({"state":"ready","updateAvailable":false,"templateId":saved["id"],"contentHash":saved["contentHash"]})))
@ -143,16 +141,16 @@ fn knowledge_rule(b:&Backend,doc:u64) -> R<Option<(Option<Value>,Value)>> {
&& saved["catalog"]["bindings"][0]["template"]["id"]==selected["id"]
&& saved["catalog"]["bindings"][0]["template"]["sourceVersion"]==selected["version"]) {
if creation["designSnapshot"]["rules"]!=saved {
can_change_rule(b,doc,&dir)?;
can_change_rule(&dir)?;
super::creation::attach_agent_rules(&dir,&saved)?;
}
return Ok(Some((Some(saved.clone()),json!({"state":"ready","updateAvailable":false,"templateId":selected["id"],"contentHash":saved["contentHash"]}))));
}
can_change_rule(b,doc,&dir)?;
can_change_rule(&dir)?;
let pack=b.selected_template_pack(selected,brand,category)?;
let catalog=knowledge_catalog(&pack,&creation)?;
let saved=rule_cache::package(pack["id"].as_str().ok_or("模板编号缺失")?,&json!({"catalog":catalog,"revision":pack["contentHash"]}),None)?;
can_change_rule(b,doc,&dir)?;
can_change_rule(&dir)?;
super::creation::attach_agent_rules(&dir,&saved)?;
write_json(&dir.join("agent-binding.json"),&saved)?;
Ok(Some((Some(saved.clone()),json!({"state":"ready","updateAvailable":false,"templateId":pack["id"],"contentHash":saved["contentHash"]}))))
@ -257,7 +255,7 @@ pub(super) fn select(b: &mut Backend, input: &Value) -> R<Value> {
.filter(|s| !s.is_empty() && s.len() <= 100 && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_')))
.ok_or("规则编号无效")?;
let dir = b.project_dir(doc)?;
can_change_rule(b, doc, &dir)?;
can_change_rule(&dir)?;
let file = dir.join("agent-binding.json");
let index = cached_index(b, Some(id.into()))?;
let c = super::creation::load(&dir)?;
@ -270,7 +268,7 @@ pub(super) fn select(b: &mut Backend, input: &Value) -> R<Value> {
return Ok(json!({"doc":doc,"rule":old,"updateAvailable":rule_cache::update_available(&old,Some(item))}));
}
let saved = cached_package(b, item)?;
can_change_rule(b, doc, &dir)?;
can_change_rule(&dir)?;
super::creation::attach_agent_rules(&dir, &saved)?;
write_json(&file, &saved)?;
Ok(json!({"doc":doc,"rule":saved,"creation":super::creation::load(&dir)?}))
@ -385,25 +383,23 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var
.collect();
json!({"accountScope":scope,"project":project,"documentId":doc,"revision":c["revision"],"brief":brief,"currentVariantId":evidence_safe_text(current_variant,100),"facts":c["facts"],"sellingPoints":c["sellingPoints"],"plan":{"status":c["plan"]["status"],"screens":screens}})
}
pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
let value = match run_inner(b, input, method, events, ctx) {
pub(super) fn run(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
let value = match run_inner(b, input, events, ctx) {
Ok(value) => value,
Err(error) => {
let doc = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()).ok_or(error.clone())?;
if input["context"]["requestScope"]["productProduction"] == true {
log::warn!("local product stage stopped for document {doc}: {error}");
}
let unknown = method != "agent" && b.locations.get(&doc)
.is_some_and(|project| combined_unknown(false, super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))));
let mut reply = json!({"engine":"pi","mode":"prompt","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin,
"error":super::transfer::redact_text(&error.message),"failure":error.wire(),"unknown":unknown});
"error":super::transfer::redact_text(&error.message),"failure":error.wire(),"unknown":false});
super::transfer::redact(&mut reply);
if matches!(error.category, "auth_revoked" | "scope_changed") { reply["phase"] = json!("paused"); }
reply
}
};
let epoch = &input["context"]["requestScope"]["writeEpoch"];
let mut value = if epoch.is_u64() {
let value = if epoch.is_u64() {
let mut observed = canonical_pi_result(b, value.clone()).unwrap_or_else(|error| {
let mut value = value;
value["error"] = json!(error);
@ -414,9 +410,6 @@ pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::S
} else {
canonical_pi_result(b, value)?
};
if method == "pi-recover" && input["automaticRecover"] == true {
value["automaticRecover"] = json!(true);
}
Ok(value)
}
@ -576,10 +569,6 @@ fn allowed_canvas_action(action: &str) -> bool {
| "pi-workflow-navigate" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-workflow-poll"
| "pi-native-reconcile" | "pi-edit-reconcile" | "pi-workflow-reconcile")
}
fn combined_unknown(reported: bool, pending: R<Vec<Value>>) -> bool {
reported || pending.map_or(true, |items| !items.is_empty())
}
type CanvasReply = Result<(Value, Option<PiCanvasSnapshot>), BridgeFailure>;
fn queue_canvas_screen(
@ -616,24 +605,17 @@ fn take_late_workflow_delegations(replies: &mut Vec<mpsc::Receiver<CanvasReply>>
ready
}
fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> Result<Value, BridgeFailure> {
fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> Result<Value, BridgeFailure> {
b.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?;
let doc = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()).ok_or("请先打开项目")?;
b.ensure_owner(doc)?;
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?.clone();
let dir = b.project_dir(doc)?;
if method == "pi-recover"
&& let Some(id) = super::pi::settle_recorded_rate_limit(&b.dir().join("pi-validation").join(&project).join("requests"))? {
return Ok(json!({"engine":"pi","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin,
"mode":"recover","unknown":false,"settledOriginalIds":[id],"text":super::pi::RATE_LIMIT_MESSAGE}));
}
let product_prompt = method == "agent" && input["context"]["requestScope"]["productProduction"] == true;
let product_prompt = input["context"]["requestScope"]["productProduction"] == true;
let begin = std::time::Instant::now();
// Pi RPC validates the same account alongside model authorization before production starts.
if !product_prompt { b.validate()?; }
let saved = if matches!(method, "pi-recover" | "pi-review") {
original_rule(&dir)?
} else if let Some((saved,_))=knowledge_rule(b,doc)? {
let saved = if let Some((saved,_))=knowledge_rule(b,doc)? {
saved
} else {
let wanted = original_rule(&dir)?.and_then(|s| s["id"].as_str().map(str::to_owned));
@ -645,25 +627,12 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
let (node, script) = runtime()?;
let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?;
let profile = b.root.parent().ok_or("配置位置无效")?;
let mode = if method == "pi-recover" {
"recover"
} else if method == "pi-review" {
"review"
} else {
"prompt"
};
let production_originals = input["productionOriginals"].as_array().filter(|ids| !ids.is_empty());
let model_role=if mode=="recover" && production_originals.is_some() {
"detail".to_owned()
}else if mode=="recover" {
super::pi::unresolved(&b.dir().join("pi-validation").join(&project).join("requests"))?.first().and_then(|pending|pending["modelRole"].as_str()).unwrap_or("chat").to_owned()
}else{"chat".to_owned()};
let scope = &input["context"]["requestScope"];
let config = json!({"modelRole":model_role,"binary":binary,"profile":profile,"root":dir.join("agent"),"project":project,"scope":b.scope(),"documentId":doc,
let config = json!({"binary":binary,"profile":profile,"root":dir.join("agent"),"project":project,"scope":b.scope(),"documentId":doc,
"dispatchLease":b.access.dispatch_path(),
"ruleCatalog":saved.as_ref().map(|rule|rule["catalog"].clone()),"ruleId":saved.as_ref().map(|rule|rule["id"].clone()),
"projectEvidence":project_evidence(&super::creation::load(&dir)?,&b.scope(),&project,doc,&input["context"]["requestScope"]["variantId"]),
"mode":mode,"text":input["text"],"productionOriginals":production_originals,
"mode":"prompt","text":input["text"],
"writeEpoch":scope["writeEpoch"],"documentKey":scope["documentKey"],"revision":input["context"]["revision"],
"outputId":if scope["productProduction"] == true { scope["outputId"].as_str() }
else { Some(scope["outputId"].as_str().unwrap_or("detail")) },
@ -674,7 +643,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
"requestedOutputs":scope["requestedOutputs"],"workspaceId":scope["project"]["workspaceId"],
"productionTemplate":scope["productionTemplate"]});
let mut config = config;
if mode == "prompt" {
{
use base64::{Engine as _, engine::general_purpose::STANDARD};
let mut content = Vec::new();
for (index, reference) in input["context"]["requestScope"]["references"].as_array().into_iter().flatten().enumerate() {
@ -929,12 +898,8 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
result["doc"] = json!(doc);
result["accountId"] = b.auth["account"]["id"].clone();
result["origin"] = json!(b.origin);
result["mode"] = json!(mode);
result["mode"] = json!("prompt");
result["contextUsage"] = super::context_usage::read(b, &dir, &project);
if mode != "prompt" {
let pending = super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"));
result["unknown"] = json!(combined_unknown(result["unknown"].as_bool().unwrap_or(true), pending));
}
Ok(result)
}
fn merge_reference_identity(item: &mut Value, reference: &Value) {
@ -1056,14 +1021,6 @@ mod tests {
}
}
#[test]
fn unknown_keeps_either_original_signal_and_fails_closed_on_journal_error() {
assert!(!combined_unknown(false, Ok(vec![])));
assert!(combined_unknown(true, Ok(vec![])), "daemon uncertainty must not be cleared by an empty local listing");
assert!(combined_unknown(false, Ok(vec![json!({"phase":"unknown"})])));
assert!(combined_unknown(false, Err("journal unreadable".into())), "unreadable journals must stay unknown");
assert!(combined_unknown(true, Err("journal unreadable".into())));
}
#[test]
fn workflow_delegation_requires_the_private_parents_exact_identity() {
let original = json!({"method":"slot-append","run":"native-run","operationId":"07803e30-ab64-4e90-90c0-ec4a44518cdf",
"accountId":"account","origin":"https://example.invalid","projectLocalId":"https://example.invalid|account|project",
@ -1167,7 +1124,7 @@ mod tests {
json!({"engine":"pi","doc":doc,"accountId":backend.auth["account"]["id"],"origin":backend.origin,"unknown":false,"mode":"recover"})
}
#[test]
fn canonical_pi_terminal_receipt_rechecks_private_journals_without_a_template_revision_change() {
fn canonical_pi_receipt_allows_material_work_with_an_archived_model_request() {
let (backend, doc, local) = local_backend();
let dir = backend.project_dir(doc).unwrap();
write_json(&dir.join("context.json"), &json!({"localId":local})).unwrap();
@ -1185,14 +1142,15 @@ mod tests {
let journal = backend.dir().join("pi-validation").join(&local).join("requests/original.json");
let mut task = json!({"id":Uuid::new_v4().to_string(),"requestId":Uuid::new_v4().to_string(),"phase":"unknown"});
write_json(&journal, &task).unwrap();
let pending = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap();
assert_eq!(pending["pending"], true);
assert_eq!(pending["workflow"]["capabilities"]["imageDispatchAllowed"], false);
let before = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap();
assert_eq!(before["pending"], false);
assert_eq!(before["workflow"]["capabilities"]["imageDispatchAllowed"], true);
assert_eq!(read_json(&journal).unwrap(), task);
task["phase"] = json!("failed");
write_json(&journal, &task).unwrap();
let settled = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap();
assert_eq!(settled["projectLocalId"], local);
assert_eq!(settled["workflow"]["revision"], pending["workflow"]["revision"]);
assert_eq!(settled["workflow"]["revision"], before["workflow"]["revision"]);
assert_eq!(settled["pending"], false);
assert_eq!(settled["workflow"]["pending"], false);
assert_eq!(settled["workflow"]["capabilities"]["imageDispatchAllowed"], true);

View File

@ -371,11 +371,13 @@ mod tests {
let root = temp.path().join("internal");
fs::create_dir(&root).unwrap();
let id = Uuid::new_v4().to_string();
let doc = Document::new("演示", Size::new(60, 40), ColorMode::Rgb, SampleType::U8);
let mut doc = Document::new("演示", Size::new(60, 40), ColorMode::Rgb, SampleType::U8);
doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(vec![123; 1 << 20])));
fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap()).unwrap();
let job = root.join("image-jobs").join(Uuid::new_v4().to_string());
fs::create_dir_all(&job).unwrap();
fs::write(job.join("generated.png"), b"candidate pixels").unwrap();
fs::write(job.join("response-image.bin"), b"unsettled cache").unwrap();
write_json(&job.join("task.json"), &json!({"artifact":job.join("generated.png"),"phase":"complete"})).unwrap();
let delivery = root.join("product-exports").join("variant");
let generation = delivery.join("generations").join("generation-published");
@ -401,12 +403,14 @@ mod tests {
let reopened = photocraft_format::load_path(&restored.join("canvas.pcraft")).unwrap();
assert_eq!(reopened.name, doc.name);
assert_eq!(reopened.size, doc.size);
assert_eq!(reopened.metadata.psd_global_blocks, doc.metadata.psd_global_blocks);
let metadata = read_json(&restored.join(CONTEXT)).unwrap();
assert_eq!(metadata["composer"], context["composer"]);
assert!(metadata.get("messages").is_none());
assert_eq!(metadata["projectFile"], context["projectFile"]);
let job = restored.join(job.strip_prefix(&root).unwrap());
assert_eq!(fs::read(job.join("generated.png")).unwrap(), b"candidate pixels");
assert!(!job.join("response-image.bin").exists());
assert_eq!(read_json(&job.join("task.json")).unwrap()["artifact"], json!(job.join("generated.png")));
let exported = restored.join(generation.strip_prefix(&root).unwrap()).join("detail.pcraft");
let restored_receipt = restored.join(delivery.strip_prefix(&root).unwrap()).join("detail.json");
@ -422,7 +426,10 @@ mod tests {
let resource_folder = manifest["resources"].as_str().unwrap();
fs::rename(temp.path().join(resource_folder), keep.join(resource_folder)).unwrap();
fs::rename(file, &moved).unwrap();
assert_eq!(open(&moved, &temp.path().join("another-profile"), "guest").unwrap(), id);
let moved_projects = temp.path().join("another-profile");
assert_eq!(open(&moved, &moved_projects, "guest").unwrap(), id);
let moved_canvas = photocraft_format::load_path(&moved_projects.join(&id).join("canvas.pcraft")).unwrap();
assert_eq!(moved_canvas.metadata.psd_global_blocks, doc.metadata.psd_global_blocks);
}
#[test]

View File

@ -95,11 +95,6 @@ pub(super) fn idle(dir: &Path) -> R<()> {
if !creation_barriers(dir)?.is_empty() {
return Err("项目有待处理的生成任务或待应用结果,请先处理原任务;不能完结或删除".into());
}
if let (Some(account), Some(id)) = (dir.parent().and_then(Path::parent), dir.file_name())
&& !super::pi::unresolved(&account.join("pi-validation").join(id).join("requests"))?.is_empty()
{
return Err("项目有小壹请求待核查,请先核查原请求再删除项目".into());
}
for name in ["task.json", "image-task.json", "creation-task.json"] {
let path = dir.join(name);
if path.exists() {

View File

@ -1,5 +1,5 @@
//! Account-scoped template candidates. Every image POST remains in the existing 98k adapter.
use super::{json, Value, Document, R, hash, Path, template_slots, read_json, slot_canvas, write_json, creation, Uuid, images, pi, project_not_trashed, Backend, mpsc, Event, original_project_present, sync, Arc};
use super::{json, Value, Document, R, hash, Path, template_slots, read_json, slot_canvas, write_json, creation, Uuid, images, project_not_trashed, Backend, mpsc, Event, original_project_present, sync, Arc};
fn rev(value: &Value) -> u64 {
value["revision"].as_u64().unwrap_or(0)
@ -176,23 +176,6 @@ fn reuse_action(dir: &Path, state: &Value, input: &Value) -> R<Value> {
// no new task is reserved, dispatched, selected or applied here.
template_slots::reuse_candidate(dir, target, target_letter, source, source_letter, rev(state))
}
pub(super) fn other_pending(dir: &Path, creation: &Value, state: &Value, except: Option<&Value>) -> R<bool> {
Ok(other_local_pending(dir, creation, state, except)? || pending_pi(dir)?.iter().any(|item| {
!except.is_some_and(|binding| binding["detailBatch"] == true
&& item["detailSlot"].as_str().is_some_and(|scope|
scope.rsplit('/').next().is_some_and(|slot| binding["slotId"] != slot)))
}))
}
pub(super) fn pending_pi(dir: &Path) -> R<Vec<Value>> {
if dir.parent().and_then(Path::file_name).is_some_and(|name| name == "projects")
&& let (Some(account), Some(project)) = (dir.parent().and_then(Path::parent), dir.file_name())
{
return pi::unresolved(&account.join("pi-validation").join(project).join("requests"));
}
Ok(Vec::new())
}
pub(super) fn other_local_pending(dir: &Path, creation: &Value, state: &Value, except: Option<&Value>) -> R<bool> {
if images::pending(dir)? {
let task = read_json(&dir.join("image-task.json"))?;
@ -232,7 +215,7 @@ fn confirmed(dir: &Path, creation: &Value, state: &Value) -> bool {
&& creation["brief"]["categoryId"] == state["template"]["categoryId"]
}
fn capabilities(dir: &Path, creation: &Value, state: &Value) -> R<Value> {
let other = other_pending(dir, creation, state, None)?;
let other = other_local_pending(dir, creation, state, None)?;
let pending = other || !creation::pending_text_tasks(dir)?.is_empty();
let ready = confirmed(dir, creation, state);
let image = ready && !other && creation::slot_image_text_allowed(dir, creation, &state["template"])?;
@ -256,7 +239,7 @@ pub(super) fn validate_image_context(dir: &Path, except: Option<&Value>) -> R<()
return Err("图位原任务关联已变化,未发送请求".into());
}
}
if other_pending(dir, &creation, &state, except)? || !creation::slot_image_text_allowed(dir, &creation, &state["template"])? {
if other_local_pending(dir, &creation, &state, except)? || !creation::slot_image_text_allowed(dir, &creation, &state["template"])? {
return Err("有依赖的原请求待核查,未发送新图位请求".into());
}
Ok(())

View File

@ -409,12 +409,14 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
return Err("文案未取得当前画布写入许可,原内容保留".into());
}
let active = app.session.active().ok_or("原项目未打开")?;
let requested_revision = input["revision"].as_u64();
if match_fields {
let live = super::agent_native::guard_production_field_write(w, app, input)?;
input["revision"].as_u64().filter(|revision| *revision <= live).ok_or("请先读取本轮文字格及其修订号")?;
super::agent_native::guard_production_field_write(w, app, input)?;
requested_revision.ok_or("缺少文案修订号")?;
}
let same_revision = requested_revision == Some(active.revision);
if super::canvas_workspace::detail_write_waiting(w, app)
|| !match_fields && (active.revision != w.expected_revision || input["revision"].as_u64() != Some(active.revision))
|| !match_fields && (active.revision != w.expected_revision || !same_revision)
{
if !match_fields { w.allow_apply = false; }
return Ok(json!({"retryWrite":true,"revision":active.revision}));
@ -434,11 +436,24 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
};
let current = field["currentText"].as_str().unwrap_or_default();
if let Some(reason) = w.production_layer_rejection(&active.doc, id) {
rejected.push(json!({"layer":layer,"code":reason.code(),"reason":reason.message()}));
rejected.push(json!({"layer":layer,"code":reason.code(),"reason":reason.message(),
"currentText":current,"revision":active.revision}));
continue;
}
if (match_fields || !current.trim().is_empty()) && item["expectedText"].as_str() != Some(current) {
rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":"文字格原文与读取值不一致,保留当前内容"}));
let expected = item["expectedText"].as_str();
let matches_original = if match_fields {
expected.map_or(same_revision, |text| text == current)
} else {
current.trim().is_empty() || expected == Some(current)
};
if !matches_original {
let reason = if match_fields && expected.is_none() {
"画布修订已变化,缺少用于比对的原文"
} else {
"文字格原文与读取值不一致,保留当前内容"
};
rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":reason,
"currentText":current,"revision":active.revision}));
continue;
}
let text = item["text"].as_str().ok_or("缺少填写文字")?;
@ -1442,7 +1457,7 @@ mod tests {
}
#[test]
fn production_copy_matches_the_sampled_fields_instead_of_the_document_revision() {
fn production_copy_uses_current_revision_or_explicit_original_text() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":200,"height":300})).unwrap();
let [title, subtitle, locked] = ["原始标题", "原始副标题", "原始规格"].map(|text|
@ -1479,6 +1494,14 @@ mod tests {
}).unwrap();
let revision = app.session.active().unwrap().revision;
assert!(snapshot["revision"].as_u64().unwrap() < revision);
let stale = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
"run":run,"documentId":doc,"revision":snapshot["revision"],"matchFields":true,
"items":[{"layer":subtitle,"text":"过时的改动"}]
}), true).unwrap();
assert_eq!(stale["appliedLayers"], json!([]));
assert_eq!(stale["revision"], revision);
assert_eq!(stale["rejected"][0], json!({"layer":subtitle,"code":"layer_precondition_failed",
"reason":"画布修订已变化,缺少用于比对的原文","currentText":"原始副标题","revision":revision}));
let apply = json!({"run":run,"documentId":doc,"revision":snapshot["revision"],"matchFields":true,"items":[
{"layer":title,"text":"小壹标题","expectedText":snapshot["fields"][0]["currentText"]},
{"layer":subtitle,"text":"小壹副标题","expectedText":snapshot["fields"][1]["currentText"]},
@ -1492,10 +1515,21 @@ mod tests {
.collect::<Vec<_>>(), vec![title, locked]);
assert_eq!(receipt["rejected"][0]["code"], "layer_manually_edited");
assert_eq!(receipt["rejected"][1]["code"], "layer_newly_locked");
let fresh = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
"run":run,"documentId":doc,"revision":receipt["revision"],"matchFields":true,
"items":[{"layer":subtitle,"text":"小壹副标题二"},{"layer":title,"text":"覆盖用户标题"},
{"layer":locked,"text":"覆盖锁定规格"}]
}), true).unwrap();
assert_eq!(fresh["appliedLayers"], json!([subtitle]));
assert_eq!(fresh["revision"], revision + 2);
assert_eq!(fresh["rejected"][0]["code"], "layer_manually_edited");
assert_eq!(fresh["rejected"][0]["currentText"], "用户标题");
assert_eq!(fresh["rejected"][1]["code"], "layer_newly_locked");
assert_eq!(fresh["rejected"][1]["currentText"], "原始规格");
let read = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields",
&json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap();
assert_eq!(read["fields"][0]["currentText"], "用户标题");
assert_eq!(read["fields"][1]["currentText"], "小壹副标题");
assert_eq!(read["fields"][1]["currentText"], "小壹副标题二");
assert_eq!(read["fields"][2]["currentText"], "原始规格");
w.agent_native.cancel();
assert!(action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &apply, true).is_err());