From 4341a37860d4dbc1cdedf9f8a68d1142be892b2a Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 00:05:13 +0800 Subject: [PATCH] refactor(xiaoyi): open canvas commands and separate production reads --- apps/detail-agent-pi/src/activity-event.mjs | 5 +- apps/detail-agent-pi/src/agent.mjs | 63 ++++--- apps/detail-agent-pi/src/native-tools.mjs | 28 ++- apps/detail-agent-pi/src/production-goal.mjs | 54 +++++- apps/detail-agent-pi/src/project-context.mjs | 48 ++--- apps/detail-agent-pi/src/project-shell.mjs | 59 ++++++ apps/detail-agent-pi/src/project-tools.mjs | 6 +- apps/detail-agent-pi/src/whole-detail.mjs | 55 ++---- .../test/conversation.test.mjs | 6 +- .../detail-agent-pi/test/native-wire.test.mjs | 120 ++++++++++-- apps/detail-agent-pi/test/pi.test.mjs | 14 +- .../test/whole-detail.test.mjs | 65 +++---- .../apps/photocraft/src/jiansun_backend.rs | 14 +- .../src/jiansun_canvas_workspace.rs | 16 +- .../photocraft/src/jiansun_image_protocol.rs | 21 +++ .../apps/photocraft/src/jiansun_images.rs | 6 +- .../apps/photocraft/src/jiansun_models.rs | 59 +++++- .../apps/photocraft/src/jiansun_pi.rs | 9 +- .../apps/photocraft/src/jiansun_pi_runtime.rs | 11 +- .../crates/ui-egui/src/jiansun.rs | 3 + .../ui-egui/src/jiansun/agent_native.rs | 173 ++++++++++++++---- .../crates/ui-egui/src/jiansun/agent_panel.rs | 84 +++++++++ .../crates/ui-egui/src/jiansun/pi_bridge.rs | 3 + .../ui-egui/src/jiansun/workflow_bridge.rs | 33 ++-- docs/development/xiaoyi/implementation.md | 29 +++ docs/development/xiaoyi/limits.md | 9 + 26 files changed, 744 insertions(+), 249 deletions(-) create mode 100644 apps/detail-agent-pi/src/project-shell.mjs create mode 100644 docs/development/xiaoyi/limits.md diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index e0271a14..481c0e63 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -8,9 +8,10 @@ const labels = Object.freeze({ workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作', native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具', canvas_candidate_image: '核对图位和候选', - plan_production: '准备制作策划', read_production_knowledge: '读取制作规则', + plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则', read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '验图并回填', - read_output_screen: '查看实际画布', review_output_screen: '复核当前屏', finish_production: '提交成品导出', + read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核', + check_image_slots: '发起验图', finish_production: '提交成品导出', save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据', plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案', }); diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 3c4377d0..b749967c 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -10,7 +10,7 @@ import fs from 'node:fs/promises'; import lockfile from 'proper-lockfile'; import { Type } from '@sinclair/typebox'; import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, - mayContinueProductionGoal, piGoalState, productionObjective } from './production-goal.mjs'; + mayContinueProductionGoal, piGoalState } from './production-goal.mjs'; import { Agent, runToolCall } from '@earendil-works/pi-agent-core'; import { createAgentSession, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent'; import { retryAssistantCall } from '@earendil-works/pi-ai'; @@ -56,14 +56,14 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料 用户明确要求先看修改预览时,使用 canvas_preview 在原生界面生成待用户采纳的预览;预览未修改画布,只有用户点击原生界面采纳才应用。用户明确要求直接编辑时沿用原有原生命令。 本轮操作前先canvas_read读取实时画布与revision,后续连续操作使用刚读取或上一真实完成回执的revision;明确完成的步骤不得重发,最终统一核验。只执行用户要求的现有未锁定对象编辑或新增对象,保留无关图层。回合最初allowed=false表示尚未申请写入,写工具会先向宿主申请;writeBlocked=true表示本轮已接手或版本已变化,必须停止写入。历史接手只影响当时那一轮,新用户回合需以实时状态为准。讨论不需要画布写许可。 references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。 -不要声称尚未执行的修改已完成。工具失败要说明。未知模型请求只读查询,不要要求重试或重新生成。`; +只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`; const PRODUCTION_SYSTEM = `你是由壹点详情页的制作 Agent 小壹。用户已授权整套制作,productionGoal 标明你当前负责的输出和款式。 先用 read 加载已提供且适用于当前任务的企业 Skill。制作软件已选 PhotoCraft。按正文及引用,使用当前画布工具写入、回填、复核和交付。 -根据已确认的产品事实、品牌和模板定好整页卖点、逐屏图文关系和统一调性。自主选择当前输出内的工具、顺序、并行任务和返工方案。逐屏初稿写入画布后,工具会派发该屏有策划依据的图位。其它图位和返工按实际问题交给子代理。局部等待时继续处理当前输出里能做的图位和文案。 +根据已确认的产品事实、品牌和模板定好整页卖点、逐屏图文关系和统一调性。自主选择当前输出内的工具、顺序、并行任务和返工方案。按需读取项目资料、原生画布和图位。需要整页策划协助时可调用 start_production_strategy。有配图依据时用 delegate_image_slots 分派,查看候选用 review_image_slots,发起验图用 check_image_slots。 根据具体退回原因修正有问题的部分。图像符合商品结构和图位要求、只有某句缺少画面依据时,依据文案修订回执改写对应格并复核原候选。逐屏复核实际画面、图文对应、裁切、可读性和标注。符合要求后提交当前输出,客户端根据实际导出回执与仍可推进的输出安排后续。 文案是给买家读的。标题说清这一屏的重点,短句说清买家能看到什么、怎么使用。拍摄说明、验图用语和部件清单只用于制作。逐屏连读标题和正文,改掉重复词、拼接的半句话及样稿里的卖点。 -保留用户编辑。缺失的商品事实不得编造。原请求未知时只核查原编号。还有可处理的工作时继续调用工具。普通回复中的参数没有执行,操作须通过标准工具提交。 +保留用户编辑。缺失的商品事实不得编造。生图和画布操作结果未确认时,只核查原编号。还有可处理的工作时继续调用工具。操作须通过标准工具提交。 用简短中文说明正在做的事和真实结果。用第几屏、标题、配图用途和产品部件名称表达,内部字段编号、工具参数和调用名称只用于工具。`; const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value }); @@ -405,17 +405,20 @@ export class DetailPiAgent { return; } host.currentCanvas = liveCanvas?.context; - const injected = await host.modelContext(); - injected.currentProduct = host.productEvidence; - if (!host.compacting && host.currentWorkflow) injected.currentWorkflow = host.currentWorkflow; - if (liveCanvas?.context?.width) injected.constraints.width = liveCanvas.context.width; - if (liveCanvas) injected.currentCanvasAuthority = { run: liveCanvas.run, conversationActive: liveCanvas.conversationActive, allowed: liveCanvas.allowed, writeBlocked: liveCanvas.writeBlocked, revision: liveCanvas.revision, documentId: liveCanvas.context?.id, appliesTo: 'current-user-turn', - canvas: liveCanvas.context && { name: liveCanvas.context.name, width: liveCanvas.context.width, height: liveCanvas.context.height, totalLayers: liveCanvas.context.totalLayers, layersTruncated: liveCanvas.context.layersTruncated, - subject: liveCanvas.context.subject, selected: liveCanvas.context.selected, references: frozenReferences(liveCanvas.context), liveSelected: liveCanvas.context.liveSelected, activeLayerId: liveCanvas.context.activeLayerId } }; - const knowledge=host.productionSkills?.knowledge??host.knowledgeContext; - await store.appendEvent({ type: 'context_injected', bindingHash: store.hash, messageCount: context.messages.length, memoryHash: digest(injected.confirmedMemory), - constraints:injected.constraints,knowledgeSources:knowledge?[...knowledge.skills,...knowledge.rules].map(({fileId,revision,kind})=>({fileId,revision,kind})):[] }); - const contextual = host.projectModelContext(context, injected); + let contextual = context; + if (!host.productionGoal && !host.compacting) { + const injected = await host.modelContext(); + injected.currentProduct = host.productEvidence; + if (host.currentWorkflow) injected.currentWorkflow = host.currentWorkflow; + if (liveCanvas?.context?.width) injected.constraints.width = liveCanvas.context.width; + if (liveCanvas) injected.currentCanvasAuthority = { run: liveCanvas.run, conversationActive: liveCanvas.conversationActive, allowed: liveCanvas.allowed, writeBlocked: liveCanvas.writeBlocked, revision: liveCanvas.revision, documentId: liveCanvas.context?.id, appliesTo: 'current-user-turn', + canvas: liveCanvas.context && { name: liveCanvas.context.name, width: liveCanvas.context.width, height: liveCanvas.context.height, totalLayers: liveCanvas.context.totalLayers, layersTruncated: liveCanvas.context.layersTruncated, + subject: liveCanvas.context.subject, selected: liveCanvas.context.selected, references: frozenReferences(liveCanvas.context), liveSelected: liveCanvas.context.liveSelected, activeLayerId: liveCanvas.context.activeLayerId } }; + const knowledge=host.knowledgeContext; + await store.appendEvent({ type: 'context_injected', bindingHash: store.hash, messageCount: context.messages.length, memoryHash: digest(injected.confirmedMemory), + constraints:injected.constraints,knowledgeSources:knowledge?[...knowledge.skills,...knowledge.rules].map(({fileId,revision,kind})=>({fileId,revision,kind})):[] }); + contextual = host.projectModelContext(context, injected); + } const encoded = protocolMode === 'structured-json' && !host.compacting; const wireContext = encoded ? jsonToolContext(contextual) : contextual; const inputChars = contextTextLength(wireContext); @@ -438,10 +441,7 @@ export class DetailPiAgent { await store.appendEvent({ type: 'provider_prepared', id: round.id, model: model.id, bindingHash: store.hash, purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation' }); host.inflight = round.id; - if (!host.compacting) { - requiredTool ??= host.requiredTool; - host.requiredTool = null; - } + if (!host.compacting) requiredTool = host.requiredTool; let wireCapture; let sentAt, headersAt, firstTextAt; const stream = apiImpl.streamSimple(model, wireContext, { ...options, apiKey: 'native-broker-only', fetch: async (...args) => { @@ -507,7 +507,7 @@ export class DetailPiAgent { } 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('原始响应未完整取到,未执行工具;请只读核查原请求'); + 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: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation', ...usage }); @@ -516,6 +516,7 @@ export class DetailPiAgent { const audit = auditResponse(wire.text, info.model.protocol); await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) }); 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(''), contextual, round.id); const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' }; @@ -552,14 +553,16 @@ export class DetailPiAgent { return {skills:[...skills.values()],diagnostics:[...local.diagnostics,...enterprise.diagnostics]}; }, getPrompts: () => extensions.resourceLoader.getPrompts(), getThemes: () => ({ themes: [], diagnostics: [] }), - getAgentsFiles: () => ({ agentsFiles: [] }), getSystemPrompt: () => productionGoal ? PRODUCTION_SYSTEM : SYSTEM, getSystemPromptSource: () => undefined, + getAgentsFiles: () => ({ agentsFiles: [] }), + getSystemPrompt: () => productionGoal ? PRODUCTION_SYSTEM+'\n当前工作画布:'+productionGoal.outputId+'。' : SYSTEM, + getSystemPromptSource: () => undefined, getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [], extendResources() {}, async reload() {}, }; 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'] : []), - // Pi retries inside the model stream after the native gateway settles the original. - settingsManager: SettingsManager.inMemory({ compaction: { enabled: true }, retry: { enabled: true } }), sessionManager: host.manager, + settingsManager: SettingsManager.inMemory({}), sessionManager: host.manager, }); host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId) => { const skills=loader.getSkills().skills; @@ -713,6 +716,14 @@ export class DetailPiAgent { && (PHOTOCRAFT_NATIVE_TOOL_NAMES.includes(tool.name)||files.tools.includes(tool))).map(tool=>tool.name), ...productionTools.map(([name])=>name)]); 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()}); + } session.agent.toolExecution = 'sequential'; // AgentSession UI listeners are fire-and-forget. Core listeners are awaited: // the native UI, durable activity journal and handover gates must settle first. @@ -856,8 +867,6 @@ export class DetailPiAgent { return reply; } projectModelContext(context, injected) { - if (this.productionGoal && !this.compacting) injected.productionGoal = {...this.productionGoal,objective:productionObjective}; - if (this.compacting) return context; return normalizeContext({...context,messages:[...context.messages, {role:'system',content:'当前项目与画布事实:\n' + JSON.stringify(injected),timestamp:0}]}); } @@ -1014,7 +1023,7 @@ export class DetailPiAgent { }); } - async executeWholeDetail(outputId, production, pending, signal, drive) { + async executeWholeDetail(outputId, production, pending, signal, drive, {planStrategy=true}={}) { const heartbeat=setInterval(()=>{this.canvas.read().catch(()=>{});},2000); heartbeat.unref(); this.wholeDetailActive=true; @@ -1046,7 +1055,7 @@ export class DetailPiAgent { if(failure)return {settled:true,...(!failure.retryable?{rejection:failure.message}:null)}; return null; }:undefined, - prepareStrategy:production ? (plan,slots,knowledge,runMainAgent)=>prepareProductStrategy(this,runMainAgent,plan,slots,knowledge) : undefined}); + prepareStrategy:production && planStrategy ? (plan,slots,knowledge,runMainAgent)=>prepareProductStrategy(this,runMainAgent,plan,slots,knowledge) : undefined}); } finally { this.wholeDetailActive=false; this.productionRequests=null; diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index f6251827..8a9e63cc 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -16,16 +16,26 @@ export const nativeCallParameters = Type.Object({ /** One registry adapter covers native commands. It does not implement them. */ export function nativeTools(host, make) { if (typeof host.canvas?.nativeCatalog !== 'function' || typeof host.canvas?.nativeCall !== 'function') return []; - const available = () => { - if (host.canvasNotificationsDetached || host.canvasWritesStopped) throw Error('原项目已切换或原操作结果需核查,本轮不再派发原生操作'); + const available = (write = true) => { + if (host.canvasNotificationsDetached || write && host.canvasWritesStopped) throw Error('原项目已切换或原操作结果需核查,本轮不再派发原生操作'); + }; + const commandLeases = new Map(); + const catalog = async args => { + available(false); + const result = await host.canvas.nativeCatalog(args); + for (const item of result?.items ?? []) commandLeases.set(item.id, item.requiresRevisionLease); + return result; }; return [ {...make('native_catalog', '查询 PhotoCraft 完整原生命令和客户端界面能力。filter支持空格分隔的并列关键词,按相关度返回紧凑摘要(默认10项);id精确取某个命令完整parameterDocs。parameterDocs是原生说明而非完整JSON Schema。先查相关命令,复用已取得说明;可在同次CodeMode中批量查所需id,不要反复打印未筛选整页。实时enabled/reason保留,不需要逐业务工具迁移。', nativeCatalogParameters, - async args => { available(); return host.canvas.nativeCatalog(args); }), ...nativeToolMetadata('native_catalog')}, + catalog), ...nativeToolMetadata('native_catalog')}, {...make('native_call', '统一执行已发现的原生命令或界面操作。engine.execute的params为{command,params};ui.set/inspect/menu.list沿用目录中的原生契约。revision必须来自实时读取。返回真实原生结果;后台任务等待原job终态,不重发。严格依次await;禁止把提案、pending或脚本文字输出当成执行成功。', nativeCallParameters, async (args, signal) => { - available(); - const readOnly = args.method === 'ui.inspect' || args.method === 'ui.menu.list'; + available(false); + const command = args.method === 'engine.execute' ? args.params.command : undefined; + if (command && !commandLeases.has(command)) await catalog({id:command}); + const readOnly = args.method === 'ui.inspect' || args.method === 'ui.menu.list' || commandLeases.get(command) === false; + available(!readOnly); if (host.nativeUnresolved && !readOnly) throw Error('原生操作结果未知,先核查原请求;可使用 native_reconcile 只读核查,不会重发'); if (host.nativeToolActive) throw Error('已有原生操作正在执行,请依次await完成结果'); const epoch = host.turnEpoch, run = host.canvas.run, documentId = host.canvas.documentId; @@ -41,11 +51,11 @@ export function nativeTools(host, make) { host.canvasWriteRequested = true; const permission = await host.canvas.requestWrite(args.revision); checkTurn(); - if (!permission.allowed) throw Error('用户已接手,本轮原生操作未获许可'); - if (permission.revision !== args.revision) throw Error('画布已修改,原生操作修订许可已过期,未执行'); + if (permission.writeBlocked && !permission.retryWrite) throw Error('用户已接手,本轮原生操作未获许可'); + if (!permission.allowed || permission.revision !== args.revision) throw Error('写入修订已变化,请重新读取画布'); } signal?.throwIfAborted(); - available(); + available(!readOnly); dispatched = true; const result = await host.canvas.nativeCall(args); if (result?.pending === true && Number.isSafeInteger(result.job) && result.job > 0) pendingJob = result.job; @@ -82,7 +92,7 @@ export function nativeTools(host, make) { return settled; } catch (error) { if (!readOnly && dispatched && !terminal) host.nativeUnresolved = { kind:'native', job:pendingJob, run, documentId, identity, epoch }; - if (host.turnEpoch === epoch && (dispatched || stopped(error) || pendingJob !== undefined || signal?.aborted)) host.canvasWritesStopped = true; + if (host.turnEpoch === epoch && (dispatched && !terminal || stopped(error) || pendingJob !== undefined || signal?.aborted)) host.canvasWritesStopped = true; throw error; } finally { if (host.nativeToolOwner === owner) { host.nativeToolActive = false; host.nativeToolOwner = null; } } }), ...nativeToolMetadata('native_call')}, diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index 61c9fb69..53156dfc 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -1,12 +1,14 @@ import { Type } from '@sinclair/typebox'; import { ProductionRequestPending } from './production-recovery.mjs'; +import { loadSlots } from './whole-detail.mjs'; +import { productionKnowledge } from './production-knowledge.mjs'; const object = fields => Type.Object(fields, { additionalProperties: false }); const text = Type.String({ minLength: 1, maxLength: 6000 }); const slotIds = Type.Array(text, { minItems: 1, maxItems: 64, uniqueItems: true }); const page = Type.Integer({ minimum: 0 }); -export const productionObjective = '依据商品实拍、品牌和模板交付详情页、主图和 SKU。先用制作策划确定各屏卖点。每屏初稿写入画布后,工具按已经登记的图位证据分派首批配图,并带出下一批待写文案。有可执行的工作就推进,生图与验图由子代理并行。验图优先核对产品结构和品牌调性。退回后针对具体问题改变取景、来源或编辑方式。只有图文表述对不上时,优先保留可用图片,按实际画面修正对应文案。子代理中断时核查原请求,同时推进其他图位。复核图文就绪的实际画布,改过的屏重新复核。当前输出通过后交给客户端导出。单个图位达到三次生图仍不合格、或模板无法排版时,记录图位和具体原因,继续其余可做的内容。'; +export const productionObjective = '依据商品实拍、品牌、模板和适用 Skill 交付详情页、主图和 SKU。按需读取资料和画布。由你决定策划、图文安排、子代理并发、核验、返工及交付时机。读取状态不会启动任务。需要调用策划、分派、核验或导出时,使用对应的工具。生图结果未确认时只核查原请求编号。'; export function piGoalState(manager) { return manager.getBranch().findLast(entry => entry.type === 'custom' && entry.customType === 'pi-goal')?.data?.goal; @@ -46,7 +48,8 @@ export async function mayContinueProductionGoal(host, event) { } export const productionTools = [ - ['plan_production','读取当前输出的进度、策划及规则目录。文字格细节按分屏调用 read_copy_fields,候选详情按图位调用 review_image_slots。',object({})], + ['plan_production','只读查看本款资料、模板或当前输出的制作进度。',object({})], + ['start_production_strategy','需要策划协助时,调用产品和整页文案策划。',object({})], ['read_production_knowledge','按编号读策划返回的当前版本规则。',object({fileId:text,offset:Type.Optional(page)})], ['read_copy_fields','读取指定分屏或任一待处理分屏的文字格、图位和返修意见。',object({pageId:Type.Optional(text)})], ['write_copy_fields','将分屏初稿写入画布并登记配图依据。多个图位时用 links 分配分句证据。返修可附 reviseFrom。',object({ @@ -57,17 +60,56 @@ export const productionTools = [ links:Type.Optional(Type.Array(object({picture:text,claims:Type.Array(page,{minItems:1,maxItems:16,uniqueItems:true})}),{maxItems:16})), }),{minItems:1,maxItems:16}), })], - ['review_page_copy','复核已上画布且证据齐备的分屏文案并确认定稿,返回待修文字和待补证据。',object({})], + ['review_page_copy','只读查看现有文案复核记录。',object({})], + ['check_page_copy','发起一次图文复核并登记结果。',object({})], ['delegate_image_slots','将已明确画布文案与卖点证据的图位交给 Pi 子代理并发制作。没有关联文案的图位按本屏策划处理。retryInterrupted 只用于立即核查这些图位的原请求。',object({slotIds,goal:text,retryInterrupted:Type.Optional(Type.Boolean())})], - ['review_image_slots','查阅候选图文复核及回填结果。可填当前画布图位编号。详情候选返回即复核,可省略 slotIds 查看全部图位。需要立即核查中断候选的原请求时,指定 slotIds 并设 retryInterrupted 为 true。',object({slotIds:Type.Optional(slotIds),retryInterrupted:Type.Optional(Type.Boolean())})], + ['review_image_slots','只读查看候选、原请求和已记录的核验结果。',object({slotIds:Type.Optional(slotIds)})], + ['check_image_slots','明确要求验图时,按指定图位核验候选。retryInterrupted 用于核查原请求。',object({slotIds:Type.Optional(slotIds),retryInterrupted:Type.Optional(Type.Boolean())})], ['read_output_screen','查看图文已回填的一屏实际像素,page 从 0 起。像素未变时返回已有复核结论;有退回意见时先修改对应格。',object({page})], - ['review_output_screen','记录读过的本屏复核结论。issues 填具体图位或文字格编号与原因。',object({ + ['record_screen_check','记录你对已读屏幕的复核结论。issues 填具体图位或文字格编号与原因。',object({ page,revision:page,issues:Type.Array(object({field:text,reason:text}),{maxItems:32}), })], ['finish_production','提交当前已复核输出供客户端实际保存和导出。',object({})], ]; +async function readProduction(host, name, args, signal) { + const {canvas, productionGoal: {outputId}} = host; + switch (name) { + case 'read_production_knowledge': { + const knowledge = productionKnowledge(host.productionSkills?.knowledge ?? host.knowledgeContext); + return knowledge.tools[0] ? (await knowledge.tools[0].execute('', args, signal)).details : {files:[]}; + } + case 'read_copy_fields': { + const current = await canvas.detailCopyFields({includeFilled:true}); + const fields = current?.fields ?? current ?? []; + return {pages:current?.pages,fields:args.pageId ? fields.filter(field=>field.page===args.pageId) : fields}; + } + case 'review_page_copy': + return {findings:[]}; + case 'read_output_screen': { + const result = await canvas.detailRender({page:args.page}); + const {images, screenStamp, ...details} = result; + (host.productionScreenReads ??= new Map()).set(args.page, {...details,screenStamp}); + return {content:[{type:'text',text:JSON.stringify(details)},...(images??[])],details}; + } + default: { + const {plan,slots}=await loadSlots(canvas, outputId); + const ids=args.slotIds && new Set(args.slotIds); + const pictures=slots.filter(slot=>!ids||ids.has(slot.id)).map(({id,fieldId:field,label,candidates,selectedCandidateId,productionRule})=> + ({id,field,label,candidates,selectedCandidateId,productionRule})); + return {outputId,pictures,...(name==='plan_production'?{ + template:plan.template,product:plan.productEvidence?.brief,facts:plan.productEvidence?.facts, + knowledgeFiles:productionKnowledge(host.productionSkills?.knowledge ?? host.knowledgeContext).files, + }:null)}; + } + } +} + +const readOnlyTools = new Set(['plan_production','read_production_knowledge','read_copy_fields', + 'review_page_copy','review_image_slots','read_output_screen']); + export async function callProductionTool(host, name, args, signal) { + if (!host.productionTurn && readOnlyTools.has(name)) return readProduction(host,name,args,signal); if (host.goalStageResult?.production?.complete) { if (name === 'finish_production') return {complete:true}; throw Error('当前输出已提交导出'); @@ -81,7 +123,7 @@ export async function callProductionTool(host, name, args, signal) { return host.executeWholeDetail(host.productionGoal.outputId, true, pending, signal, actions => { ready.resolve(actions); return close.promise; - }); + }, {planStrategy:name==='start_production_strategy'}); })(); turn.done.catch(error => { if (error instanceof ProductionRequestPending) { diff --git a/apps/detail-agent-pi/src/project-context.mjs b/apps/detail-agent-pi/src/project-context.mjs index 6e66763f..9aa373a6 100644 --- a/apps/detail-agent-pi/src/project-context.mjs +++ b/apps/detail-agent-pi/src/project-context.mjs @@ -1,19 +1,18 @@ import { digest } from './store.mjs'; -const clip=(value,max)=>Array.from(typeof value==='string'?value:'').slice(0,max).join(''); -const list=(value,max)=>Array.isArray(value)?value.slice(0,max):[]; -const safeText=(value,max)=>typeof value==='string'&&!/(?:https?:\/\/|data:|[\\/]|[a-z]:)/i.test(value)?clip(value,max):''; +const text=value=>typeof value==="string"?value:""; +const list=value=>Array.isArray(value)?value:[]; +const safeText=value=>typeof value==='string'&&!/(?:https?:\/\/|data:|[\\/]|[a-z]:)/i.test(value)?value:''; const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,128}$/i.test(value)?value:undefined; -const count=value=>Number.isSafeInteger(value)&&value>0?Math.min(value,100000):0; const outputColors=value=>Object.fromEntries(['detail','sku_images','main_images'].flatMap(key=>{ - const raw=value?.[key], color=safeText(raw,120); + const raw=value?.[key], color=safeText(raw); return color||raw===''?[[key,color]]:[]; })); -const images=(value,variantId)=>list(value,8).filter(image=>image&&typeof image==='object').map(image=>({ +const images=(value,variantId)=>list(value).filter(image=>image&&typeof image==='object').map(image=>({ ...(typeof image.ref==='string'&&/^sha256:[a-f0-9]{64}$/.test(image.ref)?{ref:image.ref}:{}), ...(['product','scene'].includes(image.purpose)?{purpose:image.purpose}:{}), - ...(safeText(image.name,100)?{name:safeText(image.name,100)}:{}), - ...(safeText(image.description,200)?{description:safeText(image.description,200)}:{}), + ...(safeText(image.name)?{name:safeText(image.name)}:{}), + ...(safeText(image.description)?{description:safeText(image.description)}:{}), ...(!(typeof image.ref==='string'&&/^sha256:[a-f0-9]{64}$/.test(image.ref))?{missing:['参考图稳定身份未提供']}:{}), scope:variantId?'variant':'common',...(variantId?{variantId}:{}), })); @@ -26,43 +25,34 @@ export function productContext(value,identity){ const brief=value.brief||{},facts=value.facts||{},selling=value.sellingPoints||{},plan=value.plan||{}; const skuPlan=brief.outputVariantIds&&typeof brief.outputVariantIds==='object'&&!Array.isArray(brief.outputVariantIds); const rawVariants=Array.isArray(brief.variants)?brief.variants:[]; - const variants=list(rawVariants,64).filter(v=>v&&safeId(v.id)).map(v=>({id:v.id, - ...(safeText(v.name,100)?{name:safeText(v.name,100)}:{}), - ...(safeText(v.colorName,100)?{colorName:safeText(v.colorName,100)}:{}), + const variants=list(rawVariants).filter(v=>v&&safeId(v.id)).map(v=>({id:v.id, + ...(safeText(v.name)?{name:safeText(v.name)}:{}), + ...(safeText(v.colorName)?{colorName:safeText(v.colorName)}:{}), ...(!skuPlan&&v.outputColors?{outputColors:outputColors(v.outputColors)}:{}), ...(safeId(v.colorMaterialId)?{colorMaterialId:v.colorMaterialId}:{}), images:images(v.images,v.id),...(Array.isArray(v.images)?{}:{missing:['花色参考图资料未提供']})})); const commonImages=images(brief.images); const selected=[]; - for(const key of list(selling.selected,20)){ + for(const key of list(selling.selected)){ if(typeof key!=='string')continue; - const split=key.lastIndexOf(':'),batch=list(selling.batches,12).find(b=>b.id===key.slice(0,split)); + const split=key.lastIndexOf(':'),batch=list(selling.batches).find(b=>b.id===key.slice(0,split)); const index=Number(key.slice(split+1)); - if(split>0&&Number.isInteger(index)&&index>=0&&typeof batch?.items?.[index]==='string')selected.push(clip(batch.items[index],200)); + if(split>0&&Number.isInteger(index)&&index>=0&&typeof batch?.items?.[index]==='string')selected.push(text(batch.items[index])); } const result={state:'ready',authority:'当前项目只读资料;品牌规范不是产品事实,模型提取仍需保留其来源与待确认项。',documentId:value.documentId,revision:value.revision, - product:Object.fromEntries(['name','brandId','brandName','categoryId','categoryName','identifierType','identifier','variant','colorName'].map(key=>[key,clip(brief[key],160)])), - dimensions:Object.fromEntries(['length','width','height','unit'].map(key=>[key,clip(brief.dimensions?.[key],24)])),note:clip(brief.note,1000), + product:Object.fromEntries(['name','brandId','brandName','categoryId','categoryName','identifierType','identifier','variant','colorName'].map(key=>[key,text(brief[key])])), + dimensions:Object.fromEntries(['length','width','height','unit'].map(key=>[key,text(brief.dimensions?.[key])])),note:text(brief.note), references:{source:'当前项目产品资料;图片内容和路径未提供,不能据此推断外观。', variants,commonImages,...(safeId(value.currentVariantId)&&variants.some(v=>v.id===value.currentVariantId)?{currentVariantId:value.currentVariantId}:{}), missing:[...(!Array.isArray(brief.variants)?['花色资料未提供']:[]),...(!Array.isArray(brief.images)?['共用参考图资料未提供']:[])]}, - factsStatus:clip(facts.status,24),facts:list(facts.items,24).map(f=>({text:clip(f.text,260),source:clip(f.source,100)})), - missing:list(facts.missing,20).map(v=>clip(v,220)),selectedSellingPoints:selling.stale?[]:selected, - plan:{status:clip(plan.status,24),screens:list(plan.screens,12).map(s=>({name:clip(s.name||s.title,100),body:clip(s.body,200)}))}}; + factsStatus:text(facts.status),facts:list(facts.items).map(f=>({text:text(f.text),source:text(f.source)})), + missing:list(facts.missing).map(v=>text(v)),selectedSellingPoints:selling.stale?[]:selected, + plan:{status:text(plan.status),screens:list(plan.screens).map(s=>({name:text(s.name||s.title),body:text(s.body)}))}}; if(skuPlan)result.references.outputVariantIds=Object.fromEntries(['detail','main_images'].flatMap(key=>{ - const ids=list(brief.outputVariantIds[key],64).map(safeId).filter(Boolean); + const ids=list(brief.outputVariantIds[key]).map(safeId).filter(Boolean); return ids.length?[[key,ids]]:[]; })); else if(brief.outputColors)result.product.outputColors=outputColors(brief.outputColors); - // Fixed transport budget; omission is explicit rather than silent evidence invention. - while(JSON.stringify(result).length>13600&&result.facts.length)result.facts.pop(); - while(JSON.stringify(result).length>13600&&result.missing.length)result.missing.pop(); - while(JSON.stringify(result).length>13600&&result.references.variants.some(v=>v.images.length))result.references.variants.findLast(v=>v.images.length).images.pop(); - while(JSON.stringify(result).length>13600&&result.references.commonImages.length)result.references.commonImages.pop(); - while(JSON.stringify(result).length>13600&&result.references.variants.length)result.references.variants.pop(); - if(result.references.currentVariantId&&!result.references.variants.some(v=>v.id===result.references.currentVariantId))delete result.references.currentVariantId; - const totalVariantImages=rawVariants.reduce((sum,v)=>sum+(Array.isArray(v?.images)?v.images.length:0)+count(v?.imagesOmitted),0); - result.omitted={facts:Math.max(0,(facts.items?.length||0)-result.facts.length),missing:Math.max(0,(facts.missing?.length||0)-result.missing.length),planScreens:Math.max(0,(plan.screens?.length||0)-result.plan.screens.length),variants:rawVariants.length-result.references.variants.length+count(brief.projectionOmitted?.variants),commonImages:Math.max(0,(brief.images?.length||0)-result.references.commonImages.length)+count(brief.projectionOmitted?.commonImages),variantImages:totalVariantImages-result.references.variants.reduce((sum,v)=>sum+v.images.length,0)}; result.contentHash=digest(result); return result; } diff --git a/apps/detail-agent-pi/src/project-shell.mjs b/apps/detail-agent-pi/src/project-shell.mjs new file mode 100644 index 00000000..e39fca2b --- /dev/null +++ b/apps/detail-agent-pi/src/project-shell.mjs @@ -0,0 +1,59 @@ +import { execFile, spawn } from 'node:child_process'; +import { promisify } from 'node:util'; + +const docker = promisify(execFile); +const endpoint = process.platform === 'win32' + ? 'npipe:////./pipe/dockerDesktopLinuxEngine' + : 'unix:///var/run/docker.sock'; +const image = 'docker.io/library/bash:5.2'; +const dockerOptions = { windowsHide: true }; + +export function projectShell(root, store) { + return { + async exec(command, _cwd, { onData, signal, timeout }) { + signal?.throwIfAborted(); + const run = (args) => docker('docker', ['--host', endpoint, ...args], dockerOptions); + let container; + try { + const {stdout} = await run([ + 'create', '--pull=never', '--network=none', '--read-only', '--cap-drop=ALL', + '--security-opt=no-new-privileges', '--tmpfs', '/tmp', + '--mount', `type=bind,source=${root},target=/workspace`, + '--workdir', '/workspace', '--entrypoint', '/usr/local/bin/bash', image, '-lc', command, + ]); + container = stdout.trim(); + } catch (error) { + await store.appendEvent({type: 'project_shell_blocked', reason: 'local-sandbox-unavailable'}); + const detail = error.stderr?.trim(); + throw Error(`项目终端需要运行中的本地 Docker 及 ${image} 镜像${detail ? '。'+detail : ''}`); + } + let cleanup; + const remove = () => cleanup ??= run(['rm', '--force', container]); + let timer; + let timedOut = false; + const stop = () => { void remove().catch(() => {}); }; + try { + signal?.throwIfAborted(); + await store.appendEvent({type: 'project_shell_started', sandbox: image}); + signal?.throwIfAborted(); + const exitCode = await new Promise((resolve, reject) => { + const child = spawn('docker', ['--host', endpoint, 'start', '-a', container], dockerOptions); + child.stdout.on('data', onData); + child.stderr.on('data', onData); + child.once('error', reject); + child.once('close', resolve); + signal?.addEventListener('abort', stop, {once: true}); + if (timeout > 0) timer = setTimeout(() => { timedOut = true; stop(); }, timeout * 1000); + }); + await store.appendEvent({type: 'project_shell_finished', exitCode, cancelled: signal?.aborted === true, timedOut}); + signal?.throwIfAborted(); + if (timedOut) throw Error('项目终端已达到本次工具调用的时限'); + return {exitCode}; + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', stop); + await remove(); + } + }, + }; +} diff --git a/apps/detail-agent-pi/src/project-tools.mjs b/apps/detail-agent-pi/src/project-tools.mjs index 623e8a66..c3272411 100644 --- a/apps/detail-agent-pi/src/project-tools.mjs +++ b/apps/detail-agent-pi/src/project-tools.mjs @@ -1,6 +1,7 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import {createReadTool,createWriteTool,createEditTool,createLsTool,createFindTool,createGrepTool,createBashTool} from '@earendil-works/pi-coding-agent'; +import {projectShell} from './project-shell.mjs'; export async function projectTools(host) { const cwd = path.join(host.store.dir,'workspace'); @@ -59,9 +60,6 @@ export async function projectTools(host) { return matches; }}}), createGrepTool(cwd,{operations:{isDirectory:async file=>(await stat(file)).isDirectory()}}), - {...createBashTool(cwd,{operations:{exec:async ()=>{ - await host.store.appendEvent({type:'project_shell_blocked',reason:'filesystem-sandbox-unavailable'}); - throw Error('本机尚未提供项目专用文件系统沙箱。可使用 Pi 文件工具或 PhotoCraft 命令。'); - }}}),defaultActive:false}, + createBashTool(cwd,{operations:projectShell(root,host.store),exposeSessionEnvironment:false}), ]}; } diff --git a/apps/detail-agent-pi/src/whole-detail.mjs b/apps/detail-agent-pi/src/whole-detail.mjs index 3069d0fb..d7f4a3d5 100644 --- a/apps/detail-agent-pi/src/whole-detail.mjs +++ b/apps/detail-agent-pi/src/whole-detail.mjs @@ -132,7 +132,7 @@ function ordered() { }; } -async function loadSlots(canvas, outputId) { +export async function loadSlots(canvas, outputId) { const slots=[]; let plan; while(!plan || slots.lengthentry.name==='write_copy_fields'); - const reads=new Map(), reviewed=new Map((journal.screenReviews??[]).map(([page,receipt])=>[page,{...receipt,revision:null}])); + const reads=host.productionScreenReads??new Map(), reviewed=new Map((journal.screenReviews??[]).map(([page,receipt])=>[page,{...receipt,revision:null}])); const screenFeedback=new Map(journal.screenFeedback??[]); let screenCount=journal.screenCount; const related=slot=>fieldCopy(slot).map(({field,text})=>({field,text})); @@ -2662,23 +2662,6 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay }; const eligible=slot=>!delegated.has(slot.id)&&(!written.has(slot.id)||needsAdoptedReview(slot)) && !['manual','missing'].includes(journal.items[slot.id]?.state); - const dispatchDraftScreens=async()=>{ - if(!screenCopyMode||!pageOutline)return []; - const pendingPages=new Set((await unstaged()).map(field=>field.page)); - const writtenFields=new Set([...drafts.values()] - .filter(row=>draftCanvasText.get(row.layer)===row.text).map(row=>row.field)); - const readyPages=new Set(pages.filter(screen=>!pendingPages.has(screen.page)&& - screen.fields.some(field=>writtenFields.has(field.field))).map(screen=>screen.page)); - const proofs=new Set(pageOutline.screens.filter(screen=>readyPages.has(screen.page)) - .flatMap(screen=>screen.proofs.map(proof=>proof.picture))); - const ready=slots.filter(slot=>proofs.has(slot.fieldId)&&eligible(slot)&& - !journal.items[slot.id]&&!selectedId(slot)); - if(ready.length){ - enqueue(ready,'按本屏已写入的初稿和策划证据制作配图',signal); - await progress(); - } - return ready.map(({id,fieldId})=>({id,field:fieldId})); - }; const checkedModelOriginals=new Set(); const interruptedWorkers=new Map(); const checkHeldModels=async(selected,signal,retryInterrupted=false)=>{ @@ -2820,23 +2803,18 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay }; const actions={ async goalProgress(previous){ - await checkHeldModels(null,signal); - enqueueExistingReviews(null,signal); const checkpoint=previous===undefined?null:JSON.stringify(previous); for(;;){ signal?.throwIfAborted(); const activity=candidateProgress.promise; const state=await progressState(); - if(verifiedProduction)pumpReviews(); const ready=checkpoint===null?state.canAdvance:JSON.stringify(state)!==checkpoint; if(ready||!runningWorkers.size&&!runningReviews.size)return {state}; await activity; } }, - async plan_production(){ + async start_production_strategy(){ await preflight(); - await checkHeldModels(null,signal); - enqueueExistingReviews(null,signal); if(pageCopyMode&&!pageOutline&&!outlinePending){ try { await loadPageOutline(); } catch(error){ @@ -2844,13 +2822,13 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay outlinePending=error; } } - const assigned=await dispatchDraftScreens(); const current=await status({includeCopy:false}); - return {...current,...(assigned.length?{assigned}:null), + return {...current, ...(blockedCopy.size||renderIssues.size?{templateIssues:[...blockedCopy.values(),...renderIssues.values()]}:null), product:plan.productEvidence?.brief,facts:plan.productEvidence?.facts, strategy,outline:pageOutline,outlineOriginal:outlinePending?.id,brandCopy,guidance:copyGuidance,knowledgeFiles:rules.files,screenCopyMode}; }, + async plan_production(){return status({includeCopy:false});}, async read_production_knowledge(args,signal){ if(!rules.tools[0])throw Error('当前模板没有可读取的制作规范'); return (await rules.tools[0].execute('',args,signal)).details; @@ -2860,12 +2838,12 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay if(!writeCopy)throw Error('当前画布没有可写入的文字格'); const fieldByLayer=new Map((await copyFields()).map(field=>[field.layer,field.field])); const result=(await writeCopy.execute('',args,signal)).details; - const assigned=result.onCanvas>0?await dispatchDraftScreens():[]; - const next=screenCopyMode&&result.onCanvas>0?await copyStatus():null; - return {...result,rejected:result.rejected?.map(row=>({...row,field:fieldByLayer.get(row.layer)})), - ...(assigned.length?{assigned}:null),...(next?.fields.length?{nextScreen:next}:null)}; + return {...result,rejected:result.rejected?.map(row=>({...row,field:fieldByLayer.get(row.layer)}))}; }, - async review_page_copy(_args,signal){ + async review_page_copy(){ + return {findings:pageReviewFindings??[]}; + }, + async check_page_copy(_args,signal){ const available=new Map((await copyFields?.()??[]).map(field=>[field.layer,field])); if(!pageCopyMode||!available.size)return {pending:available.size}; const missingDrafts=[...available.values()].filter(field=>!drafts.has(field.layer)); @@ -2876,9 +2854,6 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay for(const id of missing)awaitingPictures.add(id); return !missing.length; })); - if(screenCopyMode&&awaitingPictures.size){ - enqueueExistingReviews(new Set(slots.filter(slot=>awaitingPictures.has(slot.fieldId)).map(slot=>slot.id)),signal); - } const waiting={...copyBatch(missingDrafts),awaitingPictures:[...awaitingPictures]}; if(!ready.size||copyPending)return {...waiting,pending:available.size,pendingOriginal:copyPending?.id}; let revisions; @@ -2968,7 +2943,11 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay ({id,field,state,reason:reason??review?.reason,pendingOriginal,interruptedWorker})):undefined; return {assigned,...(rejected.length?{rejected}:null),...(blocked?{blocked}:null)}; }, - async review_image_slots({slotIds,retryInterrupted=false},signal){ + async review_image_slots({slotIds}){ + const selected=slotIds?new Set(select(slotIds).map(slot=>slot.id)):null; + return {active:delegated.size,...await status({includeCopy:false,selected})}; + }, + async check_image_slots({slotIds,retryInterrupted=false},signal){ if(retryInterrupted&&!slotIds?.length)throw Error('请指出需要重试的图位'); const selected=slotIds?new Set(select(slotIds).map(slot=>slot.id)):null; await recoverHeldImages(selected,signal); @@ -3015,7 +2994,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay reads.set(page,{...details,screenStamp:result.screenStamp}); return {content:[{type:'text',text:JSON.stringify(details)},...result.images],details}; }, - async review_output_screen({page,revision,issues}){ + async record_screen_check({page,revision,issues}){ const shown=reads.get(page); const live=(await canvas.read()).revision; if(shown?.revision!==revision||!await screenMatches(page,shown,live))throw Error('本屏已更新,请重新读取本屏'); diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index 12cc64d9..3764f1d0 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -247,11 +247,13 @@ test('a canvas click during discussion blocks writes but does not cut off a read }finally{await x.close();} }); -test('compact product evidence is bounded, omits visual prompts and rejects foreign identity',()=>{ +test('product evidence preserves complete facts and screens and rejects foreign identity',()=>{ const project=randomUUID(),source=evidence(project); source.facts.items=Array.from({length:100},()=>({text:'事实'.repeat(500),source:'来源'.repeat(500)}));source.facts.missing=Array.from({length:100},()=> '待确认'.repeat(500)); const context=productContext(source,{scope,project,documentId:7}); - assert.ok(JSON.stringify(context).length<=14000);assert.ok(context.omitted.facts>0);assert.ok(context.omitted.missing>0); + assert.equal(context.facts.length,100); + assert.equal(context.missing.length,100); + assert.equal(context.facts.at(-1).text,source.facts.items.at(-1).text); assert.ok(!JSON.stringify(context).includes('imagePrompt')); for(const identity of [{scope:'7'.repeat(64),project,documentId:7},{scope,project:randomUUID(),documentId:7},{scope,project,documentId:8}])assert.throws(()=>productContext(source,identity),/不属于/); }); diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 0f918125..8df85cb8 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -19,6 +19,8 @@ import { Native98kBroker } from '../src/native-bridge.mjs'; import { StdioCanvas } from '../src/stdio-canvas.mjs'; import { projectTools } from '../src/project-tools.mjs'; import { parseReceipt } from '../src/receipt.mjs'; +import { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs'; +import { callProductionTool } from '../src/production-goal.mjs'; test('native request validation can prove that no model was dispatched', async t => { const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-')); @@ -173,7 +175,7 @@ async function setup(reply, finish = async valid => { assert.equal(valid, true); const requests = []; const ids = []; const retries = []; - const broker = { info: async () => ({ accountScope: scope, model: recovery?.model ?? { id: 'qa', protocol: 'openai-chat' }, pending: [] }), round({retryOf}={}) { + const broker = { info: async () => ({ accountScope: scope, model: recovery?.model ?? { id: 'qa', protocol: 'openai-chat' }, thinkingLevel: recovery?.thinkingLevel, pending: [] }), round({retryOf}={}) { if(retryOf) retries.push(retryOf); const id=randomUUID(); return { id, fetch: async (_url, init) => { @@ -188,7 +190,7 @@ async function setup(reply, finish = async valid => { assert.equal(valid, true); status:async()=>({pending:[]}),isUnconfirmed:()=>Boolean(recovery.read),read:recovery.read,recover:recovery.recover}); const host = await DetailPiAgent.open({ store, broker, callBudget: production?.callBudget??3, canvas, productionGoal }); if(production)host.executeWholeDetail=async(_output,_production,_pending,_signal,drive)=> - drive({plan_production:args=>production.plan?.(args)??{pendingText:0}, + drive({start_production_strategy:args=>production.plan?.(args)??{pendingText:0}, goalProgress:production.progress,finish_production:async()=>({status:{complete:true}, stage:{text:'已核对导出。',production:{...productionGoal,complete:true}}})}); return { host, store, requests, ids, retries, close: async () => { await host.dispose(); await cleanup(dir); } }; @@ -208,7 +210,7 @@ test('ordinary chat resumes the same turn through Pi after a confirmed rate limi }); test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{ - const plan=n=>sse({tool_calls:[{index:0,id:'plan-'+n,type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls'); + const plan=n=>sse({tool_calls:[{index:0,id:'plan-'+n,type:'function',function:{name:'start_production_strategy',arguments:'{}'}}]},'tool_calls'); let plans=0; const x=await setup((_,n)=>{ if(n===1||n===3)return plan(n); @@ -234,7 +236,7 @@ test('a managed inference interruption retries without executing its partial too let plans=0; const lookedUp=[]; const call={tool_calls:[{index:0,id:'plan',type:'function', - function:{name:'plan_production',arguments:'{}'}}]}; + function:{name:'start_production_strategy',arguments:'{}'}}]}; const x=await setup((_,n)=>n===1?sse(call,null).replace('data: [DONE]','') :n===2?sse(call,'tool_calls'):sse({content:'已接续制作。'},'stop'), async valid=>valid?{phase:'complete'}:{phase:'unknown'},{ @@ -269,16 +271,18 @@ test('actual native Pi wire sends function schemas, executes typed call and acce } finally { await x.close(); } }); -test('native Pi preserves a required named tool on a string-only Responses route', async () => { +test('native Pi preserves a required named tool across a retry on a string-only Responses route', async () => { const args = JSON.stringify({key:'color',value:'米色',evidence:'布面颜色是米色'}); const call = {type:'function_call',id:'fc_required',call_id:'call_required',status:'completed',name:'memory_set',arguments:args}; const text = {type:'message',id:'msg_required',role:'assistant',status:'completed', content:[{type:'output_text',text:'已记录米色。',annotations:[]}]}; const event = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({type,...fields}) + '\n\n'; const complete = item => event('response.completed',{response:{model:'qa',status:'completed',output:[item]}}); - const fixture = {model:{id:'qa',protocol:'openai-responses',supportsImageInput:true,requireSingleTool:true, + const fixture = {thinkingLevel:'low',model:{id:'qa',protocol:'openai-responses',supportsImageInput:true,requireSingleTool:true, reasoning:true,reasoningEfforts:['low','medium','high'],requiresOutputLimit:false,maxTokens:128_000}}; const x = await setup((_payload, round) => round === 1 + ? event('response.created',{response:{id:'resp_lost',status:'in_progress'}}) + : round === 2 ? event('response.output_item.added',{output_index:0,item:{...call,arguments:'',status:'in_progress'}}) + event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(0,12)}) + event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(12)}) @@ -286,9 +290,11 @@ test('native Pi preserves a required named tool on a string-only Responses route : event('response.output_item.added',{output_index:0,item:{...text,content:[],status:'in_progress'}}) + event('response.content_part.added',{output_index:0,content_index:0,part:{...text.content[0],text:''}}) + event('response.output_text.delta',{output_index:0,content_index:0,delta:text.content[0].text}) - + event('response.output_item.done',{output_index:0,item:text}) + complete(text), undefined, undefined, fixture); + + event('response.output_item.done',{output_index:0,item:text}) + complete(text), + async valid => ({phase:valid?'complete':'unknown'}), undefined, fixture); const reference = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAgACADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAYH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AkgIpngAAAAAD/9k='; try { + assert.equal(x.host.session.thinkingLevel,'low'); assert.equal((await x.host.prompt('/thinking high')).rounds,0); assert.equal(x.host.session.thinkingLevel,'high'); await x.host.prompt('布面颜色是米色,请记住。', {requiredTool:'memory_set',referenceContent:[{label:'产品原图',image:reference}]}); @@ -296,10 +302,13 @@ test('native Pi preserves a required named tool on a string-only Responses route assert.equal(x.requests[0].reasoning.effort,'high'); assert.equal(x.requests[0].max_output_tokens,undefined); assert.deepEqual(x.requests[0].tools.map(tool=>tool.name),['memory_set']); + assert.equal(x.requests[1].tool_choice,'required'); + assert.deepEqual(x.requests[1].tools.map(tool=>tool.name),['memory_set']); + assert.notEqual(x.ids[0], x.ids[1]); const parts = x.requests[0].input.flatMap(item=>Array.isArray(item.content)?item.content:[]); assert.match(parts.find(part=>part.type==='input_image')?.image_url ?? '', /^data:image\/(?:jpeg|png);base64,/); assert.equal((await x.store.context()).confirmedMemory.color.value,'米色'); - assert.equal(x.requests[1].tool_choice,undefined); + assert.equal(x.requests[2].tool_choice,undefined); } finally { await x.close(); } }); @@ -446,7 +455,7 @@ test('the model receives prior images and original tool receipts through Pi', as } finally {await x.close();} }); -test('Pi project tools share the same file boundary and log blocked shell execution',async()=>{ +test('Pi project tools share the same file boundary',async()=>{ const x=await setup(()=>sse({content:'已核对。'},'stop')); try { const {cwd,tools}=await projectTools(x.host); @@ -457,8 +466,7 @@ test('Pi project tools share the same file boundary and log blocked shell execut assert.ok((await fs.readFile(path.join(cwd,'notes.md'),'utf8')).includes('品牌')); await assert.rejects(tool('write').execute('3',{path:'../outside.txt',content:'无'}),/工作目录之外/); await assert.rejects(tool('read').execute('4',{path:'../session.json'}),/工作目录之外/); - await assert.rejects(tool('bash').execute('5',{command:'pwd'}),/项目专用文件系统沙箱/); - assert.match(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8'),/project_shell_blocked/); + assert.ok(tool('bash')); } finally {await x.close();} }); @@ -480,7 +488,7 @@ test('a canvas can complete more than 20 edits and cancellation stops waiting',a test('production exposes direct native tools and Pi file tools',async()=>{ const x=await setup(payload=>{ const names=payload.tools.map(row=>row.function.name); - for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read','write','edit','ls','find','grep']){ + for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read','write','edit','ls','find','grep','bash']){ assert.ok(names.includes(name),name); } return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{}'}}]},'tool_calls'); @@ -495,3 +503,91 @@ test('production exposes direct native tools and Pi file tools',async()=>{ assert.equal(x.requests.length,1); } finally {await x.close();} }); + +test('a rejected native text edit can be corrected in the same production turn', async () => { + let edits = 0; + const x = await setup((_, request) => { + const name = request <= 2 ? 'native_call' : 'finish_production'; + const args = request <= 2 + ? {revision: 1, method: 'engine.execute', params: {command: 'type.edit', params: { + layer: 2, text: request === 1 ? 'A title that cannot fit' : 'New', expectedText: 'Old', + }}} + : {}; + return sse({tool_calls: [{index: 0, id: `tool-${request}`, type: 'function', + function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls'); + }, undefined, { + progress: () => ({state: {waitingOnOriginals: true}}), + canvas: { + nativeCatalog() {}, nativeReconcile() {}, + requestWrite: async revision => ({allowed: true, revision}), + nativeCall: async () => ++edits === 1 + ? {completed: true, executed: false, error: '请缩短文案'} + : {completed: true, executed: true, revision: 2}, + }, + }); + try { + assert.equal((await x.host.prompt('完成制作')).production.complete, true); + assert.equal(edits, 2); + assert.equal(x.host.nativeUnresolved, undefined); + } finally { await x.close(); } +}); + +test('production native queries follow the catalog without requesting a canvas write lease', async () => { + let read = 0; + const x = await setup((_, request) => { + const name = request === 1 ? 'native_call' : 'finish_production'; + const args = request === 1 + ? {revision: 1, method: 'engine.execute', params: {command: 'document.inspect', params: {}}} + : {}; + return sse({tool_calls: [{index: 0, id: `native-${request}`, type: 'function', + function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls'); + }, undefined, { + progress: () => ({state: {waitingOnOriginals: true}}), + canvas: { + nativeCatalog: async ({id}) => ({items: [{id, requiresRevisionLease: false}]}), + requestWrite() { assert.fail('read-only operation requested a write lease'); }, + nativeCall: async () => { read++; return {completed: true, executed: true}; }, + }, + }); + try { + assert.equal((await x.host.prompt('核对当前画布')).production.complete, true); + assert.equal(read, 1); + } finally { await x.close(); } +}); + +test('reading a fresh production goal never starts the strategy, image workers, or canvas writes', async () => { + const host = { + productionGoal: {outputId:'detail',variantId:'walnut'}, + executeWholeDetail() {assert.fail('a read started production');}, + canvas: { + workflowRead: async () => ({available:true,canvasFirst:true,outputId:'detail',productVariantId:'walnut', + template:{contentHash:'desk-version'},totalSlots:1,slots:[{id:'desk',fieldId:'cover',label:'主视觉',candidates:[]}]}), + detailCopyFields: async () => ({fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}]}), + detailRender: async () => ({page:0,revision:3,images:[]}), + }, + }; + assert.equal((await callProductionTool(host,'plan_production',{})).pictures.length,1); + assert.equal((await callProductionTool(host,'review_image_slots',{slotIds:['desk']})).pictures[0].id,'desk'); + assert.deepEqual((await callProductionTool(host,'read_copy_fields',{pageId:'specs'})).fields,[{layer:9,page:'specs'}]); + assert.deepEqual(await callProductionTool(host,'review_page_copy',{}),{findings:[]}); + assert.equal((await callProductionTool(host,'read_output_screen',{page:0})).details.revision,3); + assert.equal(host.productionTurn,undefined); +}); + +test('production loads the project’s native skill and prompt template', async t => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-project-resources-')); + t.after(() => cleanup(dir)); + const cwd = path.join(dir, 'workspace'); + const skillDir = path.join(cwd, '.pi', 'skills', 'desk-copy'); + const promptDir = path.join(cwd, '.pi', 'prompts'); + await fs.mkdir(skillDir, {recursive: true}); + await fs.mkdir(promptDir, {recursive: true}); + await fs.writeFile(path.join(skillDir, 'SKILL.md'), + '---\nname: desk-copy\ndescription: Write usable desk copy.\n---\nShow the available work surface.'); + await fs.writeFile(path.join(promptDir, 'fixture-copy.md'), + '---\ndescription: Write a fixture headline.\n---\nDescribe the work surface.'); + const {resourceLoader} = await createPhotoCraftExtensions({workingDirectory: cwd, store: {dir}}, [], {includeGoal: true}); + assert.ok(resourceLoader.getSkills().skills.some(skill => skill.name === 'desk-copy')); + assert.equal(resourceLoader.getPrompts().prompts.find(prompt => prompt.name === 'fixture-copy')?.content, + 'Describe the work surface.'); +}); diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 50d036ac..d417dc4e 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -52,7 +52,7 @@ test('Pi production and its worker read the same locked Skill and its relative r ['read',{path:path.join(path.dirname(location),'references','finish.md')}], ]:[ ['read',{path:location}], - ['plan_production',{}], + ['start_production_strategy',{}], ['finish_production',{}], ]; for(const result of context.messages.filter(message=>message.role==='toolResult'&&message.toolName==='read')){ @@ -67,7 +67,7 @@ test('Pi production and its worker read the same locked Skill and its relative r let loads=0; host.enterpriseContext={load:async()=>{loads++;return knowledge;}}; host.executeWholeDetail=async (_output,_production,_pending,_signal,drive)=>drive({ - async plan_production(){ + async start_production_strategy(){ await host.runDetailAgent('lighting-slot','worker-fixture','制作局部细节图',[]); return {planned:true}; }, @@ -140,7 +140,7 @@ test('production tools share one Pi transcript and only finish after the export assert.deepEqual(pending,[]); assert.equal(signal.aborted,false); return drive({ - async plan_production(){return {outputId:actual,pendingText:3};}, + async start_production_strategy(){return {outputId:actual,pendingText:3};}, async goalProgress(){return {state:{copyWrites}};}, async write_copy_fields(){return {written:++copyWrites};}, async finish_production(){ @@ -162,7 +162,7 @@ test('production tools share one Pi transcript and only finish after the export const next=await makeHost('main_images'); try { const copy=layer=>['write_copy_fields',{items:[{layer,text:'商品文案',sources:['P01'],pictures:[]}]}]; - steps.push(['plan_production'],['plan_production'],null,null,null,copy(1),['finish_production'],copy(2),copy(3),['finish_production']); + steps.push(['start_production_strategy'],['start_production_strategy'],null,null,null,copy(1),['finish_production'],copy(2),copy(3),['finish_production']); const result=await next.prompt('制作主图',{goalContinuation:true}); assert.equal(result.production.outputId,'main_images'); assert.equal(result.production.canvasRevision,7); @@ -170,7 +170,7 @@ test('production tools share one Pi transcript and only finish after the export assert.equal(result.production.piGoalId,savedGoal); assert.equal(preparations,2); assert.equal(copyWrites,3); - assert.deepEqual(publicActivity.filter(row=>row.toolName==='plan_production').map(row=>row.status), + assert.deepEqual(publicActivity.filter(row=>row.toolName==='start_production_strategy').map(row=>row.status), ['started','failed','started','completed']); assert.ok(publicActivity.every(row=>row.scope.documentId===canvas.documentId&&row.scope.run===canvas.run)); const entries=next.manager.getEntries(); @@ -188,7 +188,7 @@ test('production tools share one Pi transcript and only finish after the export await settleProductionGoal(store.dir,savedGoal); const chat=await DetailPiAgent.open({store,canvas,transport}); try{ - assert.equal(chat.session.getToolDefinition('plan_production'),undefined); + assert.equal(chat.session.getToolDefinition('start_production_strategy'),undefined); const entries=chat.manager.getEntries(); assert.equal(entries.findLast(e=>e.type==='custom'&&e.customType==='pi-goal').data.goal.status,'complete'); } @@ -241,7 +241,7 @@ test('actual Pi SDK executes memory tools, persists full transcript and reinject } }; let host = await DetailPiAgent.open({ store, transport }); assert.deepEqual(host.session.getActiveToolNames().sort(), - ['codemode','context_read','edit','find','grep','ls','memory_search','memory_set','read','tool_search','write']); + ['bash','codemode','context_read','edit','find','grep','ls','memory_search','memory_set','read','tool_search','write']); await host.prompt('这个测试产品颜色是胡桃色,请记住。'); const messages = host.session.messages.length, entries = host.manager.getEntryCount(); await host.dispose(); diff --git a/apps/detail-agent-pi/test/whole-detail.test.mjs b/apps/detail-agent-pi/test/whole-detail.test.mjs index 5334683e..225908a8 100644 --- a/apps/detail-agent-pi/test/whole-detail.test.mjs +++ b/apps/detail-agent-pi/test/whole-detail.test.mjs @@ -341,18 +341,18 @@ test('the Pi production tools run four concurrent image jobs and preserve an unk },async()=>({skills:[],rules:[]}),{ production:true,outputId:'main_images',prepareStrategy:async()=>({sourceIds:['P01']}), drive:async tools=>{ - const plan=await tools.plan_production(); + const plan=await tools.start_production_strategy(); const slotIds=plan.pictures.map((slot,index)=>index%2?slot.id:slot.field); await assert.rejects(tools.delegate_image_slots({slotIds:['other-output'],goal:'展示同款商品'},controller.signal),/唯一定位/u); assert.equal((await tools.delegate_image_slots({slotIds,goal:'展示同款商品'},controller.signal)).assigned.length,5); let toolsProgress; for(let index=0;index<8;index++){ - toolsProgress=await tools.review_image_slots({slotIds}); + toolsProgress=await tools.check_image_slots({slotIds}); if(toolsProgress.pictures.filter(item=>item.state==='applied').length===4)break; } assert.equal(toolsProgress.pictures.filter(item=>item.state==='applied').length,4); assert.equal(toolsProgress.pictures[2].state,'unknown'); - const scoped=await tools.review_image_slots({slotIds:['F2']}); + const scoped=await tools.check_image_slots({slotIds:['F2']}); assert.deepEqual(scoped.pictures.map(({field,state})=>[field,state]),[['F2','unknown']]); const finished=await tools.finish_production(); assert.equal(finished.stage.production.complete,false); @@ -394,26 +394,26 @@ test('the production handoff keeps approvals for unchanged screens and binds the production:true,outputId:'main_images',prepareStrategy:async()=>({sourceIds:['P01']}), drive:async tools=>{ await tools.delegate_image_slots({slotIds:['slot-0'],goal:'完整商品'}); - await tools.review_image_slots({}); + await tools.check_image_slots({}); assert.deepEqual((await tools.finish_production()).status.unreviewed,[0]); const view=await tools.read_output_screen({page:0}); assert.equal(view.content[1].mimeType,'image/jpeg'); await tools.read_output_screen({page:1}); const issue={field:'story-heading',reason:'标题遮挡'}; - await tools.review_output_screen({page:1,revision:1,issues:[issue]}); + await tools.record_screen_check({page:1,revision:1,issues:[issue]}); const unchanged=await tools.read_output_screen({page:1}); assert.deepEqual(unchanged.details.issues,[issue]); assert.equal(unchanged.content.length,1); assert.deepEqual(rendered,[0,1]); - await tools.review_output_screen({page:1,revision:1,issues:[]}); + await tools.record_screen_check({page:1,revision:1,issues:[]}); revision=2; stamps[0]='hero-edited'; - await assert.rejects(tools.review_output_screen({page:0,revision:1,issues:[]}),/重新读取/); + await assert.rejects(tools.record_screen_check({page:0,revision:1,issues:[]}),/重新读取/); assert.deepEqual((await tools.finish_production()).status.unreviewed,[0]); assert.equal((await tools.read_output_screen({page:1})).details.passed,true); await tools.read_output_screen({page:0}); assert.deepEqual(rendered,[0,1,0]); - await tools.review_output_screen({page:0,revision:2,issues:[]}); + await tools.record_screen_check({page:0,revision:2,issues:[]}); return (await tools.finish_production()).stage; }, }); @@ -470,37 +470,37 @@ test('Pi writes each screen to the canvas before dispatch and can verify while o },async()=>({skills:[],rules:[]}),{ production:true,prepareStrategy:async()=>({sourceIds:['P01'],concept:'软包椅'}), drive:async tools=>{ - await tools.plan_production(); + await tools.start_production_strategy(); assert.equal((await tools.read_copy_fields()).page,'S01'); const send=async index=>tools.write_copy_fields({items:[{layer:rows[index].layer,text:text[index],sources:['P01'],pictures:rows[index].relatedFields}]}); const first=await send(0); assert.equal(first.onCanvas,1); - assert.deepEqual(first.nextScreen.fields.map(row=>row.field),['S01-T02']); + assert.deepEqual((await tools.read_copy_fields({pageId:'S01'})).fields.map(row=>row.field),['S01-T02']); assert.equal(originals.get(8),text[0]); assert.equal(copyProgress.at(-1).filter(cell=>cell.state==="filled").length,1); assert.deepEqual((await tools.read_copy_fields({pageId:'S01'})).onCanvas.map(row=>row.text),[text[0]]); - assert.equal((await tools.review_page_copy({})).written,undefined); + assert.equal((await tools.check_page_copy({})).written,undefined); assert.equal(f.calls.length,0); assert.equal((await tools.delegate_image_slots({slotIds:['slot-0'],goal:'展示同款'})).assigned.length,1); let previous; - while((await tools.review_image_slots({})).active)previous=(await tools.goalProgress(previous)).state; - assert.equal((await tools.review_page_copy({})).written,1); + while((await tools.check_image_slots({})).active)previous=(await tools.goalProgress(previous)).state; + assert.equal((await tools.check_page_copy({})).written,1); assert.deepEqual([...originals.values()],[text[0]]); assert.equal((await tools.read_copy_fields({pageId:'S02'})).page,'S02'); const second=await send(1); assert.equal(second.staged,1); - assert.equal(second.nextScreen.page,'S02'); - assert.deepEqual(second.assigned,[{id:'slot-1',field:'S01-I02'}]); + assert.equal(second.assigned,undefined); const third=await send(2); assert.equal(third.staged,1); - assert.deepEqual(third.assigned,[{id:'slot-2',field:'S02-I01'}]); - assert.equal((await tools.delegate_image_slots({slotIds:['slot-1','slot-2'],goal:'展示同款'})).assigned.length,0); - for(let poll=0;poll<12;poll++)if((await tools.review_image_slots({})).active===0)break; + assert.equal(third.assigned,undefined); + assert.equal(f.calls.filter(row=>row.intent==='generate_candidate').length,1); + assert.equal((await tools.delegate_image_slots({slotIds:['slot-1','slot-2'],goal:'展示同款'})).assigned.length,2); + for(let poll=0;poll<12;poll++)if((await tools.check_image_slots({})).active===0)break; const images=f.calls.filter(row=>row.intent==='generate_candidate'); assert.equal(images.length,3); assert.ok(images.some(row=>row.instruction.includes('看清弧形木扶手'))); assert.ok(images.some(row=>row.instruction.includes('座面米色织纹'))); - assert.equal((await tools.review_page_copy({})).written,2); + assert.equal((await tools.check_page_copy({})).written,2); }, }); assert.ok(f.peak>=2); @@ -538,19 +538,19 @@ test('a rejected visual claim can be rewritten and the same candidate reviewed w },async()=>({skills:[],rules:[]}),{ production:true,prepareStrategy:async()=>({sourceIds:['P01'],concept:'扶手近景'}), drive:async tools=>{ - await tools.plan_production(); + await tools.start_production_strategy(); const submit=(text,reviseFrom)=>tools.write_copy_fields({ items:[{layer:8,text,sources:['P01'],pictures:[picture],reviseFrom}]}); await submit('扶手前端圆角'); await tools.delegate_image_slots({slotIds:[picture],goal:'展示扶手前端'}); let verdict; - do { verdict=await tools.review_image_slots({}); } while(verdict.active); + do { verdict=await tools.check_image_slots({}); } while(verdict.active); assert.deepEqual(verdict.pictures[0].copyCorrections.map(row=>[row.field,row.reviseFrom]),[[field,candidate]]); assert.equal((await submit('深棕木纹扶手','unrelated')).rejected.length,1); assert.equal((await submit('深棕木纹扶手',candidate)).staged,1); - do { verdict=await tools.review_image_slots({}); } while(verdict.active); + do { verdict=await tools.check_image_slots({}); } while(verdict.active); assert.equal(verdict.pictures[0].state,'applied'); - assert.equal((await tools.review_page_copy({})).written,1); + assert.equal((await tools.check_page_copy({})).written,1); }, }); assert.equal(applied,'深棕木纹扶手'); @@ -592,7 +592,7 @@ test('a completed prose-only copy review requests a typed verdict in the same pr },async()=>({skills:[],rules:[]}),{ production:true,outputId:'main_images',prepareStrategy:async()=>({sourceIds:['P01']}), drive:async tools=>{ - await tools.plan_production(); + await tools.start_production_strategy(); const receipt=await tools.write_copy_fields({items:[{layer:8,text:'弧形木扶手',sources:['P01'],pictures:['M01-I01']}]}); assert.equal(receipt.applied,1); }, @@ -1376,10 +1376,11 @@ test('an unconfirmed independent image review holds only its candidate and leave return recheck&&settled?{settled:true}:null; }, drive:async tools=>{ + await tools.check_image_slots({slotIds:['slot-0']}); const plan=await tools.plan_production(); assert.equal(plan.pictures[0].interruptedWorker.step,'验图'); assert.ok(!plan.pictures[1].interruptedWorker); - if(settled)await tools.review_image_slots({slotIds:['slot-0'],retryInterrupted:true}); + if(settled)await tools.check_image_slots({slotIds:['slot-0'],retryInterrupted:true}); let previous; for(;;){ const {state}=await tools.goalProgress(previous); @@ -2969,8 +2970,8 @@ test('production rechecks an adopted close-up and keeps its rejection without re subjects:1,people:0,detail:'clear',shownFields:[],reason:'候选的扣件接合位置不同于侧视原片'}); },async()=>({skills:[],rules:[]}),{production:true,prepareStrategy:async()=>({sourceIds:['P01','P02'],concept:'同款细节'}), drive:async tools=>{ - await tools.review_image_slots({}); - const {pictures}=await tools.review_image_slots({}); + await tools.check_image_slots({}); + const {pictures}=await tools.check_image_slots({}); assert.deepEqual(pictures.map(item=>item.state),['rejected','unknown']); assert.equal(pictures[0].canRework,undefined); assert.equal(pictures[1].pendingOriginal,pending); @@ -3050,7 +3051,7 @@ test('the planner reworks a slot within its budget without resending an unknown },async()=>({skills:[],rules:[]}),{ outputId:'main_images',production:true,prepareStrategy:async()=>({sourceIds:['P01','P02']}), drive:async tools=>{ - const {pictures}=await tools.plan_production(); + const {pictures}=await tools.start_production_strategy(); assert.equal(pictures[0].canRework,true); assert.equal(pictures[1].canRework,undefined); const waiting=await tools.delegate_image_slots({slotIds:['held'],goal:'重新取景'}); @@ -3060,7 +3061,7 @@ test('the planner reworks a slot within its budget without resending an unknown [{id:'slot-1',field:'held',state:'unknown',pendingOriginal:original}]); const queued=await tools.delegate_image_slots({slotIds:['closeup'],goal:'移开前景,从斜前方看到搭扣和连接'}); assert.equal(queued.assigned.length,1); - const checked=await tools.review_image_slots({slotIds:['closeup']}); + const checked=await tools.check_image_slots({slotIds:['closeup']}); assert.equal(checked.pictures[0].state,'applied'); }, }); @@ -3091,7 +3092,7 @@ test('a rejected archive keeps the held original visible and eligible for recove async()=>assert.fail('reading an unresolved original must not dispatch another request'), async()=>({skills:[],rules:[]}),{production:true,prepareStrategy:async()=>({sourceIds:['P01']}), drive:async tools=>{ - const {pictures}=await tools.plan_production(); + const {pictures}=await tools.start_production_strategy(); assert.equal(pictures[0].state,'rejected'); assert.equal(pictures[0].pendingOriginal,original); assert.equal(pictures[0].canRework,undefined); @@ -3130,8 +3131,8 @@ test('the production review tool reads a held original and reviews its recovered detail:'clear',shownFields:[],reason:'原结果清楚展示同款轮廓和接合'}); },async()=>({skills:[],rules:[]}),{production:true,prepareStrategy:async()=>({sourceIds:['P01']}), drive:async tools=>{ - await tools.review_image_slots({}); - const {pictures}=await tools.review_image_slots({}); + await tools.check_image_slots({}); + const {pictures}=await tools.check_image_slots({}); assert.equal(pictures[0].state,'applied'); assert.equal(pictures[0].pendingOriginal,undefined); }, diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 2fe9502b..840e4b3a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -741,7 +741,7 @@ impl Backend { .and_then(|m| m["id"].as_str()) .is_some_and(|id| available.is_some_and(|a| a.iter().any(|v| v == id))) }; - json!({"model":saved["model"].as_str().unwrap_or(""),"imageModel":saved["imageModel"].as_str().unwrap_or(""),"copyModel":crate::jiansun_models::copy_selection(saved).as_str().unwrap_or(""),"copyModels":self.copy_models,"copyReady":ready(crate::jiansun_models::copy_selection(saved),&self.copy_models),"copyCatalogError":self.copy_error,"modelReady":ready(&saved["model"],&self.models),"imageReady":ready(&saved["imageModel"],&self.image_models),"keySaved":key_saved,"availableModels":available,"models":self.models,"imageModels":self.image_models,"imageCatalogError":self.image_error}) + json!({"model":saved["model"].as_str().unwrap_or(""),"imageModel":saved["imageModel"].as_str().unwrap_or(""),"copyModel":crate::jiansun_models::copy_selection(saved).as_str().unwrap_or(""),"copyModels":self.copy_models,"copyReady":ready(crate::jiansun_models::copy_selection(saved),&self.copy_models),"copyCatalogError":self.copy_error,"modelReady":ready(&saved["model"],&self.models),"imageReady":ready(&saved["imageModel"],&self.image_models),"keySaved":key_saved,"availableModels":available,"models":self.models,"imageModels":self.image_models,"imageCatalogError":self.image_error,"thinkingByModel":saved["thinkingByModel"]}) } fn state(&mut self) -> R { let mut message = String::new(); @@ -1337,14 +1337,22 @@ impl Backend { return Err("账号已切换,请重新选择模型".into()); } let field = input["field"].as_str().ok_or("模型用途无效")?; + let choice = input["selection"].as_str().ok_or("模型选择无效")?; + let mut saved = self.settings()?; + if field == "thinkingLevel" { + let model = self.models.iter().find(|model| model["key"] == saved["model"]) + .filter(|model| model["key"] == input["model"]).ok_or("对话模型已切换,请重新选择")?; + crate::jiansun_models::pick_thinking(&mut saved, model, choice)?; + vault(&format!("models:{}", self.scope()))?.set_password(&saved.to_string()) + .map_err(|_| "思考档位未能保存到本机")?; + return Ok(json!({"field":field,"thinkingByModel":saved["thinkingByModel"]})); + } let models = match field { "model" => &self.models, "copyModel" => &self.copy_models, "imageModel" => &self.image_models, _ => return Err("模型用途无效".into()), }; - let choice = input["selection"].as_str().ok_or("模型选择无效")?; - let mut saved = self.settings()?; crate::jiansun_models::pick_model(&mut saved, field, choice, models)?; vault(&format!("models:{}", self.scope()))?.set_password(&saved.to_string()) .map_err(|_| "模型选择未能保存到本机")?; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 8fba98af..5a1df5d4 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -589,6 +589,11 @@ fn prepare_product_template(native: &mut Document, meta: &mut Value, pack: &Valu production_profile::apply(native, meta, profile)?; meta["productionProfile"] = production_profile::source(pack, component); } + if let Some(policy) = profile.and_then(|profile| profile.get("allowedChanges")) + .or_else(|| pack["allowedChanges"].get(component)) + { + native.metadata.text.push(("jiansun.allowed-changes.v1".into(), policy.to_string())); + } production_profile::bind_fixed_text(native, meta, profile); if pack["enterprise"].is_object() { production_profile::hide_sample_photos(native, meta); @@ -3138,7 +3143,9 @@ impl Backend { let source = cached_prompt_mapping(&dir, &state["template"]); field["requirements"] = json!(editable_image_prompt(&field, &output["id"], source.as_ref())); } - let instructions = text(&input["instructions"], 2000, "图片要求")?; + let instructions = input["instructions"].as_str() + .filter(|value| !value.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))) + .ok_or("图片要求须为文本且不能含控制字符")?; let parent = input.get("parentCandidateId").filter(|v| !v.is_null()).map(|value| uuid(value, "原候选")).transpose()?; let mut attachments = creation::composer_attachments::resolve(&dir, &input.get("attachments").cloned().unwrap_or_else(|| json!([])))?; if let Some(parent) = &parent { @@ -3235,9 +3242,9 @@ impl Backend { .and_then(|rule| rule["focus"].as_str().filter(|focus| !focus.trim().is_empty())); let prefer_2k = input["detailBatch"] == true && scene.is_none() && production_rule.is_some_and(|rule| rule["clearDetail"] == true); - let mut prompt = if let Some((recipe,_)) = &scene { recipe.prompt(&instructions) } else { candidate_prompt( + let mut prompt = if let Some((recipe,_)) = &scene { recipe.prompt(instructions) } else { candidate_prompt( &state, &output, &field, selected, &images, - layout_instructions.as_deref().unwrap_or(&instructions), input["replaceTemplatePrompt"] == true, production_focus, + layout_instructions.as_deref().unwrap_or(instructions), input["replaceTemplatePrompt"] == true, production_focus, ) }; if parent.is_some() && scene.is_none() { let base_index = images.as_array().map_or(0, Vec::len) + 1; @@ -3255,9 +3262,6 @@ impl Backend { let knowledge = if state["template"]["enterprise"].is_object() && input["detailBatch"] != true { self.enterprise_template_request(json!({"action":"context","projectRoot":dir,"task":"image","brandName":state["brief"]["brandName"],"categoryName":state["brief"]["categoryName"],"templateId":state["template"]["id"],"releaseId":state["template"]["version"]}))?["context"].clone() } else { Value::Null }; - if prompt.chars().count() > 6000 { - return Err("当前产品与图片要求超过单次上下文限额,请先精简资料".into()); - } let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, &prompt); if input["detailBatch"] == true { binding["detailBatch"] = json!(true); } if !attachment_refs.as_array().is_none_or(Vec::is_empty) { binding["composerHash"] = json!(hash(&attachment_refs.to_string())); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs index 4e701b02..e5fe0327 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs @@ -96,6 +96,18 @@ pub fn accepts(v: &Value, s: &Value, depth: usize) -> bool { !s.get("not").is_some_and(|s| accepts(v, s, depth + 1)) } +pub(super) fn validate_prompt_length(contract: &Value, prompt: &str) -> Result<(), String> { + if let Some(maximum) = parts(&contract["schema"], 0).into_iter() + .filter_map(|schema| schema["properties"]["prompt"]["maxLength"].as_u64()).min() + { + let length = prompt.chars().count() as u64; + if length > maximum { + return Err(format!("生图线路最多接受 {maximum} 字符,当前提示词 {length} 字符。请缩短后再提交。")); + } + } + Ok(()) +} + /// Choose only dimensions advertised by the selected public invocation schema. /// Missing dimension controls stay untouched; the native frame still crops explicitly. pub(super) fn frame(contract: &mut Value, width: u64, height: u64, prefer_2k: bool) -> Result<(), String> { @@ -333,6 +345,15 @@ mod tests { assert!(!accepts(&json!({"other":1}), &s, 0)); assert!(accepts(&json!({"image":["https://example.test/a"]}), &s, 0)); } + + #[test] + fn prompt_length_uses_the_selected_route_schema() { + let prompt = "光".repeat(6001); + assert!(validate_prompt_length(&json!({}), &prompt).is_ok()); + let contract = json!({"schema":{"allOf":[{"properties":{"prompt":{"maxLength":6000}}}]}}); + assert!(validate_prompt_length(&contract, &prompt).unwrap_err().contains("最多接受 6000 字符,当前提示词 6001 字符")); + assert!(validate_prompt_length(&contract, &prompt["光".len()..]).is_ok()); + } #[test] fn combinations_and_required_are_checked() { assert!(!accepts(&json!({}), &json!({"anyOf":[{"required":["prompt"]},{"required":["image"]}]}), 0)); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 767e684d..3c377af2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -668,7 +668,7 @@ impl Backend { return Err("请先选中没有变形的产品图片图层".into()); } } - let text = input["text"].as_str().filter(|s| !s.trim().is_empty() && s.chars().count() <= 6000).ok_or("请输入6000字以内的生图要求")?; + let text = input["text"].as_str().filter(|s| !s.trim().is_empty()).ok_or("请输入生图要求")?; let (text, template_reference) = if input["hasTemplateLayout"] == true || input["optionalLayoutReference"] == true { text.rsplit_once(TEMPLATE_LAYOUT_PROMPT_PREFIX).unwrap_or((text, "")) } else { @@ -709,9 +709,6 @@ impl Backend { references.push(json!({"layer":layer.0,"name":name,"path":path.to_string_lossy(),"sha256":format!("{:x}",Sha256::digest(&bytes))})); } let guidance = json!({"brand":input["brand"],"facts":input["facts"]}); - if guidance.to_string().len() > 96000 { - return Err("项目品牌与事实快照过大,请先精简资料".into()); - } let color_rule = if input["slotBinding"]["canvasFirst"] == true { "产品颜色服从【本图产品颜色】。" } else { @@ -726,6 +723,7 @@ impl Backend { doc.name, input["screen"].as_str().unwrap_or("当前图片") ) }; + protocol::validate_prompt_length(&contract, &prompt)?; let prior = if dir.join("image-task.json").exists() { read_json(&dir.join("image-task.json"))?["id"].clone() } else { Value::Null }; json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":prompt,"references":references,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)}) }; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs index e2cd42bb..0f71aa4c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs @@ -60,6 +60,18 @@ pub(super) fn text_routes(row: &Value) -> impl Iterator { && route["id"] == route["invocation"]["headers"]["X-Relay-Route-Option"]) } +pub(super) fn reasoning_options<'a>(protocol: &str, properties: &'a Value) -> (bool, Vec<&'a str>) { + let effort = if protocol == "openai-responses" { &properties["reasoning"]["properties"]["effort"] } + else { &properties["reasoning_effort"] }; + let levels: Vec<_> = effort["enum"].as_array().into_iter().flatten() + .filter_map(Value::as_str) + .filter(|level| matches!(*level, "minimal" | "low" | "medium" | "high" | "xhigh" | "max")) + .collect(); + let enabled = !levels.is_empty() + || protocol == "anthropic-messages" && properties["thinking"]["properties"].is_object(); + (enabled, levels) +} + fn completion_capability(route: &Value) -> u8 { let capabilities = &route["chat_capabilities"]; match capabilities["image_base64_streaming_tools"].as_str() { @@ -96,7 +108,9 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> None => return None, }; let path = contract["invocation"]["path"].as_str()?; - let tool_choice = &contract["invocation"]["input_schema"]["properties"]["tool_choice"]; + let properties = &contract["invocation"]["input_schema"]["properties"]; + let (reasoning, reasoning_efforts) = reasoning_options(protocol, properties); + let tool_choice = &properties["tool_choice"]; let require_single_tool = protocol == "openai-responses" && tool_choice["type"] == "string" && tool_choice["enum"].as_array().is_some_and(|values| values.iter().any(|value| value == "required")); let capabilities = &contract["chat_capabilities"]; @@ -110,7 +124,7 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> Some(json!({"key":key.unwrap_or(id),"id":id,"label":id,"protocol":protocol,"path":path, "routeId":route_id,"imageInputStatus":image_status,"supportsImageInput":production > 0 || image_status == "verified", "productionReady":production > 0,"productionVerified":production == 2, - "requireSingleTool":require_single_tool})) + "requireSingleTool":require_single_tool,"reasoning":reasoning,"reasoningEfforts":reasoning_efforts})) } pub fn key_models(catalog: &Value) -> R> { @@ -150,7 +164,30 @@ pub fn selection(input: &Value, saved: &Value, chat: &[Value], copies: &[Value], return Err(format!("你的Key未开放 {id},请选择其他模型")); } } - Ok(json!({"version":3,"key":key,"model":chat_key,"copyModel":copy_key,"imageModel":image_key})) + Ok(json!({"version":3,"key":key,"model":chat_key,"copyModel":copy_key,"imageModel":image_key, + "thinkingByModel":saved.get("thinkingByModel").and_then(Value::as_object)})) +} + +pub(super) fn thinking_preference<'a>(settings: &'a Value, model: &Value) -> Option<&'a str> { + let level = settings["thinkingByModel"].get(model["key"].as_str()?)?.as_str()?; + (model["reasoning"] == true && (level == "off" || model["reasoningEfforts"].as_array() + .is_some_and(|levels| levels.iter().any(|allowed| allowed == level)))).then_some(level) +} + +pub(super) fn pick_thinking(saved: &mut Value, model: &Value, level: &str) -> R<()> { + let key = model["key"].as_str().ok_or("请先选择对话模型")?; + if model["reasoning"] != true + || !matches!(level, "" | "off") && !model["reasoningEfforts"].as_array() + .is_some_and(|levels| levels.iter().any(|allowed| allowed == level)) + { + return Err("当前对话线路未开放此思考档位".into()); + } + if !saved["thinkingByModel"].is_object() { saved["thinkingByModel"] = json!({}); } + if let Some(preferences) = saved["thinkingByModel"].as_object_mut() { + if level.is_empty() { preferences.remove(key); } + else { preferences.insert(key.into(), json!(level)); } + } + Ok(()) } /// Update one preference from the loaded role's model directory. @@ -288,6 +325,22 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) { mod tests { use super::*; + #[test] + fn saved_thinking_preference_uses_the_selected_route_support() { + let schema = json!({"reasoning":{"properties":{"effort":{"enum":["low","high"]}}}}); + let (reasoning, levels) = reasoning_options("openai-responses", &schema); + assert_eq!(reasoning_options("openai-chat", &schema), (false, vec![])); + let model = json!({"key":"chat","reasoning":reasoning,"reasoningEfforts":levels}); + let mut saved = json!({"key":"test-key-in-vault"}); + assert!(pick_thinking(&mut saved, &model, "medium").is_err()); + pick_thinking(&mut saved, &model, "high").unwrap(); + assert_eq!(thinking_preference(&saved, &model), Some("high")); + assert_eq!(thinking_preference(&saved, &json!({"key":"other","reasoning":true})), None); + pick_thinking(&mut saved, &model, "").unwrap(); + assert_eq!(thinking_preference(&saved, &model), None); + assert_eq!(saved["key"], "test-key-in-vault"); + } + #[test] fn local_model_preferences_keep_credentials_and_other_roles() { let mut settings = json!({"version":3,"key":"local-test-key","model":"chat-old","imageModel":"image"}); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs index 4cb4f512..a478ac29 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs @@ -453,9 +453,9 @@ fn product_scope_tools(scope: &str) -> Option<&'static [&'static str]> { ("goal", Some("detail" | "main_images" | "sku_images"), None) => Some(&["workflow_read", "context_read", "memory_search", "native_catalog", "native_call", "native_reconcile", "codemode", "tool_search", "read", "write", "edit", "ls", "find", "grep", "bash", - "plan_production", "read_production_knowledge", "read_copy_fields", - "write_copy_fields", "review_page_copy", "delegate_image_slots", "review_image_slots", - "read_output_screen", "review_output_screen", "finish_production", "get_goal"]), + "plan_production", "start_production_strategy", "read_production_knowledge", "read_copy_fields", + "write_copy_fields", "review_page_copy", "check_page_copy", "delegate_image_slots", "review_image_slots", "check_image_slots", + "read_output_screen", "record_screen_check", "finish_production", "get_goal"]), ("strategy", None, None) => Some(PRODUCT_STRATEGY_TOOLS), ("strategy-audit", None, None) => Some(&["review_product_strategy"]), ("review", None, None) => Some(&["review_candidate"]), @@ -770,9 +770,10 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m let role = input["modelRole"].as_str().unwrap_or("chat"); let (settings, mut model, invocation, selection_timings) = selected(&mut backend, role)?; pi_runtime::apply_invocation_capacity(&mut model, &invocation)?; + let thinking = crate::jiansun_models::thinking_preference(&settings, &model).map(str::to_owned); *selection = Some((backend.scope(), role.to_owned(), settings, model.clone(), invocation.clone())); return emit( - json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"invocationHeaders":invocation["headers"],"pending":unresolved(&dir)?,"selectionTimings":selection_timings}}), + json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"thinkingLevel":thinking,"invocationHeaders":invocation["headers"],"pending":unresolved(&dir)?,"selectionTimings":selection_timings}}), ); } if method == "knowledge" { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 630c6693..d3dda71f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -184,15 +184,8 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { .or_else(|| invocation["input_schema"]["properties"][output_field]["maximum"].as_u64()) .filter(|n| *n > 0 && *n <= 9_007_199_254_740_991); let properties = &invocation["input_schema"]["properties"]; - let effort = if model["protocol"] == "openai-responses" { - &properties["reasoning"]["properties"]["effort"] - } else { - &properties["reasoning_effort"] - }; - let reasoning_efforts: Vec<_> = effort["enum"].as_array().into_iter().flatten() - .filter_map(Value::as_str).collect(); - let reasoning = !reasoning_efforts.is_empty() - || model["protocol"] == "anthropic-messages" && properties["thinking"]["properties"].is_object(); + let (reasoning, reasoning_efforts) = crate::jiansun_models::reasoning_options( + model["protocol"].as_str().unwrap_or_default(), properties); let requires_output = invocation["input_schema"]["required"].as_array().into_iter().flatten() .any(|field| field == output_field || field == "max_completion_tokens"); Ok(json!({"version":4,"headers":headers,"model":model["id"],"path":model["path"],"routeId":model["routeId"],"at":now(),"contextWindow":limit, diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 3bd9871b..548c7633 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -918,6 +918,7 @@ pub struct Workspace { origin: String, login_origin: Option, model: String, + thinking_by_model: Value, model_ready: bool, copy_models: Vec, copy_model: String, @@ -1395,6 +1396,7 @@ impl Workspace { origin: "https://sc.jiansun.vip".into(), login_origin: None, model: String::new(), + thinking_by_model: Value::Null, model_ready: false, copy_models: vec![], copy_model: String::new(), @@ -3710,6 +3712,7 @@ impl Workspace { self.copy_ready = value["copyReady"].as_bool().unwrap_or(false); self.copy_catalog_error=value["copyCatalogError"].as_str().unwrap_or("").into(); self.model = value["model"].as_str().unwrap_or("").into(); + self.thinking_by_model = value["thinkingByModel"].clone(); self.image_model = value["imageModel"].as_str().unwrap_or("").into(); self.model_ready = value["modelReady"].as_bool().unwrap_or(false); self.image_ready = value["imageReady"].as_bool().unwrap_or(false); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs index eb223016..bb0e3c34 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs @@ -194,12 +194,17 @@ fn identity(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Result<(u64, u Ok((doc, index, active.revision)) } -pub(super) fn guard(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Result<(u64, usize, u64), String> { - guard_with_background_save(w, app, input, false) -} - pub(super) fn guard_with_background_save(w: &Workspace, app: &PhotocraftApp, input: &Value, read_only: bool) -> Result<(u64, usize, u64), String> { let current = identity(w, app, input)?; + if w.pi_request_scope["productProduction"] == true { + if w.agent_native.cancelled(input["run"].as_str().unwrap_or("")) || current.2 > MAX_INTEGER { + return Err("当前制作会话已取消".into()); + } + if !read_only && (w.pi_write_blocked || w.agent_effects_paused || current.2 != w.expected_revision) { + return Err("写入修订已变化,请重新读取画布".into()); + } + return Ok(current); + } if w.pi_write_blocked || w.agent_native.cancelled(input["run"].as_str().unwrap_or("")) || w.agent_effects_paused || w.unknown || w.pi_unknown || w.unknown_image || !w.queue.is_empty() || w.pending_image.is_some() || w.pending_slot_apply.is_some() @@ -225,18 +230,39 @@ fn safe_services(app: &PhotocraftApp) -> Result<(), String> { Ok(()) } -pub(super) fn authority(w: &Workspace, app: &PhotocraftApp, scope: &CommandScope, id: &str, params: &Value) -> Option { +fn engine_query(id: &str) -> bool { + photocraft_engine::commands::find(id).is_some_and(|command| !command.journal) +} + +pub(super) fn authority(_w: &Workspace, app: &PhotocraftApp, scope: &CommandScope, id: &str, params: &Value) -> Option { if let Err(error) = safe_services(app) { return Some(error); } if let Some(authorize) = &app.services.automation_command && let Err(error) = authorize(id, params) { return Some(error); } if let Err(error) = scope.check(&app.session, id, params) { return Some(error.to_string()); } - if w.pi_request_scope["productProduction"] == true - && !matches!(id, "document.inspect" | "layer.list" | "layer.select" | "type.edit") - { - return Some("模板制作中,请通过已发布字段工具修改内容,固定图层和布局保留原样".into()); - } None } +fn template_permission(doc: &photocraft_doc::Document, command: &str, params: &Value) -> Result<&'static str, String> { + let Some((_, value)) = doc.metadata.text.iter().find(|(key, _)| key == "jiansun.allowed-changes.v1") else { + return Ok("default-allowed"); + }; + let policy: Value = serde_json::from_str(value).map_err(|_| "模板发布的允许变更格式无效")?; + let rules = policy.as_array().ok_or("模板发布的允许变更须为操作列表")?; + let allowed = rules.iter().any(|rule| { + if rule["command"] != command { return false; } + if let Some(original) = rule.get("psdLayerId") { + let target = params["layer"].as_u64().and_then(|id| doc.layer(photocraft_doc::LayerId(id))); + if target.and_then(|layer| layer.psd_id).map(u64::from) != original.as_u64() || original.as_u64().is_none() { + return false; + } + } + rule.get("params").is_none_or(|values| values.as_object().is_some_and(|pairs| + pairs.iter().all(|(key, value)| params.get(key) == Some(value)) + && params.as_object().is_some_and(|input| input.keys().all(|key| + key == "layer" || pairs.contains_key(key))))) + }); + allowed.then_some("published").ok_or_else(|| format!("模板发布的允许变更未包含 {command} 对当前目标的操作")) +} + fn current(w: &Workspace, app: &PhotocraftApp) -> Value { let active = app.session.active(); let view = app.session.active_index().and_then(|index| app.ui.views.get(index)); @@ -378,7 +404,7 @@ pub(super) fn catalog(w: &Workspace, app: &mut PhotocraftApp, input: &Value) -> row["authorityReason"] = json!(blocked); row["reason"] = if row["nativeEnabled"] == false { row["nativeReason"].clone() } else { row["authorityReason"].clone() }; row["dispatchMethod"] = json!("engine.execute"); - row["requiresRevisionLease"] = json!(true); + row["requiresRevisionLease"] = json!(!engine_query(&id)); row["revisionLeaseGranted"] = json!(w.allow_apply); let docs = row["parameterDocs"].as_str().filter(|docs| !docs.is_empty()); let summary = docs.map(|docs| docs.chars().take(200).collect::()); @@ -409,16 +435,11 @@ fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u6 /// IPC, paths, shell programs, model calls or new authentication are forwarded. pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, input: &Value) -> Result { arguments(input, &["run", "documentId", "revision", "method", "params"])?; - let (document, index, before) = guard(w, app, input)?; - if input["revision"].as_u64() != Some(before) { return Err("原生操作修订已过期,未执行".into()); } let method = input["method"].as_str().filter(|method| METHODS.contains(method)).ok_or("此原生控制方法未开放")?; let params = input["params"].as_object().ok_or("原生控制params须为对象")?; if input["params"].to_string().len() > 65_536 { return Err("单次原生参数超过64KiB".into()); } - let read = matches!(method, "ui.inspect" | "ui.menu.list"); - if read && !params.is_empty() { return Err("原生读取不接受额外参数".into()); } - if !read && !w.allow_apply { return Err("本轮原生操作尚未取得当前修订许可".into()); } - if !read && w.agent_native.pending(input["run"].as_str().unwrap_or("")) { return Err("原生任务仍在处理中,请核查原任务,不重复派发".into()); } - safe_services(app)?; + let view_read = matches!(method, "ui.inspect" | "ui.menu.list"); + if view_read && !params.is_empty() { return Err("原生读取不接受额外参数".into()); } let mut native_params = Value::Object(params.clone()); let command = if method == "engine.execute" { arguments(&native_params, &["command", "params"])?; @@ -429,7 +450,24 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte native_params["wait"] = json!(false); id } else { method.to_owned() }; - w.agent_native.make_room()?; + let read = view_read || method == "engine.execute" && engine_query(&command); + let (document, index, before) = match guard_with_background_save(w, app, input, read) { + Ok(current) => current, + Err(error) if w.pi_request_scope["productProduction"] == true => + return Ok(json!({"executed":false,"completed":true,"pending":false,"error":error})), + Err(error) => return Err(error), + }; + if input["revision"].as_u64() != Some(before) && !read { + let error = "原生操作修订已过期,未执行"; + if w.pi_request_scope["productProduction"] == true { + return Ok(json!({"executed":false,"completed":true,"pending":false,"revision":before,"error":error})); + } + return Err(error.into()); + } + if !read && !w.allow_apply { return Err("本轮原生操作尚未取得当前修订许可".into()); } + if !read && w.agent_native.pending(input["run"].as_str().unwrap_or("")) { return Err("原生任务仍在处理中,请核查原任务,不重复派发".into()); } + safe_services(app)?; + if !read { w.agent_native.make_room()?; } let (scope, token) = w.agent_native.scope(input["run"].as_str().unwrap_or(""), document, index)?; if method == "engine.execute" { if let Some(error) = authority(w, app, &scope, &command, &native_params["params"]) { return Err(error); } @@ -437,20 +475,14 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte return Err("当前原生界面命令不可用".into()); } } - if command == "type.edit" && w.pi_request_scope["productProduction"] == true { - let edit = &native_params["params"]; - arguments(edit, &["layer", "text", "expectedText"])?; - let layer = edit["layer"].as_u64().ok_or("请指定模板文字层")?; - let applied = super::pi_bridge::private_action_in_ui(w, app, ctx, "pi-detail-copy-apply", - &json!({"run":input["run"],"documentId":document,"revision":before,"items":[edit]}))?; - if !applied["appliedLayers"].as_array().is_some_and(|layers| layers.contains(&json!(layer))) { - let reason = applied["rejected"].as_array().and_then(|items| items.first()) - .and_then(|item| item["reason"].as_str()); - return Err(reason.unwrap_or("模板文字格未取得许可或原文已变化").into()); + let template_policy = if method == "engine.execute" && !read && command != "layer.select" + && w.pi_request_scope["productProduction"] == true { + let state = app.session.active().ok_or("当前画布未打开")?; + match template_permission(&state.doc, &command, &native_params["params"]) { + Ok(policy) => Some(policy), + Err(error) => return Ok(json!({"executed":false,"completed":true,"pending":false,"revision":before,"error":error})), } - let after = app.session.active().ok_or("当前画布未打开")?.revision; - return Ok(receipt(w, document, (before, after), method, &command, &applied, false)); - } + } else { None }; let before_state = current(w, app); // Equality observes actual native state, including tool/options controls // which need not bump the document revision. This private snapshot is @@ -478,6 +510,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte let result = w.agent_native.project_result(result)?; let mut value = receipt(w, document, (before, revision), method, &command, &result, true); value["job"] = json!(job.0); + value["templatePolicy"] = json!(template_policy); let receipt = w.agent_native.record(value)?; return Ok(json!({"dispatched":true,"executed":false,"pending":true,"completed":false,"job":job.0,"method":method,"command":command,"beforeRevision":before,"revision":revision,"result":result,"receipt":receipt})); } @@ -488,6 +521,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte let result = json!({"job":job.0,"pending":true}); let mut value = receipt(w, document, (before, revision), method, &command, &result, true); value["job"] = json!(job.0); + value["templatePolicy"] = json!(template_policy); let receipt = w.agent_native.record(value)?; return Ok(json!({"dispatched":true,"executed":false,"pending":true,"completed":false,"job":job.0,"method":method,"command":command,"beforeRevision":before,"revision":revision,"receipt":receipt})); } @@ -500,7 +534,13 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte } Outcome::Screenshot { .. } => return Err("此原生调用意外产生截图等待,结果待核查".into()), }; - w.expected_revision = revision; + if !read { + w.expected_revision = revision; + if revision != before && w.pi_request_scope["productProduction"] == true { + w.draft_changed = true; + w.sync_dirty = true; + } + } let result = scoped_read_result(w, app, method, result, w.agent_native.scope.as_ref().ok_or("原生能力已失效")?)?; let result = w.agent_native.project_result(result)?; let state = current(w, app); @@ -510,6 +550,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte let operation_receipt = if read { None } else { let mut value = receipt(w, document, (before, revision), method, &command, &result, false); value["changed"] = json!(changed); + value["templatePolicy"] = json!(template_policy); Some(w.agent_native.record(value)?) }; Ok(json!({"executed":true,"pending":false,"completed":true,"method":method,"command":command,"beforeRevision":before,"revision":revision, @@ -913,6 +954,72 @@ mod tests { assert!(requests.try_recv().is_err()); } + #[test] + fn production_uses_native_text_and_layer_commands_without_a_published_policy() { + let (mut w, mut app, _) = fixture(); + let layer = app.session.execute("type.create", json!({"text":"旧款","size":18})).unwrap()["layer"].as_u64().unwrap(); + w.pi_request_scope["productProduction"] = json!(true); + w.pi_request_scope["wholeDetail"] = json!(true); + w.expected_revision = app.session.active().unwrap().revision; + let applied = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"type.edit","params":{"layer":layer,"text":"New"}})).unwrap(); + assert_eq!(applied["completed"], true); + assert_eq!(applied["executed"], true); + assert_eq!(applied["revision"], w.expected_revision); + assert_eq!(applied["receipt"]["sequence"], 1); + assert_eq!(applied["receipt"]["templatePolicy"], "default-allowed"); + let current = app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap(); + assert!(matches!(¤t.content, photocraft_doc::LayerContent::Text(text) if text.text == "New")); + let hidden = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.setProps","params":{"layer":layer,"visible":false}})).unwrap(); + assert_eq!(hidden["executed"], true); + assert!(!app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().visible); + let added = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.new.layer","params":{"name":"Background paper"}})).unwrap(); + assert_eq!(added["executed"], true); + } + + #[test] + fn a_published_policy_limits_the_actual_native_write() { + let (mut w, mut app, _) = fixture(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session.edit("Template policy", |doc, _| { + doc.layer_mut(layer).unwrap().psd_id = Some(17); + doc.metadata.text.push(("jiansun.allowed-changes.v1".into(), json!([ + {"command":"layer.setProps","psdLayerId":17,"params":{"visible":false}} + ]).to_string())); + Ok(()) + }).unwrap(); + w.pi_request_scope["productProduction"] = json!(true); + w.expected_revision = app.session.active().unwrap().revision; + let rejected = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.setProps","params":{"layer":layer.0,"visible":true}})).unwrap(); + assert_eq!(rejected["executed"], false); + assert!(w.agent_native.last_receipt().is_none()); + let applied = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.setProps","params":{"layer":layer.0,"visible":false}})).unwrap(); + assert_eq!(applied["receipt"]["templatePolicy"], "published"); + assert!(!app.session.active().unwrap().doc.layer(layer).unwrap().visible); + } + + #[test] + fn production_reads_the_canvas_while_an_image_original_is_unresolved() { + let (mut w, mut app, _) = fixture(); + w.pi_request_scope["productProduction"] = json!(true); + w.unknown_image = true; + w.allow_apply = false; + let mut request = base(&w); + request["id"] = json!("document.inspect"); + let catalog = catalog(&w, &mut app, &request).unwrap(); + assert_eq!(catalog["items"][0]["requiresRevisionLease"], false); + let inspected = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"document.inspect","params":{}})).unwrap(); + assert_eq!(inspected["executed"], true); + assert!(inspected["receipt"].is_null()); + assert!(invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.select","params":{"layer":1}})).is_err()); + } + #[test] fn consecutive_native_calls_share_only_the_turns_private_clipboard() { let (mut w, mut app, _) = fixture(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index c1b7d9a2..f5d3e845 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -3295,6 +3295,10 @@ impl Workspace { } pub(super) fn receive_model_preference(&mut self, value: &Value) { + if value["field"] == "thinkingLevel" { + self.thinking_by_model = value["thinkingByModel"].clone(); + return; + } let (selected, models, ready) = match value["field"].as_str() { Some("model") => (&mut self.model, &self.models, &mut self.model_ready), Some("copyModel") => (&mut self.copy_model, &self.copy_models, &mut self.copy_ready), @@ -3309,6 +3313,44 @@ impl Workspace { }); } + fn thinking_picker(&mut self, ui: &mut Ui) { + let Some(model) = self.models.iter().find(|model| model["key"] == self.model && model["reasoning"] == true) else { + return; + }; + let label = |level: &str| match level { + "off" => "关闭", + "minimal" => "最少", + "low" => "低", + "medium" => "中", + "high" => "高", + "xhigh" => "很高", + "max" => "最高", + _ => "跟随 Pi", + }; + let current = self.thinking_by_model.get(self.model.as_str()).and_then(Value::as_str).unwrap_or(""); + let mut selected = current; + let levels = model["reasoningEfforts"].as_array().into_iter().flatten().filter_map(Value::as_str); + let width = ui.available_width(); + let tokens = Tokens::get(ui.ctx()).agent(); + ui.push_id("xiaoyi-thinking-effort", |ui| { + ui.label(RichText::new("思考档位").size(12.0).color(tokens.text_dim)); + let trigger = super::stitch_ui::select_trigger(ui, label(current), width, self.model_ready && self.busy.is_none()); + self.panel_geometry["thinkingLevel"] = rect_value(trigger.rect); + super::stitch_ui::select_popup(ui, &trigger, width, self.reduce_motion, |ui| { + for level in ["", "off"].into_iter().chain(levels) { + if super::stitch_ui::select_option(ui, label(level), current == level, true).clicked() { + selected = level; + ui.close(); + } + } + }); + }); + if selected != current { + self.send("select-model", json!({"field":"thinkingLevel","selection":selected,"model":self.model, + "accountId":self.account["id"],"origin":self.origin})); + } + } + fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { let open = self.model_settings || self.key_settings; let t = Tokens::get(ui.ctx()).agent(); @@ -3357,6 +3399,7 @@ impl Workspace { for (role, label) in [(ModelRole::Chat,"对话模型"),(ModelRole::Copy,"文案模型"),(ModelRole::Image,"生图模型")] { ui.label(RichText::new(label).size(12.0).color(t.text_dim)); self.model_picker(ui, role, ui.available_width(), true); + if role == ModelRole::Chat { self.thinking_picker(ui); } } if !self.copy_catalog_error.is_empty() { ui.horizontal_wrapped(|ui| { @@ -6047,6 +6090,47 @@ mod tests { assert!(requests.try_recv().is_err()); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn thinking_picker_visual_acceptance() { + use egui_kittest::kittest::Queryable; + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.reduce_motion = true; + workspace.model_settings = true; + workspace.models[0]["reasoning"] = json!(true); + workspace.models[0]["reasoningEfforts"] = json!(["low","medium","high"]); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(6); + let trigger = geometry(harness.state().0.jiansun.as_ref().unwrap(), "thinkingLevel"); + assert!(trigger.left() >= 0.0 && trigger.right() <= width); + harness.get_by_label("跟随 Pi").click(); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("thinking-picker-{width}.png"))).unwrap(); + harness.get_by_label("高").click(); + harness.run_steps(4); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; + assert_eq!(method, "select-model"); + assert_eq!(input["field"], "thinkingLevel"); + assert_eq!(input["selection"], "high"); + } + } + #[test] fn focused_model_picker_uses_the_list_without_a_duplicate_tooltip() { fn labels(shape: &egui::Shape, out: &mut Vec) { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index 3a3ee0c1..92637147 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -58,6 +58,9 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { "save_product_strategy" => "保存商品策划", "review_product_strategy" => "核对卖点证据", "plan_page_copy" => "规划整页卖点", "write_copy_fields" => "填写画布文案", "review_page_copy" => "复核整页文案", + "check_page_copy" => "发起文案复核", + "check_image_slots" => "发起验图", + "record_screen_check" => "记录本屏复核", "native_catalog" => "查询原生命令", "native_call" => "执行原生操作", "native_reconcile" => "核查原生任务", diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs index 03f6e36b..41d81dbe 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs @@ -453,11 +453,11 @@ fn projected_facts(w: &Workspace) -> Value { .as_array() .into_iter() .flatten() - .take(24) - .map(|item| json!({"text":clip(&item["text"],260),"source":source_label(&item["source"])})) + .map(|item| json!({"text":item["text"].as_str().unwrap_or_default(),"source":source_label(&item["source"])})) .collect() }; - let mut missing = strings(&w.creation["facts"]["missing"], 20, 220); + let mut missing: Vec<_> = w.creation["facts"]["missing"].as_array().into_iter().flatten() + .filter(|item| item.is_string()).cloned().collect(); if changed { missing.push(json!("产品资料尚有未保存修改,旧分析不作为新产品事实")); } @@ -485,15 +485,11 @@ fn projected_image(image: &Value) -> Value { fn projected_images(value: &Value) -> Value { match value.as_array() { - Some(images) => json!(images.iter().filter(|image| image.is_object()).take(8).map(projected_image).collect::>()), + Some(images) => json!(images.iter().filter(|image| image.is_object()).map(projected_image).collect::>()), None => Value::Null, } } -fn omitted_images(value: &Value) -> Option { - value.as_array().map(|images| images.len().saturating_sub(8)) -} - fn projected_brief(w: &Workspace) -> Value { let mut brief = serde_json::Map::new(); if let Some(selection) = w.creation_brief.get("outputVariantIds") { @@ -509,15 +505,13 @@ fn projected_brief(w: &Workspace) -> Value { .collect::>(); brief.insert("dimensions".into(), Value::Object(dimensions)); brief.insert("images".into(), projected_images(&w.creation_brief["images"])); - let variants = w.creation_brief["variants"].as_array().map(|rows| rows.iter().filter(|v| v.is_object()).take(64).map(|v| { + let variants = w.creation_brief["variants"].as_array().map(|rows| rows.iter().filter(|v| v.is_object()).map(|v| { json!({"id":safe_variant_id(&v["id"]),"name":safe_reference_text(&v["name"],160),"colorName":safe_reference_text(&v["colorName"],160), - "colorMaterialId":safe_variant_id(&v["colorMaterialId"]).map(str::to_owned).unwrap_or_else(|| safe_reference_text(&v["colorMaterialId"],150)),"images":projected_images(&v["images"]),"imagesOmitted":omitted_images(&v["images"]), + "colorMaterialId":safe_variant_id(&v["colorMaterialId"]).map(str::to_owned).unwrap_or_else(|| safe_reference_text(&v["colorMaterialId"],150)),"images":projected_images(&v["images"]), "dimensions":{"length":clip(&v["dimensions"]["length"],24),"width":clip(&v["dimensions"]["width"],24), "height":clip(&v["dimensions"]["height"],24),"unit":clip(&v["dimensions"]["unit"],24)}}) }).collect::>()); brief.insert("variants".into(), json!(variants)); - brief.insert("projectionOmitted".into(), json!({"commonImages":omitted_images(&w.creation_brief["images"]), - "variants":w.creation_brief["variants"].as_array().map(|v|v.len().saturating_sub(64))})); if w.template_workflow["canvasFirst"] == true && let Some(variant) = w.creation_brief["variants"].as_array().and_then(|vs| vs.iter().find(|v| v["id"] == product_variant(w))) { @@ -535,8 +529,7 @@ fn projected_batches(w: &Workspace) -> Vec { .as_array() .into_iter() .flatten() - .take(12) - .map(|batch| json!({"id":clip(&batch["id"],100),"items":strings(&batch["items"],6,200)})) + .map(|batch| json!({"id":batch["id"],"items":batch["items"]})) .collect() } @@ -547,9 +540,8 @@ fn projected_plan(w: &Workspace) -> Value { .as_array() .into_iter() .flatten() - .take(12) .map( - |screen| json!({"id":clip(&screen["id"],100),"name":clip(&screen["name"],100),"title":clip(&screen["title"],160),"body":clip(&screen["body"],300)}), + |screen| json!({"id":screen["id"],"name":screen["name"],"title":screen["title"],"body":screen["body"]}), ) .collect::>(); json!({"status":if changed {json!("stale")} else {json!(clip(&w.creation["plan"]["status"],24))}, @@ -560,7 +552,7 @@ fn product_evidence(w: &Workspace) -> Value { let Some(owner) = &w.workflow.owner else { return Value::Null }; json!({"accountScope":owner.scope,"project":owner.project,"documentId":owner.doc,"revision":w.creation["revision"], "brief":projected_brief(w),"currentVariantId":run_scope(w).and_then(|scope| safe_variant_id(&scope["variantId"])),"facts":projected_facts(w), - "sellingPoints":{"selected":w.creation_selected.iter().take(20).collect::>(),"batches":projected_batches(w), + "sellingPoints":{"selected":w.creation_selected,"batches":projected_batches(w), "stale":brief_dirty(w) || w.creation["sellingPoints"]["stale"]==true},"plan":projected_plan(w)}) } @@ -726,8 +718,11 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u } if intent == "adopt_candidate" && !w.allow_apply { return Err("本轮原生操作尚未取得当前修订许可".into()); } let instruction = input.get("instruction").map_or(Ok(""), |v| v.as_str().ok_or("调整要求须为文本"))?; - let limit = if batch && w.pi_request_scope["productProduction"] == true { 2000 } else { 500 }; - if instruction.chars().count() > limit || instruction.chars().any(|ch| ch.is_control() && !matches!(ch, '\n' | '\r' | '\t')) || (intent != "generate_candidate" && !instruction.trim().is_empty()) { + let production = batch && w.pi_request_scope["productProduction"] == true; + if !production && instruction.chars().count() > 500 + || instruction.chars().any(|ch| ch.is_control() && !matches!(ch, '\n' | '\r' | '\t')) + || intent != "generate_candidate" && !instruction.trim().is_empty() + { return Err("调整要求无效".into()); } let output_id = output(w, input)?; diff --git a/docs/development/xiaoyi/implementation.md b/docs/development/xiaoyi/implementation.md index 54b5089f..21b24e1a 100644 --- a/docs/development/xiaoyi/implementation.md +++ b/docs/development/xiaoyi/implementation.md @@ -253,3 +253,32 @@ PhotoCraft 用正式文件独立导入了 5 张主图和 1 张 SKU,并按原 证据位于 `D:/AI Code/gongxiangp2/output/xiaoyi-harness-implementation-20261125/batch-08/`。Agent 套件 318 项通过,最终原生请求回归 39 项通过,见 `phase-d-regression.log` 与 `native-wire-regression.log`。另用顾家电脑桌正式主图发布映射的 5 张模板输入重复了 3 个断点场景,均通过,见 `desk-compaction-recovery.log`。本批使用本地模拟上游,未执行 98K 调用、新客户端构建、Photoshop 兼容与三类实际导出。 下一切片推进项目级目标所有权,并梳理正式 Skill 实际依赖的执行工具。 + +## 第九批 · 恢复 Pi 原生能力 + +### 一、Pi 会话与资源 + +| 能力 | 当前状态与依据 | 验证 | +| --- | --- | --- | +| 自动压缩与摘要 | 使用锁定的 Pi 1.5.2 默认设置,保留 20,000 token、预留 16,384 token。旧的字符门禁、压缩计划与分段恢复已从宿主删除 | 本地 SDK 阈值触发一个真实会话压缩记录,验证原始历史保留。模拟摘要服务限流验证 Pi 自己重试 | +| 自动重试 | 主会话使用 AgentSession,子代理使用 Pi 的 `retryAssistantCall`。默认 3 次、2 秒起。纯推理请求可以使用新编号,写入和生图仍核查原操作 | 中断的工具草稿未执行,Pi 自动重新发出纯推理请求。生图和画布原编号回归另见测试记录 | +| 思考与输出 | 按实际线路公布的枚举或思考对象结构启用。已核对 GPT‑6.1 Sol Responses 线路的 `low`、`medium`、`high`、`xhigh`、`max`。本轮检查的 Gemini 3.8 Flash、DeepSeek Flash 和 Claude Opus 5.5 线路未声明可用档位或明确的思考对象,客户端保持关闭。支持的线路可在小壹设置选档,交给 Pi 处理。未指定时沿用 Pi 会话设置。可省略输出上限的线路使用服务商默认 | 本地 Responses 回执验证选档、图片输入、流式函数调用和断流重试。实际电脑桌首条请求使用 Pi 默认中档,省略 `max_output_tokens`。公开契约见 `public-reasoning-contracts.json` | +| 历史与缓存 | 发送 Pi 会话原有历史,保留图片和原工具回执。去掉发送前的旧投影与缓存覆盖,压缩由 Pi 处理。策划回执把逐屏文字格和图位审核细节交给现有对应读取工具 | 本地请求捕获核对历史图片与完整回执。Pi 的 Anthropic 缓存标记回归保留 | +| Skill 与提示词 | 打开 Pi 原生 Skill 发现和提示词模板。已选企业 Skill 与本地资源合并。已发布版本仍独立记账 | 本地实测发现项目 `.pi` 下的 Skill 与提示词模板。主代理、子代理读取同版本企业 Skill 的回归 | +| 项目工具 | 七个工具使用 Pi 工厂,工作目录与会话账本分离。`read` 同时支持选定的只读 Skill。`bash` 使用本地 Docker,只挂载项目工作目录,记录启动、退出与取消。缺少 Docker Linux 引擎或本机 Bash 5.2 镜像时返回所缺条件 | 文件写读和越界拒绝通过。使用本机 Docker 通过项目读写、外部账本不可见、无网络路由和取消验证,见 `project-shell-acceptance.log` | + +### 二、输入限制、等待和模型校验 + +删除产品上下文与工作流的字符拒发,取消生产生图提示词与品牌视觉规则的指定截断。生产链路的 2,000 和 6,000 字数门槛改用实际生图线路声明。超出时在派发前报告线路上限与当前长度。画布写入等待终态、取消或连接关闭。文本流使用 Pi 传输设置,原生代理沿用原有 600 秒 HTTP 请求上限。整套的 45 分钟产品预算保持。 + +已验证 21 次写入及等待中取消。文案能力随可写状态返回。原生模型桥在一次进程会话内复用已校验线路,账户设置、路由或授权状态变化时失效。子代理各自的原生桥首次调用仍会核对线路。 + +### 三、PhotoCraft 原生命令 + +生产主代理开放 `native_catalog`、`native_call`、`native_reconcile`、`codemode`、`tool_search` 和项目工具。原生命令直接执行。制作态的命令白名单和 `type.edit` 改道已移除。已发布的模板范围在命令提交时按当前目标检查,缺少范围的模板默认允许,并在回执记录 `default-allowed`。原生查询无需写入许可。 + +### 四、实机基线和只读拆分 + +改造前的原生恢复版 `2a337a42` 使用顾家电脑桌正式模板 `GJ-DESK-DNZ0385` 和五张同款原图。本机界面一次启动。约 20.1 秒画布就绪,45.7 秒进入首条模型请求。实际 GPT‑6.1 Sol Responses 返回成功,读到了企业 Skill,写入多屏初稿,并取得三张 Sunburst 中画质候选。主会话 30 个完成回执,子调用 31 个完成回执。未观察到压缩,观察到一次原生重试。23 分钟后本机 Agent 关闭,原请求保留,无三类正式导出。原生读取 `document.inspect` 申请写许可被拒,直接原生命令成功回执为零。日志、截图和实际候选记录在 `D:/AI Code/gongxiangp2/output/xiaoyi-harness-implementation-20261125/batch-09/desk-acceptance/`。 + +只读拆分采用 Pi 1.5.2 的默认设置。制作主会话保留 Pi 的消息历史,商品资料和状态改为按需查询。读进度、查文案和候选、渲染画布无需创建制作回合。策划、分派及发起审核分别使用明确工具。同款模板有发布的变更范围才检查原生写命令的模板授权。生产验图改判、派发与返工决策仍需按顺序迁移和实机验收。适用边界见 `limits.md`。 diff --git a/docs/development/xiaoyi/limits.md b/docs/development/xiaoyi/limits.md new file mode 100644 index 00000000..14bc8f35 --- /dev/null +++ b/docs/development/xiaoyi/limits.md @@ -0,0 +1,9 @@ +# 小壹运行边界 + +| 限制范围 | Pi 已有机制 | 继续方式 | 移除条件 | +| --- | --- | --- | --- | +| `bash` 只挂载本项目工作目录 | Pi 提供执行、取消和输出接口。它的本机 Bash 默认继承主机文件权限 | 在本地 Docker 的项目挂载内直接运行。缺少引擎或 Bash 镜像时,回执说明缺少哪项 | 更换为能限定同一项目目录并保留执行记录的本地进程隔离 | +| PhotoCraft 写入以当前账户、项目和画布修订为准 | Pi 会话拥有自己的目录和会话历史,PhotoCraft 的文档身份和用户手改由客户端维护 | 读当前画布和修订后提交新操作。查询用原操作编号 | PhotoCraft 提供等价的原生项目绑定、原子修订比较和原操作查询 | +| 已发布的模板变更范围应用于当前原生写命令 | Pi 负责选择命令和参数。模板包决定本版本可改的原稿内容 | 读取模板发布的操作、原始图层和参数要求,再修改相应目标。没有发布范围时默认允许并登记回执 | 同版本模板移除声明,或 PhotoCraft 引擎在写入边界接管同一声明 | +| 付费生图按原编号核查 | Pi 会重试推理连接。生图是独立的付费作业,由客户端维护账本 | 用原编号查询,继续处理其他工作。明确失败后由 Agent 决定是否发起新图 | 生图连接提供等价的原号查询和幂等约束 | +| 成果导出必须有实际文件回执 | Pi 能调用导出工具,PhotoCraft 负责保存并校验文件 | 根据缺失文件、保存路径或写入错误修正后显式调用导出 | PhotoCraft 导出接口原生返回等价的完整性回执 |