diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index b749967c..e1311cbd 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -14,15 +14,14 @@ import { productionTools, callProductionTool, closeProductionTurn, runPiProducti 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'; -import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, normalizeContext, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat'; +import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat'; import { atomic, digest } from './store.mjs'; import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs'; import { parseReceipt } from './receipt.mjs'; import { auditResponse, InvalidToolReply } from './response-audit.mjs'; import { requestPurpose } from './request-purpose.mjs'; -import { taskFor } from './rule-context.mjs'; import { productContext } from './project-context.mjs'; -import { imageProgressQuestion, readImageProgress, workflowContext, workflowResult } from './workflow-context.mjs'; +import { workflowContext, workflowResult } from './workflow-context.mjs'; import { EnterpriseContext } from './enterprise-context.mjs'; import { openEnterpriseSkills } from './enterprise-skill-resources.mjs'; import { projectTools } from './project-tools.mjs'; @@ -37,11 +36,11 @@ import { PHOTOCRAFT_NAMESPACE, PHOTOCRAFT_NATIVE_TOOL_NAMES, createPhotoCraftExt const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文,能够与用户连贯讨论、回答问题、解释原因、提出并比较方案。可以直接自然语言回答;不需要工具时不要调用工具,不把每次对话都当作执行任务。 需要用户选择、确认或补充关键资料时使用ask_user,以原生选项、确认或输入卡片等待回复,再按回复继续。用户明确要求交互选择时不要仅把选项写在正文里。多选使用multi_select;长文本修改使用editor。用户取消表示未决定,不能擅自代选或把取消当授权。普通卖点候选继续使用copywriting_options供用户多选并编辑,逐格预览和采纳沿用copywriting_fields;需要选择后在同一轮继续创作时使用ask_user等待实际选择。 -先看当前注入的产品资料和待确认项。用户要求查看画布时可以只读核对;只有明确要求修改时才能写入。讨论、解释、建议不自动改图。实际写工具会向本机申请当前版本的写许可;未授权或用户接手时不再修改。 -只信当前注入的店铺/品类/品牌规则,不沿用另一店铺或旧规则;品牌规范不是产品参数的证据。 +需要商品资料或待确认项时用 context_read 或 workflow_read 查看。用户要求查看画布时可以只读核对;只有明确要求修改时才能写入。讨论、解释、建议不自动改图。实际写工具会向本机申请当前版本的写许可;未授权或用户接手时不再修改。 +使用 context_read 读取当前店铺、品类和品牌规则,不沿用另一店铺或旧规则;品牌规范不是产品参数的证据。 用户新确认的信息覆盖旧信息,缺失事实写待确认,不编造认证、材质、性能。 为图位生成或修改候选时,产品颜色由客户端按目标输出类型与 SKU 注入。SKU 图包含全部已录入的 SKU 颜色,详情图和主图只使用产品资料为对应图类选定的 SKU 范围。instructions只描述本次场景与修改要求,不能从旧候选、模板或场景图推断并覆盖产品颜色。 -当前产品资料与当前规则注入是权威。历史对话中的旧产品、旧店铺或旧规则只作讨论历史,不能覆盖当前绑定;未配置规则时可以讨论通用方案,明确不冒充已有品牌规范。 +以工具读到的当前产品资料和规则为依据。历史对话中的旧产品、旧店铺或旧规则只作讨论历史,不能覆盖当前绑定;未配置规则时可以讨论通用方案,明确不冒充已有品牌规范。 currentWorkflow.objective说明当前项目总目标。用户创建项目、填写资料并选择模板后,总目标就是按所选模板完成该产品的图文内容。用户问目标或下一步时,结合当前产品、品牌品类、模板和真实进度回答,不因未选图层、未选卖点或没有新指令而说不知道目标。总目标与本轮执行范围分别判断;仅讨论不自动执行,明确要求“生成第一张图”时读取当前输出的图位顺序,生成首个图片格候选供预览采纳。 汇报生成与采纳进度时以currentWorkflow.slots中的当前status和selectedCandidateId为准,failed表示此候选失败,unknown才是待核查,不能用历史对话的“结果未知”或“已接手”覆盖实时状态。slots是分页结果,超出当前页时用workflow_read继续读取,不按当前页推断整项目已经完成或失败。canvasFirst流程不要求先完成旧的事实分析、卖点和页面方案向导,不能把这些旧阶段的空状态当成当前流程的阻塞。 卖点文案可以直接在当前画布协作,不要求用户先走旧分析、卖点、页面方案向导。生成产品卖点时先给可修改的消费者成稿,缺失依据单列待确认,不把内部编号或免责声明写入成稿。为模板文字框生成或修改文案时,先canvas_read读取本轮引用的真实文字层;按templateField中的页面、fieldId、用途及maxChars/maxLines组织每格内容,实际回填始终使用nativeLayerId,不按列表序号、同名标题或生成返回顺序匹配。没有模板约束的文字层沿用实时文字框尺寸和样式,不编造字数限制。只改用户指定文字,保留字号、字体、位置、其他格子和图片;多格读取全部引用文字层后,使用copywriting_fields提交每格候选;用户在原生候选列表中逐格修改、预览和采纳,用户采纳后才算回填。已有文案修改要读取原文并保留未要求改变的事实。 @@ -77,22 +76,9 @@ function toolsFor(host) { const make = (name, description, parameters, execute, format = plain) => ({ name, label: name, description, parameters:JSON.parse(JSON.stringify(parameters)), executionMode: 'sequential', execute: async (_id, args, signal, _update, ctx) => { const epoch = host.turnEpoch; if (host.compromised) throw Error('本地会话锁失效,已停止工具执行'); - if (name !== 'workflow_read' && typeof host.canvas?.workflowRead === 'function') await host.readWorkflow({ section: 'overview' }); + if (name === 'memory_set' && host.canvas?.workflowRead) await host.readWorkflow({section:'overview'}); if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工具不会继续执行'); - if (name === 'memory_search') { - const key = digest(args), count = (host.recallCounts.get(key) || 0) + 1; - host.recallCounts.set(key, count); - if (count > 1) host.recallRepeats++; - } const value = await execute(args, signal, ctx); - if (name === 'canvas_read' && host.expectCopyPreview && value?.context?.layers?.some(layer => layer.id === host.copyPreviewTarget)) { - host.copyPreviewRevision = value.revision; host.requiredTool = 'canvas_preview'; - } - if(name==='canvas_read'&&host.expectCopyFields){ - if(host.copyFieldsRevision!==value.revision){host.copyFieldsRead=new Set();host.copyFieldsRevision=value.revision;} - for(const layer of value.context?.layers||[])if(host.copyFieldsTargets.includes(layer.id))host.copyFieldsRead.add(layer.id); - if(host.copyFieldsTargets.every(id=>host.copyFieldsRead.has(id)))host.requiredTool='copywriting_fields'; - } return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value); } }); const string = maxLength => Type.String({ maxLength }); @@ -109,15 +95,9 @@ function toolsFor(host) { }, {additionalProperties:false}), ({query,toolCallId,offset=0}) => toolCallId ? host.store.readToolReceipt(host.manager,toolCallId,offset) : host.store.search(query,host.manager)), - make('canvas_read', '本轮为多格文案预览时,固定读取全部本轮引用文字格,查询参数仅用于其他场景。先使用 mode=summary 查看真实组和画板,或用 filter 按名称、文本检索;重名时使用真实 screenId 指定组,需要细节时用真实 layer ID。仅在确有需要时用 offset 翻页,勿全量遍历。revision来自实时读取;writeBlocked=true 表示本轮不可写。', canvasReadParameters, async args => { - let {layer,screen,screenId,mode,filter,maxDepth,offset=0}=canvasReadQuery(args); + make('canvas_read', '先使用 mode=summary 查看真实组和画板,或用 filter 按名称、文本检索;重名时使用真实 screenId 指定组,需要细节时用真实 layer ID。仅在确有需要时用 offset 翻页,勿全量遍历。revision来自实时读取;writeBlocked=true 表示本轮不可写。', canvasReadParameters, async args => { + const {layer,screen,screenId,mode,filter,maxDepth,offset=0}=canvasReadQuery(args); if (!host.canvas) return { available: false }; - if (host.expectCopyPreview && layer === undefined && screen === undefined && screenId === undefined && mode === undefined && filter === undefined && maxDepth === undefined && offset === 0) layer = host.copyPreviewTarget; - if(host.expectCopyFields&&typeof host.canvas.readCanvas==='function'){ - const reads=[];for(const id of host.copyFieldsTargets)reads.push(await host.canvas.readCanvas({layer:id})); - const first=reads[0];if(reads.some(value=>value.revision!==first.revision||value.context?.id!==first.context?.id||value.writeBlocked))throw Error('读取期间画布已变化,请重新读取本次文字格'); - return {...first,context:{...first.context,layers:reads.flatMap(value=>value.context.layers),matchedLayers:reads.length,hasMore:false,nextOffset:null}}; - } if (typeof host.canvas.readCanvas === 'function') return host.canvas.readCanvas(layer!==undefined?{layer}:{ ...(screen === undefined ? {} : { screen }), ...(screenId === undefined ? {} : {screenId}), ...(mode === undefined ? {} : {mode}), ...(filter === undefined ? {} : {filter}), ...(maxDepth === undefined ? {} : {maxDepth}), offset }); if (mode === 'summary' || filter !== undefined || maxDepth !== undefined || screenId !== undefined) throw Error('当前客户端不支持画布摘要或检索,请更新完整运行组件'); const state = await host.canvas.read(), context = state.context; @@ -186,7 +166,6 @@ function toolsFor(host) { Type.Object({fieldId:Type.String({minLength:1,maxLength:128})},{additionalProperties:false}), field => host.canvas.readTemplateImage(field.fieldId), ({images = [], ...source}) => { - if (source.source === 'pinnedTemplateOriginal' && images.length) host.templateImageRead = true; return {content:[{type:'text',text:JSON.stringify(source)},...images],details:source}; })); } @@ -216,14 +195,13 @@ function toolsFor(host) { return {optionsId:value.optionsId,count:value.count,awaitingSelection:true,applied:false}; }),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'}); if(typeof host.canvas?.copyFields==='function')active.push({...make('copywriting_fields','按本轮引用的每个真实文字格分别提交候选文案。先canvas_read读取文字格、用途和字数行数限制;items中每个layer只能出现一次,覆盖全部引用文字格。宿主在提交前复核每格并绑定真实版本,无需填写revision。用户逐格预览和采纳,工具不会写入画布。',Type.Object({revision:Type.Optional(Type.Integer({minimum:0})),items:Type.Array(Type.Object({layer:Type.Integer({minimum:1}),text:Type.String({minLength:1,maxLength:3000})},{additionalProperties:false}),{minItems:2,maxItems:20})},{additionalProperties:false}),async (args,signal)=>{ - if(!host.expectCopyFields||args.items.length!==host.copyFieldsTargets.length||new Set(args.items.map(item=>item.layer)).size!==args.items.length||args.items.some(item=>!host.copyFieldsTargets.includes(item.layer)))throw Error('候选文案须与本轮引用文字格一一对应'); + if(args.items.length!==host.copyFieldsTargets.length||new Set(args.items.map(item=>item.layer)).size!==args.items.length||args.items.some(item=>!host.copyFieldsTargets.includes(item.layer)))throw Error('候选文案须与本轮引用文字格一一对应'); const reads=[];for(const layer of host.copyFieldsTargets)reads.push(await previewTarget(host,layer,signal)); const revision=reads[0].revision;if(reads.some(read=>read.revision!==revision))throw Error('读取期间画布已变化,请重新读取本次文字格'); const value=await host.canvas.copyFields({...args,revision});if(!value?.optionsId||value.run!==host.canvas.run||value.documentId!==host.canvas.documentId||value.count!==args.items.length)throw Error('逐格文案回执不一致');host.copyFieldsReceipt=value.optionsId;return {...value,applied:false}; }),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'}); if (typeof host.canvas?.preview === 'function') active.push({ ...make('canvas_preview', '在原生界面预览当前图层修改,等用户采纳才应用。宿主先读取真实目标并绑定当前版本,无需填写revision。type.edit替换文案须传params.text;超出模板文字格限制时由原生输入等待用户缩短或取消,不放宽模板。只传本命令支持的参数,其他命令可先查native_catalog。保留未要求改变的字体、字号、位置和其他图层。', previewParameters, async (args, signal, ctx) => { if (host.canvasNotificationsDetached || host.canvasWritesStopped) throw Error('原项目已切换或用户已接手,未生成预览'); - if (host.expectCopyPreview && args.params.layer !== host.copyPreviewTarget) throw Error('预览目标必须是本轮引用的文字格'); let read=await previewTarget(host,args.params.layer,signal); let params={...args.params}; if(args.command==='type.edit'&&typeof params.text==='string') { @@ -241,7 +219,6 @@ function toolsFor(host) { if(confirmed)read=await previewTarget(host,args.params.layer,signal); } const request={...args,params,revision:read.revision}; - host.copyPreviewRevision=read.revision; const value = await host.canvas.preview(request); if (!value || typeof value.previewId !== 'string' || !value.previewId || value.run !== host.canvas.run || value.documentId !== host.canvas.documentId || value.revision !== request.revision || value.command !== args.command || value.target?.id !== args.params.layer) throw Error('预览回执身份不一致,未确认预览'); await host.store.appendEvent({type:'canvas_preview_bound',layer:args.params.layer,revision:read.revision,requestedRevision:args.revision??null}); @@ -298,7 +275,7 @@ export class DetailPiAgent { if (!['native-tools', 'structured-json'].includes(protocolMode)) throw Error('工具协议模式无效'); if (callBudget !== undefined && (!Number.isSafeInteger(callBudget) || callBudget < 1)) throw Error('单轮模型调用预算无效'); const host = new DetailPiAgent(); - Object.assign(host, { store, broker, canvas, onEvent, productionGoal, protocolMode, callBudget, turnEpoch: 0, rounds: 0, inflight: null, text: '', recallCounts: new Map(), recallRepeats: 0 }); + Object.assign(host, { store, broker, canvas, onEvent, productionGoal, protocolMode, callBudget, turnEpoch: 0, rounds: 0, inflight: null, text: '' }); try { host.releaseLock = lockfile.lockSync(store.root, { stale: 15000, update: 4000, retries: 0, onCompromised: error => { host.compromised = error; host.session?.agent.abort(); } }); } catch { throw Error('此项目已有本地Agent在运行,请等待当前任务结束;未发起新请求'); } try { @@ -379,6 +356,7 @@ export class DetailPiAgent { try { options.signal?.throwIfAborted(); if (host.compromised) throw Error('本地会话锁失效,已停止模型调用'); + if (host.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则'); if (host.productionGoal?.deadline * 1000 <= Date.now()) throw Error('整套制作已达到时限,保留当前结果'); const liveCanvas = host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null; if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目'); @@ -391,36 +369,18 @@ export class DetailPiAgent { output.push({ type: 'done', reason: 'stop', message }); output.end(message); return; } - if (!host.compacting && !host.productionGoal && host.recallRepeats >= 2) throw Error('模型重复检索同一证据,已停止继续调用;历史和结果已保留'); const completeStage=!host.compacting&&host.goalStageResult?.production?.complete===true; - if (!completeStage && !host.productionGoal && liveCanvas && typeof host.canvas.workflowRead === 'function') await host.readWorkflow({ section: host.task !== 'chat' && host.currentWorkflow?.canvasFirst ? 'slots' : 'overview' }); - if (completeStage || host.imageProgressTurn && !host.compacting && liveCanvas) { - const text = completeStage ? host.goalStageResult.text - : await readImageProgress(args => host.canvas.workflowRead(args), host.currentWorkflow); - await store.appendEvent({ type: completeStage?'production_stage_submitted':'local_image_progress', modelCallSkipped: true }); + if (completeStage) { + const text = host.goalStageResult.text; + await store.appendEvent({ type:'production_stage_submitted', modelCallSkipped: true }); const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } }; output.push({ type: 'start', partial: message }); - output.push({ type: 'done', reason: 'stop', message }); - output.end(message); + output.push({ type: 'done', reason: 'stop', message }); output.end(message); return; } host.currentCanvas = liveCanvas?.context; - 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 wireContext = encoded ? jsonToolContext(context) : context; const inputChars = contextTextLength(wireContext); if (!host.compacting) await host.updateContextUsage(null, 'running'); host.rounds++; @@ -518,7 +478,7 @@ export class DetailPiAgent { 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 content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id); const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' }; if (!partial) output.push({ type: 'start', partial: message }); if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message }); @@ -751,7 +711,7 @@ export class DetailPiAgent { } const changed = thinking !== host.thinking; host.thinking = thinking; - if (canvas && (!host.templateOriginal || host.templateImageRead)) { + if (canvas) { const meter = outputMeter.update(event, thinking); if (text || changed) { await host.notifyCanvas('delta', host.presentation.text.slice(-65000), changed || meter ? thinking : undefined, undefined, meter); @@ -762,7 +722,7 @@ export class DetailPiAgent { if (text) await onEvent({ type: 'text_delta', delta: text }); } if (event.type === 'message_end' && event.message.role === 'assistant' && !host.compacting - && canvas && (!host.templateOriginal || host.templateImageRead)) { + && canvas) { const meter = outputMeter.update(event, false); if (host.thinking === true || meter) { host.thinking = false; @@ -810,7 +770,6 @@ export class DetailPiAgent { this.currentWorkflow = latest.workflow; this.productEvidence = latest.product; if (this.productionGoal && args.section === 'overview') this.productionTemplate = snapshot.template; - if (this.task && this.task !== 'chat' && !this.compacting && !this.wholeDetailActive) this.knowledgeContext = await this.readEnterpriseRules(); return latest.workflow; } async readEnterpriseRules() { @@ -823,7 +782,10 @@ export class DetailPiAgent { templateId:template.id,releaseId:template.version,turn:this.turnEpoch}); } async modelContext(options = {}, {loadKnowledge = false} = {}) { - const value=await this.store.modelContext({task:this.task || 'chat',workflow:this.currentWorkflow,canvas:this.currentCanvas,...options}); + if (this.canvas?.workflowRead) await this.readWorkflow({section:'overview'}); + const value=await this.store.modelContext({workflow:this.currentWorkflow,canvas:this.currentCanvas,...options}); + value.currentProduct=this.productEvidence; + if (this.currentWorkflow) value.currentWorkflow=this.currentWorkflow; if (this.productionSkills && loadKnowledge) { const {knowledge,documents}=this.productionSkills; value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]}; @@ -866,10 +828,6 @@ export class DetailPiAgent { if (this.workflowStopReason) reply += `\n\n后续操作已停止。${this.workflowStopReason}`; return reply; } - projectModelContext(context, injected) { - return normalizeContext({...context,messages:[...context.messages, - {role:'system',content:'当前项目与画布事实:\n' + JSON.stringify(injected),timestamp:0}]}); - } async updateContextUsage(receipt = null, phase = 'ready') { this.contextUsage = contextSnapshot(this.store.identity, this.info.model, this.session, this.contextUsage, receipt, phase); if (phase === 'ready') { @@ -884,7 +842,7 @@ export class DetailPiAgent { async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false } = {}) { if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求'); if ((await this.store.get('recovered-tools.json', [])).some(t => t.phase === 'review')) throw Error('原请求的工具建议已取回,需先核对画布;不会重跑工具或模型'); - if (typeof text !== 'string' || !text.trim() || text.length > 6000) throw Error('请输入6000字以内的要求'); + if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求'); const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info); this.firstTurnBrokerInfo = null; if (latest.accountScope !== this.store.identity.scope) throw Error('账户与项目不一致;原草稿已保留'); @@ -901,21 +859,10 @@ export class DetailPiAgent { if (requiredTool && !this.session.getActiveToolNames().includes(requiredTool)) throw Error('指定工具未开放'); this.requiredTool = null; this.goalStageResult=null; - this.imageProgressTurn = !this.productionGoal && !requiredTool && !referenceContent.length && typeof this.canvas?.workflowRead === 'function' && imageProgressQuestion(text); - this.task = this.productionGoal || this.imageProgressTurn ? 'chat' : taskFor(text); - this.templateOriginal = /模板.{0,12}(?:原图|预置|原稿)|原稿.{0,8}(?:图|视角)/u.test(text) - && /看|视角|构图|是什么|读|描述|确认|核对/u.test(text); - this.templateImageRead = false; - const copyPreviewRequested = ['copy','canvas'].includes(this.task) && text.includes('预览') && !/(?:不要|不用|无需|不需要|不做|不生成)预览/.test(text); - this.previewReceipt = null; this.previewCancelled=false; this.expectCopyPreview = false; this.copyPreviewRevision = null; this.copyPreviewTarget = null; - this.expectCopyFields=false;this.copyFieldsReceipt=null;this.copyFieldsTargets=[];this.copyFieldsRead=new Set();this.copyFieldsRevision=null; - this.copyOptionsReceipt = null; - this.expectCopyOptions = this.task === 'copy' && /卖点/.test(text) && /生成|写|给|提供/.test(text) && !text.includes('预览') && !!this.session.getToolDefinition('copywriting_options'); - if (this.expectCopyOptions) this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'copywriting_options'])]); - if (text.includes('预览') && this.session.getToolDefinition('canvas_preview')) { - this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(), 'canvas_preview'])]); - } - this.rounds = 0; this.text = ''; this.presentation = new StreamPresentation(); this.thinking = undefined; this.recallCounts.clear(); this.recallRepeats = 0; + this.task = 'chat'; + this.previewReceipt = null; this.previewCancelled = false; + this.copyFieldsTargets = []; + this.rounds = 0; this.text = ''; this.presentation = new StreamPresentation(); this.thinking = undefined; this.turnEpoch = (this.turnEpoch || 0) + 1; this.canvasWriteRequested = false; this.canvasWritesStopped = false; this.workflowStopReason = null; this.generatedCandidates = new Map(); @@ -938,11 +885,8 @@ export class DetailPiAgent { const begun = await this.canvas.begin(text); this.nativeUI?.start(begun?.editorText || ''); const references = frozenReferences(begun?.context); - this.expectCopyPreview = copyPreviewRequested && references?.length === 1 && references[0].layerKind === 'Type'; - if (this.expectCopyPreview) {this.copyPreviewTarget=references[0].nativeLayerId;this.requiredTool ??= 'canvas_read';} - this.expectCopyFields=copyPreviewRequested&&references?.length>1&&references.length<=20&&references.every(ref=>ref.layerKind==='Type'&&ref.component==='layer'); - if(this.expectCopyFields){if(!this.session.getToolDefinition('copywriting_fields'))throw Error('请更新完整客户端以使用逐格文案');this.copyFieldsTargets=references.map(ref=>ref.nativeLayerId);this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'copywriting_fields'])]);this.requiredTool ??='canvas_read';} - if (this.expectCopyOptions) this.requiredTool ??= 'copywriting_options'; + this.copyFieldsTargets = (references??[]).filter(ref=>ref.layerKind==='Type'&&ref.component==='layer') + .map(ref=>ref.nativeLayerId); this.activityScope = activityScope(this.store.identity, this.canvas, begun); this.heartbeat = setInterval(() => { this.canvas.read().then(state => { if(this.nativeUI && typeof state?.editorText==='string')this.nativeUI.editorText=state.editorText; }).catch(() => {}); }, 2000); this.heartbeat.unref(); @@ -973,18 +917,14 @@ export class DetailPiAgent { } if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议'); const resultText = useStageReceipt ? this.goalStageResult.text : - this.generatedCandidateReply() ?? (this.templateOriginal && !this.templateImageRead - ? '模板原图尚未读取,暂时无法确认视角。可以引用画布里的具体图位,再继续核对。' - : this.previewCancelled&&!this.previewReceipt - ? '已取消本次预览,没有应用这项修改。' : presentText(this.session.getLastAssistantText() || this.goalStageResult?.text || '')); + (this.previewCancelled&&!this.previewReceipt + ? '已取消本次预览,没有应用这项修改。' + : presentText(this.session.getLastAssistantText() || this.goalStageResult?.text || '')); const textResult=this.productionGoal ? stripProductionToolText(resultText).trim()||this.goalStageResult?.text||'' : resultText; if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留'); - if (this.expectCopyPreview && !this.previewReceipt && !this.previewCancelled) throw Error('本轮尚未生成可采纳的修改预览;文案候选和工具结果已保留'); - if(this.expectCopyFields&&!this.copyFieldsReceipt)throw Error('本轮尚未生成与文字格对应的候选文案;原文和画布未改变'); - if (this.expectCopyOptions && !this.copyOptionsReceipt) throw Error('本轮尚未生成可选择的卖点;文案与工具结果已保留'); - if (this.canvas?.delta && this.presentation && (!this.templateOriginal || this.templateImageRead)) { + if (this.canvas?.delta && this.presentation) { await this.notifyCanvas('delta', this.presentation.text.slice(-65000), this.thinking === true ? false : undefined); } await this.updateContextUsage(null, 'ready'); diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index df076227..e516aec3 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -1,4 +1,3 @@ -import { modelRoleFor } from './rule-context.mjs'; import { createInterface } from 'node:readline'; import path from 'node:path'; import { assertPiNodeVersion } from './runtime-policy.mjs'; @@ -109,7 +108,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { signal?.throwIfAborted(); signal?.addEventListener('abort',abort,{once:true}); const [{DetailPiAgent},{Native98kBroker},{ProjectStore,atomic},{StdioCanvas},{resolveRules}] = await Promise.all([import('./agent.mjs'),import('./native-bridge.mjs'),import('./store.mjs'),import('./stdio-canvas.mjs'),import('./rules.mjs')]); - const modelRole=config.mode==='recover'?config.modelRole||'chat':config.wholeDetail?'detail':modelRoleFor(config.text); + const modelRole=config.mode==='recover'?config.modelRole||'chat':config.wholeDetail?'detail':'chat'; const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole}; broker=sharedBroker??new Native98kBroker(bindingConfig); broker.bind(bindingConfig); diff --git a/apps/detail-agent-pi/src/rule-context.mjs b/apps/detail-agent-pi/src/rule-context.mjs index eacc8af6..d009fd48 100644 --- a/apps/detail-agent-pi/src/rule-context.mjs +++ b/apps/detail-agent-pi/src/rule-context.mjs @@ -1,24 +1,5 @@ import { FONT_FALLBACKS } from './rules.mjs'; -/** Project snapshots are evidence, not a prompt to copy wholesale on every turn. */ -export function taskFor(text = '') { - // Negative instructions must not load the very subsystem the user excluded. - text = text.replace(/不(?:要|用|需要)?(?:修改|操作|改变|改动|编辑|改)画布/g, '').replace(/不要(?:生图|生成图片)/g, ''); - if (/大纲|方案|多屏|六图|分屏|结构规划/.test(text)) return 'plan'; - const request=text.split(/\n|[。;]/,1)[0]; - const imageRequested = /生图|精修|(?:生成|制作|修改|调整|替换|重做).{0,10}(?:图片|图像|场景图|主图|张图)|(?:生成|修改).{0,6}场景/.test(request); - if (/文案|卖点|措辞|文字框|文字格/.test(request) && !imageRequested) return 'copy'; - if (imageRequested || /生图|场景|精修|光线|背景/.test(text)) return 'image'; - if (/(?:修改|调整|设置|移动).{0,16}(?:画布|图层|字号|字体|排版)|文字层|右移|左移|向.{0,4}移动|标题改|改为/.test(text)) return 'canvas'; - if (/文案|卖点|标题|措辞|改写|润色|重写|精简|改短|(?:文字|文本).{0,12}(?:改为|改成|替换)/.test(text)) return 'copy'; - return 'chat'; -} - -export function modelRoleFor(text='') { - const task=taskFor(text); - return task==='copy'||task==='plan'||(task==='canvas'&&/文案|卖点|措辞|改写|润色|重写|精简|改短|标题改|(?:文字|文本).{0,12}(?:改为|改成|替换)/.test(text))?'copy':'chat'; -} - function sections(text) { return text.split(/(?=^#{1,4} )/m).map(s => s.trim()).filter(Boolean); } diff --git a/apps/detail-agent-pi/src/workflow-context.mjs b/apps/detail-agent-pi/src/workflow-context.mjs index 265abd07..7049396c 100644 --- a/apps/detail-agent-pi/src/workflow-context.mjs +++ b/apps/detail-agent-pi/src/workflow-context.mjs @@ -6,34 +6,26 @@ fields.add('screenCount'); fields.add('persistence'); for (const name of ['template','enterprise','releaseId','templateVersion']) fields.add(name); for (const name of ['canvasFirst','subject','productVariantId','variantId','variantLabel','candidateId','parentCandidateId','adoptedCandidateId','pageId','nativeLayerId','taskId','previewId','operationId','operation','workflow']) fields.add(name); -const clip = (value, max) => Array.from(value).slice(0, max).join(''); /** A small data-only view. Pixels, paths, model prompts and private task bodies * never enter the transcript, even if a future native reply includes them. */ export function workflowResult(value) { let omitted = 0; - const project = (item, depth = 0, key = '') => { - if (depth > 8) { omitted++; return null; } + const project = item => { if (item === null || typeof item === 'boolean') return item; if (typeof item === 'number') return Number.isFinite(item) ? item : null; if (typeof item === 'string') { if (blockedValue.test(item)) { omitted++; return '[已省略私有资源]'; } - const limit = key === 'instruction' ? 500 : ['text', 'body', 'message', 'invalidReason'].includes(key) ? 260 : 160; - if (Array.from(item).length > limit) omitted++; - return clip(item, limit); - } - if (Array.isArray(item)) { - omitted += Math.max(0, item.length - 20); - return item.slice(0, 20).map(child => project(child, depth + 1, key)); + return item; } + if (Array.isArray(item)) return item.map(project); if (!item || typeof item !== 'object') return null; return Object.fromEntries(Object.entries(item).filter(([name]) => { if (fields.has(name)) return true; - // productEvidence has its own identity-checked projection and is injected - // once as currentProduct, rather than duplicated into currentWorkflow. + // Product evidence is read separately through context_read. if (name !== 'productEvidence') omitted++; return false; - }).map(([name, child]) => [name, project(child, depth + 1, name)])); + }).map(([name, child]) => [name, project(child)])); }; if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('工作流结果无效,未继续处理'); const result = project(value); @@ -41,26 +33,6 @@ export function workflowResult(value) { if (result.template.screenCount) result.screenCount=result.template.screenCount; if (result.template.width) result.width=result.template.width; } - const arrays = []; - const strings = []; - const visit = item => { - if (Array.isArray(item)) { arrays.push(item); item.forEach(visit); } - else if (item && typeof item === 'object') for (const [key, child] of Object.entries(item)) { - if (typeof child === 'string' && child.length > 80) strings.push([item, key]); - else visit(child); - } - }; - visit(result); - // Keep identity/version fields intact. Omission is explicit and never changes - // the immutable raw SDK transcript or the native project itself. - while (JSON.stringify(result).length > 7600 && arrays.some(items => items.length)) { - arrays.sort((a, b) => b.length - a.length); - arrays[0].pop(); omitted++; - } - for (const [item, key] of strings) { - if (JSON.stringify(result).length <= 7600) break; - item[key] = clip(item[key], 80); omitted++; - } if (omitted) result.omitted = { entries: omitted }; return result; } @@ -78,37 +50,3 @@ export function workflowContext(value, identity) { }; return { workflow, product }; } - -export function imageProgressQuestion(text) { - const question = text.trim().replace(/[。?!?s]+$/u, ''); - return /^(?:请问|帮我看看)?(?:这套详情(?:页|图)|这套图)?(?:现在|目前|后面|接下来)?(?:还(?:有|剩)|剩下|剩余)(?:几|多少)(?:张(?:图|图片)?|个(?:图位|图片|格子))(?:还)?(?:没(?:有)?(?:完成|做完|做|回填)|未(?:完成|回填))(?:的|了|啊|呢)?$/u.test(question) - || /^(?:请问|帮我看看)?(?:这套详情(?:页|图)|这套图)?(?:现在|目前|后面)?(?:还(?:有|剩)|剩下)(?:几|多少)(?:张(?:图|图片)?|个(?:图位|格子))(?:了|呢)?$/u.test(question); -} - -export async function readImageProgress(readPage, overview) { - if (!overview?.available || !overview.canvasFirst || !overview.outputId) return '当前画布暂无可核对的图位。'; - const {outputId, productVariantId, version} = overview; - const seen = new Set(); - let total, applied = 0, ready = 0, pending = 0; - do { - const page = await readPage({section: 'slots', outputId, offset: seen.size}); - total ??= page?.totalSlots; - if (!page?.available || page.outputId !== outputId || page.version !== version || - page.productVariantId !== productVariantId || !Number.isSafeInteger(total) || - page.totalSlots !== total || !Array.isArray(page.slots) || !page.slots.length && seen.size < total) { - return '图位状态正在更新,暂时无法核对完整数量。'; - } - for (const slot of page.slots) { - if (!slot.id || seen.has(slot.id)) return '图位状态正在更新,暂时无法核对完整数量。'; - seen.add(slot.id); - if (slot.selectedCandidateId) applied++; - else if (slot.candidates?.some(candidate => candidate.status === 'complete')) ready++; - else if (slot.candidates?.some(candidate => ['unknown','running','dispatched','prepared'].includes(candidate.status))) pending++; - } - } while (seen.size < total); - if (seen.size !== total) return '图位状态正在更新,暂时无法核对完整数量。'; - if (!total) return '当前画布暂无可核对的图位。'; - const remaining = total - applied; - return `当前画布有 ${total} 个图位,已回填 ${applied} 个,还有 ${remaining} 个未回填。` - + (remaining ? `其中 ${ready} 个已有候选,${pending} 个正在生成或待核查,${remaining - ready - pending} 个暂无可用候选。` : ''); -} diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index 3764f1d0..009102c7 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -21,9 +21,10 @@ function canvas(){ async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();}, async delta(){},async activity(){},async end(){this.allowed=false;}}; } -async function fixture(reply,{shop='unconfigured',reuseOpeningInfo=false}={}){ +async function fixture(reply,{shop='unconfigured',reuseOpeningInfo=false,workflowRead}={}){ const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project},store=await ProjectStore.open(root,identity,binding(shop),{continuous:true}); const requests=[],native=canvas(),events=[]; + if(workflowRead)native.workflowRead=workflowRead; const broker={info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[]}),round(){const id=randomUUID();return {id,fetch:async(_url,init)=>{const payload=JSON.parse(init.body);requests.push(payload);const response=reply(payload,requests.length,native);return response instanceof Response?response:new Response(response,{headers:{'content-type':'text/event-stream'}});},finish:async()=>({phase:'complete'})};}}; let infoCalls=0; const readInfo=broker.info; @@ -42,8 +43,7 @@ test('three plain native-wire turns discuss product facts without JSON or a canv for(const payload of x.requests){ assert.equal(payload.tool_choice,'auto');assert.equal(payload.response_format,undefined); const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n'); - assert.equal(system.split('"currentProduct":').length-1,1); - assert.ok(system.includes('尺寸、承重、木种未确认'));assert.ok(system.includes('胡桃色'));assert.ok(system.includes('未配置')); + assert.doesNotMatch(system,/当前项目与画布事实|测试电脑桌|胡桃色/u); assert.ok(!system.includes('不得重复注入的大段生图提示'));assert.ok(!system.includes('mustNotDuplicate')); } }finally{await x.close();} @@ -64,10 +64,10 @@ test('an enterprise project supports immediate conversation and fetches rules on try{ await x.host.prompt('你好,知道现在在做什么吗?'); assert.equal(knowledgeReads,0); - assert.ok(JSON.stringify(x.requests[0].messages).includes('测试电脑桌')); + assert.ok(!JSON.stringify(x.requests[0].messages).includes('测试电脑桌')); await x.host.prompt('请查一下这个模板的规则来源'); assert.equal(knowledgeReads,1); - assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance))); + assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance)&&m.content.includes('测试电脑桌'))); await x.host.prompt('谢谢,继续聊一下'); assert.equal(knowledgeReads,1); assert.ok(JSON.stringify(x.requests[3].messages).includes(provenance)); @@ -107,7 +107,7 @@ test('project conversation survives restart and first rule binding while old-dom const payload=x.requests.at(-1),all=JSON.stringify(payload.messages); assert.ok(all.includes('继续比较刚才的方案'));assert.ok(all.includes('颜色是胡桃色')); const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n'); - assert.ok(system.includes('米白'));assert.ok(system.includes('configured-shop专属规则')); + assert.doesNotMatch(system,/米白|configured-shop专属规则/u); assert.ok(!system.includes('"evidence":"颜色是胡桃色"'),'old memory cannot become current confirmed memory on a rule change'); }finally{await x.close();} }); @@ -242,7 +242,7 @@ test('a canvas click during discussion blocks writes but does not cut off a read assert.equal(x.requests.length,2);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0); assert.ok(x.native.writeBlocked);assert.ok(x.events.some(e=>e.type==='text_delta'&&e.delta.includes('完整讨论'))); const system=x.requests[1].messages.filter(m=>m.role==='system').map(m=>m.content).join('\n'); - assert.ok(system.includes('"writeBlocked":true')); + assert.doesNotMatch(system,/当前项目与画布事实/u); assert.ok(!x.host.session.messages.some(m=>m.role==='assistant'&&m.content?.some(c=>c.type==='text'&&c.text==='本机:已接手,剩余画布操作已停止。'))); }finally{await x.close();} }); @@ -340,29 +340,29 @@ test('legacy migration rejects a pre-existing target with different bytes and ne }finally{await cleanup(root);} }); -test('a plain image count reads every slot without dispatching to the selected model',async()=>{ - const x=await fixture(()=>sse({content:'可以讨论这些图。'})); +test('the agent queries actual slot progress with its tools',async()=>{ const slots=Array.from({length:27},(_,index)=>({ id:'slot-'+index, selectedCandidateId:index<2?'accepted-'+index:null, candidates:index===2?[{status:'complete'}]:index===3?[{status:'unknown'}]:[], })); const offsets=[]; - x.native.workflowRead=async({section,offset=0})=>{ + const x=await fixture((_payload,n)=>n<=3?tool('workflow_read',{section:'slots',offset:(n-1)*12}): + sse({content:'27 个图位,已回填 2 个,还有 25 个未回填。其中 1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选。'}), { + workflowRead:async({section,offset=0})=>{ if(section==='slots')offsets.push(offset); return {available:true,version:18,section,canvasFirst:true,outputId:'detail',productVariantId:'brown', totalSlots:slots.length,slots:slots.slice(offset,offset+12),productEvidence:evidence(x.identity.project)}; - }; + } + }); try{ const result=await x.host.prompt('后面还有几张图没有完成的'); assert.match(result.text,/27 个图位,已回填 2 个,还有 25 个未回填/); assert.match(result.text,/1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选/); assert.deepEqual(offsets,[0,12,24]); - assert.equal(result.rounds,0); - assert.equal(x.requests.length,0); + assert.equal(result.rounds,4); + assert.equal(x.requests.length,4); assert.equal(x.native.writes,0); - await x.host.prompt('后面还有几张图没有完成,麻烦先生成首图'); - assert.equal(x.requests.length,1); }finally{await x.close();} }); diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index d417dc4e..fb5d5be2 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -229,14 +229,19 @@ test('snapshots, memories, sessions are isolated by account/shop/category/versio assert.deepEqual((await other.context()).confirmedMemory, {}); await cleanup(dir); }); -test('actual Pi SDK executes memory tools, persists full transcript and reinjects after restart', async () => { +test('actual Pi SDK executes memory tools, persists full transcript and reads project facts explicitly after restart', async () => { const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A')); let calls = 0; const transport = { info: info(id.scope), stream(model, ctx) { - assert.match(getCurrentSystemPrompt(ctx.messages), /"shopId":"A"/); + assert.doesNotMatch(getCurrentSystemPrompt(ctx.messages), /"shopId":"A"/); calls++; if (calls === 1) return stream([{ type: 'toolCall', id: 'qa-call-1', name: 'memory_set', arguments: { key: 'color', value: '胡桃色', evidence: '颜色是胡桃色' } }]); - assert.match(getCurrentSystemPrompt(ctx.messages), /"color"/); + if (calls === 3) return stream([{ type:'toolCall', id:'qa-read-context', name:'context_read', arguments:{} }]); + if (calls === 4) { + const evidence=ctx.messages.find(message=>message.role==='toolResult'&&message.toolName==='context_read'); + assert.match(evidence.content[0].text, /"shopId":"A"/); + assert.match(evidence.content[0].text, /"color"/); + } return stream([{ type: 'text', text: '已记录胡桃色' }]); } }; let host = await DetailPiAgent.open({ store, transport }); diff --git a/apps/detail-agent-pi/test/rule-context.test.mjs b/apps/detail-agent-pi/test/rule-context.test.mjs index 9c744362..079217a8 100644 --- a/apps/detail-agent-pi/test/rule-context.test.mjs +++ b/apps/detail-agent-pi/test/rule-context.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { ruleContext, taskFor } from '../src/rule-context.mjs'; +import { ruleContext } from '../src/rule-context.mjs'; import { responseUsage } from '../src/usage.mjs'; const binding = { brandId: 'b', shopId: 's', categoryId: 'c', brandName: '顾家', version: 'v1', brandSnapshot: { tone: '温暖克制', fontFamily: 'Noto Sans SC', visualRules: { part: '## 人物选择与连续性\n连续场景人物一致。' } }, @@ -17,9 +17,6 @@ test('creative tasks receive brand rules once and conversation loads details on assert.equal(ruleContext(binding, { task: 'plan' }).templateSnapshot.screens, undefined); assert.equal(binding.templateSnapshot.screens.length, 1); assert.match(JSON.stringify(ruleContext(binding, { topic: 'brand' })), /连续场景/); - assert.equal(taskFor('生成六图总览方案'), 'plan'); assert.equal(taskFor('修改画布图层'), 'canvas'); - assert.equal(taskFor('记住最新颜色,不要修改画布'), 'chat'); - assert.equal(taskFor('请精简卖点文案,不改画布,不要生图'), 'copy'); }); test('cache metrics use returned counts, never substitute missing fields with zero', () => { const raw = 'data: {"usage":{"prompt_tokens":100,"prompt_tokens_details":{"cached_tokens":64}}}\n\ndata: [DONE]\n'; diff --git a/apps/detail-agent-pi/test/workflow.test.mjs b/apps/detail-agent-pi/test/workflow.test.mjs index 916a9541..ee195e81 100644 --- a/apps/detail-agent-pi/test/workflow.test.mjs +++ b/apps/detail-agent-pi/test/workflow.test.mjs @@ -18,11 +18,9 @@ const scope = '8'.repeat(64); const binding = { brandId:'qa',shopId:'qa',categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',rules:[] }; const info = { accountScope:scope,accountId:'local-qa',origin:'https://platform.test', model:{id:'qa-workflow',protocol:'openai-chat',contextWindow:131072,contextWindowSource:'fixture'},pending:[] }; -const prefix = '当前项目与画布事实:\n'; -function injection(context) { - const text = getCurrentSystemPrompt(context.messages); - const start=text.lastIndexOf(prefix); - return start<0?undefined:JSON.parse(text.slice(start + prefix.length).split('\n')[0]); +function readContext(context) { + const result=context.messages.findLast(message=>message.role==='toolResult'&&message.toolName==='context_read'&&!message.isError); + return result&&JSON.parse(result.content[0].text); } function stream(content) { const out = createAssistantMessageEventStream(); @@ -126,7 +124,7 @@ async function fixture(reply,{adapter='full',execute=false,broker,history=false, } if(execute){canvas.workflowExecute=async args=>({operationId:args.operationId,phase:'submitted'});canvas.workflowPoll=async operationId=>({operationId,phase:'complete'});} const calls=[]; - const transport={info,stream(_model,context){calls.push({context,injected:injection(context)});return stream(reply(context,calls.length,native,canvas));}}; + const transport={info,stream(_model,context){calls.push({context,evidence:readContext(context)});return stream(reply(context,calls.length,native,canvas));}}; const host=await DetailPiAgent.open({store,canvas,transport,broker,projectEvidence:nativeEvidence?evidence(project,'胡桃色',native.brandId,native.categoryId):undefined,documentId:7}); return {root,project,identity,store,canvas,native,calls,host,async close(){await host.dispose();await cleanup(root);}}; } @@ -134,8 +132,9 @@ async function fixture(reply,{adapter='full',execute=false,broker,history=false, test('each SDK step reads live workflow and product state while suggestions stay review-only',async()=>{ const x=await fixture((_context,n,native)=>{ if(n===1)return tool('workflow_read',{section:'materials'},'read-materials'); - if(n===2)return tool('workflow_navigate',{stage:'plan',outputId:'detail'},'show-plan'); - if(n===3)return tool('workflow_propose',{version:native.version,intent:'plan',outputId:'detail'},'propose-plan'); + if(n===2)return tool('context_read',{},'read-current'); + if(n===3)return tool('workflow_navigate',{stage:'plan',outputId:'detail'},'show-plan'); + if(n===4)return tool('workflow_propose',{version:native.version,intent:'plan',outputId:'detail'},'propose-plan'); return answer('已添加待审核建议,尚未生成页面。'); }); const read=x.canvas.workflowRead; @@ -146,18 +145,18 @@ test('each SDK step reads live workflow and product state while suggestions stay try{ const result=await x.host.prompt('先看当前资料,再展示方案步骤并列出建议,暂不执行。'); assert.match(result.text,/待审核/); - assert.equal(x.calls.length,4); - assert.equal(x.calls[0].injected.currentProduct.product.colorName,'胡桃色'); - for(const call of x.calls.slice(1)){ - assert.equal(call.injected.currentWorkflow.version,2); - assert.equal(call.injected.currentProduct.product.colorName,'米白色'); - assert.equal(call.injected.currentProduct.dimensions.length,'1400'); + assert.equal(x.calls.length,5); + assert.equal(x.calls[0].evidence,undefined); + assert.equal(x.calls[1].evidence,undefined); + for(const call of x.calls.slice(2)){ + assert.equal(call.evidence.currentWorkflow.version,2); + assert.equal(call.evidence.currentProduct.product.colorName,'米白色'); + assert.equal(call.evidence.currentProduct.dimensions.length,'1400'); const system=getCurrentSystemPrompt(call.context.messages); - assert.equal(system.split('"currentProduct":').length-1,1); - assert.equal(system.split('"currentWorkflow":').length-1,1); - assert.ok(!JSON.stringify(call.injected.currentWorkflow).includes('productEvidence')); + assert.doesNotMatch(system,/当前项目与画布事实/u); + assert.ok(!JSON.stringify(call.evidence.currentWorkflow).includes('productEvidence')); } - assert.equal(x.native.reads.filter(v=>v.section==='overview').length,7); + assert.equal(x.native.reads.filter(v=>v.section==='overview').length,2); assert.equal(x.native.navigations.length,1);assert.equal(x.native.proposals.length,1);assert.equal(x.native.generated,0); assert.equal(x.canvas.writes,0);assert.equal(x.canvas.grants,0); for(const label of ['读取创作进度','切换创作视图','添加待审核建议'])assert.ok(x.canvas.activities.some(a=>a.includes(label))); @@ -170,14 +169,14 @@ test('each SDK step reads live workflow and product state while suggestions stay test('missing workflow adapters keep old tools compatible; unavailable live data never revives an old product',async()=>{ for(const adapter of ['legacy','unavailable']){ - const x=await fixture(()=>answer('仅讨论当前可确认的资料。'),{adapter}); + const x=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('仅讨论当前可确认的资料。'),{adapter}); try{ await x.host.prompt('先聊一下当前资料。'); const names=x.host.session.getActiveToolNames(); assert.equal(names.includes('workflow_read'),adapter!=='legacy'); assert.ok(!names.includes('workflow_navigate'));assert.ok(!names.includes('workflow_propose')); - if(adapter==='legacy')assert.equal(x.calls[0].injected.currentProduct.product.colorName,'胡桃色'); - else{assert.equal(x.calls[0].injected.currentWorkflow.available,false);assert.equal(x.calls[0].injected.currentProduct.state,'unavailable');assert.ok(!JSON.stringify(x.calls[0].injected.currentProduct).includes('胡桃色'));} + if(adapter==='legacy')assert.equal(x.calls[1].evidence.currentProduct.product.colorName,'胡桃色'); + else{assert.equal(x.calls[1].evidence.currentWorkflow.available,false);assert.equal(x.calls[1].evidence.currentProduct.state,'unavailable');assert.ok(!JSON.stringify(x.calls[1].evidence.currentProduct).includes('胡桃色'));} }finally{await x.close();} } }); @@ -203,7 +202,7 @@ test('foreign live evidence rejects before inference and memory_set cannot mutat try{ await x.host.prompt('我在讨论中确认颜色是米白色,请先记住。'); assert.equal((await x.store.context()).confirmedMemory.color.value,'米白色'); - assert.equal(x.calls[1].injected.currentProduct.product.colorName,'胡桃色'); + assert.equal(x.host.productEvidence.product.colorName,'胡桃色'); assert.equal(x.native.color,'胡桃色');assert.equal(x.native.proposals.length,0); }finally{await x.close();} }); @@ -230,17 +229,20 @@ test('brand or category changes stop before inference or tools and require a new const updated=await ProjectStore.open(x.root,x.identity,{...binding,brandId:'new-rule-brand',categoryId:'new-rule-category',version:'2',rules:['新回合已加载新规则']},{continuous:true}); const next=[]; reopened=await DetailPiAgent.open({store:updated,canvas:x.canvas,documentId:7,projectEvidence:evidence(x.project,x.native.color,x.native.brandId,x.native.categoryId), - transport:{info,stream(_model,context){next.push(injection(context));return stream(answer('已按新回合的规则继续讨论。'));}}}); + transport:{info,stream(_model,context){ + next.push(readContext(context)); + return stream(next.length===1?tool('context_read',{}):answer('已按新回合的规则继续讨论。')); + }}}); await reopened.prompt('按当前产品重新讨论,不修改画布。'); - assert.equal(next.length,1);assert.equal(next[0].snapshot.brandId,'new-rule-brand');assert.equal(next[0].snapshot.categoryId,'new-rule-category'); - assert.equal(next[0].currentProduct.product[key],'changed-native-id'); - assert.deepEqual(next[0].confirmedMemory,{});assert.equal(x.canvas.writes,0); + assert.equal(next.length,2);assert.equal(next[1].snapshot.brandId,'new-rule-brand');assert.equal(next[1].snapshot.categoryId,'new-rule-category'); + assert.equal(next[1].currentProduct.product[key],'changed-native-id'); + assert.deepEqual(next[1].confirmedMemory,{});assert.equal(x.canvas.writes,0); }finally{await reopened?.dispose();if(!disposed)await x.host.dispose();await cleanup(x.root);} } // An adapter without initial native evidence may establish its first live // binding, while a native empty ID above remains a real immutable binding. - const initial=await fixture(()=>answer('首次读取的本机资料已可用于讨论。'),{nativeEvidence:false}); - try{await initial.host.prompt('读取当前资料。');assert.equal(initial.calls.length,1);assert.equal(initial.calls[0].injected.currentProduct.product.brandId,'native-brand');} + const initial=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('首次读取的本机资料已可用于讨论。'),{nativeEvidence:false}); + try{await initial.host.prompt('读取当前资料。');assert.equal(initial.calls.length,2);assert.equal(initial.calls[1].evidence.currentProduct.product.brandId,'native-brand');} finally{await initial.close();} }); @@ -305,7 +307,7 @@ test('proposal instructions describe only selling-point direction and other inte }); test('unsaved native drafts keep prior analysis stale and compaction does not refresh or navigate the UI',async()=>{ - const x=await fixture(()=>answer('草稿尚未保存,旧分析不能作为新依据;先等待用户核对。'),{history:true}); + const x=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('草稿尚未保存,旧分析不能作为新依据;先等待用户核对。'),{history:true}); const read=x.canvas.workflowRead; x.canvas.workflowRead=async args=>{ const value=await read(args); @@ -319,17 +321,17 @@ test('unsaved native drafts keep prior analysis stale and compaction does not re }; try{ await x.host.prompt('讨论当前还没保存的资料草稿。'); - assert.equal(x.calls[0].injected.currentWorkflow.uiDirty,true); - assert.equal(x.calls[0].injected.currentWorkflow.draftDirty,true); - assert.equal(x.calls[0].injected.currentWorkflow.writeBlocked,false); - assert.equal(x.calls[0].injected.currentWorkflow.factsStatus,'stale'); - assert.equal(x.calls[0].injected.currentWorkflow.planConfirmed,false); - assert.equal(x.calls[0].injected.currentWorkflow.batchCount,1); - assert.deepEqual(x.calls[0].injected.currentWorkflow.selected,['batch:0']); - assert.deepEqual(x.calls[0].injected.currentWorkflow.capabilities,{imageDispatchAllowed:false,copyDispatchAllowed:false,localApplyAllowed:false}); - assert.equal(x.calls[0].injected.currentProduct.factsStatus,'stale'); - assert.deepEqual(x.calls[0].injected.currentProduct.selectedSellingPoints,[]); - assert.equal(x.calls[0].injected.currentProduct.plan.status,'stale'); + assert.equal(x.calls[1].evidence.currentWorkflow.uiDirty,true); + assert.equal(x.calls[1].evidence.currentWorkflow.draftDirty,true); + assert.equal(x.calls[1].evidence.currentWorkflow.writeBlocked,false); + assert.equal(x.calls[1].evidence.currentWorkflow.factsStatus,'stale'); + assert.equal(x.calls[1].evidence.currentWorkflow.planConfirmed,false); + assert.equal(x.calls[1].evidence.currentWorkflow.batchCount,1); + assert.deepEqual(x.calls[1].evidence.currentWorkflow.selected,['batch:0']); + assert.deepEqual(x.calls[1].evidence.currentWorkflow.capabilities,{imageDispatchAllowed:false,copyDispatchAllowed:false,localApplyAllowed:false}); + assert.equal(x.calls[1].evidence.currentProduct.factsStatus,'stale'); + assert.deepEqual(x.calls[1].evidence.currentProduct.selectedSellingPoints,[]); + assert.equal(x.calls[1].evidence.currentProduct.plan.status,'stale'); assert.match(getCurrentSystemPrompt(x.calls[0].context.messages),/version只用于上下文一致性,不代表方案已确认/); const reads=x.native.reads.length; await x.host.compact(); @@ -369,14 +371,14 @@ test('recovery can restore workflow_read but never replays navigation or review } }); -test('a generated candidate keeps its receipt through projection and drives the final canvas reply', async () => { +test('a generated candidate keeps its receipt in the Pi transcript and the model replies', async () => { let originalOperation; const x = await fixture((context, round) => { if (round === 1) return tool('workflow_execute', { version: 1, intent: 'generate_candidate', outputId: 'detail', slotId: 'hero', productVariantId: 'walnut', }, 'generate-hero'); if (round === 3) return answer('这是另一轮对话。'); - return answer('没有新候选,原回执已经归档。'); + return answer('已生成一张候选,回执已归档。'); }, { execute: true }); const originalExecute = x.canvas.workflowExecute; x.canvas.workflowExecute = async args => { @@ -398,8 +400,7 @@ test('a generated candidate keeps its receipt through projection and drives the assert.equal(receipt.operation.candidateId, 'new-hero'); assert.equal(receipt.operation.slotId, 'hero'); assert.equal(receipt.archivedWorkflowResult, undefined); - assert.match(result.text, /已生成.*候选/); - assert.doesNotMatch(result.text, /没有新候选|归档/); + assert.equal(result.text,'已生成一张候选,回执已归档。'); assert.deepEqual(replies, [result.text]); assert.equal(x.native.generated, 1); const next = await x.host.prompt('只聊一下当前资料。'); 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 41d81dbe..0ff18e7b 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 @@ -220,10 +220,6 @@ fn clip(value: &Value, max: usize) -> String { value.as_str().unwrap_or("").chars().take(max).collect() } -fn strings(value: &Value, count: usize, length: usize) -> Vec { - value.as_array().into_iter().flatten().filter(|item| item.is_string()).take(count).map(|item| json!(clip(item, length))).collect() -} - fn source_label(value: &Value) -> String { let source = clip(value, 100); if source.contains(['/', '\\']) || source.contains("://") { "来源地址已省略".into() } else { source } @@ -567,7 +563,7 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, "revisions":{"canvas":canvas["revision"],"creation":w.creation["revision"],"slots":w.template_workflow["revision"]}, "dirty":w.creation_dirty,"draftDirty":brief_dirty(w) || plan_dirty(w),"width":w.creation_width,"screenCount":w.creation_count, "pending":w.unknown || w.template_workflow["pending"]==true,"writeBlocked":w.pi_write_blocked, - "factsStatus":facts["status"],"missing":facts["missing"],"selected":w.creation_selected.iter().take(20).collect::>(), + "factsStatus":facts["status"],"missing":facts["missing"],"selected":w.creation_selected, "batchCount":batches.len(),"planConfirmed":plan["confirmed"],"capabilities":w.template_workflow["capabilities"],"productEvidence":product_evidence(w)}); result["canvasFirst"] = w.template_workflow["canvasFirst"].clone(); result["template"] = w.template_workflow["template"].clone(); @@ -607,18 +603,18 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, result["offset"] = json!(offset); result["totalSlots"] = json!(slots.len()); result["slots"] = json!(slots.into_iter().skip(offset).take(12).map(|slot| { - let candidates=slot["candidates"].as_array().into_iter().flatten().rev().take(12).map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"],"reused":candidate["reusedFrom"].is_object()})).collect::>(); + let candidates=slot["candidates"].as_array().into_iter().flatten().rev().map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"],"reused":candidate["reusedFrom"].is_object()})).collect::>(); let manually_edited = w.pi_request_scope["wholeDetail"] == true && w.pi_canvas_basis.is_some() && slot["nativeLayerId"].as_u64().is_some_and(|id| active_doc .is_some_and(|doc| !w.detail_layer_unchanged(doc, photocraft_doc::LayerId(id)))); json!({"id":clip(&slot["id"],160),"fieldId":clip(&slot["fieldId"],100),"documentId":clip(&slot["documentId"],100),"outputId":output, "label":clip(&slot["label"],160),"selectedCandidateId":if w.template_workflow["canvasFirst"]==true{adopted(&slot["id"])}else{slot["selectedCandidateId"].clone()}, "sourcePolicy":slot["sourcePolicy"],"manuallyEdited":manually_edited,"candidates":candidates, - "role":clip(&slot["role"],240),"requirements":clip(&slot["requirements"],2200), - "templatePrompt":clip(&slot["templatePrompt"],1200),"relatedFields":slot["relatedFields"], + "role":slot["role"],"requirements":slot["requirements"], + "templatePrompt":slot["templatePrompt"],"relatedFields":slot["relatedFields"], "layoutReference":slot["layoutReference"],"textRegions":slot["textRegions"],"productionRule":slot["productionRule"]}) }).collect::>()); - result["outputs"] = json!(w.template_workflow["outputs"].as_array().into_iter().flatten().filter(|row| row["outputId"]==output).take(32) + result["outputs"] = json!(w.template_workflow["outputs"].as_array().into_iter().flatten().filter(|row| row["outputId"]==output) .map(|row|json!({"documentId":clip(&row["documentId"],100),"name":clip(&row["name"],160),"ready":row["ready"]==true,"requiredImages":row["requiredImages"],"selectedImages":row["selectedImages"],"hasEditedDraft":row["hasEditedDraft"]==true})).collect::>()); } _ => {} diff --git a/docs/development/xiaoyi/implementation.md b/docs/development/xiaoyi/implementation.md index c210986f..7e83a1e9 100644 --- a/docs/development/xiaoyi/implementation.md +++ b/docs/development/xiaoyi/implementation.md @@ -297,3 +297,12 @@ PhotoCraft 用正式文件独立导入了 5 张主图和 1 张 SKU,并按原 | 验图发起后,画布检测有白边、色样背景或文字区高反差边缘 | 实拍、模板参考、候选和相关局部送给验图代理;检测值单独返回为定位依据 | 本地测试拟定第一张为返工、第二张为通过。两张均带白边诊断。第一张虽四项为真,仍保留返工;第二张有一项为假且理由含「看不清」,仍按原结论通过 | | 验图代理已提交结构化结论 | 原样保存结论、检查项、理由和返工建议。正常采用及后续复核使用同一候选和对应文案的有效记录 | 本地测试另覆盖不同结构的台灯和局部取景,及画布已有候选、新文案触发复核时保持同一候选号 | | 有已发布的结构标注,验图代理给出坐标 | 采用时按候选身份和坐标范围应用现有标注。无坐标可用 PhotoCraft 工具单独绘制 | Node 流程测试核对记录的实物落点。原生测试核对同候选和坐标边界 | + + +### 七、对话状态和知识按需读取 + +| 触发条件 | 出口 | 验证 | +| --- | --- | --- | +| 普通对话、用户引用画布、查询制作进度 | 使用对话模型及 Pi 原有消息。小壹可通过工具在需要时查询项目、引用图层和图位。不按措辞静默更换文案模型、强制下一工具或代答 | Pi 原生传输回归比较工具调用前后的消息;图位查询按原生分页读完,预览与真实写入分别遵守各自工具回执 | +| 对话需要当前产品资料及规则 | 由 `context_read` 读到当前项目绑定。知识和画布状态通过工具回执进入 Pi 历史 | 回归覆盖首次打开、切换品牌或品类、旧项目记录隔离、未保存资料和原生分页 | +| 项目返回多屏、多花色或较多历史候选 | 按查询范围返回整页记录,由客户端的 `offset` 分页浏览。保留工作流字段的私有资源过滤 | 本地 Node 回归使用 27 个图位跨三页;原生端保留全部已选信息和输出记录 |