refactor(xiaoyi): restore native Pi session and production tools

This commit is contained in:
WuYongJie 2026-11-25 23:47:09 +08:00
parent 6de9700d93
commit 2a337a42cb
32 changed files with 486 additions and 1758 deletions

View File

@ -1,7 +1,7 @@
import {setTimeout as delay} from 'node:timers/promises';
import { runWholeDetail } from './whole-detail.mjs';
import { prepareProductStrategy } from './product-strategy.mjs';
import { confirmProductionResponse, confirmedProductionFailure, isProductPending, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending, recoverProductionResponse, retryGatewayModelCall } from './production-recovery.mjs';
import { confirmProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs';
import { enterpriseTools } from './enterprise-knowledge.mjs';
import { executeWorkflow } from './workflow-execute.mjs';
import { StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs';
@ -13,30 +13,27 @@ import { productionTools, callProductionTool, closeProductionTurn, runPiProducti
mayContinueProductionGoal, piGoalState, productionObjective } 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';
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, normalizeContext, 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 { transportProjection } from './context-budget.mjs';
import { compactionExtension, prepareCompactionRequest, requestPurpose, recoverCompaction, recoverCompactionWithoutResult, resumeProductionCompaction, hasCompactionReviewForBranch, localBudgetFailureHash, COMPACTION_INSTRUCTIONS } from './compaction-recovery.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 { EnterpriseContext } from './enterprise-context.mjs';
import { enterpriseSkillReadTool, openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { projectTools } from './project-tools.mjs';
import { responseUsage } from './usage.mjs';
import { contextSnapshot, exceedsModelBudget, modelCapacity, contextTextLength } from './context-usage.mjs';
import { contextSnapshot, modelCapacity, contextTextLength } from './context-usage.mjs';
import { activityScope, activitySummary, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { nativeTools } from './native-tools.mjs';
import { NativeExtensionUI } from './native-ui.mjs';
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
// Pi recognizes this machine marker; it describes our measured transport limit,
// never an invented provider context window or an already dispatched request.
const LOCAL_CONTEXT_OVERFLOW = 'local context_length_exceeded';
import { PHOTOCRAFT_NAMESPACE, PHOTOCRAFT_NATIVE_TOOL_NAMES, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文,能够与用户连贯讨论、回答问题、解释原因、提出并比较方案。可以直接自然语言回答;不需要工具时不要调用工具,不把每次对话都当作执行任务。
需要用户选择、确认或补充关键资料时使用ask_user,以原生选项、确认或输入卡片等待回复,再按回复继续。用户明确要求交互选择时不要仅把选项写在正文里。多选使用multi_select;长文本修改使用editor。用户取消表示未决定,不能擅自代选或把取消当授权。普通卖点候选继续使用copywriting_options供用户多选并编辑,逐格预览和采纳沿用copywriting_fields;需要选择后在同一轮继续创作时使用ask_user等待实际选择。
@ -103,7 +100,6 @@ function toolsFor(host) {
...(host.productionGoal ? productionTools.map(([name, description, schema]) =>
make(name, description, schema, (args,signal)=>callProductionTool(host,name,args,signal),
name==='read_output_screen'?result=>result:plain)) : []),
...(host.productionGoal ? [enterpriseSkillReadTool(host.store, () => host.productionSkills, 'main')] : []),
make('context_read', '按需读取当前项目规则。未指定topic返回当前任务必需规则;brand为品牌细节、template为模板模块、sources为来源。普通问答涉及企业知识库或模板规则时,先用此工具取依据。', Type.Object({ topic: Type.Optional(Type.Union([Type.Literal('brand'), Type.Literal('template'), Type.Literal('sources')])) }, { additionalProperties: false }), args => host.modelContext(args, {loadKnowledge:true})),
make('memory_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }), args => host.store.remember(args, host.session.messages)),
make('memory_search', '查找本项目历史。用 query 查对话,或用 toolCallId 和 offset 分段读取归档的工具回执。', Type.Object({
@ -295,11 +291,6 @@ function toolsFor(host) {
return active;
}
function hasBlockingOriginal(pending, goalScope, resumeGoal = false) {
return pending?.some(request => !goalScope || !isProductPending(request) || !resumeGoal && request.detailSlot === goalScope);
}
/** Coding Agent SDK owns the transcript/compaction; our host owns all I/O boundaries. */
export class DetailPiAgent {
static async open({ store, broker, brokerInfo, canvas, transport, projectEvidence, documentId, productionGoal, protocolMode = 'native-tools', callBudget, onEvent = () => {} }) {
@ -350,9 +341,15 @@ export class DetailPiAgent {
} else payload.tool_choice = namedTool(name);
return payload;
};
// This route defaults to thinking and rejects a named tool in that mode.
const deepSeekThinking = api === 'openai-completions' && info.model.id === 'deepseek-v4.1-flash-1017';
const usesProviderDefaultOutput = api !== 'anthropic-messages' && !info.model.maxTokens;
const known = runtime.getModel(api==='anthropic-messages'?'anthropic':'openai-codex', info.model.id);
const reasoning = info.model.reasoning === true;
const efforts = info.model.reasoningEfforts;
const thinkingLevelMap = Array.isArray(efforts) && efforts.length ? Object.fromEntries(
['off','minimal','low','medium','high','xhigh','max'].map(level=>[
level,efforts.includes(level)?level:level==='minimal'&&efforts.includes('low')?'low':null,
])) : known?.thinkingLevelMap;
const usesProviderDefaultOutput = api !== 'anthropic-messages'
&& (info.model.requiresOutputLimit === false || !info.model.maxTokens);
const applyOutputContract = payload => {
if (usesProviderDefaultOutput) {
delete payload.max_tokens;
@ -366,41 +363,27 @@ export class DetailPiAgent {
api, apiKey: 'native-broker-only', baseUrl: api === 'anthropic-messages' ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1',
models: [{
id: info.model.id, name: info.model.id, api,
reasoning: deepSeekThinking,
reasoning, ...(reasoning && thinkingLevelMap ? {thinkingLevelMap} : {}),
input: info.model.supportsImageInput === false ? ['text'] : ['text', 'image'],
cost, contextWindow: modelCapacity(info.model).limit ?? 0, maxTokens: info.model.maxTokens ?? 8192,
cost, contextWindow: modelCapacity(info.model).limit ?? known?.contextWindow ?? 0,
maxTokens: info.model.maxTokens ?? known?.maxTokens ?? 0, inputLimits:known?.inputLimits,
compat: {
supportsStore: false, supportsDeveloperRole: false, supportsReasoningEffort: false, maxTokensField: 'max_tokens',
...(deepSeekThinking ? { thinkingFormat: 'deepseek' } : {}),
supportsStore: false, supportsDeveloperRole: false, supportsReasoningEffort: reasoning, maxTokensField: 'max_tokens',
},
}],
streamSimple(model, context, options = {}) {
const output = createAssistantMessageEventStream();
(async () => {
let requiredTool;
const visibleBeforeAttempt = host.presentation && Object.assign(new StreamPresentation(), host.presentation);
let round, compaction, retryOf = host.nextGoalRetryOf;
host.nextGoalRetryOf = undefined;
let round;
try {
await retryGatewayModelCall(async () => {
round = undefined;
compaction = undefined;
try {
options.signal?.throwIfAborted();
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
if (host.productionGoal?.deadline * 1000 <= Date.now()) throw Error('整套制作已达到时限,保留当前结果');
if (host.localBudgetRecovery?.phase === 'prepared') {
await host.checkLocalBudgetRecovery(options.signal);
if (!host.compacting) {
const recovery = host.localBudgetRecovery;
if (!host.manager.getEntries().some(entry => entry.type === 'compaction' && entry.details?.jiansunCompactionPlanId === recovery.planId)) throw Error('预算压缩尚未提交,本轮未继续;原工具结果已保留');
recovery.phase = 'committed';
await store.appendEvent({type: 'local_budget_recovery_continued', planId: recovery.planId, originalBranchHash: recovery.branchHash});
}
}
const liveCanvas = host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null;
if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目');
if (host.canvasNotificationsDetached || !liveCanvas?.manualEdit && (host.canvasWritesStopped || liveCanvas?.writeBlocked && host.canvasWriteRequested)) {
if (!host.compacting && (host.canvasNotificationsDetached ||
!liveCanvas?.manualEdit && (host.canvasWritesStopped || liveCanvas?.writeBlocked && host.canvasWriteRequested))) {
const text=host.canvasNotificationsDetached?'本机:原项目已切换,原回复保留在原项目,后续画布操作已停止。':host.workflowStopReason?`本次创作已停止:${host.workflowStopReason}`:'本机:已接手,剩余画布操作已停止。';
const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } };
await store.appendEvent({ type: host.canvasNotificationsDetached?'inactive_project_stopped':host.workflowStopReason?'workflow_operation_stopped':'handover_stopped', modelCallSkipped: true });
@ -408,7 +391,7 @@ export class DetailPiAgent {
output.push({ type: 'done', reason: 'stop', message }); output.end(message);
return;
}
if (!host.productionGoal && host.recallRepeats >= 2) throw Error('模型重复检索同一证据,已停止继续调用;历史和结果已保留');
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) {
@ -437,10 +420,6 @@ export class DetailPiAgent {
const wireContext = encoded ? jsonToolContext(contextual) : contextual;
const inputChars = contextTextLength(wireContext);
if (!host.compacting) await host.updateContextUsage(null, 'running');
if (!host.compacting && inputChars > (host.productionGoal ? 80_000 : 120_000)) {
throw await host.localBudgetOverflow('本轮上下文超过本地输入预算', inputChars, options.signal);
}
if (exceedsModelBudget(wireContext, info.model)) throw await host.localBudgetOverflow('本轮上下文估算超过模型输入预算', inputChars, options.signal);
host.rounds++;
if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`);
await store.appendEvent({ type: 'context_budget', inputChars, originalChars: JSON.stringify(context).length });
@ -455,15 +434,9 @@ export class DetailPiAgent {
output.end(result);
return;
}
round = (host.goalBroker ?? broker).round({
retryPreparation:!host.compacting&&!!host.productionGoal,
retryOf,
});
retryOf = undefined;
compaction = host.compacting ? await prepareCompactionRequest(host, round.id) : null;
round = (host.goalBroker ?? broker).round({inference:true});
await store.appendEvent({ type: 'provider_prepared', id: round.id, model: model.id, bindingHash: store.hash,
purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation',
...(compaction ? {compactionPlanId: compaction.planId, compactionPlanHash: compaction.planHash, compactionPart: compaction.part, summaryProtocolMode: compaction.summaryProtocolMode} : {}) });
purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation' });
host.inflight = round.id;
if (!host.compacting) {
requiredTool ??= host.requiredTool;
@ -477,8 +450,7 @@ export class DetailPiAgent {
headersAt = Date.now();
wireCapture = response.clone().text().then(text => ({ text }), error => ({ error }));
return response;
}, maxRetries: 0, maxRetryDelayMs: 0, timeoutMs: host.goalBroker ? 180_000 : 600_000, reasoning: undefined,
cacheRetention: api === 'anthropic-messages' ? 'short' : 'none',
},
onPayload: async payload => {
applyOutputContract(payload);
if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool);
@ -526,10 +498,14 @@ export class DetailPiAgent {
}) });
host.inflight = ['complete', 'failed'].includes(settled.phase) ? null : round.id;
const failure = confirmedProductionFailure(settled, round.id);
if (host.goalBroker && ['complete','failed'].includes(settled.phase)) host.goalPendingOriginal = undefined;
if (failure) throw failure;
if (!valid || settled.phase !== 'complete') throw Error(`请求${round.id}结果待核查;不会重发`);
if (result.stopReason === 'length') throw Error('模型已达到输出上限,未执行这一轮工具建议;已完成的改动保留');
if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) {
const message={...result,content:result.content.filter(block=>block.type!=='toolCall')};
output.push({type:'done',reason:'length',message});
output.end(message);
return;
}
if (!valid || settled.phase !== 'complete') throw Error(result.errorMessage ?? 'network error: inference stream did not complete');
const wire = await wireCapture;
if (!wire || wire.error) throw Error('原始响应未完整取到,未执行工具;请只读核查原请求');
const usage = responseUsage(wire.text);
@ -547,62 +523,8 @@ export class DetailPiAgent {
if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message });
output.push({ type: 'done', reason: message.stopReason, message }); output.end(message);
} else { output.push(finalEvent); output.end(result); }
} catch (error) {
if (host.compacting && host.goalBroker && round && host.goalBroker.isUnconfirmed?.(round.id)) {
host.goalPendingOriginal = round.id;
}
if (!host.compacting && round && !(error instanceof ProductionRequestFailed) &&
(host.goalBroker ?? broker)?.isUnconfirmed?.(round.id) && !options.signal?.aborted) {
const original = host.goalBroker ? broker.forDetailSlot(host.goalRequestScope) : broker;
try {
const managedInference = host.goalBroker && host.productionGoal?.deadline * 1000 > Date.now()
&& !host.canvasWritesStopped && !host.canvasNotificationsDetached;
const recovered = await recoverProductionResponse(original, round.id, model, context.tools,
{signal:options.signal,waitForResult:!managedInference,protocolMode}).catch(()=>({phase:'unknown'}));
await store.appendEvent({type:host.goalBroker?'production_goal_original_checked':'conversation_original_checked',id:round.id,phase:recovered.phase});
if (recovered.message && !options.signal?.aborted && !host.canvasWritesStopped) {
host.inflight = null;
host.goalPendingOriginal = undefined;
output.push({type:'done',reason:recovered.message.stopReason,message:recovered.message});
output.end(recovered.message);
return;
}
if (recovered.phase === 'failed') {
host.inflight = null;
host.goalPendingOriginal = undefined;
error = confirmedProductionFailure(recovered, round.id) ?? error;
} else if (host.goalBroker && !['complete','rejected','not_dispatched','prepared'].includes(recovered.phase)) {
host.goalPendingOriginal=round.id;
if (managedInference && recovered.phase === 'unknown') {
// A model round has no canvas or image effects until its
// complete response is journaled and handed to Pi.
retryOf = round.id;
error = new ProductionRequestFailed(round.id);
error.message = '本轮推理连接中断,按当前制作进度接续';
} else {
error = new ProductionRequestPending({id:round.id,requestId:recovered.requestId,detailSlot:host.goalRequestScope});
}
}
} finally { if (host.goalBroker) await original.close(); }
}
if (error instanceof ProductionRequestFailed && host.canvasWritesStopped) throw Error(host.workflowStopReason ?? '当前画布操作已停止');
throw error;
}
}, piRetryPolicy, options.signal, async ({ failure, attempt, maxAttempts, delayMs }) => {
if (compaction) host.activeCompaction.part--;
if (!host.compacting && host.goalBroker?.failed) {
await host.goalBroker.close();
host.goalBroker = broker.forDetailSlot(host.goalRequestScope);
}
host.presentation = Object.assign(new StreamPresentation(), visibleBeforeAttempt);
host.thinking = false;
await store.appendEvent({type:'model_retry',id:round.id,requestScope:host.goalRequestScope,
httpStatus:failure.httpStatus,attempt,maxAttempts,waitMs:delayMs});
if (!host.compacting) await host.notifyCanvas('delta', host.presentation.text, false).catch(()=>{});
});
} catch (error) {
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: String(error.message).slice(0, 2000), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
if (error.localBudgetRecovery === host.localBudgetRecovery && host.localBudgetRecovery) host.localBudgetRecovery.errorHash = localBudgetFailureHash(message);
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+error.message : String(error.message), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
await store.appendEvent({ type: 'provider_error', id: round?.id, reason: message.errorMessage });
output.push({ type: 'error', reason: 'error', error: message }); output.end(message);
}
@ -612,54 +534,52 @@ export class DetailPiAgent {
});
const saved = await store.get('session.json', null);
host.manager = saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir) : SessionManager.create(store.dir, path.join(store.dir, 'sessions'));
// Stale bodies are archived only in transportProjection. Opening/recovering
// a session must not append context edits that change a checkpoint's branch.
if (typeof canvas?.uiRequest === 'function') host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
const customTools = toolsFor(host);
const extensions = await createPhotoCraftExtensions(host, [compactionExtension(host)], {
const files = await projectTools(host);
const customTools = [...toolsFor(host),...files.tools];
host.workingDirectory=files.cwd;
const extensions = await createPhotoCraftExtensions(host, [], {
includeGoal: !!productionGoal, mayContinueGoal: event => mayContinueProductionGoal(host, event),
});
host.localSkillFiles = new Set(extensions.resourceLoader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
const loader = {
getExtensions: () => extensions,
getSkills: () => host.productionSkills?.resource ?? extensions.resourceLoader.getSkills(),
getPrompts: () => ({ prompts: [], diagnostics: [] }), getThemes: () => ({ themes: [], diagnostics: [] }),
getSkills: () => {
const local=extensions.resourceLoader.getSkills();
const enterprise=host.productionSkills?.resource;
if (!enterprise) return local;
const skills=new Map([...local.skills,...enterprise.skills].map(skill=>[skill.name,skill]));
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,
getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [], extendResources() {}, async reload() {},
};
const { session } = await createAgentSession({ cwd: store.dir, agentDir: store.dir, modelRuntime: runtime,
model: runtime.getModel('jiansun-native-98k', info.model.id), thinkingLevel: 'off',
const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime,
model: runtime.getModel('jiansun-native-98k', info.model.id),
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: false, keepRecentTokens: 2048, reserveTokens: 4096 }, retry: { enabled: false }, summarization: { enabled: false } }), sessionManager: host.manager,
settingsManager: SettingsManager.inMemory({ compaction: { enabled: true }, retry: { enabled: true } }), sessionManager: host.manager,
});
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId) => {
if (host.productionSkills) {
systemPrompt += formatSkillsForPrompt(host.productionSkills.resource.skills);
tools = [...tools,enterpriseSkillReadTool(store, () => host.productionSkills, 'worker', requestScope)];
const skills=loader.getSkills().skills;
if (skills.length) {
systemPrompt += formatSkillsForPrompt(skills);
tools = [...tools,files.read('worker',requestScope)];
}
const model = runtime.getModel('jiansun-native-98k', info.model.id);
let scoped = broker?.forDetailSlot?.(requestScope);
if (!model || !scoped && !transport?.stream) throw Error('详情页模型连接未就绪');
const requiredTool = tools.length===1 && (requestScope==='production-strategy' ||
tools[0].name==='plan_page_copy' && requestScope.startsWith('product/copy/') ||
/^product\/(review|compare|copy-audit|strategy|strategy-audit)\//.test(requestScope)) ? tools[0].name : null;
const opus55 = api==='anthropic-messages' && model.id==='claude-opus-5-5';
const opusCopy = opus55 && requestScope.startsWith('product/copy/');
const taskTools=tools.filter(tool=>tool.name!=='read');
const requiredTool = taskTools.length===1 && (requestScope==='production-strategy' ||
taskTools[0].name==='plan_page_copy' && requestScope.startsWith('product/copy/') ||
/^product\/(review|compare|copy-audit|strategy|strategy-audit)\//.test(requestScope)) ? taskTools[0].name : null;
const autoOnly = productionUsesAutomaticTools(info.model);
const toolChoice = autoOnly ? 'auto' : requiredTool ? (singleTool ? 'required' : namedTool(requiredTool)) : undefined;
const readOriginal=async(id,selected,recoveryTools,options)=>{
// The streaming worker can have lost its pipe. A fresh bridge only reads this ID.
const reader=broker.forDetailSlot(requestScope);
try {
const result=await recoverProductionResponse(reader,id,selected,recoveryTools,options).catch(()=>({phase:'unknown'}));
await store.appendEvent({type:'whole_detail_original_checked',id,slotId,requestScope,phase:result.phase});
return result;
} finally { await reader.close(); }
};
const used = new Map();
let pendingError;
const agent = new Agent({
initialState:{model,systemPrompt,tools,thinkingLevel:'off'},
initialState:{model,systemPrompt,tools,thinkingLevel:host.session.thinkingLevel},
toolExecution:'sequential',
streamFn:apiImpl.streamSimple,
});
@ -694,47 +614,29 @@ export class DetailPiAgent {
(async()=>{
let round;
try {
await retryGatewayModelCall(async () => {
const result = await retryAssistantCall(async () => {
round = undefined;
let requestBytes, firstOutputMs;
try {
const camera=await host.canvas.read();
if(camera?.conversationActive!==true||camera.writeBlocked)throw Error('用户已暂停详情页制作');
const held=host.productionRequests?.get(requestScope);
if(held){
const result=await readOriginal(held.id,selected,tools,{signal:options.signal});
const failure=confirmedProductionFailure(result,held.id);
if(!['complete','rejected'].includes(result.phase)&&!failure) {
const pending={...held,phase:result.phase==='failed'?held.phase:result.phase};
host.productionRequests.set(requestScope,pending);
throw new ProductionRequestPending(pending);
} else {
host.productionRequests.delete(requestScope);
if(failure&&!failure.retryable)throw failure;
}
}
options.signal?.throwIfAborted();
if (host.productionGoal?.deadline * 1000 <= Date.now()) throw Error('整套制作已达到时限,保留当前结果');
if(exceedsModelBudget(context,info.model))throw Error('该图位的证据超出模型容量');
round=scoped.round({retryPreparation:Boolean(host.productionRequests)});
round=scoped.round({inference:true});
const imageCount=context.messages.reduce((count,message)=>count+
(Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0);
const started=Date.now();
await store.appendEvent({type:'provider_prepared',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount});
let wire;
const stream=apiImpl.streamSimple(selected,context,{...options,toolChoice,apiKey:'native-broker-only',
cacheRetention: api === 'anthropic-messages' ? 'short' : 'none',
onPayload:payload=>{
applyOutputContract(payload);
return opusCopy ? {...payload,thinking:{type:'adaptive'},output_config:{effort:'low'}} : payload;
},
onPayload:applyOutputContract,
fetch:async (...args)=>{
const body=args[1]?.body;
if(typeof body==='string')requestBytes=Buffer.byteLength(body);
const response=await round.fetch(...args);
wire=response.clone().text().catch(()=>null);
return response;
},maxRetries:0,maxRetryDelayMs:0,timeoutMs:180000});
}});
let finalEvent;
for await (const event of stream) {
if(event.type==='done'||event.type==='error')finalEvent=event;
@ -754,47 +656,26 @@ export class DetailPiAgent {
const failure=confirmedProductionFailure(receipt,round.id);
if(['complete','failed'].includes(receipt.phase))host.productionRequests?.delete(requestScope);
if(failure)throw failure;
if(!valid||receipt.phase!=='complete')throw Error('原模型请求尚未核实,工具未执行');
if(!valid||receipt.phase!=='complete')throw Error(message.errorMessage ?? 'network error: inference stream did not complete');
if(!raw)throw Error('原始模型响应尚未读完,工具未执行');
const audit=auditResponse(raw,info.model.protocol);
if(message.content.filter(item=>item.type==='toolCall').length!==audit.calls.length)throw Error('原模型工具调用未完整返回');
await store.appendEvent({type:'usage',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,...usage});
await onEvent({type:'usage',id:round.id,model:selected.id,...usage});
output.push(finalEvent);output.end(message);
} catch(error){
if(round && !(error instanceof ProductionRequestFailed) && (scoped.isUnconfirmed?.(round.id)??scoped.hasUnconfirmedRequest)){
if(host.productionRequests)await host.canvas.delta('正在按原请求号核查当前制作步骤').catch(()=>{});
const recovered=await readOriginal(round.id,selected,tools,{
signal:options.signal,waitForResult:Boolean(host.productionRequests),
}).catch(()=>({phase:'unknown'}));
const camera=await host.canvas.read().catch(()=>null);
if(recovered.message&&!options.signal?.aborted&&camera?.conversationActive===true&&!camera.writeBlocked){
host.productionRequests?.delete(requestScope);
output.push({type:'done',reason:recovered.message.stopReason,message:recovered.message});
output.end(recovered.message);
return;
}
if(recovered.phase==='failed'){
host.productionRequests?.delete(requestScope);
const requestId=recovered.requestId??round.id;
error=confirmedProductionFailure(recovered, round.id)??
Error('模型服务已确认制作请求失败(原请求 '+requestId+')');
} else if(!['complete','rejected'].includes(recovered.phase)){
const pending={id:round.id,requestId:recovered.requestId,phase:recovered.phase,detailSlot:requestScope,modelRole:'detail'};
host.productionRequests?.set(requestScope,pending);
error=new ProductionRequestPending(pending);
}
}
throw error;
return message;
} catch(error) {
if (error instanceof ProductionOutputLimit || error instanceof InvalidToolReply || options.signal?.aborted) throw error;
return {role:'assistant',api,provider:selected.provider,model:selected.id,content:[],stopReason:'error',
errorMessage:error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+error.message : error.message,
timestamp:Date.now(),usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{...cost,total:0}}};
}
}, piRetryPolicy, options.signal, async ({ failure, attempt, maxAttempts, delayMs }) => {
if (scoped.failed) {
await scoped.close();
scoped=broker.forDetailSlot(requestScope);
}
await store.appendEvent({type:'model_retry',id:round.id,requestScope,slotId,
httpStatus:failure.httpStatus,attempt,maxAttempts,waitMs:delayMs});
});
}, piRetryPolicy, options.signal, {onRetryScheduled:async(attempt,maxAttempts,delayMs)=>{
await store.appendEvent({type:'pi_retry',id:round?.id,requestScope,slotId,attempt,maxAttempts,delayMs});
}});
if (result.stopReason === 'error' || result.stopReason === 'aborted') {
output.push({type:'error',reason:result.stopReason,error:result});
} else output.push({type:'done',reason:result.stopReason,message:result});
output.end(result);
} catch (error) {
if(error instanceof ProductionRequestPending||error instanceof ProductionRequestFailed||error instanceof ProductionOutputLimit||
error instanceof InvalidToolReply)pendingError=error;
@ -814,20 +695,29 @@ export class DetailPiAgent {
} finally { if(scoped)await scoped.close(); }
};
host.session = session;
session.subscribe(event => {
if (event.type === 'compaction_start') host.compacting = true;
if (event.type === 'auto_retry_start') {
host.presentation = new StreamPresentation();
void store.appendEvent({type:'pi_retry',attempt:event.attempt,maxAttempts:event.maxAttempts,delayMs:event.delayMs}).catch(()=>{});
}
if (event.type === 'compaction_end') {
host.compacting = false;
void store.appendEvent({type:'pi_compaction',reason:event.reason,
completed:Boolean(event.result),tokensBefore:event.result?.tokensBefore}).catch(()=>{});
}
});
activatePhotoCraftTools(session, customTools);
if (productionGoal) session.setActiveToolsByName(['context_read','memory_search',...productionTools.map(([name])=>name)]);
if (productionGoal) session.setActiveToolsByName(['context_read','memory_search','codemode','tool_search',
...customTools.filter(tool=>tool.defaultActive!==false
&& (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(); } });
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.
let outputMeter = new StreamOutputMeter();
session.agent.subscribe(async event => {
if (event.type === 'message_end' && event.message.role === 'assistant' &&
['stop','toolUse'].includes(event.message.stopReason) && host.localBudgetRecovery?.phase === 'committed') {
const {planId}=host.localBudgetRecovery;
host.localBudgetRecovery.phase = 'completed';
await store.appendEvent({type: 'local_budget_recovery_completed', planId});
}
if (event.type === 'message_start' && event.message.role === 'assistant') outputMeter = new StreamOutputMeter();
if (event.type === 'message_update' && !host.compacting) {
const update = event.assistantMessageEvent;
@ -955,14 +845,7 @@ export class DetailPiAgent {
}
}
async prompt(text, options = {}) {
return this.exclusive(async () => {
try { return await this.promptTurn(text, options); }
catch (error) {
if (this.localBudgetRecovery) this.localBudgetRecovery.phase = 'failed';
throw error;
}
finally { this.session.setAutoCompactionEnabled(false); }
});
return this.exclusive(() => this.promptTurn(text, options));
}
generatedCandidateReply() {
if (!this.generatedCandidates.size) return null;
@ -972,60 +855,11 @@ export class DetailPiAgent {
if (this.workflowStopReason) reply += `\n\n后续操作已停止。${this.workflowStopReason}`;
return reply;
}
async checkLocalBudgetRecovery(signal) {
const recovery = this.localBudgetRecovery;
if (signal?.aborted || recovery?.signal?.aborted || this.disposed) throw Error('预算压缩已停止;原工具结果与历史已保留');
if (this.compromised) throw Error('本地会话锁失效,已停止预算压缩');
if (this.canvasNotificationsDetached || this.canvasWritesStopped || this.workflowBindingChanged) throw Error('原项目状态已变化,预算压缩未继续;原工具结果已保留');
const latest = this.broker ? await this.broker.info() : this.info;
if (this.inflight || hasBlockingOriginal(latest.pending, this.goalRequestScope)) {
throw Error('本项目仍有未知请求,预算压缩未继续;请先核查原请求');
}
if (latest.accountScope !== this.store.identity.scope || latest.model.id !== this.info.model.id || latest.model.protocol !== this.info.model.protocol) throw Error('账户或模型已变化,预算压缩未继续;原记录已保留');
if ((await this.store.get('recovered-tools.json', [])).some(tool => tool.phase === 'review')) throw Error('原工具建议尚待核对,预算压缩未继续');
if (await hasCompactionReviewForBranch(this, recovery?.branchHash)) throw Error('原分支摘要尚待核对,不能重复摘要;原记录已保留');
if (this.canvas) {
const state = await this.canvas.read();
const expectedDocument=this.productIdentity.documentId;
// Production reads the private run status without copying the full canvas context.
const scopedDocument=this.productionGoal&&state.conversationActive===true&&state.run===this.canvas.run?
this.canvas.documentId:undefined;
if (state.conversationActive === false || state.writeBlocked || (expectedDocument && (state.context?.id??scopedDocument) !== expectedDocument)) throw Error('原项目已切换或接手,预算压缩未继续;原记录已保留');
}
if (signal?.aborted || recovery?.signal?.aborted || this.disposed) throw Error('预算压缩已停止;原工具结果与历史已保留');
}
async localBudgetOverflow(reason, inputChars, signal) {
const failure = Error(`${reason},本轮未完成;未发起该次模型请求,原工具结果与历史已保留`);
// Pi can compact again after a successful response, but not for the same failed request.
if (this.compacting || this.localBudgetRecovery && this.localBudgetRecovery.phase !== 'completed') return failure;
await this.checkLocalBudgetRecovery(signal);
const branch = this.manager.getBranch();
const recovery = {phase: 'armed', branchHash: digest(branch), branchLength: branch.length, leafId: this.manager.getLeafId(), signal, inputChars, reason};
this.localBudgetRecovery = recovery;
await this.store.appendEvent({type: 'local_budget_recovery_armed', inputChars, originalBranchHash: recovery.branchHash, originalLeafId: recovery.leafId, modelCallSkipped: true});
signal?.throwIfAborted();
this.session.setAutoCompactionEnabled(true);
const overflow = Error(`${LOCAL_CONTEXT_OVERFLOW}: ${reason}(${inputChars} chars);本地派发前拦截,未发起该次模型请求`);
overflow.localBudgetRecovery = recovery;
return overflow;
}
projectModelContext(context, injected) {
if (this.productionGoal && !this.compacting) injected.productionGoal = {...this.productionGoal,objective:productionObjective};
return transportProjection(normalizeContext({messages: [...context.messages, {role: 'system', content: '当前项目规则快照与已确认事实(每次调用重新注入,以此为准):\n' + JSON.stringify(injected), timestamp: 0}]}),
{bindingHash: this.store.hash, version: this.currentWorkflow?.version, templateOriginal: this.templateOriginal,
production: Boolean(this.productionGoal)});
}
async projectedPromptChars(text) {
return contextTextLength(await this.projectedContext(text));
}
async projectedContext(text, images = []) {
const injected = await this.modelContext();
injected.currentProduct = this.productEvidence;
if (this.currentWorkflow) injected.currentWorkflow = this.currentWorkflow;
const context = normalizeContext({systemPrompt: this.session.agent.state.systemPrompt, tools: this.session.agent.state.tools,
messages: [...this.session.messages, ...(text ? [{role: 'user', content: images.length ? [{ type: 'text', text }, ...images] : text, timestamp: 0}] : [])]});
const projected = this.projectModelContext(context, injected);
return this.protocolMode === 'structured-json' ? jsonToolContext(projected) : projected;
if (this.compacting) return context;
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);
@ -1044,37 +878,20 @@ export class DetailPiAgent {
if (typeof text !== 'string' || !text.trim() || text.length > 6000) throw Error('请输入6000字以内的要求');
const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info);
this.firstTurnBrokerInfo = null;
if (hasBlockingOriginal(latest.pending, this.goalRequestScope, !!this.productionGoal)) throw Error('本项目仍有未知请求,先核查原请求;不会重发');
if (latest.accountScope !== this.store.identity.scope) throw Error('账户与项目不一致;原草稿已保留');
if (latest.model.id !== this.info.model.id || latest.model.protocol !== this.info.model.protocol) throw Error('用户已更换模型,请重新打开会话后再调用');
if (this.session.isStreaming) throw Error('本轮尚未结束');
const thinking = !this.productionGoal && /^\/thinking\s+(off|minimal|low|medium|high|xhigh|max)\s*$/u.exec(text.trim());
if (thinking) {
if (!this.session.model?.reasoning && thinking[1]!=='off') throw Error('当前模型线路没有发布可用的推理参数');
this.session.setThinkingLevel(thinking[1]);
await atomic(path.join(this.store.dir,'session.json'),{file:this.manager.getSessionFile()});
return {text:`思考档位已设为 ${this.session.thinkingLevel}。`,rounds:0};
}
if (this.nativeToolActive) throw Error('原操作仍在执行,请先等待或核查;不会重发');
if (requiredTool && !this.session.getActiveToolNames().includes(requiredTool)) throw Error('指定工具未开放');
this.requiredTool = null;
this.goalStageResult=null;
this.goalPendingOriginal=undefined;
this.nextGoalRetryOf=undefined;
const originalGoal = this.goalRequestScope && latest.pending?.find(request => request.detailSlot === this.goalRequestScope);
if (originalGoal) {
const recovered = await this.recoverTurn(originalGoal.id, {executeReadOnly:false});
if (recovered.internalCompaction && recovered.phase === 'unknown') {
this.goalPendingOriginal = originalGoal.id;
await closeProductionTurn(this);
return this.goalStageResult;
}
if (recovered.phase === 'unknown') {
const deadline = this.productionGoal?.deadline;
const sameTask = deadline * 1000 > Date.now() && originalGoal.createdAt >= deadline - 45 * 60
&& ['dispatched','unknown','unavailable'].includes(originalGoal.phase);
this.goalPendingOriginal = originalGoal.id;
if (sameTask) {
this.nextGoalRetryOf = originalGoal.id;
} else {
await closeProductionTurn(this);
return this.goalStageResult;
}
}
}
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)
@ -1095,38 +912,18 @@ export class DetailPiAgent {
this.generatedCandidates = new Map();
this.canvasNotificationsDetached=false;this.canvasEndAttempted=false;
this.activityScope = activityScope(this.store.identity);
this.localBudgetRecovery = null;
this.compactionFailure = null;
this.knowledgeContext = null;
const images = [], quoted = [];
for (const item of referenceContent ?? []) {
let image;
if (typeof item.image === 'string' && item.image) {
images.push({ type: 'image', data: item.image, mimeType: 'image/jpeg' });
images.push({ type:'image',data:item.image,mimeType:item.mimeType??'image/jpeg' });
image = images.length;
}
const source = item.kind === 'candidate' ? '候选图' : item.kind === 'layer' ? '发送时的画布图层' : '本轮引用';
quoted.push({ label: item.label, source, ...(image ? { image } : {}), ...(typeof item.text === 'string' ? { text: item.text } : {}) });
}
const prompt = quoted.length ? text + '\n\n本条消息附带的画布引用(按图片顺序对应,以下文字为引用内容):' + JSON.stringify(quoted) : text;
const projection = this.imageProgressTurn || this.productionGoal ? null : await this.projectedContext(prompt, images);
const projectedChars = projection ? contextTextLength(projection) : 0;
if (projection) await this.store.appendEvent({type: 'automatic_compaction_budget', projectedChars, originalChars: JSON.stringify(this.session.messages).length});
if (projection && (projectedChars > 80_000 || exceedsModelBudget(projection, this.info.model, 0.8))) {
if (await hasCompactionReviewForBranch(this)) {
if (projectedChars > 120_000 || exceedsModelBudget(projection, this.info.model)) throw Error('原分支摘要尚未应用,本轮上下文超过输入预算;原记录保留,请先人工核对摘要或新建会话。未发起模型请求');
// The explicit new user turn has not reached SDK yet. Summarizing now
// would repeat the unchanged reviewed branch, while rejecting it would
// prevent any new branch from ever being created. Continue once under
// the provider's independently enforced hard budget; never replay the
// old summary or remove its review/checkpoint evidence.
await this.store.appendEvent({type: 'automatic_compaction_deferred', reason: 'unapplied_summary_same_branch', projectedChars});
} else {
await this.store.appendEvent({ type: 'automatic_compaction_started', reason: 'bounded-input-budget', projectedChars });
await this.compactTurn({ preserveBudget: true });
await this.store.appendEvent({ type: 'automatic_compaction_completed' });
}
}
this.requiredTool = requiredTool;
if (this.canvas) {
const begun = await this.canvas.begin(text);
@ -1151,16 +948,6 @@ export class DetailPiAgent {
this.productionSkills=await openEnterpriseSkills(this.store,selection,pins=>this.loadWholeDetailKnowledge(selection,undefined,false,pins));
this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'read'])]);
}
if (this.productionGoal && (goalContinuation || originalGoal)) {
try {
await resumeProductionCompaction(this);
} catch (error) {
if (!this.goalPendingOriginal) throw error;
await closeProductionTurn(this);
await this.notifyCanvas('end',this.goalStageResult.text);
return this.goalStageResult;
}
}
if (!goalContinuation) await this.store.recordUserEvidence(text);
const running = this.productionGoal
? runPiProductionGoal(this, prompt, goalContinuation)
@ -1170,14 +957,12 @@ export class DetailPiAgent {
await running;
await closeProductionTurn(this);
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
if (this.localBudgetRecovery && this.localBudgetRecovery.phase !== 'completed' && !this.goalPendingOriginal) {
throw this.compactionFailure || Error('本轮预算压缩未完成或已停止;未继续模型请求,原工具结果与历史已保留');
}
const last = this.session.messages.filter(m => m.role === 'assistant').at(-1);
const useStageReceipt = last?.stopReason === 'error' && this.goalStageResult && !this.canvasWritesStopped;
if (last?.stopReason === 'aborted' || last?.stopReason === 'error' && !useStageReceipt) {
throw Error(last.errorMessage || '本轮未完成;保留原请求');
}
if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议');
const resultText = useStageReceipt ? this.goalStageResult.text :
this.generatedCandidateReply() ?? (this.templateOriginal && !this.templateImageRead
? '模板原图尚未读取,暂时无法确认视角。可以引用画布里的具体图位,再继续核对。'
@ -1216,7 +1001,6 @@ export class DetailPiAgent {
throw Error('整套详情页需要可识图的对话模型及完整的小壹客户端');
}
const pending=(await this.broker?.info())?.pending??[];
if(pending.length&&(!production||!pending.every(isProductPending)))throw Error('原模型请求待核查,暂未开始新步骤');
const begun=await this.canvas.begin(text);
this.activityScope=activityScope(this.store.identity,this.canvas,begun);
try {
@ -1299,22 +1083,13 @@ export class DetailPiAgent {
});
}
async compact() { return this.exclusive(() => this.compactTurn()); }
async compactTurn({ preserveBudget = false } = {}) {
const pending = this.broker ? (await this.broker.info()).pending : [];
if (hasBlockingOriginal(pending, this.goalRequestScope)) throw Error('有未知请求,不能启动压缩调用');
if ((await this.store.get('recovered-tools.json', [])).some(t => t.phase === 'review')) throw Error('原工具建议尚待核对,不能启动新模型调用');
if (await hasCompactionReviewForBranch(this)) throw Error('当前分支的原内部摘要尚未应用,不能重复摘要;原会话保留');
if (!preserveBudget) this.rounds = 0;
this.compacting = true;
this.compactionFailure = null;
try {
const result = await this.session.compact(COMPACTION_INSTRUCTIONS);
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
async compact() {
return this.exclusive(async () => {
this.rounds = 0;
const result = await this.session.compact();
await atomic(path.join(this.store.dir, 'session.json'), {file:this.manager.getSessionFile()});
return result;
} catch (error) {
throw this.compactionFailure || error;
} finally { this.compacting = false; this.activeCompaction = null; }
});
}
async recover(id, options = {}) { return this.exclusive(() => this.recoverTurn(id, options)); }
async recoverTurn(id, { executeReadOnly = false } = {}) {
@ -1340,20 +1115,15 @@ export class DetailPiAgent {
return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose.kind==='whole-detail-review'
?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)};
}
if (internalCompaction && !['complete','received'].includes(record.phase)) return recoverCompactionWithoutResult(this, id, record, purpose);
if (internalCompaction) {
return {phase:['complete','received','failed','rejected'].includes(record.phase)?'complete':'unknown',
requestId:record.requestId,reposted:false,internalCompaction:true,toolsExecuted:0,canvasWrites:0};
}
if (record.phase === 'failed') return { phase: 'failed', requestId: record.requestId, reposted: false };
if (record.phase === 'unavailable') return {phase: 'unknown', requestId: record.requestId, reposted: false,
needsManualReview: true, reason: '原对话结果不可用,保留待核查,未自动放弃或重发', toolsExecuted: 0, canvasWrites: 0};
// New summaries have an explicit persisted no-tools wire mode. Legacy
// summaries retain the original host mode; prose is never guessed to be a
// valid structured-json envelope and recovered calls are never executed.
const originalMode = internalCompaction && purpose.event.summaryProtocolMode === 'native-tools' ? 'native-tools' : this.protocolMode;
const message = await parseReceipt(record, this.session.model, originalMode, internalCompaction ? [] : this.session.agent.state.tools);
if (internalCompaction && (message.stopReason !== 'stop' || message.content.some(content => content.type === 'toolCall'))) {
return {phase: 'unknown', requestId: record.requestId, internalCompaction: true, reason: '原摘要不完整或包含工具,未应用压缩或执行工具', reposted: false};
}
const message = await parseReceipt(record, this.session.model, this.protocolMode, this.session.agent.state.tools);
if (record.phase === 'received') await this.broker.confirm(id, record.bodyHash, true, message.stopReason);
if (internalCompaction) return recoverCompaction(this, id, record, message, purpose);
if (message.stopReason === 'length') return { phase: 'complete', usable: false, reason: 'output_limit', toolsExecuted: 0, reposted: false };
const entries = this.manager.getEntries(), calls = message.content.filter(c => c.type === 'toolCall');
const recorded = message.responseId && entries.some(e => e.type === 'message' && e.message.role === 'assistant' && e.message.responseId === message.responseId);

View File

@ -1,309 +0,0 @@
import path from 'node:path';
import fs from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { compact as sdkCompact, createSyntheticSourceInfo, VERSION } from '@earendil-works/pi-coding-agent';
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
import { atomic, digest } from './store.mjs';
import { transportProjection } from './context-budget.mjs';
import { parseReceipt } from './receipt.mjs';
import { piGoalState } from './production-goal.mjs';
const safeId = id => typeof id === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(id);
const instructions = '保留当前目标、商品事实、用户决定、店铺和品类绑定及已读规则和版本。记录尚未完成的图位、原请求编号和核查状态。待确认信息保留原状态,恢复时以制作工具的当前记录为准。历史原文仍在会话树。';
export const COMPACTION_INSTRUCTIONS = instructions;
// SDK may add thinkingLevel metadata; bind the actual empty failed response,
// independent of object property order and that presentation-only addition.
export const localBudgetFailureHash = message => digest([message.role, message.api, message.provider, message.model,
message.content, message.stopReason, message.errorMessage, message.timestamp]);
const serializePreparation = prep => ({ ...prep, fileOps: Object.fromEntries(Object.entries(prep.fileOps).map(([key, values]) => [key, [...values]])) });
const restorePreparation = prep => ({ ...prep, fileOps: Object.fromEntries(Object.entries(prep.fileOps).map(([key, values]) => [key, new Set(values)])) });
const branchHash = host => digest(host.manager.getBranch());
const metadataPath = id => `compaction-requests/${id}.json`;
const sha256 = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
/** A retained summary only fences the branch it summarized. A later user turn
* creates a new branch and must not be permanently blocked by old review work. */
export async function hasCompactionReviewForBranch(host, originalBranchHash) {
const pending = await host.store.get('recovered-compactions.json', []), current = originalBranchHash ?? branchHash(host);
// Earlier local versions did not persist this field. Fence the first branch
// observed after upgrade once, rather than globally blocking every future one.
let changed = false;
for (const row of pending) if (row.phase === 'review' && !sha256(row.branchHash)) { row.branchHash = current; changed = true; }
if (changed) await atomic(path.join(host.store.dir, 'recovered-compactions.json'), pending);
return pending.some(row => row.phase === 'review' && row.branchHash === current);
}
/** Native verifies this proof against the original authenticated key and ledger.
* Pi additionally checks the public identity fields before acknowledging a
* missing internal summary. A 410 response alone is never a terminal proof. */
export function verifiedOriginalNoResult(record, id) {
const proof = record.originalLookup;
const status = record.phase === 'failed' ? 'failed' : ['unavailable', 'rejected'].includes(record.phase) ? 'succeeded' : null;
return Boolean(status && safeId(id) && proof?.verified === true && proof.method === 'GET'
&& proof.path === '/api/external/requests/by-idempotency-key' && proof.httpStatus === 200
&& proof.idempotencyKey === id && safeId(record.requestId) && proof.requestId === record.requestId
&& proof.status === status && proof.resultAvailable === false
&& proof.resultPath === `/api/external/requests/${record.requestId}/result`
&& sha256(record.bodyHash) && proof.bodyHash === record.bodyHash
&& sha256(proof.lookupSha256) && sha256(proof.bindingHash) && proof.keyFingerprintMatches === true);
}
/** Public SDK hook supplies the exact cut point before any summary call. No
* private prepareCompaction import or mutation of SDK session/archive entries. */
export function compactionExtension(host) {
const source = 'jiansun:durable-compaction';
return {path: source, resolvedPath: source, sourceInfo: createSyntheticSourceInfo(source, {source: 'local'}),
tools: new Map(), messageRenderers: new Map(), commands: new Map(), flags: new Map(), shortcuts: new Map(),
handlers: new Map([['session_before_compact', [async event => {
const recovery = host.localBudgetRecovery;
const localOverflow = recovery?.phase === 'armed' && event.reason === 'overflow' && event.willRetry === true;
const wasCompacting = host.compacting;
try {
if (!host.compacting && !localOverflow) return {cancel: true};
if (host.resumingCompaction) {
const {plan,planHash,parts}=host.resumingCompaction;
if (!currentCheckpoint(host,plan)) return {cancel:true};
host.activeCompaction={plan,planHash,part:0};
const result=await sdkCheckpoint(host,plan,parts,event.signal,(part,...args)=>{
host.activeCompaction.part=part-1;
return host.session.agent.streamFunction(...args);
});
return {compaction:{...result,details:{...result.details,jiansunCompactionPlanId:plan.id}}};
}
if (localOverflow) {
host.session.setAutoCompactionEnabled(false);
await host.checkLocalBudgetRecovery(event.signal);
// SDK owns this omission. Verify it only hid our empty, undispatched
// error, after the exact frozen branch; never conceal a real response.
const branch = host.manager.getBranch(), tail = branch.slice(recovery.branchLength);
const goal = host.productionGoal && piGoalState(host.manager);
const omission = tail.at(-1);
const proof = {branchUnchanged: digest(branch.slice(0, recovery.branchLength)) === recovery.branchHash,
onlyFailureAndOmission: tail.length >= 2 && tail.slice(1,-1).every(entry =>
goal && entry.type === 'custom' && entry.customType === 'pi-goal' && entry.data?.goal?.id === goal.id),
parentUnchanged: tail[0]?.parentId === recovery.leafId,
failureUnchanged: tail[0]?.type === 'message' && localBudgetFailureHash(tail[0].message) === recovery.errorHash,
exactOmission: omission?.type === 'context_edit' && omission.targetId === tail[0]?.id && omission.replacement === null};
if (Object.values(proof).some(value => !value)) {
await host.store.appendEvent({type: 'local_budget_recovery_rejected', ...proof});
throw Error('本地预算恢复分支已变化,未派发摘要;原记录已保留');
}
recovery.phase = 'preparing';
host.compacting = true;
}
const raw = event.preparation;
const options = {bindingHash: host.store.hash, version: host.currentWorkflow?.version, production: Boolean(host.productionGoal)};
const preparation = { ...raw,
// enabled controls SDK scheduling, not cut points or summary content.
// Persist the normal disabled policy so recovery still compares every
// saved setting exactly after this single-use runtime switch is off.
...(localOverflow ? {settings: {...raw.settings, enabled: false}} : {}),
messagesToSummarize: transportProjection({messages: raw.messagesToSummarize}, options).messages,
turnPrefixMessages: transportProjection({messages: raw.turnPrefixMessages}, options).messages,
};
const expectedParts = raw.isSplitTurn && raw.turnPrefixMessages.length ? (raw.messagesToSummarize.length ? 2 : 1) : 1;
const plan = {schema: 1, purpose: 'compaction', summaryProtocolMode: 'native-tools', sdkVersion: VERSION, id: randomUUID(), identity: host.store.identity,
bindingHash: host.store.hash, sessionFile: host.manager.getSessionFile(), leafId: host.manager.getLeafId(), branchHash: branchHash(host),
...(host.goalRequestScope ? {productionRequestScope:host.goalRequestScope} : {}),
model: {id: host.info.model.id, protocol: host.info.model.protocol}, firstKeptEntryId: raw.firstKeptEntryId, tokensBefore: raw.tokensBefore,
expectedParts, preparation: serializePreparation(preparation), instructions: event.customInstructions || instructions,
...(localOverflow ? {trigger: 'local-input-budget', originalBranchHash: recovery.branchHash, originalLeafId: recovery.leafId} : {})};
const planHash = digest(plan);
await atomic(path.join(host.store.dir, 'compaction-plans', plan.id + '.json'), plan);
await host.store.appendEvent({type: 'compaction_prepared', planId: plan.id, planHash, branchHash: plan.branchHash,
firstKeptEntryId: plan.firstKeptEntryId, tokensBefore: plan.tokensBefore, purpose: 'compaction'});
host.activeCompaction = {plan, planHash, part: 0};
if (localOverflow) { recovery.planId = plan.id; recovery.phase = 'prepared'; }
const result = await sdkCompact(preparation, host.session.model, 'native-broker-only', undefined, plan.instructions, event.signal,
'off', host.session.agent.streamFunction, undefined, {enabled: false, maxRetries: 0});
return {compaction: {...result, details: {...result.details, jiansunCompactionPlanId: plan.id}}};
} catch (error) {
// ExtensionRunner catches thrown handlers and would run the default
// summarizer. Explicit cancellation prevents that second dispatch.
host.compactionFailure = error;
if (localOverflow) recovery.phase = 'failed';
return {cancel: true};
} finally {
if (localOverflow) {
host.session.setAutoCompactionEnabled(false);
host.compacting = wasCompacting;
host.activeCompaction = null;
}
}
}]]]),
};
}
export async function prepareCompactionRequest(host, id) {
const active = host.activeCompaction;
if (!host.compacting || !active || !safeId(id) || branchHash(host) !== active.plan.branchHash) throw Error('压缩断点或会话分支已变化,未派发摘要');
const part = ++active.part;
if (part > active.plan.expectedParts) throw Error('摘要调用超出已保存的SDK计划,未派发');
const metadata = {schema: 1, purpose: 'compaction', summaryProtocolMode: 'native-tools', id, planId: active.plan.id, planHash: active.planHash, part,
firstKeptEntryId: active.plan.firstKeptEntryId, tokensBefore: active.plan.tokensBefore, branchHash: active.plan.branchHash, bindingHash: host.store.hash};
await atomic(path.join(host.store.dir, metadataPath(id)), metadata);
return metadata;
}
export async function requestPurpose(host, id) {
const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;});
const events = text.split('\n').filter(Boolean).map(line => {try {return JSON.parse(line);} catch {return null;}}).filter(Boolean);
const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash));
if (index < 0) throw Error('原请求没有当前会话归属记录');
const event = events[index];
if (event.purpose === 'compaction') return {kind: 'compaction', event};
if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event};
if (event.purpose === 'conversation') return {kind: 'conversation', event};
// Legacy automatic summaries lack a durable cut-point contract. Recognize
// their purpose, but never guess a checkpoint from the returned prose.
let started = -1, finished = -1;
for (let i = 0; i < index; i++) {
if (events[i].type === 'automatic_compaction_started') started = i;
if (events[i].type === 'automatic_compaction_completed') finished = i;
}
if (started > finished) return {kind: 'legacy-compaction', event};
return {kind: 'conversation', event};
}
async function retainReview(host, id, record, message, reason, extra = {}) {
const pending = await host.store.get('recovered-compactions.json', []);
if (!pending.some(row => row.id === id)) {
const metadata = await host.store.get(metadataPath(id), null);
const originalBranch = metadata?.id === id && metadata.bindingHash === host.store.hash && sha256(metadata.branchHash) ? metadata.branchHash : branchHash(host);
await atomic(path.join(host.store.dir, 'compaction-recovered', id + '.json'), {id, requestId: record.requestId, purpose: 'compaction', reason, branchHash: originalBranch, message, ...extra});
pending.push({id, requestId: record.requestId, phase: 'review', reason, branchHash: originalBranch});
await atomic(path.join(host.store.dir, 'recovered-compactions.json'), pending);
}
return {phase: 'complete', requestId: record.requestId, reposted: false, internalCompaction: true, compactionApplied: false,
needsCompactionReview: true, toolsExecuted: 0, canvasWrites: 0, reason};
}
/** No result bytes exist to parse. Preserve the original SDK tree, retain the
* authenticated disposition separately, and only acknowledge the local ledger
* after that evidence is durable. Upstream success remains success. */
export async function recoverCompactionWithoutResult(host, id, record, purpose) {
if (purpose.kind === 'conversation' || !verifiedOriginalNoResult(record, id)) return {
phase: 'unknown', requestId: record.requestId, reposted: false, internalCompaction: purpose.kind !== 'conversation',
needsManualReview: true, reason: '原结果不可用的身份或终态尚未严格核实,保留待核查', toolsExecuted: 0, canvasWrites: 0};
const reason = record.originalLookup.status === 'failed' ? 'compaction_original_request_failed' : 'compaction_original_result_unavailable';
const result = await retainReview(host, id, record, null, reason, {originalLookup: record.originalLookup, originalResultUnavailable: true});
if (record.phase === 'unavailable') {
const settled = await host.broker.confirm(id, record.bodyHash, false, 'compaction_original_result_unavailable');
if (settled?.phase !== 'rejected') throw Error('原摘要不可用的本机回执尚未完成,原会话保留');
}
return {...result, originalResultUnavailable: true, originalExecutionStatus: record.originalLookup.status,
localDisposition: record.originalLookup.status === 'failed' ? 'failed' : 'rejected', originalTreePreserved: true};
}
function currentCheckpoint(host, plan) {
return plan.bindingHash === host.store.hash && sameIdentity(plan.identity, host.store.identity) &&
plan.sdkVersion === VERSION && plan.model.id === host.info.model.id && plan.model.protocol === host.info.model.protocol &&
host.manager.getLeafId() === plan.leafId && host.manager.getSessionFile() === plan.sessionFile &&
branchHash(host) === plan.branchHash &&
digest(plan.preparation.settings) === digest(host.session.settingsManager.getCompactionSettings(host.session.model)) &&
host.manager.getBranch().some(entry => entry.id === plan.firstKeptEntryId);
}
async function readCompactionParts(host, plan, planHash, directory, names, parts = new Map()) {
const attempts = new Set(parts.keys());
for (const name of names) {
const prior = await host.store.get(directory+'/'+name, null);
if (prior?.planId !== plan.id || prior.planHash !== planHash || prior.bindingHash !== host.store.hash ||
!safeId(prior.id) || !Number.isSafeInteger(prior.part) || prior.part < 1 || prior.part > plan.expectedParts) continue;
attempts.add(prior.part);
if (parts.has(prior.part)) continue;
const saved = await host.broker.read(prior.id).catch(() => null);
if (saved?.phase !== 'complete') continue;
const response = await parseReceipt(saved, host.session.model, 'native-tools', []);
if (response.stopReason === 'stop') parts.set(prior.part, response);
}
return {parts, attempts};
}
const storedEntries = (host, directory) => fs.readdir(path.join(host.store.dir,directory)).catch(error => {
if (error.code === 'ENOENT') return [];
throw error;
});
function sdkCheckpoint(host, plan, parts, signal, missingStream) {
let calls = 0;
return sdkCompact(restorePreparation(plan.preparation), host.session.model, 'native-broker-only', undefined, plan.instructions,
signal, 'off', (...args) => {
const part = parts.get(++calls);
if (!part) {
if (!missingStream) throw Error('原摘要未包含完整压缩计划');
return missingStream(calls,...args);
}
const stream = createAssistantMessageEventStream();
queueMicrotask(() => {stream.push({type: 'start', partial: part}); stream.push({type: 'done', reason: 'stop', message: part}); stream.end(part);});
return stream;
}, undefined, {enabled: false, maxRetries: 0});
}
async function applyCheckpoint(host, plan, parts) {
const result = await sdkCheckpoint(host,plan,parts);
if (branchHash(host) !== plan.branchHash || result.firstKeptEntryId !== plan.firstKeptEntryId || result.tokensBefore !== plan.tokensBefore) return false;
host.manager.appendCompaction(result.summary, result.firstKeptEntryId, result.tokensBefore,
{...result.details, jiansunCompactionPlanId: plan.id}, true, result.usage);
await atomic(path.join(host.store.dir, 'session.json'), {file: host.manager.getSessionFile()});
host.session.refreshContext();
await host.store.appendEvent({type: 'compaction_recovered', planId: plan.id, branchHash: plan.branchHash, toolsExecuted: 0});
return true;
}
// Resume a saved checkpoint before Pi adds new entries to the branch.
export async function resumeProductionCompaction(host) {
if (!host.broker || !host.goalBroker) return;
for (const name of await storedEntries(host,'compaction-plans')) {
const plan = await host.store.get('compaction-plans/'+name, null);
if (!plan || plan.productionRequestScope !== host.goalRequestScope || plan.leafId !== host.manager.getLeafId() ||
!currentCheckpoint(host,plan)) continue;
const planHash = digest(plan);
const directory = 'compaction-requests';
const {parts,attempts}=await readCompactionParts(host,plan,planHash,directory,await storedEntries(host,directory));
if (!parts.size || parts.size !== attempts.size) continue;
const remaining = parts.size < plan.expectedParts;
if (!remaining) return applyCheckpoint(host,plan,parts);
host.resumingCompaction={plan,planHash,parts};
try {
return await host.compactTurn({preserveBudget:true});
} finally {
host.resumingCompaction=null;
}
}
}
/** Reinterpret the retained response as an SDK checkpoint, never an ordinary assistant reply. */
export async function recoverCompaction(host, id, record, message, purpose) {
if (purpose.kind === 'legacy-compaction') return retainReview(host, id, record, message, 'legacy_checkpoint_not_proven');
const metadata = safeId(id) ? await host.store.get(metadataPath(id), null) : null;
if (!metadata || !safeId(metadata.planId) || metadata.purpose !== 'compaction' || metadata.summaryProtocolMode !== 'native-tools'
|| purpose.event.summaryProtocolMode !== metadata.summaryProtocolMode || metadata.id !== id || metadata.bindingHash !== host.store.hash
|| purpose.event.compactionPlanHash !== metadata.planHash || purpose.event.compactionPlanId !== metadata.planId) {
return retainReview(host, id, record, message, 'checkpoint_metadata_unproven');
}
const plan = await host.store.get(`compaction-plans/${metadata.planId}.json`, null);
if (!plan || plan.summaryProtocolMode !== metadata.summaryProtocolMode || digest(plan) !== metadata.planHash || plan.bindingHash !== host.store.hash || !sameIdentity(plan.identity, host.store.identity)
|| plan.sdkVersion !== VERSION || plan.model.id !== host.info.model.id || plan.model.protocol !== host.info.model.protocol) {
return retainReview(host, id, record, message, 'checkpoint_identity_unproven');
}
if (host.manager.getEntries().some(entry => entry.type === 'compaction' && entry.details?.jiansunCompactionPlanId === plan.id)) {
return {phase: 'complete', requestId: record.requestId, reposted: false, internalCompaction: true, compactionApplied: true, alreadyApplied: true, toolsExecuted: 0, canvasWrites: 0};
}
if (!currentCheckpoint(host,plan) || metadata.firstKeptEntryId !== plan.firstKeptEntryId || metadata.tokensBefore !== plan.tokensBefore) {
return retainReview(host, id, record, message, 'checkpoint_branch_or_parts_unproven');
}
const directory='compaction-requests';
const {parts,attempts}=await readCompactionParts(host,plan,metadata.planHash,directory,
await storedEntries(host,directory),new Map([[metadata.part,message]]));
if (parts.size < plan.expectedParts) {
if (plan.productionRequestScope && attempts.size === parts.size) return {phase:'complete',requestId:record.requestId,
reposted:false,internalCompaction:true,compactionApplied:false,compactionContinuation:true,toolsExecuted:0,canvasWrites:0};
return retainReview(host, id, record, message, 'checkpoint_branch_or_parts_unproven');
}
if (!await applyCheckpoint(host,plan,parts)) {
return retainReview(host, id, record, message, 'checkpoint_changed_during_recovery');
}
return {phase: 'complete', requestId: record.requestId, reposted: false, internalCompaction: true, compactionApplied: true, toolsExecuted: 0, canvasWrites: 0};
}
const sameIdentity = (left, right) => left?.scope === right?.scope && left?.project === right?.project;

View File

@ -1,180 +0,0 @@
import { workflowHistory } from './workflow-context.mjs';
import { presentText } from './stream-presentation.mjs';
const parse = m => { try { return JSON.parse(m.content.filter(c => c.type === 'text').map(c => c.text).join('')); } catch { return null; } };
const short = (s, n = 240) => {
if (typeof s !== 'string') return undefined;
let value = '', count = 0;
for (const c of s) { if (count++ === n) return { value, truncated:true }; value += c; }
return { value, truncated:false };
};
const numbers = (array, length) => Array.isArray(array) && array.length === length && array.every(v => typeof v === 'number' && Number.isFinite(v)) ? [...array] : undefined;
const layerSnapshot = (layer, limit = 240) => {
if (!layer || !Number.isSafeInteger(layer.id) || layer.id < 1) return undefined;
const result = { id: layer.id };
for (const key of ['name', 'kind', 'text']) {
const s = short(layer[key], limit);
if (s) { result[key] = s.value; if (s.truncated || layer[`${key}Truncated`] === true) result[`${key}Truncated`] = true; }
}
for (const key of ['visible', 'opacity']) if (typeof layer[key] === 'boolean' || (typeof layer[key] === 'number' && Number.isFinite(layer[key]))) result[key] = layer[key];
if (layer.appearance && typeof layer.appearance === 'object') {
const a = layer.appearance, appearance = {};
const font = short(a.font, 120); if (font) { appearance.font = font.value; if (font.truncated) appearance.fontTruncated = true; }
if (typeof a.sizePt === 'number' && Number.isFinite(a.sizePt)) appearance.sizePt = a.sizePt;
if (typeof a.color === 'string' && /^#[0-9a-f]{6,8}$/i.test(a.color)) appearance.color = a.color;
const color = numbers(a.color, 4); if (color) appearance.color = color;
const matrix = numbers(a.transform?.m, 6); if (matrix) appearance.transform = { m:matrix };
if (Object.keys(appearance).length) result.appearance = appearance;
}
if (layer.bounds && ['x0','y0','x1','y1'].every(k => typeof layer.bounds[k] === 'number' && Number.isFinite(layer.bounds[k]))) {
result.bounds = Object.fromEntries(['x0','y0','x1','y1'].map(k => [k, layer.bounds[k]]));
}
return result;
};
/** A transport projection only: the SDK's original transcript and tool evidence stay intact. */
export function projectContext(context,{bindingHash,templateOriginal,production}={}) {
const currentTurn=context.messages.findLastIndex(message=>message.role==='user');
const canvasResults = context.messages.map((m, index) => m.role === 'toolResult' && ['canvas_read', 'canvas_edit'].includes(m.toolName) && !m.isError ? index : -1).filter(i => i >= 0);
const newest = canvasResults.at(-1), detailed = new Set(canvasResults.slice(-9, -1));
const calls = new Map();
const dispatchCalls = new Map();
let documentId, revision, layers = new Map();
const summaries = new Map();
for (let index = 0; index < context.messages.length; index++) {
const m = context.messages[index];
// A new user turn may bind another project or account. Do not carry an
// unscoped canvas observation across that boundary.
if (m.role === 'user') { documentId = undefined; revision = undefined; layers = new Map(); }
if (m.role === 'assistant' && Array.isArray(m.content)) for (const c of m.content) {
if (c.type === 'toolCall' && typeof c.id === 'string' && ['canvas_read','canvas_edit'].includes(c.name)) calls.set(c.id, c);
if (c.type === 'toolCall' && c.name === 'delegate_image_slots' && Array.isArray(c.arguments?.slotIds))
dispatchCalls.set(c.id, new Set(c.arguments.slotIds));
}
if (m.role !== 'toolResult' || !['canvas_read','canvas_edit'].includes(m.toolName)) continue;
const call = calls.get(m.toolCallId), value = parse(m);
if (m.isError || !value || !call || call.name !== m.toolName) { documentId = undefined; revision = undefined; layers = new Map(); continue; }
if (m.toolName === 'canvas_read') {
const doc = value.context?.id, rev = value.revision;
if (!Number.isSafeInteger(doc) || !Number.isSafeInteger(rev)) { documentId = undefined; revision = undefined; layers = new Map(); continue; }
if (doc !== documentId || rev !== revision) layers = new Map();
documentId = doc; revision = rev;
const items = Array.isArray(value.context?.layers) ? value.context.layers : [];
for (const item of items) { const snap = layerSnapshot(item); if (snap) layers.set(snap.id, snap); }
const target = call.arguments?.layer;
const page = items.slice(0, 8).map(item => layerSnapshot(item, 64)).filter(Boolean);
summaries.set(index, { documentId:doc, revision:rev, ...(Number.isSafeInteger(target) && layers.has(target) ? { layer:layers.get(target) } : { layers:page, layersTruncated:items.length > 8 }),
...(Number.isSafeInteger(value.context.totalLayers) ? { totalLayers:value.context.totalLayers } : {}),
...(typeof value.context.hasMore === 'boolean' ? { hasMore:value.context.hasMore } : {}) });
} else {
const args = call.arguments, target = args?.params?.layer;
const valid = value.applied === true && Number.isSafeInteger(target) && Number.isSafeInteger(value.revision);
const receiptDoc = Number.isSafeInteger(value.documentId) && value.documentId > 0 ? value.documentId : undefined;
const chained = valid && documentId !== undefined && (receiptDoc === undefined || receiptDoc === documentId)
&& args.revision === revision && value.revision > revision;
const after = valid && value.layer?.id === target ? layerSnapshot(value.layer) : undefined;
const before = chained ? layers.get(target) : undefined;
const run = typeof value.run === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(value.run) ? value.run : undefined;
summaries.set(index, { ...(receiptDoc !== undefined ? { documentId:receiptDoc } : chained ? { documentId } : {}),
...(run ? { run } : {}), ...(value.metadataUnavailable === true ? { metadataUnavailable:true } : {}),
revision:value.revision, applied:value.applied === true,
...(Number.isSafeInteger(target) ? { layerId:target } : {}), ...(typeof args?.command === 'string' && ['type.edit','layer.translate','layer.setProps'].includes(args.command) ? { command:args.command } : {}),
before:before ?? 'unknown', after:after ?? 'unknown' });
if (chained) { revision = value.revision; layers = new Map(); if (after) layers.set(target, after); }
else { documentId = undefined; revision = undefined; layers = new Map(); }
}
}
const ruleResults = context.messages.map((m, index) => m.role === 'toolResult' && m.toolName === 'context_read' && !m.isError ? index : -1).filter(i => i >= 0);
const newestRule = ruleResults.findLast(index => index > currentTurn);
const screenReadBatch = context.messages.findLastIndex(m=>m.role==='assistant' &&
m.content?.some(block=>block.type==='toolCall'&&block.name==='read_output_screen'));
const latestImageReview = context.messages.findLastIndex(m=>m.role==='toolResult'&&
m.toolName==='review_image_slots'&&!m.isError);
const latestCopyRead = context.messages.findLastIndex(m=>m.role==='toolResult'&&
m.toolName==='read_copy_fields'&&!m.isError);
const latestProductionPlan = context.messages.findLastIndex(m=>m.role==='toolResult'&&
m.toolName==='plan_production'&&!m.isError);
const reviewedScreens = new Map();
for (let index=screenReadBatch+1; index<context.messages.length; index++) {
const message = context.messages[index];
if(message.role!=='toolResult'||message.toolName!=='review_output_screen'||message.isError)continue;
const result = parse(message);
if(Number.isSafeInteger(result?.page)&&typeof result.passed==='boolean')reviewedScreens.set(result.page,index);
}
const messages = context.messages.map((m, index) => {
if (templateOriginal && index < currentTurn && m.role === 'user' && Array.isArray(m.content) && m.content.some(block => block.type === 'image')) {
return { ...m, content: [...m.content.filter(block => block.type !== 'image'),
{type:'text',text:'历史引用的图片仅属于当时的消息,无法用于判定本轮模板原图。'}] };
}
if (m.role === 'assistant' && Array.isArray(m.content)) {
m = { ...m, content:m.content.map(block => block.type === 'text' ? { ...block, text:presentText(block.text) } : block) };
}
if (m.role === 'toolResult' && Object.hasOwn(m, 'details')) { m = { ...m }; delete m.details; }
if(m.role==='toolResult'&&m.toolName==='read_output_screen') {
if(index<Math.max(currentTurn,screenReadBatch)||(reviewedScreens.get(parse(m)?.page)??-1)>index) {
return {...m,content:m.content.filter(block=>block.type!=='image')};
}
}
if(m.role==='toolResult'&&m.toolName==='plan_production'&&!m.isError&&index<latestProductionPlan) {
const receipt=parse(m);
if(receipt?.outputId) return {...m,content:[{type:'text',text:JSON.stringify({
outputId:receipt.outputId,archivedPlan:m.toolCallId,note:'此策划快照已归档,以最新策划回执和对应图位的原请求状态为准。',
})}]};
}
if(m.role==='toolResult'&&m.toolName==='delegate_image_slots'&&!m.isError&&dispatchCalls.has(m.toolCallId)){
const receipt=parse(m);
if(Array.isArray(receipt?.pictures)){
const requested=dispatchCalls.get(m.toolCallId);
const blocked=receipt.pictures.filter(row=>requested.has(row.id)||requested.has(row.field))
.map(({id,field,state,reason,review,pendingOriginal})=>({id,field,state,reason:reason??review?.reason,pendingOriginal}));
return {...m,content:[{type:'text',text:JSON.stringify({assigned:receipt.assigned,rejected:receipt.rejected,blocked})}]};
}
}
if(m.role==='toolResult'&&m.toolName==='review_image_slots'&&!m.isError&&index<latestImageReview){
const receipt=parse(m);
if(receipt?.pictures) {
delete receipt.pictures;
delete receipt.fields;
return {...m,content:[{type:'text',text:JSON.stringify(receipt)}]};
}
}
if(m.role==='toolResult'&&['plan_production','read_copy_fields'].includes(m.toolName)&&
!m.isError&&index<latestCopyRead){
const receipt=parse(m);
if(receipt?.fields) {
delete receipt.fields;
return {...m,content:[{type:'text',text:JSON.stringify(receipt)}]};
}
}
if(m.role==='toolResult'&&['ekb_read_image','canvas_template_image','canvas_candidate_image'].includes(m.toolName)&&index<currentTurn&&m.content.some(c=>c.type==='image')) {
return {...m,content:[...m.content.filter(c=>c.type!=='image'),{type:'text',text:'历史图片保留来源记录;本轮需要查看时重新读取当前授权和指定版本。'}]};
}
let staleBinding=false;
if(ruleResults.includes(index)&&bindingHash){
try{const old=JSON.parse(m.content.filter(c=>c.type==='text').map(c=>c.text).join(''));staleBinding=typeof old.bindingHash==='string'&&old.bindingHash!==bindingHash;}catch{}
}
if (ruleResults.includes(index) && (index !== newestRule||staleBinding)) return { ...m, content: [{ type: 'text', text: JSON.stringify({ archivedRuleResult: m.toolCallId, note: staleBinding?'此为旧规则域历史,不能作为当前店铺或品类的依据。':'原规则读取结果保存在会话记录中,需要当前依据时按主题读取。' }) }] };
if (production && m.role === 'toolResult' && m.content.some(item => item.type === 'text' && item.text.length > 48_000)) {
const text = m.content.filter(item => item.type === 'text').map(item => item.text).join('\n');
const preview = text.slice(0,6000);
return {...m, content:[{type:'text',text:JSON.stringify({
toolCallId:m.toolCallId, preview,
note:'完整回执已保存在本轮会话。可用 memory_search 按 toolCallId 与 offset 读取剩余内容。',
nextOffset:preview.length,
})},...m.content.filter(item=>item.type!=='text')]};
}
if (!canvasResults.includes(index) || index === newest) return m;
const summary = summaries.get(index);
const compact = summary && !detailed.has(index) ? { ...summary,
...(summary.layer ? { layer:layerSnapshot(summary.layer,64) } : {}),
...(summary.before && typeof summary.before === 'object' ? { before:layerSnapshot(summary.before,64) } : {}),
...(summary.after && typeof summary.after === 'object' ? { after:layerSnapshot(summary.after,64) } : {}) } : summary;
return { ...m, content: [{ type:'text', text:JSON.stringify({ archivedCanvasResult:m.toolCallId, tool:m.toolName, ...(summary || {}),
...(compact || {}),
...(!detailed.has(index) ? { summaryTruncated:true } : {}), note:'历史证据;原文可检索。当前对象、版本及写许可须重新读取。' }) }] };
});
return { messages };
}
export const transportProjection = (context, { version, ...options } = {}) =>
projectContext(workflowHistory(context, { version }), options);
export const promptChars = (context, options) => JSON.stringify(transportProjection(context, options)).length;

View File

@ -1,4 +1,4 @@
import { calculateContextTokens, estimateTokens, getLastAssistantUsage } from '@earendil-works/pi-coding-agent';
import { calculateContextTokens, getLastAssistantUsage } from '@earendil-works/pi-coding-agent';
/** Usage is scoped to one model and one project. Never turn a local safety
* budget, a billing tier or a missing receipt into a claimed model capacity. */
@ -9,11 +9,6 @@ export function modelCapacity(model) {
return limit > 0 && typeof model.contextWindowSource === 'string' && model.contextWindowSource.length > 0
? { limit, source: model.contextWindowSource } : { limit: null, source: null };
}
export function projectedUsage(context) {
// Preflight only. Use Pi's own estimator, never show this safety budget as
// the session meter or replace an available provider receipt with it.
return { budgetTokens: context.messages.reduce((sum, message) => sum + estimateTokens(message), 0), inputChars: contextTextLength(context) };
}
export function piContextUsage(session, model) {
const native = session.getContextUsage();
const manager = session.sessionManager;
@ -41,11 +36,3 @@ export function contextSnapshot(identity, model, session, previous = null, recei
...piContextUsage(session, model), contextWindow: capacity.limit, capacitySource: capacity.source,
receipt: receipt ?? (same ? previous.receipt : null), phase, at: Date.now() };
}
export function exceedsModelBudget(context, model, fraction = 1) {
const capacity = modelCapacity(model).limit;
if (capacity === null) return false;
// Leave room for a response when deciding whether to compact incoming context.
// Pi's provider determines the actual output budget from the available window.
const reserve = Math.min(8192, Math.max(1, Math.floor(capacity / 4)));
return projectedUsage(context).budgetTokens > (capacity - reserve) * fraction;
}

View File

@ -82,9 +82,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
if(closed||active?.runId!==runId){reject(Error('客户端连接已关闭,原操作需核查'));return;}
if(controller?.signal.aborted){reject(controller.signal.reason);return;}
const id=++serial;
const responseTime=action==='pi-detail-images'?60000:15000;
const timer=setTimeout(()=>{waiting.delete(id);reject(Error('画布连接中断,原操作不会重发'));},responseTime);
waiting.set(id,{resolve,reject,timer,runId});send({type:'canvas',runId,id,action,input});
waiting.set(id,{resolve,reject,runId});send({type:'canvas',runId,id,action,input});
});
void (async()=>{
try {

View File

@ -31,9 +31,7 @@ async function cli() {
const send = value => { if (!closed) process.stdout.write(JSON.stringify(value) + '\n'); };
const call = (action, input) => new Promise((resolve, reject) => {
const id = ++serial;
const responseTime = action === 'pi-detail-images' ? 60000 : 15000;
const timer = setTimeout(() => { waiting.delete(id); reject(Error('画布连接中断,原操作不会重发')); }, responseTime);
waiting.set(id, { resolve, reject, timer }); send({ type: 'canvas', id, action, input });
waiting.set(id, { resolve, reject }); send({ type: 'canvas', id, action, input });
});
lines.on('line', line => {
try {
@ -41,12 +39,12 @@ async function cli() {
const value = JSON.parse(line);
if (!initial) { initial = value; void runSession(value, call).then(result => send({type:'complete',value:result})).finally(() => { lines.close(); process.stdin.destroy(); }); return; }
const pending = waiting.get(value.id);
if (pending) { waiting.delete(value.id); clearTimeout(pending.timer); value.error ? pending.reject(Error(value.error)) : pending.resolve(value.value); }
if (pending) { waiting.delete(value.id); value.error ? pending.reject(Error(value.error)) : pending.resolve(value.value); }
} catch { send({ type: 'fatal', error: '本地连接消息无效;不会重发模型请求' }); }
});
lines.on('close', () => {
closed = true;
for (const pending of waiting.values()) { clearTimeout(pending.timer); pending.reject(Error('客户端已关闭,原请求需只读核查')); }
for (const pending of waiting.values()) { pending.reject(Error('客户端已关闭,原请求需只读核查')); }
waiting.clear();
});
}
@ -160,14 +158,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
if (pending.length !== 1) throw Error('待核查请求数量异常,请保留项目和请求号');
result = await host.recover(pending[0].id, { executeReadOnly: false });
result.text = result.phase === 'unknown' ? `原请求仍待核查(${result.requestId || pending[0].id}),未重发。`
: result.internalCompaction ? result.compactionApplied
? '已取回原摘要并恢复会话进度。'
: result.compactionContinuation ? '已取回原摘要,制作继续时会补齐剩余段落。'
: result.originalResultUnavailable
? result.originalExecutionStatus === 'succeeded'
? '原内部摘要请求已成功,但上游未保留可取回的结果。摘要未应用,原始会话树完整保留;未执行原工作流或画布操作,也未重发原请求。'
: '已核实原内部摘要请求失败,摘要未应用,原始会话树完整保留;未执行原工作流或画布操作,也未重发原请求。'
: '原内部会话摘要已取回,但压缩断点尚未严格核对,未应用。原始会话保留,没有执行原工作流请求,也不会重发摘要。'
: result.internalCompaction ? '已核对旧摘要的请求记录。Pi 会在需要时压缩当前会话。'
: result.phase === 'failed' ? '已确认这条请求失败。你可以在原对话发送新消息。'
: result.needsToolReview ? '原响应已取回。画布建议尚待核对,未自动执行。' : '原响应已取回,未重新调用模型。';
if (result.restoredText) result.text += '\n\n' + result.restoredText;

View File

@ -1,6 +1,6 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { createReadTool, loadSkills } from '@earendil-works/pi-coding-agent';
import { loadSkills } from '@earendil-works/pi-coding-agent';
import { atomic, digest } from './store.mjs';
// Selections are separate per output, with source versions shared within a run.
@ -63,21 +63,3 @@ export async function openEnterpriseSkills(store, selection, load) {
sources:[...documents.values()]});
return {knowledge, resource, documents};
}
export function enterpriseSkillReadTool(store, getBinding, agent, requestScope) {
const source = file => {
const document = getBinding()?.documents.get(path.normalize(file));
if (!document) throw Error('该路径未随本次制作的企业 Skill 加载,请读取所选 Skill 或已发布的引用。');
return document;
};
return createReadTool(store.dir, {operations:{
access: async file => { source(file); },
readFile: async file => {
const document = source(file);
const bytes = await fs.readFile(file);
await store.appendEvent({type:'enterprise_skill_resource_read', agent, requestScope,
fileId:document.fileId, revision:document.revision, kind:document.kind, path:document.path});
return bytes;
},
}});
}

View File

@ -69,7 +69,7 @@ export class Native98kBroker {
this.exited = new Promise(resolve => child.once('close', resolve));
const fail = () => {
if (this.closed) return;
this.failed = Error('模型桥连接中断或响应无效;请核查原请求,不会重发');
this.failed = Error('network error: 模型桥连接中断或响应无效');
if (this.active) { const active = this.active; this.active = null; active.reject(this.failed); }
child.kill();
};
@ -145,7 +145,7 @@ export class Native98kBroker {
return info;
}
/** A new fetch object for ONE provider request. It refuses all implicit retries. */
round({ retryPreparation = false, retryOf } = {}) {
round({ inference = false } = {}) {
const id = randomUUID();
let calls = 0, metadata, completed;
const fetch = async (address, init = {}) => {
@ -159,18 +159,27 @@ export class Native98kBroker {
let cancelled = false;
const enqueue = data => { if (!cancelled) { try { controller.enqueue(data); } catch { cancelled = true; } } };
const request = () => this.start('request', { id, body: init.body, invocationPath: url.pathname, invocationHeaders: this.invocationHeaders,
...(retryOf ? { retryOf } : {}) }, event => {
...(inference ? { inference:true } : {}) }, event => {
if (event.type === 'headers') {
metadata = event;
resolveHeaders(new Response(body, { status: event.status, headers: event.headers }));
} else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64'));
});
completed = retryPreparation ? request().catch(async error => {
// Only the native preflight can prove this ID was never dispatched.
if (!error.retryPreparation || metadata) throw error;
await delay(500, undefined, { signal: init.signal });
return request();
}) : request();
if (inference && this.failed) {
await this.exited;
this.child = null;
this.failed = null;
}
const abort = () => {
if (this.active?.requestId === id) this.child?.kill();
};
init.signal?.addEventListener('abort', abort, {once:true});
completed = request().catch(error=>{
if (inference && (error.retryPreparation || /^98k(?:连接|响应)中断/u.test(error.message))) {
throw Error('network error: '+error.message);
}
throw error;
}).finally(()=>init.signal?.removeEventListener('abort',abort));
completed.then(() => { try { controller.close(); } catch {} }, error => {
rejectHeaders(error);
try { controller.error(error); } catch {}
@ -301,7 +310,7 @@ export class NativeCanvas {
}
action(action, input = {}) { return this.call('jiansun.action', { action, input: { ...input, run: this.run, documentId: this.documentId } }); }
async begin(text) {
this.run = randomUUID(); this.edits = 0;
this.run = randomUUID();
const state = await this.action('pi-begin', { text, ...(this.identity || {}) });
const documentId = state?.context?.id;
if (!Number.isSafeInteger(documentId) || documentId < 1 || (this.documentId !== undefined && this.documentId !== documentId)) throw Error('原生会话文档身份尚未确认,未派发后续操作');
@ -330,18 +339,15 @@ export class NativeCanvas {
workflowPoll(operationId) { return this.action('pi-workflow-poll', { operationId }); }
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('jiansun.action', { action:'pi-workflow-reconcile', input:{ run, documentId, operationId, ...(adoption?{adoption}:null) } }); }
async edit(edit, revision, signal) {
if (++this.edits > 20) throw Error('本轮画布操作已达20步');
signal?.throwIfAborted();
await this.action('pi-edit', { edit, revision });
const deadline = Date.now() + 8000;
while (Date.now() < deadline) {
await new Promise(r => setTimeout(r, 90));
for (;;) {
await delay(90, undefined, {signal});
const state = await this.read();
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
if (state.error) throw Error(state.error);
if (!state.queued && state.revision !== revision) return state;
}
throw Error('画布操作尚未确认,禁止重复执行');
}
end(text) { return this.action('pi-end', { text }); }
close() { this.closed = true; this.disconnect(this.socket); }

View File

@ -51,16 +51,15 @@ export function nativeTools(host, make) {
if (result?.pending === true && Number.isSafeInteger(result.job) && result.job > 0) pendingJob = result.job;
checkTurn();
let settled = result;
let deadline = Date.now() + 120000;
if (result?.pending === true) {
pendingJob = result.job;
if (!Number.isSafeInteger(pendingJob) || pendingJob < 1 || typeof host.canvas.nativePoll !== 'function') throw Error('原生操作尚未确认,禁止重复执行');
await host.store.appendEvent({ type: 'native_job_started', run: host.canvas.run, job: pendingJob, method: args.method, revision: args.revision });
if (args.method === 'engine.execute' && host.qaNativeTimeout?.(args.params.command)) {
deadline = Date.now();
const interrupt = args.method === 'engine.execute' && host.qaNativeTimeout?.(args.params.command);
if (interrupt) {
await host.store.appendEvent({ type:'qa_native_wait_timeout', run, documentId, job:pendingJob, command:args.params.command, revision:args.revision });
}
while (settled?.pending === true && Date.now() < deadline) {
while (settled?.pending === true && !interrupt) {
signal?.throwIfAborted();
await delay(90, undefined, { signal });
settled = await host.canvas.nativePoll(pendingJob);

View File

@ -24,21 +24,18 @@ export function nativeToolMetadata(name) {
}
/**
* Instantiate the official factories through the public SDK loader. Existing
* entries (notably compactionExtension) are already compiled Extension objects;
* passing those objects as InlineExtension factories would silently lose them.
* Cache this result in the host's resourceLoader.getExtensions().
* Instantiate the official factories through the public SDK loader.
*/
export async function createPhotoCraftExtensions(host, existing = [], { includeGoal = false, mayContinueGoal } = {}) {
const cwd = host?.store?.dir;
const cwd = host?.workingDirectory ?? host?.store?.dir;
if (typeof cwd !== 'string' || !cwd) throw new TypeError('PhotoCraft extension loading requires host.store.dir');
if (!Array.isArray(existing) || existing.some(extension => !(extension?.handlers instanceof Map) || !(extension?.tools instanceof Map))) {
throw new TypeError('Existing PhotoCraft extensions must be compiled SDK Extension objects');
}
const loader = new DefaultResourceLoader({
cwd, agentDir: cwd,
cwd, agentDir: host.store.dir,
settingsManager: SettingsManager.inMemory({}),
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
noExtensions: true, noThemes: true, noContextFiles: true,
additionalExtensionPaths: includeGoal ? [path.join(goalPackage, '.pi', 'extensions', 'pi-goal', 'index.ts')] : [],
additionalSkillPaths: includeGoal ? [path.join(goalPackage, 'skills')] : [],
systemPrompt: '',

View File

@ -39,14 +39,14 @@ export async function runPiProductionGoal(host, text, continuation) {
export async function mayContinueProductionGoal(host, event) {
const last = event.messages.findLast(message => message.role === 'assistant');
if (host.compacting || host.canvasWritesStopped || host.canvasNotificationsDetached ||
host.goalStageResult || host.goalPendingOriginal || last?.stopReason !== 'stop') return false;
host.goalStageResult || last?.stopReason !== 'stop') return false;
const {state} = await productionProgress(host) ?? {};
return !state?.waitingOnOriginals && state?.canAdvance !== false &&
!(host.productionGoal?.deadline * 1000 <= Date.now());
}
export const productionTools = [
['plan_production','读取当前输出的进度、可用图文证据、策划及规则目录。',object({})],
['plan_production','读取当前输出的进度、策划及规则目录。文字格细节按分屏调用 read_copy_fields,候选详情按图位调用 review_image_slots。',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({
@ -124,10 +124,4 @@ export async function closeProductionTurn(host) {
const snapshot = await turn.done;
if (snapshot?.production) host.goalStageResult ??= snapshot;
}
if (host.goalPendingOriginal && !host.goalStageResult?.production?.complete) {
const stage = host.goalStageResult ?? {text:'当前制作已保留,正在核查中断的原响应。',production:{...host.productionGoal,complete:false}};
const {models=[],images=[]} = stage.production.originals ?? {};
stage.production.originals = {models:[...new Set([...models,host.goalPendingOriginal])],images,goal:host.goalPendingOriginal};
host.goalStageResult = stage;
}
}

View File

@ -1,6 +1,6 @@
import { parseReceipt } from './receipt.mjs';
import { setTimeout as delay } from 'node:timers/promises';
import { retryAssistantCall, retryDelayMs } from '@earendil-works/pi-ai';
import { retryDelayMs } from '@earendil-works/pi-ai';
import { SettingsManager } from '@earendil-works/pi-coding-agent';
export const piRetryPolicy = SettingsManager.inMemory().getRetrySettings();
@ -38,29 +38,6 @@ export function confirmedProductionFailure(receipt, id) {
: null;
}
export async function retryGatewayModelCall(run, policy, signal, onRetry) {
let failure;
const result = await retryAssistantCall(async () => {
signal?.throwIfAborted();
try {
await run();
return { stopReason: 'stop' };
} catch (error) {
if (signal?.aborted) throw error;
if (!(error instanceof ProductionRequestFailed) || !error.retryable) throw error;
failure = error;
return { stopReason: 'error', errorMessage: 'Transient upstream request failed' };
}
}, policy, signal, {
onRetryScheduled: (attempt, maxAttempts, delayMs) => onRetry({ attempt, maxAttempts, delayMs, failure }),
});
if (result.stopReason === 'aborted') signal?.throwIfAborted();
if (result.stopReason === 'error') {
failure.retryExhausted = true;
throw failure;
}
}
export class ProductionOutputLimit extends Error {
constructor() { super('模型回复达到单次输出长度,当前制作步骤未完成'); }
}

View File

@ -63,7 +63,6 @@ export function productContext(value,identity){
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)};
if(JSON.stringify(result).length>14000)throw Error('产品上下文超过固定预算,未派发模型');
result.contentHash=digest(result);
return result;
}

View File

@ -0,0 +1,67 @@
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';
export async function projectTools(host) {
const cwd = path.join(host.store.dir,'workspace');
await fs.mkdir(cwd,{recursive:true});
const root = await fs.realpath(cwd);
const inside = (parent,file) => {
const relative=path.relative(parent,file);
if (relative==='..' || relative.startsWith('..'+path.sep) || path.isAbsolute(relative)) {
throw Error('路径在本项目工作目录之外');
}
};
const checked=async file=>{
inside(cwd,file);
try { inside(root,await fs.realpath(file)); }
catch(error) {
if(error.code!=='ENOENT')throw error;
await checked(path.dirname(file));
}
return file;
};
const exists=async file=>{
await checked(file);
try {await fs.access(file);return true;}
catch(error) {if(error.code==='ENOENT')return false;throw error;}
};
const read=(agent,requestScope)=>createReadTool(cwd,{operations:{
access:async file=>{
if(!host.productionSkills?.documents.has(path.normalize(file))&&!host.localSkillFiles?.has(path.normalize(file))) await checked(file);
await fs.access(file);
},
readFile:async file=>{
const resource=host.productionSkills?.documents.get(path.normalize(file));
if(!resource) return fs.readFile(host.localSkillFiles?.has(path.normalize(file))?file:await checked(file));
const bytes=await fs.readFile(file);
await host.store.appendEvent({type:'enterprise_skill_resource_read',agent,requestScope,
fileId:resource.fileId,revision:resource.revision,kind:resource.kind,path:resource.path});
return bytes;
},
}});
const writeFile=async (file,content)=>fs.writeFile(await checked(file),content);
const stat=async file=>fs.stat(await checked(file));
return {cwd,read,tools:[
read('main'),
createWriteTool(cwd,{operations:{writeFile,mkdir:async dir=>{await fs.mkdir(await checked(dir),{recursive:true});}}}),
createEditTool(cwd,{operations:{writeFile,readFile:async file=>fs.readFile(await checked(file)),
access:async file=>fs.access(await checked(file),fs.constants.R_OK|fs.constants.W_OK)}}),
createLsTool(cwd,{operations:{exists,stat,readdir:async file=>fs.readdir(await checked(file))}}),
createFindTool(cwd,{operations:{exists,glob:async (pattern,dir,{ignore,limit})=>{
if(path.isAbsolute(pattern)||pattern.split(/[\\/]/u).includes('..'))throw Error('搜索模式超出本项目工作目录');
const matches=[];
for await(const file of fs.glob(pattern,{cwd:await checked(dir),exclude:ignore})){
await checked(path.resolve(dir,file));
matches.push(file);
if(matches.length>=limit)break;
}
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},
]};
}

View File

@ -34,7 +34,7 @@ export async function parseReceipt(record, piModel, protocolMode, tools) {
api: responses ? 'openai-responses' : anthropic ? 'anthropic-messages' : 'openai-completions',
baseUrl: anthropic ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1'};
const stream = api.streamSimple(originalModel, normalizeContext({ messages: [{ role: 'user', content: '仅在内存中解析留存响应', timestamp: 0 }] }), {
apiKey: 'native-broker-only', maxRetries: 0,
apiKey: 'native-broker-only',
fetch: async () => {
if (++fetches !== 1) throw Error('禁止重试原请求');
return new Response(raw, { headers: { 'content-type': 'text/event-stream' } });

View File

@ -0,0 +1,22 @@
import fs from 'node:fs/promises';
import path from 'node:path';
export async function requestPurpose(host, id) {
const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;});
const events = text.split('\n').filter(Boolean).map(line => {try {return JSON.parse(line);} catch {return null;}}).filter(Boolean);
const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash));
if (index < 0) throw Error('原请求没有当前会话归属记录');
const event = events[index];
if (event.purpose === 'compaction') return {kind: 'compaction', event};
if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event};
if (event.purpose === 'conversation') return {kind: 'conversation', event};
// Legacy automatic summaries lack a durable cut-point contract. Recognize
// their purpose, but never guess a checkpoint from the returned prose.
let started = -1, finished = -1;
for (let i = 0; i < index; i++) {
if (events[i].type === 'automatic_compaction_started') started = i;
if (events[i].type === 'automatic_compaction_completed') finished = i;
}
if (started > finished) return {kind: 'legacy-compaction', event};
return {kind: 'conversation', event};
}

View File

@ -22,7 +22,7 @@ export class StdioCanvas {
}
}
}
async begin(text) { this.run = randomUUID(); this.edits = 0; return this.action('pi-begin', { text, ...(this.identity || {}) }); }
async begin(text) { this.run = randomUUID(); return this.action('pi-begin', { text, ...(this.identity || {}) }); }
read() { return this.#observe('pi-state'); }
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
detailRender(options) { return this.#observe('pi-product-screen', options); }
@ -68,18 +68,15 @@ export class StdioCanvas {
workflowPoll(operationId) { return this.#observe('pi-workflow-poll', { operationId }); }
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('pi-workflow-reconcile', { run, documentId, operationId, ...(adoption?{adoption}:null) }); }
async edit(edit, revision, signal) {
if (++this.edits > 20) throw Error('本轮画布操作已达20步');
signal?.throwIfAborted();
await this.action('pi-edit', { edit, revision });
const until = Date.now() + 8000;
while (Date.now() < until) {
await new Promise(resolve => setTimeout(resolve, 90));
for (;;) {
await delay(90, undefined, {signal});
const state = await this.read();
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
if (state.error) throw Error(state.error);
if (!state.queued && state.revision !== revision) return state;
}
throw Error('画布操作尚未确认,禁止重复执行');
}
end(text) { return this.action('pi-end', { text }); }
}

View File

@ -1498,7 +1498,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
...imageCounts.map(({target,count,minimum})=>
count===0?`最终图框内不要出现「${target}」。`:`在最终图框中,「${target}」的可确认数量${minimum?'至少为':'为'} ${count}。`),
imageCounts.some(({count})=>count>0)&&'按最终图框安排站位、道具和边距。每一处要求可见的证据都要和前景物体错开,保留足够画面空间,并能分别定位。',
].filter(Boolean).join('\n').slice(0,2000)):prompt;
].filter(Boolean).join('\n')):prompt;
if(source==='generate'&&item?.state!=='waiting_retry'&&item?.generationInstructions?.includes(generatedPrompt)){
return report({status:'replan',reason:'这个构图已经出图并核对。请改变具体机位、主体和道具的空间关系或取景,保留本图位要求。'});
}
@ -1643,7 +1643,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
...imageKnowledge.tools,
tool('make_candidate',candidateDescription,params({
...(!production?{source:Type.Union([Type.Literal('generate'),Type.Literal('product')])}:null),
prompt:production?Type.String({minLength:1,maxLength:2000}):short,
prompt:production?Type.String({minLength:1}):short,
...(production?{referenceIndex:Type.Optional(Type.Integer({minimum:0,maximum:7}))}:null),
...(verifiedProduction&&!needsOriginal?{geometryReferenceIndex:closeUpNeedsOriginal?geometrySource:Type.Optional(geometrySource)}:null),
...(cropBounds?{referenceCrop:rule?.crop?cropBounds:Type.Optional(cropBounds)}:null),
@ -1788,7 +1788,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
reworkReady?'制作修订候选。保持同款商品、共同布景和模特,逐项落实本次重做要求。':
'按当前模板与产品资料保留要求展示的同款轮廓及细节。',
'只返回一张图像。保留可见的原品铭牌与固定标记,标题、尺寸和品牌角标交由画布排版。画面不添加水印。',
].filter(Boolean).join('\n').slice(0,1600);
].filter(Boolean).join('\n');
if(!generationConflict(rule,prompt)){
const sent=await makeCandidate({source:'generate',prompt},slotSignal,true);
if(deferredReview)return deferredReview;
@ -2845,7 +2845,8 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
}
}
const assigned=await dispatchDraftScreens();
return {...await status(),...(assigned.length?{assigned}:null),
const current=await status({includeCopy:false});
return {...current,...(assigned.length?{assigned}:null),
...(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};

View File

@ -62,7 +62,6 @@ export function workflowResult(value) {
item[key] = clip(item[key], 80); omitted++;
}
if (omitted) result.omitted = { entries: omitted };
if (JSON.stringify(result).length > 8000) throw Error('工作流摘要超过本地预算,未继续派发模型');
return result;
}
@ -80,46 +79,6 @@ export function workflowContext(value, identity) {
return { workflow, product };
}
/** Original tool results stay in the session tree. The model sees only the
* latest current read per section, plus compact receipts for other operations. */
export function workflowHistory(context, { version } = {}) {
const parsed = new Map(), latest = new Map();
// Native version counters restart with the application. Equal numbers from
// an earlier user turn never make that turn's tool snapshot current again.
const turnStart = context.messages.findLastIndex(message => message.role === 'user');
context.messages.forEach((message, index) => {
if (message.role !== 'toolResult' || !['workflow_read', 'workflow_navigate', 'workflow_propose', 'workflow_execute'].includes(message.toolName) || message.isError) return;
try {
const value = JSON.parse(message.content.filter(c => c.type === 'text').map(c => c.text).join(''));
parsed.set(index, value);
if (turnStart >= 0 && index > turnStart && message.toolName === 'workflow_read') latest.set(`${value.section || 'overview'}:${value.outputId || ''}`, index);
} catch { /* An unparseable original result is retained for review. */ }
});
return { ...context, messages: context.messages.map((message, index) => {
const value = parsed.get(index);
if (!value) return message;
const sameTurn = turnStart >= 0 && index > turnStart;
const current = sameTurn && message.toolName === 'workflow_read' && latest.get(`${value.section || 'overview'}:${value.outputId || ''}`) === index && (!version || value.version === version);
if (current) return message;
if (sameTurn && message.toolName === 'workflow_execute' && value.operation?.intent === 'generate_candidate'
&& value.operation.phase === 'complete' && value.operation.candidateId) {
const next = { ...message, content: [{ type: 'text', text: JSON.stringify({ operation: workflowResult(value.operation) }) }] };
delete next.details;
return next;
}
const proposal = value.proposal && typeof value.proposal === 'object' && !Array.isArray(value.proposal) ? value.proposal : value;
const receipt = { archivedWorkflowResult: message.toolCallId, tool: message.toolName, version: value.version, section: value.section,
stage: value.stage, outputId: proposal.outputId || value.outputId, slotId: proposal.slotId, variant: proposal.variant,
productVariantId: proposal.productVariantId, candidateId: proposal.candidateId,
proposed: value.proposed, awaitingReview: value.awaitingReview, executed: value.executed,
intent: proposal.intent, proposalId: value.proposalId || value.cardId,
note: message.toolName === 'workflow_propose' ? '这里只保留待审核建议,未自动执行;原结果在会话树。' : '历史工作流结果保留于会话树;以本轮实时版本为准。' };
const next = { ...message, content: [{ type: 'text', text: JSON.stringify(receipt) }] };
delete next.details;
return next;
}) };
}
export function imageProgressQuestion(text) {
const question = text.trim().replace(/[。?!?s]+$/u, '');
return /^(?:请问|帮我看看)?(?:这套详情(?:页|图)|这套图)?(?:现在|目前|后面|接下来)?(?:还(?:有|剩)|剩下|剩余)(?:几|多少)(?:张(?:图|图片)?|个(?:图位|图片|格子))(?:还)?(?:没(?:有)?(?:完成|做完|做|回填)|未(?:完成|回填))(?:的|了|啊|呢)?$/u.test(question)

View File

@ -70,7 +70,7 @@ test('an enterprise project supports immediate conversation and fetches rules on
assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance)));
await x.host.prompt('谢谢,继续聊一下');
assert.equal(knowledgeReads,1);
assert.ok(!JSON.stringify(x.requests[3].messages).includes(provenance));
assert.ok(JSON.stringify(x.requests[3].messages).includes(provenance));
assert.ok(sections.every(section=>section==='overview'));
assert.equal(x.native.writes,0);
}finally{await x.close();}

View File

@ -1,6 +1,5 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { transportProjection } from '../src/context-budget.mjs';
import { StreamOutputMeter, stripProductionToolText } from '../src/stream-presentation.mjs';
test('production shows readable prose throughout an incomplete tool payload', () => {
@ -35,89 +34,3 @@ test('thinking output meter throttles snapshots and settles on SDK usage', () =>
{ tokens: 12, tokensPerSecond: 12, estimated: true });
assert.equal(new StreamOutputMeter().update(end, false), undefined);
});
test('inline thinking is excluded from model history while the original tool call and session stay intact',()=>{
const tool={type:'toolCall',id:'execute-original',name:'workflow_execute',arguments:{version:2,intent:'generate_candidate',slotId:'hero'}};
const context={messages:[
{role:'user',content:'只生成一个候选'},
{role:'assistant',content:[{type:'text',text:'<thinking>Old operation analysis with no current authority.</thinking>准备生成。'},tool],stopReason:'toolUse'},
{role:'toolResult',toolName:'workflow_execute',toolCallId:tool.id,isError:true,content:[{type:'text',text:'原操作结果未知,禁止重发'}]},
{role:'user',content:'核查原请求'},
]};
const original=JSON.stringify(context), projected=transportProjection(context);
assert.equal(projected.messages[1].content[0].text,'准备生成。');
assert.deepEqual(projected.messages[1].content[1],tool);
assert.deepEqual(projected.messages[2],context.messages[2]);
assert.equal(JSON.stringify(context),original);
});
test('signed thinking, user and tool text, English replies and code examples retain their original meaning',()=>{
const thinking={type:'thinking',thinking:'Provider native thought',thinkingSignature:'original-signature'};
const text='An English reply with a literal example: `<thinking>example</thinking>`\n```xml\n<think>code</think>\n```';
const context={messages:[
{role:'user',content:'<thinking>user supplied material</thinking>'},
{role:'assistant',content:[thinking,{type:'text',text}]},
{role:'toolResult',toolName:'read_text',toolCallId:'read',content:[{type:'text',text:'<think>document text</think>'}]},
]};
const projected=transportProjection(context);
assert.deepEqual(projected.messages,context.messages);
});
test('current assistant text uses the same tag-aware presentation without altering tool arguments',()=>{
const tool={type:'toolCall',id:'new-call',name:'workflow_read',arguments:{section:'slots',note:'<thinking>literal argument</thinking>'}};
const context={messages:[{role:'user',content:'查看图位'},{role:'assistant',content:[
{type:'text',text:'正在读取。<THINK>private analysis</THINK>读取后核对。'},tool,
{type:'text',text:'<thinking>unfinished analysis'},
]}]};
const projected=transportProjection(context);
assert.equal(projected.messages[1].content[0].text,'正在读取。读取后核对。');
assert.equal(projected.messages[1].content[2].text,'');
assert.deepEqual(projected.messages[1].content[1],tool);
});
test('old dispatch receipts retain only the requested slot and original request in model history', () => {
const call={type:'toolCall',id:'dispatch',name:'delegate_image_slots',arguments:{slotIds:['held'],goal:'继续制作'}};
const receipt={assigned:[],pendingText:11,fields:[{field:'unrelated-copy',text:'整页文案'}],
pictures:[{id:'slot-0',field:'held',state:'unknown',pendingOriginal:'original-id'},
{id:'slot-1',field:'unrelated',state:'rejected',review:{reason:'无关图位不合格'}}]};
const context={messages:[{role:'assistant',content:[call]},
{role:'toolResult',toolName:call.name,toolCallId:call.id,content:[{type:'text',text:JSON.stringify(receipt)}]}]};
const projected=transportProjection(context).messages;
assert.deepEqual(JSON.parse(projected[1].content[0].text),
{assigned:[],blocked:[{id:'slot-0',field:'held',state:'unknown',pendingOriginal:'original-id'}]});
assert.deepEqual(JSON.parse(context.messages[1].content[0].text),receipt);
});
test('production history keeps the current plan and only unreviewed screen pixels in the model request', () => {
const result=(toolName,toolCallId,value,images=[])=>({role:'toolResult',toolName,toolCallId,
content:[{type:'text',text:JSON.stringify(value)},...images]});
const image={type:'image',data:'AAAA',mimeType:'image/jpeg'};
const first=result('plan_production','old-plan',{outputId:'detail',pictures:[{id:'old'}]});
const latest=result('plan_production','latest-plan',{outputId:'detail',pictures:[{id:'current'}]});
const scanned=result('read_output_screen','first',{page:0,revision:3},[image]);
const notReviewed=result('read_output_screen','second',{page:1,revision:3},[image]);
const review=result('review_output_screen','review',{page:0,passed:false,issues:[{field:'title',reason:'标题待填'}]});
const context={messages:[first,latest,{role:'assistant',content:[
{type:'toolCall',id:'first',name:'read_output_screen',arguments:{page:0}},
{type:'toolCall',id:'second',name:'read_output_screen',arguments:{page:1}},
]},scanned,notReviewed,review]};
const projected=transportProjection(context).messages;
assert.equal(JSON.parse(projected[0].content[0].text).archivedPlan,'old-plan');
assert.deepEqual(projected[1],latest);
assert.deepEqual(projected[3].content,[scanned.content[0]]);
assert.deepEqual(projected[4],notReviewed);
assert.deepEqual(projected[5],review);
assert.deepEqual(context.messages[3].content,[scanned.content[0],image]);
});
test('an original-template question does not receive a previous candidate as visual evidence', () => {
const old = {role:'user', content:[{type:'text',text:'大桌面图的旧候选'}, {type:'image',data:'old',mimeType:'image/jpeg'}]};
const fresh = {role:'user', content:[{type:'text',text:'查看模板原图的视角'}, {type:'image',data:'current',mimeType:'image/jpeg'}]};
const context = {messages:[old, fresh]};
const projected = transportProjection(context, {templateOriginal:true});
assert.ok(!projected.messages[0].content.some(block => block.type === 'image'));
assert.deepEqual(projected.messages[1], fresh);
assert.equal(old.content[1].data, 'old');
assert.deepEqual(transportProjection(context).messages, context.messages);
});

View File

@ -61,7 +61,8 @@ test('output length stop never executes even a syntactically complete JSON tool
}, finish: async () => ({ phase: 'complete' }) };
} };
const host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' });
await assert.rejects(host.prompt('测试颜色是红色'), /输出上限/);
assert.deepEqual((await store.context()).confirmedMemory, {}); assert.equal(posts, 1);
await host.dispose(); await cleanup(dir);
try {
await assert.rejects(host.prompt('测试颜色是红色'), /达到线路上限/);
assert.deepEqual((await store.context()).confirmedMemory, {}); assert.equal(posts, 1);
} finally { await host.dispose(); await cleanup(dir); }
});

View File

@ -44,11 +44,11 @@ test('an idle EOF reconnects and authenticates only before a new read/edit, pres
});
let canvas;
try{
canvas=await NativeCanvas.connect(f.options);canvas.run='same-run';canvas.identity={doc:12,revision:7};canvas.edits=2;
canvas=await NativeCanvas.connect(f.options);canvas.run='same-run';canvas.identity={doc:12,revision:7};
await canvas.call('idle-close');await wait(()=>canvas.socket.destroyed);
assert.equal((await canvas.read()).revision,7);
assert.equal((await canvas.edit({type:'text',layer:3,text:'修改中文'},7)).revision,8);
assert.equal(canvas.run,'same-run');assert.deepEqual(canvas.identity,{doc:12,revision:7});assert.equal(canvas.edits,3);
assert.equal(canvas.run,'same-run');assert.deepEqual(canvas.identity,{doc:12,revision:7});
assert.equal(f.connections,2);assert.equal(f.requests.filter(q=>q.method==='auth').length,2);
assert.equal(f.requests.filter(q=>q.params.action==='pi-edit').length,1);
}finally{canvas?.close();await f.close();}

View File

@ -9,7 +9,6 @@ import { PassThrough } from 'node:stream';
import { ProjectStore } from '../src/store.mjs';
import { DetailPiAgent } from '../src/agent.mjs';
import { auditResponse, InvalidToolReply } from '../src/response-audit.mjs';
import { projectContext } from '../src/context-budget.mjs';
import { cleanup } from './cleanup.mjs';
import { decodeToolReply } from '../src/json-tool-codec.mjs';
import { normalizeContext } from '@earendil-works/pi-ai/compat';
@ -17,6 +16,8 @@ import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponse
import { SessionManager } from '@earendil-works/pi-coding-agent';
import { atomic } from '../src/store.mjs';
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';
test('native request validation can prove that no model was dispatched', async t => {
@ -48,65 +49,34 @@ test('native request validation can prove that no model was dispatched', async t
}
});
test('production retries only an explicitly retryable preflight under the same request ID', async t => {
test('the native bridge reports a retryable preflight to Pi without replaying it', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
const reason = '客户端准备模型请求失败,本次未发送';
for (const [proof, unavailable, expected] of [
[{dispatched:false,retryPreparation:true}, false, 2],
[{dispatched:false,retryPreparation:true}, true, 2],
[{dispatched:false}, false, 1],
[{retryPreparation:true}, false, 1],
]) {
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close', 0);
});
const publish = event => child.stdout.write(JSON.stringify(event)+'\n');
const requests = [];
let posts = 0;
child.stdin.on('data', buffer => {
const input = JSON.parse(buffer.toString());
if (input.method === 'finish') {
assert.equal(input.id, requests[0].id);
publish({type:'result',value:{phase:'complete'}});
return;
}
assert.equal(input.method, 'request');
requests.push(input);
if (requests.length === 1 || unavailable) {
publish({type:'error',error:reason,...proof});
return;
}
posts++;
publish({type:'headers',status:200,headers:{'content-type':'text/event-stream'},bodyHash:'abc'});
publish({type:'result',value:{phase:'received'}});
});
const broker = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => child});
broker.scope = 'fixture';
try {
const round = broker.round({retryPreparation:true});
const fetch = round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'});
if (expected === 2 && !unavailable) {
assert.equal((await fetch).status, 200);
assert.equal((await round.finish(true, 'stop')).phase, 'complete');
assert.equal(posts, 1);
} else {
await assert.rejects(fetch, /本次未发送/);
assert.equal(posts, 0);
}
assert.equal(requests.length, expected);
assert.ok(requests.every(request => request.id === round.id && request.body === '{}'));
assert.equal(broker.hasUnconfirmedRequest, proof.dispatched !== false);
} finally {
await broker.close();
}
}
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close', 0);
});
const requests=[];
child.stdin.on('data', buffer => {
requests.push(JSON.parse(buffer.toString()));
child.stdout.write(JSON.stringify({type:'error',error:'客户端准备模型请求失败,本次未发送',
dispatched:false,retryPreparation:true})+'\n');
});
const broker=new Native98kBroker({project:randomUUID(),profile,spawnProcess:()=>child});
broker.scope='fixture';
try {
const round=broker.round({inference:true});
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/network error/);
assert.equal(requests.length,1);
assert.equal(requests[0].id,round.id);
assert.equal(requests[0].inference,true);
assert.equal(broker.hasUnconfirmedRequest,false);
} finally {await broker.close();}
});
test('the native bridge posts only to the endpoint bound to the selected route', async () => {
@ -212,7 +182,7 @@ async function setup(reply, finish = async valid => { assert.equal(valid, true);
}, finish };
} };
const canvas=production&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},
activity:async()=>{},delta:async()=>{},end:async()=>{}};
activity:async()=>{},delta:async()=>{},end:async()=>{},...production.canvas};
const productionGoal=production&&{outputId:'detail',variantId:randomUUID(),deadline:production.deadline};
if(recovery)Object.assign(broker,{forDetailSlot:()=>broker,close:async()=>{},
status:async()=>({pending:[]}),isUnconfirmed:()=>Boolean(recovery.read),read:recovery.read,recover:recovery.recover});
@ -260,36 +230,6 @@ test('the one-click goal resumes on changed fields at the same count without nam
} finally { await x.close(); }
});
test('a production turn pages an oversized receipt on its authenticated canvas',async()=>{
const x=await setup((payload,n)=>{
if(n===1)return sse({tool_calls:[{index:0,id:'plan',type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls');
if(n===2){
const receipt=JSON.parse(payload.messages.find(message=>message.role==='tool'&&message.tool_call_id==='plan').content);
assert.equal(receipt.toolCallId,'plan');
assert.equal(receipt.nextOffset,6000);
return sse({tool_calls:[{index:0,id:'page',type:'function',function:{name:'memory_search',
arguments:JSON.stringify({toolCallId:receipt.toolCallId,offset:receipt.nextOffset})}}]},'tool_calls');
}
const page=JSON.parse(payload.messages.find(message=>message.role==='tool'&&message.tool_call_id==='page').content);
assert.equal(page.toolCallId,'plan');
assert.equal(page.text.length,8000);
assert.equal(page.nextOffset,14000);
return sse({content:'等待原请求。'},'stop');
},undefined,{plan:()=>({plan:'本款商品资料'.repeat(24000)}),
progress:()=>({state:{waitingOnOriginals:true}})});
try{
x.host.productIdentity.documentId=21;
Object.assign(x.host.canvas,{documentId:21,run:'private-production',
read:async()=>({conversationActive:true,run:'private-production',context:null})});
await x.host.checkLocalBudgetRecovery();
assert.equal((await x.host.prompt('继续整套制作')).text,'等待原请求。');
assert.equal(x.requests.length,3);
assert.ok(x.requests.every(payload=>JSON.stringify(payload.messages).length <= 80_000));
x.host.canvas.documentId=22;
await assert.rejects(x.host.checkLocalBudgetRecovery(),/原项目已切换/);
}finally{await x.close();}
});
test('a managed inference interruption retries without executing its partial tool', async () => {
let plans=0;
const lookedUp=[];
@ -307,146 +247,13 @@ test('a managed inference interruption retries without executing its partial too
});
try {
assert.equal((await x.host.prompt('开始整套制作')).text,'已接续制作。');
assert.deepEqual(lookedUp,[x.ids[0]]);
assert.deepEqual(x.retries,[x.ids[0]]);
assert.deepEqual(lookedUp,[]);
assert.deepEqual(x.retries,[]);
assert.equal(plans,1);
assert.equal(x.requests.length,3);
} finally {await x.close();}
});
test('ordinary chat checks an interrupted original and retries only a verified transient failure', async () => {
for (const confirmed of [false,true]) {
const requestId=randomUUID(), lookedUp=[];
let finishes=0;
const x=await setup((_p,n)=>n===1?sse({content:'只有前缀'},null):sse({content:'接续成功。'},'stop'), async()=>{
if(++finishes===1)throw Error('network error: stream disconnected before completion');
return {phase:'complete'};
},undefined,{
read:async()=>lookedUp.length&&confirmed?
{phase:'failed',requestId,failureHttpStatus:503,originalLookup:{verified:true,requestId,status:'failed'}}:
{phase:'unknown',requestId,recovery:{status:410}},
recover:async id=>{lookedUp.push(id);},
});
try {
if(confirmed)assert.equal((await x.host.prompt('请完成这条回复')).text,'接续成功。');
else await assert.rejects(x.host.prompt('请完成这条回复'),/network error/);
assert.deepEqual(lookedUp,[x.ids[0]]);
assert.equal(x.requests.length,confirmed?2:1);
} finally { await x.close(); }
}
});
for(const outcome of ['rate-limited','confirmed','unknown','invalid-input'])
test(`production retries only a confirmed temporary failure (${outcome})`,async()=>{
const originalRequest=randomUUID(), reads=[], queries=[];
let plans=0;
const confirmed=outcome==='confirmed'||outcome==='invalid-input';
const retry=outcome==='rate-limited'||outcome==='confirmed';
const toolFirst=outcome==='rate-limited';
const failedAttempt=toolFirst?2:1;
const x=await setup((_p,n)=>n===failedAttempt
? 'data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n'
: n===(toolFirst?1:2)?sse({tool_calls:[{index:0,id:'plan',type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls')
:sse({content:'继续制作。'},'stop'),
async valid=>valid?{phase:'complete'}:outcome==='rate-limited'?{phase:'failed',failureCode:'rate_limit_exceeded'}:{phase:'unknown'},
{ ...(outcome==='rate-limited'?{}:{
read:async id=>{
reads.push(id);
return confirmed?{phase:'failed',requestId:originalRequest,httpStatus:200,
failureHttpStatus:outcome==='confirmed'?503:400,originalLookup:{verified:true,requestId:originalRequest,status:'failed'}}:
{phase:'unknown',requestId:originalRequest,recovery:{status:410}};
},
recover:async id=>{queries.push(id);}
}),plan:()=>{plans++;return {pendingText:0};},progress:()=>({state:{waitingOnOriginals:true}}) });
try{
if(outcome==='invalid-input')await assert.rejects(x.host.prompt('开始这批制作'),/待核查|失败/);
else {
const result=await x.host.prompt('开始这批制作');
if(outcome==='unknown')assert.equal(result.production.originals.goal,x.ids[0]);
else assert.equal(result.text,'继续制作。');
}
assert.equal(x.requests.length,retry?3:1);
assert.equal(plans,retry?1:0);
assert.ok(reads.every(id=>id===x.ids[0]));
assert.ok(queries.every(id=>id===x.ids[0]));
if(retry){
const failedIndex=failedAttempt-1;
assert.notEqual(x.ids[failedIndex],x.ids[failedIndex+1]);
assert.deepEqual(x.requests[failedIndex].messages,x.requests[failedIndex+1].messages);
if(toolFirst)assert.ok(x.requests[failedIndex+1].messages.some(message=>message.role==='tool'&&message.tool_call_id==='plan'));
}
if(outcome==='unknown')assert.deepEqual(queries,[x.ids[0]]);
assert.deepEqual(x.retries,[]);
}finally{await x.close();}
});
for(const outcome of ['rate-limit','recovered-transient','recovered-invalid'])
test(`an explicitly failed production worker resolves the same slot (${outcome})`,async()=>{
const direct=outcome==='rate-limit', original=randomUUID(), ids=[];
const requestId=randomUUID();
const x=await setup((_p,n)=>direct&&n===1
? 'data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n'
: sse({content:'已核对同一张候选。'},'stop'),
async valid=>valid?{phase:'complete'}:{phase:'failed',failureCode:'rate_limit_exceeded'},direct?{}:{
read:async id=>{
assert.equal(id,original);
return ids.length?{phase:'failed',requestId,failureHttpStatus:outcome==='recovered-transient'?503:400,
originalLookup:{verified:true,requestId,status:'failed'}}:{phase:'unknown',requestId};
},recover:async id=>{ids.push(id);}
});
try{
const scope='product/review/'+randomUUID();
x.host.productionRequests=new Map(direct?[]:[[scope,{id:original,phase:'unknown'}]]);
const run=x.host.runDetailAgent('slot-0','核对实物','核对本候选',[],undefined,scope);
if(outcome==='recovered-invalid')await assert.rejects(run,/HTTP 400/);
else await run;
assert.equal(x.host.productionRequests.has(scope),false);
assert.deepEqual(ids,direct?[]:[original]);
assert.equal(x.requests.length,direct?2:outcome==='recovered-transient'?1:0);
if(direct){
assert.notEqual(x.ids[0],x.ids[1]);
assert.deepEqual(x.requests[0].messages,x.requests[1].messages);
}
}finally{await x.close();}
});
for(const [step,resume] of [['review',false],['review',true],['slot',false],['slot',true]]){
test(`an interrupted image worker keeps the original request (${step}, ${resume?'saved':'live'})`, async()=>{
const original=randomUUID(), candidate=randomUUID();
const scope=step==='review'?'product/review/'+candidate:'product/slot/'+'a'.repeat(64);
const lookedUp=[];
let reviews=0;
const verify={name:step==='review'?'review_candidate':'make_candidate',label:'处理图位',description:'处理当前候选',
parameters:{type:'object',properties:{candidate:{type:'string'}},required:['candidate']},
execute:async(_id,args)=>{
assert.equal(args.candidate,candidate);
reviews++;
return {content:[{type:'text',text:'已复核'}],details:{},terminate:true};
}};
const x=await setup((_p,n)=>{
const tool_calls=[{index:0,id:'check-'+n,type:'function',
function:{name:verify.name,arguments:JSON.stringify({candidate})}}];
return !resume&&n===1?sse({tool_calls},null).replace('data: [DONE]',''):sse({tool_calls},'tool_calls');
},async valid=>valid?{phase:'complete'}:{phase:'unknown'}, {},{
read:async()=>({phase:'unknown',recovery:{status:410}}),
recover:async id=>{lookedUp.push(id);},
});
try{
x.host.productionRequests=new Map(resume?[[scope,{id:original,phase:'unknown',detailSlot:scope}]]:[]);
const run=()=>x.host.runDetailAgent('slot-0','验候选','验这张候选 '+candidate,[verify],undefined,scope);
await assert.rejects(run(),/正在核查/);
assert.equal(reviews,0);
assert.equal(x.requests.length,resume?0:1);
await assert.rejects(run(),/正在核查/);
assert.equal(reviews,0);
assert.equal(x.requests.length,resume?0:1);
const pendingId=resume?original:x.ids[0];
assert.equal(x.host.productionRequests.get(scope).id,pendingId);
assert.deepEqual(lookedUp,[pendingId,pendingId]);
assert.deepEqual(x.retries,[]);
}finally{await x.close();}
});
}
test('actual native Pi wire sends function schemas, executes typed call and accepts a plain final reply', async () => {
const x = await setup((_p, n) => n === 1 ? sse({ tool_calls: [{ index: 0, id: 'call-memory', type: 'function', function: { name: 'memory_set', arguments: JSON.stringify({ key: 'color', value: '胡桃色', evidence: '测试颜色是胡桃色' }) } }] }, 'tool_calls') : sse({ content: '已记录胡桃色' }, 'stop'));
try {
@ -469,7 +276,8 @@ test('native Pi preserves a required named tool on a string-only Responses route
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 = {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.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)})
@ -481,8 +289,12 @@ test('native Pi preserves a required named tool on a string-only Responses route
+ event('response.output_item.done',{output_index:0,item:text}) + complete(text), undefined, undefined, fixture);
const reference = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAgACADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAYH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AkgIpngAAAAAD/9k=';
try {
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}]});
assert.equal(x.requests[0].tool_choice,'required');
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']);
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,/);
@ -495,7 +307,7 @@ test('native partial arguments and length-stopped valid prefixes never execute m
for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) {
const x = await setup(() => sse({ tool_calls: [{ index: 0, id: 'partial', type: 'function', function: { name: 'memory_set', arguments: args } }] }, finish));
try {
await assert.rejects(x.host.prompt('测试颜色是红色'), /未完整|输出上限/);
await assert.rejects(x.host.prompt('测试颜色是红色'), /未完整|达到线路上限/);
assert.deepEqual((await x.store.context()).confirmedMemory, {});
assert.equal(x.requests.length, 1);
} finally { await x.close(); }
@ -513,22 +325,6 @@ test('a literal marker in a normal explanation is ordinary text, never a command
try { const r = await x.host.prompt('解释一个结束标记,不要调用工具'); assert.match(r.text, /结束标记/); assert.equal(x.requests.length, 1); }
finally { await x.close(); }
});
test('projection bounds stale canvas bodies without deleting original facts, errors or evidence', () => {
const large = { revision: 1, context: { layers: Array.from({ length: 200 }, (_, i) => ({ id: i, name: '完整画布数据'.repeat(20) })) } };
const m = { role: 'toolResult', toolName: 'canvas_read', toolCallId: 'old', content: [{ type: 'text', text: JSON.stringify(large) }], details: large };
const messages = [{ role: 'user', content: '原始用户事实保留' }, m, { ...m, toolCallId: 'new' }];
const before = JSON.stringify(messages), out = projectContext({ messages });
assert.equal(JSON.stringify(messages), before); assert.equal(out.messages[0], messages[0]);
assert.ok(out.messages[1].content[0].text.length < 300); assert.equal(out.messages[1].details, undefined);
assert.equal(out.messages[2].content[0].text, m.content[0].text);
});
test('a continuous conversation archives a previous rule domain rather than reinjecting it as the latest rules',()=>{
const old={role:'toolResult',toolName:'context_read',toolCallId:'old-domain',isError:false,content:[{type:'text',text:JSON.stringify({bindingHash:'old',snapshot:{rules:['旧店铺专属规范'.repeat(7000)]}})}]};
const original=JSON.stringify(old),projected=projectContext({messages:[old]},{bindingHash:'current',production:true});
assert.equal(JSON.stringify(old),original);
assert.ok(!JSON.stringify(projected).includes('旧店铺专属规范'));
assert.ok(JSON.stringify(projected).includes('旧规则域历史'));
});
test('wire audit detects complete SSE with a literal early EOS instead of blaming the browser', () => {
const a = auditResponse(sse({ content: '{"reply":"未结束<|eos|>' }, 'stop'), 'openai-chat');
assert.equal(a.literalEos, true); assert.deepEqual(a.finishes, ['stop']);
@ -550,14 +346,14 @@ async function compactionFixture({ withCanvas, callBudget = 4, large = false, pe
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')), scope = '9'.repeat(64);
const store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', source: 'qa', version: '1', rules: [] });
const manager = SessionManager.create(store.dir, path.join(store.dir, 'sessions'));
for (let i = 0; i < (large ? 30 : 12); i++) {
manager.appendMessage({ role: 'user', content: `archive-marker-${i}: ` + 'x'.repeat(large ? 1400 : 500), timestamp: Date.now() });
manager.appendMessage({ role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa', content: [{ type: 'text', text: 'Synthetic, not a live model reply. ' + 'y'.repeat(large ? 1400 : 500) }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 5000, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: 5500, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
for (let i = 0; i < (large ? 45 : 26); i++) {
manager.appendMessage({ role: 'user', content: `archive-marker-${i}: ` + 'x'.repeat(large ? 3000 : 1600), timestamp: Date.now() });
manager.appendMessage({ role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa', content: [{ type: 'text', text: 'Synthetic, not a live model reply. ' + 'y'.repeat(large ? 3000 : 1600) }], stopReason: 'stop', timestamp: Date.now(), usage: { input: large?50000:5000, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: large?50500:5500, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
}
await atomic(path.join(store.dir, 'session.json'), { file: manager.getSessionFile() });
let calls = 0, canvasCalls = 0;
const canvas = withCanvas ? { read() { canvasCalls++; throw Error('no canvas edit run during compaction'); }, delta() { canvasCalls++; throw Error('must not show internal summary'); } } : undefined;
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }, stream(model) {
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat', contextWindow:64000, contextWindowSource:'fixture' }, pending: [] }, stream(model) {
calls++;
const stream = createAssistantMessageEventStream();
const message = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [{ type: 'text', text: 'Summary: original evidence remains archived.' }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 5000, output: 20, cacheRead: 0, cacheWrite: 0, totalTokens: 5020, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
@ -604,161 +400,98 @@ test('compaction with a connected canvas does not call an inactive edit run or s
assert.ok(x.host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user' && e.message.content.includes('archive-marker-0')));
} finally { await x.close(); }
});
test('production compaction continues past an unrelated review and holds the active goal original', async () => {
const independent = await compactionFixture({withCanvas:true,pendingStep:'review'});
test('the Pi defaults compact from the native session threshold',async()=>{
const x=await compactionFixture({large:true});
try {
assert.match((await independent.host.compact()).summary,/original evidence/);
assert.equal(independent.calls,1);
assert.equal(independent.canvasCalls,0);
} finally { await independent.close(); }
const held = await compactionFixture({withCanvas:true,pendingStep:'goal'});
try {
await assert.rejects(held.host.compact(),/未知请求/);
assert.equal(held.calls,0);
} finally { await held.close(); }
const settings=x.host.session.settingsManager;
assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:16384,keepRecentTokens:20000});
assert.deepEqual(Object.fromEntries(Object.entries(settings.getRetrySettings()).filter(([k])=>['enabled','maxRetries','baseDelayMs'].includes(k))),
{enabled:true,maxRetries:3,baseDelayMs:2000});
await x.host.prompt('继续');
assert.equal(x.calls,3);
const checkpoints=x.host.manager.getEntries().filter(entry=>entry.type==='compaction');
assert.equal(checkpoints.length,1);
assert.ok(x.host.manager.getEntries().some(entry=>entry.message?.role==='user'&&entry.message.content.includes('archive-marker-0')));
} finally {await x.close();}
});
test('a confirmed rate limit retries the same production compaction part', async () => {
const x = await compactionFixture({withCanvas:true,pendingStep:'review',rateLimit:true});
test('native compaction retries its own interrupted summary', async()=>{
const x=await compactionFixture({withCanvas:true,pendingStep:'review',rateLimit:true});
try {
assert.match((await x.host.compact()).summary,/original evidence/);
assert.equal(x.calls,2);
assert.equal(x.canvasCalls,0);
const requests = path.join(x.host.store.dir,'compaction-requests');
const records = await Promise.all((await fs.readdir(requests)).map(async name =>
JSON.parse(await fs.readFile(path.join(requests,name),'utf8'))));
assert.deepEqual(records.map(record => record.part),[1,1]);
assert.equal(records[0].planId,records[1].planId);
} finally { await x.close(); }
assert.equal(x.host.manager.getEntries().filter(entry=>entry.type==='compaction').length,1);
} finally {await x.close();}
});
test('automatic compaction and subsequent inference share one user-turn call budget', async () => {
const x = await compactionFixture({ withCanvas: false, callBudget: 1, large: true });
test('the model receives prior images and original tool receipts through Pi', async()=>{
const x=await setup((payload,n)=>{
if(n===1) return sse({tool_calls:[{index:0,id:'context-1',type:'function',function:{name:'context_read',arguments:'{}'}}]},'tool_calls');
return sse({content:'继续核对。'},'stop');
});
try {
await assert.rejects(x.host.prompt('继续处理,但不能绕过预算'), /预算/);
assert.equal(x.calls, 1);
} finally { await x.close(); }
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
await x.host.prompt('继续');
const tool=x.requests[1].messages.find(message=>message.tool_call_id==='context-1');
assert.ok(tool);
assert.ok(x.requests[2].messages.some(message=>message.tool_call_id==='context-1'&&message.content===tool.content));
assert.ok(x.requests[2].messages.some(message=>Array.isArray(message.content)&&message.content.some(x=>x.type==='image_url')),
JSON.stringify({model:x.host.session.model.input,session:x.host.session.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]),
wire:x.requests.map(payload=>payload.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]))}));
} finally {await x.close();}
});
for (const recovery of ['first_part','last_part','settled']) {
test(`production compacts with Pi and resumes from its checkpoint (${recovery})`, async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
t.after(() => cleanup(dir));
const scope = 'e'.repeat(64);
const templatePath=process.env.XIAOYI_COMPACTION_TEST_TEMPLATE;
const template=templatePath?JSON.parse(await fs.readFile(templatePath,'utf8')).pack:null;
const store = await ProjectStore.open(dir, {scope,project:randomUUID()},
{brandId:template?.brandId??'qa',shopId:'qa',categoryId:template?.categoryId??'lighting',
platform:'qa',source:'QA',version:'1',rules:[]});
const goal = {outputId:'main_images',variantId:randomUUID(),deadline:Math.floor(Date.now()/1000)+300};
const goalScope = 'product/goal/'+goal.variantId+'/'+goal.outputId;
const worker = {id:randomUUID(),modelRole:'detail',detailSlot:'product/review/'+randomUUID(),phase:'unknown'};
const model = {id:'qa',protocol:'openai-chat',supportsImageInput:true};
const sent = [], queries = [], originalIds = [], summaries = new Map();
let interrupted, available = false, plans = 0;
const pending = () => [worker,...(interrupted && summaries.get(interrupted).phase !== 'complete' ?
[{id:interrupted,modelRole:'detail',detailSlot:goalScope,phase:'unknown',createdAt:goal.deadline-60}] : [])];
const broker = {
info:async()=>({accountScope:scope,model,pending:pending()}),
status:async()=>({pending:pending()}),
forDetailSlot(requestScope) {assert.equal(requestScope,goalScope);return broker;},
close:async()=>{},
isUnconfirmed:id=>summaries.get(id)?.phase==='unknown',
read:async id=>summaries.get(id),
recover:async id=>{
queries.push(id);
assert.equal(id,interrupted);
if(available)summaries.get(id).phase='received';
},
confirm:async id=>{summaries.get(id).phase='complete';return {phase:'complete'};},
round({retryOf}={}) {
assert.equal(retryOf,undefined);
const id=randomUUID();
return {id,fetch:async(_url,init)=>{
const body=JSON.parse(init.body);
sent.push({id,summary:!body.tools?.length,body});
if (!body.tools?.length) {
const ordinal=originalIds.push(id);
const result=sse({content:'Checkpoint part '+ordinal},'stop');
const phase=ordinal===(recovery==='first_part'?1:2)?'unknown':'complete';
summaries.set(id,{phase,terminal:true,model,requestId:'original-'+id,bodyHash:'fixture',
raw:Buffer.from(result).toString('base64'),recovery:{status:410}});
if(phase==='unknown')interrupted=id;
return reply(phase==='unknown'?result.replace('"finish_reason":"stop"','"finish_reason":null').replace('data: [DONE]',''):result);
}
assert.ok(body.tools.some(row=>row.function.name==='plan_production'));
const name=++plans===1?'plan_production':'finish_production';
return reply(sse({tool_calls:[{index:0,id:name,type:'function',function:{name,arguments:'{}'}}]},'tool_calls'));
},finish:async valid=>valid?{phase:'complete'}:{phase:'unknown'}};
},
};
const reply = text => new Response(text,{headers:{'content-type':'text/event-stream'}});
const canvas={run:'lighting',documentId:31,detailImages(){},begin:async()=>({run:'lighting',conversationActive:true}),
read:async()=>({run:'lighting',conversationActive:true}),activity:async()=>{},delta:async()=>{},end:async()=>{}};
const open=async(productionGoal=goal)=>{
const host=await DetailPiAgent.open({store,broker,canvas,documentId:31,productionGoal});
host.executeWholeDetail=(_output,_production,persisted,_signal,drive)=>drive({
async plan_production() {
assert.ok(persisted.some(request=>request.id===worker.id));
return {pendingOriginal:worker.id,workingNotes:'细节'.repeat(20_000),
template:template&&{id:template.id,version:template.version,
outputs:template.outputs.map(({id,slots})=>({id,slots:slots.map(({id,kind})=>({id,kind}))}))}};
},
async finish_production(){
return {status:{complete:true},stage:{text:'已复核。',production:{...goal,complete:true}}};
},
});
return host;
};
let host=await open();
test('Pi project tools share the same file boundary and log blocked shell execution',async()=>{
const x=await setup(()=>sse({content:'已核对。'},'stop'));
try {
for(let index=0;index<12;index++){
host.manager.appendMessage({role:'user',content:'archive-'+index+' '+'a'.repeat(1500),timestamp:Date.now()});
host.manager.appendMessage({role:'assistant',api:'openai-completions',provider:'jiansun-native-98k',model:'qa',
content:[{type:'text',text:'b'.repeat(1500)}],stopReason:'stop',timestamp:Date.now(),
usage:{input:800,output:375,cacheRead:0,cacheWrite:0,totalTokens:1175,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}});
}
host.session.refreshContext();
const waiting=await host.prompt('制作灯具主图');
assert.equal(waiting.production.originals.goal,interrupted);
const beforeResume=recovery==='first_part'?[false,true]:[false,true,true];
assert.deepEqual(sent.map(row=>row.summary),beforeResume);
assert.equal(host.manager.getEntries().filter(e=>e.type==='compaction').length,0);
await host.dispose();
host=await open();
if (recovery==='settled') summaries.get(interrupted).phase='complete';
else {
assert.equal((await host.prompt('继续制作',{goalContinuation:true})).production.originals.goal,interrupted);
assert.deepEqual(queries,[interrupted]);
assert.equal(sent.length,beforeResume.length);
available=true;
}
if (recovery==='first_part') {
await host.dispose();
host=await open(null);
const original=await host.recover(interrupted);
assert.equal(original.compactionContinuation,true);
assert.equal(sent.length,beforeResume.length);
await host.dispose();
host=await open();
}
const resumed=await host.prompt('继续制作',{goalContinuation:true});
assert.equal(resumed.production.complete,true);
assert.deepEqual(sent.map(row=>row.summary),[false,true,true,false]);
assert.deepEqual(queries,recovery==='settled'?[]:[interrupted,interrupted]);
const compacted=host.manager.getEntries().filter(e=>e.type==='compaction');
assert.equal(compacted.length,1);
assert.match(compacted[0].summary,/Checkpoint part 1[\s\S]+Checkpoint part 2/);
assert.ok(host.manager.getEntries().some(e=>e.type==='message'&&e.message.role==='user'&&e.message.content.includes('archive-0')));
const originalPlan=host.manager.getEntries().find(e=>e.type==='message'&&e.message.role==='toolResult'&&e.message.toolName==='plan_production');
const savedPlan=JSON.parse(originalPlan.message.content[0].text);
assert.equal(savedPlan.pendingOriginal,worker.id);
if(template)assert.equal(savedPlan.template.outputs.length,template.outputs.length);
assert.equal((await host.recover(interrupted)).alreadyApplied,true);
assert.equal(sent.length,4);
t.diagnostic(JSON.stringify({phase:recovery,template:template?.id??'lighting-fixture',
templatePages:template?.outputs.length,originalLookups:queries.length,summaryPosts:originalIds.length,
newPostsWhileUnknown:0,compactionEntries:compacted.length}));
} finally {await host.dispose();}
const {cwd,tools}=await projectTools(x.host);
const tool=name=>tools.find(row=>row.name===name);
await tool('write').execute('1',{path:'notes.md',content:'品牌说明'});
const result=await tool('read').execute('2',{path:'notes.md'});
assert.match(result.content[0].text,/品牌说明/);
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/);
} finally {await x.close();}
});
test('a canvas can complete more than 20 edits and cancellation stops waiting',async()=>{
let rev=0, dispatched=0, apply=true;
const canvas=new StdioCanvas(async action=>{
if(action==='pi-edit'){dispatched++;if(apply)rev++;}
if(action==='pi-state')return {allowed:true,revision:rev,queued:!apply};
return {};
},1);
await canvas.begin('更新当前模板');
for(let index=0;index<21;index++)await canvas.edit({command:'text'},index);
apply=false;
const signal=AbortSignal.timeout(150);
await assert.rejects(canvas.edit({command:'text'},rev,signal),{name:'AbortError'});
assert.equal(dispatched,22);
});
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']){
assert.ok(names.includes(name),name);
}
return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{}'}}]},'tool_calls');
},undefined,{progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{nativeCatalog(){},nativeCall(){},nativeReconcile(){}}});
try {
const names=x.host.session.getActiveToolNames();
assert.ok(names.includes('codemode'));
assert.ok(names.includes('tool_search'));
assert.ok(names.includes('read')&&names.includes('write'));
assert.equal((await x.host.prompt('核对制作工具')).production.complete,true);
assert.equal(x.requests.length,1);
} finally {await x.close();}
});
}

View File

@ -240,7 +240,8 @@ test('actual Pi SDK executes memory tools, persists full transcript and reinject
return stream([{ type: 'text', text: '已记录胡桃色' }]);
} };
let host = await DetailPiAgent.open({ store, transport });
assert.deepEqual(host.session.getActiveToolNames().sort(), ['codemode','context_read','memory_search','memory_set','tool_search']);
assert.deepEqual(host.session.getActiveToolNames().sort(),
['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();
@ -248,17 +249,17 @@ test('actual Pi SDK executes memory tools, persists full transcript and reinject
assert.equal(host.session.messages.length, messages);
assert.equal(host.manager.getEntryCount(), entries);
await host.prompt('继续:颜色是什么?');
assert.equal(host.session.settingsManager.getRetryEnabled(), false);
assert.equal(host.session.settingsManager.getRetryEnabled(), true);
await host.dispose(); await cleanup(dir);
});
test('unknown preflight forbids dispatch and does not create a new prompt', async () => {
test('an unresolved inference does not block a new prompt or replay an old tool', 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() { calls++; return stream([{ type:'text',text:'x' }]); } };
const broker = { info: async () => ({ ...info(id.scope), pending: [{ id: 'original', phase: 'unknown' }] }) };
const host = await DetailPiAgent.open({ store, broker, transport });
await assert.rejects(host.prompt('不应发送'), /未知请求/);
assert.equal(calls, 0); assert.equal(host.session.messages.length, 0);
assert.equal((await host.prompt('新一轮请求')).text,'x');
assert.equal(calls, 1);
await host.dispose(); await cleanup(dir);
});
test('references enter the actual Pi user message as image and quoted text parts', async () => {
@ -281,18 +282,19 @@ test('references enter the actual Pi user message as image and quoted text parts
await cleanup(dir);
}
});
test('actual Pi SDK does not retry an overload or truncated completion', async () => {
test('actual Pi SDK retries an overloaded inference with the default budget', async () => {
const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A'));
let calls = 0;
const host = await DetailPiAgent.open({ store, transport: { info: info(id.scope), stream(model) {
calls++;
if (calls>1) return stream([{type:'text',text:'已接续。'}]);
const out = createAssistantMessageEventStream();
const error = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [], stopReason: 'error', errorMessage: 'HTTP 503 overload; original outcome unknown', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
queueMicrotask(() => { out.push({ type: 'error', reason: 'error', error }); out.end(error); });
return out;
} } });
await assert.rejects(host.prompt('验证自动重试已关闭'), /503/);
assert.equal(calls, 1);
assert.equal((await host.prompt('继续处理')).text,'已接续。');
assert.equal(calls, 2);
assert.ok(host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user'));
await host.dispose(); await cleanup(dir);
});

View File

@ -71,7 +71,7 @@ test('recovers structured image review for the original slot without adding it t
assert.equal(posts,0);
}finally{await host.dispose();await cleanup(root);}
});
test('410 remains unknown and all new inference stays blocked', async () => {
test('explicit text recovery queries the original without submitting inference', async () => {
const { root, scope, store } = await setup();
let queries = 0, posts = 0;
await store.appendEvent({ type: 'provider_prepared', id: 'original', bindingHash: store.hash });
@ -84,26 +84,9 @@ test('410 remains unknown and all new inference stays blocked', async () => {
const host = await DetailPiAgent.open({ store, broker });
const result = await host.recover('original');
assert.equal(result.phase, 'unknown'); assert.equal(result.reposted, false);
await assert.rejects(host.prompt('继续'), /未知请求/);
assert.equal(queries, 1); assert.equal(posts, 0);
await host.dispose(); await cleanup(root);
});
test('a pending goal outside the current conversation cannot be retried', async t => {
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const variantId=randomUUID(), detailSlot='product/goal/'+variantId+'/detail';
let starts=0;
const transport={info:{accountScope:scope,model:{id:'qa',protocol:'openai-chat'},
pending:[{id:randomUUID(),modelRole:'detail',phase:'unknown',detailSlot}]},
stream(){ starts++; throw Error('original still unknown'); }};
const canvas={detailImages(){},begin(){throw Error('native goal must not begin again');}};
const host=await DetailPiAgent.open({store,transport,canvas,productionGoal:{outputId:'detail',variantId}});
try {
await assert.rejects(host.prompt('继续整套制作'),/原请求不属于当前店铺/);
assert.equal(starts,0);
} finally { await host.dispose(); }
});
test('a waiting detail original does not hold independent main image and SKU goals',async t=>{
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
@ -149,125 +132,6 @@ test('a waiting detail original does not hold independent main image and SKU goa
assert.ok(offered.every(row=>row.id!==originalId));
});
test('a live production step uses the recovered original tool reply and never resends the POST', async t => {
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const id=randomUUID(), scopeId='product/strategy/'+randomUUID();
const model={id:'qa',protocol:'openai-chat'};
const call={index:0,id:'verified-tool',type:'function',function:{name:'save_result',arguments:'{"text":"原始答复"}'}};
const raw='data: '+JSON.stringify({id:'original',model:'qa',choices:[{index:0,delta:{tool_calls:[call]},finish_reason:'tool_calls'}]})+'\n\ndata: [DONE]\n\n';
let phase='unknown', posts=0, executed=0;
const lookedUp=[];
const reader={
read:async original=>{
assert.equal(original,id);
return {phase,terminal:phase==='received',model,bodyHash:'body',requestId:'original',raw:Buffer.from(raw).toString('base64')};
},
recover:async original=>{lookedUp.push(original);phase='received';},
confirm:async original=>{assert.equal(original,id);phase='complete';return {phase};},
close:async()=>{},
};
let bridges=0;
const broker={info:async()=>({accountScope:scope,model,pending:[]}),forDetailSlot:value=>{
assert.equal(value,scopeId);
if(++bridges>1)return reader;
return {hasUnconfirmedRequest:true,close:async()=>{},round:()=>{
posts++;
const wire='data: {"error":{"code":"request_outcome_unknown"}}\n\n';
return {id,fetch:async()=>new Response(wire,{headers:{'content-type':'text/event-stream'}}),finish:async()=>{throw Error('未收到原响应');}};
}};
}};
const canvas={read:async()=>({conversationActive:true,revision:1}),delta:async()=>{}};
const host=await DetailPiAgent.open({store,broker,canvas});
try{
host.productionRequests=new Map();
await host.runDetailAgent('production-strategy','保存原任务结果','策略',[
{name:'save_result',label:'保存',description:'保存',parameters:{type:'object',properties:{text:{type:'string'}},required:['text']},
execute:async(_id,args)=>{
assert.equal(args.text,'原始答复');
executed++;
return {content:[{type:'text',text:'已保存'}],details:{},terminate:true};
}},
],undefined,scopeId);
assert.deepEqual(lookedUp,[id]);
assert.equal(posts,1);
assert.equal(executed,1);
assert.equal(phase,'complete');
} finally { await host.dispose(); }
});
for (const mode of ['recover','in-progress','hold','resume']) {
test(`one-click goal recovers from an interrupted stream (${mode})`, async t=>{
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const variantId=randomUUID(),id=randomUUID(),review=randomUUID();
const inProgress=mode==='in-progress', upstreamReturned=mode==='recover'||inProgress, resume=mode==='resume';
const requestScope='product/goal/'+variantId+'/detail';
const model={id:'qa',protocol:'openai-chat',supportsImageInput:true};
const packet=(name,responseId)=>'data: '+JSON.stringify({id:responseId,model:model.id,choices:[{
index:0,delta:name?{tool_calls:[{index:0,id:'call-'+responseId,type:'function',
function:{name,arguments:'{}'}}]}:{role:'assistant',content:'详情已复核'},
finish_reason:name?'tool_calls':'stop'}]})+'\n\ndata: [DONE]\n\n';
const wire=body=>new Response(body,{headers:{'content-type':'text/event-stream'}});
const lookedUp=[], posted=[];
let state='unknown', bridges=0, plans=0;
const reader={
read:async original=>{
assert.equal(original,id);
return {phase:state,terminal:state==='received',model,bodyHash:'body',requestId:'upstream-original',
recovery:{status:inProgress&&state==='unknown'?409:410},raw:Buffer.from(packet('plan_production','original')).toString('base64')};
},
recover:async original=>{lookedUp.push(original);if(upstreamReturned&&(!inProgress||lookedUp.length===2)) state='received';},
confirm:async original=>{assert.equal(original,id);state='complete';return {phase:state};},
close:async()=>{},
};
const retries=[];
const pending=resume?[{id,phase:'unknown',detailSlot:requestScope,modelRole:'detail'}]:[];
if(resume) await store.appendEvent({type:'provider_prepared',id,purpose:'product-goal',bindingHash:store.hash});
const broker={...reader,info:async()=>({accountScope:scope,model,pending}),status:async()=>({pending}),
forDetailSlot:value=>{
assert.equal(value,requestScope);
if(++bridges>1)return reader;
return {isUnconfirmed:id=>posted.includes(id),close:async()=>{},round:({retryOf}={})=>{
if(retryOf) retries.push(retryOf);
const requestId=posted.length===0?id:randomUUID();
const interrupted=requestId===id;
const tool=interrupted?'plan_production':plans?'finish_production':'plan_production';
return {id:requestId,fetch:async()=>{
posted.push(requestId);
const reply=packet(tool,requestId);
return wire(interrupted?reply.replace('"finish_reason":"tool_calls"','"finish_reason":null').replace('data: [DONE]',''):reply);
},finish:async()=>{
if(interrupted)throw Error('原请求响应中断');
return {phase:'complete'};
}};
}};
}};
const canvas={run:'goal-fixture',documentId:13,detailImages(){},
begin:async()=>({run:'goal-fixture',conversationActive:true,context:null}),
read:async()=>({conversationActive:true}),delta:async()=>{},end:async()=>{},activity:async()=>{}};
const goal={outputId:'detail',variantId};
const host=await DetailPiAgent.open({store,broker,canvas,productionGoal:goal});
host.executeWholeDetail=async(_output,_production,_pending,_signal,drive)=>{
const stage=await drive({
async plan_production(){plans++;return {pendingText:0};},
async finish_production(){return {stage:{text:'已复核',production:{...goal,complete:true,canvasRevision:4}},status:{complete:true}};},
});
return stage??{text:'已保留草稿',production:{...goal,complete:false,originals:{models:[review],images:[]}}};
};
try {
const result=await host.prompt('制作详情、主图和 SKU');
assert.deepEqual(lookedUp,inProgress?[id,id]:[id]);
assert.equal(posted.length,resume?0:upstreamReturned?2:1);
assert.deepEqual(retries,[]);
assert.equal(plans,upstreamReturned?1:0);
assert.equal(result.production.complete,upstreamReturned);
if(upstreamReturned)assert.equal(result.production.canvasRevision,4);
else assert.equal(result.production.originals.goal,id);
}finally{await host.dispose();}
});
}
test('DeepSeek Flash 1017 can receive a named strategy tool and product image with thinking disabled', async t => {
const { root, scope, store } = await setup();
t.after(() => cleanup(root));
@ -312,7 +176,7 @@ test('DeepSeek Flash 1017 can receive a named strategy tool and product image wi
[[toolName,'started'],[toolName,'completed']]);
assert.ok(activity.every(event=>!JSON.stringify(event).includes('P01')));
const [body] = responses;
assert.deepEqual(body.thinking, { type: 'disabled' });
assert.equal(body.thinking,undefined);
assert.deepEqual(body.tool_choice, { type: 'function', function: { name: toolName } });
assert.ok(body.messages.some(message => Array.isArray(message.content) &&
message.content.some(part => part.image_url?.url === 'data:image/png;base64,UE5H')));
@ -497,8 +361,8 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
}
assert.equal(executed,cases.length);
assert.equal(sent.length,cases.length);
assert.deepEqual(sent[0].thinking,{type:'adaptive'});
assert.deepEqual(sent[0].output_config,{effort:'low'});
assert.equal(sent[0].thinking,undefined);
assert.equal(sent[0].output_config,undefined);
for(const body of sent){
assert.equal(body.max_tokens,128000);
assert.deepEqual(body.tool_choice,{type:'auto'});
@ -509,74 +373,6 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im
}
});
test('an original production rejection is reported after the same request is checked', async t => {
const { root, scope, store } = await setup();
t.after(() => cleanup(root));
const id = randomUUID(), requestId = randomUUID(), requestScope = 'product/strategy/' + randomUUID();
const model = { id: 'qa', protocol: 'openai-chat' };
let dispatched = 0, phase = 'unknown';
const lookedUp = [];
const reader = {
close: async () => {},
read: async original => {
assert.equal(original, id);
return { phase, requestId };
},
recover: async original => {
lookedUp.push(original);
phase = 'failed';
},
};
const broker = {
info: async () => ({ accountScope: scope, model, pending: [] }),
forDetailSlot: () => dispatched ? reader : {
hasUnconfirmedRequest: true, close: async () => {},
round: () => ({
id,
fetch: async () => {
dispatched++;
return new Response('{"error":{"code":"invalid_request","message":"Invalid request"}}',
{ status: 400, headers: { 'content-type': 'application/json' } });
},
finish: async () => { throw Error('结果未知'); },
}),
},
};
const canvas = { read: async () => ({ conversationActive: true, revision: 1 }), delta: async () => {} };
const host = await DetailPiAgent.open({ store, broker, canvas });
try {
host.productionRequests = new Map();
await assert.rejects(host.runDetailAgent('production-strategy', '检查原请求', '商品', [], undefined, requestScope),
error => error.message === '模型服务已确认制作请求失败(原请求 ' + requestId + ')');
assert.equal(dispatched, 1);
assert.deepEqual(lookedUp, [id]);
assert.equal(host.productionRequests.size, 0);
} finally {
await host.dispose();
}
});
test('a lost production reply stays scoped after the read-only 410',async t=>{
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const id=randomUUID(), scopeId='product/strategy/'+randomUUID();
const lookedUp=[];
let attemptedPosts=0;
const worker={close:async()=>{},read:async original=>({phase:'unknown',requestId:'original',recovery:{status:410}}),
recover:async original=>{lookedUp.push(original);throw Error('原结果未保留');},
round:()=>{attemptedPosts++;throw Error('不可重发');}};
const model={id:'qa',protocol:'openai-chat'};
const broker={info:async()=>({accountScope:scope,model,pending:[]}),forDetailSlot:()=>worker};
const host=await DetailPiAgent.open({store,broker,canvas:{read:async()=>({conversationActive:true,revision:1})}});
try {
host.productionRequests=new Map([[scopeId,{id,detailSlot:scopeId,phase:'unknown'}]]);
await assert.rejects(host.runDetailAgent('production-strategy','计划','商品',[],undefined,scopeId),
error=>error instanceof ProductionRequestPending&&error.id===id);
assert.deepEqual(lookedUp,[id]);
assert.equal(attemptedPosts,0);
assert.equal(host.productionRequests.get(scopeId).phase,'unknown');
} finally { await host.dispose(); }
});
test('an original request confirmed failed can be closed without replay and followed by a new message', async () => {
const { root, scope, store } = await setup();
const id = randomUUID(), requestId = randomUUID();

View File

@ -1158,7 +1158,7 @@ test('real Pi supervisor and slot agents use separate tool contexts',async t=>{
const what=previous?.toolName;
let request;
if(options.includes('delegate_image_slots')){
assert.deepEqual(options,['delegate_image_slots']);
assert.deepEqual(options.filter(name=>name!=='read'),['delegate_image_slots']);
if(!what)request=['delegate_image_slots',{slotIds:f.slots.map(slot=>slot.id),goal:'核对同款'}];
}else if(!what) {
request=['view_slot',{}];

View File

@ -10,17 +10,19 @@ import { DetailPiAgent } from '../src/agent.mjs';
import { ProjectStore, atomic } from '../src/store.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { NativeCanvas } from '../src/native-bridge.mjs';
import { workflowContext, workflowHistory, workflowResult } from '../src/workflow-context.mjs';
import { workflowContext, workflowResult } from '../src/workflow-context.mjs';
import { executeWorkflow } from '../src/workflow-execute.mjs';
import { cleanup } from './cleanup.mjs';
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'},pending:[] };
const prefix = '当前项目规则快照与已确认事实(每次调用重新注入,以此为准):\n';
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);
return JSON.parse(text.slice(text.lastIndexOf(prefix) + prefix.length).split('\n')[0]);
const start=text.lastIndexOf(prefix);
return start<0?undefined:JSON.parse(text.slice(start + prefix.length).split('\n')[0]);
}
function stream(content) {
const out = createAssistantMessageEventStream();
@ -106,7 +108,7 @@ async function fixture(reply,{adapter='full',execute=false,broker,history=false,
const store=await ProjectStore.open(root,identity,binding,{continuous:true}),canvas=baseCanvas();
if(history){
const manager=SessionManager.create(store.dir,path.join(store.dir,'sessions'));
for(let i=0;i<12;i++){
for(let i=0;i<48;i++){
manager.appendMessage({role:'user',content:`本地旧讨论${i}:`+'资料'.repeat(500),timestamp:Date.now()});
manager.appendMessage({role:'assistant',api:'openai-completions',provider:'jiansun-native-98k',model:info.model.id,content:answer('本地mock历史说明。'.repeat(100)),stopReason:'stop',timestamp:Date.now(),usage:{input:5000,output:500,cacheRead:0,cacheWrite:0,totalTokens:5500,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}});
}
@ -336,35 +338,6 @@ test('unsaved native drafts keep prior analysis stale and compaction does not re
}finally{await x.close();}
});
test('workflow projection is bounded and data-only while history compaction preserves original receipts',()=>{
const value={available:true,version:9,section:'slots',slots:Array.from({length:100},(_,i)=>({id:'slot-'+i,name:'槽位'+i,text:'可确认摘要'.repeat(100),source:'C:\\private\\original.png'})),
imagePrompt:'PRIVATE_LONG_PROMPT'.repeat(1000),path:'D:\\private\\project',images:['data:image/png;base64,PRIVATE_PIXELS'],previewUrl:'https://private.example/image'};
const safe=workflowResult(value),text=JSON.stringify(safe);
assert.ok(text.length<=8000);assert.ok(safe.omitted.entries>0);
for(const secret of ['PRIVATE_LONG_PROMPT','PRIVATE_PIXELS','D:\\private','C:\\private','https://private'])assert.ok(!text.includes(secret));
const nativeShape={available:true,version:9,section:'materials',brief:{name:'电脑桌',brandId:'brand',categoryId:'desk',identifierType:'SKU',identifier:'TABLE-1',colorName:'胡桃色',dimensions:{length:'1400',width:'600',height:'750',unit:'mm'},note:'实拍核对'},
draftDirty:true,factsStatus:'stale',planConfirmed:false,writeBlocked:true,width:1440,screenCount:5,selected:['batch:0'],batchCount:1,
capabilities:{imageDispatchAllowed:false,copyDispatchAllowed:false,localApplyAllowed:true},
slots:[{id:'slot',candidates:[{id:'candidate',variant:'B',reused:true}]}],
outputs:[{documentId:'M01',selectedImages:1,hasEditedDraft:true}]};
assert.deepEqual(workflowResult(nativeShape),nativeShape);
assert.deepEqual(workflowResult({navigated:true,stage:'plan',outputId:'detail',version:9,executed:false}),{navigated:true,stage:'plan',outputId:'detail',version:9,executed:false});
const read=(id,text)=>({role:'toolResult',toolName:'workflow_read',toolCallId:id,
content:[{type:'text',text:JSON.stringify({available:true,version:9,section:'slots',items:[{text}]})}]});
const raw={messages:[{role:'user',content:'上轮核对槽位'},read('old','OLD_LARGE_WORKFLOW'.repeat(500)),
{role:'user',content:'本轮重新读取槽位'},read('earlier','EARLIER_CURRENT_WORKFLOW'),read('latest','latest')]};
raw.messages.push({role:'toolResult',toolName:'workflow_propose',toolCallId:'proposal',content:[{type:'text',text:JSON.stringify({version:9,proposed:true,awaitingReview:true,executed:false,proposal:{version:9,intent:'export',instruction:'长建议'.repeat(100),outputId:'main_images',slotId:'main-slot',variant:'B',awaitingReview:true,executed:false}})}]});
const original=JSON.stringify(raw),projected=workflowHistory(raw,{version:9});
const old=JSON.parse(projected.messages[1].content[0].text),earlier=JSON.parse(projected.messages[3].content[0].text);
assert.equal(old.archivedWorkflowResult,'old');assert.equal(earlier.archivedWorkflowResult,'earlier');
assert.doesNotMatch(JSON.stringify(projected),/OLD_LARGE_WORKFLOW|EARLIER_CURRENT_WORKFLOW/);
assert.deepEqual(projected.messages[4],raw.messages[4]);
const receipt=JSON.parse(projected.messages.at(-1).content[0].text);
assert.equal(receipt.executed,false);assert.equal(receipt.intent,'export');assert.equal(receipt.outputId,'main_images');assert.equal(receipt.slotId,'main-slot');assert.equal(receipt.variant,'B');
assert.equal(JSON.stringify(raw),original);
assert.throws(()=>workflowContext({...value,version:Number.MAX_SAFE_INTEGER+1},{scope,project:'p',documentId:7}),/工作流版本/);
});
test('stdio and socket adapters route only the three typed workflow actions without network',async()=>{
const sent=[];
const stdio=new StdioCanvas(async(action,input)=>{sent.push({action,input});return {ok:true};},7);stdio.run='same-run';

View File

@ -2773,7 +2773,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>) -> R<Value> {
let template = json!({"id":state["template"]["id"],"name":state["template"]["name"],"version":state["template"]["version"],"contentHash":state["template"]["contentHash"],"resourceSetId":state["template"]["enterprise"]["resourceSetId"],"enterprise":state["template"]["enterprise"].is_object(),
"width":original_canvas[0],"height":original_canvas[1],"screenCount":screen_count,
"productionRoute":pack["productionRoute"],"production":profile.map(production_profile::agent_rules)});
let mut workflow = json!({"canvasFirst":true,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&active_color_enabled,"copyDispatchAllowed":false,"localApplyAllowed":ready}});
let mut workflow = json!({"canvasFirst":true,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&active_color_enabled,"copyDispatchAllowed":ready&&!pending&&active_color_enabled,"localApplyAllowed":ready}});
if state["productTemplates"].is_object() {
workflow["productionStages"] = json!(runnable_stages(&state, remaining_stages(dir, &state, &current["revision"], false)));
workflow["productionBlocks"] = json!(blocked_production_stages(&state));
@ -3276,7 +3276,7 @@ impl Backend {
let profile = &creation["designSnapshot"]["brand"]["profile"];
let visual =
profile["visualRules"].as_object().map(|values| values.values().filter_map(Value::as_str).collect::<Vec<_>>().join("\n")).unwrap_or_default();
let brand = json!({"name":creation["brief"]["brandName"],"tone":profile["tone"],"visualRules":visual.chars().take(4000).collect::<String>(),"fontFamily":"Noto Sans SC"});
let brand = json!({"name":creation["brief"]["brandName"],"tone":profile["tone"],"visualRules":visual,"fontFamily":"Noto Sans SC"});
let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height}));
let call = self.image_job_with_scene(Some(Arc::new(references)), &json!({"doc":doc,"revision":input["baseRevision"],"model":model,"mode":if parent.is_some(){"refine"}else{"generate"},"text":prompt,"screen":output["name"],"references":layers,"hasTemplateLayout":layout_position.is_some(),"optionalLayoutReference":layout_position.is_some()&&!fixed_layout,"slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k,"brand":if knowledge.is_null(){brand}else{json!({"name":creation["brief"]["brandName"],"knowledge":knowledge})},"facts":creation["facts"]}), false, events, ctx, scene);
let file = dir.join("image-jobs").join(&candidate).join("task.json");

View File

@ -411,8 +411,8 @@ fn stream_terminal(text: &str, model: &Value, bound_stream: bool) -> bool {
terminal
}
const ALLOWED_TOOLS: [&str; 22] = [
"ask_user",
const ALLOWED_TOOLS: &[&str] = &[
"ask_user", "read", "write", "edit", "ls", "find", "grep", "bash",
"context_read", "memory_set", "memory_search", "tool_develop", "tool_run", "canvas_read", "canvas_template_image", "canvas_candidate_image", "canvas_edit",
"workflow_read", "workflow_navigate", "workflow_propose", "workflow_execute", "codemode", "tool_search", "native_catalog", "native_call", "native_reconcile", "canvas_preview", "copywriting_options", "copywriting_fields",
];
@ -451,7 +451,9 @@ fn product_scope_tools(scope: &str) -> Option<&'static [&'static str]> {
Uuid::parse_str(id).ok()?;
match (step, parts.next(), parts.next()) {
("goal", Some("detail" | "main_images" | "sku_images"), None) =>
Some(&["workflow_read", "context_read", "plan_production", "read_production_knowledge", "read_copy_fields",
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"]),
("strategy", None, None) => Some(PRODUCT_STRATEGY_TOOLS),
@ -488,7 +490,7 @@ fn validate_scoped_payload(value: &Value, model: &Value, detail_slot: Option<&st
};
let n = n.map(|limit| limit.as_u64().ok_or("输出长度无效")).transpose()?;
let model_limit = model["maxTokens"].as_u64();
if n.is_none() && (model_limit.is_some() || model["protocol"] == "anthropic-messages") {
if n.is_none() && (model["requiresOutputLimit"] == true || model["protocol"] == "anthropic-messages") {
return Err("所选线路需要明确的输出长度".into());
}
if n.is_some_and(|limit| limit == 0 || model_limit.is_some_and(|declared| limit > declared))
@ -498,7 +500,7 @@ fn validate_scoped_payload(value: &Value, model: &Value, detail_slot: Option<&st
}
if let Some(tools) = value["tools"].as_array() {
let expected = detail_slot.map(|slot| product_scope_tools(slot).unwrap_or(DETAIL_SLOT_TOOLS));
let limit = expected.map_or(ALLOWED_TOOLS.len() + ENTERPRISE_TOOLS.len(), <[_]>::len);
let limit = expected.map_or(ALLOWED_TOOLS.len() + ENTERPRISE_TOOLS.len(), |names| names.len() + usize::from(!names.contains(&"read")));
if tools.len() > limit {
return Err("工具数量超限".into());
}
@ -510,7 +512,7 @@ fn validate_scoped_payload(value: &Value, model: &Value, detail_slot: Option<&st
let name = direct.or(nested).ok_or("工具名称无效")?;
let authorized = expected.map_or_else(
|| ALLOWED_TOOLS.contains(&name) || name.strip_prefix("ekb_").is_some_and(|name| ENTERPRISE_TOOLS.contains(&name)),
|names| names.contains(&name),
|names| names.contains(&name) || name == "read",
);
if !authorized {
return Err("工具未授权".into());
@ -605,7 +607,7 @@ pub(super) fn unresolved(dir: &Path) -> R<Vec<Value>> {
if let Some(original) = v["retryOf"].as_str() {
replaced_model_calls.insert(original.to_owned());
}
if matches!(v["phase"].as_str(), Some("dispatched" | "unknown" | "received" | "unavailable")) {
if v["inference"] != true && matches!(v["phase"].as_str(), Some("dispatched" | "unknown" | "received" | "unavailable")) {
pending.push(json!({"id":v["id"],"requestId":v["requestId"],"phase":v["phase"],"detailSlot":v["detailSlot"],
"modelRole":v["modelRole"].as_str().unwrap_or("chat"),"retryOf":v["retryOf"],"createdAt":v["createdAt"],
"originalLookup":public_lookup(&v)}));
@ -638,7 +640,7 @@ pub(super) fn run() -> R<()> {
return Err("SDK输入过大".into());
}
let input: Value = serde_json::from_slice(&bytes).map_err(|_| "SDK输入无效")?;
dispatch(input, &mut None, &mut false)
dispatch(input, &mut None, &mut None, &mut false)
}
// Read each line without ever allocating more than the request limit. Oversized
@ -717,11 +719,12 @@ pub(super) fn run_rpc() -> R<()> {
let stdin = std::io::stdin();
let mut reader = stdin.lock();
let mut shared_http = None;
let mut selection = None;
while let Some(line) = bounded_line(&mut reader)? {
let mut new_request_preflight = false;
let result = line.map_err(|_| "SDK输入过大".to_owned())
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).map_err(|_| "SDK输入无效".to_owned()))
.and_then(|input| dispatch(input, &mut shared_http, &mut new_request_preflight));
.and_then(|input| dispatch(input, &mut shared_http, &mut selection, &mut new_request_preflight));
if let Err(error) = result {
emit(rpc_error_frame(&error, new_request_preflight))?;
}
@ -729,7 +732,9 @@ pub(super) fn run_rpc() -> R<()> {
Ok(())
}
fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, new_request_preflight: &mut bool) -> R<()> {
type Selection = (String, String, Value, Value, Value);
fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &mut Option<Selection>, new_request_preflight: &mut bool) -> R<()> {
let project = uuid(&input, "project")?;
let root = crate::services::config_dir().ok_or("本机配置目录不可用")?.join("jiansun");
let mut backend = Backend::new(root)?;
@ -762,8 +767,10 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, new_request_p
return emit(json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],
"origin":backend.origin,"model":original["model"],"pending":pending}}));
}
let (_, mut model, invocation, selection_timings) = selected(&mut backend,input["modelRole"].as_str().unwrap_or("chat"))?;
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)?;
*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}}),
);
@ -809,12 +816,23 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, new_request_p
let original = read_task(&file)?;
(backend.settings()?, original["model"].clone())
} else {
let (settings, mut model, invocation, _) = selected(&mut backend,input["modelRole"].as_str().unwrap_or("chat"))?;
pi_runtime::apply_invocation_capacity(&mut model, &invocation)?;
if input["invocationHeaders"] != invocation["headers"] || input["invocationPath"] != model["path"] {
return Err("模型调用路由已更新,本次尚未提交".into());
let role = input["modelRole"].as_str().unwrap_or("chat");
let settings = backend.settings()?;
let scoped_model = selection.as_ref().filter(|(scope, cached_role, cached, model, invocation)|
scope == &backend.scope() && cached_role == role && cached == &settings
&& input["invocationHeaders"] == invocation["headers"] && input["invocationPath"] == model["path"]);
if let Some((_, _, _, model, _)) = scoped_model {
(settings, model.clone())
} else {
let (settings, mut model, invocation, _) = selected(&mut backend, role)?;
pi_runtime::apply_invocation_capacity(&mut model, &invocation)?;
if input["invocationHeaders"] != invocation["headers"] || input["invocationPath"] != model["path"] {
*selection = None;
return Err("模型调用路由已更新,本次尚未提交".into());
}
*selection = Some((backend.scope(), role.to_owned(), settings.clone(), model.clone(), invocation));
(settings, model)
}
(settings, model)
};
let key = settings["key"].as_str().ok_or("个人Key缺失")?;
let lookup = |task: &mut Value| {
@ -866,12 +884,8 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, new_request_p
validate_scoped_payload(&value, &model, detail_slot)?;
let headers = invocation_headers(&input)?;
let model_path = model["path"].as_str().ok_or("模型路径无效")?;
let timeout = Duration::from_secs(if scoped && detail_slot.is_some_and(|slot| slot.starts_with("product/goal/")) {
180
} else {
600
});
task = json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers,"timeoutMs":timeout.as_millis() as u64});
let timeout = Duration::from_secs(600);
task = json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers,"inference":input["inference"] == true,"timeoutMs":timeout.as_millis() as u64});
if let Some(original) = retry_of {
task["retryOf"] = json!(original);
}
@ -903,6 +917,9 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, new_request_p
write_task(&file, &task)?;
}
let status = response.status().as_u16();
if method == "request" && matches!(status, 401 | 403) {
*selection = None;
}
let content_type = response.headers().get("content-type").and_then(|s| s.to_str().ok()).unwrap_or("application/octet-stream").to_owned();
response_metadata(&mut task, method, status, &content_type);
write_task(&file, &task)?;

View File

@ -183,12 +183,29 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R<Value> {
let output_limit = capacity_route.and_then(|route| route["invocation"]["input_schema"]["properties"][output_field]["maximum"].as_u64())
.or_else(|| invocation["input_schema"]["properties"][output_field]["maximum"].as_u64())
.filter(|n| *n > 0 && *n <= 9_007_199_254_740_991);
Ok(json!({"version":3,"headers":headers,"model":model["id"],"path":model["path"],"routeId":model["routeId"],"at":now(),"contextWindow":limit,
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 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,
"reasoning":reasoning,"reasoningEfforts":reasoning_efforts,
"requiresOutputLimit":requires_output,
"contextWindowSource":limit.map(|_| format!("{UPSTREAM}/api/v2/catalog/models")),
"maxTokens":output_limit,"maxTokensSource":output_limit.map(|_| format!("{UPSTREAM}/api/v2/catalog/models"))}))
}
pub(super) fn apply_invocation_capacity(model: &mut Value, invocation: &Value) -> R<()> {
enrich_models(std::slice::from_mut(model))?;
model["reasoning"] = invocation["reasoning"].clone();
model["reasoningEfforts"] = invocation["reasoningEfforts"].clone();
model["requiresOutputLimit"] = invocation["requiresOutputLimit"].clone();
if invocation["contextWindow"].as_u64().is_some_and(|limit| limit > 0) {
model["contextWindow"] = invocation["contextWindow"].clone();
model["contextWindowSource"] = invocation["contextWindowSource"].clone();
@ -205,7 +222,7 @@ pub(super) fn invocation(b: &Backend, model: &Value) -> R<Value> {
let file = b.root.join("public-invocations").join(format!("{}.json", hash(&format!("{id}:{route}"))));
if file.exists() {
let value = read_json(&file)?;
if value["version"] == 3 && value["model"] == model["id"] && value["path"] == model["path"]
if value["version"] == 4 && value["model"] == model["id"] && value["path"] == model["path"]
&& value["routeId"] == model["routeId"] && value["at"].as_u64().is_some_and(|at| now().saturating_sub(at) < 300) {
return Ok(value);
}

View File

@ -225,10 +225,15 @@ fn safe_services(app: &PhotocraftApp) -> Result<(), String> {
Ok(())
}
pub(super) fn authority(_w: &Workspace, app: &PhotocraftApp, scope: &CommandScope, id: &str, params: &Value) -> Option<String> {
pub(super) fn authority(w: &Workspace, app: &PhotocraftApp, scope: &CommandScope, id: &str, params: &Value) -> Option<String> {
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
}
@ -432,6 +437,20 @@ 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 after = app.session.active().ok_or("当前画布未打开")?.revision;
return Ok(receipt(w, document, (before, after), method, &command, &applied, false));
}
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