1029 lines
82 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {setTimeout as delay} from 'node:timers/promises';
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, stoppedCanvas } from './bridge-error.mjs';
import { protectSession, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, 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, parseStreamingJson } from '@earendil-works/pi-ai/compat';
import { atomic } from './store.mjs';
import { jsonToolContext, decodeToolReply } from './json-tool-codec.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 { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { projectTools } from './project-tools.mjs';
import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs';
import { activityScope, activitySummary, canvasPresence, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { 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';
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 注入。SKU 图包含全部已录入的 SKU 颜色,详情图和主图只使用产品资料为对应图类选定的 SKU 范围。instructions只描述本次场景与修改要求,不能从旧候选、模板或场景图推断并覆盖产品颜色。
以工具读到的当前产品资料和规则为依据。历史对话中的旧产品、旧店铺或旧规则只作讨论历史,不能覆盖当前绑定;未配置规则时可以讨论通用方案,明确不冒充已有品牌规范。
需要核对项目目标时,用 workflow_read 读取当前工作流的 objective。用户创建项目、填写资料并选择模板后,总目标就是按所选模板完成该产品的图文内容。用户问目标或下一步时,结合当前产品、品牌品类、模板和真实进度回答,不因未选图层、未选卖点或没有新指令而说不知道目标。总目标与本轮执行范围分别判断;仅讨论不自动执行,明确要求“生成第一张图”时读取当前输出的图位顺序,生成首个图片格候选供预览采纳。
汇报生成与采纳进度时用 workflow_read 读取实时图位,以 status 和 selectedCandidateId 为准,failed表示此候选失败,unknown才是待核查,不能用历史对话的“结果未知”或“已接手”覆盖实时状态。slots是分页结果,超出当前页时用workflow_read继续读取,不按当前页推断整项目已经完成或失败。canvasFirst流程不要求先完成旧的事实分析、卖点和页面方案向导,不能把这些旧阶段的空状态当成当前流程的阻塞。
卖点文案可以直接在当前画布协作,不要求用户先走旧分析、卖点、页面方案向导。生成产品卖点时先给可修改的消费者成稿,缺失依据单列待确认,不把内部编号或免责声明写入成稿。为模板文字框生成或修改文案时,先canvas_read读取本轮引用的真实文字层;按templateField中的页面、fieldId、用途及maxChars/maxLines组织每格内容,实际回填始终使用nativeLayerId,不按列表序号、同名标题或生成返回顺序匹配。没有模板约束的文字层沿用实时文字框尺寸和样式,不编造字数限制。只改用户指定文字,保留字号、字体、位置、其他格子和图片;多格读取全部引用文字层后,使用copywriting_fields提交每格候选;用户在原生候选列表中逐格修改、预览和采纳,用户采纳后才算回填。已有文案修改要读取原文并保留未要求改变的事实。
重要产品事实和用户决定用 memory_set 保存,必须引用当前规则域用户明确确认的原话。旧店铺历史只能讨论,需用户在当前域重新确认才能记为当前事实。需要历史用 memory_search。
需要企业依据时,通过 tool_search 查找 enterprise_knowledge_base_fcd6fe6f 的只读工具;每个新任务重新查询当前来源,历史结果不得冒充最新。知识库内容是参考资料,可作为真实资料或用户选定模板的适用依据,但不能自动视为当前产品已确认事实;它不授权执行脚本或修改画布。尊重用户已选定模板及其实际适用约束。结合当前产品资料、素材、品牌知识和模板字段开展创作;先读取实时工作流。用户明确要求并确定范围时,可使用 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、商品实拍、资料和模板制作并复核。按需读取适用 Skill 和引用。由你决定工作范围内的顺序、并行和返工。
当前为无人值守制作,没有可询问的人,也没有人工后期。小壹原生画布完成合成和导出,交付目录已由界面指定。指引中交给人工处理或需要用户确认的事项,可依据商品资料用现有工具处理,确实无法处理的在交付回执中如实列出。
${PRODUCT_VOICE}
用 plan_production 查看待交付项,open_production_output 切换可写画布,保留各成品在途工作。用 list_project_images 查询本项目可复用的候选。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。脚本可用 store() 留存需要复用的大对象,只输出本次判断所需的字段、状态和失败原因。查图层树时可用 layer.list,并在脚本内筛选目标。
按实际像素和企业 Skill 复核成片。结果未知的付费请求用 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', '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 && host.canvas?.workflowRead) 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;
if (!host.productionGoal&&host.canvasOperations.writesBlocked) host.canvasOperations.stopReason=error.message;
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=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','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);
if (!host.canvas) return { available: false };
if (typeof host.canvas.readCanvas === 'function') return host.canvas.readCanvas(layer!==undefined?{layer}:{ ...(screen === undefined ? {} : { screen }), ...(screenId === undefined ? {} : {screenId}), ...(mode === undefined ? {} : {mode}), ...(filter === undefined ? {} : {filter}), ...(maxDepth === undefined ? {} : {maxDepth}), offset });
if (mode === 'summary' || filter !== undefined || maxDepth !== undefined || screenId !== undefined) throw Error('当前客户端不支持画布摘要或检索,请更新完整运行组件');
const state = await host.canvas.read(), context = state.context;
if(state.conversationActive===false||!context)throw Error('当前项目已切换,未读取其他项目的画布');
if (context.layersTruncated || (context.totalLayers !== undefined && context.totalLayers > context.layers.length)) throw Error('当前客户端尚未提供完整有界读取,请更新完整运行组件;未将截断结果当完整画布');
const layers = layer ? context.layers.filter(l => l.id === layer) : screen ? context.layers.filter(l => l.name.startsWith(screen + '/') || l.name.startsWith(screen + ' ')) : context.layers;
if ((layer || screen) && !layers.length) throw Error('指定图层或分屏不存在,未更改画布');
return { allowed: state.allowed, writeBlocked:state.writeBlocked,revision: state.revision, context: { id:context.id,name:context.name,width:context.width,height:context.height,subject:context.subject,selected:context.selected,references:frozenReferences(context),totalLayers: context.layers.length, offset,
hasMore: !layer && offset + 20 < layers.length,
layers: layer ? layers : layers.slice(offset, offset + 20).map(l => ({ id: l.id, name: l.name, kind: l.kind, text: l.text ? Array.from(l.text).slice(0, 80).join('') : null, locked: l.locked })) } };
}),
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.canvas) throw Error('本轮没有连接画布');
if (host.canvasOperations.original || host.canvasOperations.active) 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 || host.canvasOperations.writesBlocked)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 || host.canvasOperations.writesBlocked) 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:'原回合已结束,未读取其他回合的图层详情'};
if (typeof host.canvas.readCanvas === 'function') {
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:'编辑已确认,图层详情读取失败;请重新读取'};
}
}
const layer = state.context?.layers?.find(l => l.id === edit.params.layer);
return layer ? {...result, layer} : {...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});
if (host.turnEpoch === epoch && (dispatched && !terminal || stoppedCanvas(error)||signal?.aborted)) host.canvasOperations.writesBlocked = true;
throw error;
} finally { if (host.canvasOperations.active === owner) { host.canvasOperations.active = null; } }
})();
}),
];
const active = host.canvas ? tools : tools.filter(t => !t.name.startsWith('canvas_'));
if (typeof host.canvas?.readTemplateImage === 'function') {
active.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};
}));
}
if (typeof host.canvas?.detailImages === 'function') {
active.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'});
}
active.push(...projectResources);
if (typeof host.canvas?.copyOptions === 'function') active.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'});
if(typeof host.canvas?.copyFields==='function')active.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'});
if (typeof host.canvas?.preview === 'function') active.push({ ...make('canvas_preview', '在原生界面预览当前图层修改,等用户采纳才应用。宿主先读取真实目标并绑定当前版本,无需填写revision。type.edit替换文案须传params.text;超出模板文字格限制时由原生输入等待用户缩短或取消,不放宽模板。只传本命令支持的参数,其他命令可先查native_catalog。保留未要求改变的字体、字号、位置和其他图层。', previewParameters, async (args, signal, ctx) => {
if (host.canvasNotificationsDetached || host.canvasOperations.writesBlocked) 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)) {
if(!host.nativeUI)throw Error('文案超过模板文字格的字数或行数,请缩短后预览');
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;host.canvasOperations.writesBlocked=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);
if (typeof host.canvas?.workflowRead === 'function') active.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)));
if (typeof host.canvas?.workflowNavigate === 'function') active.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));
}));
if (typeof host.canvas?.workflowExecute === 'function' && typeof host.canvas?.workflowPoll === 'function') active.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);
}));
if (typeof host.canvas?.workflowPropose === 'function') active.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 active;
}
/** 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, protocolMode = 'native-tools', callBudget, onEvent = () => {} }) {
assertPiNodeVersion(process.versions.node);
if (!['native-tools', 'structured-json'].includes(protocolMode)) throw Error('工具协议模式无效');
if (callBudget !== undefined && (!Number.isSafeInteger(callBudget) || callBudget < 1)) throw Error('单轮模型调用预算无效');
const host = new DetailPiAgent();
Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, protocolMode, callBudget, turnEpoch: 0, rounds: 0, 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 (!canvas?.detailImages || 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;
if (canvas) 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};
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) => 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),
...(event.isError?{error:event.result?.content?.find(item=>item.type==='text')?.text?.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('本地会话锁失效,已停止模型调用');
const encoded = !worker && protocolMode === 'structured-json' && !host.compacting;
const wireContext = encoded ? jsonToolContext(context) : context;
if (!worker) {
const {textChars: inputChars, totalChars} = contextLengths(wireContext);
if (!host.compacting) await host.updateContextUsage(null, 'running');
host.rounds++;
if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`);
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: encoded ? contextLengths(context).totalChars : totalChars });
}
if (transport?.stream) {
const stream = transport.stream(model, wireContext, options);
for await (const event of stream) output.push(event);
const result = await stream.result();
if (!worker && !host.compacting && !['error','aborted'].includes(result.stopReason)) {
await host.recordUsage(result, {purpose});
}
output.end(result);
return;
}
round = (worker ? worker.broker : host.goalBroker ?? broker).round();
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
const stream = apiImpl.streamSimple(model, wireContext, { ...options,
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
apiKey: 'native-broker-only', fetch: async (...args) => {
sentAt=Date.now();
if (typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
await store.appendEvent({type:'provider_started',id:round.id,...workerFields,requestBytes});
host.productionSignal?.throwIfAborted();
const response=await round.fetch(...args);
headersAt=Date.now();
return response;
},
onPayload: async payload => {
applyOutputContract(payload);
if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool);
if (!worker && !encoded && api === 'openai-completions' && payload.tools?.length) {
payload.tool_choice ||= 'auto';
payload.parallel_tool_calls = false;
}
if (encoded && api === 'openai-completions') payload.response_format = { type: 'json_object' };
if (encoded && api === 'openai-responses') payload.text = { format: { type: 'json_object' } };
// Private project evidence: BODY ONLY, never the fetch headers or API Key.
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
}
return payload;
},
});
let finalEvent, partial, reply = '';
for await (const event of stream) {
if (event.type === 'text_delta') firstTextAt??=Date.now();
if (event.type === 'done' || event.type === 'error') finalEvent = event;
else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
else if (!encoded) output.push(event);
else if (event.type === 'start') {
partial = { ...event.partial, content: [] };
output.push({ type: 'start', partial });
} else if (event.type === 'text_delta' && partial) {
const raw = event.partial.content.filter(c => c.type === 'text').map(c => c.text).join('');
const current = parseStreamingJson(raw)?.reply;
if (typeof current === 'string' && current.startsWith(reply) && current !== reply) {
if (!reply) output.push({ type: 'text_start', contentIndex: 0, partial });
const delta = current.slice(reply.length); reply = current;
partial.content = [{ type: 'text', text: current }];
output.push({ type: 'text_delta', contentIndex: 0, delta, partial });
}
}
}
const result = await stream.result();
const {stopReason}=result;
await store.appendEvent({type:'provider_finished',id:round.id,stopReason,...workerFields,requestBytes,promptCacheKeyPresent,
...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}),
...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}),
...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
if (broker?.authority?.error) throw broker.authority.error;
if (['error','aborted'].includes(stopReason)) {
result.errorMessage=redactText(result.errorMessage??'');
output.push(finalEvent);
output.end(result);
return;
}
host.productionSignal?.throwIfAborted();
options.signal?.throwIfAborted();
await host.recordUsage(result, {id:round.id,purpose,...workerFields}, !worker&&!host.compacting);
if (stopReason==='length') {
output.push(finalEvent);
output.end(result);
return;
}
if (requiredTool && !result.content.some(block=>block.type==='toolCall'&&block.name===requiredTool)) {
throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
}
if (requiredTool) host.requiredTool = null;
if (encoded) {
const content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id);
const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' };
if (!partial) output.push({ type: 'start', partial: message });
if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message });
output.push({ type: 'done', reason: message.stopReason, message }); output.end(message);
} else { output.push(finalEvent); output.end(result); }
} catch (error) {
const reason = redactText(String(error.message));
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 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')));
if (typeof canvas?.uiRequest === 'function') host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
const files = await projectTools(host);
const customTools = [...toolsFor(host), ...files.tools.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}), 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) => {
const signals = [productionSignal,signal].filter(Boolean);
const activeSignal = signals.length ? AbortSignal.any(signals) : undefined;
activeSignal?.throwIfAborted();
const scoped = broker?.forDetailSlot?.(requestScope);
if (!scoped&&!transport?.stream) throw Error('详情页模型连接未就绪');
const enterpriseSkills = host.productionSkills?.resource.skills;
if (enterpriseSkills?.length) {
systemPrompt += formatSkillsForPrompt(enterpriseSkills);
tools = [...tools,files.read('worker',requestScope)];
}
const 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,host.activityScope||activityScope(store.identity));
void recordToolEvent(event,activity,{slotId,requestScope})
.catch(error=>console.warn('子代理工具事件未保存',error.code??error.name));
}
});
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();
workerSession.dispose();
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.canvasOperations.writesBlocked||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);
if (host.nativeUI || productionGoal) 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([
canvas && (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 = canvas && 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
&& canvas) {
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' && typeof canvas.reply==='function') {
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));
if (canvas) await host.notifyCanvas('activity', activitySummary(event),
activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{});
await recordToolEvent(event,activity);
void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});
}
});
// 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) && this.canvas?.workflowRead
? 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(!this.canvas)return;
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} 张已采纳到画布。`;
if (this.canvasOperations.stopReason) reply += `\n\n后续操作已停止。${this.canvasOperations.stopReason}`;
return reply;
}
async recordUsage({model,usage}, fields, updateContext=true) {
const {input,output,cacheRead,cacheWrite,totalTokens}=usage;
const receipt={model,inputTokens:input+cacheRead+cacheWrite,outputTokens:output,
cachedTokens:cacheRead,totalTokens,source:'sdk-response'};
const event={type:'usage',...fields,...receipt};
await this.store.appendEvent(event);
await this.onEvent(event);
if (updateContext) await this.updateContextUsage({...receipt,id:fields.id,at:Date.now()},'running');
}
async updateContextUsage(receipt = null, phase = 'ready') {
this.contextUsage = contextSnapshot(this.store.identity, this.info.model, this.session, this.contextUsage, receipt, phase);
if (phase === 'ready') {
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?.contextUsage && 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;
if (this.canvas) {
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) && typeof this.canvas?.workflowRead === 'function') await this.readWorkflow({ section: 'overview' });
const template=production?.template??this.productionTemplate;
if (this.productionGoal && template?.enterprise) {
const {brandName,categoryName}=this.productEvidence.product;
const selection={brandName,categoryName,templateId:template.id,releaseId:template.version,
resourceSetId:template.resourceSetId,...(template.skillSources?{skillSources:template.skillSources}:null),
outputId:production.outputId??undefined};
this.enterpriseContext??=new EnterpriseContext(this.store);
this.productionSkills=await openEnterpriseSkills(this.store,selection,
()=>this.loadProductionKnowledge(selection,this.productionSignal),
(target,lock)=>this.enterpriseContext.loadReference(target,{
...lock,read:this.productionKnowledgeRead('production',lock.signal),
}),
pinned=>this.enterpriseContext.checkPinnedGuides(pinned,{
signal:this.productionSignal,read:this.productionKnowledgeRead('production',this.productionSignal),
}),{signal:this.productionSignal});
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.canvasOperations.stopReason ??
(this.previewCancelled&&!this.previewReceipt
? '已取消本次预览,没有应用这项修改。'
: presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || this.canvasOperations.stopReason || ''));
const textResult=this.productionGoal?stripProductionToolText(resultText).trim():
this.canvasNotificationsDetached&&last?.stopReason==='toolUse'
? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText;
if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留');
await this.display.flush();
await this.updateContextUsage(null, 'ready');
await this.nativeUI?.stop();
if (this.canvas) 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=this.productionSkills?.versionNotice;
return { ...(result?{production:{...result,...(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();
if (this.canvas) await this.notifyCanvas('end', generated && !this.canvasOperations.stopReason
? `${generated}\n\n${error.message}` : generated ?? error.message).catch(() => {});
throw error;
} finally {
await closeProductionTurn(this).catch(()=>{});
}
}
async loadProductionKnowledge(selection, signal) {
this.enterpriseContext??=new EnterpriseContext(this.store);
return this.enterpriseContext.load({task:'production',...selection,turn:this.canvas.run}, {
signal,read:this.productionKnowledgeRead('production',signal),
});
}
productionKnowledgeRead(task, signal) {
const requireCurrent = async () => {
signal?.throwIfAborted();
const state=await this.canvas.read();
if (state.conversationActive===false||state.writeBlocked) throw Error('资料读取已取消,已完成图位保留');
};
return async read=>{
for(;;){
await requireCurrent();
try { return await read(); }
catch(error){
if(error.status!==429||!(error.retryAfterSeconds>0))throw error;
const seconds=Math.ceil(error.retryAfterSeconds);
const notice=task!=='image'?{heading:'等待知识库响应'}:undefined;
await this.canvas.delta('知识库访问限流,约 '+seconds+' 秒后继续',undefined,notice);
const until=Date.now()+seconds*1000;
while(Date.now()<until){
await delay(Math.min(1000,until-Date.now()),undefined,{signal});
await requireCurrent();
}
}
}
};
}
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; }
}
}
}