Merge T2: native Pi schemas, model switch, steer, recovery

This commit is contained in:
WuYongJie 2026-12-02 18:52:23 +08:00
commit d64dc3187f
25 changed files with 1140 additions and 309 deletions

View File

@ -5,16 +5,16 @@ import { executeWorkflow } from './workflow-execute.mjs';
import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
import path from 'node:path';
import fs from 'node:fs/promises';
import lockfile from 'proper-lockfile';
import { createHash, randomUUID } from 'node:crypto';
import { Type } from '@sinclair/typebox';
import { productionLedger } from './production-repository.mjs';
import { CanvasOperations } from './canvas-operations.mjs';
import { BridgeError } from './bridge-error.mjs';
import { protectSession, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, piGoalState, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
import { protectSession, redact, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, lockProjectSession, piGoalState, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
import { productionVideoTools } from './production-operations.mjs';
import { createAgentSession, DEFAULT_COMPACTION_SETTINGS, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
import { getSupportedThinkingLevels } from '@earendil-works/pi-ai';
import { getSupportedThinkingLevels, StringEnum } from '@earendil-works/pi-ai';
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
import { atomic } from './store.mjs';
import { workerTurnBudget } from './worker-receipts.mjs';
@ -43,12 +43,125 @@ const protocolBaseUrl = protocol => protocol === 'anthropic-messages' ? 'https:/
const authorizedCandidates = candidates => (candidates ?? []).filter(route =>
Object.hasOwn(protocolPaths,route.protocol) && route.path === protocolPaths[route.protocol]);
function thinkingMap(efforts, fallback) {
if (!efforts?.length) return fallback;
if (!efforts?.length) return fallback && {...fallback,off:fallback.off ?? 'off'};
return Object.fromEntries(['off','minimal','low','medium','high','xhigh','max'].map(level=>[
level,efforts.includes(level)?level:level==='minimal'&&efforts.includes('low')?'low':null,
level,level==='off'||efforts.includes(level)?level:level==='minimal'&&efforts.includes('low')?'low':null,
]));
}
const catalogProviders = ['anthropic','openai','openai-codex','google','xai','deepseek','openrouter'];
function catalogModel(runtime, id, api) {
const models = catalogProviders.map(provider=>runtime.getModel(provider,id)).filter(Boolean);
return models.find(model=>model.api===api) ?? models[0];
}
function limitChatToolIds(payload) {
const shorten = id => /^[\w-]{1,40}$/.test(id) ? id :
id.slice(0,23).replace(/[^\w-]/g,'_') + '_' + createHash('sha256').update(id).digest('hex').slice(0,16);
for (const message of payload.messages) {
if (message.tool_call_id) message.tool_call_id = shorten(message.tool_call_id);
for (const call of message.tool_calls ?? []) call.id = shorten(call.id);
}
}
function sessionFilename(file) {
if (typeof file !== 'string') return null;
const parts = file.split(/[\\/]/);
const name = parts.at(-1);
return !parts.includes('..') && /^[\w.-]+\.jsonl$/i.test(name) ? name : null;
}
async function restoreSession(store) {
const sessionDir = path.join(store.dir,'sessions');
const pointer = path.join(store.dir,'session.json');
let saved, invalidPointer = false;
try {
saved = JSON.parse(await fs.readFile(pointer,'utf8'));
invalidPointer = !sessionFilename(saved?.file);
} catch (error) {
if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error;
invalidPointer = error instanceof SyntaxError;
}
if (invalidPointer) await fs.rename(pointer, pointer + '.corrupt-' + randomUUID());
let name = sessionFilename(saved?.file);
if (invalidPointer) {
const files = await fs.readdir(sessionDir,{withFileTypes:true}).catch(error=>{
if (error.code === 'ENOENT') return [];
throw error;
});
const sessions = await Promise.all(files.filter(file=>file.isFile() && sessionFilename(file.name))
.map(async file=>({name:file.name,modified:(await fs.stat(path.join(sessionDir,file.name))).mtimeMs})));
name = sessions.sort((a,b)=>b.modified-a.modified)[0]?.name;
}
if (!name) return SessionManager.create(store.dir,sessionDir);
const file = path.join(sessionDir,name);
const stat = await fs.lstat(file).catch(error=>{ if (error.code !== 'ENOENT') throw error; });
if (!stat?.isFile()) return SessionManager.create(store.dir,sessionDir);
const raw = await fs.readFile(file,'utf8');
const lines = raw.trimEnd().split('\n');
const parse = line => {
try { return JSON.parse(line); } catch (error) { if (!(error instanceof SyntaxError)) throw error; }
};
const header = parse(lines[0]);
if (header?.type !== 'session' || typeof header.id !== 'string') {
await fs.rename(file,file+'.corrupt-'+randomUUID());
return SessionManager.create(store.dir,sessionDir);
}
let end = lines.length;
while (end > 1) {
const entry = parse(lines[end-1]);
if (typeof entry?.type === 'string' && typeof entry.id === 'string' &&
(entry.type !== 'message' || typeof entry.message?.role === 'string')) break;
end--;
}
if (end !== lines.length || !raw.endsWith('\n')) {
const backup = file + '.corrupt-' + randomUUID();
if (end !== lines.length) await fs.writeFile(backup,lines.slice(end).join('\n'),{flag:'wx',mode:0o600});
const repair = file + '.repair-' + randomUUID();
try {
await fs.writeFile(repair,lines.slice(0,end).join('\n')+'\n',{flag:'wx',mode:0o600});
await fs.rename(repair,file);
} finally {
await fs.unlink(repair).catch(error=>{ if (error.code !== 'ENOENT') throw error; });
}
}
const manager = SessionManager.open(file,sessionDir,store.dir);
const messages = manager.buildSessionContext().messages;
const lastAssistant = messages.findLastIndex(message=>message.role==='assistant');
if (lastAssistant >= 0 && !messages.slice(lastAssistant+1).some(message=>message.role==='user')) {
const results = new Set(messages.slice(lastAssistant+1).filter(message=>message.role==='toolResult').map(message=>message.toolCallId));
for (const call of messages[lastAssistant].content) {
if (call.type !== 'toolCall' || results.has(call.id)) continue;
manager.appendMessage({role:'toolResult',toolCallId:call.id,toolName:call.name,isError:true,timestamp:Date.now(),
content:[{type:'text',text:'会话中断前未保存工具回执。原操作状态未知,请按原请求核查。'}]});
results.add(call.id);
}
}
if (invalidPointer) await atomic(pointer,{file});
return manager;
}
const referenceMarker = '\n\n本条消息附带的画布引用(按图片顺序对应,以下文字为引用内容):';
function referencedPrompt(text, referenceContent) {
const images = [], quoted = [];
for (const item of referenceContent ?? []) {
let image;
if (typeof item.image === 'string' && item.image) {
images.push({ type:'image',data:item.image,mimeType:item.mimeType??'image/jpeg' });
image = images.length;
}
const source = item.source ?? (item.kind === 'candidate' ? '候选图' : item.kind === 'layer' ? '发送时的画布图层' : '本轮引用');
const entry = { label: item.label, source, ...(image ? { image } : {}), ...(typeof item.text === 'string' ? { text: item.text } : {}) };
for (const key of ['kind', 'nativeLayerId', 'component', 'layerKind', 'slotId', 'fieldId', 'candidateId',
'taskId', 'outputId', 'productVariantId', 'documentId', 'status']) {
if (item[key] != null) entry[key] = item[key];
}
quoted.push(entry);
}
const prompt = quoted.length ? text + referenceMarker + JSON.stringify(redact(quoted)) : text;
return {prompt,images,quoted};
}
const COMPACTION_FACTS = `压缩摘要用于继续当前工作。合并旧摘要和本次记录,保留仍有效的事实及其原始编号:
- 在途及已付费的出图请求号、候选号、各图位状态和各图位已采用的候选。
- 已做的决定及理由,以及未解决的问题。
@ -172,8 +285,8 @@ function toolsFor(host) {
const string = maxLength => Type.String({ maxLength });
const commands = nativeTools(host, make);
const contextTools = [
make('context_read', '按需读取当前项目规则。未指定topic返回当前任务必需规则;brand为品牌细节、template为模板模块、sources为来源。普通问答涉及企业知识库或模板规则时,先用此工具取依据。', Type.Object({ topic: Type.Optional(Type.Union([Type.Literal('brand'), Type.Literal('template'), Type.Literal('sources')])) }, { additionalProperties: false }), args => host.modelContext(args, {loadKnowledge:true})),
make('memory_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }), args => host.store.remember(args)),
make('context_read', '按需读取当前项目规则。未指定topic返回当前任务必需规则;brand为品牌细节、template为模板模块、sources为来源。普通问答涉及企业知识库或模板规则时,先用此工具取依据。', Type.Object({ topic: Type.Optional(StringEnum(['brand', 'template', 'sources'])) }, { additionalProperties: false }), args => host.modelContext(args, {loadKnowledge:true})),
make('memory_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }, { additionalProperties: false }), args => host.store.remember(args)),
make('memory_search', '用 query 查本项目对话。用真实 toolCallId 读取工具回执或子代理失败原因,可用 offset 分段读取。回执无匹配时仍按 query 查询。', Type.Object({
query:Type.Optional(Type.String({maxLength:200})),
toolCallId:Type.Optional(Type.String()),
@ -202,7 +315,7 @@ function toolsFor(host) {
const outputName = Type.String({ minLength: 1 });
const outputId = Type.Optional(outputName);
const workflowRead = make('workflow_read', '读取当前创作工作流、实时版本及资料摘要;section按需读取,原图片和长提示词不会进入摘要。', Type.Object({
section: Type.Optional(Type.Union(['overview', 'materials', 'points', 'plan', 'slots'].map(value => Type.Literal(value)))),
section: Type.Optional(StringEnum(['overview', 'materials', 'points', 'plan', 'slots'])),
outputId, offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 300 })),
}, { additionalProperties: false }), args => host.readWorkflow(args));
if (host.productionGoal) return [
@ -211,7 +324,7 @@ function toolsFor(host) {
];
const tools = [
...contextTools, ...productionKit, canvasRead, workflowRead,
make('canvas_edit', '一次修改现有图层,共享本机撤销历史。revision须等于刚读取的版本。支持type.edit/layer.translate/layer.setProps,参数沿用原生画布。', Type.Object({ revision: Type.Integer({ minimum: 0 }), command: Type.Union([Type.Literal('type.edit'), Type.Literal('layer.translate'), Type.Literal('layer.setProps')]), params: Type.Object({ layer: Type.Integer({ minimum: 1 }), text: Type.Optional(string(3000)), size: Type.Optional(Type.Number({ minimum: 8, maximum: 240 })), color: Type.Optional(Type.String({ pattern: '^#[0-9a-fA-F]{6}$' })), name: Type.Optional(string(120)), dx: Type.Optional(Type.Integer({ minimum: -3000, maximum: 3000 })), dy: Type.Optional(Type.Integer({ minimum: -3000, maximum: 3000 })), opacity: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })), visible: Type.Optional(Type.Boolean()) }, { additionalProperties: false }), label: Type.String({ minLength: 1, maxLength: 120 }) }), ({ revision, ...edit }, signal) => {
make('canvas_edit', '一次修改现有图层,共享本机撤销历史。revision须等于刚读取的版本。支持type.edit/layer.translate/layer.setProps,参数沿用原生画布。', Type.Object({ revision: Type.Integer({ minimum: 0 }), command: StringEnum(['type.edit', 'layer.translate', 'layer.setProps']), params: Type.Object({ layer: Type.Integer({ minimum: 1 }), text: Type.Optional(string(3000)), size: Type.Optional(Type.Number({ minimum: 8, maximum: 240 })), color: Type.Optional(Type.String({ pattern: '^#[0-9a-fA-F]{6}$' })), name: Type.Optional(string(120)), dx: Type.Optional(Type.Integer({ minimum: -3000, maximum: 3000 })), dy: Type.Optional(Type.Integer({ minimum: -3000, maximum: 3000 })), opacity: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })), visible: Type.Optional(Type.Boolean()) }, { additionalProperties: false }), label: Type.String({ minLength: 1, maxLength: 120 }) }, { additionalProperties: false }), ({ revision, ...edit }, signal) => {
if (host.canvasOperations.active || host.canvasOperations.pending.some(op => op.kind !== 'workflow')) throw Error('原操作尚未确认,先核查原请求;可使用 native_reconcile 只读核查,不会重发');
const epoch = host.turnEpoch, run = host.canvas.run, documentId = host.canvas.documentId, owner = Symbol('canvas edit');
const identity = {scope:host.store.identity?.scope, project:host.store.identity?.project, accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin};
@ -293,6 +406,7 @@ function toolsFor(host) {
}),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'});
tools.push({ ...make('canvas_preview', '在原生界面预览当前图层修改,等用户采纳才应用。宿主先读取真实目标并绑定当前版本,无需填写revision。type.edit替换文案须传params.text;超出模板文字格限制时由原生输入等待用户缩短或取消,不放宽模板。只传本命令支持的参数,其他命令可先查native_catalog。保留未要求改变的字体、字号、位置和其他图层。', previewParameters, async (args, signal, ctx) => {
if (host.canvasNotificationsDetached) throw Error('原项目已切换,未生成预览');
if (Object.keys(args.params).length < 2) throw Error('请指定要预览的图层修改');
let read=await previewTarget(host,args.params.layer,signal);
let params={...args.params};
if(args.command==='type.edit'&&typeof params.text==='string') {
@ -325,14 +439,14 @@ function toolsFor(host) {
}), namespace:PHOTOCRAFT_NAMESPACE, exposure:'deferred' });
tools.push(make('workflow_navigate', '切换到当前项目的资料、卖点、方案、图位或画布视图。整套制作中,查看其它输出不会切换已绑定的制作画布。', Type.Object({
stage: Type.Union(['materials', 'points', 'plan', 'slots', 'canvas'].map(value => Type.Literal(value))), outputId,
stage: StringEnum(['materials', 'points', 'plan', 'slots', 'canvas']), outputId,
}, { additionalProperties: false }), async args => {
if (host.canvasNotificationsDetached) throw Error('当前项目已切换,未切换其他项目视图');
return workflowResult(await host.canvas.workflowNavigate(args));
}));
tools.push(make('workflow_execute', '在用户明确授权范围内执行当前画布模板的单个候选生成或明确候选采纳;version来自实时workflow_read,目标必须明确。等待原操作终态并刷新工作流;未知或中断不得重发。候选图像不可见时不能伪称视觉比较。', Type.Object({
version: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
intent: Type.Union([Type.Literal('generate_candidate'), Type.Literal('adopt_candidate')]),
intent: StringEnum(['generate_candidate', 'adopt_candidate']),
outputId: outputName,
slotId: Type.String({ minLength:1, maxLength:120 }), productVariantId: Type.String({ minLength:1, maxLength:120 }),
candidateId: Type.Optional(Type.String({ minLength:1, maxLength:120 })), instruction: Type.Optional(string(500)),
@ -342,8 +456,8 @@ function toolsFor(host) {
}));
tools.push(make('workflow_propose', '按实时version创建一张待执行操作,不自动执行。画布工作区generate_candidate指定slotId/productVariantId,candidateId可指定父版本;adopt_candidate明确采纳一个完成候选。旧项目的生成保留variant A/B兼容。export_psd导出成品分层副本。', Type.Object({
version: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
intent: Type.Union(['analyze', 'selling_points', 'plan', 'review_plan', 'install_template', 'slot_copy', 'apply_copy', 'generate_candidate', 'adopt_candidate', 'review_candidates', 'fill_output', 'export', 'export_psd'].map(value => Type.Literal(value))),
instruction: Type.Optional(string(500)), outputId, slotId: Type.Optional(string(120)), variant: Type.Optional(Type.Union([Type.Literal('A'), Type.Literal('B')])),productVariantId:Type.Optional(string(120)),candidateId:Type.Optional(string(120)),
intent: StringEnum(['analyze', 'selling_points', 'plan', 'review_plan', 'install_template', 'slot_copy', 'apply_copy', 'generate_candidate', 'adopt_candidate', 'review_candidates', 'fill_output', 'export', 'export_psd']),
instruction: Type.Optional(string(500)), outputId, slotId: Type.Optional(string(120)), variant: Type.Optional(StringEnum(['A', 'B'])),productVariantId:Type.Optional(string(120)),candidateId:Type.Optional(string(120)),
}, { additionalProperties: false }), async args => {
if (host.canvasNotificationsDetached) throw Error('当前项目已切换,未向其他项目添加建议');
const result = await host.canvas.workflowPropose(args);
@ -360,8 +474,10 @@ export class DetailPiAgent {
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, 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在运行,请等待当前任务结束;未发起新请求'); }
host.releaseLock = await lockProjectSession(store.root,error => {
host.compromised = error;
host.session?.agent.abort();
});
try {
const info = transport?.info ?? brokerInfo ?? await broker.info();
if (info.accountScope !== store.identity.scope) throw Error('模型账户与项目隔离域不一致');
@ -386,8 +502,6 @@ export class DetailPiAgent {
} : null;
canvas.identity = { accountId: info.accountId, origin: info.origin };
const runtime = await ModelRuntime.create({ authPath: path.join(store.dir, 'pi-runtime-auth.json'), modelsPath: null, modelsStorePath: path.join(store.dir, 'pi-model-cache'), refreshOnCreate: false, allowModelNetwork: false });
const protocol = info.model.protocol;
const api = modelApi(protocol);
const implementations = {
'anthropic-messages':anthropicMessagesApi(),
'openai-responses':openAIResponsesApi(),
@ -402,9 +516,6 @@ export class DetailPiAgent {
} else payload.tool_choice = route.protocol === 'anthropic-messages' ? {type:'tool',name} :
route.protocol === 'openai-responses' ? {type:'function',name} : {type:'function',function:{name}};
};
const known = runtime.getModel(api==='anthropic-messages'?'anthropic':'openai-codex', info.model.id);
const reasoning = info.model.reasoning === true;
const thinkingLevelMap = thinkingMap(info.model.reasoningEfforts,known?.thinkingLevelMap);
const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
const retry = {enabled:true,maxRetries:3};
// The main agent carries the run, so its waits of 3–60 s ride out a gateway outage of about
@ -423,177 +534,194 @@ export class DetailPiAgent {
...(failure ? {...failure,error:failure.message.slice(0,300)} : null),
});
};
runtime.registerProvider('jiansun-native-98k', {
api, apiKey: 'native-broker-only', baseUrl: protocolBaseUrl(protocol),
models: [{
id: info.model.id, name: info.model.id, api,
reasoning, ...(reasoning && thinkingLevelMap ? {thinkingLevelMap} : {}),
input: info.model.supportsImageInput === false ? ['text'] : ['text', 'image'],
cost, contextWindow: modelCapacity(info.model).limit ?? known?.contextWindow ?? 0,
maxTokens: info.model.maxTokens ?? known?.maxTokens ?? 0, inputLimits:known?.inputLimits,
compat: {
supportsStore: false, supportsDeveloperRole: false, supportsReasoningEffort: reasoning, maxTokensField: 'max_tokens',
},
}],
streamSimple(model, context, options = {}) {
const output = createAssistantMessageEventStream();
const worker = workers.get(options.sessionId);
const workerFields = worker && {slotId:worker.slotId,requestScope:worker.requestScope};
const signals = [options.signal, worker?.signal, host.productionSignal].filter(Boolean);
if (signals.length) options = {...options, signal:AbortSignal.any(signals)};
(async () => {
let round;
const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
try {
const provider = 'jiansun-native-98k';
const streamSimple = (model, context, options = {}) => {
const output = createAssistantMessageEventStream();
const worker = workers.get(options.sessionId);
const workerFields = worker && {slotId:worker.slotId,requestScope:worker.requestScope};
const signals = [options.signal, worker?.signal, host.productionSignal].filter(Boolean);
if (signals.length) options = {...options, signal:AbortSignal.any(signals)};
(async () => {
let round;
const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
try {
options.signal?.throwIfAborted();
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
if (purpose === 'compaction') {
// Keep Pi's summary generator, including split turns, retries and overflow recovery.
context = {...context, systemPrompt: context.systemPrompt + '\n\n' + COMPACTION_FACTS};
if (['medium','high','xhigh','max'].includes(options.reasoning)) {
const supported = getSupportedThinkingLevels(model);
const reasoning = supported.includes('low') ? 'low' : supported.find(level => level === 'minimal');
if (reasoning) options = {...options, reasoning};
}
}
if (!worker) {
const {textChars: inputChars, totalChars} = contextLengths(context);
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: totalChars });
}
if (transport?.stream) {
const stream = transport.stream(model, context, options);
for await (const event of stream) output.push(event);
const result = await stream.result();
if (!worker && !host.compacting && !['error','aborted'].includes(result.stopReason)) {
await host.recordUsage(result, {purpose});
}
output.end(result);
return;
}
const requestBroker = worker ? worker.broker : host.goalBroker ?? broker;
const selection = host.routeInfo;
const candidates = authorizedCandidates(selection.candidates ?? requestBroker.candidates);
const selectedRoute = candidates.find(route=>route.protocol===selection.model.protocol);
const primary = {...selectedRoute,...selection.model,headers:selection.invocationHeaders ?? selectedRoute?.headers};
const sticky = worker ? worker.activeProtocol : host.activeProtocol;
const routes = new Map([[primary.protocol, primary]]);
for (const candidate of candidates) {
if (!routes.has(candidate.protocol)) routes.set(candidate.protocol,candidate);
}
const first = routes.get(sticky) ?? primary;
const attempts = [first,...[...routes.values()].filter(route=>route.protocol!==first.protocol)].slice(0,3);
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
for (const [index, route] of attempts.entries()) {
options.signal?.throwIfAborted();
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
if (purpose === 'compaction') {
// Keep Pi's summary generator, including split turns, retries and overflow recovery.
context = {...context, systemPrompt: context.systemPrompt + '\n\n' + COMPACTION_FACTS};
if (['medium','high','xhigh','max'].includes(options.reasoning)) {
const supported = getSupportedThinkingLevels(model);
const reasoning = supported.includes('low') ? 'low' : supported.find(level => level === 'minimal');
if (reasoning) options = {...options, reasoning};
round = requestBroker.round(route.headers === undefined ? undefined : {invocationHeaders:route.headers});
const api = modelApi(route.protocol);
const reasoning = route.reasoning === true;
const catalog = catalogModel(runtime,model.id,api);
const thinkingLevelMap = thinkingMap(route.reasoningEfforts, catalog?.thinkingLevelMap);
const compat=api===model.api ? model.compat : {...catalog?.compat,supportsStore:false,supportsMessageThreads:false};
// Pi's Anthropic converter needs a reasoning-capable model to emit
// disabled thinking instead of injecting adaptive effort messages.
const dispatchModel = {...model, api, baseUrl:protocolBaseUrl(route.protocol), thinkingLevelMap,compat,
reasoning:reasoning || (api==='anthropic-messages' && compat.supportsMidConvoEffort===true),
maxTokens:route.maxTokens ?? model.maxTokens};
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
let unknownOutcomeError, httpStatus;
const stream = implementations[route.protocol].streamSimple(dispatchModel, context, { ...options,
reasoning:reasoning ? options.reasoning : undefined,
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
apiKey: 'native-broker-only', fetch: async (...args) => {
sentAt=Date.now();
if (typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
await store.appendEvent({type:'provider_started',id:round.id,protocol:route.protocol,...workerFields,requestBytes});
host.productionSignal?.throwIfAborted();
const response=await round.fetch(...args);
headersAt=Date.now();
httpStatus=response.status;
return observeUnknownOutcome(response, message => { unknownOutcomeError = message; });
},
onPayload: async payload => {
if (api !== 'anthropic-messages' && (route.requiresOutputLimit === false || !route.maxTokens)) {
delete payload.max_tokens;
delete payload.max_completion_tokens;
delete payload.max_output_tokens;
}
if (requiredTool) selectRequiredTool(payload, requiredTool, route);
if (api === 'openai-completions') {
limitChatToolIds(payload);
if (!worker && payload.tools?.length) payload.tool_choice ||= 'auto';
}
// Private project evidence: BODY ONLY, never the fetch headers or API Key.
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
}
return payload;
},
});
let finalEvent, startEvent;
let hasEmittedContent = false;
for await (const event of stream) {
if (event.type === 'text_delta') firstTextAt??=Date.now();
if (event.type === 'done' || event.type === 'error') finalEvent = event;
else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
else if (event.type === 'start') startEvent = event;
else {
if (!hasEmittedContent && /^(text|thinking|toolcall)_/.test(event.type)) {
hasEmittedContent = true;
if (startEvent) output.push(startEvent);
}
output.push(event);
}
}
if (!worker) {
const {textChars: inputChars, totalChars} = contextLengths(context);
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: totalChars });
const result = await stream.result();
const {stopReason}=result;
await store.appendEvent({type:'provider_finished',id:round.id,stopReason,protocol:route.protocol,httpStatus,...workerFields,requestBytes,promptCacheKeyPresent,
...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}),
...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}),
...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
if (broker?.authority?.error) throw broker.authority.error;
const next = attempts[index+1];
if (next && stopReason==='error' && !hasEmittedContent && !unknownOutcomeError &&
!options.signal?.aborted && !host.productionSignal?.aborted && (httpStatus===502 || httpStatus===503)) {
await store.appendEvent({type:'provider_failover',id:round.id,attempt:index+1,httpStatus,
fromProtocol:route.protocol,toProtocol:next.protocol,...workerFields});
continue;
}
if (transport?.stream) {
const stream = transport.stream(model, context, options);
for await (const event of stream) output.push(event);
const result = await stream.result();
if (!worker && !host.compacting && !['error','aborted'].includes(result.stopReason)) {
await host.recordUsage(result, {purpose});
}
if (['error','aborted'].includes(stopReason)) {
if (stopReason==='error' && unknownOutcomeError) result.errorMessage=unknownOutcomeError;
result.errorMessage=redactText(result.errorMessage??'');
output.push(finalEvent);
output.end(result);
return;
}
const requestBroker = worker ? worker.broker : host.goalBroker ?? broker;
const selection = host.routeInfo;
const candidates = authorizedCandidates(selection.candidates ?? requestBroker.candidates);
const selectedRoute = candidates.find(route=>route.protocol===selection.model.protocol);
const primary = {...selectedRoute,...selection.model,headers:selection.invocationHeaders ?? selectedRoute?.headers};
const sticky = worker ? worker.activeProtocol : host.activeProtocol;
const routes = new Map([[primary.protocol, primary]]);
for (const candidate of candidates) {
if (!routes.has(candidate.protocol)) routes.set(candidate.protocol,candidate);
}
const first = routes.get(sticky) ?? primary;
const attempts = [first,...[...routes.values()].filter(route=>route.protocol!==first.protocol)].slice(0,3);
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
for (const [index, route] of attempts.entries()) {
options.signal?.throwIfAborted();
round = requestBroker.round(route.headers === undefined ? undefined : {invocationHeaders:route.headers});
const api = modelApi(route.protocol);
const reasoning = route.reasoning === true;
const thinkingLevelMap = thinkingMap(route.reasoningEfforts, route.protocol===protocol ? model.thinkingLevelMap : undefined);
const dispatchModel = {...model, api, baseUrl:protocolBaseUrl(route.protocol), reasoning, thinkingLevelMap,
maxTokens:route.maxTokens ?? model.maxTokens, compat:{...model.compat,supportsReasoningEffort:reasoning}};
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
let unknownOutcomeError, httpStatus;
const stream = implementations[route.protocol].streamSimple(dispatchModel, context, { ...options,
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
apiKey: 'native-broker-only', fetch: async (...args) => {
sentAt=Date.now();
if (typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
await store.appendEvent({type:'provider_started',id:round.id,protocol:route.protocol,...workerFields,requestBytes});
host.productionSignal?.throwIfAborted();
const response=await round.fetch(...args);
headersAt=Date.now();
httpStatus=response.status;
return observeUnknownOutcome(response, message => { unknownOutcomeError = message; });
},
onPayload: async payload => {
if (api !== 'anthropic-messages' && (route.requiresOutputLimit === false || !route.maxTokens)) {
delete payload.max_tokens;
delete payload.max_completion_tokens;
delete payload.max_output_tokens;
}
if (requiredTool) selectRequiredTool(payload, requiredTool, route);
if (!worker && api === 'openai-completions' && payload.tools?.length) {
payload.tool_choice ||= 'auto';
payload.parallel_tool_calls = false;
}
// Private project evidence: BODY ONLY, never the fetch headers or API Key.
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
}
return payload;
},
});
let finalEvent, startEvent;
let hasEmittedContent = false;
for await (const event of stream) {
if (event.type === 'text_delta') firstTextAt??=Date.now();
if (event.type === 'done' || event.type === 'error') finalEvent = event;
else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
else if (event.type === 'start') startEvent = event;
else {
if (!hasEmittedContent && /^(text|thinking|toolcall)_/.test(event.type)) {
hasEmittedContent = true;
if (startEvent) output.push(startEvent);
}
output.push(event);
}
}
const result = await stream.result();
const {stopReason}=result;
await store.appendEvent({type:'provider_finished',id:round.id,stopReason,protocol:route.protocol,httpStatus,...workerFields,requestBytes,promptCacheKeyPresent,
...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}),
...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}),
...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
if (broker?.authority?.error) throw broker.authority.error;
const next = attempts[index+1];
if (next && stopReason==='error' && !hasEmittedContent && !unknownOutcomeError &&
!options.signal?.aborted && !host.productionSignal?.aborted && (httpStatus===502 || httpStatus===503)) {
await store.appendEvent({type:'provider_failover',id:round.id,attempt:index+1,httpStatus,
fromProtocol:route.protocol,toProtocol:next.protocol,...workerFields});
continue;
}
if (['error','aborted'].includes(stopReason)) {
if (stopReason==='error' && unknownOutcomeError) result.errorMessage=unknownOutcomeError;
result.errorMessage=redactText(result.errorMessage??'');
output.push(finalEvent);
output.end(result);
return;
}
host.productionSignal?.throwIfAborted();
options.signal?.throwIfAborted();
await host.recordUsage(result, {id:round.id,purpose,...workerFields}, !worker&&!host.compacting);
if (stopReason==='length') {
output.push(finalEvent);
output.end(result);
return;
}
if (requiredTool && !result.content.some(block=>block.type==='toolCall'&&block.name===requiredTool)) {
throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
}
if (requiredTool) host.requiredTool = null;
if (worker) worker.activeProtocol = route.protocol;
else host.activeProtocol = route.protocol;
output.push(finalEvent); output.end(result);
host.productionSignal?.throwIfAborted();
options.signal?.throwIfAborted();
await host.recordUsage(result, {id:round.id,purpose,...workerFields}, !worker&&!host.compacting);
if (stopReason==='length') {
output.push(finalEvent);
output.end(result);
return;
}
} catch (error) {
const reason = redactText(String(error.message));
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: options.signal?.aborted || host.productionSignal?.aborted ? 'aborted' : 'error', errorMessage: reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
await store.appendEvent({ type: 'provider_error', id: round?.id, ...workerFields, reason: message.errorMessage,
...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) });
output.push({ type: 'error', reason: message.stopReason, error: message }); output.end(message);
if (requiredTool && !result.content.some(block=>block.type==='toolCall'&&block.name===requiredTool)) {
throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
}
if (requiredTool) host.requiredTool = null;
if (worker) worker.activeProtocol = route.protocol;
else host.activeProtocol = route.protocol;
output.push(finalEvent); output.end(result);
return;
}
})();
return output;
},
});
const saved = await store.get('session.json', null);
host.manager = protectSession(saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir)
: SessionManager.create(store.dir, path.join(store.dir, 'sessions')));
} catch (error) {
const reason = redactText(String(error.message));
const message = { role: 'assistant', api:model.api, provider, model:model.id, content: [], stopReason: options.signal?.aborted || host.productionSignal?.aborted ? 'aborted' : 'error', errorMessage: reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
await store.appendEvent({ type: 'provider_error', id: round?.id, ...workerFields, reason: message.errorMessage,
...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) });
output.push({ type: 'error', reason: message.stopReason, error: message }); output.end(message);
}
})();
return output;
};
host.registerModel = selection => {
const protocol = selection.protocol;
const api = modelApi(protocol);
const known = catalogModel(runtime,selection.id,api);
const reasoning = selection.reasoning === true;
const thinkingLevelMap = thinkingMap(selection.reasoningEfforts,known?.thinkingLevelMap);
runtime.registerProvider(provider,{
api, apiKey:'native-broker-only',baseUrl:protocolBaseUrl(protocol),streamSimple,
models:[{
id:selection.id,name:selection.id,api,reasoning,
...(reasoning && thinkingLevelMap ? {thinkingLevelMap} : {}),
input:selection.supportsImageInput===false?['text']:['text','image'],
cost,contextWindow:modelCapacity(selection).limit ?? known?.contextWindow ?? 0,
maxTokens:selection.maxTokens ?? known?.maxTokens ?? 0,inputLimits:known?.inputLimits,
compat:{...known?.compat,supportsStore:false,supportsMessageThreads:false},
}],
});
return runtime.getModel(provider,selection.id);
};
const model = host.registerModel(info.model);
host.manager = protectSession(await restoreSession(store));
const restored = host.manager.buildSessionContext();
const hasExistingSession = restored.messages.length > 0;
const restoredProtocol = host.manager.getBranch().findLast(entry=>entry.type==='custom' &&
entry.customType==='photocraft-model-protocol')?.data?.protocol ??
restored.messages.findLast(message=>message.role==='assistant' && message.model===restored.model?.modelId)?.api?.replace('openai-completions','openai-chat');
host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
const files = await projectTools(host);
const customTools = [...toolsFor(host), ...files.tools.map(tool =>
@ -604,11 +732,10 @@ export class DetailPiAgent {
systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM,
});
host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
const model = runtime.getModel('jiansun-native-98k', info.model.id);
const reserveTokens = Math.max(DEFAULT_COMPACTION_SETTINGS.reserveTokens, model.contextWindow - MAIN_CONTEXT_BUDGET);
const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime,
model,
thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined,
thinkingLevel:hasExistingSession ? undefined : info.thinkingLevel ?? undefined,
resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal','update_goal'] : []),
settingsManager: SettingsManager.inMemory({retry:mainRetry, compaction:{reserveTokens}}), sessionManager: host.manager,
});
@ -712,7 +839,24 @@ export class DetailPiAgent {
return decision;
};
host.session = session;
// Keep the native message identity through image normalization at delivery.
const queuedUserMessages = new WeakMap();
for (const behavior of ['steer','followUp']) {
const enqueue = session.agent[behavior].bind(session.agent);
session.agent[behavior] = message => {
if (message.role === 'user') {
const text = (typeof message.content === 'string' ? message.content :
message.content.filter(part=>part.type==='text').map(part=>part.text).join('\n')).split(referenceMarker)[0];
queuedUserMessages.set(message,{text,behavior,timestamp:message.timestamp});
}
return enqueue(message);
};
}
session.subscribe(event => {
if (event.type === 'queue_update' && host.canvas.queueUpdate) {
const {steering,followUp}=event;
void host.notifyCanvas('queueUpdate',{steering,followUp}).catch(()=>{});
}
if (event.type === 'compaction_start') host.compacting = true;
if (event.type === 'auto_retry_start') {
host.presentation = new StreamPresentation();
@ -727,6 +871,18 @@ export class DetailPiAgent {
activatePhotoCraftTools(session, customTools);
host.conversationTools = session.getActiveToolNames();
await session.bindExtensions({ uiContext:host.nativeUI.context, mode:'rpc', abortHandler:() => { void session.abort(); } });
if (hasExistingSession && (restored.model?.modelId !== model.id || restored.model?.provider !== provider ||
restoredProtocol && restoredProtocol !== info.model.protocol)) {
await session.setModel(model);
}
if (info.thinkingLevel != null) {
session.setThinkingLevel(info.thinkingLevel);
if (hasExistingSession && host.manager.buildSessionContext().thinkingLevel !== session.thinkingLevel) {
// On open the SDK may already have clamped the restored value.
host.manager.appendThinkingLevelChange(session.thinkingLevel);
}
}
if (restoredProtocol !== info.model.protocol) host.manager.appendCustomEntry('photocraft-model-protocol',{protocol:info.model.protocol});
if (productionGoal) {
const defaults = SettingsManager.inMemory({});
await store.appendEvent({type:'pi_session_configuration',model:session.model?.id,
@ -747,9 +903,22 @@ export class DetailPiAgent {
output:next.output ?? pending.output,
delta:(pending.delta ?? '') + (next.delta ?? ''),
}));
const flushReply = async () => {
const prose=host.presentation?.text.trim();
host.presentation=new StreamPresentation();
await host.display.flush();
if (prose) await host.notifyCanvas('reply',prose.slice(-16000));
};
let outputMeter = new StreamOutputMeter();
session.agent.subscribe(async event => {
if (event.type === 'message_start' && event.message.role === 'assistant') outputMeter = new StreamOutputMeter();
if (event.type === 'message_start' && event.message.role === 'user' && host.rounds > 0) {
const delivered = queuedUserMessages.get(event.message);
if (delivered && host.canvas.userDelivered) {
await flushReply();
await host.notifyCanvas('userDelivered',delivered);
}
}
if (event.type === 'message_update' && !host.compacting) {
const update = event.assistantMessageEvent;
host.presentation ??= new StreamPresentation();
@ -785,14 +954,7 @@ export class DetailPiAgent {
host.thinking = false;
host.display.push({thinking:false,output:meter});
}
if (event.message.stopReason==='toolUse') {
const prose=host.presentation?.text.trim();
if(prose) {
await host.display.flush();
await host.notifyCanvas('reply',prose.slice(-16000));
}
host.presentation=new StreamPresentation();
}
if (event.message.stopReason==='toolUse' || session.pendingMessageCount > 0) await flushReply();
}
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
const activity = toolActivity(event, host.activityScope || activityScope(store.identity));
@ -909,6 +1071,31 @@ export class DetailPiAgent {
async prompt(text, options = {}) {
return this.exclusive(() => this.promptTurn(text, options));
}
async steer(text, {behavior='steer',referenceContent=[]}={}) {
if (!['steer','followUp'].includes(behavior)) throw Error('插话方式无效');
if (typeof text !== 'string' || !text.trim()) throw Error('请输入插话内容');
text=redactText(text);
const check = () => {
if (this.disposed || this.canvasNotificationsDetached || this.workflowBindingChanged) {
throw Error('原会话已关闭或项目已切换');
}
this.productionSignal?.throwIfAborted();
if (this.broker?.authority?.error) throw this.broker.authority.error;
return this.session?.isStreaming;
};
const idle = {accepted:false,behavior,disposition:null,reason:'not_streaming',error:null};
if (!check()) return idle;
const {prompt,images}=referencedPrompt(text,referenceContent);
await this.store.recordUserEvidence(text);
if (!check()) return idle;
const result = await this.session[behavior](prompt,images);
return result === 'queued' ? {accepted:true,behavior,disposition:'queued',reason:null,error:null} : idle;
}
clearQueue() {
return this.session.clearQueue();
}
generatedCandidateReply() {
if (!this.generatedCandidates.size) return null;
const adopted = [...this.generatedCandidates.values()].filter(Boolean).length;
@ -942,13 +1129,19 @@ export class DetailPiAgent {
const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info);
this.firstTurnBrokerInfo = null;
if (latest.accountScope !== this.store.identity.scope) throw Error('账户与项目不一致;原草稿已保留');
if (latest.model.id !== this.info.model.id || latest.model.protocol !== this.info.model.protocol &&
!authorizedCandidates(this.routeInfo.candidates).some(route=>route.protocol===latest.model.protocol) &&
!authorizedCandidates(latest.candidates).some(route=>route.protocol===this.info.model.protocol)) {
throw Error('用户已更换模型,请重新打开会话后再调用');
}
this.routeInfo = latest;
if (this.session.isStreaming) throw Error('本轮尚未结束');
const changed = latest.model.id !== this.info.model.id || latest.model.protocol !== this.info.model.protocol;
if (changed) {
if (this.productionGoal && latest.model.supportsImageInput===false) throw Error('整套制作需要支持视觉的对话模型');
await this.session.setModel(this.registerModel(latest.model));
this.manager.appendCustomEntry('photocraft-model-protocol',{protocol:latest.model.protocol});
this.activeProtocol = undefined;
}
if (latest.thinkingLevel != null && (changed || latest.thinkingLevel !== this.info.thinkingLevel)) {
this.session.setThinkingLevel(latest.thinkingLevel);
}
this.info = this.routeInfo = latest;
this.productionSignal?.throwIfAborted();
const thinking = !this.productionGoal && /^\/thinking\s+(off|minimal|low|medium|high|xhigh|max)\s*$/u.exec(text.trim());
if (thinking) {
if (!this.session.model?.reasoning && thinking[1]!=='off') throw Error('当前模型线路没有发布可用的推理参数');
@ -972,22 +1165,7 @@ export class DetailPiAgent {
this.knowledgeContext = null;
this.productionWorkspace = null;
this.productionSkills = null;
const images = [], quoted = [];
for (const item of referenceContent ?? []) {
let image;
if (typeof item.image === 'string' && item.image) {
images.push({ type:'image',data:item.image,mimeType:item.mimeType??'image/jpeg' });
image = images.length;
}
const source = item.source ?? (item.kind === 'candidate' ? '候选图' : item.kind === 'layer' ? '发送时的画布图层' : '本轮引用');
const entry = { label: item.label, source, ...(image ? { image } : {}), ...(typeof item.text === 'string' ? { text: item.text } : {}) };
for (const key of ['kind', 'nativeLayerId', 'component', 'layerKind', 'slotId', 'fieldId', 'candidateId',
'taskId', 'outputId', 'productVariantId', 'documentId', 'status']) {
if (item[key] != null) entry[key] = item[key];
}
quoted.push(entry);
}
const prompt = quoted.length ? text + '\n\n本条消息附带的画布引用(按图片顺序对应,以下文字为引用内容):' + JSON.stringify(quoted) : text;
const {prompt,images,quoted}=referencedPrompt(text,referenceContent);
this.requiredTool = requiredTool;
const begun = await this.canvas.begin(text);
this.nativeUI.start(begun?.editorText || '');

View File

@ -1,3 +1,4 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { Type } from '@sinclair/typebox';
import { productRequestScope } from './production-recovery.mjs';
import { InvalidToolReply } from './response-audit.mjs';
@ -28,14 +29,14 @@ export const visualReviewChecks = {
const actions=['adopt','canvas_adjust','regenerate'];
const coordinate=Type.Integer({minimum:0,maximum:1000});
export const canvasTransformArgs={
crop:Type.Optional(Type.Tuple([coordinate,coordinate,coordinate,coordinate],{
crop:Type.Optional(Type.Array(coordinate,{minItems:4,maxItems:4,
description:'原图坐标 [左,上,右,下],从 0 到 1000。'})),
flipX:Type.Optional(Type.Boolean()),flipY:Type.Optional(Type.Boolean()),
rotateDeg:Type.Optional(Type.Number({description:'正值为顺时针角度。'})),
scale:Type.Optional(Type.Number({exclusiveMinimum:0,description:'相对 fit 的缩放倍数,默认 1。'})),
scale:Type.Optional(Type.Number({minimum:0,description:'相对 fit 的缩放倍数,默认 1。'})),
offsetX:Type.Optional(Type.Number({description:'向右移动的目标图框像素数。'})),
offsetY:Type.Optional(Type.Number({description:'向下移动的目标图框像素数。'})),
fit:Type.Optional(Type.Union([Type.Literal('cover'),Type.Literal('contain')])),
fit:Type.Optional(StringEnum(['cover', 'contain'])),
};
export async function reviewProductionCandidate({
@ -60,22 +61,22 @@ export async function reviewProductionCandidate({
const originalReference=Number.isInteger(originalIndex)&&originalIndex>=0&&originalIndex<referenceCount
? 'P'+String(originalIndex+1).padStart(2,'0') : null;
const originalImages=originalReference?[input.images[originalIndex]]:input.images.slice(0,referenceCount);
const guidePoint=Type.Tuple([Type.Integer({minimum:0,maximum:1000}),Type.Integer({minimum:0,maximum:1000})]);
const guidePoint=Type.Array(Type.Integer({minimum:0,maximum:1000}),{minItems:2,maxItems:2,description:'归一化标注坐标 [x,y]。'});
const guides=adopted?[]:Object.entries(rule?.structureGuides??{});
const issue = {location:Type.String(),problem:Type.String(),suggestion:Type.String()};
const visualChecks=Object.fromEntries(Object.entries(visualReviewChecks).map(([key,description])=>
[key,Type.Optional(Type.Union([Type.Boolean(),Type.Null()],{description}))]));
[key,Type.Optional(Type.Boolean({description}))]));
const {imageIssues,overlayFixes,copyFixes,summary}=screenAssessment.properties;
const requirementsText='顶层填写候选 verdict(pass、revise 或 missing)和非空 reason。checks 可省略,按实际证据填写。整屏问题在顶层填写 imageIssues、overlayFixes 或 copyFixes。整屏通过时填 screenVerdict: pass,发现问题时可从问题列表推导 needs_fix。整屏模板风格填顶层 templateStyle;候选图的模板风格填在 checks 对象内的 templateStyle 字段。';
const example='最小提交示例 '+JSON.stringify({verdict:'revise',reason:'候选商品与实拍的部件形状不一致。'});
const assessment=params({
candidateId:Type.Optional(Type.String({description:'省略时使用本次受审候选。'})),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))),
candidateId:Type.Optional(Type.String({description:'省略时使用本次受审候选。'})),verdict:StringEnum(['pass','revise','missing']),
shownSubject:Type.Optional(Type.String({description:'画面实际突出呈现的部位、景别或场景。'})),
recommendedAction:Type.Optional(Type.Union(actions.map(value=>Type.Literal(value)))),
recommendedAction:Type.Optional(StringEnum(actions)),
canvasTransform:Type.Optional(params(canvasTransformArgs)),
checks:Type.Optional(params({...visualChecks,structure:Type.Optional(Type.Boolean()),color:Type.Optional(Type.Boolean()),
material:Type.Optional(Type.Boolean()),
templateStyle:Type.Optional(Type.Union([Type.Boolean(),Type.Null()],{description:'对照模板原屏和品牌规则判断模板风格'})),
templateStyle:Type.Optional(Type.Boolean({description:'对照模板原屏和品牌规则判断模板风格'})),
composition:Type.Optional(Type.Boolean()),evidence:Type.Optional(Type.Boolean()),
copyAlignment:Type.Optional(Type.Boolean({description:'画面主角和本图位承担的实时文案是否一致。'}))})),
mustRedo:Type.Optional(Type.Array(params({...issue,
@ -150,6 +151,7 @@ export async function reviewProductionCandidate({
return [];
});
}
if (value.canvasTransform?.scale <= 0) throw new InvalidToolReply('缩放倍数必须大于 0');
const audit=droppedReferences.length?{droppedReferences}:{};
const errors=[];
if(value.candidateId!==undefined&&value.candidateId!==candidateId)errors.push(`candidateId ${JSON.stringify(value.candidateId)} 与本次受审候选不一致`);
@ -160,11 +162,12 @@ export async function reviewProductionCandidate({
const screenReview=verdict===undefined?undefined:{
page:screen.details.page+1,name:screen.details.pageName,screenFingerprint:screen.details.screenFingerprint,
wholeScreen,...(screen.details.templateFidelity?{templateEvidence:true}:null),
verdict,summary:screenSummary??value.reason,templateStyle,imageIssues,overlayFixes,copyFixes,
verdict,summary:screenSummary??value.reason,templateStyle:templateStyle??null,imageIssues,overlayFixes,copyFixes,
};
if (screenReview) findings.validate(screenReview,{example,verdictKey:'screenVerdict'});
receipt={candidateId,...audit,verdict:value.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform,
checks:{...Object.fromEntries(Object.keys(visualReviewChecks).map(key=>[key,null])),...value.checks},reason:value.reason,shownSubject:value.shownSubject,observation:{
checks:{...value.checks,...Object.fromEntries([...Object.keys(visualReviewChecks),'templateStyle']
.map(key=>[key,value.checks?.[key]??null]))},reason:value.reason,shownSubject:value.shownSubject,observation:{
source,shownSubject:value.shownSubject,reviewedCopy,visualEvidence:value.shownFields??[],
screenReview,
mustRedo:value.mustRedo??[],canvasFixes:value.canvasFixes??[],
@ -200,7 +203,7 @@ export async function reviewProductionCandidate({
'用 shownSubject 描述实际画面。shownFields 只填写 screenCopy 中存在且有画面依据的条目。每项原样复制 shownFieldOptions 中的一个 field。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。',
...(fieldList.length?[]:[shownFieldsGuide]),
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
'checks 记录逐项结论。允许 null 的字段可用 reason 说明依据。generationEvidence 提供实发模型、参数和像素。',
'checks 记录逐项结论。证据不足时可省略对应字段,在 reason 说明依据。generationEvidence 提供实发模型、参数和像素。',
'调用 review_candidate 提交结论。',
].join('\n');
const slotTemplate=input.layoutSource==='pinnedTemplateOriginal'

View File

@ -1,10 +1,11 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { Type } from '@sinclair/typebox';
export const canvasReadParameters=Type.Object({
layer:Type.Optional(Type.Integer({minimum:1,description:'单查图层时填真实 ID。指定分屏、筛选或摘要时按查找条件读取。'})),
revision:Type.Optional(Type.Integer({minimum:0,description:'可选的上次读取版本,用于对照;读取始终返回当前真实revision,不授予修改许可。'})),
screen:Type.Optional(Type.String({maxLength:160})),screenId:Type.Optional(Type.Integer({minimum:1})),
mode:Type.Optional(Type.Union([Type.Literal('summary'),Type.Literal('layers')])),
mode:Type.Optional(StringEnum(['summary', 'layers'])),
filter:Type.Optional(Type.String({maxLength:160})),maxDepth:Type.Optional(Type.Integer({minimum:0,description:'摘要中显示的最大图层组深度;省略时先看浅层概况。'})),
offset:Type.Optional(Type.Integer({minimum:0,maximum:100000})),
},{additionalProperties:false});
@ -28,16 +29,52 @@ export async function previewTarget(host, layer, signal) {
return state;
}
const any=()=>Type.Optional(Type.Any());
// The native preview commands keep their original engine parameter names.
export const previewParameters=Type.Object({
revision:Type.Optional(Type.Integer({minimum:0,description:'无需填写;宿主在本轮重新读取目标后绑定真实版本。'})),
command:Type.Union(['type.edit','type.setStyle','shape.edit','layer.translate','layer.setProps'].map(value=>Type.Literal(value))),
params:Type.Object({layer:Type.Integer({minimum:1}),text:Type.Optional(Type.String({maxLength:3000})),
name:Type.Optional(Type.String({maxLength:1000})),dx:Type.Optional(Type.Number()),dy:Type.Optional(Type.Number()),units:Type.Optional(Type.Literal('px')),
visible:Type.Optional(Type.Boolean()),opacity:Type.Optional(Type.Number({minimum:0,maximum:1})),fill:any(),blend:any(),
replace:any(),box:any(),point:any(),move:any(),transform:any(),antialias:any(),kerning:any(),range:any(),runs:any(),
font:any(),fontStyle:any(),weight:any(),italic:any(),size:any(),color:any(),tracking:any(),leading:any(),baselineShift:any(),horizontalScale:any(),verticalScale:any(),underline:any(),strikethrough:any(),fauxBold:any(),fauxItalic:any(),caps:any(),ligatures:any(),discretionaryLigatures:any(),features:any(),variations:any(),language:any(),align:any(),
kind:any(),rect:any(),radii:any(),radius:any(),sides:any(),starRatio:any(),from:any(),to:any(),
},{additionalProperties:false,minProperties:2}),
},{additionalProperties:false});
const optional=Type.Optional;
const object=properties=>Type.Object(properties,{additionalProperties:false});
const number=Type.Number();
const string=Type.String();
const boolean=Type.Boolean();
const index=Type.Integer({minimum:0});
const fixed=(items,length)=>Type.Array(items,{minItems:length,maxItems:length});
const point=fixed(number,2);
const box=fixed(number,4);
const colorChannels=Type.Array(number,{minItems:3,maxItems:4});
const color=Type.Union([string,colorChannels]);
const gradient=object({
stops:optional(Type.Array(fixed(Type.Union([number,string,colorChannels]),2),{description:'每个色标为 [位置, 颜色]。'})),
angle:optional(number),scale:optional(number),
style:optional(StringEnum(['linear','radial','angle','reflected','diamond'])),reverse:optional(boolean),
opacityStops:optional(Type.Array(point)),midpoints:optional(Type.Array(number)),offset:optional(point),
dither:optional(boolean),align:optional(boolean),
});
const fill=Type.Union([number,string,colorChannels,object({gradient}),object({pattern:string,scale:optional(number)})]);
const characterStyle={
font:optional(string),fontStyle:optional(string),weight:optional(number),italic:optional(boolean),
size:optional(number),color:optional(color),tracking:optional(number),
leading:optional(Type.Union([number,StringEnum(['auto'])])),
baselineShift:optional(number),horizontalScale:optional(number),verticalScale:optional(number),
underline:optional(boolean),strikethrough:optional(boolean),fauxBold:optional(boolean),fauxItalic:optional(boolean),
kerning:optional(Type.Union([number,StringEnum(['metrics','optical','off'])])),
caps:optional(StringEnum(['normal','small','all'])),ligatures:optional(boolean),discretionaryLigatures:optional(boolean),
features:optional(Type.Unsafe({type:'object',additionalProperties:{anyOf:[{type:'integer'},{type:'boolean'}]}})),
variations:optional(Type.Unsafe({type:'object',additionalProperties:{type:'number'}})),language:optional(string),
};
// Shared native field names keep preview parameters usable with the engine.
export const previewParameters=object({
revision:optional(Type.Integer({minimum:0,description:'无需填写;宿主在本轮重新读取目标后绑定真实版本。'})),
command:StringEnum(['type.edit','type.setStyle','shape.edit','layer.translate','layer.setProps']),
params:object({
layer:Type.Integer({minimum:1}),text:optional(Type.String({maxLength:3000})),
name:optional(Type.String({maxLength:1000})),dx:optional(Type.Integer()),dy:optional(Type.Integer()),units:optional(StringEnum(['px'])),
visible:optional(boolean),opacity:optional(Type.Number({minimum:0,maximum:1})),fill:optional(fill),blend:optional(string),
replace:optional(object({start:index,end:index,text:string})),
box:optional(box),point:optional(point),move:optional(point),transform:optional(fixed(number,6)),
antialias:optional(StringEnum(['none','sharp','crisp','strong','smooth'])),
range:optional(fixed(index,2)),runs:optional(Type.Array(object({start:index,end:index,...characterStyle}))),
...characterStyle,
align:optional(StringEnum(['left','center','right','justify','justifyCenter','justifyRight','justifyAll'])),
kind:optional(string),rect:optional(box),radii:optional(Type.Union([number,box])),radius:optional(number),
sides:optional(Type.Integer()),starRatio:optional(number),from:optional(point),to:optional(point),
}),
});

View File

@ -30,6 +30,13 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
},intervalMs);
const failure=(runId,error,unknown=false)=>send({type:'complete',runId,value:{error,unknown,reposted:false}});
const exitReady=()=>{if(exiting&&!active&&!knowledge.size)send({type:'exit_ready'});};
const controlRun=(value)=>{
if(!active || active.signal.aborted || value.runId!==active.runId) return {reason:'no_active_run'};
const config=active.config;
if(value.scope!==config.scope || value.project!==config.project || value.documentId!==config.documentId)
return {reason:'scope_mismatch'};
return {run:active};
};
lines.on('line',line=>{
if(closed)return;
let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;}
@ -58,6 +65,32 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
&& (value.writeEpoch??null)===(config.writeEpoch??null)) {
active.abort(new BridgeError('本轮制作已停止,已保留原请求', 'cancelled'));
}
return;
}
if(value?.type==='abort_run') {
controlRun(value).run?.abort(new BridgeError('本轮已停止,已保留原请求','cancelled'));
return;
}
if(value?.type==='steer' || value?.type==='clear_queue') {
const {type,id,runId}=value;
const behavior=value.behavior==='followUp'?'followUp':'steer';
const ack={type:type+'_ack',id,runId};
const reject=(reason,error=null)=>{
if(type==='steer') send({...ack,accepted:false,behavior,disposition:null,reason,error});
else send({...ack,steering:[],followUp:[],error:error??reason});
};
const {run,reason}=controlRun(value);
if(!run?.host) {reject(reason??'starting');return;}
run.controls=run.controls.then(async ()=>{
const current=controlRun(value);
if(!current.run) {reject(current.reason);return;}
if(type==='steer') {
const result=await run.host.steer(value.text,{behavior:value.behavior,referenceContent:value.referenceContent});
send({...ack,...result});
} else {
send({...ack,...run.host.clearQueue(),error:null});
}
}).catch(error=>reject(null,error.message));
return;
}
if(value?.type==='knowledge_cancel' && uuid.test(value.id||'')) {
@ -111,12 +144,13 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
task.reject(new BridgeError(error.message,error.category ?? 'cancelled',{dispatched:true}));
}
};
active={runId,config,abort};
const run={runId,config,abort,signal:controller.signal,controls:Promise.resolve()};
active=run;
config.runId=runId;
const call=(action,input,accepted)=>new Promise((resolve,reject)=>{
if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;}
if(controller.signal.aborted){reject(new BridgeError(controller.signal.reason.message,controller.signal.reason.category ?? 'cancelled'));return;}
if (action === 'pi-delta' || action === 'pi-activity') {
if (['pi-delta','pi-activity','pi-queue-update','pi-user-delivered'].includes(action)) {
send({type:'presentation',runId,action,input});
resolve();
return;
@ -152,7 +186,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
send({type:'auth_failure',runId,category:error.category});
abort(error);
}
});
}, host=>{run.host=host;});
if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;send({type:'complete',runId,value:result});}
} catch {if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;failure(runId,controller?.signal.reason?.message??'本地模型桥失败;请核查原请求,不会重发',true);}}
finally {

View File

@ -14,7 +14,7 @@ const canvasTelemetry = new Set(['pi-state', 'pi-context-usage', 'pi-ui-request'
export function observeCanvasCalls(store, call) {
return async (action, input, execution) => {
if (action === 'pi-delta' || action === 'pi-activity') return call(action,input);
if (['pi-delta','pi-activity','pi-queue-update','pi-user-delivered'].includes(action)) return call(action,input);
const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(),
attempt:execution?.attempt ?? 1,requestId:execution?.requestId ?? input.request?.requestId,
revision:input.revision ?? store.executionScope.revision};
@ -135,7 +135,7 @@ export function bindRecovery(host, recovery, identity) {
}
};
}
export async function runSession(config, call, sharedBroker, recovery, signal, onAuthorizationLost) {
export async function runSession(config, call, sharedBroker, recovery, signal, onAuthorizationLost, onHostReady) {
if (config.mode === 'record-production-export') {
try {
const {recordProductionExport} = await import('./production-goal.mjs');
@ -195,6 +195,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
host = await DetailPiAgent.open({ store, broker, productionGoal, productionSignal:signal, brokerInfo:info, canvas, projectEvidence:config.projectEvidence, documentId:config.documentId, onEvent: event => {
if (event.type === 'usage') usage.push(event);
} });
onHostReady?.(host);
if (productionGoal) await store.appendEvent({type:'production_startup',
importsMs:Math.round(brokerStartedAt-startedAt),brokerMs:Math.round(brokerReadyAt-brokerStartedAt),
sessionMs:Math.round(performance.now()-brokerReadyAt),checks:info.selectionTimings});

View File

@ -13,11 +13,11 @@ export const ENTERPRISE_SERVER = 'enterprise_knowledge_base';
const names = toolNames.filter(name => name !== 'download_file');
const text = (min=1,max=500) => Type.String({minLength:min,maxLength:max});
const offset = Type.Optional(Type.Integer({minimum:0,maximum:10000000}));
const directory = Type.Optional(Type.Union([text(0,1000),Type.Null()]));
const directory = Type.Optional(text(0,1000));
const revision = Type.Optional(text(1,200));
const schemas = {
list_libraries: Type.Object({}, {additionalProperties:false}),
query_knowledge: Type.Object({query:text(2,500),directory,limit:Type.Optional(Type.Integer({minimum:1,maximum:8})),maxCharacters:Type.Optional(Type.Union([Type.Literal(0),Type.Integer({minimum:1024,maximum:24000})]))},{additionalProperties:false}),
query_knowledge: Type.Object({query:text(2,500),directory,limit:Type.Optional(Type.Integer({minimum:1,maximum:8})),maxCharacters:Type.Optional(Type.Integer({minimum:0,maximum:24000,description:'返回字符上限;0 表示不限,其余范围 1024–24000。'}))},{additionalProperties:false}),
list_resource_sets: Type.Object({query:Type.Optional(text(1,120)),brand:Type.Optional(text(1,120)),category:Type.Optional(text(1,120)),offset,limit:Type.Optional(Type.Integer({minimum:1,maximum:100})),revision},{additionalProperties:false}),
get_resource_set: Type.Object({resourceSetId:text(1,120),revision},{additionalProperties:false}),
list_directory: Type.Object({path:text(0,1000),offset,limit:Type.Optional(Type.Integer({minimum:1,maximum:100})),revision},{additionalProperties:false}),
@ -282,6 +282,7 @@ export class EnterpriseKnowledge {
if (name==='list_directory' && (args.offset??0)>0 && !args.revision) throw Error('目录续页必须携带原revision');
if (name==='search_files' && (args.offset??0)>0 && !args.revision) throw Error('搜索续页必须携带原revision');
if (name==='read_text') args={...args,limit:args.limit??16000};
if (name==='query_knowledge' && args.maxCharacters>0 && args.maxCharacters<1024) throw Error('返回字符上限须为 0 或至少 1024');
if (name==='query_knowledge') args={...args,limit:args.limit??3,maxCharacters:args.maxCharacters??8000};
if (name==='search_files') args={...args,limit:args.limit??5};
if (name==='list_directory') args={...args,limit:args.limit??10};

View File

@ -427,8 +427,7 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
const original = pack.enterprise.components[component].originals[0];
Object.assign(pack.enterprise,{component,sourceKind:'xiaoyi-release',snapshotVersion:manifest.version,
originalSha256:original.sha256,canvas:original.canvas,
resourceSetId:templateId,componentId:component,
mappingPath:path.join(root,binding.mapping),inventoryPath:path.join(root,binding.inventory)});
resourceSetId:templateId,componentId:component});
const intake = intakeMetadata(manifest.intake ?? input.intake);
pack.xiaoyi = {...skills.productionBinding,...(intake && {intake})};
packs[component] = pack;

View File

@ -1,3 +1,4 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { currentProductionOperations } from './production-goal.mjs';
import { Type } from '@sinclair/typebox';
import { setTimeout as delay } from 'node:timers/promises';
@ -52,13 +53,17 @@ export const NATIVE_CANVAS_QUICK_REFERENCE = [
export const nativeCatalogParameters = Type.Object({
filter: Type.Optional(Type.String({ maxLength: 160 })), id: Type.Optional(Type.String({ maxLength: 160 })),
ids: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 160 }), { minItems: 1, maxItems: 12, uniqueItems: true })),
ids: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 160 }), { minItems: 1, maxItems: 12 })),
offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 100000 })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 40, default: 10 })),
}, { additionalProperties: false });
export const nativeCallParameters = Type.Object({
revision: Type.Integer({ minimum: 0 }),
method: Type.Union(['engine.execute', 'ui.set', 'ui.inspect', 'ui.menu.list', 'result.read'].map(value => Type.Literal(value))),
params: Type.Object({}, { additionalProperties: true }),
method: StringEnum(['engine.execute', 'ui.set', 'ui.inspect', 'ui.menu.list', 'result.read']),
params: Type.Object({
command: Type.Optional(Type.String()), params: Type.Optional(Type.Unsafe({type:'object',additionalProperties:true})),
resultId: Type.Optional(Type.Integer({minimum:0})), pointer: Type.Optional(Type.String()),
offset: Type.Optional(Type.Integer({minimum:0})), document: Type.Optional(Type.Integer({minimum:0})),
}, { additionalProperties: true }),
}, { additionalProperties: false });
/** One registry adapter covers native commands. It does not implement them. */

View File

@ -2,6 +2,8 @@ import { candidateReceipt } from './production-receipts.mjs';
import { compactDeliveryReceipt } from './delivery-fidelity.mjs';
import { candidateUsage, productionFacts, loadSlots, productionSettings, saveProductionSettings } from './production-slots.mjs';
import fs from 'node:fs/promises';
import { readFileSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import { setTimeout as delay } from 'node:timers/promises';
import path from 'node:path';
import lockfile from 'proper-lockfile';
import { createAgentSession, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
@ -27,12 +29,71 @@ export function piGoalState(manager) {
return manager.getBranch().findLast(entry => entry.type === 'custom' && entry.customType === 'pi-goal')?.data?.goal;
}
const lockOptions = { stale:15000, update:4000 };
const missing = error => { if (error.code !== 'ENOENT') throw error; };
export async function lockProjectSession(root, onCompromised) {
const lockPath = root + '.lock';
const ownerFile = lockPath + '.owner.json';
const options = {...lockOptions,...(onCompromised && {onCompromised})};
for (let attempt=0; ; attempt++) {
try {
// Serialize owner inspection and acquisition so two recovering clients
// cannot remove each other's replacement lock.
const releaseClaim = lockfile.lockSync(lockPath+'.claim-target',{...lockOptions,realpath:false,lockfilePath:lockPath+'.claim'});
try {
let unlock;
try {
unlock = lockfile.lockSync(root,options);
} catch (error) {
if (error.code !== 'ELOCKED') throw error;
let owner, lock;
try {
owner = JSON.parse(readFileSync(ownerFile,'utf8'));
lock = statSync(lockPath);
} catch (cause) {
if (cause.code !== 'ENOENT' && !(cause instanceof SyntaxError)) throw cause;
throw error;
}
if (owner?.lockCreatedAt !== lock.birthtimeMs || !Number.isInteger(owner.pid) || owner.pid <= 0) throw error;
try {
process.kill(owner.pid,0);
throw error;
} catch (cause) {
if (cause.code !== 'ESRCH') throw cause.code === 'EPERM' ? error : cause;
}
rmdirSync(lockPath);
unlock = lockfile.lockSync(root,options);
}
try {
writeFileSync(ownerFile,JSON.stringify({pid:process.pid,startedAt:Date.now(),lockCreatedAt:statSync(lockPath).birthtimeMs}));
} catch (error) {
unlock();
throw error;
}
return () => {
try {
const owner = JSON.parse(readFileSync(ownerFile,'utf8'));
if (owner.pid === process.pid) unlinkSync(ownerFile);
} catch (error) { missing(error); }
finally { unlock(); }
};
} finally { releaseClaim(); }
} catch (error) {
if (error.code !== 'ELOCKED') throw error;
if (attempt === 8) throw Error('此项目已有本地Agent在运行,请等待当前任务结束;未发起新请求');
await delay(50);
}
}
}
// The native export service calls this only after every requested file is verified.
export async function recordProductionExport(dir, goalId) {
const unlock = await lockfile.lock(path.dirname(dir), { stale:15000, update:4000 });
const unlock = await lockProjectSession(path.dirname(dir));
try {
const saved = JSON.parse(await fs.readFile(path.join(dir, 'session.json'), 'utf8'));
const manager = SessionManager.open(path.join(dir, 'sessions', path.basename(saved.file)), dir, dir);
const sessions = path.join(dir, 'sessions');
const manager = SessionManager.open(path.join(sessions, path.basename(saved.file)), sessions, dir);
const goal = piGoalState(manager);
if (goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致');
if (goal.status !== 'complete') {
@ -61,6 +122,7 @@ export async function runPiProductionGoal(host, text, continuation, images=[], u
if (!continuation || !continuing || userCanvasChanges) {
const request = JSON.stringify({request:text,...productionFacts(host.store,host.productionGoal),
requestedOutputs:host.productionGoal.requestedOutputs,product:host.productEvidence?.product,
platformFacts:host.productEvidence?.platformFacts,
...(host.productEvidence?.intake?{intake:host.productEvidence.intake,barcodeBindings:host.productEvidence.barcodeBindings}:null),
enterpriseKnowledge:host.productionSkills?.execution,userCanvasChanges:userCanvasChanges??undefined});
await host.session.sendCustomMessage({customType:'photocraft-goal-request',
@ -86,7 +148,7 @@ export async function settleProductionGoal(host, {messages}) {
host.session.clearQueue();
return;
}
if (!active) return;
if (!active || host.session.pendingMessageCount > 0) return;
const end=messages.findLast(message=>message.role==='assistant');
if (['error','aborted','length'].includes(end?.stopReason)) {
host.session.clearQueue();
@ -94,7 +156,7 @@ export async function settleProductionGoal(host, {messages}) {
}
const start=messages.findLastIndex(message=>message.role==='custom'&&message.customType==='pi-goal-event'
&& ['continuation','resumed'].includes(message.details?.kind));
if(start===-1||!end||messages.slice(start+1).some(message=>message.role==='toolResult'))return;
if(start===-1||!end||messages.slice(start+1).some(message=>['toolResult','user'].includes(message.role)))return;
const blocker=host.productionGoal.drafts?.findLast(draft=>draft.blocker)?.blocker;
host.productionPause=blocker
? {reason:blocker.reason,requiredAction:blocker.requiredAction}
@ -169,7 +231,11 @@ async function projectSlotMap(host) {
export async function callProductionTool(host, name, args, signal) {
const goal=host.productionContext ?? host.productionGoal;
if (!goal) throw Error('当前没有打开模板制作画布');
if (name==='set_production_settings') return saveProductionSettings(host.store,args);
if (name==='set_production_settings') {
const {mainImageAspects,...settings}=args;
if (mainImageAspects) settings.mainImageAspects=[...new Set(mainImageAspects)];
return saveProductionSettings(host.store,settings);
}
if (name==='open_production_output') {
const started=performance.now();
const previous=await currentProductionOperations(host)?.catch(()=>undefined);

View File

@ -1,3 +1,4 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { candidateReceipt, compactProgress, receiptPage, reviewSlotSummary } from './production-receipts.mjs';
import { compactTemplateFidelity } from './template-fidelity.mjs';
import { compareTemplateFields, visibleTemplateConflicts } from './field-requirements.mjs';
@ -33,13 +34,13 @@ const layer=Type.Integer({minimum:1});
const page=Type.Integer({minimum:0});
const rev=Type.Integer({minimum:0});
const optional=Type.Optional;
const fit=Type.Union([Type.Literal('cover'),Type.Literal('contain')]);
const fit=StringEnum(['cover', 'contain']);
const productReference=Type.String({pattern:'^P[0-9]{2,}$',description:'从 read_slot_images 的 productReferences 清单选择,例如 P01。'});
const referenceIndexOf=id=>Number(id.slice(1))-1;
const productReferences=count=>Array.from({length:count??0},(_,index)=>'P'+String(index+1).padStart(2,'0'));
const productImageArgs={
reference:optional(productReference),
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
referenceIndex:optional(page),referenceCrop:optional(Type.Array(Type.Integer({minimum:0,maximum:1000}),{minItems:4,maxItems:4,description:'归一化裁切 [x,y,w,h]。'})),
};
const reuseTarget=obj({outputId:optional(text),slotId:slotRef});
const transformDescription='在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选。sourceSlotId 精确匹配本项目的完整 slotId、fieldId 或图位标签,使用该图位当前采用的同花色候选,可跨成品。sourceCandidateId 接收候选编号,referenceIndex 接收从 0 开始的实拍序号,三种来源互斥。来源编号无效时返回匹配图位或目标图位的已完成候选。返回新候选、实际来源 sourceCandidateId、cropSourcePixels、targetFrame、resolutionRatio 和 resolutionSufficient。';
@ -72,8 +73,8 @@ const preparationArgs={
prompt:text,
reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})),
reworkCandidateId:optional(text),
references:optional(Type.Array(productReference,{minItems:1,uniqueItems:true})),
referenceIndexes:optional(Type.Array(page,{minItems:1,uniqueItems:true,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
references:optional(Type.Array(productReference,{minItems:1})),
referenceIndexes:optional(Type.Array(page,{minItems:1,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
useTemplateBase:optional(Type.Boolean({description:'使用本图位固定模板原稿像素作为第一张图,随后发送本款实拍。false 表示本请求不使用模板底图。'})),
prefer2k:optional(Type.Boolean({description:'传 true 可请求 2K。'})),
retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})),
@ -92,8 +93,8 @@ const outputScope={outputId:optional(text),variantId:optional(text)};
export const productionOperationTools = [
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。work 中的 waitingCanvas 列出仍在等切回的图位。',obj({outputId:text,variantId:text})],
['set_production_settings','记录当前项目的参考偏好或主图画幅。template-base 表示用原图换商品,composition-only 表示只参考构图,none 表示不参考。单个生图请求可自行选择是否使用模板底图。',obj({
referenceMode:optional(Type.Union([Type.Literal('template-base'),Type.Literal('composition-only'),Type.Literal('none')])),
mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1,uniqueItems:true})),
referenceMode:optional(StringEnum(['template-base', 'composition-only', 'none'])),
mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1})),
})],
['plan_production','读取商品、模板和成品进度。projectSlots 按成品和花色列出本轮所有图位的屏、图框像素、模板主体事实和候选号。framePending 表示像素值来自模板,实际图框待核对。adoptionRecorded 是已有采用记录的候选号,selectedCandidateId 是画布读到的当前采用。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。返回已声明的参考方式和主图画幅。mode 为制作模式,budget 为制作时间,limits 为候选上限。candidateCount 和 candidatesRemaining 为图位已用和剩余候选数。pictures 中的 copyReady 表示关联文案是否已写好。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
['read_copy_fields','省略 pageId 和 fieldId 返回全页字段身份、当前文字、约束及修订号;指定页面或字段可读取图层样式、范围及关联字段。',obj({
@ -129,7 +130,7 @@ export const productionOperationTools = [
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原请求已收口。网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或 180 秒恢复预算用完后原查询仍是 unresolved 或 404 request_not_found,都会进入此终态。404 request_not_found 收口时按未发起处理。expired 可以为同图位另备新请求;按未发起处理的请求不计入该图位的生图次数,其他已派发请求仍计入。',obj({...outputScope,slotIds:optional(ids)})],
['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry、annotationLayout 和 textClipping。slotImageFacts 逐图位列出已采用图片的 source(来源类别、候选或请求号、上游图位或实拍文件)、当前与模板图框的近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空),以及 nearest 中本成品最相近的最多三个其它图位的屏号和 64 位 dHash 汉明距离 distance(0–64,越小越相似)。textLayers 逐层返回样式差异、当前和模板的字形附近对比度 P10/P50(WCAG 公式)及底色亮度标准差,缺少样本时对应值为空。annotationLayout.dimensionGroups 按模板图层编号列出标签和线,subjectBoundsOffsets 为端点减去主体框左、上、右、下边界的坐标差。guides 的 visibility 和 templateVisibility 分别是当前成图和模板原屏同层的像素回执。contrastP10 和 contrastP50 是标记像素与紧邻一像素背景的 WCAG 对比度百分位。lineWidthsPx 与 lines 顺序一致,diameterPx 是无标线几何时标记像素包围盒的最长边。textClipping 列出越出当前屏的文字图层和墨迹边界矩形 [x,y,w,h]。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。reviewRound 为已完成的整屏复核次数,issueHistory 为此前各轮问题数。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({
page:optional(page),pages:optional(Type.Array(page)),
region:optional(Type.Tuple([Type.Integer(),Type.Integer(),Type.Integer({minimum:1}),Type.Integer({minimum:1})])),
region:optional(Type.Array(Type.Integer(),{minItems:4,maxItems:4,description:'画布坐标 [x,y,w,h],宽高至少 1 像素。'})),
zoom:optional(Type.Number({minimum:1,maximum:4})),
includeTemplateImage:optional(Type.Boolean()),templateLayerId:optional(Type.Integer({minimum:1})),templateChangeOffset:optional(Type.Integer({minimum:0})),
})],
@ -139,11 +140,10 @@ export const productionOperationTools = [
})],
['read_screen_review','读取指定成品最近一次完整的整屏复核回执。page 从 1 编号。不启动新的复核。',obj({...outputScope,page:Type.Integer({minimum:1})})],
['defer_production_output','挂起当前输出并记录需要外部处理的原因和所需动作。可用 await_image_slots 或 reconcile_image_slots 查询在途请求。',obj({
blocker:obj({kind:Type.Union([Type.Literal('missing_required_input'),Type.Literal('authorization_required'),
Type.Literal('permanent_service_failure')]),reason:text,requiredAction:text}),
blocker:obj({kind:StringEnum(['missing_required_input', 'authorization_required', 'permanent_service_failure']),reason:text,requiredAction:text}),
})],
['finish_production','保存并导出当前画布修订,返回成品状态、落盘文件、尺寸和工程重开结果。slotCoverage 统计已采用、人工置入、有候选待采用、空白与跳过的图位。若仍有通过复核的图位尚未填入,返回待采用候选;明确交付现状时可填写 deliveryReason。fidelityReport 包含差异总条数、按屏分类计数和待复核差异,reportPath 可用 read 读取完整报告。scope=all 按实际文件核验本轮交付,可附当前画布修订同时导出。用 issues 记录已知问题。',obj({
...outputScope,revision:optional(rev),scope:optional(Type.Union([Type.Literal('current'),Type.Literal('all')])),issues:optional(Type.Array(obj({outputId:optional(text),variantId:optional(text),page:optional(Type.Integer({minimum:1})),field:optional(text),reason:text}))),
...outputScope,revision:optional(rev),scope:optional(StringEnum(['current', 'all'])),issues:optional(Type.Array(obj({outputId:optional(text),variantId:optional(text),page:optional(Type.Integer({minimum:1})),field:optional(text),reason:text}))),
deliveryReason:optional(text),
})],
];
@ -898,8 +898,10 @@ export async function openProductionOperations(host,{target=host.productionConte
if(action==='transform')notice('画布调整已有候选');
return result;
};
const transformImage=(slot,{sourceSlotId,sourceCandidateId,referenceIndex,reference,...transform},signal)=>
serialize(()=>localCandidate(slot,'transform',{sourceSlotId,sourceCandidateId,referenceIndex:reference?referenceIndexOf(reference):referenceIndex,transform},signal,'transform'));
const transformImage=(slot,{sourceSlotId,sourceCandidateId,referenceIndex,reference,...transform},signal)=>{
if (transform.scale <= 0) throw Error('缩放倍数必须大于 0');
return serialize(()=>localCandidate(slot,'transform',{sourceSlotId,sourceCandidateId,referenceIndex:reference?referenceIndexOf(reference):referenceIndex,transform},signal,'transform'));
};
const prepareImageRequest=async(slot,{prompt,retryOf,prefer2k,
references,referenceIndexes,reworkCandidateId,reworkChange,useTemplateBase},signal)=>{
signal?.throwIfAborted();
@ -909,7 +911,8 @@ export async function openProductionOperations(host,{target=host.productionConte
if(status.drawLimitReached)return drawLimit(live,status);
const limit=candidateLimit(live);
if(limit)return limit;
const indexes=references?.map(referenceIndexOf)??referenceIndexes;
const selected=references?.map(referenceIndexOf)??referenceIndexes;
const indexes=selected && [...new Set(selected)];
const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,
prefer2k,reworkOf:reworkCandidateId,reworkChange,
useTemplateBase:useTemplateBase??(productionSettings(store,plan.template?.production).referenceMode==='template-base'||undefined),
@ -1824,6 +1827,7 @@ export async function openProductionOperations(host,{target=host.productionConte
return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))];
},
async read_output_screen({page=0,pages,includeTemplateImage=false,templateLayerId,templateChangeOffset=0,region,zoom},signal){
if(region && (region[2]<1 || region[3]<1)) throw Error('局部读取的宽高至少为 1 像素');
if(region && pages?.length) throw Error('局部读取请用 page 指定单屏');
const render=async page=>{
const {images=[],overlayLayers,templateFidelity:templateEvidence,...details}=await canvas.detailRender({

View File

@ -2,7 +2,6 @@ import { mkdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
const schemaVersion = 1;
const scopeColumns = 'account_id, project_id, output_id, variant_id';
const scopeValues = '?, ?, ?, ?';
const scopeWhere = 'account_id = ? AND project_id = ? AND output_id = ? AND variant_id = ?';
@ -17,7 +16,7 @@ const json = value => JSON.stringify(value, (_key, entry) => {
return entry;
});
const schema = `
const migrations = [`
CREATE TABLE production_ledgers (
${scopeDefinition},
metadata_json TEXT NOT NULL,
@ -87,7 +86,15 @@ const schema = `
FOREIGN KEY (${scopeColumns}, generation_id) REFERENCES delivery_generations (${scopeColumns}, generation_id),
FOREIGN KEY (${scopeColumns}, asset_id) REFERENCES assets (${scopeColumns}, asset_id)
) STRICT;
`;
`];
const schemaVersion = migrations.length;
function canonicalJson(value) {
return JSON.stringify(value, (_key, entry) => {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry;
return Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]]));
});
}
function transaction(db, work, write = true) {
db.exec(write ? 'BEGIN IMMEDIATE' : 'BEGIN');
@ -121,13 +128,17 @@ export class ProjectRepository {
const db = new DatabaseSync(path.toNamespacedPath(this.file), { timeout: 5000, enableForeignKeyConstraints: true });
try {
const version = () => db.prepare('PRAGMA user_version').get().user_version;
if (version() === 0) {
if (version() < schemaVersion) {
db.exec('PRAGMA journal_mode = WAL');
transaction(db, () => {
if (version() === 0) db.exec(`${schema} PRAGMA user_version = ${schemaVersion};`);
let v = version();
while (v < schemaVersion) {
db.exec(migrations[v++]);
db.exec(`PRAGMA user_version = ${v};`);
}
});
}
if (version() !== schemaVersion) throw Error('项目仓库版本不受当前客户端支持');
if (version() > schemaVersion) throw Error('项目仓库版本不受当前客户端支持');
return work(db);
} finally {
db.close();
@ -193,7 +204,7 @@ export class ProjectRepository {
if (!row.changes) {
const original = db.prepare(`SELECT value_json FROM project_versions WHERE ${scopeWhere}
AND kind = ? AND record_id = ? AND revision = ?`).get(...this.scope, kind, id, String(revision));
if (original.value_json !== encoded) throw Error('项目记录内容已变化,请保存为新版本');
if (canonicalJson(JSON.parse(original.value_json)) !== canonicalJson(JSON.parse(encoded))) throw Error('项目记录内容已变化,请保存为新版本');
}
}

View File

@ -1,3 +1,4 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { OVERLAY_SCREEN_FIELDS } from './copy-image-alignment.mjs';
import { Type } from '@sinclair/typebox';
import { productRequestScope } from './production-recovery.mjs';
@ -19,9 +20,9 @@ const finding = target => Type.Optional(Type.Array(object({
...target, issue:text(240), suggestion:text(240),
}), {maxItems:12}));
export const screenAssessment = object({
verdict:Type.Union([Type.Literal('pass'),Type.Literal('needs_fix')],{description:'必填。通过填 pass,有问题填 needs_fix 并列出至少一项。'}),
verdict:StringEnum(['pass', 'needs_fix'],{description:'必填。通过填 pass,有问题填 needs_fix 并列出至少一项。'}),
summary:Type.String({minLength:1,maxLength:280,description:'必填。简述整屏结论及画面依据。'}),
templateStyle:Type.Optional(Type.Union([Type.Boolean(),Type.Null()])),
templateStyle:Type.Optional(Type.Boolean()),
imageIssues:finding({
slotId:Type.Optional(Type.String({description:'可选。只填本屏清单里的 slotId。不知道编号时省略 slotId,只填写 location。'})),
slotNumber:Type.Optional(Type.Integer({description:'本屏 slots 清单中的序号,可替代 slotId。'})),
@ -31,7 +32,7 @@ export const screenAssessment = object({
copyFixes:finding({field:Type.Optional(Type.String()),screenFieldNumber:Type.Optional(Type.Integer({description:'本屏 screenCopy 清单中的序号。'})),location:Type.Optional(text(160))}),
});
export const TEMPLATE_REVIEW_GUIDANCE = field => `按项目锁定的企业 Skill 及品牌资料填写 ${field}。templateFidelity 提供图层差异、保留原文及事实冲突。read_output_screen 的 templateLayerId 返回指定图层原值与现值。缺少依据时 ${field} 填 null。`;
export const TEMPLATE_REVIEW_GUIDANCE = field => `按项目锁定的企业 Skill 及品牌资料填写 ${field}。templateFidelity 提供图层差异、保留原文及事实冲突。read_output_screen 的 templateLayerId 返回指定图层原值与现值。缺少依据时 ${field} 省略。`;
export function numberScreenCopy(screenCopy) {
return screenCopy.filter(row => row.field).map((row,index) => ({...row,screenFieldNumber:index+1}));
@ -167,7 +168,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
const audit=droppedReferences.length?{droppedReferences}:{};
validate(value,{example});
const {verdict} = value;
receipt = {page,revision,screenFingerprint,...value,...audit};
receipt = {page,revision,screenFingerprint,...value,templateStyle:value.templateStyle??null,...audit};
return {content:[{type:'text',text:'已收到本屏复核结论'}],details:{verdict,...audit},terminate:true};
},
};

View File

@ -166,6 +166,8 @@ export class StdioCanvas {
}
reply(text) { return this.action('pi-reply', {text}); }
activity(text, event) { return this.action('pi-activity', { text, ...(event ? { event } : {}) }); }
queueUpdate(value) { return this.call('pi-queue-update',value); }
userDelivered(value) { return this.call('pi-user-delivered',value); }
async contextUsage(value) {
try { return await this.action('pi-context-usage', { value }); }
catch (error) { if (!canvasReplyTimedOut(error)) throw error; }

View File

@ -1,9 +1,9 @@
import { StringEnum, validateToolArguments } from '@earendil-works/pi-ai';
import fs from 'node:fs/promises';
import { constants } from 'node:fs';
import path from 'node:path';
import lockfile from 'proper-lockfile';
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
import { BridgeError } from './bridge-error.mjs';
import { atomic, digest } from './store.mjs';
import { buildTimelineFilter, createVideoMedia, videoTransitions } from './video-ffmpeg.mjs';
@ -11,11 +11,11 @@ import { buildTimelineFilter, createVideoMedia, videoTransitions } from './video
const object = fields => Type.Object(fields, { additionalProperties: false });
const text = Type.String({ minLength: 1 });
const seconds = Type.Number({ minimum: 0 });
const duration = Type.Number({ exclusiveMinimum: 0 });
const dimension = Type.Integer({ minimum: 2, multipleOf: 2 });
const duration = Type.Number({ minimum: 0 });
const dimension = Type.Integer({ minimum: 2 });
const optional = Type.Optional;
const invalid = message => new BridgeError(message, 'invalid_video_input');
const filename = Type.String({ pattern: '^[^<>:"/\\\\|?*\\u0000-\\u001f]+$' });
const filename = Type.String({ minLength: 1 });
export const videoTools = [
['video_generate_clip', '按镜头描述与参考素材生成一个视频片段。同一 requestKey 用于读取或核查同一个原请求。',
@ -27,14 +27,14 @@ export const videoTools = [
path: text, start: optional(seconds), duration: optional(duration), still: optional(Type.Boolean()),
zoom: optional(object({ from: Type.Number({ minimum: 1, maximum: 10 }), to: Type.Number({ minimum: 1, maximum: 10 }) })),
interpolate: optional(Type.Boolean()),
transition: optional(object({ type: Type.Union(videoTransitions.map(value => Type.Literal(value))), duration })),
transition: optional(object({ type: StringEnum(videoTransitions), duration })),
}), { minItems: 1 }),
audioTracks: optional(Type.Array(object({ path: text, start: optional(seconds), offset: optional(seconds),
gain: optional(Type.Number({ minimum: 0 })) }))),
muteSource: optional(Type.Boolean()),
subtitles: optional(object({ path: optional(text), captions: optional(Type.Array(
object({ start: seconds, end: duration, text }), { minItems: 1 })),
mode: Type.Union(['burn', 'sidecar', 'both'].map(value => Type.Literal(value))) })),
mode: StringEnum(['burn', 'sidecar', 'both']) })),
outputDir: optional(text), name: filename, width: dimension, height: dimension,
fps: Type.Integer({ minimum: 1, maximum: 120 }), coverTime: optional(seconds),
crf: optional(Type.Integer({ minimum: 0, maximum: 51 })), audioBitrateKbps: optional(Type.Integer({ minimum: 1 })),
@ -45,7 +45,11 @@ export const videoTools = [
const schemas = new Map(videoTools.map(([name, , schema]) => [name, schema]));
const validate = (name, input) => {
if (!Value.Check(schemas.get(name), input)) throw invalid('视频工具参数不符合要求');
try {
return validateToolArguments({name,parameters:schemas.get(name)},{name,arguments:input});
} catch (error) {
throw invalid(error.message);
}
};
function videoRequestSpec({ prompt, firstFrame, lastFrame, referenceImages = [], duration, aspectRatio, model }) {
@ -134,9 +138,11 @@ async function subtitleText({ path: file, captions }, duration) {
}
async function composeTimeline(input, { media, deliveryDir }, signal) {
if (input.width % 2 || input.height % 2) throw invalid('视频宽高必须为偶数');
if (input.clips.some(clip => clip.duration === 0 || clip.transition?.duration === 0)) throw invalid('片段和转场时长必须大于 0');
const { clips, subtitles, outputDir = deliveryDir, name, coverTime = 0 } = input;
if (!outputDir) throw invalid('请指定成品目录');
if (name.endsWith('.') || name.endsWith(' ')) throw invalid('请填写有效的成品文件名');
if (/[<>:"/\\|?*\x00-\x1f]/.test(name) || name.endsWith('.') || name.endsWith(' ')) throw invalid('请填写有效的成品文件名');
const resolved = await Promise.all(clips.map(async clip => {
const start = clip.start ?? 0;
if (clip.still) {
@ -205,15 +211,16 @@ export function createVideoToolExecutors({ generator, ledgerDir, deliveryDir, ..
const media = createVideoMedia(ffmpeg);
return {
async video_generate_clip(input, signal) {
validate('video_generate_clip', input);
input = validate('video_generate_clip', input);
if (input.duration === 0) throw invalid('片段时长必须大于 0');
return generateClip(input, { media, generator, ledgerDir }, signal);
},
async video_compose_timeline(input, signal) {
validate('video_compose_timeline', input);
input = validate('video_compose_timeline', input);
return composeTimeline(input, { media, deliveryDir }, signal);
},
async video_inspect(input, signal) {
validate('video_inspect', input);
input = validate('video_inspect', input);
const info = await media.inspect(input.path, signal);
const frameTimes = [...new Set(input.frameTimes ?? [0])];
if (frameTimes.some(time => time >= info.duration)) throw invalid('抽帧时间超出视频范围');

View File

@ -0,0 +1,73 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import { openAgent } from './fake-canvas.mjs';
import { assistant, piInfo, piProject } from './pi-compat-fixture.mjs';
test('a fresh lock from a dead process is reclaimed immediately while a live owner is protected',async t=>{
const store=await piProject(t);
const module=new URL('../src/production-goal.mjs',import.meta.url).href;
const child=spawn(process.execPath,['--input-type=module','-e',
'const {lockProjectSession}=await import(process.argv[1]); await lockProjectSession(process.argv[2]); console.log("locked"); setInterval(()=>{},1000);',
module,store.root],{stdio:['ignore','pipe','inherit'],windowsHide:true});
try {
const [bytes]=await once(child.stdout,'data');
assert.match(bytes.toString(),/locked/);
const options={store,transport:{info:piInfo(store)}};
await assert.rejects(openAgent(options),/已有本地Agent/);
const exit=once(child,'exit');
child.kill('SIGKILL');
await exit;
const host=await openAgent(options);
await host.dispose();
await assert.rejects(fs.stat(store.root+'.lock'),{code:'ENOENT'});
} finally { if (child.exitCode===null && child.signalCode===null) child.kill('SIGKILL'); }
});
test('recovers a corrupt pointer and truncated transcript while retaining completed tool receipts',async t=>{
const store=await piProject(t);
const dir=path.join(store.dir,'sessions');
const manager=SessionManager.create(store.dir,dir);
const info=piInfo(store);
const model={id:info.model.id,api:'openai-completions',provider:'jiansun-native-98k'};
const toolCalls=['done','pending'].map(id=>({type:'toolCall',id,name:'canvas_read',arguments:{layer:1}}));
manager.appendMessage({role:'user',content:'请读两次画布',timestamp:1});
manager.appendMessage(assistant(model,toolCalls,'toolUse'));
manager.appendMessage({role:'toolResult',toolCallId:'done',toolName:'canvas_read',content:[{type:'text',text:'已读'}],isError:false,timestamp:2});
const file=manager.getSessionFile();
const pointer=path.join(store.dir,'session.json');
const corrupted='{"type":"message","id":"invalid"}\n{"type":"message","id":';
await fs.appendFile(file,corrupted);
await fs.writeFile(pointer,'{"file":');
const options={store,transport:{info}};
for (let i=0;i<2;i++) {
const host=await openAgent(options);
try {
assert.equal(host.manager.getSessionFile(),file);
assert.deepEqual(host.manager.buildSessionContext().messages.filter(m=>m.role==='toolResult')
.map(m=>[m.toolCallId,m.isError]),[['done',false],['pending',true]]);
} finally { await host.dispose(); }
}
const backups=(await fs.readdir(dir)).filter(name=>name.includes('.corrupt-'));
assert.equal(backups.length,1);
assert.equal(await fs.readFile(path.join(dir,backups[0]),'utf8'),corrupted);
assert.equal(JSON.parse(await fs.readFile(pointer,'utf8')).file,file);
assert.equal((await fs.readdir(store.dir)).filter(name=>name.startsWith('session.json.corrupt-')).length,1);
for (const line of (await fs.readFile(file,'utf8')).trim().split('\n')) JSON.parse(line);
});
test('a missing saved session creates a new project-local session',async t=>{
const store=await piProject(t);
const missing=path.join(store.dir,'sessions','missing.jsonl');
await fs.writeFile(path.join(store.dir,'session.json'),JSON.stringify({file:missing}));
const host=await openAgent({store,transport:{info:piInfo(store)}});
try {
assert.notEqual(host.manager.getSessionFile(),missing);
assert.equal(path.dirname(host.manager.getSessionFile()),path.dirname(missing));
assert.deepEqual(host.manager.buildSessionContext().messages,[]);
} finally { await host.dispose(); }
});

View File

@ -3,7 +3,7 @@ import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { Value } from '@sinclair/typebox/value';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { mergeReviewCopy, extractPageLiveCopy, resolveLiveSlotCopy } from '../src/copy-image-alignment.mjs';
import { reviewProductionCandidate } from '../src/candidate-review.mjs';
import { openProductionOperations } from '../src/production-operations.mjs';
@ -77,7 +77,7 @@ test('candidate review records the observed subject and alignment while acceptin
const assessment={screenVerdict:'pass',candidateId:'candidate',verdict:'revise',reason:'桌腿未入画',
...(shownSubject?{shownSubject}:{}),
checks:{...checks,...(copyAlignment===false?{copyAlignment}:{})}};
assert.ok(Value.Check(tool.parameters,assessment));
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:assessment}),assessment);
await tool.execute('review',assessment);
},
});

View File

@ -10,6 +10,7 @@ const quiet = {
async readCanvas() { return this.read(); },
async workflowRead() { return {available:false,version:1}; },
async detailCopyFields({includeFilled} = {}) { return includeFilled ? {} : []; },
async queueUpdate() {}, async userDelivered() {},
async delta() {}, async reply() {}, async activity() {}, async end() {}, async contextUsage() {},
async uiRequest() { return {}; }, async uiPoll() { return {}; }, async uiCancel() {},
};

View File

@ -0,0 +1,69 @@
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { ModelRuntime } from '@earendil-works/pi-coding-agent';
import { openAgent } from './fake-canvas.mjs';
import { assistant, piInfo, piProject, replyStream } from './pi-compat-fixture.mjs';
test('Pi records live and restored model and thinking selections across native APIs',async t=>{
const store=await piProject(t);
const catalog=await ModelRuntime.create({authPath:path.join(store.dir,'catalog-auth.json'),modelsPath:null,
modelsStorePath:path.join(store.dir,'catalog-cache'),refreshOnCreate:false,allowModelNetwork:false});
const anthropic=catalog.getModels('anthropic').find(model=>model.compat?.forceAdaptiveThinking);
const responses=catalog.getModels('openai').find(model=>model.api==='openai-responses');
const chat=catalog.getModels('deepseek').find(model=>model.api==='openai-completions' && model.compat);
assert.ok(anthropic && responses && chat);
const selection=(model,protocol,level='off')=>({...piInfo(store,{id:model.id,protocol}),thinkingLevel:level});
let info=selection(anthropic,'anthropic-messages','high');
const seen=[];
const broker={
info:async()=>info,
round(){return {id:'chat-round',fetch:async (_url,init)=>{
const payload=JSON.parse(init.body);
const calls=payload.messages.flatMap(message=>message.tool_calls??[]);
const results=payload.messages.filter(message=>message.role==='tool');
assert.equal(calls.length,2);
assert.deepEqual(results.map(result=>result.tool_call_id),calls.map(call=>call.id));
assert.equal(new Set(calls.map(call=>call.id)).size,2);
assert.ok(calls.every(call=>call.id.length<=40));
assert.equal(payload.parallel_tool_calls,undefined);
return new Response('data: '+JSON.stringify({id:'fixture',model:chat.id,
choices:[{index:0,delta:{content:'已切换'},finish_reason:'stop'}]})+'\n\ndata: [DONE]\n\n',
{headers:{'content-type':'text/event-stream'}});
}};},
};
let host;
try {
host=await openAgent({store,broker,transport:{info,stream(model,_context,options){
seen.push([model.api,options.reasoning??'off']);
return replyStream(model,'已记录');
}}});
for(const [model,protocol,level] of [[anthropic,'anthropic-messages','high'],[responses,'openai-responses','off']]){
info=selection(model,protocol,level);
await host.prompt('记录所选模型');
assert.equal(host.session.model.id,model.id);
assert.equal(host.session.thinkingLevel,level);
assert.deepEqual(host.session.model.compat,{...model.compat,supportsStore:false,supportsMessageThreads:false});
}
assert.deepEqual(seen,[['anthropic-messages','high'],['openai-responses','off']]);
const longIds=['a','b'].map(suffix=>'toolu_'+ 'x'.repeat(65)+suffix);
host.manager.appendMessage(assistant({id:anthropic.id,api:'anthropic-messages',provider:'jiansun-native-98k'},
longIds.map(id=>({type:'toolCall',id,name:'canvas_read',arguments:{layer:1}})),'toolUse'));
for (const toolCallId of longIds) host.manager.appendMessage({role:'toolResult',toolCallId,toolName:'canvas_read',
content:[{type:'text',text:'已读'}],isError:false,timestamp:Date.now()});
const file=host.manager.getSessionFile();
await host.dispose();
host=null;
info=selection(chat,'openai-chat');
host=await openAgent({store,broker,callBudget:1});
assert.equal(host.session.model.api,'openai-completions');
assert.equal(host.session.thinkingLevel,'off');
assert.deepEqual(host.session.model.compat,{...chat.compat,supportsStore:false,supportsMessageThreads:false});
assert.equal((await host.prompt('继续聊天')).text,'已切换');
const entries=(await fs.readFile(file,'utf8')).trim().split('\n').map(JSON.parse);
assert.deepEqual(entries.filter(entry=>entry.type==='model_change').map(entry=>entry.modelId),[anthropic.id,responses.id,chat.id]);
assert.deepEqual(entries.filter(entry=>entry.type==='thinking_level_change').map(entry=>entry.thinkingLevel),['high','off']);
} finally { await host?.dispose(); }
});

View File

@ -25,7 +25,7 @@ import { projectTools } from '../src/project-tools.mjs';
import { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs';
import { callProductionTool } from '../src/production-goal.mjs';
import { productionStore, stubProductionOperations } from './production-store-fixture.mjs';
import { Value } from '@sinclair/typebox/value';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { canvasReadParameters, canvasReadQuery } from '../src/canvas-contract.mjs';
import { nativeCatalogParameters, nativeTools } from '../src/native-tools.mjs';
@ -54,10 +54,11 @@ test('native_catalog batches exact host lookups, reports misses and retains comm
const [catalog, call] = nativeTools(host, (_name, _description, _parameters, execute) => ({execute}));
const args = {id: ' layer.list ', ids: ['layer.list', 'type.edit', ' type.edit ', 'unknown.command', ' '],
filter: 'ignored', offset: 2, limit: 1};
assert.equal(Value.Check(nativeCatalogParameters, args), true);
for (const invalid of [{ids: []}, {ids: ['']}, {ids: ['type.edit', 'type.edit']},
const tool = {name:'native_catalog',parameters:nativeCatalogParameters};
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:args}),args);
for (const invalid of [{ids: []}, {ids: ['']},
{ids: Array.from({length: 13}, (_, i) => String(i))}, {ids: ['x'.repeat(161)]}, {ids: ['a'], extra: true}]) {
assert.equal(Value.Check(nativeCatalogParameters, invalid), false);
assert.throws(()=>validateToolArguments(tool,{name:tool.name,arguments:invalid}));
}
assert.deepEqual(await catalog.execute(args), {
...metadata, matchMode: 'exact-ids', total: 2, items, missingIds: ['unknown.command'],
@ -650,7 +651,7 @@ test('actual native Pi wire sends function schemas, executes typed call and acce
assert.equal((await x.store.context()).confirmedMemory.color.value, '胡桃色');
assert.equal(x.requests.length, 2);
assert.deepEqual(x.requests[0].tool_choice, { type: 'function', function: { name: 'memory_set' } });
assert.equal(x.requests[0].parallel_tool_calls, false);
assert.equal(x.requests[0].parallel_tool_calls, undefined);
assert.ok(x.requests[0].tools.some(t => t.type === 'function' && t.function.name === 'memory_set'));
assert.ok(x.requests[1].messages.some(m => m.role === 'tool' && m.tool_call_id === 'call-memory'));
assert.equal(x.requests[0].response_format, undefined);
@ -1150,7 +1151,7 @@ test('canvas search keeps the screen and keyword when a layer argument is also p
test('the Pi canvas contract forwards a deeper group summary with the requested scope',()=>{
const query={screenId:90,maxDepth:6};
assert.ok(Value.Check(canvasReadParameters,query));
assert.deepEqual(validateToolArguments({name:'canvas_read',parameters:canvasReadParameters},{name:'canvas_read',arguments:query}),query);
assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0});
});

View File

@ -0,0 +1,42 @@
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
import { ProjectStore } from '../src/store.mjs';
import { cleanup } from './cleanup.mjs';
export async function piProject(t) {
const root=await fs.mkdtemp(path.join(os.tmpdir(),'pi-recovery-'));
t.after(()=>cleanup(root));
return ProjectStore.open(root,{scope:'d'.repeat(64),project:randomUUID()},
{brandId:'qa',shopId:'qa',categoryId:'qa',platform:'qa',version:'1',source:'fixture',rules:[]},{continuous:true});
}
export const piInfo = (store, model = {}) => ({
accountScope:store.identity.scope,thinkingLevel:'off',
model:{id:'qa',protocol:'openai-chat',reasoning:true,reasoningEfforts:['low','high'],...model},
});
export const usage = {input:1,output:1,cacheRead:0,cacheWrite:0,totalTokens:2,
cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};
export function assistant(model, content, stopReason='stop') {
return {role:'assistant',api:model.api,provider:model.provider,model:model.id,content,stopReason,usage,timestamp:Date.now()};
}
export function replyStream(model, text, wait = Promise.resolve()) {
const stream=createAssistantMessageEventStream();
void wait.then(()=>{
const message=assistant(model,[{type:'text',text}]);
stream.push({type:'start',partial:{...message,content:[]}});
stream.push({type:'text_delta',contentIndex:0,delta:text,partial:message});
stream.push({type:'done',reason:'stop',message});
stream.end(message);
},error=>{
const message={...assistant(model,[],'aborted'),errorMessage:error.message};
stream.push({type:'error',reason:'aborted',error:message});
stream.end(message);
});
return stream;
}

View File

@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import test from 'node:test';
import { ProjectRepository } from '../src/project-repository.mjs';
import { piProject } from './pi-compat-fixture.mjs';
test('a version-zero project DB migrates and newer versions are rejected without rewriting data',async t=>{
const store=await piProject(t);
const file=path.join(store.dir,'project.sqlite');
const scope={accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'};
let db=new DatabaseSync(file);
db.exec('CREATE TABLE prior_workspace (name TEXT); INSERT INTO prior_workspace VALUES (\'existing\');');
db.close();
const repo=new ProjectRepository(file,scope);
repo.saveVersion('plan','plan',1,{slots:[{label:'首屏',frame:{y:2,x:1}}],template:'sample'});
repo.saveVersion('plan','plan',1,{template:'sample',slots:[{frame:{x:1,y:2},label:'首屏',optional:undefined}]});
assert.throws(()=>repo.saveVersion('plan','plan',1,{template:'sample',slots:[]}),/新版本/);
db=new DatabaseSync(file);
try {
assert.equal(db.prepare('PRAGMA user_version').get().user_version,1);
assert.equal(db.prepare('SELECT name FROM prior_workspace').get().name,'existing');
db.exec('PRAGMA user_version = 99;');
} finally { db.close(); }
assert.throws(()=>repo.readVersion('plan','plan',1),/版本不受/);
db=new DatabaseSync(file);
try {
assert.equal(db.prepare('PRAGMA user_version').get().user_version,99);
assert.equal(db.prepare('SELECT count(*) AS count FROM project_versions').get().count,1);
} finally { db.close(); }
});

View File

@ -208,7 +208,7 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
}
assert.equal(executed,cases.length);
assert.equal(sent.length,cases.length);
assert.equal(sent[0].thinking,undefined);
assert.deepEqual(sent[0].thinking,{type:'disabled'});
assert.equal(sent[0].output_config,undefined);
for(const body of sent){
assert.equal(body.max_tokens,128000);

View File

@ -4,7 +4,7 @@ import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { Value } from '@sinclair/typebox/value';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
import { activityToolLabel, toolActivity } from '../src/activity-event.mjs';
import { completeCanvas, openAgent } from './fake-canvas.mjs';
@ -335,8 +335,8 @@ test('screen reviews keep images in the worker and persist findings and passes',
};
const receipts=await callProductionTool(host,'check_output_screens',{pages:[1,2,2,17,19]});
assert.deepEqual(receipts,[
{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',...pass},{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',...needsFix},
{page:17,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P17',...needsFix,imageIssues:[{...needsFix.imageIssues[0],slotId:'slot-17'}],
{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',templateStyle:null,...pass},{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',templateStyle:null,...needsFix},
{page:17,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P17',templateStyle:null,...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,16]);
@ -363,7 +363,7 @@ test('Pi drops invalid references and keeps located findings', {timeout:10_000},
copyFixes:[{...locationOnly.copyFixes[0],field:'wrong-field',screenFieldNumber:999}],
}));
const [receipt]=await actions.check_output_screens({pages:[2],wait:true});
assert.deepEqual(receipt,{reviewRound:1,issueHistory:[],page:2,revision:7,screenFingerprint:'screen-P2',...locationOnly,
assert.deepEqual(receipt,{reviewRound:1,issueHistory:[],page:2,revision:7,screenFingerprint:'screen-P2',templateStyle:null,...locationOnly,
droppedReferences:[
{path:'imageIssues[0].slotId',value:' '},{path:'imageIssues[0].slotNumber',value:999},
{path:'overlayFixes[0].nativeLayerId',value:999},{path:'copyFixes[0].field',value:'wrong-field'},
@ -457,7 +457,7 @@ test('finish and progress keep screen reviews across unrelated edits and clear t
const reviewed=await actions.review_image_slots({});
assert.equal(waiting.progressSummary.screensWithOpenIssues,reviewed.progressSummary.screensWithOpenIssues.length);
assert.deepEqual(await actions.read_screen_review({page:2}),
{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',...needsFix});
{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',templateStyle:null,...needsFix});
const reopened=await openProductionOperations(host);
assert.deepEqual(await reopened.read_screen_review({page:2}),await actions.read_screen_review({page:2}));
await reopened.close();
@ -507,7 +507,7 @@ test('screen reviews share the six-worker queue and expose asynchronous receipts
await sixScreens.promise;
assert.equal(started,6);
screens.resolve();
assert.deepEqual(await joined,[{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',...pass}]);
assert.deepEqual(await joined,[{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',templateStyle:null,...pass}]);
let result=await actions.await_image_slots({});
while(result.screenChecks.some(row=>row.state==='queued'||row.state==='checking')){
result=await actions.await_image_slots({});
@ -563,9 +563,11 @@ test('an unrelated screen edit during a worker review preserves its pass',async
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,17]}),true);
for(const args of [{pages:[0]},{pages:[]},{pages:['1']},{pages:[2],wait:'false'}]){
assert.equal(Value.Check(schema,args),false);
const tool={name:'check_output_screens',parameters:schema};
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:{pages:[1,17]}}),{pages:[1,17]});
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:{pages:['1'],wait:'false'}}),{pages:[1],wait:false});
for(const args of [{pages:[0]},{pages:[]},{pages:['page']},{pages:[2],wait:'sometimes'}]){
assert.throws(()=>validateToolArguments(tool,{name:tool.name,arguments:args}));
}
assert.match(description,/默认等待结论/);
const event={type:'tool_execution_start',toolName:'check_output_screens',toolCallId:'call-9',args:{pages:[1]}};

View File

@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { EventEmitter, once } from 'node:events';
import { PassThrough } from 'node:stream';
import test from 'node:test';
import { startDaemon } from '../src/desktop-daemon.mjs';
import { observeCanvasCalls } from '../src/desktop-host.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { runPiProductionGoal, settleProductionGoal } from '../src/production-goal.mjs';
import { openAgent } from './fake-canvas.mjs';
import { piInfo, piProject, replyStream } from './pi-compat-fixture.mjs';
test('daemon delivers native steer and follow-up, clears queues, and aborts chat by run identity', {timeout:15_000},async t=>{
const store=await piProject(t);
const input=new PassThrough(), output=new PassThrough(), events=new EventEmitter();
const startup=Promise.withResolvers(), first=Promise.withResolvers();
const firstStarted=Promise.withResolvers(), finalStarted=Promise.withResolvers();
const frames=[], observed=[], replies=[];
const runId=randomUUID();
const identity={...store.identity,documentId:7};
output.on('data',bytes=>{
const frame=JSON.parse(bytes.toString());
frames.push(frame);
events.emit('frame');
});
const waitFor=async predicate=>{
const signal=AbortSignal.timeout(8000);
while(!frames.some(predicate)) await once(events,'frame',{signal});
return frames.find(predicate);
};
const send=value=>input.write(JSON.stringify(value)+'\n');
const control=async(type,fields={})=>{
const id=randomUUID();
send({type,id,runId,...identity,...fields});
return waitFor(frame=>frame.type===type+'_ack'&&frame.id===id);
};
const daemon=startDaemon({input,output,parentAlive:()=>true,exit:()=>{},
brokerFactory:()=>({close:async()=>{}}),
async runSession(_config,call,_broker,_recovery,signal,_auth,onHostReady){
await startup.promise;
const canvas=new StdioCanvas(observeCanvasCalls(store,call),identity.documentId);
const host=await openAgent({store,productionSignal:signal,
canvas:{queueUpdate:canvas.queueUpdate.bind(canvas),userDelivered:canvas.userDelivered.bind(canvas),
reply:async text=>replies.push(text)},
transport:{info:piInfo(store),stream(model,context){
const users=context.messages.filter(message=>message.role==='user').map(message=>JSON.stringify(message.content));
observed.push(users);
if(observed.length===1) firstStarted.resolve();
if(observed.length===3) finalStarted.resolve();
const wait=observed.length===1?first.promise:observed.length===3?
once(signal,'abort').then(()=>{throw signal.reason;}):Promise.resolve();
return replyStream(model,'第'+observed.length+'段回复',wait);
}},
});
const abort=()=>{void host.session.abort();};
signal.addEventListener('abort',abort,{once:true});
try {
onHostReady(host);
return await host.prompt('开始讨论');
} finally {
signal.removeEventListener('abort',abort);
await host.dispose();
}
}});
try {
assert.equal((await control('steer',{text:'无任务'})).reason,'no_active_run');
send({type:'run',runId,config:identity});
assert.equal((await control('steer',{text:'启动中'})).reason,'starting');
startup.resolve();
await firstStarted.promise;
assert.equal((await control('steer',{text:'错画布',documentId:8})).reason,'scope_mismatch');
assert.equal((await control('steer',{text:'撤回插话'})).disposition,'queued');
assert.equal((await control('steer',{text:'撤回追问',behavior:'followUp'})).disposition,'queued');
const {steering,followUp,error}=await control('clear_queue');
assert.deepEqual({steering,followUp,error},{steering:['撤回插话'],followUp:['撤回追问'],error:null});
assert.equal((await control('steer',{text:'插话',referenceContent:[{label:'参考图层',nativeLayerId:12}]})).accepted,true);
assert.equal((await control('steer',{text:'追问',behavior:'followUp'})).accepted,true);
assert.ok(frames.some(frame=>frame.type==='presentation'&&frame.action==='pi-queue-update'));
first.resolve();
const delivered=await waitFor(frame=>frame.action==='pi-user-delivered'&&frame.input.behavior==='followUp');
assert.equal(delivered.input.text,'追问');
assert.equal(typeof delivered.input.timestamp,'number');
assert.deepEqual(frames.filter(frame=>frame.action==='pi-user-delivered')
.map(({input})=>[input.text,input.behavior]),[['插话','steer'],['追问','followUp']]);
assert.deepEqual(replies,['第1段回复','第2段回复']);
await finalStarted.promise;
assert.match(observed.at(-1).join('\n'),/参考图层/u);
assert.doesNotMatch(observed.at(-1).join('\n'),/撤回/u);
send({type:'abort_run',runId,...identity,project:'wrong-project'});
assert.equal((await control('clear_queue')).error,null);
send({type:'abort_run',runId,...identity});
const complete=await waitFor(frame=>frame.type==='complete'&&frame.runId===runId);
assert.match(complete.value.error,/本轮已停止/u);
assert.ok(frames.every(frame=>frame.type!=='fatal'));
} finally { first.resolve(); await daemon.stop(); }
});
test('production continues after an interjection and carries platform facts in the goal request',async t=>{
const store=await piProject(t);
const goal={status:'active',objective:'fixture'};
const sent=[];
const host={manager:{getBranch:()=>[{type:'custom',customType:'pi-goal',data:{goal}}]},
store,productionGoal:{requestedOutputs:[{outputId:'detail',label:'详情页'}]},
productEvidence:{platformFacts:{shared:{claims:['已核对']}}},
session:{pendingMessageCount:1,messages:[],prompt:async text=>sent.push(text),waitForIdle:async()=>{},
sendCustomMessage:async message=>sent.push(message),clearQueue:()=>sent.push('clear')}};
const start={role:'custom',customType:'pi-goal-event',details:{kind:'continuation'}};
const end={role:'assistant',content:[{type:'text',text:'已收到'}],stopReason:'stop'};
await settleProductionGoal(host,{messages:[start,end]});
host.session.pendingMessageCount=0;
await settleProductionGoal(host,{messages:[start,{role:'user'},end]});
assert.deepEqual(sent,[]);
await settleProductionGoal(host,{messages:[start,end]});
assert.deepEqual(sent,['/goal pause','clear']);
sent.length=0;
await runPiProductionGoal(host,'开始制作',false);
assert.deepEqual(JSON.parse(sent[0].content).platformFacts,host.productEvidence.platformFacts);
});

View File

@ -0,0 +1,144 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { anthropicMessagesApi, normalizeContext, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
import { convertTools as googleTools } from '@earendil-works/pi-ai/api/google-shared';
import { renderToolSample } from '@earendil-works/pi-codemode';
import { openProductionOperations } from '../src/production-operations.mjs';
import { reviewProductionCandidate } from '../src/candidate-review.mjs';
import { reviewOutputScreen } from '../src/screen-review.mjs';
import { completeCanvas, openAgent } from './fake-canvas.mjs';
import { piInfo, piProject } from './pi-compat-fixture.mjs';
function inspectSchema(schema, name) {
assert.ok(schema.type || schema.anyOf || schema.oneOf || schema.allOf || schema.$ref,`untyped schema: ${name}`);
assert.notEqual(schema.type,'null',name);
for (const keyword of ['const','minProperties','uniqueItems','exclusiveMinimum','multipleOf','prefixItems','nullable']) {
assert.ok(!Object.hasOwn(schema,keyword),`${keyword}: ${name}`);
}
assert.doesNotMatch(schema.pattern??'',/\\u[0-9a-f]{4}/i,name);
assert.ok(!Array.isArray(schema.items),`tuple items: ${name}`);
if (schema.type==='array') assert.ok(schema.items,`array without items: ${name}`);
if (schema.additionalProperties===true && schema.properties) {
assert.ok(Object.keys(schema.properties).length,`empty open properties: ${name}`);
}
for (const [key,child] of Object.entries(schema.properties??{})) inspectSchema(child,name+'.'+key);
if (schema.items) inspectSchema(schema.items,name+'[]');
for (const child of [...(schema.anyOf??[]),...(schema.oneOf??[]),...(schema.allOf??[])]) inspectSchema(child,name);
if (typeof schema.additionalProperties==='object') inspectSchema(schema.additionalProperties,name+'.*');
}
function sample(schema) {
if (schema.default!==undefined) return schema.default;
if (schema.enum) return schema.enum[0];
if (schema.anyOf) return sample(schema.anyOf[0]);
if (schema.type==='object') return Object.fromEntries((schema.required??[]).map(key=>[key,sample(schema.properties[key])]));
if (schema.type==='array') return Array.from({length:schema.minItems??0},()=>sample(schema.items));
if (schema.type==='boolean') return true;
if (schema.type==='integer' || schema.type==='number') return Math.max(schema.minimum??1,0);
if (schema.pattern) {
const example=['P01','1:1','#111111','a'.repeat(64),'a'.repeat(36)].find(value=>new RegExp(schema.pattern).test(value));
assert.ok(example,schema.pattern);
return example;
}
return 'x'.repeat(Math.max(1,schema.minLength??0));
}
async function wireSchemas(api, factory, tools) {
let payload;
const model={id:'schema-test',name:'schema-test',api,provider:'fixture',
baseUrl:api==='anthropic-messages'?'https://example.invalid':'https://example.invalid/v1',
input:['text'],maxTokens:512,contextWindow:12_000,reasoning:false,
cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
const stream=factory().streamSimple(model,normalizeContext({tools,messages:[
{role:'user',content:'schema fixture',timestamp:1},
]}),{apiKey:'fixture',maxRetries:0,onPayload(value){payload=value;},
fetch:async()=>new Response('{}',{status:400})});
await stream.result();
assert.ok(payload?.tools,api);
return payload.tools.map(tool=>api==='anthropic-messages'?[tool.name,tool.input_schema] :
api==='openai-responses'?[tool.name,tool.parameters]:[tool.function.name,tool.function.parameters]);
}
test('all registered chat, production and worker tool schemas pass Pi validation and four wire converters',async t=>{
const store=await piProject(t);
const model=piInfo(store);
const productionGoal={workspaceId:'schema-test',requestedOutputs:[{outputId:'detail',variantId:'natural'}]};
const modes=[];
for (const goal of [undefined,productionGoal]) {
const host=await openAgent({store,transport:{info:model},productionGoal:goal});
try { modes.push(host.session.getAllTools()); }
finally { await host.dispose(); }
}
const image={type:'image',data:'fixture',mimeType:'image/png'};
const slot={id:'slot',fieldId:'field',label:'首屏'};
const screen={image,content:[image],details:{page:0,revision:1,screenFingerprint:'fixture',
slots:[slot],overlayLayers:[],screenCopy:[]}};
const workerTools=[];
await reviewProductionCandidate({canvas:{detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image]})},
slot,candidateId:'candidate',screen,rule:{structureGuides:{edge:'部件边缘'}},
async runAgent(_id,_system,_prompt,[tool]){
workerTools.push(tool);
const args={verdict:'pass',reason:'已核对',checks:{templateStyle:null,viewpoint:null},
canvasTransform:{crop:[0,0,1000,1000]},structureGuides:{edge:[[10,20]]}};
const checked=validateToolArguments(tool,{name:tool.name,arguments:args});
assert.notEqual(checked.checks.viewpoint,false);
assert.notEqual(checked.checks.templateStyle,false);
await tool.execute('review',args);
}});
await reviewOutputScreen({page:1,screen,slots:[slot],outputId:'detail',variantId:'natural',
references:async()=>({photos:[]}),async runAgent(_id,_system,_prompt,[tool]){
workerTools.push(tool);
await tool.execute('review',{verdict:'pass',summary:'已核对',templateStyle:null});
}});
const slots=[slot,{id:'slot-2',fieldId:'field-2',label:'细节图'},{id:'slot-3',fieldId:'field-3',label:'局部图'}];
const delegateTools=[];
const groupedTools=[];
const canvas=completeCanvas({
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'natural',
template:{contentHash:'schema-test'},slots,totalSlots:slots.length}),
imageRequest:async()=>[],
});
const operations=await openProductionOperations({canvas,store,
productionGoal:{outputId:'detail',variantId:'natural'},
runDetailAgent:async(_id,_system,prompt,tools)=>{
const target=JSON.parse(prompt).groupTargets?groupedTools:delegateTools;
target.push(...tools);
}});
try {
await operations.delegate_image_slots({jobs:[
{slotId:'slot',goal:'展示商品'},
{slotId:'slot-2',goal:'展示结构',reuseTargets:[{slotId:'slot-3'}]},
]});
while (operations.active) await operations.await_image_slots({});
} finally { await operations.close(); }
assert.ok(delegateTools.some(tool=>tool.name==='prepare_image_request'));
assert.ok(groupedTools.some(tool=>tool.name==='adopt_production_image'));
modes.push(workerTools,delegateTools,groupedTools);
const preview=modes[0].find(tool=>tool.name==='canvas_preview');
const args={command:'type.edit',params:{layer:1,box:[1,2,3,4],
runs:[{start:0,end:2,font:'Inter',kerning:-20,features:{ss01:true},variations:{wght:650}}]}};
assert.deepEqual(validateToolArguments(preview,{name:preview.name,arguments:args}),args);
const productImage=delegateTools.find(tool=>tool.name==='use_product_image');
assert.throws(()=>validateToolArguments(productImage,{name:productImage.name,arguments:{referenceCrop:[1,2,3]}}));
for (const tools of modes) {
for (const tool of tools) {
inspectSchema(tool.parameters,tool.name);
const args=sample(tool.parameters);
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:args}),args,tool.name);
assert.ok(renderToolSample({name:tool.name,description:tool.description,inputSchema:tool.parameters}).includes(tool.name));
}
const google=googleTools(tools)[0].functionDeclarations.map(tool=>[tool.name,tool.parametersJsonSchema]);
for (const declarations of [
await wireSchemas('anthropic-messages',anthropicMessagesApi,tools),
await wireSchemas('openai-responses',openAIResponsesApi,tools),
await wireSchemas('openai-completions',openAICompletionsApi,tools),google,
]) {
assert.deepEqual(declarations.map(([name])=>name),tools.map(tool=>tool.name));
for (const [name,schema] of declarations) inspectSchema(schema,name);
}
}
});