合入小壹 P2-1 子代理改用 Pi 原生会话
This commit is contained in:
commit
a6e9aeb2a2
@ -1,7 +1,5 @@
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs';
|
||||
import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, productRequestScope, ProductionOutputLimit, ProductionRequestFailed } 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';
|
||||
@ -17,14 +15,14 @@ import { productionTools, callProductionTool, closeProductionTurn, runPiProducti
|
||||
mayContinueProductionGoal } from './production-goal.mjs';
|
||||
import { productionVideoTools } from './production-operations.mjs';
|
||||
import { COPY_IMAGE_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
|
||||
import { Agent, runToolCall } from '@earendil-works/pi-agent-core';
|
||||
import { createAgentSession, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { retryAssistantCall } from '@earendil-works/pi-ai';
|
||||
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 { 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';
|
||||
@ -345,7 +343,7 @@ export class DetailPiAgent {
|
||||
if (!['native-tools', 'structured-json'].includes(protocolMode)) throw Error('工具协议模式无效');
|
||||
if (callBudget !== undefined && (!Number.isSafeInteger(callBudget) || callBudget < 1)) throw Error('单轮模型调用预算无效');
|
||||
const host = new DetailPiAgent();
|
||||
Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, protocolMode, callBudget, turnEpoch: 0, rounds: 0, inflight: null, text: '' });
|
||||
Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, protocolMode, callBudget, turnEpoch: 0, rounds: 0, text: '' });
|
||||
try { host.releaseLock = lockfile.lockSync(store.root, { stale: 15000, update: 4000, retries: 0, onCompromised: error => { host.compromised = error; host.session?.agent.abort(); } }); }
|
||||
catch { throw Error('此项目已有本地Agent在运行,请等待当前任务结束;未发起新请求'); }
|
||||
try {
|
||||
@ -405,6 +403,12 @@ export class DetailPiAgent {
|
||||
return payload;
|
||||
};
|
||||
const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
||||
const retry = {enabled:true,maxRetries:3};
|
||||
const workers = new Map();
|
||||
const recordToolEvent = (event,activity,scope) => store.appendEvent({
|
||||
type:event.type,toolName:event.toolName,toolCallId:event.toolCallId,isError:event.isError??false,...scope,
|
||||
...(activity?{status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs}:null),
|
||||
});
|
||||
runtime.registerProvider('jiansun-native-98k', {
|
||||
api, apiKey: 'native-broker-only', baseUrl: api === 'anthropic-messages' ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1',
|
||||
models: [{
|
||||
@ -419,16 +423,20 @@ export class DetailPiAgent {
|
||||
}],
|
||||
streamSimple(model, context, options = {}) {
|
||||
const output = createAssistantMessageEventStream();
|
||||
const worker = workers.get(options.sessionId);
|
||||
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;
|
||||
let round, sentAt;
|
||||
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 = host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null;
|
||||
const liveCanvas = !worker && host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null;
|
||||
if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目');
|
||||
if (!host.compacting && (host.canvasNotificationsDetached || !host.productionGoal &&
|
||||
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 } } };
|
||||
@ -437,7 +445,7 @@ export class DetailPiAgent {
|
||||
output.push({ type: 'done', reason: 'stop', message }); output.end(message);
|
||||
return;
|
||||
}
|
||||
const completedProduction=!host.compacting&&Boolean(host.productionCompletion?.receipt);
|
||||
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 });
|
||||
@ -446,35 +454,43 @@ export class DetailPiAgent {
|
||||
output.push({ type: 'done', reason: 'stop', message }); output.end(message);
|
||||
return;
|
||||
}
|
||||
host.currentCanvas = liveCanvas?.context;
|
||||
const encoded = protocolMode === 'structured-json' && !host.compacting;
|
||||
const encoded = !worker && protocolMode === 'structured-json' && !host.compacting;
|
||||
const wireContext = encoded ? jsonToolContext(context) : 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 (!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 (!host.compacting && result.stopReason !== 'error' && result.stopReason !== 'aborted') {
|
||||
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 = (host.goalBroker ?? broker).round({inference:true});
|
||||
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: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation' });
|
||||
host.inflight = round.id;
|
||||
if (!host.compacting) requiredTool = host.requiredTool;
|
||||
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 sentAt, headersAt, firstThinkingAt, firstTextAt, firstToolAt;
|
||||
const stream = apiImpl.streamSimple(model, wireContext, { ...options, apiKey: 'native-broker-only', fetch: async (...args) => {
|
||||
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();
|
||||
await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id});
|
||||
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();
|
||||
@ -484,17 +500,20 @@ export class DetailPiAgent {
|
||||
onPayload: async payload => {
|
||||
applyOutputContract(payload);
|
||||
if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool);
|
||||
if (!encoded && api === 'openai-completions' && payload.tools?.length) {
|
||||
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.
|
||||
const archivedPayload = process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1' ? payload : summarizePayloadImages(payload);
|
||||
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), archivedPayload);
|
||||
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(archivedPayload),
|
||||
promptCacheKeyPresent:typeof payload.prompt_cache_key==='string' });
|
||||
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;
|
||||
},
|
||||
});
|
||||
@ -503,7 +522,7 @@ export class DetailPiAgent {
|
||||
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();
|
||||
// Finalize the durable journal BEFORE Pi can execute any returned tool.
|
||||
// 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);
|
||||
@ -522,11 +541,13 @@ export class DetailPiAgent {
|
||||
}
|
||||
}
|
||||
const result = await stream.result();
|
||||
const valid = finalEvent?.type === 'done' && (host.compacting
|
||||
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}),
|
||||
@ -534,11 +555,11 @@ export class DetailPiAgent {
|
||||
...(firstTextAt === undefined ? {} : {firstTextMs:firstTextAt-sentAt}),
|
||||
...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}),
|
||||
}) });
|
||||
host.inflight = ['complete', 'failed'].includes(settled.phase) ? null : round.id;
|
||||
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')};
|
||||
@ -550,14 +571,15 @@ export class DetailPiAgent {
|
||||
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: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation', ...usage });
|
||||
await store.appendEvent({ type: 'usage', id: round.id, model: model.id, purpose, ...workerFields, ...usage });
|
||||
host.productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage });
|
||||
if (!host.compacting) await host.updateContextUsage({ ...usage, id: round.id, model: model.id, at: Date.now(), source: 'provider-response' }, 'running');
|
||||
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);
|
||||
await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) });
|
||||
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('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
|
||||
@ -572,7 +594,7 @@ export class DetailPiAgent {
|
||||
} 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() };
|
||||
await store.appendEvent({ type: 'provider_error', id: round?.id, reason: message.errorMessage,
|
||||
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);
|
||||
}
|
||||
@ -596,169 +618,72 @@ export class DetailPiAgent {
|
||||
model: runtime.getModel('jiansun-native-98k', info.model.id),
|
||||
thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined,
|
||||
resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal'] : []),
|
||||
settingsManager: SettingsManager.inMemory({}), sessionManager: host.manager,
|
||||
settingsManager: SettingsManager.inMemory({retry}), sessionManager: host.manager,
|
||||
});
|
||||
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId, captions, workerSignal=productionSignal) => {
|
||||
const skills=loader.getSkills().skills;
|
||||
if (skills.length) {
|
||||
systemPrompt += formatSkillsForPrompt(skills);
|
||||
const workerSettings = SettingsManager.inMemory({retry,cacheWarming:'off',compaction:{enabled:false},enableSkillCommands:false});
|
||||
let workerResources;
|
||||
const loadWorkerResources = async () => {
|
||||
const resources = new DefaultResourceLoader({
|
||||
cwd:files.cwd, agentDir:store.dir, settingsManager:workerSettings,
|
||||
noExtensions:true, noSkills:true, noPromptTemplates:true, noContextFiles:true, noThemes:true,
|
||||
extensionFactories:[
|
||||
{name:'photocraft-image-context',factory:createImageContextPruningExtension()},
|
||||
{name:'photocraft-worker-task',factory:pi=>pi.on('before_agent_start',(_event,ctx)=>({
|
||||
systemPrompt:workers.get(ctx.sessionManager.getSessionId()).systemPrompt,
|
||||
}))},
|
||||
],
|
||||
});
|
||||
await resources.reload();
|
||||
return resources;
|
||||
};
|
||||
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId, captions, signal) => {
|
||||
const signals = [productionSignal,signal].filter(Boolean);
|
||||
const activeSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
||||
activeSignal?.throwIfAborted();
|
||||
const scoped = broker?.forDetailSlot?.(requestScope);
|
||||
if (!scoped&&!transport?.stream) throw Error('详情页模型连接未就绪');
|
||||
const enterpriseSkills = host.productionSkills?.resource.skills;
|
||||
if (enterpriseSkills?.length) {
|
||||
systemPrompt += formatSkillsForPrompt(enterpriseSkills);
|
||||
tools = [...tools,files.read('worker',requestScope)];
|
||||
}
|
||||
const model = runtime.getModel('jiansun-native-98k', info.model.id);
|
||||
let scoped = broker?.forDetailSlot?.(requestScope);
|
||||
if (!model || !scoped && !transport?.stream) throw Error('详情页模型连接未就绪');
|
||||
const taskTools=tools.filter(tool=>tool.name!=='read');
|
||||
const requiredTool = taskTools.length===1 && (requestScope==='production-strategy' ||
|
||||
taskTools[0].name==='plan_page_copy' && requestScope.startsWith('product/copy/') ||
|
||||
/^product\/(review|compare|copy-audit|strategy|strategy-audit)\//.test(requestScope)) ? taskTools[0].name : null;
|
||||
const autoOnly = productionUsesAutomaticTools(info.model);
|
||||
const toolChoice = autoOnly ? 'auto' : requiredTool ? (singleTool ? 'required' : namedTool(requiredTool)) : undefined;
|
||||
let previousToolCall, consecutiveToolCalls = 0;
|
||||
let pendingError;
|
||||
const [scopeKind, step] = requestScope.split('/');
|
||||
const workerKind = scopeKind === 'product' ? step : taskTools[0]?.name ?? 'detail';
|
||||
const agent = new Agent({
|
||||
initialState:{model,systemPrompt:systemPrompt+"\n"+PRODUCT_VOICE,tools,thinkingLevel:host.session.thinkingLevel},
|
||||
sessionId:host.manager.getSessionId()+':'+workerKind,
|
||||
streamFn:apiImpl.streamSimple,
|
||||
const resourceLoader = await (workerResources ??= loadWorkerResources());
|
||||
const sessionManager = SessionManager.inMemory(files.cwd);
|
||||
const {session:workerSession} = await createAgentSession({
|
||||
cwd:files.cwd, agentDir:store.dir, modelRuntime:runtime, model:session.model,
|
||||
thinkingLevel:session.thinkingLevel, settingsManager:workerSettings, sessionManager, resourceLoader,
|
||||
customTools:tools, tools:tools.map(tool=>tool.name),
|
||||
});
|
||||
const supervisor = ['supervisor','production-strategy','production-strategy-audit'].includes(slotId);
|
||||
let thinking = false;
|
||||
let outputMeter = new StreamOutputMeter();
|
||||
if (supervisor && host.canvas?.run) agent.subscribe(event => {
|
||||
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
|
||||
const activity = toolActivity(event, host.activityScope);
|
||||
if (activity) void host.notifyCanvas('activity', activitySummary(event),
|
||||
{...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
|
||||
}
|
||||
const type = event.type === 'message_update' ? event.assistantMessageEvent?.type : null;
|
||||
const next = type === 'thinking_start' || type === 'thinking_delta' ? true
|
||||
: type === 'thinking_end' || event.type === 'message_end' ? false : thinking;
|
||||
const meter = outputMeter.update(event, next);
|
||||
if (event.type === 'message_end') outputMeter = new StreamOutputMeter();
|
||||
if (thinking !== next || meter) {
|
||||
thinking = next;
|
||||
host.display.push({thinking, output:meter});
|
||||
const sessionId = sessionManager.getSessionId();
|
||||
const [kind,step] = requestScope.split('/');
|
||||
const worker = {slotId,requestScope,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE,
|
||||
cacheKey:host.manager.getSessionId()+':'+(kind==='product'?step:tools[0]?.name??'detail')};
|
||||
const abort = () => { void workerSession.abort(); };
|
||||
workers.set(sessionId,worker);
|
||||
activeSignal?.addEventListener('abort',abort,{once:true});
|
||||
const unsubscribe = workerSession.subscribe(event=>{
|
||||
if(event.type==='tool_execution_start'||event.type==='tool_execution_end'){
|
||||
const activity=toolActivity(event,host.activityScope||activityScope(store.identity));
|
||||
void recordToolEvent(event,activity,{slotId,requestScope})
|
||||
.catch(error=>console.warn('子代理工具事件未保存',error.code??error.name));
|
||||
}
|
||||
});
|
||||
agent.beforeToolCall=async ({toolCall})=>{
|
||||
if(workerSignal?.aborted)return {block:true,terminate:true,reason:'原制作回合已停止'};
|
||||
const repeated = toolCall.name === previousToolCall?.name && isDeepStrictEqual(toolCall.arguments,previousToolCall.arguments);
|
||||
consecutiveToolCalls = repeated ? consecutiveToolCalls + 1 : 1;
|
||||
previousToolCall = toolCall;
|
||||
if(consecutiveToolCalls>8)return {block:true,reason:'同一工具和参数已连续调用 8 次,请根据已有回执调整操作或提交当前结果'};
|
||||
};
|
||||
agent.streamFunction=(selected,context,options={})=>{
|
||||
if(transport?.stream) return transport.stream(selected,context,options);
|
||||
const output=createAssistantMessageEventStream();
|
||||
(async()=>{
|
||||
let round;
|
||||
const operationId=randomUUID();
|
||||
let attempt=0;
|
||||
try {
|
||||
const result = await retryAssistantCall(async () => {
|
||||
attempt++;
|
||||
round = undefined;
|
||||
let requestBytes, firstOutputMs, promptCacheKeyPresent;
|
||||
try {
|
||||
const camera=await host.canvas.read();
|
||||
if(camera?.conversationActive!==true||camera.writeBlocked)throw Error('用户已暂停详情页制作');
|
||||
options.signal?.throwIfAborted();
|
||||
round=scoped.round({inference:true});
|
||||
const imageCount=context.messages.reduce((count,message)=>count+
|
||||
(Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0);
|
||||
const started=Date.now();
|
||||
await store.appendEvent({type:'provider_prepared',id:round.id,requestId:round.id,operationId,attempt,
|
||||
model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount});
|
||||
let wire;
|
||||
const stream=apiImpl.streamSimple(selected,context,{...options,toolChoice,apiKey:'native-broker-only',
|
||||
onPayload:payload=>{
|
||||
promptCacheKeyPresent=typeof payload.prompt_cache_key==='string';
|
||||
return applyOutputContract(payload);
|
||||
},
|
||||
fetch:async (...args)=>{
|
||||
const body=args[1]?.body;
|
||||
if(typeof body==='string')requestBytes=Buffer.byteLength(body);
|
||||
await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,operationId,attempt,slotId});
|
||||
workerSignal?.throwIfAborted();
|
||||
const response=await round.fetch(...args);
|
||||
wire=response.clone().text().catch(()=>null);
|
||||
return response;
|
||||
}});
|
||||
let finalEvent;
|
||||
for await (const event of stream) {
|
||||
if(event.type==='done'||event.type==='error')finalEvent=event;
|
||||
else{
|
||||
if(event.type==='text_delta'||event.type==='toolcall_delta')firstOutputMs??=Date.now()-started;
|
||||
if (!options.signal?.aborted && !workerSignal?.aborted) output.push(event);
|
||||
}
|
||||
}
|
||||
const message=await stream.result();
|
||||
const valid=finalEvent?.type==='done' && ['stop','toolUse'].includes(message.stopReason);
|
||||
const receipt=await round.finish(valid,message.stopReason);
|
||||
if (broker?.authority?.error) throw broker.authority.error;
|
||||
const raw=valid&&receipt.phase==='complete'?await wire:null;
|
||||
const usage=raw?responseUsage(raw):null;
|
||||
await store.appendEvent({type:'provider_finished',id:round.id,requestId:round.id,operationId,attempt,
|
||||
slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent,
|
||||
...(options.signal?.aborted || workerSignal?.aborted ? {consumption:'discarded_after_cancel'} : null),
|
||||
...(usage?{inputTokens:usage.inputTokens,outputTokens:usage.outputTokens,cachedTokens:usage.cachedTokens}:null)});
|
||||
if(receipt.phase==='rejected'&&message.stopReason==='length')throw new ProductionOutputLimit();
|
||||
const failure=confirmedProductionFailure(receipt,round.id);
|
||||
if(failure)throw failure;
|
||||
if(!valid||receipt.phase!=='complete')throw Error(message.errorMessage ?? 'network error: inference stream did not complete');
|
||||
if(!raw)throw Error('原始模型响应尚未读完,工具未执行');
|
||||
const audit=auditResponse(raw,info.model.protocol);
|
||||
if(message.content.filter(item=>item.type==='toolCall').length!==audit.calls.length)throw Error('原模型工具调用未完整返回');
|
||||
await store.appendEvent({type:'usage',id:round.id,operationId,attempt,model:selected.id,purpose:'whole-detail-worker',slotId,...usage});
|
||||
await onEvent({type:'usage',id:round.id,model:selected.id,...usage});
|
||||
workerSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
return message;
|
||||
} catch(error) {
|
||||
if (error instanceof ProductionOutputLimit || error instanceof InvalidToolReply || options.signal?.aborted) throw error;
|
||||
return {role:'assistant',api,provider:selected.provider,model:selected.id,content:[],stopReason:'error',
|
||||
errorMessage:error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+error.message : error.message,
|
||||
timestamp:Date.now(),usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{...cost,total:0}}};
|
||||
}
|
||||
}, piRetryPolicy, options.signal, {onRetryScheduled:async(attempt,maxAttempts,delayMs)=>{
|
||||
await store.appendEvent({type:'pi_retry',id:round?.id,operationId,requestScope,slotId,attempt,maxAttempts,delayMs});
|
||||
}});
|
||||
workerSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
if (result.stopReason === 'error' || result.stopReason === 'aborted') {
|
||||
output.push({type:'error',reason:result.stopReason,error:result});
|
||||
} else output.push({type:'done',reason:result.stopReason,message:result});
|
||||
output.end(result);
|
||||
} catch (error) {
|
||||
if (round && (workerSignal?.aborted || options.signal?.aborted)) {
|
||||
await store.appendEvent({type:'provider_error',id:round.id,operationId,attempt,slotId,
|
||||
status:'cancelled',consumption:'discarded_after_cancel'});
|
||||
}
|
||||
if(error instanceof ProductionRequestPending||error instanceof ProductionRequestFailed||error instanceof ProductionOutputLimit||
|
||||
error instanceof InvalidToolReply)pendingError=error;
|
||||
const failure={role:'assistant',api,provider:selected.provider,model:selected.id,content:[],stopReason:'error',
|
||||
errorMessage:error.message,timestamp:Date.now(),usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{...cost,total:0}}};
|
||||
output.push({type:'error',reason:'error',error:failure});output.end(failure);
|
||||
}
|
||||
})();
|
||||
return output;
|
||||
};
|
||||
const abort = () => agent.abort();
|
||||
try {
|
||||
workerSignal?.throwIfAborted();
|
||||
workerSignal?.addEventListener('abort',abort,{once:true});
|
||||
const input=captions?{role:'user',timestamp:Date.now(),content:[{type:'text',text:prompt},
|
||||
...images.flatMap((image,index)=>[{type:'text',text:captions[index]},image])]}:prompt;
|
||||
await agent.prompt(input,images);
|
||||
workerSignal?.throwIfAborted();
|
||||
if(pendingError)throw pendingError;
|
||||
if(agent.state.errorMessage)throw Error(agent.state.errorMessage);
|
||||
const result=agent.state.messages.filter(message=>message.role==='assistant').at(-1);
|
||||
if(result?.stopReason==='error'||result?.stopReason==='aborted')throw Error(result.errorMessage||'当前制作步骤未完成');
|
||||
activeSignal?.throwIfAborted();
|
||||
const content = images.length ? [{type:'text',text:prompt},...images.flatMap((image,index)=>
|
||||
captions?[{type:'text',text:captions[index]},image]:[image])] : prompt;
|
||||
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==='error'||result?.stopReason==='aborted') {
|
||||
throw Error(result.errorMessage||'当前制作步骤未完成');
|
||||
}
|
||||
} finally {
|
||||
workerSignal?.removeEventListener('abort',abort);
|
||||
if(scoped)await scoped.close();
|
||||
activeSignal?.removeEventListener('abort',abort);
|
||||
unsubscribe();
|
||||
workerSession.dispose();
|
||||
workers.delete(sessionId);
|
||||
await scoped?.close();
|
||||
}
|
||||
};
|
||||
host.session = session;
|
||||
@ -848,8 +773,7 @@ export class DetailPiAgent {
|
||||
const activity = toolActivity(event, host.activityScope || activityScope(store.identity));
|
||||
if (canvas) void host.notifyCanvas('activity', activitySummary(event),
|
||||
activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
|
||||
await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false,
|
||||
...(activity ? {status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs} : null) });
|
||||
await recordToolEvent(event,activity);
|
||||
void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});
|
||||
}
|
||||
});
|
||||
@ -966,7 +890,6 @@ export class DetailPiAgent {
|
||||
}
|
||||
async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false } = {}) {
|
||||
if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求');
|
||||
if ((await this.store.get('recovered-tools.json', [])).some(t => t.phase === 'review')) 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);
|
||||
|
||||
@ -1,16 +1,15 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { productionUsesAutomaticTools, productRequestScope, ProductionRequestFailed } from './production-recovery.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { InvalidToolReply } from './response-audit.mjs';
|
||||
import { COPY_IMAGE_REVIEW_GUIDANCE, mergeReviewCopy } from './copy-image-alignment.mjs';
|
||||
import { mergeReviewCopy } from './copy-image-alignment.mjs';
|
||||
|
||||
const params = properties => Type.Object(properties,{additionalProperties:false});
|
||||
const tool = (name, description, parameters, execute) => ({
|
||||
name,label:description,description,parameters,execute:(_id,args)=>execute(args),
|
||||
});
|
||||
export const copySignature = copy=>copy.map(({field,text,claims})=>[field,...(claims??[text])])
|
||||
const copySignature = copy=>copy.map(({field,text,claims})=>[field,...(claims??[text])])
|
||||
.sort(([left],[right])=>(left??'').localeCompare(right??''));
|
||||
|
||||
const reviewChecks=['structure','color','templateStyle','composition','evidence','copyAlignment'];
|
||||
const actions=['adopt','canvas_adjust','regenerate'];
|
||||
const coordinate=Type.Integer({minimum:0,maximum:1000});
|
||||
export const canvasTransformArgs={
|
||||
@ -24,43 +23,9 @@ export const canvasTransformArgs={
|
||||
fit:Type.Optional(Type.Union([Type.Literal('cover'),Type.Literal('contain')])),
|
||||
};
|
||||
|
||||
export function readAutoAdoptionPolicy(policy) {
|
||||
if(policy==null)return null;
|
||||
const {version,candidateCount,priorityChecks=[]}=policy;
|
||||
if(typeof version!=='string'||!version.trim()||!Number.isSafeInteger(candidateCount)||candidateCount<1||
|
||||
!Array.isArray(priorityChecks)||priorityChecks.some(check=>!reviewChecks.includes(check))){
|
||||
throw Error('自动采用政策须声明版本、候选数量和有效的验图优先项');
|
||||
}
|
||||
return {version,candidateCount,priorityChecks};
|
||||
}
|
||||
|
||||
export function decideCandidateSet(policy, requests, reviews) {
|
||||
if(requests.length!==policy.candidateCount||requests.some(request=>
|
||||
!['complete','failed','retired','expired'].includes(request.state)))return;
|
||||
const completed=requests.filter(request=>request.state==='complete');
|
||||
if(completed.some(({requestId})=>!reviews?.[requestId]))return;
|
||||
const basis=completed.map(({requestId,operationId,prepared})=>{
|
||||
const review=reviews?.[requestId];
|
||||
return {
|
||||
candidateId:requestId,operationId,position:prepared.candidateSet.position,
|
||||
verdict:review.decision,checks:review.checks,reason:review.reason,original:review.original,
|
||||
};
|
||||
});
|
||||
const ranked=basis.filter(row=>row.verdict==='pass').sort((a,b)=>{
|
||||
for(const check of policy.priorityChecks){
|
||||
const difference=Number(b.checks?.[check]===true)-Number(a.checks?.[check]===true);
|
||||
if(difference)return difference;
|
||||
}
|
||||
return a.position-b.position;
|
||||
});
|
||||
const candidateId=ranked[0]?.candidateId;
|
||||
return {actor:'agent',policyVersion:policy.version,candidateId,priorityChecks:policy.priorityChecks,basis,
|
||||
reason:ranked.length===0?'all_rejected':ranked.length===1?'only_pass':'policy_priority'};
|
||||
}
|
||||
|
||||
export async function reviewProductionCandidate({
|
||||
canvas,host,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
|
||||
reviewKnowledge,refusal,onRequestFailure,liveScreenCopy,
|
||||
canvas,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
|
||||
reviewKnowledge,liveScreenCopy,
|
||||
}) {
|
||||
const input=await canvas.detailImages(slot.id,candidateId,{
|
||||
...(adopted?{adopted:true}:null),
|
||||
@ -119,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,
|
||||
copy:screenCopy,screenCopy,knowledgeFiles:reviewKnowledge.files,
|
||||
screenCopy,taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files,
|
||||
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,
|
||||
@ -127,13 +92,10 @@ export async function reviewProductionCandidate({
|
||||
const instructions=[
|
||||
'第一张是本次受审候选图框。按当前图位要求审阅,后续图像依标注用于核对同款实拍和模板构图。',
|
||||
...(adopted?['第一张取自当前画布的实际图框。']:[]),
|
||||
'原件尺寸和透明通道见 candidateFile,实际图框见 frame。查看主体是否完整清晰、透视和动作是否自然、接地与光影是否可信,注意异常留边、生成杂字、拼接痕迹及文案区域的可读性。模板有色卡、纯色衬底或透明要求时按当前图位标准检查。',
|
||||
'requirements 是当前 fieldId 的画面要求。templateContext 提供整屏目标与通用适配规则。整屏要实现的多图对应关系由各图位分别完成,交给整屏复核。',
|
||||
COPY_IMAGE_REVIEW_GUIDANCE,
|
||||
'对照关联文案 copy 和同屏上下文核对图文一致性。看清候选实际体现的材质、颜色、款式和结构,以及场景、功能、尺寸、规格、数量和 SKU 花色是否支持本图位的卖点。',
|
||||
'结构、材质、颜色或卖点证据出现实质错误时,在 mustRedo 写明位置、问题和建议。商品主体准确且仅需调整构图、裁切、朝向或偏移时,在 canvasFixes 写明建议,可选填 recommendedAction 或 canvasTransform,裁切坐标以未裁切原图为准。用 shownFields 记录可见依据,主代理根据回执决定采纳或修整。',
|
||||
'原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。',
|
||||
'用 shownSubject 描述实际画面,用 shownFields 标明与文案对应的画面依据。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。',
|
||||
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
|
||||
...(reviewKnowledge.files.length?['当前图位引用了未提供的专项标准且会影响结论时,可按 knowledgeFiles 查阅对应文件。']:[]),
|
||||
...(reviewKnowledge.files.length?['用 read_production_knowledge 获取 knowledgeFiles 中适用的企业 Skill 和审稿规则。']:[]),
|
||||
'调用 review_candidate 提交结论。',
|
||||
].join('\n');
|
||||
const images=[input.images.at(-1),...originalImages,...layoutImages];
|
||||
@ -141,29 +103,8 @@ export async function reviewProductionCandidate({
|
||||
'同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0'))),
|
||||
...layoutImages.map(()=> '模板构图参考')];
|
||||
const scope=productRequestScope('review',candidateId);
|
||||
const model=host.info?.model?.id??null;
|
||||
const automaticTools=productionUsesAutomaticTools(host.info?.model);
|
||||
if(refusal?.candidateId===candidateId&&refusal.model===model&&
|
||||
!(automaticTools&&refusal.automaticTools!==true&&refusal.httpStatus===400)){
|
||||
throw Error(refusal.reason);
|
||||
}
|
||||
const run=async(instruction)=> {
|
||||
await runAgent(slot.id,instruction,prompt,[review,...reviewKnowledge.tools],images,scope,captions,signal);
|
||||
if(!receipt)throw new InvalidToolReply('独立验图未提交结论');
|
||||
};
|
||||
try {
|
||||
await run(instructions);
|
||||
} catch(error) {
|
||||
signal?.throwIfAborted();
|
||||
if(!(error instanceof InvalidToolReply||error instanceof ProductionRequestFailed&&error.retryable&&!error.retryExhausted)){
|
||||
if(error instanceof ProductionRequestFailed&&!error.retryable){
|
||||
await onRequestFailure?.({candidateId,model,automaticTools,httpStatus:error.httpStatus,reason:error.message});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await run(error instanceof InvalidToolReply
|
||||
? instructions+'\n请调用本次提供的 review_candidate 工具提交候选号、结论和具体证据。'
|
||||
: instructions);
|
||||
}
|
||||
await runAgent(slot.id,instructions,prompt,[review,...reviewKnowledge.tools],images,scope,captions,signal);
|
||||
signal?.throwIfAborted();
|
||||
if(!receipt)throw new InvalidToolReply('独立验图未提交结论');
|
||||
return {...receipt,referenceCount,...(input.candidateFile?{original:input.candidateFile}:null)};
|
||||
}
|
||||
|
||||
@ -1,11 +1,9 @@
|
||||
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;
|
||||
const WOOD_FINISH_GUIDANCE='逐条对照商品资料及画面实际呈现的木材纹理、色泽深浅和涂装观感,核对材质、木种与颜色文案是否自洽。若资料确认深木色来自涂装,文案应客观交代木种与涂装的关系或修正矛盾描述。';
|
||||
export const COPY_IMAGE_REVIEW_GUIDANCE='先用 shownSubject 客观描述候选图框实际拍到的部位、景别或场景,再逐条对照关联与同屏实时文案,填写 checks.copyAlignment。即使同款、颜色和构图正确,若图位应证明的部位与画面主角不同,或该部位被裁切、遮挡、看不清,图文一致性应判不通过,候选应退回。'+WOOD_FINISH_GUIDANCE+'指出具体不符的文案、画面依据,并建议重做特写、裁切实拍或修正文案。同屏其他图位承担的卖点交由整屏复核。';
|
||||
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 花色相符,尺寸、规格、数量是否与画面和标注自洽。'+WOOD_FINISH_GUIDANCE;
|
||||
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;
|
||||
|
||||
|
||||
@ -137,10 +137,10 @@ 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,
|
||||
...(config.autoAdoptionPolicy?{autoAdoptionPolicy:config.autoAdoptionPolicy}:null),
|
||||
...(Number.isSafeInteger(config.productionDeadline)?{skillRunDeadline:config.productionDeadline}:null)} : undefined;
|
||||
const startedAt = performance.now();
|
||||
const abort = () => { if (host) void host.session.abort().catch(()=>{}); };
|
||||
@ -235,8 +235,8 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
} else 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 = (await broker.status()).pending;
|
||||
const reviews = (await store.get('recovered-tools.json', [])).filter(t => t.phase === 'review');
|
||||
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() };
|
||||
} catch (error) {
|
||||
@ -256,21 +256,12 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
unknown:broker?.hasUnconfirmedRequest ?? false, reposted:false};
|
||||
}
|
||||
let pending = [], unknown = false;
|
||||
if (broker) { try { pending = (await broker.status()).pending; unknown = pending.length > 0; } catch { unknown = broker.hasUnconfirmedRequest; } }
|
||||
else if (sharedBroker && sharedBroker.binary===config.binary && sharedBroker.profile===config.profile && sharedBroker.project===config.project && sharedBroker.scope===config.scope) unknown=sharedBroker.hasUnconfirmedRequest;
|
||||
if (historical && broker) {
|
||||
try { pending = (await broker.status()).pending; unknown = pending.length > 0; }
|
||||
catch { unknown = broker.hasUnconfirmedRequest; }
|
||||
}
|
||||
const failure = BridgeError.from(error).wire();
|
||||
output = { error:failure.message, failure, unknown, pending, reposted:false, contextUsage:host?.contextUsage };
|
||||
if (host && productionGoal) {
|
||||
const scope=host.goalRequestScope;
|
||||
const models=pending.filter(request=>request.modelRole==='detail'&&request.detailSlot===scope)
|
||||
.map(request=>request.id);
|
||||
if(models.length) {
|
||||
delete output.error;
|
||||
output.text='制作请求正在核查,已保留当前进度。';
|
||||
output.production={outputId:productionGoal.outputId,variantId:productionGoal.variantId,
|
||||
complete:false,stageStatus:'waiting-originals',originals:{models,images:[],goal:models[0]}};
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearInterval(heartbeat);
|
||||
signal?.removeEventListener('abort',abort);
|
||||
|
||||
@ -229,8 +229,8 @@ export class Native98kBroker {
|
||||
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 (inference && result.phase === 'unknown') return result;
|
||||
if (result.phase !== 'received') throw Error(`请求 ${id} 结果未知;不会重发`);
|
||||
return this.start('finish', { id, bodyHash: metadata.bodyHash, valid, reason });
|
||||
},
|
||||
|
||||
@ -7,16 +7,26 @@ const stageRules = {
|
||||
review: ['review', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
|
||||
};
|
||||
|
||||
export const knowledgeFileIdInstruction = 'fileId 必须取自 knowledgeFiles 列表,不能传模板编号(如 SFY-CHAIR-001)。';
|
||||
export const knowledgeReadInstruction = '优先使用 read 读取当前阶段必需的企业制作指引及其引用,也可用 read_production_knowledge 读取固定版本。'+knowledgeFileIdInstruction;
|
||||
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}));
|
||||
if (!files.length) return {files, tools:[]};
|
||||
return {files, tools:[{
|
||||
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({
|
||||
@ -27,11 +37,8 @@ export function productionKnowledge(knowledge, stage) {
|
||||
signal?.throwIfAborted();
|
||||
const document=documents.find(entry=>entry.fileId===fileId);
|
||||
if(!document)throw Error('该文件不属于当前制作阶段使用的知识资料');
|
||||
const body=document.text??await document.loadText();
|
||||
const details=await readPage(document,offset);
|
||||
signal?.throwIfAborted();
|
||||
const text=body.slice(offset,offset+6000);
|
||||
const nextOffset=offset+text.length;
|
||||
const details={fileId,revision:document.revision,text,nextOffset:nextOffset<body.length?nextOffset:null};
|
||||
return {content:[{type:'text',text:JSON.stringify(details)}],details};
|
||||
},
|
||||
}]};
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import path from 'node:path';
|
||||
import { addAbortListener } from 'node:events';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
@ -8,14 +7,14 @@ import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agen
|
||||
import { productionLedger, recordProductionInputs } from './production-repository.mjs';
|
||||
import { PresentationBatch } from './stream-presentation.mjs';
|
||||
import { loadSlots } from './production-slots.mjs';
|
||||
import { productionKnowledge, knowledgeReadInstruction, knowledgeFileIdInstruction } from './production-knowledge.mjs';
|
||||
import { productionKnowledge, knowledgeFileIdInstruction } from './production-knowledge.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { canvasTransformArgs, copySignature, decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from './candidate-review.mjs';
|
||||
import { COPY_IMAGE_PROMPT_GUIDANCE, COPY_IMAGE_SCREEN_GUIDANCE, OVERLAY_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.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 { 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, screenReviewScope } from './screen-review.mjs';
|
||||
import { reviewOutputScreen } from './screen-review.mjs';
|
||||
import { createTailWatcher } from './tail-watcher.mjs';
|
||||
|
||||
const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
@ -24,7 +23,6 @@ const ids=Type.Array(text);
|
||||
const slotRef=Type.String({minLength:1,description:'优先填写 plan_production 返回的当前画布 fieldId;字段编号重复时使用对应的完整 id。'});
|
||||
const layer=Type.Integer({minimum:1});
|
||||
const page=Type.Integer({minimum:0});
|
||||
const maxScreenReviewPages=16;
|
||||
const rev=Type.Integer({minimum:0});
|
||||
const optional=Type.Optional;
|
||||
const fit=Type.Union([Type.Literal('cover'),Type.Literal('contain')]);
|
||||
@ -57,7 +55,6 @@ function rememberImageExpiry(item,candidateId,receipt){
|
||||
}
|
||||
const preparationArgs={
|
||||
prompt:text,
|
||||
candidateSetId:optional(Type.String({description:'按自动采用政策准备同批下一张时,使用首张回执的 candidateSet.id,保持正式请求内容相同。'})),
|
||||
reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})),
|
||||
reworkCandidateId:optional(text),
|
||||
referenceIndexes:optional(Type.Array(page,{minItems:1,uniqueItems:true,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
|
||||
@ -93,10 +90,10 @@ export const productionOperationTools = [
|
||||
['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 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及关联的待写文案字段。',obj({
|
||||
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',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)})],
|
||||
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已经返回结果未知的原请求用 reconcile_image_slots 核查。',obj({slotIds:optional(ids)})],
|
||||
['review_image_slots','只读查看当前制作输出的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求、验图详细结论与提示词。',obj({slotIds:optional(Type.Array(Type.String()))})],
|
||||
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({
|
||||
slotIds:optional(Type.Array(Type.String())),
|
||||
@ -104,7 +101,7 @@ export const productionOperationTools = [
|
||||
['stage_archived_image','把已完成的候选加入当前目标图位待验,沿用其原素材任务。来源是本项目已知候选时省略 projectId,来源是另一同款项目时使用 read_archived_images 返回的 projectId。请按目标图位复核再决定是否采用。',obj({
|
||||
slotId:slotRef,projectId:optional(Type.String()),candidateId:text,
|
||||
})],
|
||||
['check_image_slots','请验图代理查看指定候选的真实画面,对照当前图位关联文案核对图文一致性,指出不符的具体卖点和画面位置。配置自动采用政策时,审核同批全部候选后自动择优回填,自动采用回执同样列出覆盖图位的模板叠层。默认先返回受理结果,可用 review_image_slots 查看结论。',obj({
|
||||
['check_image_slots','请验图代理按企业 Skill 查看指定候选的实际画面,对照当前图位关联文案核对图文一致性,返回依据与修改建议。默认先返回受理结果,可用 review_image_slots 查看结论,用 adopt_production_image 采用你选定的候选。',obj({
|
||||
wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean())})),
|
||||
})],
|
||||
['adopt_production_image','采用你选择的候选,返回画布修订和覆盖该图位的模板叠层。尺寸线、虚线、引线、文字和装饰角标的错位或数值是否匹配本款,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
|
||||
@ -113,8 +110,8 @@ export const productionOperationTools = [
|
||||
['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。后续新读图时自动释放较早的截图并保留文字元数据。${COPY_IMAGE_SCREEN_GUIDANCE}`,obj({
|
||||
page:optional(page),pages:optional(Type.Array(page)),
|
||||
})],
|
||||
['check_output_screens','按屏并行复核整屏合成画面、商品实拍、实时文案与叠加图层。'+OVERLAY_SCREEN_CRITERIA+'pages 填第 1–16 屏的屏号。默认等待结论,通过的屏自动登记。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取文字结论。',obj({
|
||||
pages:Type.Array(Type.Integer({minimum:1,maximum:maxScreenReviewPages}),{minItems:1,maxItems:maxScreenReviewPages}),
|
||||
['check_output_screens','按企业 Skill 并行复核整屏合成画面、商品实拍、实时文案与叠加图层。pages 从 1 编号,以当前画布实际屏数为准。默认等待结论,通过的屏自动登记。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取文字结论。',obj({
|
||||
pages:Type.Array(Type.Integer({minimum:1}),{minItems:1}),
|
||||
wait:optional(Type.Boolean({default:true})),
|
||||
})],
|
||||
['record_screen_check','登记整屏实际画面的复核结论。page 使用 read_output_screen 返回的零起始屏号,revision 使用同次读取的画布修订。',obj({
|
||||
@ -343,8 +340,6 @@ 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 autoAdoptionPolicy=readAutoAdoptionPolicy(plan.autoAdoptionPolicy??host.productionGoal.autoAdoptionPolicy??
|
||||
plan.template.production?.autoAdoptionPolicy);
|
||||
const ledger=productionLedger(store,outputId,variantId);
|
||||
const {repository}=ledger;
|
||||
const previous=ledger.read();
|
||||
@ -358,8 +353,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
record.copyInputs=productionInputs(value,variantId);
|
||||
record.creationRevision=value.revisions?.creation;
|
||||
};
|
||||
const knowledge=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext);
|
||||
const reviews=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext,'review');
|
||||
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);
|
||||
@ -419,6 +416,16 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
activeDelegates--;
|
||||
startNextDelegate();
|
||||
};
|
||||
const scheduleDelegate=async(signal,task)=>{
|
||||
signal.throwIfAborted();
|
||||
const acquired=await acquireDelegate();
|
||||
try{
|
||||
signal.throwIfAborted();
|
||||
return await task();
|
||||
}finally{
|
||||
if(acquired)releaseDelegate();
|
||||
}
|
||||
};
|
||||
const slotWorking=id=>[...jobs.values()].some(job=>job.row.slotId===id);
|
||||
const generationReceipts=scope=>[...generation.values()].reverse().filter(row=>scope.has(row.slotId));
|
||||
const pendingReviews=()=>[...reviewWork].filter(job=>job.run);
|
||||
@ -551,9 +558,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const pictureCells=slots.map(({id,label})=>{
|
||||
const item=journal.items[id];
|
||||
const candidateId=filled.get(id);
|
||||
const adopted=item?.autoAdoptions?.[item.autoCandidateSetId];
|
||||
const checked=adopted?.candidateId===candidateId&&adopted?.receipt||
|
||||
item?.approvals?.some(review=>review.candidateId===candidateId)||
|
||||
const checked=item?.approvals?.some(review=>review.candidateId===candidateId)||
|
||||
item?.review?.candidateId===candidateId&&item?.review?.decision==='pass';
|
||||
return {slotId:id,label,state:candidateId?(checked?'verified':'filled'):'empty'};
|
||||
});
|
||||
@ -585,7 +590,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
...(args.includeTemplateReference===false?{includeTemplateReference:false}:null),
|
||||
});
|
||||
};
|
||||
async function operate(slot,intent,values,signal,attempt,decision) {
|
||||
async function operate(slot,intent,values,signal,attempt) {
|
||||
const scope=new CanvasOperations();
|
||||
const prior=journal.items[slot.id], adopting=intent==='adopt_candidate';
|
||||
const pendingKey=adopting?'pendingAdoption':'pendingOperation';
|
||||
@ -603,7 +608,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const archive=async operation=>{
|
||||
const candidateId=adopting?values.candidateId:
|
||||
canvas.durableGenerationIds&&values.useProductReference!==true?operation.operationId:null;
|
||||
prepared={...operation,intent,candidateId,...(decision?{decision}:null)};
|
||||
prepared={...operation,intent,candidateId};
|
||||
dispatchingImages.set(operation.operationId,undefined);
|
||||
await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)});
|
||||
};
|
||||
@ -640,13 +645,11 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const item=journal.items[slot.id]??={};
|
||||
Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending,
|
||||
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null),
|
||||
...(state==='applied'&&!decision?{autoCandidateSetId:null}:null)});
|
||||
if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision,
|
||||
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
|
||||
...(state==='applied'?{autoCandidateSetId:null}:null)});
|
||||
rememberAttempt(item,operation.candidateId);
|
||||
rememberImageExpiry(item,operation.candidateId,operation);
|
||||
},operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate',
|
||||
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined);
|
||||
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId}]}:undefined);
|
||||
if(state==='applied')markProgressDirty();
|
||||
return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)};
|
||||
} finally {
|
||||
@ -683,21 +686,18 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return result;
|
||||
};
|
||||
const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,
|
||||
referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange,candidateSetId},signal)=>{
|
||||
referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
const input=await current();
|
||||
const live=await liveSlot(slot);
|
||||
const status=slotDrawStatus(live);
|
||||
if(status.drawLimitReached)return drawLimit(live,status);
|
||||
const versions=recordProductionInputs(repository,input,slots);
|
||||
const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:candidateSetId?undefined:retryOf?.trim()||undefined,useTemplateReference,
|
||||
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)});
|
||||
// A partially funded batch cannot meet the automatic adoption policy.
|
||||
const policy=status.remainingGenerationAttempts>=autoAdoptionPolicy?.candidateCount?autoAdoptionPolicy:undefined;
|
||||
const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files},
|
||||
policy,candidateSetId});
|
||||
return {...receipt,operationId:request.operationId,...(request.prepared.candidateSet?{candidateSet:request.prepared.candidateSet}:null)};
|
||||
const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}});
|
||||
return {...receipt,operationId:request.operationId};
|
||||
};
|
||||
const preparedRequest=(requestId,slot)=>{
|
||||
const saved=repository.readImageRequest(requestId);
|
||||
@ -833,57 +833,14 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
});
|
||||
const outstanding=async()=>{
|
||||
await journalWrite;
|
||||
const pending=(await host.broker?.status?.())?.pending??[];
|
||||
const scopes=new Set(slots.map(slot=>productRequestScope('slot',slot.id)));
|
||||
for(let page=1;page<=maxScreenReviewPages;page++)scopes.add(screenReviewScope(variantId,outputId,page));
|
||||
for(const job of reviewWork)scopes.add(productRequestScope('review',job.row.candidateId));
|
||||
for(const slot of slots)for(const candidate of slot.candidates??[]){
|
||||
scopes.add(productRequestScope('review',candidate.id));
|
||||
}
|
||||
const models=pending.filter(request=>request.modelRole==='detail'&&scopes.has(request.detailSlot)).map(request=>request.id);
|
||||
const requests=imageOriginals(journal);
|
||||
const images=[...new Set(requests.filter(row=>!row.projectId&&!row.adoption&&row.candidateId).map(row=>row.candidateId))];
|
||||
return {requests,originals:{models,images}};
|
||||
return {requests,originals:{models:[],images}};
|
||||
};
|
||||
const unfinished=({models,images})=>({outputId,variantId,complete:false,
|
||||
stageStatus:models.length||images.length?'waiting-originals':'continue',
|
||||
...(models.length||images.length?{originals:{models,images}}:null),
|
||||
const unfinished=originals=>({outputId,variantId,complete:false,
|
||||
stageStatus:originals.images.length?'waiting-originals':'continue',
|
||||
...(originals.images.length?{originals}:null),
|
||||
});
|
||||
const autoAdopt=(slot,candidateSet,signal)=>serialize(async()=>{
|
||||
signal?.throwIfAborted();
|
||||
const {id,policy}=candidateSet;
|
||||
const previous=journal.items[slot.id]?.autoAdoptions?.[id];
|
||||
if(previous&&previous.state!=='selected')return previous;
|
||||
const requests=repository.candidateSet(slot.id,id);
|
||||
const item=journal.items[slot.id];
|
||||
if(item?.autoCandidateSetId!==id)return previous;
|
||||
const copy=JSON.stringify(copySignature(await liveSlotCopy(slot)));
|
||||
signal?.throwIfAborted();
|
||||
const currentReviews=Object.fromEntries(Object.entries(item?.candidateReviews??{}).filter(([,row])=>
|
||||
row.creationRevision===plan.revisions?.creation&&
|
||||
JSON.stringify(row.observation.reviewedCopy)===copy));
|
||||
const selected=decideCandidateSet(policy,requests,currentReviews);
|
||||
if(!selected||item?.pendingAdoption)return previous;
|
||||
const assetSha256=selected.basis.find(row=>row.candidateId===selected.candidateId)?.original?.sha256;
|
||||
const decision={...selected,candidateSetId:id,assetSha256,fieldId:slot.fieldId,outputId,variantId};
|
||||
const state=decision.candidateId?'selected':'needs_rework';
|
||||
if(!previous)await update(journal=>{
|
||||
(journal.items[slot.id].autoAdoptions??={})[id]={...decision,state};
|
||||
});
|
||||
if(!decision.candidateId)return {...decision,state};
|
||||
const result=await operate(slot,'adopt_candidate',{candidateId:decision.candidateId},signal,undefined,decision);
|
||||
if(result.phase==='complete'){
|
||||
if(candidates.has(decision.candidateId))candidates.get(decision.candidateId).status='adopted';
|
||||
notice('画布回填回执');
|
||||
}
|
||||
return journal.items[slot.id].autoAdoptions[id];
|
||||
});
|
||||
const tryAutoAdopt=(slot,signal)=>{
|
||||
if(stageSignal.aborted)return;
|
||||
const {autoCandidateSetId:id,candidateReviews}=journal.items[slot.id]??{};
|
||||
const set=id&&candidateReviews&&repository.readImageRequest(id)?.prepared.candidateSet;
|
||||
if(set)return autoAdopt(slot,set,signal);
|
||||
};
|
||||
const tailsFor=slot=>slotOriginals(journal.items[slot.id]).map(tail=>{
|
||||
const {adopting,request:{candidateId,operationId,projectId}}=tail;
|
||||
return {...tail,slot,key:JSON.stringify([slot.id,Boolean(adopting),
|
||||
@ -919,9 +876,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
markProgressDirty();
|
||||
notice(heading);
|
||||
}
|
||||
if(receipt.phase==='complete'&&!adopting&&byId.has(slot.id)){
|
||||
tryAutoAdopt(slot,AbortSignal.any([signal,stageSignal]))?.catch(error=>{if(!stageSignal.aborted&&!signal.aborted)reportRecoveryError(error);});
|
||||
}
|
||||
return receipt;
|
||||
},
|
||||
onError:reportRecoveryError,
|
||||
@ -929,11 +883,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
async function check(slot,candidateId,adopted,signal){
|
||||
const item=journal.items[slot.id];
|
||||
const request=repository.readImageRequest(candidateId);
|
||||
const candidateSet=!adopted&&request?.slotId===slot.id&&request.prepared.binding===binding?request.prepared.candidateSet:null;
|
||||
const source=request?.slotId===slot.id?'generate':item?.candidateId===candidateId?item.source:undefined;
|
||||
try{
|
||||
const liveScreenCopy=await liveSlotCopy(slot);
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas,host,runAgent:host.runDetailAgent,
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas,runAgent:host.runDetailAgent,
|
||||
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews});
|
||||
const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review;
|
||||
const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform,
|
||||
@ -941,7 +894,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
await update(journal=>{
|
||||
const record=journal.items[slot.id]??={};
|
||||
record.review=row;
|
||||
if(candidateSet)(record.candidateReviews??={})[candidateId]=row;
|
||||
record.approvals=(record.approvals??[]).filter(old=>old.candidateId!==candidateId);
|
||||
if(verdict==='pass')record.approvals.push(row);
|
||||
const history=record.reviewHistory??=[];
|
||||
@ -951,8 +903,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf;
|
||||
await store.appendEvent({type:'whole_detail_review',outputId,variantId,slotId:slot.id,fieldId:slot.fieldId,
|
||||
...review,...(reworkOf?{reworkOf}:null)});
|
||||
const adoption=candidateSet&&await autoAdopt(slot,candidateSet,signal);
|
||||
return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null),...(adoption?{adoption}:null)};
|
||||
return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null)};
|
||||
}catch(error){
|
||||
return {slotId:slot.id,candidateId,error:error.message};
|
||||
}
|
||||
@ -998,7 +949,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
pictures,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs,
|
||||
pendingOutputs:host.productionGoal.pendingOutputs??[],
|
||||
progressSummary:await progressSummary(),
|
||||
...(autoAdoptionPolicy?{autoAdoptionPolicy}:null),
|
||||
...(unmatched.length?{unmatched}:null)};
|
||||
},
|
||||
async read_production_knowledge(args,signal){
|
||||
@ -1126,6 +1076,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return queueDispatch(slot,approval,request,signal?AbortSignal.any([signal,stageSignal]):stageSignal);
|
||||
},
|
||||
async delegate_image_slots({jobs:requested},signal){
|
||||
if(!requested.length)return {assigned:[]};
|
||||
const delegateSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
delegateSignal.throwIfAborted();
|
||||
const assigned=[],unmatched=[];
|
||||
const statuses=drawStatuses(await liveSlots());
|
||||
const resolved=requested.map(job=>({...job,slot:findSlot(job.slotId)}));
|
||||
@ -1137,10 +1090,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const status={...statuses.get(slot.id),...(pendingCopyFields?.length?{pendingCopyFields}:null)};
|
||||
if(slotWorking(slot.id)){assigned.push({id:slot.id,state:'already_running',...status});continue;}
|
||||
const row={number:nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'排队中',active:true};
|
||||
const delegateSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
let rework, produced=false, acquiredPermit=false;
|
||||
let rework, produced=false;
|
||||
const dispatched=new Set();
|
||||
const dispatchRuns=new Set();
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>({
|
||||
name,label:description,description,parameters:obj(properties),executionMode:'sequential',
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
@ -1160,37 +1111,25 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
(args,activeSignal)=>useProductImage(slot,args,activeSignal),true),
|
||||
workerTool('transform_slot_image','用本款实拍或本项目候选裁切、镜像、旋转、缩放或位移',transformImageArgs,
|
||||
(args,activeSignal)=>serialize(()=>transformImage(slot,args,activeSignal))),
|
||||
workerTool('prepare_image_request','准备并持久保存完整生图请求。'+imagePromptGuidance,preparationArgs,
|
||||
workerTool('prepare_image_request','准备并持久保存完整生图请求。',preparationArgs,
|
||||
(args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)),
|
||||
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
|
||||
async (approval,activeSignal)=>{
|
||||
const request=preparedRequest(approval.requestId,slot);
|
||||
row.step='正在生图';
|
||||
notice('子代理正在生图');
|
||||
const key=request.operationId??approval.requestId;
|
||||
const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number);
|
||||
if(receipt.operationId)dispatched.add(receipt.operationId);
|
||||
const run=jobs.get(key)?.run;
|
||||
if(run)dispatchRuns.add(run);
|
||||
if(request.candidateSet||!run)return receipt;
|
||||
const cancelled=Promise.withResolvers();
|
||||
using listener=addAbortListener(activeSignal,()=>cancelled.reject(activeSignal.reason));
|
||||
return await Promise.race([run,cancelled.promise]);
|
||||
},result=>{
|
||||
if(result.limitReached)return false;
|
||||
if(result.phase!=='accepted'&&result.phase!=='already_running')return true;
|
||||
return dispatched.size>=(autoAdoptionPolicy?.candidateCount??1);
|
||||
}),
|
||||
await dispatchingImages.get(receipt.operationId);
|
||||
return receipt;
|
||||
},result=>!result.limitReached),
|
||||
];
|
||||
const readTool={name:'read_slot_images',label:'查看本图位实拍与构图',description:'读取本图位的原片与模板构图。',
|
||||
parameters:obj({}),execute:async()=>{
|
||||
delegateSignal.throwIfAborted();
|
||||
return imageResult(await readImages(slot.id));
|
||||
}};
|
||||
const run=acquireDelegate().then(async acquired=>{
|
||||
if(!acquired)return;
|
||||
acquiredPermit=true;
|
||||
delegateSignal.throwIfAborted();
|
||||
const run=scheduleDelegate(delegateSignal,async()=>{
|
||||
row.step='正在准备';
|
||||
notice('子代理正在制作');
|
||||
const prior=journal.items[slot.id];
|
||||
@ -1219,15 +1158,15 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
}
|
||||
const live=await liveSlot(slot);
|
||||
const status=slotDrawStatus(live);
|
||||
const instructions='完成主代理委托的图位。根据 goal 和 screenCopy 确定本屏卖点及画面要证明的细节。'+imagePromptGuidance+'可用 transform_slot_image 调整同图位或跨图位候选,并查看像素指标。特写可裁切已有中景,或用 prefer2k 请求 2K 中景后裁切。'+
|
||||
(autoAdoptionPolicy?'\n准备回执带 candidateSet 时,备齐同批候选后分别审阅并派发。后续准备传首张的 candidateSet.id 和同一份完整请求。':'')+
|
||||
const instructions='完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+
|
||||
(rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+
|
||||
knowledgeReadInstruction;
|
||||
(delegateKnowledge.files.length?'\n用 read_production_knowledge 获取 knowledgeFiles 中本任务适用的企业 Skill 和制作规则。':'');
|
||||
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,
|
||||
knowledgeFiles:knowledge.files,...(autoAdoptionPolicy?{autoAdoptionPolicy}:null)}),[readTool,...makeTools(),...knowledge.tools],
|
||||
taskGuidance,knowledgeFiles:delegateKnowledge.files}),[readTool,...makeTools(),...delegateKnowledge.tools],
|
||||
rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id),undefined,delegateSignal);
|
||||
if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'});
|
||||
}).catch(async error=>{
|
||||
@ -1238,11 +1177,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
generation.set(workerId,{slotId:slot.id,phase:'failed',reason:error.message});
|
||||
await save(slot,{reason:error.message});
|
||||
}).finally(async()=>{
|
||||
// A multi-candidate worker can return before its image receipts.
|
||||
if(!stageSignal.aborted)await Promise.allSettled(dispatchRuns);
|
||||
jobs.delete(workerId);
|
||||
if(acquiredPermit)releaseDelegate();
|
||||
if(!stageSignal.aborted)notice('子代理已有回执');
|
||||
notice('子代理已有回执');
|
||||
});
|
||||
generation.delete(workerId);
|
||||
jobs.set(workerId,{row,run,dispatched});
|
||||
@ -1293,14 +1229,13 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const [generationReceipt]=generations;
|
||||
const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId;
|
||||
const reviews=checks.get(id)??[];
|
||||
const adoption=record?.autoAdoptions?.[record.autoCandidateSetId];
|
||||
if(requested.size)return {id,fieldId,label,selectedCandidateId,attemptCount,...status,rejections,candidates,working:slotWorking(id),
|
||||
record,generation:generationReceipt,...(generations.length>1?{generations}:null),checks:reviews.map(job=>job.receipt)};
|
||||
const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined;
|
||||
const adopted=adoption?.state==='adopted'||adoption?.state==='placed';
|
||||
const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId;
|
||||
const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking':
|
||||
record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)||Object.keys(record?.pendingGenerations??{}).length?'unknown':
|
||||
adoption?.state==='needs_rework'?'needs_rework':adopted?'applied':
|
||||
adopted?'applied':
|
||||
decision??generationReceipt?.phase??latest?.status??record?.state??'empty';
|
||||
return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,...status,rejectionCount:rejections.length};
|
||||
}),...(unmatched.length?{unmatched}:{})};
|
||||
@ -1322,6 +1257,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return receipt;
|
||||
},
|
||||
async check_image_slots({candidates:requested,wait=false},signal){
|
||||
const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const live=new Map((await liveSlots()).map(slot=>[slot.id,slot]));
|
||||
const statuses=drawStatuses([...live.values()]);
|
||||
const batch=requested.map(({slotId,candidateId,adopted})=>{
|
||||
@ -1336,7 +1273,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const row={number:nextWorkerNumber(),slotId:slot.id,label:slot.label,candidateId,step:'正在验图',active:true};
|
||||
const status=statuses.get(slot.id);
|
||||
const job={row,adopted:Boolean(adopted),receipt:{slotId:slot.id,candidateId,phase:'checking',...status}};
|
||||
job.run=check(slot,candidateId,adopted,signal?AbortSignal.any([signal,stageSignal]):stageSignal).then(receipt=>{
|
||||
job.run=scheduleDelegate(activeSignal,()=>check(slot,candidateId,adopted,activeSignal))
|
||||
.catch(error=>({slotId:slot.id,candidateId,error:error.message})).then(receipt=>{
|
||||
job.receipt={...receipt,...slotDrawStatus(live.get(slot.id)??slot)};
|
||||
return job.receipt;
|
||||
}).finally(()=>{
|
||||
@ -1395,7 +1333,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return receipts;
|
||||
}));
|
||||
signal?.throwIfAborted();
|
||||
for(const slot of selected)await tryAutoAdopt(slot,signal);
|
||||
return results;
|
||||
},
|
||||
async read_output_screen({page=0,pages},signal){
|
||||
@ -1448,12 +1385,13 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return {content,details:{screens}};
|
||||
},
|
||||
async check_output_screens({pages,wait=true},signal){
|
||||
if(!Array.isArray(pages)||pages.length<1||pages.length>maxScreenReviewPages||
|
||||
pages.some(page=>!Number.isSafeInteger(page)||page<1||page>maxScreenReviewPages)){
|
||||
throw Error('请填写 1–16 个有效屏号,每个屏号须为 1–16 的整数');
|
||||
if(!Array.isArray(pages)||!pages.length||pages.some(page=>!Number.isSafeInteger(page)||page<1)){
|
||||
throw Error('请填写有效屏号,屏号从 1 开始');
|
||||
}
|
||||
const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
activeSignal?.throwIfAborted();
|
||||
activeSignal.throwIfAborted();
|
||||
const {pages:canvasPages=[]}=await copySnapshot();
|
||||
activeSignal.throwIfAborted();
|
||||
let referenceRead;
|
||||
const references=()=>referenceRead??=readReferences();
|
||||
async function readReferences(){
|
||||
@ -1470,14 +1408,12 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return {product,photos,inputSignature:productionInputs(inputPlan,variantId)};
|
||||
}
|
||||
const batch=[...new Set(pages)].map(page=>{
|
||||
if(page>canvasPages.length)return {receipt:{page,error:'此屏不属于当前工作画布'}};
|
||||
const existing=screenChecks.get(page);
|
||||
if(existing?.run)return existing;
|
||||
const job={receipt:{page,state:'queued'}};
|
||||
let revision, acquiredPermit=false;
|
||||
job.run=acquireDelegate().then(async acquired=>{
|
||||
if(!acquired)return;
|
||||
acquiredPermit=true;
|
||||
activeSignal.throwIfAborted();
|
||||
let revision;
|
||||
job.run=scheduleDelegate(activeSignal,async()=>{
|
||||
job.receipt={page,state:'checking'};
|
||||
notice('正在按屏复核');
|
||||
const screen=await operations.read_output_screen({page:page-1},activeSignal);
|
||||
@ -1485,7 +1421,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});
|
||||
slots:screenSlots,outputId,variantId,signal:activeSignal,reviewKnowledge:reviews});
|
||||
job.inputSignature=(await references()).inputSignature;
|
||||
if(receipt.verdict==='pass'){
|
||||
await operations.record_screen_check({page:page-1,revision,issues:[]},activeSignal,job.inputSignature);
|
||||
@ -1495,7 +1431,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
job.receipt={page,...(revision===undefined?null:{revision}),error:error.message};
|
||||
}).finally(()=>{
|
||||
job.run=null;
|
||||
if(acquiredPermit)releaseDelegate();
|
||||
notice('按屏复核已有回执');
|
||||
});
|
||||
screenChecks.set(page,job);
|
||||
@ -1543,8 +1478,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
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||originals.models.length)return {submitted:false,reason:'originals_pending',requests,originals,
|
||||
nextTool:requests.length?'reconcile_image_slots':'finish_production'};
|
||||
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'};
|
||||
}
|
||||
@ -1562,7 +1497,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const {originals}=await outstanding();
|
||||
const revisions=screenReviewRevisions();
|
||||
const screenEvidence=revisions.length?{screenReviewRevisions:revisions}:null;
|
||||
if(originals.models.length||originals.images.length){
|
||||
if(originals.images.length){
|
||||
return {text:'制作请求正在核查,已保留当前进度。',production:{...unfinished(originals),...screenEvidence}};
|
||||
}
|
||||
return {text:'已提交当前画布,正在保存和导出。',production:{
|
||||
|
||||
@ -10,15 +10,6 @@ export function gatewayImageRetryDelay(retries, retryAfterSeconds) {
|
||||
Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1000 : 0);
|
||||
}
|
||||
|
||||
export class ProductionRequestPending extends Error {
|
||||
constructor({id,requestId,detailSlot}) {
|
||||
super('原制作请求 '+id+' 正在核查');
|
||||
this.id=id;
|
||||
this.requestId=requestId;
|
||||
this.detailSlot=detailSlot;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProductionRequestFailed extends Error {
|
||||
constructor(requestId, httpStatus) {
|
||||
super('模型服务已确认请求失败(原请求 '+requestId+(httpStatus?',HTTP '+httpStatus:'')+')');
|
||||
@ -45,11 +36,6 @@ export function productRequestScope(step, variant, output) {
|
||||
return ['product',step,variant,output].filter(Boolean).join('/');
|
||||
}
|
||||
|
||||
export function productionUsesAutomaticTools(model) {
|
||||
return model?.protocol==='anthropic-messages'
|
||||
&& /^claude-(?:opus-5-5|sonnet-5-5|fable-5-[12]|mythos-5-[12])(?:$|-)/u.test(model.id);
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
@ -32,7 +32,9 @@ export async function projectTools(host) {
|
||||
const read=(agent,requestScope)=>createReadTool(cwd,{operations:{
|
||||
access:async file=>{
|
||||
const normalized=path.normalize(file);
|
||||
if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checked(file);
|
||||
if(agent==='worker'){
|
||||
if(!await host.productionSkills.resolveFile(normalized))throw Error('制作助手只能读取当前项目锁定的企业资料');
|
||||
} else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checked(file);
|
||||
await fs.access(file);
|
||||
},
|
||||
readFile:async file=>{
|
||||
|
||||
@ -20,7 +20,7 @@ export function auditResponse(raw, protocol) {
|
||||
});
|
||||
if (protocol === 'openai-responses') {
|
||||
const terminal = values.findLast(v => ['response.completed', 'response.incomplete'].includes(v.type));
|
||||
if (!terminal) throw Error('原响应缺少完成原因;未执行工具,保留原请求待核查');
|
||||
if (!terminal) throw Error('network error: 原响应缺少完成原因;未执行工具');
|
||||
const items = terminal.response.output;
|
||||
const functions = items.filter(item => item.type === 'function_call');
|
||||
const calls = functions.map(item => ({name:item.name, arguments:toolArguments(item.arguments, true)}));
|
||||
@ -52,7 +52,7 @@ export function auditResponse(raw, protocol) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!finishes.length) throw Error('原响应缺少完成原因;未执行工具,保留原请求待核查');
|
||||
if (!finishes.length) throw Error('network error: 原响应缺少完成原因;未执行工具');
|
||||
const parsed = [...calls.values()].map(c => ({name:c.name,
|
||||
arguments:c.arguments || protocol !== 'anthropic-messages' ? toolArguments(c.arguments, true) : toolArguments(c.input, false)}));
|
||||
return { finishes, textLength: text.length, literalEos: text.includes('<|eos|>'), calls:parsed };
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { COPY_IMAGE_SCREEN_GUIDANCE } from './copy-image-alignment.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { InvalidToolReply } from './response-audit.mjs';
|
||||
import { digest } from './store.mjs';
|
||||
@ -26,15 +25,7 @@ const assessment = object({
|
||||
copyFixes:finding({field:text(200)}),
|
||||
});
|
||||
|
||||
const instructions = [
|
||||
'你负责复核一屏成片。第一张图是整屏实际画面,后续图片是本款实拍。',
|
||||
COPY_IMAGE_SCREEN_GUIDANCE,
|
||||
'同时核对品牌元素与实时文案。',
|
||||
'仅提交 review_output_screen 回执。为主代理写清像素依据和可执行的修改建议。图片问题定位 location 与已知 slotId,叠层问题使用 overlayLayers 中的 nativeLayerId,正文问题使用 screenCopy 中的 field。',
|
||||
'有需修改的问题就返回 needs_fix 并至少填写一项。通过时三组问题均为空。',
|
||||
].join('\n');
|
||||
|
||||
export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) {
|
||||
export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal, reviewKnowledge}) {
|
||||
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('未读取到当前屏的实际画面和修订号');
|
||||
@ -66,9 +57,16 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
|
||||
},
|
||||
};
|
||||
const scope = screenReviewScope(variantId,outputId,page);
|
||||
const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length});
|
||||
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 captions = ['当前整屏成片', ...photos.map((_,index) => `本款实拍 ${index + 1}`)];
|
||||
await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal);
|
||||
await runAgent(`screen-${page}`, instructions, prompt, [tool,...reviewKnowledge.tools], [...images,...photos], scope, captions,signal);
|
||||
signal?.throwIfAborted();
|
||||
if (!receipt) throw new InvalidToolReply('整屏复核未提交结论');
|
||||
return receipt;
|
||||
|
||||
@ -11,7 +11,7 @@ description: Use product image sources and Image Request tools in PhotoCraft.
|
||||
- transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
|
||||
- 按已发布规则撰写完整的 `prompt`,包括商品外观、构图、颜色、参考用途和返工要求。用 `referenceIndexes` 指定发送的原片及顺序,按需指定模板参考、画幅规格或实拍合成。实拍合成时,提示词描述在模板场景中擦除旧商品,本款实拍由客户端合成。
|
||||
- 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。调用 `dispatch_image_request` 时填写该回执的 `requestId`,宿主从该编号绑定的请求读取版本和哈希。
|
||||
- `plan_production` 返回 `autoAdoptionPolicy` 时,按 `candidateCount` 准备同批样本。第二张起传入首张的 `candidateSet.id` 和相同的正式请求。备齐后分别确认派发,完成后将整批编号交给 `check_image_slots`。验完会自动采用合格图,全部退回时可在图位回执查看待返工记录。
|
||||
- 需要比较多张候选时,分别准备并确认各自的请求,完成后可把候选号一起交给 `check_image_slots`。根据验图依据选择候选,再用 `adopt_production_image` 放入画布。
|
||||
- `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。
|
||||
- 验图可提供画布调整建议,按当前画面决定是否调整、重新生成或采用。
|
||||
- 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。
|
||||
|
||||
@ -391,7 +391,7 @@ test('SKU color plan exposes all SKUs and only the chosen IDs for detail and mai
|
||||
assert.ok(!JSON.stringify(context).includes('旧颜色'));
|
||||
});
|
||||
|
||||
test('legacy transcript migration retains originals and never clears broker pending on a binding change',async()=>{
|
||||
test('legacy transcript migration retains originals and a new conversation can proceed',async()=>{
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};let host;
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('A'));
|
||||
@ -406,9 +406,20 @@ test('legacy transcript migration retains originals and never clears broker pend
|
||||
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
|
||||
assert.ok((await fs.readFile(path.join(stable.dir,'events.jsonl'),'utf8')).includes('preserved-request'));
|
||||
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(){posts++;throw Error('must not post');}}});
|
||||
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);
|
||||
return {id:randomUUID(),fetch:async()=>{
|
||||
posts++;
|
||||
return new Response(sse({content:'当前对话可以继续。'}),{headers:{'content-type':'text/event-stream'}});
|
||||
},finish:async()=>({phase:'complete'})};
|
||||
},
|
||||
}});
|
||||
assert.ok(host.session.messages.some(m=>m.role==='user'&&m.content==='原始会话必须保留'));
|
||||
await assert.rejects(host.prompt('继续普通聊天也不能重发未知请求'),/未知请求|工具建议/);assert.equal(posts,0);
|
||||
assert.equal((await host.prompt('继续当前讨论')).text,'当前对话可以继续。');
|
||||
assert.equal(posts,1);
|
||||
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
|
||||
assert.equal(await fs.readFile(manager.getSessionFile(),'utf8'),original);
|
||||
}finally{await host?.dispose();await cleanup(root);}
|
||||
});
|
||||
|
||||
@ -5,7 +5,7 @@ import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { mergeReviewCopy, extractPageLiveCopy, resolveLiveSlotCopy } from '../src/copy-image-alignment.mjs';
|
||||
import { decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from '../src/candidate-review.mjs';
|
||||
import { reviewProductionCandidate } from '../src/candidate-review.mjs';
|
||||
import { openProductionOperations } from '../src/production-operations.mjs';
|
||||
import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
@ -65,12 +65,11 @@ 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:[]},
|
||||
liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}],reviewKnowledge:{files:[],tools:[],guidance:()=>undefined},
|
||||
async runAgent(_slot,instructions,prompt,[tool]){
|
||||
assert.match(instructions,/shownSubject.*checks.copyAlignment/u);
|
||||
const {copy,screenCopy}=JSON.parse(prompt);
|
||||
assert.deepEqual(copy,screenCopy);
|
||||
assert.deepEqual(copy.map(row=>row.text),['加厚桌腿','实木横梁']);
|
||||
assert.match(instructions,/shownSubject.*shownFields/u);
|
||||
const {screenCopy}=JSON.parse(prompt);
|
||||
assert.deepEqual(screenCopy.map(row=>row.text),['加厚桌腿','实木横梁']);
|
||||
const assessment={candidateId:'candidate',verdict:'revise',reason:'桌腿未入画',
|
||||
...(shownSubject?{shownSubject}:{}),
|
||||
checks:{...checks,...(copyAlignment===false?{copyAlignment}:{})}};
|
||||
@ -83,8 +82,6 @@ test('candidate review records the observed subject and alignment while acceptin
|
||||
assert.equal(result.checks.copyAlignment,copyAlignment);
|
||||
assert.deepEqual(result.observation.reviewedCopy,[['tag','实木横梁'],['title','加厚桌腿']]);
|
||||
}
|
||||
const policy={version:'1',candidateCount:2,priorityChecks:['structure','copyAlignment']};
|
||||
assert.deepEqual(readAutoAdoptionPolicy(policy),policy);
|
||||
});
|
||||
|
||||
test('candidate review sends the candidate, same-product photo and template composition only',async()=>{
|
||||
@ -97,12 +94,12 @@ 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:[]},
|
||||
reviewKnowledge:{files:[{fileId:'special-rule'}],tools:[],guidance:()=>({fileId:'special-rule',text:'企业审稿标准'})},
|
||||
async runAgent(_slot,instructions,prompt,[tool],images,_scope,captions){
|
||||
assert.deepEqual(images,[candidate,photo,layout]);
|
||||
assert.deepEqual(captions,['受审候选图框','同款实拍 P02','模板构图参考']);
|
||||
assert.match(instructions,/接地与光影.*异常留边/u);
|
||||
assert.match(instructions,/专项标准且会影响结论时/u);
|
||||
assert.match(instructions,/read_production_knowledge.*企业 Skill/u);
|
||||
assert.equal(JSON.parse(prompt).taskGuidance.text,'企业审稿标准');
|
||||
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}});
|
||||
@ -112,18 +109,6 @@ test('candidate review sends the candidate, same-product photo and template comp
|
||||
assert.equal(result.observation.pixelFindings,undefined);
|
||||
});
|
||||
|
||||
test('automatic choice waits for unsettled requests and ranks reviewed images when one draw failed',()=>{
|
||||
const policy={version:'1',candidateCount:2,priorityChecks:['composition']};
|
||||
const requests=[
|
||||
{requestId:'a',state:'complete',prepared:{candidateSet:{position:0}}},
|
||||
{requestId:'b',state:'unknown',prepared:{candidateSet:{position:1}}},
|
||||
];
|
||||
const reviews={a:{decision:'pass',checks:{composition:true},reason:'构图完整'}};
|
||||
assert.equal(decideCandidateSet(policy,requests,reviews),undefined);
|
||||
requests[1].state='failed';
|
||||
assert.equal(decideCandidateSet(policy,requests,reviews).candidateId,'a');
|
||||
});
|
||||
|
||||
test('production delegation and screen rendering use live copy after a direct canvas edit',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-copy-alignment-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
@ -145,7 +130,7 @@ test('production delegation and screen rendering use live copy after a direct ca
|
||||
readCanvas:async({layer})=>({context:{layers:[{id:layer,visible:true,effectiveVisible:layer!==7}]}}),
|
||||
delta:async()=>{},
|
||||
},async runDetailAgent(_slot,instructions,prompt){
|
||||
assert.match(instructions,/useTemplateReference: false/u);
|
||||
assert.match(instructions,/screenCopy 是画布实时文案/u);
|
||||
delegated=JSON.parse(prompt);
|
||||
}};
|
||||
const actions=await openProductionOperations(host);
|
||||
|
||||
@ -448,7 +448,7 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
|
||||
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'}});
|
||||
emit({type:'chunk',data:Buffer.from(success?response:error).toString('base64')});
|
||||
return success?{phase:'received'}:{phase:'unknown',requestId:originalId};
|
||||
return success?{phase:'complete'}:{phase:'unknown',requestId:originalId};
|
||||
};
|
||||
const canvas={begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},activity:async()=>{},delta:async()=>{},end:async()=>{},finishProduction:async input=>productionExportReceipt(input)};
|
||||
const variantId=randomUUID();
|
||||
@ -463,7 +463,7 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
|
||||
assert.equal(resumed.production.complete,true);
|
||||
assert.deepEqual(operations,[{revision:7,scope:"all"}]);
|
||||
assert.equal(resumed.production.finalized,true);
|
||||
assert.deepEqual(finished,[requests[1].id]);
|
||||
assert.deepEqual(finished,[]);
|
||||
assert.notEqual(requests[0].id,requests[1].id);
|
||||
assert.equal(requests[0].body,requests[1].body);
|
||||
const guarded=broker.round();
|
||||
@ -503,7 +503,7 @@ test('a managed inference interruption retries without executing its partial too
|
||||
const x=await setup((_,n)=>n===1?sse(call,null).replace('data: [DONE]','')
|
||||
:n===2?sse(call,'tool_calls'):sse({tool_calls:[{index:0,id:'finish',type:'function',
|
||||
function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls'),
|
||||
async valid=>valid?{phase:'complete'}:{phase:'unknown'},{
|
||||
async()=>({phase:'complete'}),{
|
||||
deadline:Math.floor(Date.now()/1000)+600,callBudget:4,
|
||||
plan:()=>{plans++;return {pendingText:0};},
|
||||
progress:()=>({state:{waitingOnOriginals:true}}),
|
||||
@ -799,24 +799,25 @@ test('main request archives summarize image bytes by default and support raw pay
|
||||
});
|
||||
|
||||
test('a worker can change course after many identical calls without terminating',async t=>{
|
||||
const calls=[];
|
||||
const calls=[], imageCounts=[];
|
||||
const image={type:'image',mimeType:'image/png',
|
||||
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='};
|
||||
const x=await setup((payload,round)=>{
|
||||
if(round===10){
|
||||
const last=payload.messages.findLast(message=>message.role==='tool');
|
||||
assert.match(last.content,/已连续调用 8 次/u);
|
||||
}
|
||||
imageCounts.push(payload.messages.reduce((count,{content})=>count+
|
||||
(Array.isArray(content)?content.filter(part=>part.type==='image_url').length:0),0));
|
||||
if(round===12)return sse({content:'核对完成。'},'stop');
|
||||
return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'inspect_item',
|
||||
return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'read_slot_images',
|
||||
arguments:JSON.stringify({item:round===10?'other':'same'})}}]},'tool_calls');
|
||||
},undefined,undefined,{canvas:{}});
|
||||
t.after(x.close);
|
||||
const tool={name:'inspect_item',description:'Inspect item',parameters:{type:'object',properties:{item:{type:'string'}},required:['item']},
|
||||
const tool={name:'read_slot_images',label:'Inspect item',description:'Inspect item',parameters:{type:'object',properties:{item:{type:'string'}},required:['item']},
|
||||
async execute(_id,{item}){
|
||||
calls.push(item);
|
||||
return {content:[{type:'text',text:item}],details:{item}};
|
||||
return {content:[{type:'text',text:item},image],details:{item}};
|
||||
}};
|
||||
await x.host.runDetailAgent('slot-a','Inspect the item.','Read the fixture.',[tool],[],'product/slot/slot-a');
|
||||
assert.deepEqual(calls,[...Array(8).fill('same'),'other','same']);
|
||||
assert.deepEqual(calls,[...Array(9).fill('same'),'other','same']);
|
||||
assert.deepEqual(imageCounts,[0,...Array(11).fill(1)]);
|
||||
assert.equal(x.requests.length,12);
|
||||
});
|
||||
|
||||
@ -1269,7 +1270,7 @@ test('Pi serializes shared cache affinity for the same kind of production worker
|
||||
bodies.push(typeof input.body === 'string' ? JSON.parse(input.body) : input.body);
|
||||
emit({type:'headers',status:200,requestId:randomUUID(),headers:{'content-type':'text/event-stream'},bodyHash:'synthetic'});
|
||||
emit({type:'chunk',data:Buffer.from(response).toString('base64')});
|
||||
return {phase:'received'};
|
||||
return {phase:'complete'};
|
||||
};
|
||||
const production = new AbortController();
|
||||
const host = await DetailPiAgent.open({store,broker,productionSignal:production.signal,
|
||||
@ -1284,6 +1285,14 @@ test('Pi serializes shared cache affinity for the same kind of production worker
|
||||
|
||||
const enter=Promise.withResolvers();
|
||||
const round=broker.round.bind(broker);
|
||||
let interrupted=0;
|
||||
broker.round=()=>({id:randomUUID(),fetch:async()=>{
|
||||
interrupted++;
|
||||
throw Error('network error: synthetic disconnect');
|
||||
},finish:async()=>{throw Error('network error: synthetic disconnect');}});
|
||||
await assert.rejects(host.runDetailAgent('slot-interrupted','Synthetic system','Inspect fixture.',[],[],
|
||||
'product/review/slot-interrupted'),/synthetic disconnect/u);
|
||||
assert.equal(interrupted,4);
|
||||
let stoppedCalls=0;
|
||||
broker.round=options=>({...round(options),fetch:(_address,{signal})=>{
|
||||
stoppedCalls++;
|
||||
|
||||
@ -155,8 +155,9 @@ test('Pi production and its worker read the same locked Skill and its relative r
|
||||
try {
|
||||
assert.equal((await host.prompt('制作详情页')).production.complete,true);
|
||||
await t.test('production prompts only list bound and bundled skills',()=>{
|
||||
const expected=['lighting','pi-goal-writer','product-image-sources'];
|
||||
assert.deepEqual(Object.fromEntries(skillLists),{main:expected,worker:expected});
|
||||
assert.deepEqual(Object.fromEntries(skillLists),{
|
||||
main:['lighting','pi-goal-writer','product-image-sources'],worker:['lighting'],
|
||||
});
|
||||
});
|
||||
const context=await host.modelContext({}, {loadKnowledge:true});
|
||||
assert.deepEqual(context.enterpriseKnowledge.sources.map(row=>row.revision),['r4','r7']);
|
||||
|
||||
@ -30,6 +30,7 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
if(args.expectedHash!==request.receipt.requestSpecHash||args.expectedRevision!==request.receipt.revision){
|
||||
throw new BridgeError('生图请求版本已变化,请重新准备');
|
||||
}
|
||||
if(dispatch.length<4)execution?.onEnqueued?.();
|
||||
return dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued);
|
||||
};
|
||||
}
|
||||
@ -164,6 +165,7 @@ test('six original lookups run while all six generation delegates are posting',{
|
||||
} finally {
|
||||
releasePosts.resolve();
|
||||
releaseReads.resolve();
|
||||
while(actions.active)await actions.await_image_slots({});
|
||||
await actions.close();
|
||||
}
|
||||
});
|
||||
@ -664,16 +666,8 @@ test('the unbound production plan lists the same readable knowledge files as the
|
||||
assert.deepEqual((await actions.plan_production()).knowledgeFiles,plan.knowledgeFiles);
|
||||
});
|
||||
|
||||
test('P07 waits for both candidate reviews and persists the automatic adoption decision',async t=>{
|
||||
for(const scenario of [
|
||||
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true},
|
||||
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true,watchA:true},
|
||||
{verdicts:['pass','pass'],winner:1,reason:'policy_priority'},
|
||||
{verdicts:['revise','revise'],winner:null,reason:'all_rejected'},
|
||||
{verdicts:['pass','pass'],winner:1,reason:'policy_priority',editCopy:true},
|
||||
{verdicts:['revise','pass'],manual:true,reason:'honors the explicit choice before the draw cap'},
|
||||
])await t.test(scenario.watchA?'adopts a recovered image from existing reviews':
|
||||
scenario.editCopy?'rechecks earlier candidates after a live copy edit':scenario.reason,{timeout:5000},async t=>{
|
||||
test('candidate review leaves placement to the main agent, even with an old template policy',async t=>{
|
||||
for(const recoverA of [false,true])await t.test(recoverA?'recovered original':'completed originals',{timeout:5000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-p07-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
@ -681,18 +675,18 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
const ledger=store.ledger('detail','oak');
|
||||
const slotId='main-photo';
|
||||
const posts=[],placements=[],seen=[];
|
||||
const bothStarted=Promise.withResolvers(), complete=Promise.withResolvers();
|
||||
const tailWatchClock=tailClock(), placed=Promise.withResolvers();
|
||||
const firstStarted=Promise.withResolvers(), complete=Promise.withResolvers();
|
||||
const tailWatchClock=tailClock();
|
||||
const image={type:'image',mimeType:'image/png',
|
||||
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j1f8AAAAASUVORK5CYII='};
|
||||
const digest='a'.repeat(64);
|
||||
let currentText='桌腿接口';
|
||||
const currentText='桌腿接口';
|
||||
const canvas={
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
|
||||
template:{contentHash:'studio',production:{autoAdoptionPolicy:policy}},totalSlots:1,
|
||||
slots:[{id:slotId,fieldId:'cover',documentId:'P07',relatedFields:['title']}]}),
|
||||
detailCopyFields:async({includeFilled})=>includeFilled?{fields:[{page:'P07',field:'title',currentText}]}:[],
|
||||
async delta(_text,_thinking,{heading}){if(heading==='画布回填回执')placed.resolve();},
|
||||
async delta(){},
|
||||
async detailRecover(recoveredSlot,{candidateId}){
|
||||
assert.equal(recoveredSlot,slotId);
|
||||
assert.equal(candidateId,posts[0]);
|
||||
@ -700,7 +694,7 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
},
|
||||
async detailImages(_slot,candidateId,options){
|
||||
assert.deepEqual(options,{});
|
||||
return {candidateId,referenceCount:1,candidateFile:{width:1,height:1,...(scenario.recoverA?{sha256:digest}:null)},
|
||||
return {candidateId,referenceCount:1,candidateFile:{width:1,height:1,...(recoverA?{sha256:digest}:null)},
|
||||
prompt:'桌腿接口近景',requirements:'同一屏的各个部位分别用对应图位表现。桌腿接口近景。',
|
||||
images:[image,image],relatedCopy:[{fieldId:'title',text:currentText}]};
|
||||
},
|
||||
@ -726,7 +720,7 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
assert.deepEqual(images,[image,image]);
|
||||
assert.deepEqual(captions,['受审候选图框','同款实拍 P01']);
|
||||
seen.push(candidateId);
|
||||
await tools[0].execute('review-fixture',{candidateId,verdict:scenario.verdicts[index],
|
||||
await tools[0].execute('review-fixture',{candidateId,verdict:index===0?'revise':'pass',
|
||||
checks:{structure:true,color:true,composition:true,evidence:true,templateStyle:index===1},
|
||||
reason:index===0?'原图能看到桌脚':'原图中能看到桌脚与完整布景'});
|
||||
},
|
||||
@ -734,31 +728,28 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
imageBridge(host,async(_request,id)=>{
|
||||
posts.push(id);
|
||||
assert.ok(ledger.read().items[slotId].pendingGenerations[id]);
|
||||
if(posts.length===2)bothStarted.resolve();
|
||||
firstStarted.resolve();
|
||||
await complete.promise;
|
||||
return {status:scenario.recoverA&&id===posts[0]?'unknown':'complete',id};
|
||||
return {status:recoverA&&id===posts[0]?'unknown':'complete',id};
|
||||
});
|
||||
let actions=await openProductionOperations(host,{tailWatchClock});
|
||||
assert.deepEqual((await actions.plan_production()).autoAdoptionPolicy,policy);
|
||||
assert.equal((await actions.plan_production()).autoAdoptionPolicy,undefined);
|
||||
const input={slotId:'cover',prompt:'保留同款原片的轮廓。\r\n窗侧光。'};
|
||||
const a=await actions.prepare_image_request(input);
|
||||
const b=await actions.prepare_image_request({...input,candidateSetId:a.candidateSet.id});
|
||||
const b=await actions.prepare_image_request({...input,prompt:'保留同款原片的轮廓,使用正面取景。'});
|
||||
assert.equal(a.requestSpecHash,b.requestSpecHash);
|
||||
assert.equal(a.spec.prompt,b.spec.prompt);
|
||||
assert.notEqual(a.spec.prompt,b.spec.prompt);
|
||||
assert.notEqual(a.operationId,b.operationId);
|
||||
if(scenario.reason==='policy_priority'){
|
||||
await actions.prepare_image_request({...input,prompt:'备选构图草案'});
|
||||
}
|
||||
const ids=[a.requestId,b.requestId];
|
||||
await Promise.all([actions.dispatch_image_request(approve(a)),actions.dispatch_image_request(approve(b))]);
|
||||
await bothStarted.promise;
|
||||
await actions.dispatch_image_request(approve(a));
|
||||
await firstStarted.promise;
|
||||
assert.equal((await actions.dispatch_image_request(approve(a))).phase,'already_running');
|
||||
assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),ids);
|
||||
assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),[a.requestId]);
|
||||
complete.resolve();
|
||||
while(actions.active)await actions.await_image_slots({});
|
||||
await actions.close();
|
||||
actions=await openProductionOperations(host,{tailWatchClock});
|
||||
if(scenario.recoverA&&!scenario.watchA){
|
||||
if(recoverA){
|
||||
assert.equal((await actions.dispatch_image_request(approve(a))).pendingOriginal,a.requestId);
|
||||
const [recovered]=await actions.reconcile_image_slots({slotIds:[slotId]});
|
||||
assert.equal(recovered.operationId,a.operationId);
|
||||
@ -770,64 +761,19 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
const [first]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:a.requestId}]});
|
||||
assert.equal(first.adoption,undefined);
|
||||
assert.deepEqual(placements,[]);
|
||||
if(scenario.manual){
|
||||
const placement=await actions.adopt_production_image({slotId,candidateId:a.requestId});
|
||||
assert.equal(placement.phase,'complete');
|
||||
assert.equal(placement.afterRevision,4);
|
||||
assert.deepEqual(placement.overlayLayers,[{nativeLayerId:9,kind:'text',text:'62.26cm',
|
||||
mapped:false,bounds:[5,10,18,12],overlapsSlots:['cover']}]);
|
||||
assert.match(placement.overlayNote,/整屏合成画面/);
|
||||
const [later]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
|
||||
assert.equal(later.adoption,undefined);
|
||||
assert.deepEqual(placements.map(row=>row.candidateId),[a.requestId]);
|
||||
return;
|
||||
}
|
||||
if(scenario.editCopy)currentText='加厚桌腿与横梁接口';
|
||||
const [second]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
|
||||
let adoption=second.adoption;
|
||||
if(scenario.watchA){
|
||||
assert.equal(adoption,undefined);
|
||||
assert.deepEqual(placements,[]);
|
||||
await tailWatchClock.advance();
|
||||
await placed.promise;
|
||||
adoption=ledger.read().items[slotId].autoAdoptions[a.candidateSet.id];
|
||||
}
|
||||
if(scenario.editCopy){
|
||||
assert.equal(adoption,undefined);
|
||||
assert.deepEqual(placements,[]);
|
||||
const [rechecked]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:a.requestId}]});
|
||||
adoption=rechecked.adoption;
|
||||
}
|
||||
assert.deepEqual(seen,scenario.editCopy?[...ids,ids[0]]:ids);
|
||||
assert.equal(adoption.reason,scenario.reason);
|
||||
if(scenario.winner!=null)assert.equal(adoption.receipt.overlayLayers[0].text,'62.26cm');
|
||||
assert.equal(adoption.actor,'agent');
|
||||
assert.equal(adoption.policyVersion,policy.version);
|
||||
assert.deepEqual(adoption.basis.map(row=>row.candidateId),ids);
|
||||
assert.equal(first.verdict,'revise');
|
||||
assert.equal(second.verdict,'pass');
|
||||
assert.deepEqual(seen,ids);
|
||||
assert.deepEqual(placements,[]);
|
||||
const placement=await actions.adopt_production_image({slotId,candidateId:a.requestId});
|
||||
assert.equal(placement.phase,'complete');
|
||||
assert.equal(placement.afterRevision,4);
|
||||
assert.deepEqual(placement.overlayLayers,[{nativeLayerId:9,kind:'text',text:'62.26cm',
|
||||
mapped:false,bounds:[5,10,18,12],overlapsSlots:['cover']}]);
|
||||
assert.match(placement.overlayNote,/整屏合成画面/);
|
||||
assert.deepEqual(placements.map(row=>row.candidateId),[a.requestId]);
|
||||
await actions.close();
|
||||
const reopened=await openProductionOperations(host);
|
||||
const {pictures:[{record}]}=await reopened.review_image_slots({slotIds:[slotId]});
|
||||
const persisted=record.autoAdoptions[a.candidateSet.id];
|
||||
assert.equal(persisted.policyVersion,policy.version);
|
||||
assert.equal(persisted.actor,'agent');
|
||||
const {pictures:[summary]}=await reopened.review_image_slots({});
|
||||
assert.equal(summary.state,scenario.winner===null?'needs_rework':'applied');
|
||||
if(scenario.winner===null){
|
||||
assert.equal(persisted.state,'needs_rework');
|
||||
assert.deepEqual(placements,[]);
|
||||
}else{
|
||||
const winner=ids[scenario.winner];
|
||||
assert.equal(persisted.state,'adopted');
|
||||
assert.equal(persisted.candidateId,winner);
|
||||
assert.equal(placements.length,1);
|
||||
const adopted=ledger.repository.candidateEvidence(slotId,winner).find(row=>row.kind==='adoption').detail;
|
||||
assert.equal(adopted.actor,'agent');
|
||||
assert.equal(adopted.policyVersion,policy.version);
|
||||
assert.equal(adopted.assetSha256,scenario.recoverA?digest:undefined);
|
||||
assert.equal(adopted.operationId,placements[0].operationId);
|
||||
assert.equal(adopted.reason,scenario.reason);
|
||||
}
|
||||
await reopened.close();
|
||||
});
|
||||
});
|
||||
|
||||
@ -859,7 +805,7 @@ test('a malformed slot reference does not strand the other explicitly delegated
|
||||
]});
|
||||
while(actions.active)await actions.await_image_slots({});
|
||||
await actions.close();
|
||||
assert.deepEqual(requests,[['lamp-full','实拍全景'],['lamp-switch','实拍开关']]);
|
||||
assert.deepEqual(requests.sort(([left],[right])=>left.localeCompare(right)),[['lamp-full','实拍全景'],['lamp-switch','实拍开关']]);
|
||||
assert.deepEqual(result.assigned,[
|
||||
{id:'lamp-full',state:'assigned',...drawStatus(0)},
|
||||
{id:'lamp-switch',state:'assigned',...drawStatus(0)},
|
||||
@ -970,6 +916,7 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie
|
||||
imageBridge(host,async args=>{requests.push(args);return {status:'complete'};},()=> 'replacement');
|
||||
const ops=await openProductionOperations(host);
|
||||
await ops.delegate_image_slots({jobs:[{slotId:'front',goal:'改掉多余支撑',reworkCandidateId:'old'}]});
|
||||
while(ops.active)await ops.await_image_slots({slotIds:['front']});
|
||||
const {generation:[result]}=await ops.await_image_slots({slotIds:['front']});
|
||||
assert.equal(delegated,true);
|
||||
assert.equal(result.phase,'complete');
|
||||
@ -1612,14 +1559,14 @@ test('worker progress shares a number with delegated image dispatch and reuses r
|
||||
await imageRelease.promise;
|
||||
return {status:'complete',id:requestId};
|
||||
});
|
||||
const actions=await openProductionOperations(host);
|
||||
const actions=await openProductionOperations(host,{maxActiveDelegates:5});
|
||||
await actions.write_copy_fields({revision:1,recordOnly:true,items:[
|
||||
{layer:9,text:'露出实木榫接',sources:['P01'],pictures:[first.fieldId]},
|
||||
]});
|
||||
await actions.delegate_image_slots({jobs:slots.slice(0,5).map(slot=>({slotId:slot.id,goal:'展示榫接结构'}))});
|
||||
assert.deepEqual((await started.promise).workers.map(row=>row.number),[1,2,3,4,5]);
|
||||
assert.equal(prompts.find(row=>row.slot===first.id).screenCopy[0].text,'露出实木榫接');
|
||||
assert.match(prompts[0].instructions,/goal 和 screenCopy.*模板原图.*本款实拍/u);
|
||||
assert.match(prompts[0].instructions,/goal 是本次任务,screenCopy 是画布实时文案/u);
|
||||
assert.deepEqual(prompts.find(row=>row.slot===others[0].id).screenCopy,[]);
|
||||
preparation.resolve();
|
||||
const active=(await generating.promise).workers;
|
||||
@ -1634,6 +1581,7 @@ test('worker progress shares a number with delegated image dispatch and reuses r
|
||||
assert.equal((await checking.promise).reviews[0].number,7);
|
||||
reviewRelease.resolve();
|
||||
assert.deepEqual((await reviewed.promise).reviews,[]);
|
||||
assert.equal((await actions.review_image_slots({slotIds:[first.id]})).pictures[0].working,true);
|
||||
workerRelease.resolve();
|
||||
imageRelease.resolve();
|
||||
while(actions.active)await actions.await_image_slots({});
|
||||
@ -1864,7 +1812,7 @@ test('copy writes reuse confirmed revisions and rebase only unchanged, previousl
|
||||
await ops.close();
|
||||
});
|
||||
|
||||
test('the fourth draw occupies the last slot while in flight and a rejected batch candidate can still be exported',async t=>{
|
||||
test('the fourth draw occupies the last slot while 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);
|
||||
@ -1930,14 +1878,15 @@ test('the fourth draw occupies the last slot while in flight and a rejected batc
|
||||
assertStatus((await plan()).pictures[0],drawStatus(1));
|
||||
const input={slotId:'hero',prompt:'同款正面'};
|
||||
const a=await ops.prepare_image_request(input);
|
||||
const b=await ops.prepare_image_request({...input,candidateSetId:a.candidateSet.id});
|
||||
await Promise.all([ops.dispatch_image_request(approve(a)),ops.dispatch_image_request(approve(b))]);
|
||||
await ops.await_image_slots({slotIds:['hero']});
|
||||
const b=await ops.prepare_image_request({...input,prompt:'同款侧面'});
|
||||
await ops.dispatch_image_request(approve(a));
|
||||
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));
|
||||
|
||||
const fourth=await ops.prepare_image_request(input);
|
||||
spare=await ops.prepare_image_request(input);
|
||||
const fourth=await ops.prepare_image_request({...input,prompt:'同款俯拍'});
|
||||
spare=await ops.prepare_image_request({...input,prompt:'同款低机位'});
|
||||
assert.equal(fourth.candidateSet,undefined);
|
||||
assert.equal((await ops.dispatch_image_request(approve(fourth))).phase,'accepted');
|
||||
await fourthStarted.promise;
|
||||
|
||||
@ -7,7 +7,7 @@ import os from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
import { ProductionRequestPending, recoverProductionResponse } from '../src/production-recovery.mjs';
|
||||
import { recoverProductionResponse } from '../src/production-recovery.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
|
||||
const setup = async () => {
|
||||
@ -133,12 +133,11 @@ test('a waiting detail original does not hold independent main image and SKU goa
|
||||
assert.ok(offered.every(row=>row.id!==originalId));
|
||||
});
|
||||
|
||||
test('DeepSeek Flash 1017 can receive a named strategy tool and product image with thinking disabled', async t => {
|
||||
test('DeepSeek Flash 1017 can receive an optional strategy tool and product image with thinking disabled', async t => {
|
||||
const { root, scope, store } = await setup();
|
||||
t.after(() => cleanup(root));
|
||||
const model = { id: 'deepseek-v4.1-flash-1017', protocol: 'openai-chat', supportsImageInput: true };
|
||||
const responses = [];
|
||||
const activity = [];
|
||||
const toolName = 'save_product_strategy';
|
||||
const broker = {
|
||||
info: async () => ({ accountScope: scope, model, pending: [] }),
|
||||
@ -159,8 +158,7 @@ test('DeepSeek Flash 1017 can receive a named strategy tool and product image wi
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const canvas = { run:'strategy-run', read: async () => ({ conversationActive: true, revision: 1 }),
|
||||
activity: async (_summary,event) => activity.push(event) };
|
||||
const canvas = { run:'strategy-run', read: async () => ({ conversationActive: true, revision: 1 }) };
|
||||
const host = await DetailPiAgent.open({ store, broker, canvas });
|
||||
try {
|
||||
host.activityScope = {run:canvas.run};
|
||||
@ -171,16 +169,13 @@ test('DeepSeek Flash 1017 can receive a named strategy tool and product image wi
|
||||
assert.equal(args.evidence, 'P01');
|
||||
return { content: [{ type: 'text', text: '已保存' }], details: {}, terminate: true };
|
||||
},
|
||||
}], [{ type: 'image', mimeType: 'image/png', data: 'UE5H' }], 'product/strategy/' + randomUUID());
|
||||
}], [{ type: 'image', mimeType: 'image/png', data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==' }], 'product/strategy/' + randomUUID());
|
||||
assert.equal(responses.length, 1);
|
||||
assert.deepEqual(activity.map(({toolName,status})=>[toolName,status]),
|
||||
[[toolName,'started'],[toolName,'completed']]);
|
||||
assert.ok(activity.every(event=>!JSON.stringify(event).includes('P01')));
|
||||
const [body] = responses;
|
||||
assert.equal(body.thinking,undefined);
|
||||
assert.deepEqual(body.tool_choice, { type: 'function', function: { name: toolName } });
|
||||
assert.equal(body.tool_choice??'auto','auto');
|
||||
assert.ok(body.messages.some(message => Array.isArray(message.content) &&
|
||||
message.content.some(part => part.image_url?.url === 'data:image/png;base64,UE5H')));
|
||||
message.content.some(part => part.image_url?.url === 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==')));
|
||||
} finally {
|
||||
await host.dispose();
|
||||
}
|
||||
@ -330,7 +325,7 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
|
||||
fetch:async(_url,init)=>{
|
||||
const body=JSON.parse(init.body);
|
||||
sent.push(body);
|
||||
if(body.tool_choice?.type!=='auto')return new Response('{"type":"error","error":{"type":"invalid_request_error","message":"forced tool use is unsupported"}}',
|
||||
if(body.tool_choice&&body.tool_choice.type!=='auto')return new Response('{"type":"error","error":{"type":"invalid_request_error","message":"forced tool use is unsupported"}}',
|
||||
{status:400,headers:{'content-type':'application/json'}});
|
||||
return new Response(events(body.tools[0].name).map(event=>'event: '+event.type+'\ndata: '+JSON.stringify(event)+'\n\n').join(''),
|
||||
{headers:{'content-type':'text/event-stream'}});
|
||||
@ -358,7 +353,7 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
|
||||
executed++;
|
||||
return {content:[{type:'text',text:'已保存'}],terminate:true};
|
||||
},
|
||||
}],[{type:'image',mimeType:'image/png',data:'UE5H'}],requestScope);
|
||||
}],[{type:'image',mimeType:'image/png',data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='}],requestScope);
|
||||
}
|
||||
assert.equal(executed,cases.length);
|
||||
assert.equal(sent.length,cases.length);
|
||||
@ -366,8 +361,8 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
|
||||
assert.equal(sent[0].output_config,undefined);
|
||||
for(const body of sent){
|
||||
assert.equal(body.max_tokens,128000);
|
||||
assert.deepEqual(body.tool_choice,{type:'auto'});
|
||||
assert.ok(body.messages.some(message=>message.content.some(block=>block.type==='image'&&block.source.data==='UE5H')));
|
||||
assert.equal(body.tool_choice?.type??'auto','auto');
|
||||
assert.ok(body.messages.some(message=>message.content.some(block=>block.type==='image'&&block.source.data==='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==')));
|
||||
}
|
||||
} finally {
|
||||
await host.dispose();
|
||||
|
||||
@ -26,7 +26,7 @@ async function fixture(t) {
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-screen-review-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
const pages=Array.from({length:8},(_,i)=>`P${i+1}`);
|
||||
const pages=Array.from({length:18},(_,i)=>`P${i+1}`);
|
||||
const fields=pages.map((page,i)=>({page,layer:100+i,field:`title-${i+1}`,currentText:'橡胶木桌面'}));
|
||||
const slots=pages.map((documentId,i)=>({documentId,id:`slot-${i+1}`,fieldId:`pic-${i+1}`,selectedCandidateId:'candidate'}));
|
||||
const state={revision:7,overlay:true,reads:[],referenceReads:0};
|
||||
@ -66,17 +66,19 @@ test('screen reviews keep images in the worker and record only the verified scre
|
||||
assert.equal(screenCopy[0].field,`title-${page}`);
|
||||
assert.equal(slots[0].id,`slot-${page}`);
|
||||
assert.deepEqual(images,[pixels,pixels]);
|
||||
assert.match(system,/尺寸线、虚线轮廓、引线、标注文字和装饰角标/);
|
||||
assert.match(system,/nativeLayerId[^。]*移动、缩放、隐藏或改写叠层/);
|
||||
assert.match(system,/write_copy_fields[^。]*transform_slot_image[^。]*重新生图/);
|
||||
assert.equal(tool.execute('',page===1?pass:needsFix).terminate,true);
|
||||
assert.match(system,/overlayLayers 中的 nativeLayerId/);
|
||||
assert.equal(tool.execute('',page===1?pass:{...needsFix,
|
||||
imageIssues:needsFix.imageIssues.map(issue=>({...issue,slotId:slots[0].id})),
|
||||
overlayFixes:needsFix.overlayFixes.map(fix=>({...fix,nativeLayerId:200+page})),
|
||||
copyFixes:needsFix.copyFixes.map(fix=>({...fix,field:`title-${page}`}))}).terminate,true);
|
||||
};
|
||||
const receipts=await callProductionTool(host,'check_output_screens',{pages:[1,2,2,16]});
|
||||
const receipts=await callProductionTool(host,'check_output_screens',{pages:[1,2,2,17,19]});
|
||||
assert.deepEqual(receipts,[
|
||||
{page:1,revision:7,...pass},{page:2,revision:7,...needsFix},
|
||||
{page:16,error:'此屏不属于当前工作画布'},
|
||||
{page:17,revision:7,...needsFix,imageIssues:[{...needsFix.imageIssues[0],slotId:'slot-17'}],
|
||||
overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:217}],copyFixes:[{...needsFix.copyFixes[0],field:'title-17'}]},{page:19,error:'此屏不属于当前工作画布'},
|
||||
]);
|
||||
assert.deepEqual(state.reads,[0,1,15]);
|
||||
assert.deepEqual(state.reads,[0,1,16]);
|
||||
assert.equal(state.referenceReads,1);
|
||||
assert.ok(!JSON.stringify(receipts).includes(pixels.data));
|
||||
assert.deepEqual(journal().screenReviews.map(([page,row])=>[page,row.revision,row.issues,row.copyTexts]),
|
||||
@ -158,7 +160,7 @@ test('screen reviews share the six-worker queue and expose asynchronous receipts
|
||||
|
||||
test('screen review refuses unsupported evidence, invalid targets and stale passes',async t=>{
|
||||
const {host,actions,state,journal}=await fixture(t);
|
||||
for(const pages of [[],[0],[17],[1.5],[1,NaN],Array(17).fill(1)]){
|
||||
for(const pages of [[],[0],[1.5],[1,NaN]]){
|
||||
await assert.rejects(actions.check_output_screens({pages}),/有效屏号/);
|
||||
}
|
||||
assert.deepEqual(state.reads,[]);
|
||||
@ -181,8 +183,8 @@ test('screen review refuses unsupported evidence, invalid targets and stale pass
|
||||
|
||||
test('screen review tool schema and activity expose the public contract',()=>{
|
||||
const [,description,schema]=productionOperationTools.find(([name])=>name==='check_output_screens');
|
||||
assert.equal(Value.Check(schema,{pages:[1,16]}),true);
|
||||
for(const args of [{pages:[0]},{pages:[17]},{pages:[]},{pages:['1']},{pages:[2],wait:'false'}]){
|
||||
assert.equal(Value.Check(schema,{pages:[1,17]}),true);
|
||||
for(const args of [{pages:[0]},{pages:[]},{pages:['1']},{pages:[2],wait:'false'}]){
|
||||
assert.equal(Value.Check(schema,args),false);
|
||||
}
|
||||
assert.match(description,/默认等待结论/);
|
||||
@ -193,10 +195,10 @@ test('screen review tool schema and activity expose the public contract',()=>{
|
||||
phase:'started',category:'inference',timestampMs:123,scope:{}});
|
||||
});
|
||||
|
||||
test('a reopened canvas reports unresolved model requests for its own screens',async t=>{
|
||||
test('a reopened canvas can finish with historical screen inference records',async t=>{
|
||||
const {host,actions}=await fixture(t);
|
||||
const detailSlot=screenReviewScope(variantId,outputId,2);
|
||||
const other=screenReviewScope(variantId,'main_images',2);
|
||||
const detailSlot=screenReviewScope(variantId,outputId,17);
|
||||
const other=screenReviewScope(variantId,'main_images',17);
|
||||
assert.notEqual(detailSlot,other);
|
||||
assert.notEqual(detailSlot,screenReviewScope(variantId,outputId,1));
|
||||
assert.notEqual(detailSlot,screenReviewScope('walnut',outputId,2));
|
||||
@ -204,5 +206,6 @@ test('a reopened canvas reports unresolved model requests for its own screens',a
|
||||
{modelRole:'detail',detailSlot,id:'existing-request'},
|
||||
{modelRole:'detail',detailSlot:other,id:'different-output'},
|
||||
]})};
|
||||
assert.deepEqual((await actions.unfinished()).originals,{models:['existing-request'],images:[]});
|
||||
assert.deepEqual(await actions.unfinished(),{outputId,variantId,complete:false,stageStatus:'continue'});
|
||||
assert.equal((await actions.finish_production({revision:7})).production.complete,true);
|
||||
});
|
||||
|
||||
@ -41,7 +41,7 @@ test('both conversation prompts and delegated production share the product voice
|
||||
const prompt = agent.match(new RegExp('const ' + name + ' = `([\\s\\S]+?)`;'))?.[1];
|
||||
assert.ok(prompt?.includes('${PRODUCT_VOICE}'), name);
|
||||
}
|
||||
assert.match(agent, /initialState:\{model,systemPrompt:systemPrompt\+"\\n"\+PRODUCT_VOICE/);
|
||||
assert.match(agent, /systemPrompt:systemPrompt\+'\\n'\+PRODUCT_VOICE/);
|
||||
assert.match(agent, /对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」/);
|
||||
assert.match(agent, /不得向用户暴露底层技术或开源底座名称/);
|
||||
});
|
||||
@ -66,23 +66,19 @@ test('production review guidance covers copy, images and overlays followed by vi
|
||||
assert.match(adopt, /放置回执|返回画布修订和覆盖该图位的模板叠层/);
|
||||
assert.match(adopt, /read_output_screen 查看整屏合成画面/);
|
||||
const review = productionTools.find(([tool]) => tool === 'check_output_screens')?.[1];
|
||||
assert.match(review, /整屏合成画面[^]*叠层错位、压字或数值不符/);
|
||||
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[^。]*不能传模板编号/);
|
||||
for (const guidance of ['IMAGE_COPY_CRITERIA', 'COPY_IMAGE_REVIEW_GUIDANCE']) {
|
||||
assert.match(source('copy-image-alignment.mjs'), new RegExp(guidance + '=[^\\n]*WOOD_FINISH_GUIDANCE'));
|
||||
}
|
||||
assert.match(source('copy-image-alignment.mjs'), /木材纹理、色泽深浅和涂装观感[^。]*木种与颜色文案[^]*深木色来自涂装/);
|
||||
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'), /关联文案 copy[^。]*图文一致性。[^。]*材质、颜色、款式和结构[^。]*SKU 花色/);
|
||||
assert.match(source('candidate-review.mjs'), /read_production_knowledge[^。]*企业 Skill 和审稿规则/);
|
||||
});
|
||||
|
||||
test('native tooling and production share the documented canvas commands', () => {
|
||||
|
||||
@ -800,8 +800,9 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
}
|
||||
let id = uuid(&input, "id")?;
|
||||
let file = dir.join(format!("{id}.json"));
|
||||
let inference = method == "request" && input["inference"] == true;
|
||||
if method == "request" {
|
||||
if file.try_exists().map_err(|_| "本机原请求记录无法核对")? {
|
||||
if !inference && file.try_exists().map_err(|_| "本机原请求记录无法核对")? {
|
||||
return Err("原请求待核查或已提交,禁止重发".into());
|
||||
}
|
||||
*new_request_preflight = true;
|
||||
@ -858,6 +859,9 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
}
|
||||
};
|
||||
let key = settings["key"].as_str().ok_or("个人Key缺失")?;
|
||||
let persist = |task: &Value| -> R<()> {
|
||||
if inference { Ok(()) } else { write_task(&file, task) }
|
||||
};
|
||||
let lookup = |task: &mut Value| {
|
||||
lookup_original(task, |path, original_id| {
|
||||
let response = backend.http.get(format!("{UPSTREAM}{path}"))
|
||||
@ -891,12 +895,12 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
} else {
|
||||
let native = backend.dir().join("projects").join(&project);
|
||||
let scoped = scoped_production_request(&input);
|
||||
if !scoped && (super::creation::unresolved(&native)? || super::images::pending(&native)?) {
|
||||
if !inference && !scoped && (super::creation::unresolved(&native)? || super::images::pending(&native)?) {
|
||||
return Err("原创作或生图请求待核查,禁止从Agent重新派发".into());
|
||||
}
|
||||
let detail_slot = input.get("detailSlot").map(|slot| slot.as_str().filter(|slot| !slot.is_empty() && slot.len() <= 240 && !slot.chars().any(char::is_control)).ok_or("详情页图位身份无效")).transpose()?;
|
||||
let retry_of = input.get("retryOf").map(|_| uuid(&input, "retryOf")).transpose()?;
|
||||
if request_conflicts(&unresolved(&dir)?, detail_slot, scoped, retry_of.as_deref()) {
|
||||
if !inference && request_conflicts(&unresolved(&dir)?, detail_slot, scoped, retry_of.as_deref()) {
|
||||
return Err("原请求待核查或已提交,禁止重发".into());
|
||||
}
|
||||
let payload = input["body"].as_str().filter(|s| s.len() <= LIMIT).ok_or("模型输入过大")?;
|
||||
@ -908,13 +912,14 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
let headers = invocation_headers(&input)?;
|
||||
let model_path = model["path"].as_str().ok_or("模型路径无效")?;
|
||||
let timeout = Duration::from_secs(600);
|
||||
task = json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers,"selectionSource":selection_source,"inference":input["inference"] == true,"timeoutMs":timeout.as_millis() as u64});
|
||||
task = if inference { json!({"requestId":null}) } else {
|
||||
json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers,"selectionSource":selection_source,"timeoutMs":timeout.as_millis() as u64})
|
||||
};
|
||||
if let Some(original) = retry_of {
|
||||
task["retryOf"] = json!(original);
|
||||
}
|
||||
// Durable dispatch barrier BEFORE the POST.
|
||||
*new_request_preflight = false;
|
||||
write_task(&file, &task)?;
|
||||
persist(&task)?;
|
||||
let mut request = backend
|
||||
.http
|
||||
.post(format!("{UPSTREAM}{model_path}"))
|
||||
@ -932,7 +937,7 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
}
|
||||
if let Err(error) = check_dispatch_lease(&input["dispatchLease"]) {
|
||||
task["phase"] = json!("not_dispatched");
|
||||
write_task(&file, &task)?;
|
||||
persist(&task)?;
|
||||
*new_request_preflight = true;
|
||||
return Err(error);
|
||||
}
|
||||
@ -940,10 +945,10 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
};
|
||||
let mut raw = Vec::new();
|
||||
let result = (|| -> R<()> {
|
||||
let mut response = response.map_err(|_| "98k连接中断,结果未知;不会重发")?;
|
||||
let mut response = response.map_err(|_| if inference { "98k连接中断" } else { "98k连接中断,结果未知;不会重发" })?;
|
||||
if let Some(request) = response.headers().get("x-request-id").and_then(|s| s.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) {
|
||||
record_request_header(&mut task, method, request);
|
||||
write_task(&file, &task)?;
|
||||
persist(&task)?;
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
if method == "request" && matches!(status, 401 | 403) {
|
||||
@ -955,12 +960,12 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
}
|
||||
let content_type = response.headers().get("content-type").and_then(|s| s.to_str().ok()).unwrap_or("application/octet-stream").to_owned();
|
||||
response_metadata(&mut task, method, status, &content_type);
|
||||
write_task(&file, &task)?;
|
||||
persist(&task)?;
|
||||
if status == 401 {
|
||||
if method == "request" {
|
||||
task["phase"] = json!("failed");
|
||||
task["failureCode"] = json!("auth_revoked");
|
||||
write_task(&file, &task)?;
|
||||
persist(&task)?;
|
||||
}
|
||||
emit(json!({"type":"headers","status":401,"headers":{"content-type":"application/json"},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?;
|
||||
// Refresh the model authorization catalogue for a subsequent turn.
|
||||
@ -971,14 +976,19 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
emit(json!({"type":"headers","status":status,"headers":{"content-type":content_type},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?;
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let n = response.read(&mut chunk).map_err(|_| "98k响应中断,结果未知;不会重发")?;
|
||||
let n = response.read(&mut chunk).map_err(|_| if inference { "98k响应中断" } else { "98k响应中断,结果未知;不会重发" })?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
let part = chunk.get(..n).ok_or("响应长度无效")?;
|
||||
append_response(&mut raw, part)?;
|
||||
if !inference {
|
||||
append_response(&mut raw, part)?;
|
||||
}
|
||||
emit(json!({"type":"chunk","data":STANDARD.encode(part)}))?;
|
||||
}
|
||||
if inference {
|
||||
return emit(json!({"type":"result","value":{"phase":"complete","requestId":task["requestId"]}}));
|
||||
}
|
||||
transfer::check_wire(&raw)?;
|
||||
let text = std::str::from_utf8(&raw).map_err(|_| "98k响应编码无效,结果未知;不会重发")?;
|
||||
if method == "recover" {
|
||||
@ -1033,6 +1043,7 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
emit(json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"bodyHash":task["bodyHash"]}}))
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
if inference { return Err(e); }
|
||||
if matches!(task["phase"].as_str(), Some("failed" | "unavailable"))
|
||||
&& (checked_lookup(&task).is_ok() || task["failureCode"] == "rate_limit_exceeded" || task["failureCode"] == "auth_revoked") {
|
||||
// The proof and outcome already landed. A broken SDK output pipe
|
||||
|
||||
@ -393,8 +393,8 @@ pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::S
|
||||
if input["context"]["requestScope"]["productProduction"] == true {
|
||||
log::warn!("local product stage stopped for document {doc}: {error}");
|
||||
}
|
||||
let pending = b.locations.get(&doc).map(|project| super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))).transpose();
|
||||
let unknown = pending.as_ref().map_or(true, |p| p.as_ref().is_some_and(|p| !p.is_empty()));
|
||||
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});
|
||||
super::transfer::redact(&mut reply);
|
||||
@ -931,8 +931,10 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
result["origin"] = json!(b.origin);
|
||||
result["mode"] = json!(mode);
|
||||
result["contextUsage"] = super::context_usage::read(b, &dir, &project);
|
||||
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));
|
||||
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) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user