1146 lines
96 KiB
JavaScript
1146 lines
96 KiB
JavaScript
import {setTimeout as delay} from 'node:timers/promises';
|
||
import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, productRequestScope, ProductionOutputLimit, ProductionRequestFailed } from './production-recovery.mjs';
|
||
import { enterpriseTools } from './enterprise-knowledge.mjs';
|
||
import { executeWorkflow } from './workflow-execute.mjs';
|
||
import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
|
||
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, runPiProductionGoal,
|
||
mayContinueProductionGoal } from './production-goal.mjs';
|
||
import { productionVideoTools } from './production-operations.mjs';
|
||
import { COPY_IMAGE_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
|
||
import { runToolCall } from '@earendil-works/pi-agent-core';
|
||
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat';
|
||
import { atomic, digest } from './store.mjs';
|
||
import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs';
|
||
import { parseReceipt } from './receipt.mjs';
|
||
import { auditResponse, InvalidToolReply } from './response-audit.mjs';
|
||
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
|
||
import { requestPurpose } from './request-purpose.mjs';
|
||
import { productContext } from './project-context.mjs';
|
||
import { workflowContext, workflowResult } from './workflow-context.mjs';
|
||
import { EnterpriseContext } from './enterprise-context.mjs';
|
||
import { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
|
||
import { projectTools } from './project-tools.mjs';
|
||
import { responseUsage } from './usage.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 { NATIVE_CANVAS_QUICK_REFERENCE, 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 = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。
|
||
${PRODUCT_VOICE}
|
||
用 plan_production 读取本轮目标及待交付项。单独调用 open_production_output 在同一会话打开或切换到指定成品及花色,收到绑定回执后再查询 native_catalog 或操作画布。切换回执包含前一工程的保存结果、已取消的未派发图位和仍在处理的付费原请求编号。回到原成品时,可重新派发已取消的图位,并复核原请求留下的候选。打开失败时按回执处理,可重新打开或选择另一待制作成品。用户查看的页面和制作画布独立。
|
||
${DRAW_LIMIT_GUIDANCE}
|
||
用户附带引用时,按引用的 outputId、productVariantId、slotId、candidateId 或 nativeLayerId、component 定位目标,结合附带图片精修;实时选择不能替代本轮引用。
|
||
企业制作指引中的命令行编修可用等价的画布命令完成。用 read_production_knowledge 时,fileId 取自 knowledgeFiles 列表,模板编号不能当作文件编号。read_copy_fields 省略 pageId 和 fieldId 即可一次读取全页文案字段及修订号。
|
||
子代理生图和验图读取本屏实时文案,候选验图回执绑定当时的文案签名。文案还没写时派图,子代理缺少本款卖点,写入 goal 的模板原文也会变成制作要求。文案改动后要按新文案复核,画面与新卖点不符时需要返工。读清实拍、商品资料和制作规则后,建议每批选 1–3 屏,先用 write_copy_fields 把本批文案写到画布,再用 delegate_image_slots 派这批图位,生图期间写下一批。
|
||
围绕每屏卖点主角定镜头和验收候选。分派 goal 依据本款实拍、商品资料、品牌规则和已确认的卖点,写明画面要重点呈现的部件、动作或结构,避免引用画布上尚未更新的模板原文。模板对应图位的原图符合卖点部位和景别时可参考构图,用本款实拍还原商品。模板原图拍了不同部位或景别时,传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 裁切本款实拍。回填回执列出压在图位上方的模板叠层。整屏成片填充完成后,可用 check_output_screens 并行复核实际成片,pages 从 1 编号,通过时自动登记。
|
||
${COPY_IMAGE_SCREEN_CRITERIA}
|
||
根据 needs_fix 回执中的 nativeLayerId、文案字段或图位定位修正。需要看实际像素时用 read_output_screen(其 page 从 0 编号)。可用 native_catalog 查命令,再用 native_call 移动、缩放、隐藏或改写叠层。映射文案可用 write_copy_fields,图片可用 transform_slot_image 调整或重新生图。结合实际画面和商品资料自行选择处理方式。
|
||
需要独立观察结果的工具(如 open_production_output、read_output_screen、await_image_slots、finish_production)单独调用。多项连续查目录、批量采纳、批量回填文案及图层隐藏、选择、变换、样式修正等确定性操作,优先合并在一次 codemode 脚本中依次 await,使用各步实际回执衔接后续操作。
|
||
${NATIVE_CANVAS_QUICK_REFERENCE}
|
||
其余命令或完整参数说明用 native_catalog({ ids: [...] }) 一次取齐,在本回合和后续回合复用已取得的 parameterDocs。
|
||
用 read_output_screen 复核多屏时,每次按需查看 2–4 屏。后续新读图时会自动释放较早的查看截图,保留文字元数据。
|
||
transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
|
||
独立手动复核时可用 record_screen_check 登记实际结果。复核后用 finish_production 提交当前画布修订,以工具返回的文件和版本为交付依据。可随时用 open_production_output 切换其它成品或回到此前的草稿。收口时用 finish_production 的 scope=all 核验本轮交付。子代理正在运行时可用 await_image_slots 等待回执。已返回结果未知的生图请求用 reconcile_image_slots 按原编号核查,核查期间可继续其它可做的图位和画布编辑。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
|
||
|
||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||
function imageLengthSummary(data, start = 0) {
|
||
const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
|
||
const bytes = Math.floor((data.length - start - padding) * 3 / 4);
|
||
return `[image-base64-omitted:${bytes}B]`;
|
||
}
|
||
|
||
function summarizePayloadImages(value) {
|
||
if (typeof value === 'string' && value.startsWith('data:image/')) {
|
||
const comma = value.indexOf(',');
|
||
if (comma !== -1 && value.startsWith(';base64,', comma - 7)) return imageLengthSummary(value, comma + 1);
|
||
}
|
||
if (Array.isArray(value)) return value.map(summarizePayloadImages);
|
||
if (!value || typeof value !== 'object') return value;
|
||
if ((value.type === 'image' || value.type === 'base64' && value.media_type?.startsWith('image/')) && typeof value.data === 'string') {
|
||
return {...value, data: imageLengthSummary(value.data)};
|
||
}
|
||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, summarizePayloadImages(item)]));
|
||
}
|
||
// 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 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);
|
||
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=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==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain)),
|
||
...contextTools, ...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) 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();
|
||
const recordToolEvent = (event,activity,scope) => store.appendEvent({
|
||
type:event.type,toolName:event.toolName,toolCallId:event.toolCallId,isError:event.isError??false,...scope,
|
||
...(activity?{status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs}:null),
|
||
});
|
||
runtime.registerProvider('jiansun-native-98k', {
|
||
api, apiKey: 'native-broker-only', baseUrl: api === 'anthropic-messages' ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1',
|
||
models: [{
|
||
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 requiredTool;
|
||
let round, sentAt;
|
||
const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
|
||
try {
|
||
options.signal?.throwIfAborted();
|
||
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
|
||
if (host.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则');
|
||
const liveCanvas = !worker && host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null;
|
||
if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目');
|
||
if (!worker && !host.compacting && (host.canvasNotificationsDetached || !host.productionGoal &&
|
||
!liveCanvas?.manualEdit && (host.canvasOperations.writesBlocked || liveCanvas?.writeBlocked && host.canvasOperations.writeRequested))) {
|
||
const text=host.canvasNotificationsDetached?'本机:原项目已切换,原回复保留在原项目,后续画布操作已停止。':host.canvasOperations.stopReason?`本次创作已停止:${host.canvasOperations.stopReason}`:'本机:已接手,剩余画布操作已停止。';
|
||
const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } };
|
||
await store.appendEvent({ type: host.canvasNotificationsDetached?'inactive_project_stopped':host.canvasOperations.stopReason?'workflow_operation_stopped':'handover_stopped', modelCallSkipped: true });
|
||
output.push({ type: 'start', partial: message });
|
||
output.push({ type: 'done', reason: 'stop', message }); output.end(message);
|
||
return;
|
||
}
|
||
const completedProduction=!worker&&!host.compacting&&Boolean(host.productionCompletion?.receipt);
|
||
if (completedProduction) {
|
||
const text = host.productionCompletion.text;
|
||
await store.appendEvent({ type:'production_stage_submitted', modelCallSkipped: true });
|
||
const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } };
|
||
output.push({ type: 'start', partial: message });
|
||
output.push({ type: 'done', reason: 'stop', message }); output.end(message);
|
||
return;
|
||
}
|
||
const encoded = !worker && protocolMode === 'structured-json' && !host.compacting;
|
||
const wireContext = encoded ? jsonToolContext(context) : context;
|
||
if (!worker) {
|
||
host.currentCanvas = liveCanvas?.context;
|
||
const {textChars: inputChars, totalChars} = contextLengths(wireContext);
|
||
if (!host.compacting) await host.updateContextUsage(null, 'running');
|
||
host.rounds++;
|
||
if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`);
|
||
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: encoded ? contextLengths(context).totalChars : totalChars });
|
||
}
|
||
if (transport?.stream) {
|
||
const stream = transport.stream(model, wireContext, options);
|
||
for await (const event of stream) output.push(event);
|
||
const result = await stream.result();
|
||
if (!worker && !host.compacting && result.stopReason !== 'error' && result.stopReason !== 'aborted') {
|
||
const u = result.usage;
|
||
await host.updateContextUsage({ inputTokens: u.input + u.cacheRead + u.cacheWrite, outputTokens: u.output, cachedTokens: u.cacheRead, model: info.model.id, at: Date.now(), source: 'sdk-response' }, 'running');
|
||
}
|
||
output.end(result);
|
||
return;
|
||
}
|
||
round = (worker ? worker.broker : host.goalBroker ?? broker).round({inference:true});
|
||
await store.appendEvent({ type: 'provider_prepared', id: round.id, requestId:round.id, model: model.id, bindingHash: store.hash,
|
||
purpose, ...workerFields,
|
||
...(worker ? {imageCount:context.messages.reduce((count,message)=>count+
|
||
(Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0)} : null) });
|
||
if (!worker) {
|
||
if (!host.compacting) requiredTool = host.requiredTool;
|
||
}
|
||
let wireCapture;
|
||
let requestBytes, promptCacheKeyPresent, headersAt, firstThinkingAt, firstTextAt, firstToolAt;
|
||
const stream = apiImpl.streamSimple(model, wireContext, { ...options,
|
||
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
|
||
apiKey: 'native-broker-only', fetch: async (...args) => {
|
||
sentAt = Date.now();
|
||
if (worker && typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body);
|
||
await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,...workerFields});
|
||
host.productionSignal?.throwIfAborted();
|
||
const response = await round.fetch(...args);
|
||
headersAt = Date.now();
|
||
wireCapture = response.clone().text().then(text => ({ text }), error => ({ error }));
|
||
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) {
|
||
const archivedPayload = process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1' ? payload : summarizePayloadImages(payload);
|
||
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), archivedPayload);
|
||
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(archivedPayload),
|
||
promptCacheKeyPresent });
|
||
}
|
||
return payload;
|
||
},
|
||
});
|
||
let finalEvent, partial, reply = '';
|
||
for await (const event of stream) {
|
||
if (event.type === 'thinking_delta' && firstThinkingAt === undefined) firstThinkingAt = Date.now();
|
||
if (event.type === 'toolcall_delta' && firstToolAt === undefined) firstToolAt = Date.now();
|
||
if (event.type === 'text_delta' && firstTextAt === undefined) firstTextAt = Date.now();
|
||
// Release the final event only after the transport and wire audit finish.
|
||
if (event.type === 'done' || event.type === 'error') finalEvent = event;
|
||
else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
|
||
else if (!encoded) output.push(event);
|
||
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 valid = finalEvent?.type === 'done' && (worker
|
||
? ['stop','toolUse'].includes(result.stopReason) : host.compacting
|
||
? result.stopReason === 'stop' && !result.content.some(content => content.type === 'toolCall')
|
||
: ['stop', 'toolUse', 'length'].includes(result.stopReason));
|
||
const settled = await round.finish(valid, result.stopReason);
|
||
await store.appendEvent({ type: 'provider_finished', id: round.id, requestId:round.id, ...settled,
|
||
...(worker ? {...workerFields,requestBytes,promptCacheKeyPresent} : null),
|
||
...(options.signal?.aborted || host.productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null),
|
||
...(sentAt === undefined ? {} : {
|
||
...(headersAt === undefined ? {} : {responseHeadersMs:headersAt-sentAt}),
|
||
...(firstThinkingAt === undefined ? {} : {firstThinkingMs:firstThinkingAt-sentAt}),
|
||
...(firstTextAt === undefined ? {} : {firstTextMs:firstTextAt-sentAt}),
|
||
...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}),
|
||
}) });
|
||
if (broker?.authority?.error) throw broker.authority.error;
|
||
const failure = confirmedProductionFailure(settled, round.id);
|
||
if (failure) throw failure;
|
||
if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) {
|
||
if (worker) throw new ProductionOutputLimit();
|
||
host.productionSignal?.throwIfAborted();
|
||
options.signal?.throwIfAborted();
|
||
const message={...result,content:result.content.filter(block=>block.type!=='toolCall')};
|
||
output.push({type:'done',reason:'length',message});
|
||
output.end(message);
|
||
return;
|
||
}
|
||
if (!valid || settled.phase !== 'complete') throw Error(result.errorMessage ?? 'network error: inference stream did not complete');
|
||
const wire = await wireCapture;
|
||
if (!wire || wire.error) throw Error('network error: incomplete inference receipt, tool was not executed');
|
||
const usage = responseUsage(wire.text);
|
||
await store.appendEvent({ type: 'usage', id: round.id, model: model.id, purpose, ...workerFields, ...usage });
|
||
host.productionSignal?.throwIfAborted();
|
||
options.signal?.throwIfAborted();
|
||
await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage });
|
||
if (!worker && !host.compacting) await host.updateContextUsage({ ...usage, id: round.id, model: model.id, at: Date.now(), source: 'provider-response' }, 'running');
|
||
const audit = auditResponse(wire.text, info.model.protocol);
|
||
if (worker) {
|
||
if (result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回');
|
||
} else await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) });
|
||
host.productionSignal?.throwIfAborted();
|
||
options.signal?.throwIfAborted();
|
||
if (!encoded && requiredTool && !audit.calls.some(c => c.name === requiredTool)) throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
|
||
if (!host.compacting && 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: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+reason : reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
|
||
await store.appendEvent({ type: 'provider_error', id: round?.id, ...workerFields, reason: message.errorMessage,
|
||
...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) });
|
||
output.push({ type: 'error', reason: 'error', error: message }); output.end(message);
|
||
}
|
||
})();
|
||
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];
|
||
host.workingDirectory=files.cwd;
|
||
const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], {
|
||
includeGoal: !!productionGoal, mayContinueGoal: event => mayContinueProductionGoal(host, event),
|
||
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'] : []),
|
||
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(); };
|
||
workers.set(sessionId,worker);
|
||
activeSignal?.addEventListener('abort',abort,{once:true});
|
||
const unsubscribe = workerSession.subscribe(event=>{
|
||
if(event.type==='tool_execution_start'||event.type==='tool_execution_end'){
|
||
const activity=toolActivity(event,host.activityScope||activityScope(store.identity));
|
||
void recordToolEvent(event,activity,{slotId,requestScope})
|
||
.catch(error=>console.warn('子代理工具事件未保存',error.code??error.name));
|
||
}
|
||
});
|
||
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();
|
||
const result = workerSession.messages.findLast(message=>message.role==='assistant');
|
||
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();
|
||
}
|
||
};
|
||
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) void 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('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合');
|
||
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 value=await this.store.modelContext({workflow,canvas:this.currentCanvas,...options});
|
||
value.currentProduct=product;
|
||
if (workflow) value.currentWorkflow=workflow;
|
||
if (this.productionSkills && loadKnowledge) {
|
||
const {knowledge,documents}=this.productionSkills;
|
||
value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]};
|
||
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 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 (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求');
|
||
if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求');
|
||
text = redactText(text);
|
||
const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info);
|
||
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 || 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),...(production.outputId?{outputId:production.outputId}:null),
|
||
runDeadline:production.skillRunDeadline};
|
||
this.enterpriseContext??=new EnterpriseContext(this.store);
|
||
this.productionSkills=await openEnterpriseSkills(this.store,selection,
|
||
pins=>this.loadProductionKnowledge(selection,this.productionSignal,pins),
|
||
(target,lock)=>this.enterpriseContext.loadReference(target,{
|
||
...lock,read:this.productionKnowledgeRead('production',lock.signal),
|
||
}));
|
||
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 (await this.productionOperations)?.unfinished?.();
|
||
const remaining=await closeProductionTurn(this);
|
||
this.productionSignal?.throwIfAborted();
|
||
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);
|
||
const useCompletionReceipt = last?.stopReason === 'error' && this.productionCompletion && !this.canvasOperations.writesBlocked;
|
||
if (last?.stopReason === 'aborted' || last?.stopReason === 'error' && !useCompletionReceipt) {
|
||
throw Error(last.errorMessage || '本轮未完成;保留原请求');
|
||
}
|
||
if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议');
|
||
const resultText = useCompletionReceipt ? this.productionCompletion.text :
|
||
(this.previewCancelled&&!this.previewReceipt
|
||
? '已取消本次预览,没有应用这项修改。'
|
||
: presentText(this.session.getLastAssistantText() || this.productionCompletion?.text || ''));
|
||
const textResult=this.productionGoal
|
||
? stripProductionToolText(resultText).trim()||this.productionCompletion?.text||''
|
||
: 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?.inFlightImages.map(image=>image.requestId)??[]}}:{stageStatus:'continue'}),
|
||
});
|
||
return { ...(result?{production:result}: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, pins) {
|
||
this.enterpriseContext??=new EnterpriseContext(this.store);
|
||
return this.enterpriseContext.load({task:'production',...selection,turn:this.canvas.run}, {
|
||
signal,pins,read:this.productionKnowledgeRead(selection.task,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 recover(id, options = {}) { return this.exclusive(() => this.recoverTurn(id, options)); }
|
||
async recoverTurn(id, { executeReadOnly = false } = {}) {
|
||
if (this.session.isStreaming) throw Error('先等待当前操作结束');
|
||
const purpose = await requestPurpose(this, id);
|
||
if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose)) {
|
||
const original=await recoverProductionResponse(this.broker,id,this.session.model,[]);
|
||
const {requestId}=original;
|
||
const phase=['failed','rejected'].includes(original.phase)?'failed':original.phase==='complete'?'complete':'unknown';
|
||
if (phase==='unknown' && original.recoveryError) {
|
||
await this.store.appendEvent({type:'recovery_unknown',id,requestId,reason:original.recoveryError.message});
|
||
}
|
||
return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose==='whole-detail-review'
|
||
?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)};
|
||
}
|
||
const internalCompaction = ['compaction','legacy-compaction'].includes(purpose);
|
||
let record = { id, ...await this.broker.read(id) };
|
||
if (record.phase === 'unknown' || record.phase === 'dispatched') {
|
||
try { await this.broker.recover(id); }
|
||
catch (error) {
|
||
await this.store.appendEvent({ type: 'recovery_unknown', id, requestId: record.requestId, reason: error.message });
|
||
return { phase: 'unknown', requestId: record.requestId, reason: error.message, reposted: false, internalCompaction };
|
||
}
|
||
record = { id, ...await this.broker.read(id) };
|
||
}
|
||
if (purpose === 'cancelled') {
|
||
const receipt = record.phase === 'received'
|
||
? await confirmProductionResponse(this.broker, record, this.session.model, this.session.agent.state.tools, this.protocolMode)
|
||
: record;
|
||
const phase = ['failed','rejected'].includes(receipt.phase) ? 'failed' : receipt.phase === 'complete' ? 'complete' : 'unknown';
|
||
return {phase,requestId:receipt.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'};
|
||
}
|
||
if (internalCompaction) {
|
||
return {phase:['complete','received','failed','rejected'].includes(record.phase)?'complete':'unknown',
|
||
requestId:record.requestId,reposted:false,internalCompaction:true,toolsExecuted:0,canvasWrites:0};
|
||
}
|
||
if (record.phase === 'failed') return { phase: 'failed', requestId: record.requestId, reposted: false };
|
||
if (record.phase === 'unavailable') return {phase: 'unknown', requestId: record.requestId, reposted: false,
|
||
needsManualReview: true, reason: '原对话结果不可用,保留待核查,未自动放弃或重发', toolsExecuted: 0, canvasWrites: 0};
|
||
const message = await parseReceipt(record, this.session.model, this.protocolMode, this.session.agent.state.tools);
|
||
if (record.phase === 'received') await this.broker.confirm(id, record.bodyHash, true, message.stopReason);
|
||
if (message.stopReason === 'length') return { phase: 'complete', usable: false, reason: 'output_limit', toolsExecuted: 0, reposted: false };
|
||
const entries = this.manager.getEntries(), calls = message.content.filter(c => c.type === 'toolCall');
|
||
const recorded = message.responseId && entries.some(e => e.type === 'message' && e.message.role === 'assistant' && e.message.responseId === message.responseId);
|
||
const completed = calls.every(call => entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id));
|
||
if (recorded && completed) return { phase: 'complete', requestId: record.requestId, alreadyApplied: true, reposted: false };
|
||
if (calls.length && executeReadOnly && calls.every(call => ['context_read', 'memory_search', 'canvas_read', 'workflow_read'].includes(call.name))) {
|
||
const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1);
|
||
if (!recorded && last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null);
|
||
if (!recorded) this.manager.appendMessage(message);
|
||
if (this.canvas) await this.canvas.begin('取回原请求,恢复只读步骤');
|
||
let recovered = 0;
|
||
try {
|
||
for (const call of calls) {
|
||
if (entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id)) continue;
|
||
const outcome = await runToolCall(call, { tools: this.session.agent.state.tools, assistantMessage: message, context: { messages: this.session.messages, tools: this.session.agent.state.tools }, beforeToolCall: this.session.agent.beforeToolCall, afterToolCall: this.session.agent.afterToolCall });
|
||
this.manager.appendMessage({ role: 'toolResult', toolCallId: call.id, toolName: call.name, content: outcome.result.content, isError: outcome.isError, timestamp: Date.now() });
|
||
recovered++;
|
||
}
|
||
} finally { if (this.canvas) await this.canvas.end('原请求已取回,未重发;画布未被修改。'); }
|
||
const pending = await this.store.get('recovered-tools.json', []);
|
||
await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending.map(t => t.id === id ? { ...t, phase: 'read-only-complete' } : t));
|
||
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||
this.needsReopen = true;
|
||
return { phase: 'complete', requestId: record.requestId, reposted: false, readOnlyToolsRecovered: recovered, canvasWrites: 0, reopenRequired: true };
|
||
}
|
||
if (calls.length) {
|
||
const pending = await this.store.get('recovered-tools.json', []);
|
||
if (!pending.some(t => t.id === id)) pending.push({ id, requestId: record.requestId, phase: 'review', message });
|
||
await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending);
|
||
return { phase: 'complete', needsToolReview: true, requestId: record.requestId, reposted: false, toolsExecuted: 0 };
|
||
}
|
||
const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1);
|
||
if (last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null);
|
||
this.manager.appendMessage(message);
|
||
this.manager.appendCustomEntry('pi-recovered-receipt', { id, requestId: record.requestId, restoredAt: Date.now() });
|
||
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||
this.needsReopen = true;
|
||
return { phase: 'complete', requestId: record.requestId, reposted: false, reopenRequired: true, toolsExecuted: 0,
|
||
restoredText: presentText(message.content.filter(c => c.type === 'text').map(c => c.text).join('\n')) };
|
||
}
|
||
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; }
|
||
}
|
||
}
|
||
}
|