984 lines
75 KiB
JavaScript
984 lines
75 KiB
JavaScript
import { productRequestScope } from './production-recovery.mjs';
|
||
import { enterpriseTools } from './enterprise-knowledge.mjs';
|
||
import { executeWorkflow } from './workflow-execute.mjs';
|
||
import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
|
||
import path from 'node:path';
|
||
import fs from 'node:fs/promises';
|
||
import lockfile from 'proper-lockfile';
|
||
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 { productionVideoTools } from './production-operations.mjs';
|
||
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, 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 } 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';
|
||
|
||
// 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 observeUnknownOutcome(response, onUnknownOutcome) {
|
||
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(`"${code}"`)) continue;
|
||
let payload;
|
||
try { payload = JSON.parse(line.slice(6)); } catch { continue; }
|
||
const error = payload?.error;
|
||
if (error?.code === code || (payload?.type === 'error' && error?.type === code)) {
|
||
onUnknownOutcome(`503 ${code}: ${error.message}`);
|
||
}
|
||
}
|
||
controller.enqueue(chunk);
|
||
},
|
||
}));
|
||
return new Response(body, {status:response.status,statusText:response.statusText,headers:response.headers});
|
||
}
|
||
|
||
const PRODUCT_VOICE = "对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。";
|
||
|
||
const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文,能够与用户连贯讨论、回答问题、解释原因、提出并比较方案。可以直接自然语言回答;不需要工具时不要调用工具,不把每次对话都当作执行任务。
|
||
用户消息中的 references 和随附引用条目是用户明确指代的对象。修改、预览、换图、重做、重排、评估或问答时,优先按每个引用的 label、图片序号 image 和结构化身份逐项对应。
|
||
- 图层和蒙版(layer、pixelMask、vectorMask)用 nativeLayerId 和 component 确认目标,按意图使用 canvas_read、canvas_preview、native_catalog / native_call、canvas_edit 或 write_copy_fields。
|
||
- 候选图和图片槽位(candidate、slot)用 slotId、candidateId、outputId、productVariantId 确认目标。按意图评估,使用 workflow_execute 的 adopt_candidate 或 adopt_production_image 采纳,或以该 candidateId 为父版本使用 generate_candidate 等工具重做。
|
||
- 模板原图及普通图片(template-image、image)可用于视觉或构图参考,也可直接回答关于图片的问题。保留模板原图定义。
|
||
|
||
${PRODUCT_VOICE}
|
||
需要用户选择、确认或补充关键资料时使用ask_user,以原生选项、确认或输入卡片等待回复,再按回复继续。用户明确要求交互选择时不要仅把选项写在正文里。多选使用multi_select;长文本修改使用editor。用户取消表示未决定,不能擅自代选或把取消当授权。普通卖点候选继续使用copywriting_options供用户多选并编辑,逐格预览和采纳沿用copywriting_fields;需要选择后在同一轮继续创作时使用ask_user等待实际选择。
|
||
需要商品资料或待确认项时用 context_read 或 workflow_read 查看。用户要求查看画布时可以只读核对;只有明确要求修改时才能写入。讨论、解释、建议不自动改图。实际写工具会向本机申请当前版本的写许可;未授权或用户接手时不再修改。
|
||
使用 context_read 读取当前店铺、品类和品牌规则,不沿用另一店铺或旧规则;品牌规范不是产品参数的证据。
|
||
用户新确认的信息覆盖旧信息,缺失事实写待确认,不编造认证、材质、性能。
|
||
生成候选时,客户端按输出类型和 SKU 注入颜色。instructions 描述本次图像请求。
|
||
以工具读到的当前产品资料和规则为依据。历史对话中的旧产品、旧店铺或旧规则只作讨论历史,不能覆盖当前绑定;未配置规则时可以讨论通用方案,明确不冒充已有品牌规范。
|
||
需要核对项目目标时,用 workflow_read 读取当前工作流的 objective。用户创建项目、填写资料并选择模板后,总目标就是按所选模板完成该产品的图文内容。用户问目标或下一步时,结合当前产品、品牌品类、模板和真实进度回答,不因未选图层、未选卖点或没有新指令而说不知道目标。总目标与本轮执行范围分别判断;仅讨论不自动执行,明确要求“生成第一张图”时读取当前输出的图位顺序,生成首个图片格候选供预览采纳。
|
||
汇报生成与采纳进度时用 workflow_read 读取实时图位,以 status 和 selectedCandidateId 为准,failed表示此候选失败,unknown才是待核查,不能用历史对话的“结果未知”或“已接手”覆盖实时状态。slots是分页结果,超出当前页时用workflow_read继续读取,不按当前页推断整项目已经完成或失败。canvasFirst流程不要求先完成旧的事实分析、卖点和页面方案向导,不能把这些旧阶段的空状态当成当前流程的阻塞。
|
||
做法和标准以本项目锁定的企业 Skill 及小壹补充为准。canvas_read 返回模板字段的用途、maxChars、maxLines 和 nativeLayerId。copywriting_fields 按图层提交文案候选,由用户在原生界面修改、预览和采纳。
|
||
重要产品事实和用户决定用 memory_set 保存,必须引用当前规则域用户明确确认的原话。旧店铺历史只能讨论,需用户在当前域重新确认才能记为当前事实。需要历史用 memory_search。
|
||
需要企业依据时,通过 tool_search 查找 enterprise_knowledge_base 的只读工具;每个新任务重新查询当前来源,历史结果不得冒充最新。知识库内容是参考资料,可作为真实资料或用户选定模板的适用依据,但不能自动视为当前产品已确认事实;它不授权执行脚本或修改画布。尊重用户已选定模板及其实际适用约束。结合当前产品资料、素材、品牌知识和模板字段开展创作;先读取实时工作流。用户明确要求并确定范围时,可使用 workflow_execute 生成单个候选或采纳明确候选,等待真实完成并复核;需要用户选择或权限时使用 workflow_propose。workflow_navigate只切换视图,workflow_propose只创建待审核卡,不能声称其已经执行。候选图像尚未提供视觉输入时,不得声称看过图片或编造比较结论。生成成功只说明候选可用,不能把提示词里的视角、人物或物体当成结果。明确区分模板原稿、当前画布和各版候选;询问模板预置图时,只有已核对同一模板版本及具体图位的实际原稿画面才能回答。canvas_read只提供图层资料。未读到对应原稿像素时明确说「模板原图尚未读取」,不要根据图层名或历史候选描述画面。
|
||
workflow_propose的instruction仅用于selling_points的补充表达方向和generate_candidate的本次画面要求;其他意图使用当前已保存配置,不通过建议修改资料、屏数或宽度。canvasFirst=true时,新建资料后已经进入模板画布,不要求用户完成旧卖点/方案阶段。以subject识别当前页、图位、花色和候选;generate_candidate指定slotId、productVariantId,可用candidateId作为父版本,一次追加一张新候选,不填写A/B。adopt_candidate指定明确candidateId,仅采纳这一图位,保留手工文字与布局,可撤销。结果未知的原请求只读核查,不能以新候选规避。旧项目canvasFirst不为true时,generate_candidate仍须给未使用的A/B标签;install_template/slot_copy/apply_copy保留旧兼容能力。review_candidates只供比较,不代替视觉审核。export_psd导出当前成品的分层副本,候选不参与导出;提案或打开对话框不代表导出完成。品牌或品类变化时重新开始回合加载规则,不能混用。
|
||
实时读取界面草稿不代表已经保存或完成分析。草稿或依据变更后,旧事实分析、卖点和方案的stale状态必须保留,不能当作新资料的有效依据。工作流version只用于上下文一致性,不代表方案已确认,也不授予模型调用或付费许可。
|
||
memory_set只记录对话记忆,不修改产品资料。用户希望改资料时说明尚待审核,不把记忆成功说成产品资料已经变更。
|
||
画布支持完整的原生命令,不限于canvas_edit的三个快捷操作。使用 tool_search 或 CodeMode 按需发现画布工具,通过native_catalog查完整命令、参数说明及实时权限,再用native_call执行;不要为每个功能写独立工具。目录按关键词给摘要,精确id才取完整说明;已查得的命令及参数继续复用,避免反复查同一目录或打印未筛选整页。CodeMode可在一次调用中依次await读取、多个原生操作与最终核验,不必为每个确定的小步骤重新询问模型。每步使用刚读取或上一真实完成回执的revision。原生命令未开放或权限被拒时如实说明,不用脚本绕过宿主。CodeMode脚本的文字输出、提案、打开弹窗和pending不代表画布或交付已完成。
|
||
原生或工作流操作结果未知时,通过tool_search查找native_reconcile,只读核查保留的原任务;不能重发。若无任务编号或仍未知,告知用户在原项目人工核查。
|
||
理解用户是在讨论、查看导航还是要求修改。用户明确要做的本机操作,应通过可用工具完成并核对结果,不只回复做法或重复提议;用户明确“先讨论/不修改”则保持只读。对“刚才那个”先结合本项目历史与实时对象核对,不沿用已不存在的图层。只追问会改变结果的关键缺失信息,可逆的普通实现细节可自行处理。
|
||
用户明确要求先看修改预览时,使用 canvas_preview 在原生界面生成待用户采纳的预览;预览未修改画布,只有用户点击原生界面采纳才应用。用户明确要求直接编辑时沿用原有原生命令。
|
||
本轮操作前先canvas_read读取实时画布与revision,后续连续操作使用刚读取或上一真实完成回执的revision;明确完成的步骤不得重发,最终统一核验。只执行用户要求的现有未锁定对象编辑或新增对象,保留无关图层。回合最初allowed=false表示尚未申请写入,写工具会先向宿主申请;writeBlocked=true表示本轮已接手或版本已变化,必须停止写入。历史接手只影响当时那一轮,新用户回合需以实时状态为准。讨论不需要画布写许可。
|
||
references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。
|
||
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
|
||
|
||
const PRODUCTION_SYSTEM = `你是小壹的制作助手,当前为无人值守制作。做法和标准以本项目锁定的企业 Skill 及小壹补充为准。
|
||
本轮没有可询问的人,也没有人工后期;用户启动制作即授权你代为决定。指引中要求用户事先选择、确认或交人工处理的事项,由你依据商品资料和模板自行决定并继续制作,所作选择和确实无法处理的事项在交付回执中如实列出。工作范围内的顺序、并行和返工由你决定。
|
||
${PRODUCT_VOICE}
|
||
plan_production(includeKnowledge=true) 返回锁定的知识文件路径,用 read 读取。plan_production 返回制作状态,open_production_output 切换可写画布,list_project_images 查询项目候选。
|
||
用 tool_search 查找工具,通过 native_catalog 查原生命令与参数,复用已取得的 parameterDocs。企业指引中的命令行编修可用等价的画布命令完成。codemode 可依次 await 工具调用并用真实回执衔接各步。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件和版本回执确认交付。`;
|
||
|
||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||
// Both shapes are native projections of the frozen request, never the live selection.
|
||
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', 'record_field_requirements', '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', 'record_screen_check',
|
||
'defer_production_output', 'finish_production',
|
||
]);
|
||
function toolsFor(host) {
|
||
const make = (name, description, parameters, execute, format = plain) => ({ name, label: name, description, parameters:JSON.parse(JSON.stringify(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('原回合已结束,旧工具不会继续执行');
|
||
try {
|
||
host.productionSignal?.throwIfAborted();
|
||
const value = await execute(args, signal, ctx);
|
||
if ((name==='finish_production'||name==='defer_production_output') && value.finalized) {
|
||
if (value.completed) await ctx.executeTool('update_goal',{status:'complete'});
|
||
else await host.session.prompt('/goal pause');
|
||
}
|
||
return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value);
|
||
} catch(error) {
|
||
if (!(error instanceof BridgeError)) throw error;
|
||
return {...plain({failure:error.wire()}),isError:true};
|
||
}
|
||
} });
|
||
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('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, ...enterpriseTools(host, make), ...productionVideoTools(host, make)];
|
||
if (host.productionGoal) return [
|
||
...productionTools.map(([name, description, schema])=>({
|
||
...make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
|
||
['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),
|
||
...(['read_archived_images','stage_archived_image','retire_production_image','read_screen_review','record_screen_check']
|
||
.includes(name)?{exposure:'deferred'}:null),
|
||
})),
|
||
...contextTools.map(tool => ({...tool, exposure:'deferred'})), ...projectResources,
|
||
];
|
||
const tools = [
|
||
...contextTools,
|
||
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 });
|
||
}),
|
||
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) => {
|
||
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('当前项目已切换,本轮画布写入已停止');
|
||
const permission = await host.canvas.requestWrite(revision);
|
||
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧画布编辑未派发');
|
||
if (!permission.allowed || permission.writeBlocked) throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked');
|
||
if (permission.revision !== revision) throw new BridgeError('画布已修改,写入许可已过期,未执行','revision_conflict');
|
||
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('原项目已切换,未生成预览');
|
||
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' });
|
||
|
||
const outputName = Type.String({ minLength: 1 });
|
||
const outputId = Type.Optional(outputName);
|
||
tools.push(make('workflow_read', '读取当前创作工作流、实时版本及资料摘要;section按需读取,原图片和长提示词不会进入摘要。', Type.Object({
|
||
section: Type.Optional(Type.Union(['overview', 'materials', 'points', 'plan', 'slots'].map(value => Type.Literal(value)))),
|
||
outputId, offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 300 })),
|
||
}, { additionalProperties: false }), args => host.readWorkflow(args)));
|
||
tools.push(make('workflow_navigate', '切换到当前项目的资料、卖点、方案、图位或画布视图。整套制作中,查看其它输出不会切换已绑定的制作画布。', Type.Object({
|
||
stage: Type.Union(['materials', 'points', 'plan', 'slots', 'canvas'].map(value => Type.Literal(value))), 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')]),
|
||
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创建一张待执行操作,不自动执行。画布工作区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)),
|
||
}, { 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: '' });
|
||
try { host.releaseLock = lockfile.lockSync(store.root, { stale: 15000, update: 4000, retries: 0, onCompromised: error => { host.compromised = error; host.session?.agent.abort(); } }); }
|
||
catch { throw Error('此项目已有本地Agent在运行,请等待当前任务结束;未发起新请求'); }
|
||
try {
|
||
const info = transport?.info ?? brokerInfo ?? await broker.info();
|
||
if (info.accountScope !== store.identity.scope) throw Error('模型账户与项目隔离域不一致');
|
||
host.info = 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 protocol = info.model.protocol;
|
||
const api = protocol === 'openai-chat' ? 'openai-completions' : protocol;
|
||
const apiImpl = api === 'anthropic-messages' ? anthropicMessagesApi() :
|
||
api === 'openai-responses' ? openAIResponsesApi() : openAICompletionsApi();
|
||
const namedTool = name => api === 'anthropic-messages' ? { type: 'tool', name } :
|
||
api === 'openai-responses' ? { type: 'function', name } : { type: 'function', function: { name } };
|
||
const singleTool = api === 'openai-responses' && info.model.requireSingleTool === true;
|
||
const selectRequiredTool = (payload, name) => {
|
||
if (singleTool) {
|
||
const tool = payload.tools?.find(tool => tool.type === 'function' && tool.name === name);
|
||
if (!tool) throw Error('指定工具不在本次请求中');
|
||
payload.tools = [tool];
|
||
payload.tool_choice = 'required';
|
||
} else payload.tool_choice = namedTool(name);
|
||
return payload;
|
||
};
|
||
const known = runtime.getModel(api==='anthropic-messages'?'anthropic':'openai-codex', info.model.id);
|
||
const reasoning = info.model.reasoning === true;
|
||
const efforts = info.model.reasoningEfforts;
|
||
const thinkingLevelMap = Array.isArray(efforts) && efforts.length ? Object.fromEntries(
|
||
['off','minimal','low','medium','high','xhigh','max'].map(level=>[
|
||
level,efforts.includes(level)?level:level==='minimal'&&efforts.includes('low')?'low':null,
|
||
])) : known?.thinkingLevelMap;
|
||
const usesProviderDefaultOutput = api !== 'anthropic-messages'
|
||
&& (info.model.requiresOutputLimit === false || !info.model.maxTokens);
|
||
const applyOutputContract = payload => {
|
||
if (usesProviderDefaultOutput) {
|
||
delete payload.max_tokens;
|
||
delete payload.max_completion_tokens;
|
||
delete payload.max_output_tokens;
|
||
}
|
||
return payload;
|
||
};
|
||
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
|
||
// 2.5 minutes (R5 run 8 lost a whole run to a 502 burst longer than the default 14 s window).
|
||
// Workers use a shorter retry window so failed work can be re-delegated.
|
||
const mainRetry = {enabled:true,maxRetries:6,baseDelayMs:3000};
|
||
const workers = new Map();
|
||
// 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),
|
||
});
|
||
};
|
||
runtime.registerProvider('jiansun-native-98k', {
|
||
api, apiKey: 'native-broker-only', baseUrl: api === 'anthropic-messages' ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1',
|
||
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};
|
||
if (worker?.signal) options = {...options,signal:AbortSignal.any([options.signal,worker.signal].filter(Boolean))};
|
||
(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 (!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;
|
||
}
|
||
round = (worker ? worker.broker : host.goalBroker ?? broker).round();
|
||
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
|
||
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
|
||
let unknownOutcomeError;
|
||
const stream = apiImpl.streamSimple(model, 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,...workerFields,requestBytes});
|
||
host.productionSignal?.throwIfAborted();
|
||
const response=await round.fetch(...args);
|
||
headersAt=Date.now();
|
||
return observeUnknownOutcome(response, message => { unknownOutcomeError = message; });
|
||
},
|
||
onPayload: async payload => {
|
||
applyOutputContract(payload);
|
||
if (requiredTool) selectRequiredTool(payload, requiredTool);
|
||
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;
|
||
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 output.push(event);
|
||
}
|
||
const result = await stream.result();
|
||
const {stopReason}=result;
|
||
await store.appendEvent({type:'provider_finished',id:round.id,stopReason,...workerFields,requestBytes,promptCacheKeyPresent,
|
||
...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}),
|
||
...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}),
|
||
...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
|
||
if (broker?.authority?.error) throw broker.authority.error;
|
||
if (['error','aborted'].includes(stopReason)) {
|
||
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;
|
||
output.push(finalEvent); output.end(result);
|
||
} catch (error) {
|
||
const reason = redactText(String(error.message));
|
||
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 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 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')));
|
||
host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
|
||
const files = await projectTools(host);
|
||
const customTools = [...toolsFor(host), ...files.tools.map(tool =>
|
||
productionGoal && tool.name !== 'read' ? {...tool, exposure:'deferred'} : tool)];
|
||
host.workingDirectory=files.cwd;
|
||
const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], {
|
||
includeGoal: !!productionGoal,
|
||
systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM,
|
||
});
|
||
host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
|
||
const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime,
|
||
model: runtime.getModel('jiansun-native-98k', info.model.id),
|
||
thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined,
|
||
resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal','update_goal'] : []),
|
||
settingsManager: SettingsManager.inMemory({retry:mainRetry}), 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 = [productionSignal,signal].filter(Boolean);
|
||
const activeSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
||
activeSignal?.throwIfAborted();
|
||
const scoped = broker?.forDetailSlot?.(requestScope);
|
||
if (!scoped&&!transport?.stream) throw Error('详情页模型连接未就绪');
|
||
const enterpriseSkills = host.productionSkills;
|
||
if (enterpriseSkills?.resource.skills.length) {
|
||
systemPrompt = enterpriseSkills.workerGuidePrefix + 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,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 worker = {slotId,requestScope,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE,
|
||
cacheKey:host.manager.getSessionId()+':'+(kind==='product'?step:tools[0]?.name??'detail')};
|
||
const abort = () => { void workerSession.abort(); };
|
||
const budget = workerTurnBudget(slotId);
|
||
const finishTurn = workerSession.agent.finishTurn;
|
||
workerSession.agent.finishTurn = async (turn, turnSignal) => {
|
||
const decision = await finishTurn(turn,turnSignal);
|
||
const limit = budget.finishTurn();
|
||
// Native Pi may retry a failed model turn after the agent loop ends.
|
||
if(limit && turn.message.stopReason==='error')abort();
|
||
return limit ?? decision;
|
||
};
|
||
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 Error(result.errorMessage||'当前制作步骤未完成');
|
||
}
|
||
} finally {
|
||
activeSignal?.removeEventListener('abort',abort);
|
||
unsubscribe();
|
||
try { workerSession.dispose(); }
|
||
finally {
|
||
workers.delete(sessionId);
|
||
await scoped?.close();
|
||
}
|
||
}
|
||
};
|
||
const finishTurn=session.agent.finishTurn;
|
||
session.agent.finishTurn=async (turn, signal)=>{
|
||
const decision=await finishTurn(turn,signal);
|
||
if (turn.message.stopReason==='length' || host.productionCompletion || !host.productionGoal &&
|
||
(host.canvasNotificationsDetached||host.workflowBindingChanged)) {
|
||
return {action:'end'};
|
||
}
|
||
return decision;
|
||
};
|
||
host.session = session;
|
||
session.subscribe(event => {
|
||
if (event.type === 'compaction_start') host.compacting = true;
|
||
if (event.type === 'auto_retry_start') {
|
||
host.presentation = new StreamPresentation();
|
||
void store.appendEvent({type:'pi_retry',attempt:event.attempt,maxAttempts:event.maxAttempts,delayMs:event.delayMs}).catch(()=>{});
|
||
}
|
||
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);
|
||
await session.bindExtensions({ uiContext:host.nativeUI.context, mode:'rpc', abortHandler:() => { void session.abort(); } });
|
||
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(() => 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 ?? ''),
|
||
}));
|
||
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_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') {
|
||
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.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(()=>{});
|
||
await recordToolEvent(event,activity);
|
||
void Promise.resolve().then(() => 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);
|
||
}
|
||
|
||
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 (this.productionGoal && args.section === 'overview') this.productionTemplate = snapshot.template;
|
||
return latest;
|
||
}
|
||
async readEnterpriseRules(workflow, productEvidence) {
|
||
const template = workflow?.template;
|
||
if (!workflow?.available || !template?.enterprise) return null;
|
||
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','end'].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));
|
||
}
|
||
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;
|
||
}
|
||
async recordUsage({model,usage}, fields, updateContext=true) {
|
||
const {input,output,cacheRead,cacheWrite,totalTokens}=usage;
|
||
const receipt={model,inputTokens:input+cacheRead+cacheWrite,outputTokens:output,
|
||
cachedTokens:cacheRead,totalTokens,source:'sdk-response'};
|
||
const event={type:'usage',...fields,...receipt};
|
||
await this.store.appendEvent(event);
|
||
await this.onEvent(event);
|
||
if (updateContext) await this.updateContextUsage({...receipt,id:fields.id,at:Date.now()},'running');
|
||
}
|
||
async updateContextUsage(receipt = null, phase = 'ready') {
|
||
this.contextUsage = contextSnapshot(this.store.identity, this.info.model, this.session, this.contextUsage, receipt, phase);
|
||
if (phase === 'ready') {
|
||
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 } = {}) {
|
||
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 (latest.model.id !== this.info.model.id || latest.model.protocol !== this.info.model.protocol) throw Error('用户已更换模型,请重新打开会话后再调用');
|
||
if (this.session.isStreaming) throw Error('本轮尚未结束');
|
||
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.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.canvasOperations.beginTurn();
|
||
this.generatedCandidates = new Map();
|
||
this.canvasNotificationsDetached=false;this.canvasEndAttempted=false;
|
||
this.activityScope = activityScope(this.store.identity);
|
||
this.knowledgeContext = 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;
|
||
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 (!production && (await this.canvas.read()).conversationActive===false) {
|
||
throw Error('当前项目已切换,本轮对话未应用到其他项目');
|
||
}
|
||
if (!production || production.outputId) await this.readWorkflow({ section: 'overview' });
|
||
const template=production?.template??this.productionTemplate;
|
||
if (this.productionGoal && template?.enterprise) {
|
||
const current = piGoalState(this.manager);
|
||
const finishedGoal = current?.status === 'complete' ? current.id : undefined;
|
||
const pinned = !finishedGoal && (goalContinuation || current) ? template.knowledgeVersion : undefined;
|
||
this.productionSkills=await this.openProductionKnowledge(template.id,finishedGoal,pinned);
|
||
this.session.resourceLoader.extendResources({
|
||
skillPaths: this.productionSkills.resource.skills.map(skill => ({
|
||
path: skill.filePath, metadata: {source:'enterprise', scope:'project', origin:'top-level'},
|
||
})),
|
||
});
|
||
this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'read'])]);
|
||
}
|
||
if (!goalContinuation) await this.store.recordUserEvidence(text);
|
||
const running = production
|
||
? runPiProductionGoal(this, prompt, goalContinuation && !quoted.length, images)
|
||
: this.session.prompt(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 = this.productionCompletion || this.productionPause
|
||
? undefined : await unfinishedProductionTurn(this);
|
||
const remaining=await closeProductionTurn(this);
|
||
this.productionSignal?.throwIfAborted();
|
||
if (this.workflowBindingChanged) throw Error(workflowBindingError);
|
||
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||
const last = this.session.messages.filter(m => m.role === 'assistant').at(-1);
|
||
if (last?.stopReason === 'aborted' || last?.stopReason === 'error') {
|
||
throw Error(last.errorMessage || '本轮对话未完成');
|
||
}
|
||
if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议');
|
||
const resultText = this.productionCompletion?.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();
|
||
await this.notifyCanvas('end',textResult);
|
||
const result=this.productionCompletion?.receipt??unfinished??(production&&{
|
||
outputId:this.productionGoal.outputId,variantId:this.productionGoal.variantId,complete:false,
|
||
...(this.productionPause?{stageStatus:'paused',pause:this.productionPause,
|
||
originals:{images:remaining?.outputs.find(row=>row.outputId===this.productionGoal.outputId
|
||
&&row.variantId===this.productionGoal.variantId)?.inFlightImages.map(image=>image.requestId)??[]}}:{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) {
|
||
await this.display.flush();
|
||
await this.nativeUI.stop().catch(() => {});
|
||
const generated = this.generatedCandidateReply();
|
||
await this.notifyCanvas('end', generated ? `${generated}\n\n${error.message}` : error.message).catch(() => {});
|
||
throw error;
|
||
} finally {
|
||
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();
|
||
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; }
|
||
}
|
||
}
|
||
}
|