1398 lines
91 KiB
JavaScript
1398 lines
91 KiB
JavaScript
import { canvasToolReceipts } from './stdio-canvas.mjs';
|
||
import { toolSchema, defineTool } from './tool-schema.mjs';
|
||
import { productRequestScope } from './production-recovery.mjs';
|
||
import { executeWorkflow } from './workflow-execute.mjs';
|
||
import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
|
||
import path from 'node:path';
|
||
import { setTimeout as delay } from 'node:timers/promises';
|
||
import fs from 'node:fs/promises';
|
||
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, modelDispatchIdentity, unknownModelOutcome } from './bridge-error.mjs';
|
||
import { protectSession, redact, redactText } from './credentials.mjs';
|
||
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, lockProjectSession, productionGoalState, runProductionGoal, 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, StringEnum } from '@earendil-works/pi-ai';
|
||
import { streamSimple as streamAnthropic } from '@earendil-works/pi-ai/api/anthropic-messages';
|
||
import { streamSimple as streamChat } from '@earendil-works/pi-ai/api/openai-completions';
|
||
import { streamSimple as streamResponses } from '@earendil-works/pi-ai/api/openai-responses';
|
||
import { createInitialSystemMessage, getCurrentTools } from '@earendil-works/pi-ai/utils/transcript';
|
||
import { streamGoogle } from './google-broker-stream.mjs';
|
||
import { googleModelPath } from './native-bridge.mjs';
|
||
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
|
||
import { atomic } from './store.mjs';
|
||
import { workerTurnBudget } from './worker-receipts.mjs';
|
||
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
|
||
import { productContext } from './project-context.mjs';
|
||
import { workflowContext, workflowResult } from './workflow-context.mjs';
|
||
import { EnterpriseContext } from './enterprise-context.mjs';
|
||
import { openXiaoyiSkills } from './xiaoyi-release.mjs';
|
||
import { projectTools } from './project-tools.mjs';
|
||
import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs';
|
||
import { activityScope, activitySummary, canvasPresence, toolActivity, toolFailure } from './activity-event.mjs';
|
||
import { assertPiNodeVersion } from './runtime-policy.mjs';
|
||
import { nativeTools, requestCanvasWrite } from './native-tools.mjs';
|
||
import { NativeExtensionUI } from './native-ui.mjs';
|
||
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
|
||
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
|
||
|
||
const MAIN_CONTEXT_BUDGET = 150_000;
|
||
const protocolPaths = {
|
||
'openai-chat':'/v1/chat/completions',
|
||
'openai-responses':'/v1/responses',
|
||
'anthropic-messages':'/v1/messages',
|
||
};
|
||
const modelApi = protocol => protocol === 'openai-chat' ? 'openai-completions' : protocol;
|
||
const protocolBaseUrl = protocol => 'https://api.vip98k.com' +
|
||
(protocol === 'anthropic-messages' ? '' : protocol === 'google-generative-ai' ? '/v1beta' : '/v1');
|
||
const authorizedCandidates = candidates => (candidates ?? []).filter(route =>
|
||
route.protocol === 'google-generative-ai' ? googleModelPath.test(route.path?.replace(/\?alt=sse$/u,''))
|
||
: Object.hasOwn(protocolPaths,route.protocol) && route.path === protocolPaths[route.protocol]);
|
||
function thinkingMap(efforts, fallback) {
|
||
if (!efforts?.length) return fallback && {...fallback,off:fallback.off ?? 'off'};
|
||
return Object.fromEntries(['off','minimal','low','medium','high','xhigh','max'].map(level=>[
|
||
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];
|
||
}
|
||
|
||
const protocolProviders = {
|
||
'anthropic-messages':'anthropic',
|
||
'openai-responses':'openai',
|
||
'openai-chat':'openai',
|
||
'google-generative-ai':'google',
|
||
};
|
||
const routeKey = route => JSON.stringify([route.provider,route.protocol,route.id,route.routeId ?? route.headers?.['X-Relay-Route-Option']]);
|
||
const signatureDomain = route => route.signatureDomain ?? route.routeId ?? route.headers?.['X-Relay-Route-Option'] ?? null;
|
||
const protocolStreams = {
|
||
'anthropic-messages':streamAnthropic,
|
||
'openai-responses':streamResponses,
|
||
'openai-chat':streamChat,
|
||
'google-generative-ai':streamGoogle,
|
||
};
|
||
|
||
function routeContext(context, route) {
|
||
const chatId = id => /^[\w-]{1,40}$/u.test(id) ? id :
|
||
id.slice(0,23).replace(/[^\w-]/gu,'_')+'_'+createHash('sha256').update(id).digest('hex').slice(0,16);
|
||
const chat = route.protocol === 'openai-chat';
|
||
const domain = signatureDomain(route);
|
||
return {messages:context.messages.map(message => {
|
||
if (message.role === 'toolResult' && chat) return {...message,toolCallId:chatId(message.toolCallId)};
|
||
if (message.role !== 'assistant') return message;
|
||
const sourceDomain = message.signatureDomain ?? message.actualRouteId ?? null;
|
||
return {...message,provider:sourceDomain === domain ? message.provider : 'previous-route',
|
||
content:chat ? message.content.map(block=>block.type==='toolCall' ? {...block,id:chatId(block.id)} : block) : message.content};
|
||
})};
|
||
}
|
||
|
||
function dispatchOptions(route, context, name) {
|
||
if (!name) return {context};
|
||
if (!getCurrentTools(context.messages).some(tool=>tool.name===name)) throw Error('指定工具不在本次请求中');
|
||
const restrict = () => ({messages:context.messages.map(message => message.role === 'system' && message.toolsAdded
|
||
? {...message,toolsAdded:message.toolsAdded.filter(tool=>tool.name===name)} : message)});
|
||
switch (route.protocol) {
|
||
case 'openai-responses':
|
||
return route.requireSingleTool
|
||
? {context:restrict(),toolChoice:'required'}
|
||
: {context,toolChoice:{type:'function',name}};
|
||
case 'anthropic-messages':
|
||
return {context,toolChoice:{type:'tool',name}};
|
||
case 'google-generative-ai':
|
||
return {context:restrict(),toolChoice:'any'};
|
||
default:
|
||
return {context,toolChoice:{type:'function',function:{name}}};
|
||
}
|
||
}
|
||
|
||
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);
|
||
const statSession = name => fs.lstat(path.join(sessionDir,name)).catch(error=>{
|
||
if (error.code !== 'ENOENT') throw error;
|
||
});
|
||
const recoverPointer = !name || !(await statSession(name))?.isFile();
|
||
if (recoverPointer) {
|
||
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 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 (recoverPointer) 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 = `压缩摘要用于继续当前工作。合并旧摘要和本次记录,保留仍有效的事实及其原始编号:
|
||
- 在途及已付费的出图请求号、候选号、各图位状态和各图位已采用的候选。
|
||
- 已做的决定及理由,以及未解决的问题。
|
||
- 当前成品、当前屏、锁定的知识库版本和已写出的文件路径。
|
||
遇到状态变更,以最新明确回执为准。保留未确认状态,不猜测缺失编号或结果。`;
|
||
|
||
// 98k sends a single data line for terminal errors after the HTTP status is committed.
|
||
// Observe the structured code before the provider parser drops it from errorMessage.
|
||
function observeStreamFailure(response, onFailure) {
|
||
if (!response.headers.get('content-type')?.startsWith('text/event-stream') || !response.body) return response;
|
||
const code = 'request_outcome_unknown';
|
||
const decoder = new TextDecoder();
|
||
let pending = '';
|
||
const body = response.body.pipeThrough(new TransformStream({
|
||
transform(chunk, controller) {
|
||
const lines = (pending + decoder.decode(chunk, {stream:true})).split('\n');
|
||
pending = lines.pop();
|
||
for (const line of lines) {
|
||
if (!line.startsWith('data:') || !line.includes('"error"')) continue;
|
||
let payload;
|
||
try { payload = JSON.parse(line.slice(5)); } catch { continue; }
|
||
const error = payload?.error ?? (payload?.type === 'response.failed' && payload.response?.error);
|
||
if (!error) continue;
|
||
const dispatchState = error.code === code || error.type === code ? 'outcome_unknown' : 'committed_error';
|
||
onFailure(modelDispatchIdentity({dispatchState,...payload,...error,
|
||
originalRequestId:error.originalRequestId ?? payload.originalRequestId ?? error.requestId ?? payload.requestId}));
|
||
}
|
||
controller.enqueue(chunk);
|
||
},
|
||
}));
|
||
return new Response(body, {status:response.status,statusText:response.statusText,headers:response.headers});
|
||
}
|
||
|
||
const PRODUCT_VOICE = "对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。";
|
||
const LIVE_CANVAS_WRITES = '写入与核验以实时 workflow_read / canvas_read 为准。retryWrite=true、waiting_save、revision_conflict 和 changedLayers 是可核对的事实。重新读取目标及当前 revision,保留人工修改,继续未受影响的图位。只有写入许可明确被撤销时才停止对应写入。按真实回执说明原因,避免把保存或修订冲突说成权限被收回。';
|
||
|
||
const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文。讨论、解释或建议时直接回复;用户明确要求并确定范围后才修改画布。
|
||
用户消息中的 references 和随附引用条目是用户明确指代的对象,按 label、图片序号和实际身份逐项对应。
|
||
- 图层和蒙版用 nativeLayerId 和 component(layer、pixelMask、vectorMask)确认目标。用「canvas_read」「canvas_preview」「native_catalog」「native_call」「canvas_edit」或「write_copy_fields」。
|
||
- 用 slotId、candidateId、outputId 和 productVariantId 确认候选。用「workflow_execute」或「adopt_production_image」采纳,也可用生成候选操作以该 candidateId 为父版本。保留模板原图定义。
|
||
- 只根据实际读取的像素判断模板原图、画布和候选。缺少实际画面时明确说明,不用提示词冒充视觉核验。
|
||
|
||
${PRODUCT_VOICE}
|
||
用「workflow_read」读取项目目标、商品、实时进度和图位分页。以 status 和 selectedCandidateId 为准。canvasFirst 项目直接用模板画布,不把旧向导空状态当阻塞。
|
||
用「context_read」读取当前绑定的规则。缺少关键资料时询问,用户新确认的信息覆盖旧信息。用「memory_set」保存明确确认的事实,引用用户原话;用「memory_search」读取历史。
|
||
按照「context_read」返回的本项目锁定 Skill 和补充规则工作。通用建议可以直接讨论,不借用其他品牌的规则或臆测产品事实。
|
||
用「copywriting_options」提供卖点选项,用「copywriting_fields」提供逐格预览和采纳。「workflow_propose」只创建待审核建议,「workflow_navigate」只切换视图。用户取消表示未决定。
|
||
${LIVE_CANVAS_WRITES}
|
||
申请写入许可后执行实际修改。只确认经回执验证的结果;未知的付费或写入操作按原编号核查。`;
|
||
|
||
const PRODUCTION_SYSTEM = `你是小壹的制作助手,当前为无人值守制作。以项目锁定的企业 Skill、模板和补充规则为准,自主决定操作顺序、并行、复核及返工。
|
||
${PRODUCT_VOICE}
|
||
「plan_production」返回制作状态,设置 includeKnowledge=true 可列出锁定资料路径,用「read」按需读取。「open_production_output」打开目标画布,「list_project_images」查询项目候选。
|
||
${LIVE_CANVAS_WRITES}
|
||
「write_copy_fields」可注明刻意留空的依据。「check_output_screens」记录整屏复核,「read_screen_review」读取结论。用「tool_search」查找工具。用「native_catalog」查询原生命令,复用 parameterDocs。用「codemode」组合操作,依次 await 真实回执。
|
||
用「reconcile_image_slots」按原编号核查未知付费请求。用「finish_production」提交并核对文件和交付回执,按实际缺项汇报。`;
|
||
|
||
export const sessionSystemPrompt = production => production ? PRODUCTION_SYSTEM : SYSTEM;
|
||
|
||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||
// Both shapes are native projections of the frozen request, never the live selection.
|
||
const frozenReferences = context => Array.isArray(context?.requestScope?.references)
|
||
? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined;
|
||
// Only the native owner's explicit inactive-document response detaches display.
|
||
// Connection, account/authentication and all other failures must still surface.
|
||
const workflowBindingError = '品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合';
|
||
const inactiveDocument = error => error?.category === 'scope_changed';
|
||
const sequentialTools = new Set([
|
||
'memory_set', 'canvas_edit', 'canvas_preview', 'copywriting_options', 'copywriting_fields',
|
||
'workflow_navigate', 'workflow_execute', 'workflow_propose',
|
||
'open_production_output', 'write_copy_fields', 'use_product_image', 'transform_slot_image', 'prepare_image_request',
|
||
'dispatch_image_request', 'delegate_image_slots', 'stage_archived_image', 'check_image_slots', 'check_output_screens',
|
||
'adopt_production_image', 'retire_production_image', 'reconcile_image_slots',
|
||
'defer_production_output', 'finish_production',
|
||
]);
|
||
const conversationOnlyTools = new Set(['canvas_edit','canvas_template_image','canvas_preview','copywriting_options','copywriting_fields',
|
||
'workflow_navigate','workflow_execute','workflow_propose','memory_set','memory_search','context_read',
|
||
'bash','find','grep','ls','write','edit']);
|
||
const deferredProductionTools = new Set(['read_archived_images','stage_archived_image','retire_production_image','read_screen_review']);
|
||
const productionToolNames = productionTools.map(([name])=>name).filter(name=>!deferredProductionTools.has(name));
|
||
function toolsFor(host) {
|
||
const make = (name, description, parameters, execute, format = plain) => ({ name, label: name, description, parameters:toolSchema(name,parameters),
|
||
...(sequentialTools.has(name) ? {executionMode:'sequential'} : {}), execute: async (_id, args, signal, _update, ctx) => {
|
||
const epoch = host.turnEpoch;
|
||
if (host.compromised) throw Error('本地会话锁失效,已停止工具执行');
|
||
if (name === 'memory_set' && !host.productionGoal) await host.readWorkflow({section:'overview'});
|
||
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工具不会继续执行');
|
||
const receiptScope = {active:true};
|
||
const withReceipts = result => {
|
||
for (const userCanvasChanges of host.canvas.userCanvasChanges?.splice(0) ?? []) {
|
||
result.content.push({type:'text',text:JSON.stringify({userCanvasChanges})});
|
||
}
|
||
return result;
|
||
};
|
||
try {
|
||
host.productionSignal?.throwIfAborted();
|
||
const value = await (host.productionContext
|
||
? canvasToolReceipts.run(receiptScope, () => execute(args, signal, ctx))
|
||
: execute(args, signal, ctx));
|
||
const projected = name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value;
|
||
const result = withReceipts(format(redact(projected)));
|
||
if (name === 'finish_production' && host.productionCompletion ||
|
||
!host.productionGoal && (host.canvasNotificationsDetached || host.workflowBindingChanged)) result.terminate = true;
|
||
return result;
|
||
} catch(error) {
|
||
if (!(error instanceof BridgeError) && !host.canvas.userCanvasChanges?.length) throw error;
|
||
return withReceipts({...plain({failure:BridgeError.from(error).wire()}),isError:true});
|
||
} finally {
|
||
receiptScope.active = false;
|
||
}
|
||
} });
|
||
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(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()),
|
||
offset:Type.Optional(Type.Integer({minimum:0})),
|
||
}, {additionalProperties:false}), async ({query,toolCallId,offset=0}) => {
|
||
const id=toolCallId?.trim();
|
||
if (!id) return host.store.search(query,host.manager);
|
||
const receipt=await host.store.readToolReceipt(host.manager,id,offset);
|
||
return receipt ?? {toolCallId:id,found:false,matches:await host.store.search(query,host.manager)};
|
||
}),
|
||
];
|
||
const projectResources = [...commands, ...productionVideoTools(host, make)];
|
||
const productionKit = productionTools.map(([name, description, schema])=>({
|
||
...make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
|
||
['read_output_screen','read_slot_images'].includes(name)?result=>result:
|
||
name==='open_production_output'?receipt=>({...plain(describeProductionOutput(receipt)),details:receipt}):
|
||
name==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain),
|
||
defaultActive:false,
|
||
...(deferredProductionTools.has(name)?{exposure:'deferred'}:null),
|
||
}));
|
||
const canvasRead = make('canvas_read', '先使用 mode=summary 查看真实组和画板,或用 filter 按名称、文本检索;重名时使用真实 screenId 指定组,需要细节时用真实 layer ID。仅在确有需要时用 offset 翻页,勿全量遍历。revision来自实时读取;writeBlocked=true 表示本轮不可写。', canvasReadParameters, async args => {
|
||
const {layer,screen,screenId,mode,filter,maxDepth,offset=0}=canvasReadQuery(args);
|
||
return host.canvas.readCanvas(layer!==undefined?{layer}:{ ...(screen === undefined ? {} : { screen }), ...(screenId === undefined ? {} : {screenId}), ...(mode === undefined ? {} : {mode}), ...(filter === undefined ? {} : {filter}), ...(maxDepth === undefined ? {} : {maxDepth}), offset });
|
||
});
|
||
const outputName = Type.String({ minLength: 1 });
|
||
const outputId = Type.Optional(outputName);
|
||
const workflowRead = make('workflow_read', '读取当前创作工作流、实时版本及资料摘要。version 只用于上下文一致性,方案状态以 planConfirmed 为准。section 按需读取。', Type.Object({
|
||
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));
|
||
const tools = [
|
||
...contextTools, ...productionKit, canvasRead, workflowRead,
|
||
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};
|
||
host.canvasOperations.active = owner;
|
||
host.canvasOperations.writeRequested = true;
|
||
return (async () => {
|
||
let dispatched = false, terminal = false;
|
||
try {
|
||
if(host.canvasNotificationsDetached)throw Error('当前项目已切换,本轮画布写入已停止');
|
||
revision = await requestCanvasWrite(host, revision, signal, () => {
|
||
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧画布编辑未派发');
|
||
}, {command:edit.command,params:edit.params});
|
||
signal?.throwIfAborted();
|
||
if (host.canvasNotificationsDetached) throw Error('当前项目已切换,旧画布编辑未派发');
|
||
dispatched = true;
|
||
const state = await host.canvas.edit(edit, revision, signal);
|
||
terminal = true;
|
||
const result = { applied: true, revision: state.revision, allowed: state.allowed,
|
||
...(typeof run === 'string' && run ? {run} : {}), ...(Number.isSafeInteger(documentId) ? {documentId} : {}) };
|
||
if (host.turnEpoch !== epoch) return {...result, metadataUnavailable:'原回合已结束,未读取其他回合的图层详情'};
|
||
try {
|
||
const detail = await host.canvas.readCanvas({layer:edit.params.layer});
|
||
const rows = detail?.context?.layers;
|
||
if (host.turnEpoch !== epoch || host.canvas.run !== run || host.canvas.documentId !== documentId
|
||
|| typeof run !== 'string' || !run || !Number.isSafeInteger(documentId)
|
||
|| state.run !== run || state.context?.id !== documentId
|
||
|| detail?.run !== run || detail?.conversationActive !== true || detail?.context?.id !== documentId
|
||
|| !Number.isSafeInteger(state.revision) || detail.revision !== state.revision
|
||
|| !Array.isArray(rows) || rows.length !== 1 || rows[0]?.id !== edit.params.layer) {
|
||
return {...result, metadataUnavailable:'图层详情的会话、文档或修订已变化,请重新读取'};
|
||
}
|
||
return {...result, layer:rows[0]};
|
||
} catch {
|
||
return {...result, metadataUnavailable:'编辑已确认,图层详情读取失败;请重新读取'};
|
||
}
|
||
} catch (error) {
|
||
if (dispatched && !terminal) host.canvasOperations.retain({kind:'canvas-edit',run,documentId,identity,epoch,beforeRevision:revision,command:edit.command,targetLayerId:edit.params.layer});
|
||
throw error;
|
||
} finally { if (host.canvasOperations.active === owner) { host.canvasOperations.active = null; } }
|
||
})();
|
||
}),
|
||
];
|
||
tools.push(make('canvas_template_image',
|
||
'按真实fieldId读取当前项目固定版本的模板原图像素。请通过canvas_read核对具体图位;读取当前画布或候选时不使用此工具。工具返回模板版本和实际图片,读取失败时明确说明原图尚未读取。',
|
||
Type.Object({fieldId:Type.String({minLength:1,maxLength:128})},{additionalProperties:false}),
|
||
field => host.canvas.readTemplateImage(field.fieldId),
|
||
({images = [], ...source}) => {
|
||
return {content:[{type:'text',text:JSON.stringify(source)},...images],details:source};
|
||
}));
|
||
tools.push({...make('canvas_candidate_image',
|
||
'查看当前输出的实际候选图或已回填图、同款参考和已记录的验图依据。先用 workflow_read 查图位和候选 ID。默认读取该图位实际回填的图片。',
|
||
Type.Object({slotId:Type.String({pattern:'^[a-f0-9]{64}$'}),
|
||
candidateId:Type.Optional(Type.String({pattern:'^[a-f0-9-]{36}$'}))}, {additionalProperties:false}),
|
||
async ({slotId,candidateId})=>{
|
||
const evidence=await host.canvas.detailImages(slotId,candidateId,{inspectCandidate:true});
|
||
const {candidateId:id,outputId,variantId,relatedCopy,images,referenceCount,adopted}=evidence;
|
||
const journal=productionLedger(host.store,outputId,variantId).read();
|
||
const item=journal?.items?.[slotId];
|
||
const review=[item?.review,...(item?.approvals??[])].find(row=>row?.candidateId===id);
|
||
const reviewRecord=review ? {decision:review.decision,reason:review.reason,observation:review.observation} : null;
|
||
const metadata={slotId,candidateId:id,adopted,relatedCopy,review:reviewRecord,
|
||
imageOrder:referenceCount ? ['同款产品原图','实际图位图片'] : ['实际图位图片']};
|
||
return {content:[{type:'text',text:JSON.stringify(metadata)},...(referenceCount ? images.slice(0,1) : []),...images.slice(-1)],
|
||
details:metadata};
|
||
},value=>value),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'});
|
||
tools.push(...projectResources);
|
||
tools.push({...make('copywriting_options', '把已生成的产品卖点逐条显示为可多选的候选。items 是可选条目,missing 列出缺失依据。工具打开原生候选卡。', Type.Object({items:Type.Array(Type.String({minLength:1,maxLength:160}),{minItems:1,maxItems:20}),missing:Type.Optional(Type.Array(Type.String({minLength:1,maxLength:160}),{maxItems:20}))},{additionalProperties:false}), async args => {
|
||
const value = await host.canvas.copyOptions(args);
|
||
if (!value?.optionsId || value.run !== host.canvas.run || value.documentId !== host.canvas.documentId) throw Error('卖点选项不属于当前会话');
|
||
return {optionsId:value.optionsId,count:value.count,awaitingSelection:true,applied:false};
|
||
}),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'});
|
||
tools.push({...make('copywriting_fields','按本轮引用的每个真实文字格分别提交候选文案。先canvas_read读取文字格、用途和字数行数限制;items中每个layer只能出现一次,覆盖全部引用文字格。宿主在提交前复核每格并绑定真实版本,无需填写revision。用户逐格预览和采纳,工具不会写入画布。',Type.Object({revision:Type.Optional(Type.Integer({minimum:0})),items:Type.Array(Type.Object({layer:Type.Integer({minimum:1}),text:Type.String({minLength:1,maxLength:3000})},{additionalProperties:false}),{minItems:2,maxItems:20})},{additionalProperties:false}),async (args,signal)=>{
|
||
if(args.items.length!==host.copyFieldsTargets.length||new Set(args.items.map(item=>item.layer)).size!==args.items.length||args.items.some(item=>!host.copyFieldsTargets.includes(item.layer)))throw Error('候选文案须与本轮引用文字格一一对应');
|
||
const reads=[];for(const layer of host.copyFieldsTargets)reads.push(await previewTarget(host,layer,signal));
|
||
const revision=reads[0].revision;if(reads.some(read=>read.revision!==revision))throw Error('读取期间画布已变化,请重新读取本次文字格');
|
||
const value=await host.canvas.copyFields({...args,revision});
|
||
if(!value?.optionsId||value.run!==host.canvas.run||value.documentId!==host.canvas.documentId||value.count!==args.items.length)throw Error('逐格文案回执不一致');
|
||
return {...value,applied:false};
|
||
}),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') {
|
||
let confirmed=false;
|
||
const field=read.context.layers.find(layer=>layer.id===args.params.layer)?.templateField;
|
||
const exceeds=text=>field&&(Number.isSafeInteger(field.maxChars)&&Array.from(text).length>field.maxChars||Number.isSafeInteger(field.maxLines)&&text.split('\n').length>field.maxLines);
|
||
while(exceeds(params.text)) {
|
||
const limits=[field.maxChars?`最多${field.maxChars}字`:'',field.maxLines?`最多${field.maxLines}行`:''].filter(Boolean).join(',');
|
||
const text=await ctx.ui.input(`这格文案${limits},请缩短后继续`,params.text,{signal});
|
||
if(text===undefined){host.previewCancelled=true;return {cancelled:true,applied:false,previewCreated:false};}
|
||
if(!text.trim())continue;
|
||
params.text=text;confirmed=true;
|
||
}
|
||
if(confirmed)read=await previewTarget(host,args.params.layer,signal);
|
||
}
|
||
const request={...args,params,revision:read.revision};
|
||
const value = await host.canvas.preview(request);
|
||
if (!value || typeof value.previewId !== 'string' || !value.previewId || value.run !== host.canvas.run || value.documentId !== host.canvas.documentId || value.revision !== request.revision || value.command !== args.command || value.target?.id !== args.params.layer) throw Error('预览回执身份不一致,未确认预览');
|
||
await host.store.appendEvent({type:'canvas_preview_bound',layer:args.params.layer,revision:read.revision,requestedRevision:args.revision??null});
|
||
const image = item => {
|
||
if (!item || !Number.isSafeInteger(item.width) || !Number.isSafeInteger(item.height) || !Number.isSafeInteger(item.bytes) || typeof item.hash !== 'string') throw Error('预览元数据无效');
|
||
return {width:item.width,height:item.height,bytes:item.bytes,hash:item.hash};
|
||
};
|
||
if (!Array.isArray(value.changes) || value.changes.length > 32 || value.changes.some(c => !c || ['label','before','after'].some(k => typeof c[k] !== 'string' || c[k].length > 1000))) throw Error('预览变更元数据无效');
|
||
const crop=value.crop;
|
||
if (!crop || typeof crop !== 'object' || Array.isArray(crop) || Object.values(crop).some(v=>typeof v!=='number'||!Number.isFinite(v))) throw Error('预览范围无效');
|
||
if (typeof value.hash !== 'string' || typeof value.target.name !== 'string') throw Error('预览元数据无效');
|
||
host.previewReceipt = value.previewId;
|
||
return {previewId:value.previewId,run:value.run,documentId:value.documentId,revision:value.revision,command:value.command,target:{id:value.target.id,name:value.target.name},changes:value.changes.map(({label,before,after})=>({label,before,after})),before:image(value.before),after:image(value.after),hash:value.hash,crop:{...crop},pending:true,applied:false};
|
||
}), namespace:PHOTOCRAFT_NAMESPACE, exposure:'deferred' });
|
||
|
||
tools.push(make('workflow_navigate', '切换到当前项目的资料、卖点、方案、图位或画布视图。整套制作中,查看其它输出不会切换已绑定的制作画布。', Type.Object({
|
||
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: 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)),
|
||
}, { additionalProperties: false }), async (args, signal) => {
|
||
if (args.intent === 'adopt_candidate' && !args.candidateId) throw Error('请明确要采纳的候选');
|
||
return executeWorkflow(host, args, signal);
|
||
}));
|
||
tools.push(make('workflow_propose', '按实时 version 创建待审核建议。instruction 仅用于 selling_points 的表达方向或 generate_candidate 的画面要求。画布生成用 slotId、productVariantId,candidateId 可指定父版本;旧项目保留 variant A/B。adopt_candidate 指定完成候选。export_psd 导出成品分层副本。', Type.Object({
|
||
version: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
|
||
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);
|
||
if (result?.proposed !== true || result?.awaitingReview !== true || result?.executed !== false) throw Error('工作流建议未按待审核状态返回,未确认任何执行');
|
||
return workflowResult(result);
|
||
}));
|
||
return tools;
|
||
}
|
||
|
||
/** Coding Agent SDK owns the transcript/compaction; our host owns all I/O boundaries. */
|
||
export class DetailPiAgent {
|
||
static async open({ store, broker, brokerInfo, canvas, transport, projectEvidence, documentId, productionGoal, productionSignal, videoRuntime, callBudget, onEvent = () => {} }) {
|
||
assertPiNodeVersion(process.versions.node);
|
||
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: '' });
|
||
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('模型账户与项目隔离域不一致');
|
||
host.info = info;
|
||
host.routeInfo = info;
|
||
host.firstTurnBrokerInfo = brokerInfo;
|
||
if (productionGoal) {
|
||
const {outputId,variantId,requestedOutputs,workspaceId}=productionGoal;
|
||
if (!requestedOutputs?.length || !workspaceId || outputId &&
|
||
!requestedOutputs.some(row=>row.outputId===outputId && row.variantId===variantId)) throw Error('制作目标与当前项目不匹配');
|
||
if (info.model.supportsImageInput===false) throw Error('整套制作需要支持视觉的对话模型');
|
||
host.bindGoalRequestScope();
|
||
}
|
||
try {
|
||
const savedUsage = JSON.parse(await fs.readFile(path.join(store.root, 'context-usage.json'), 'utf8'));
|
||
if (savedUsage.version === 1 && savedUsage.scope === store.identity.scope && savedUsage.project === store.identity.project && savedUsage.model === info.model.id) host.contextUsage = savedUsage;
|
||
} catch { /* Missing or invalid telemetry never blocks the authoritative session. */ }
|
||
host.productIdentity = { ...store.identity, documentId };
|
||
host.productEvidence = productContext(projectEvidence,{...store.identity,documentId});
|
||
host.productRuleIdentity = projectEvidence ? {
|
||
brandId: host.productEvidence.product.brandId, categoryId: host.productEvidence.product.categoryId,
|
||
} : 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 cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
||
const retry = {enabled:false,maxRetries:0};
|
||
const workers = new Map();
|
||
const routesWithoutReasoning = new Set();
|
||
// Worker sessions are in memory, so the event log is the only place a failed tool's reason survives.
|
||
const recordToolEvent = (event,activity,scope) => {
|
||
const failure = toolFailure(event);
|
||
return store.appendEvent({
|
||
type:event.type,toolName:event.toolName,toolCallId:event.toolCallId,isError:event.isError??false,...scope,
|
||
...(activity?{status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs}:null),
|
||
...(activity?.status==='pending'?{requestId:event.result.details.pendingOriginal ?? event.result.details.operationId,
|
||
operationPhase:event.result.details.phase,pendingKind:activity.pendingKind}:null),
|
||
...(failure ? {...failure,error:failure.message.slice(0,300)} : null),
|
||
});
|
||
};
|
||
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 = {messages:[createInitialSystemMessage(COMPACTION_FACTS),...context.messages]};
|
||
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 && !host.compacting) {
|
||
const {textChars: inputChars, totalChars} = contextLengths(context);
|
||
if (!host.compacting) await host.updateContextUsage(null, 'running');
|
||
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: totalChars });
|
||
}
|
||
if (transport?.stream) {
|
||
if (worker) worker.budget.beginDispatch();
|
||
else host.countDispatch();
|
||
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 selectedId = selection.model.routeId ?? selection.invocationHeaders?.['X-Relay-Route-Option'];
|
||
const selectedRoute = candidates.find(route => route.protocol === selection.model.protocol &&
|
||
(selectedId === undefined || (route.routeId ?? route.headers?.['X-Relay-Route-Option']) === selectedId));
|
||
const primary = {...selectedRoute,...selection.model,headers:selection.invocationHeaders ?? selectedRoute?.headers};
|
||
const routes = new Map([[routeKey(primary),primary]]);
|
||
for (const candidate of candidates) {
|
||
const route = {...candidate,id:candidate.id ?? primary.id};
|
||
if (!routes.has(routeKey(route))) routes.set(routeKey(route),route);
|
||
}
|
||
const first = routes.get(worker ? worker.activeRoute : host.activeRoute) ?? primary;
|
||
const attempts = [first, ...[...routes.values()].filter(route => route !== first &&
|
||
(!host.productionGoal || route.supportsImageInput !== false))].slice(0,3);
|
||
if (attempts.length === 1) attempts.push(first);
|
||
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
|
||
for (const [index, route] of attempts.entries()) {
|
||
options.signal?.throwIfAborted();
|
||
if (worker) worker.budget.beginDispatch();
|
||
else host.countDispatch();
|
||
round = requestBroker.round(route.headers === undefined ? undefined : {invocationHeaders:route.headers});
|
||
const key = routeKey(route);
|
||
const dispatchModel = buildModel(routesWithoutReasoning.has(key) ? {...route,reasoning:false} : route);
|
||
if (dispatchModel.api === 'anthropic-messages' && dispatchModel.compat.supportsMidConvoEffort === true) {
|
||
dispatchModel.reasoning = true;
|
||
}
|
||
const {context:dispatchContext,toolChoice} = dispatchOptions(route,routeContext(context,route),requiredTool);
|
||
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
|
||
let legacyFailure, fetchError, httpStatus, reasoningSent, reasoningRejected;
|
||
const stream = protocolStreams[route.protocol](dispatchModel, dispatchContext, { ...options, toolChoice,
|
||
reasoning:route.reasoning === true && dispatchModel.reasoning ? options.reasoning : undefined,
|
||
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
|
||
apiKey: 'native-broker-only', fetch: async (...args) => {
|
||
sentAt=Date.now();
|
||
const body = args[1]?.body;
|
||
if (typeof body === 'string') {
|
||
requestBytes = Buffer.byteLength(body);
|
||
const payload = JSON.parse(body);
|
||
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
|
||
reasoningSent = route.protocol === 'openai-responses' && Object.hasOwn(payload,'reasoning');
|
||
}
|
||
await host.store.appendEvent({type:'provider_started',id:round.id,protocol:route.protocol,...workerFields,requestBytes});
|
||
host.productionSignal?.throwIfAborted();
|
||
try {
|
||
const response=await round.fetch(...args);
|
||
headersAt=Date.now();
|
||
httpStatus=response.status;
|
||
if (!response.ok && response.headers.get('content-type')?.includes('application/json')) {
|
||
const {error} = await response.clone().json().catch(() => ({}));
|
||
if (error?.code === 'request_outcome_unknown') legacyFailure = modelDispatchIdentity({...error,dispatchState:'outcome_unknown'});
|
||
// This exact gateway error comes from route preparation, before inference.
|
||
reasoningRejected = reasoningSent && httpStatus === 400 && error?.code === 'invalid_request' &&
|
||
error.message === 'The request parameter "reasoning" is not supported by the selected model.';
|
||
}
|
||
return observeStreamFailure(response, identity => { legacyFailure = identity; });
|
||
} catch (error) {
|
||
fetchError = error;
|
||
throw error;
|
||
}
|
||
},
|
||
});
|
||
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();
|
||
await round.settled?.();
|
||
const outcome = {...legacyFailure,...modelDispatchIdentity(fetchError ?? {}),...modelDispatchIdentity(round.outcome ?? {})};
|
||
if (legacyFailure?.dispatchState === 'outcome_unknown') outcome.dispatchState = 'outcome_unknown';
|
||
const stopReason = outcome.dispatchState && result.stopReason !== 'aborted' ? 'error' : result.stopReason;
|
||
outcome.originalRequestId ??= round.id;
|
||
outcome.actualRouteId ??= route.routeId ?? route.headers?.['X-Relay-Route-Option'];
|
||
outcome.actualProtocol ??= route.protocol;
|
||
const unknown = outcome.dispatchState === 'outcome_unknown' || !outcome.dispatchState &&
|
||
stopReason === 'error' && httpStatus >= 200 && httpStatus < 300;
|
||
if (unknown) outcome.dispatchState = 'outcome_unknown';
|
||
await host.store.appendEvent({type:'provider_finished',id:outcome.originalRequestId,stopReason,protocol:outcome.actualProtocol,
|
||
...outcome,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 (unknown) {
|
||
const error=unknownModelOutcome(outcome);
|
||
if (!worker) host.modelOutcome=error;
|
||
throw error;
|
||
}
|
||
if (host.broker?.authority?.error) throw host.broker.authority.error;
|
||
if (reasoningRejected && stopReason === 'error' && !hasEmittedContent &&
|
||
(outcome.dispatchState === 'committed_error' || !outcome.dispatchState) &&
|
||
!routesWithoutReasoning.has(key) && !options.signal?.aborted && !host.productionSignal?.aborted) {
|
||
routesWithoutReasoning.add(key);
|
||
if (attempts[index+1] !== route) attempts.splice(index+1,0,route);
|
||
continue;
|
||
}
|
||
const next = attempts[index+1];
|
||
const retryable = outcome.dispatchState
|
||
? ['not_dispatched','retryable_error'].includes(outcome.dispatchState)
|
||
: httpStatus === 502 || httpStatus === 503 || fetchError?.retryPreparation === true;
|
||
if (next && stopReason==='error' && !hasEmittedContent && retryable &&
|
||
!options.signal?.aborted && !host.productionSignal?.aborted) {
|
||
await host.store.appendEvent({type:'provider_failover',id:outcome.originalRequestId,...outcome,attempt:index+1,httpStatus,
|
||
fromProtocol:route.protocol,toProtocol:next.protocol,...workerFields});
|
||
await delay(250 * (index+1),undefined,{signal:options.signal});
|
||
continue;
|
||
}
|
||
Object.assign(result,modelDispatchIdentity(outcome));
|
||
result.signatureDomain = route.signatureDomain ?? outcome.actualRouteId ?? null;
|
||
if (['error','aborted'].includes(stopReason)) {
|
||
result.stopReason=stopReason;
|
||
result.errorMessage=redactText(result.errorMessage ?? '模型请求未完成');
|
||
output.push({type:'error',reason:stopReason,error:result});
|
||
output.end(result);
|
||
return;
|
||
}
|
||
host.productionSignal?.throwIfAborted();
|
||
options.signal?.throwIfAborted();
|
||
if (!worker && !host.compacting) host.usageModel = {...route,protocol:outcome.actualProtocol,routeId:outcome.actualRouteId};
|
||
await host.recordUsage(result, {id:outcome.originalRequestId,...outcome,purpose,...workerFields}, !worker&&!host.compacting);
|
||
if (stopReason==='length') {
|
||
result.stopReason='error';
|
||
result.errorMessage='模型输出达到线路上限,未执行未完成的工具建议';
|
||
output.push({type:'error',reason:'error',error:result});
|
||
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.activeRoute = routeKey(route);
|
||
else {
|
||
host.activeRoute = routeKey(route);
|
||
host.activeProtocol = outcome.actualProtocol;
|
||
host.usageModel = {...route,protocol:outcome.actualProtocol,routeId:outcome.actualRouteId};
|
||
}
|
||
output.push({...finalEvent,message:result}); output.end(result);
|
||
return;
|
||
}
|
||
} catch (error) {
|
||
const reason = redactText(String(error.message));
|
||
const message = { role: 'assistant', api:model.api, provider:model.provider, model:model.id, ...modelDispatchIdentity(error), 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;
|
||
};
|
||
const buildModel = selection => {
|
||
const api = modelApi(selection.protocol);
|
||
const known = catalogModel(runtime,selection.id,api);
|
||
const provider = selection.provider ?? known?.provider ?? protocolProviders[selection.protocol];
|
||
const thinkingLevelMap = thinkingMap(selection.reasoningEfforts,known?.thinkingLevelMap);
|
||
return {
|
||
provider, id:selection.id, name:selection.name ?? selection.id, api,
|
||
baseUrl:protocolBaseUrl(selection.protocol),reasoning:selection.reasoning === true,
|
||
...(thinkingLevelMap ? {thinkingLevelMap} : {}),
|
||
input:selection.supportsImageInput===undefined ? known?.input ?? ['text','image']
|
||
: selection.supportsImageInput ? ['text','image'] : ['text'],
|
||
cost,contextWindow:modelCapacity(selection).limit ?? known?.contextWindow ?? 0,
|
||
maxTokens:selection.maxTokens ?? known?.maxTokens ?? 0,inputLimits:known?.inputLimits,
|
||
compat:{...(known?.api===api && known.provider===provider ? known.compat : {}),
|
||
supportsStore:false,supportsMessageThreads:false,...selection.compat},
|
||
};
|
||
};
|
||
host.registerModel = selection => {
|
||
const model = buildModel(selection);
|
||
runtime.registerProvider(model.provider,{
|
||
api:model.api, apiKey:'native-broker-only',baseUrl:model.baseUrl,streamSimple,models:[model],
|
||
});
|
||
return model;
|
||
};
|
||
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=>
|
||
defineTool(tool.name==='read' ? tool : {...tool,exposure:'deferred'}))];
|
||
host.workingDirectory=files.cwd;
|
||
const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], {
|
||
systemPrompt: () => sessionSystemPrompt(host.productionGoal),
|
||
});
|
||
host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
|
||
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:hasExistingSession ? undefined : info.thinkingLevel ?? undefined,
|
||
resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools),
|
||
settingsManager: SettingsManager.inMemory({retry, compaction:{reserveTokens}}), sessionManager: host.manager,
|
||
});
|
||
const workerSettings = SettingsManager.inMemory({retry,cacheWarming:'off',compaction:{enabled:false},enableSkillCommands:false});
|
||
let workerResources;
|
||
const loadWorkerResources = async () => {
|
||
const resources = new DefaultResourceLoader({
|
||
cwd:files.cwd, agentDir:store.dir, settingsManager:workerSettings,
|
||
noExtensions:true, noSkills:true, noPromptTemplates:true, noContextFiles:true, noThemes:true,
|
||
extensionFactories:[
|
||
{name:'photocraft-image-context',factory:createImageContextPruningExtension()},
|
||
{name:'photocraft-worker-task',factory:pi=>pi.on('before_agent_start',(_event,ctx)=>({
|
||
systemPrompt:workers.get(ctx.sessionManager.getSessionId()).systemPrompt,
|
||
}))},
|
||
|
||
],
|
||
});
|
||
await resources.reload();
|
||
return resources;
|
||
};
|
||
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId, captions, signal, output=host.productionGoal) => {
|
||
const workerActivityScope={...(host.activityScope||activityScope(store.identity)),
|
||
...(output?{outputId:output.outputId,variantId:output.variantId}:null)};
|
||
const signals = [host.productionSignal,signal].filter(Boolean);
|
||
const activeSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
||
activeSignal?.throwIfAborted();
|
||
const scoped = host.broker?.forDetailSlot?.(requestScope);
|
||
if (!scoped&&!transport?.stream) throw Error('详情页模型连接未就绪');
|
||
const enterpriseSkills = host.productionSkills;
|
||
if (enterpriseSkills?.resource.skills.length) {
|
||
systemPrompt = JSON.stringify(enterpriseSkills.execution) + '\n\n' + systemPrompt;
|
||
systemPrompt += formatSkillsForPrompt(enterpriseSkills.resource.skills.map(skill=>({
|
||
...skill,filePath:enterpriseSkills.documents.get(skill.filePath).path,
|
||
}))).replace("Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.",
|
||
'调用 read 时填写相对于锁定资料根目录的路径。SKILL.md 内的相对链接先按该文件所在目录拼接。');
|
||
tools = [...tools,defineTool(files.read('worker',requestScope))];
|
||
}
|
||
const resourceLoader = await (workerResources ??= loadWorkerResources());
|
||
const sessionManager = SessionManager.inMemory(files.cwd);
|
||
const {session:workerSession} = await createAgentSession({
|
||
cwd:files.cwd, agentDir:store.dir, modelRuntime:runtime, model:session.model,
|
||
thinkingLevel:session.thinkingLevel, settingsManager:workerSettings, sessionManager, resourceLoader,
|
||
customTools:tools, tools:tools.map(tool=>tool.name),
|
||
});
|
||
const sessionId = sessionManager.getSessionId();
|
||
const [kind,step] = requestScope.split('/');
|
||
const budget = workerTurnBudget(slotId);
|
||
const worker = {budget,slotId,requestScope,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE,
|
||
cacheKey:host.manager.getSessionId()+':'+(kind==='product'?step:tools[0]?.name??'detail')};
|
||
const abort = () => { void workerSession.abort(); };
|
||
workers.set(sessionId,worker);
|
||
activeSignal?.addEventListener('abort',abort,{once:true});
|
||
const unsubscribe = workerSession.subscribe(event=>{
|
||
budget.observe(event);
|
||
if(event.type==='tool_execution_start'||event.type==='tool_execution_end'){
|
||
const activity=toolActivity(event,workerActivityScope);
|
||
void recordToolEvent(event,activity,{slotId,requestScope,
|
||
outputId:workerActivityScope.outputId,variantId:workerActivityScope.variantId})
|
||
.catch(error=>console.warn('子代理工具事件未保存',error.code??error.name));
|
||
if (activity && (event.isError || activity.status === 'pending')) {
|
||
void host.notifyCanvas('activity', activity.summary, {...activity,scope:host.activityScope}).catch(()=>{});
|
||
}
|
||
}
|
||
});
|
||
try {
|
||
activeSignal?.throwIfAborted();
|
||
const content = images.length ? [{type:'text',text:prompt},...images.flatMap((image,index)=>
|
||
captions?[{type:'text',text:captions[index]},image]:[image])] : prompt;
|
||
await workerSession.sendCustomMessage({customType:'photocraft-worker-task',content,display:false},{triggerTurn:true});
|
||
activeSignal?.throwIfAborted();
|
||
if(budget.failure)throw budget.failure;
|
||
const result = workerSession.messages.findLast(message=>message.role==='assistant');
|
||
if (result?.stopReason==='length') throw Error('模型回复达到单次输出长度,当前制作步骤未完成');
|
||
if (result?.stopReason==='error'||result?.stopReason==='aborted') {
|
||
throw new BridgeError(result.errorMessage||'当前制作步骤未完成',result.dispatchState,result);
|
||
}
|
||
} finally {
|
||
activeSignal?.removeEventListener('abort',abort);
|
||
unsubscribe();
|
||
try { workerSession.dispose(); }
|
||
finally {
|
||
workers.delete(sessionId);
|
||
await scoped?.close();
|
||
}
|
||
}
|
||
};
|
||
host.session = session;
|
||
host.queuedUserMessages = new Map();
|
||
host.userDeliveryStates = new Map();
|
||
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 === 'compaction_end') {
|
||
host.compacting = false;
|
||
void store.appendEvent({type:'pi_compaction',reason:event.reason,
|
||
completed:Boolean(event.result),tokensBefore:event.result?.tokensBefore}).catch(()=>{});
|
||
}
|
||
});
|
||
activatePhotoCraftTools(session, customTools);
|
||
host.conversationTools = [...new Set([...session.getActiveToolNames(),...files.tools.map(tool=>tool.name)])];
|
||
host.activeProductionTools = [...host.conversationTools.filter(name=>!conversationOnlyTools.has(name)),...productionToolNames];
|
||
session.setActiveToolsByName(productionGoal ? host.activeProductionTools : host.conversationTools);
|
||
await session.bindExtensions({ uiContext:host.nativeUI.context, mode:'rpc', abortHandler:() => { void session.abort(); } });
|
||
if (hasExistingSession && (restored.model?.modelId !== model.id || restored.model?.provider !== model.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,
|
||
compaction:session.settingsManager.getCompactionSettings(session.model),
|
||
defaultCompaction:defaults.getCompactionSettings(session.model),
|
||
retry:session.settingsManager.getRetrySettings(),defaultRetry:defaults.getRetrySettings(),
|
||
thinking:session.thinkingLevel,tools:session.getActiveToolNames()});
|
||
}
|
||
host.display = new PresentationBatch(async ({text, thinking, output, delta}) => {
|
||
await Promise.allSettled([
|
||
text !== undefined || thinking !== undefined || output
|
||
? host.notifyCanvas('delta', text ?? '', thinking, undefined, output) : undefined,
|
||
delta ? Promise.resolve().then(() => host.onEvent({type:'text_delta',delta})) : undefined,
|
||
]);
|
||
}, (pending, next) => ({
|
||
text:next.text ?? pending.text,
|
||
thinking:next.thinking ?? pending.thinking,
|
||
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 text = typeof event.message.content === 'string' ? event.message.content : event.message.content[0]?.text;
|
||
const entries = [...host.queuedUserMessages.values()];
|
||
const ordered = ['steer','followUp'].flatMap(behavior => entries.filter(entry=>entry.behavior===behavior));
|
||
const delivered = ordered.find(entry=>text === entry.prompt) ?? ordered.find(entry=>text?.startsWith(entry.prompt+'\n\n'));
|
||
if (delivered) {
|
||
host.queuedUserMessages.delete(delivered.messageId);
|
||
if (host.canvas.userDelivered) await flushReply();
|
||
host.publishUserDelivery(delivered,'delivered');
|
||
}
|
||
}
|
||
if (event.type === 'message_update' && !host.compacting) {
|
||
const update = event.assistantMessageEvent;
|
||
host.presentation ??= new StreamPresentation();
|
||
let text = '', thinking = host.thinking;
|
||
if (update?.type === 'text_delta') {
|
||
const before = host.presentation.inThought;
|
||
const part = host.presentation.push(update.delta);
|
||
text = part.text;
|
||
if (part.thought || before !== host.presentation.inThought || (text && thinking === true)) {
|
||
thinking = host.presentation.inThought;
|
||
}
|
||
} else if (update?.type === 'thinking_start' || update?.type === 'thinking_delta') {
|
||
thinking = true;
|
||
} else if (update?.type === 'thinking_end') {
|
||
thinking = false;
|
||
} else if (update?.type === 'text_end') {
|
||
host.presentation.endText();
|
||
if (thinking === true) thinking = false;
|
||
}
|
||
const changed = thinking !== host.thinking;
|
||
host.thinking = thinking;
|
||
const meter = outputMeter.update(event, thinking);
|
||
if (text || changed || meter) host.display.push({
|
||
text:text ? host.presentation.text.slice(-65000) : undefined,
|
||
thinking:changed || meter ? thinking ?? false : undefined,
|
||
output:meter || undefined,
|
||
delta:text,
|
||
});
|
||
}
|
||
if (event.type === 'message_end' && event.message.role === 'assistant' && !host.compacting) {
|
||
const meter = outputMeter.update(event, false);
|
||
if (host.thinking === true || meter) {
|
||
host.thinking = false;
|
||
host.display.push({thinking:false,output:meter});
|
||
}
|
||
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));
|
||
await host.notifyCanvas('activity', activitySummary(event),
|
||
activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
|
||
if (event.type === 'tool_execution_end' && !host.productionGoal &&
|
||
(host.canvasNotificationsDetached || host.workflowBindingChanged)) event.result.terminate = true;
|
||
await recordToolEvent(event,activity);
|
||
void Promise.resolve().then(() => host.onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});
|
||
}
|
||
});
|
||
// Restore the meter from Pi's durable session, not a cached local estimate.
|
||
// This only reads the session and publishes telemetry; it never prompts.
|
||
await host.updateContextUsage(null, 'ready');
|
||
return host;
|
||
} catch (error) {
|
||
try { await host.dispose(); } finally { throw error; }
|
||
}
|
||
}
|
||
async exclusive(operation) {
|
||
if (this.disposed || this.operationActive) throw Error('此会话已有操作或已关闭,未发起新请求');
|
||
this.operationActive = true;
|
||
try { return await operation(); } finally { this.operationActive = false; }
|
||
}
|
||
bindGoalRequestScope() {
|
||
const {workspaceId,outputId,variantId}=this.productionGoal;
|
||
this.goalRequestScope=outputId?productRequestScope('goal',variantId,outputId):productRequestScope('run',workspaceId);
|
||
this.goalBroker=this.broker?.forDetailSlot(this.goalRequestScope);
|
||
}
|
||
|
||
get productionContext() {
|
||
return this.productionGoal ?? this.productionWorkspace;
|
||
}
|
||
|
||
async readWorkflow(args) {
|
||
return (await this.readWorkflowContext(args)).workflow;
|
||
}
|
||
async readWorkflowContext(args) {
|
||
const epoch = this.turnEpoch;
|
||
if (this.canvasNotificationsDetached) throw Error('当前项目已切换,未读取其他项目工作流');
|
||
if (this.workflowBindingChanged) throw Error(workflowBindingError);
|
||
const snapshot = await this.canvas.workflowRead(args);
|
||
const latest = workflowContext(snapshot, this.productIdentity);
|
||
if (this.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流读取不更新当前回合');
|
||
if (latest.workflow.available) {
|
||
const identity = { brandId: latest.product.product.brandId, categoryId: latest.product.product.categoryId };
|
||
if (this.productRuleIdentity && (identity.brandId !== this.productRuleIdentity.brandId || identity.categoryId !== this.productRuleIdentity.categoryId)) {
|
||
this.workflowBindingChanged = true;
|
||
throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未记录事实或修改画布');
|
||
}
|
||
this.productRuleIdentity ??= identity;
|
||
}
|
||
this.currentWorkflow = latest.workflow;
|
||
this.productEvidence = latest.product;
|
||
if (args.section === 'overview') this.workflowOverview = snapshot;
|
||
return latest;
|
||
}
|
||
async readEnterpriseRules(workflow, productEvidence) {
|
||
const template = workflow?.template;
|
||
if (!workflow?.available || !template?.enterprise) return null;
|
||
if (template.knowledgeVersion) {
|
||
const {execution,snapshot,sources} = await openXiaoyiSkills(
|
||
this.store,template.id,undefined,undefined,undefined,template.knowledgeVersion,true,
|
||
);
|
||
const rules = await Promise.all([execution.entrypoint,execution.supplement].map(async rulePath => ({
|
||
path:rulePath,
|
||
text:await fs.readFile(path.join(snapshot.root,rulePath),'utf8'),
|
||
})));
|
||
return {execution,sources,rules};
|
||
}
|
||
const product = productEvidence.product;
|
||
this.enterpriseContext ??= new EnterpriseContext(this.store);
|
||
return this.enterpriseContext.load({task:this.task || 'chat',
|
||
brandName:product.brandName,categoryName:product.categoryName,
|
||
templateId:template.id,releaseId:template.version,turn:this.turnEpoch});
|
||
}
|
||
async modelContext(options = {}, {loadKnowledge = false} = {}) {
|
||
const {workflow,product}=!this.productionGoal || this.productionGoal.outputId
|
||
? await this.readWorkflowContext({section:'overview'})
|
||
: {workflow:this.currentWorkflow,product:this.productEvidence};
|
||
const canvas=await this.canvas.read();
|
||
if (canvas.conversationActive===false) throw Error('当前项目已切换,未读取其他项目画布');
|
||
const value=await this.store.modelContext({workflow,canvas:canvas.context,...options});
|
||
value.currentProduct=product;
|
||
if (workflow) value.currentWorkflow=workflow;
|
||
if (this.productionSkills && loadKnowledge) {
|
||
const {execution,files,versionNotice}=this.productionSkills;
|
||
value.enterpriseKnowledge={execution,sources:files,...(versionNotice?{versionNotice}:null)};
|
||
value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule));
|
||
return value;
|
||
}
|
||
const knowledge = this.knowledgeContext ?? (loadKnowledge ? await this.readEnterpriseRules(workflow,product) : null);
|
||
if (knowledge) {
|
||
value.enterpriseKnowledge=knowledge;
|
||
value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule));
|
||
}
|
||
return value;
|
||
}
|
||
async notifyCanvas(method,...args) {
|
||
const epoch = this.turnEpoch;
|
||
if(method==='end'){
|
||
if(this.canvasEndAttempted)return;
|
||
this.canvasEndAttempted=true;
|
||
}else if(this.canvasEndAttempted||this.canvasNotificationsDetached)return;
|
||
if(this.productionGoal&&['delta','reply'].includes(method)&&typeof args[0]==='string'){
|
||
args[0]=stripProductionToolText(args[0],method==='delta');
|
||
}
|
||
try{return await this.canvas[method](...args);}
|
||
catch(error){
|
||
if(!inactiveDocument(error))throw error;
|
||
if(this.turnEpoch !== epoch)return;
|
||
this.canvasNotificationsDetached=true;
|
||
await this.store.appendEvent({type:'inactive_ui_delivery',method,reason:error.message,originalResponseRetained:true});
|
||
}
|
||
}
|
||
async prompt(text, options = {}) {
|
||
return this.exclusive(() => this.promptTurn(text, options));
|
||
}
|
||
async steer(text, {behavior='steer',messageId=randomUUID(),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,messageId,deliveryStatus:'expired',disposition:null,reason:'not_streaming',error:null};
|
||
const prior = this.userDeliveryStates.get(messageId);
|
||
if (prior === 'expired') return idle;
|
||
if (prior) return {accepted:true,behavior,messageId,deliveryStatus:prior,disposition:prior,reason:null,error:null};
|
||
if (!check()) return idle;
|
||
const {prompt,images}=referencedPrompt(text,referenceContent);
|
||
await this.store.recordUserEvidence(text);
|
||
if (!check()) return idle;
|
||
if (this.queuedUserMessages.has(messageId)) {
|
||
return {accepted:true,behavior,messageId,deliveryStatus:'queued',disposition:'queued',reason:null,error:null};
|
||
}
|
||
const queued = {text,behavior,messageId,prompt,timestamp:Date.now()};
|
||
this.queuedUserMessages.set(messageId,queued);
|
||
try {
|
||
const result = await this.session[behavior](prompt,images);
|
||
if (result === 'queued') {
|
||
if (!this.userDeliveryStates.has(messageId)) this.userDeliveryStates.set(messageId,'queued');
|
||
return {accepted:true,behavior,messageId,deliveryStatus:'queued',disposition:'queued',reason:null,error:null};
|
||
}
|
||
this.queuedUserMessages.delete(messageId);
|
||
return idle;
|
||
} catch (error) {
|
||
this.queuedUserMessages.delete(messageId);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
publishUserDelivery({text,behavior,messageId,timestamp}, deliveryStatus) {
|
||
this.userDeliveryStates.set(messageId,deliveryStatus);
|
||
if (this.canvas.userDelivered) {
|
||
void this.notifyCanvas('userDelivered',{text,behavior,messageId,timestamp,deliveryStatus}).catch(()=>{});
|
||
}
|
||
}
|
||
|
||
clearQueue() {
|
||
const result = this.session.clearQueue();
|
||
for (const message of this.queuedUserMessages.values()) this.publishUserDelivery(message,'expired');
|
||
this.queuedUserMessages.clear();
|
||
return result;
|
||
}
|
||
|
||
bindTurn({store,broker,productionGoal,productionSignal,brokerInfo,canvas,projectEvidence,documentId,onEvent}) {
|
||
if (store.dir !== this.store.dir || store.root !== this.store.root ||
|
||
store.projectExportRoot !== this.store.projectExportRoot) throw Error('项目存储位置已改变,请重新打开项目');
|
||
Object.assign(this.store,store);
|
||
Object.assign(this,{broker,productionGoal,productionSignal,firstTurnBrokerInfo:brokerInfo,canvas,onEvent});
|
||
this.nativeUI.canvas = canvas;
|
||
canvas.identity = {accountId:brokerInfo.accountId,origin:brokerInfo.origin};
|
||
this.productIdentity = {...store.identity,documentId};
|
||
this.productEvidence = productContext(projectEvidence,this.productIdentity);
|
||
this.productRuleIdentity = projectEvidence ? {
|
||
brandId:this.productEvidence.product.brandId,categoryId:this.productEvidence.product.categoryId,
|
||
} : null;
|
||
this.workflowBindingChanged = false;
|
||
this.modelOutcome = undefined;
|
||
this.workflowOverview = this.currentWorkflow = undefined;
|
||
if (productionGoal) this.bindGoalRequestScope();
|
||
}
|
||
|
||
async releaseTurn() {
|
||
this.clearQueue();
|
||
await closeProductionTurn(this);
|
||
await this.goalBroker?.close();
|
||
this.goalBroker = undefined;
|
||
this.turnEpoch++;
|
||
this.productionSignal = undefined;
|
||
this.onEvent = () => {};
|
||
}
|
||
|
||
generatedCandidateReply() {
|
||
if (!this.generatedCandidates.size) return null;
|
||
const adopted = [...this.generatedCandidates.values()].filter(Boolean).length;
|
||
let reply = `已生成 ${this.generatedCandidates.size} 张候选图,可以在画布对应图位或对话中的「生成图片」查看。`;
|
||
if (adopted) reply += `其中 ${adopted} 张已采纳到画布。`;
|
||
return reply;
|
||
}
|
||
countDispatch() {
|
||
if (this.callBudget !== undefined && this.rounds >= this.callBudget) {
|
||
throw Error(`本轮已达${this.callBudget}次调用预算,停止继续调用`);
|
||
}
|
||
this.rounds++;
|
||
}
|
||
|
||
async recordUsage({model,usage}, fields, updateContext=true) {
|
||
const {input,output,cacheRead,cacheWrite,totalTokens}=usage;
|
||
const receipt={model,inputTokens:input+cacheRead+cacheWrite,outputTokens:output,
|
||
cachedTokens:cacheRead,totalTokens,source:'sdk-response'};
|
||
const event={type:'usage',...fields,...receipt};
|
||
await this.store.appendEvent(event);
|
||
await this.onEvent(event);
|
||
if (updateContext) await this.updateContextUsage({...receipt,id:fields.id,at:Date.now()},'running');
|
||
}
|
||
async updateContextUsage(receipt = null, phase = 'ready') {
|
||
this.contextUsage = contextSnapshot(this.store.identity, this.usageModel ?? this.info.model, this.session, this.contextUsage, receipt, phase);
|
||
if (phase === 'ready') {
|
||
await atomic(path.join(this.store.root, 'context-usage.json'), this.contextUsage).catch(error => {
|
||
if (!['EACCES', 'EBUSY', 'EPERM'].includes(error.code)) throw error;
|
||
});
|
||
}
|
||
await this.onEvent({ type: 'context_usage', value: this.contextUsage });
|
||
if (this.canvas.run && !this.canvasEndAttempted) await this.notifyCanvas('contextUsage', this.contextUsage);
|
||
return this.contextUsage;
|
||
}
|
||
async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false, resetProductionGoal = false } = {}) {
|
||
this.modelOutcome=undefined;
|
||
if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求');
|
||
text = redactText(text);
|
||
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 (this.session.isStreaming) throw Error('本轮尚未结束');
|
||
const changed = JSON.stringify(latest.model) !== JSON.stringify(this.info.model);
|
||
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 = this.activeRoute = this.usageModel = 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('当前模型线路没有发布可用的推理参数');
|
||
this.session.setThinkingLevel(thinking[1]);
|
||
await atomic(path.join(this.store.dir,'session.json'),{file:this.manager.getSessionFile()});
|
||
return {text:`思考档位已设为 ${this.session.thinkingLevel}。`,rounds:0};
|
||
}
|
||
if (this.canvasOperations.active) throw Error('原操作仍在执行,请先等待或核查;不会重发');
|
||
if (requiredTool && !this.session.getActiveToolNames().includes(requiredTool)) throw Error('指定工具未开放');
|
||
this.requiredTool = null;
|
||
this.productionCompletion=null;
|
||
this.productionDelivery=null;
|
||
this.task = 'chat';
|
||
this.previewReceipt = null; this.previewCancelled = false;
|
||
this.copyFieldsTargets = [];
|
||
this.rounds = 0; this.text = ''; this.presentation = new StreamPresentation(); this.thinking = undefined;
|
||
this.turnEpoch = (this.turnEpoch || 0) + 1;
|
||
this.userDeliveryStates.clear();
|
||
this.canvasOperations.beginTurn();
|
||
this.generatedCandidates = new Map();
|
||
this.canvasNotificationsDetached=false;this.canvasEndAttempted=false;
|
||
this.activityScope = activityScope(this.store.identity);
|
||
this.knowledgeContext = null;
|
||
this.productionWorkspace = null;
|
||
this.productionSkills = null;
|
||
const {prompt,images}=referencedPrompt(text,referenceContent);
|
||
this.requiredTool = requiredTool;
|
||
const begun = await this.canvas.begin(text);
|
||
this.nativeUI.start(begun?.editorText || '');
|
||
const references = frozenReferences(begun?.context);
|
||
this.copyFieldsTargets = (references??[]).filter(ref=>ref.layerKind==='Type'&&ref.component==='layer')
|
||
.map(ref=>ref.nativeLayerId);
|
||
this.activityScope = activityScope(this.store.identity, this.canvas, begun);
|
||
try {
|
||
const production=this.productionGoal;
|
||
if (resetProductionGoal && productionGoalState(this.manager)) {
|
||
this.manager.appendCustomEntry('production-goal',{goal:null});
|
||
}
|
||
if (!production && (await this.canvas.read()).conversationActive===false) {
|
||
throw Error('当前项目已切换,本轮对话未应用到其他项目');
|
||
}
|
||
if (!production || production.outputId) await this.readWorkflow({ section: 'overview' });
|
||
const request=begun?.context?.requestScope;
|
||
const overview=this.workflowOverview;
|
||
const outputId=request?.outputId ?? overview?.outputId;
|
||
const variantId=request?.variantId ?? overview?.productVariantId;
|
||
if (!production && outputId && variantId &&
|
||
(request?.productionTemplate || request?.canvasFirst || overview?.available && overview.canvasFirst)) {
|
||
const choices=overview?.productEvidence?.brief?.outputVariantIds;
|
||
const requestedOutputs=request?.requestedOutputs ?? (choices
|
||
? Object.entries(choices).flatMap(([outputId, variants]) => variants.map(variantId => ({outputId,variantId})))
|
||
: [{outputId,variantId}]);
|
||
this.productionWorkspace={workspaceId:request?.workspaceId ?? overview?.workspaceId,outputId,variantId,
|
||
requestedOutputs,template:request?.productionTemplate ?? overview?.template};
|
||
}
|
||
const template=this.productionContext?.template ?? (production ? overview?.template : undefined);
|
||
if (template?.enterprise) {
|
||
const current = productionGoalState(this.manager);
|
||
const finishedGoal = current?.status === 'complete' ? current.id : undefined;
|
||
const pinned = (!production || !finishedGoal && (goalContinuation || current)) ? template.knowledgeVersion : undefined;
|
||
this.productionSkills=await this.openProductionKnowledge(template.id,production ? finishedGoal : undefined,pinned);
|
||
this.session.resourceLoader.extendResources({
|
||
skillPaths: this.productionSkills.resource.skills.map(skill => ({
|
||
path: skill.filePath, metadata: {source:'enterprise', scope:'project', origin:'top-level'},
|
||
})),
|
||
});
|
||
}
|
||
const goalOnlyTools=new Set(['open_production_output','finish_production','defer_production_output']);
|
||
const followUpProductionTools=productionTools.map(([name])=>name).filter(name=>!goalOnlyTools.has(name));
|
||
const active=this.productionWorkspace && !production ? [...this.conversationTools,...followUpProductionTools] :
|
||
production ? this.activeProductionTools : this.conversationTools;
|
||
this.session.setActiveToolsByName([...new Set([...active,...(this.productionSkills?['read']:[])])]);
|
||
if (!goalContinuation) await this.store.recordUserEvidence(text);
|
||
const userCanvasChanges=request?.userCanvasChanges ?? production?.userCanvasChanges;
|
||
const running = production
|
||
? runProductionGoal(this, prompt, images, userCanvasChanges)
|
||
: this.session.prompt(userCanvasChanges ? prompt+'\n\n本轮画布的人工改动:'+JSON.stringify(userCanvasChanges) : prompt,
|
||
images.length ? { images } : undefined);
|
||
// SDK flushes the user entry before dispatch. Persist the authoritative file location.
|
||
if (this.manager.getSessionFile()) await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||
await running;
|
||
const unfinished = !production || this.productionCompletion
|
||
? undefined : await unfinishedProductionTurn(this);
|
||
await closeProductionTurn(this);
|
||
this.productionSignal?.throwIfAborted();
|
||
if (this.workflowBindingChanged) throw Error(workflowBindingError);
|
||
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||
const last = this.session.messages.filter(m => m.role === 'assistant').at(-1);
|
||
if (last?.stopReason === 'aborted' || last?.stopReason === 'error') {
|
||
throw new BridgeError(last.errorMessage || '本轮对话未完成',last.dispatchState,last);
|
||
}
|
||
if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议');
|
||
const resultText = this.productionCompletion?.text ?? this.productionDelivery?.text ??
|
||
(this.previewCancelled&&!this.previewReceipt
|
||
? '已取消本次预览,没有应用这项修改。'
|
||
: presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || ''));
|
||
const textResult=this.productionGoal?stripProductionToolText(resultText).trim():
|
||
this.canvasNotificationsDetached&&last?.stopReason==='toolUse'
|
||
? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText;
|
||
if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留');
|
||
await this.display.flush();
|
||
await this.updateContextUsage(null, 'ready');
|
||
await this.nativeUI.stop();
|
||
this.clearQueue();
|
||
await this.notifyCanvas('end',textResult);
|
||
const result=this.productionCompletion?.receipt??this.productionDelivery?.receipt??unfinished??(production&&{
|
||
outputId:this.productionGoal.outputId,variantId:this.productionGoal.variantId,complete:false,
|
||
stageStatus:'continue',
|
||
});
|
||
const {versionNotice,knowledgeVersion}=this.productionSkills??{};
|
||
return { ...(result?{production:{...result,...(knowledgeVersion?{knowledgeVersion}:null),...(versionNotice?{knowledgeVersionNotice:versionNotice}:null)}}:null),
|
||
text: textResult, rounds: this.rounds, messages: this.session.messages.length, sessionFile: this.manager.getSessionFile() };
|
||
} catch (error) {
|
||
const goal = this.productionGoal && productionGoalState(this.manager);
|
||
if (this.productionSignal?.aborted && goal?.status === 'active') {
|
||
this.manager.appendCustomEntry('production-goal',{goal:{...goal,status:'paused'}});
|
||
}
|
||
await this.updateContextUsage(null, 'ready').catch(() => {});
|
||
await this.display.flush();
|
||
await this.nativeUI.stop().catch(() => {});
|
||
this.clearQueue();
|
||
const generated = this.generatedCandidateReply();
|
||
await this.notifyCanvas('end', generated ? `${generated}\n\n${error.message}` : error.message).catch(() => {});
|
||
throw error;
|
||
} finally {
|
||
this.clearQueue();
|
||
await closeProductionTurn(this).catch(()=>{});
|
||
}
|
||
}
|
||
openProductionKnowledge(templateId, finishedGoal, pinnedKnowledgeVersion) {
|
||
return openXiaoyiSkills(this.store, templateId, this.productionSignal, finishedGoal, undefined, pinnedKnowledgeVersion);
|
||
}
|
||
|
||
async compact() {
|
||
return this.exclusive(async () => {
|
||
this.rounds = 0;
|
||
const result = await this.session.compact();
|
||
this.productionSignal?.throwIfAborted();
|
||
await atomic(path.join(this.store.dir, 'session.json'), {file:this.manager.getSessionFile()});
|
||
return result;
|
||
});
|
||
}
|
||
async dispose() {
|
||
this.disposed = true;
|
||
if (this.nativeUI) this.nativeUI.active = false;
|
||
try {
|
||
try { await this.session?.abort(); } finally { this.session?.dispose(); }
|
||
} finally {
|
||
try { await this.goalBroker?.close(); }
|
||
finally { this.releaseLock?.(); this.releaseLock = null; }
|
||
}
|
||
}
|
||
}
|