fix(xiaoyi): resume Pi production compaction from original receipts

This commit is contained in:
WuYongJie 2026-11-25 23:09:43 +08:00
parent 795f1ea3ab
commit 6de9700d93
7 changed files with 349 additions and 106 deletions

View File

@ -18,8 +18,8 @@ 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 { boundProductionContext, transportProjection } from './context-budget.mjs';
import { compactionExtension, prepareCompactionRequest, requestPurpose, recoverCompaction, recoverCompactionWithoutResult, hasCompactionReviewForBranch, localBudgetFailureHash, COMPACTION_INSTRUCTIONS } from './compaction-recovery.mjs';
import { transportProjection } from './context-budget.mjs';
import { compactionExtension, prepareCompactionRequest, requestPurpose, recoverCompaction, recoverCompactionWithoutResult, resumeProductionCompaction, hasCompactionReviewForBranch, localBudgetFailureHash, COMPACTION_INSTRUCTIONS } from './compaction-recovery.mjs';
import { taskFor } from './rule-context.mjs';
import { productContext } from './project-context.mjs';
import { imageProgressQuestion, readImageProgress, workflowContext, workflowResult } from './workflow-context.mjs';
@ -106,7 +106,13 @@ function toolsFor(host) {
...(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', '查找本项目完整历史,包括压缩前的原始记录。', Type.Object({ query: Type.String({ minLength: 1, maxLength: 200 }) }), ({ query }) => host.store.search(query, host.manager)),
make('memory_search', '查找本项目历史。用 query 查对话,或用 toolCallId 和 offset 分段读取归档的工具回执。', Type.Object({
query:Type.Optional(Type.String({minLength:1,maxLength:200})),
toolCallId:Type.Optional(Type.String({minLength:1})),
offset:Type.Optional(Type.Integer({minimum:0})),
}, {additionalProperties:false}), ({query,toolCallId,offset=0}) => toolCallId
? host.store.readToolReceipt(host.manager,toolCallId,offset)
: host.store.search(query,host.manager)),
make('canvas_read', '本轮为多格文案预览时,固定读取全部本轮引用文字格,查询参数仅用于其他场景。先使用 mode=summary 查看真实组和画板,或用 filter 按名称、文本检索;重名时使用真实 screenId 指定组,需要细节时用真实 layer ID。仅在确有需要时用 offset 翻页,勿全量遍历。revision来自实时读取;writeBlocked=true 表示本轮不可写。', canvasReadParameters, async args => {
let {layer,screen,screenId,mode,filter,maxDepth,offset=0}=canvasReadQuery(args);
if (!host.canvas) return { available: false };
@ -415,8 +421,6 @@ export class DetailPiAgent {
output.end(message);
return;
}
host.rounds++;
if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`);
host.currentCanvas = liveCanvas?.context;
const injected = await host.modelContext();
injected.currentProduct = host.productEvidence;
@ -433,9 +437,12 @@ export class DetailPiAgent {
const wireContext = encoded ? jsonToolContext(contextual) : contextual;
const inputChars = contextTextLength(wireContext);
if (!host.compacting) await host.updateContextUsage(null, 'running');
if (host.productionGoal && !host.compacting && inputChars > 80_000) throw Error('当前制作所需资料超过单次输入预算,请按屏或按图位读取');
if (!host.productionGoal && inputChars > 120000) throw await host.localBudgetOverflow('本轮上下文超过本地输入预算', inputChars, options.signal);
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 });
if (transport?.stream) {
const stream = transport.stream(model, wireContext, options);
@ -458,8 +465,10 @@ export class DetailPiAgent {
purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation',
...(compaction ? {compactionPlanId: compaction.planId, compactionPlanHash: compaction.planHash, compactionPart: compaction.part, summaryProtocolMode: compaction.summaryProtocolMode} : {}) });
host.inflight = round.id;
requiredTool ??= host.requiredTool;
host.requiredTool = null;
if (!host.compacting) {
requiredTool ??= host.requiredTool;
host.requiredTool = null;
}
let wireCapture;
let sentAt, headersAt, firstTextAt;
const stream = apiImpl.streamSimple(model, wireContext, { ...options, apiKey: 'native-broker-only', fetch: async (...args) => {
@ -539,6 +548,9 @@ export class DetailPiAgent {
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;
@ -803,13 +815,19 @@ export class DetailPiAgent {
};
host.session = session;
activatePhotoCraftTools(session, customTools);
if (productionGoal) session.setActiveToolsByName(['context_read',...productionTools.map(([name])=>name)]);
if (productionGoal) session.setActiveToolsByName(['context_read','memory_search',...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;
@ -978,8 +996,8 @@ export class DetailPiAgent {
}
async localBudgetOverflow(reason, inputChars, signal) {
const failure = Error(`${reason},本轮未完成;未发起该次模型请求,原工具结果与历史已保留`);
// Summary requests and a second overflow never arm another recovery.
if (this.compacting || this.localBudgetRecovery) return failure;
// 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};
@ -993,9 +1011,9 @@ export class DetailPiAgent {
}
projectModelContext(context, injected) {
if (this.productionGoal && !this.compacting) injected.productionGoal = {...this.productionGoal,objective:productionObjective};
const projected = 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});
return this.productionGoal && !this.compacting ? boundProductionContext(projected, this.info.model) : projected;
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));
@ -1039,6 +1057,11 @@ export class DetailPiAgent {
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
@ -1086,12 +1109,12 @@ export class DetailPiAgent {
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 ? null : await this.projectedContext(prompt, images);
const projection = this.imageProgressTurn || this.productionGoal ? null : await this.projectedContext(prompt, images);
const projectedChars = projection ? contextTextLength(projection) : 0;
await this.store.appendEvent({type: 'automatic_compaction_budget', projectedChars, originalChars: JSON.stringify(this.session.messages).length});
if (projection && ((!this.productionGoal && projectedChars > 80000) || exceedsModelBudget(projection, this.info.model, 0.8))) {
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 ((!this.productionGoal && projectedChars > 120000) || exceedsModelBudget(projection, this.info.model)) throw Error('原分支摘要尚未应用,本轮上下文超过输入预算;原记录保留,请先人工核对摘要或新建会话。未发起模型请求');
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
@ -1128,6 +1151,16 @@ 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)
@ -1137,17 +1170,14 @@ 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 !== 'committed') throw this.compactionFailure || Error('本轮预算压缩未完成或已停止;未继续模型请求,原工具结果与历史已保留');
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 (this.localBudgetRecovery && last?.stopReason !== 'stop') throw Error('本轮预算压缩后尚未得到完整回复;原工具结果与历史已保留');
if (this.localBudgetRecovery) {
this.localBudgetRecovery.phase = 'completed';
await this.store.appendEvent({type: 'local_budget_recovery_completed', planId: this.localBudgetRecovery.planId});
}
const resultText = useStageReceipt ? this.goalStageResult.text :
this.generatedCandidateReply() ?? (this.templateOriginal && !this.templateImageRead
? '模板原图尚未读取,暂时无法确认视角。可以引用画布里的具体图位,再继续核对。'
@ -1297,7 +1327,7 @@ export class DetailPiAgent {
try { await this.broker.recover(id); }
catch (error) {
await this.store.appendEvent({ type: 'recovery_unknown', id, requestId: record.requestId, reason: error.message });
return { phase: 'unknown', requestId: record.requestId, reason: error.message, reposted: false };
return { phase: 'unknown', requestId: record.requestId, reason: error.message, reposted: false, internalCompaction };
}
record = { id, ...await this.broker.read(id) };
}
@ -1310,7 +1340,7 @@ export class DetailPiAgent {
return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose.kind==='whole-detail-review'
?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)};
}
if (['unavailable', 'failed', 'rejected'].includes(record.phase) && internalCompaction) return recoverCompactionWithoutResult(this, id, record, purpose);
if (internalCompaction && !['complete','received'].includes(record.phase)) return recoverCompactionWithoutResult(this, id, record, purpose);
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};

View File

@ -5,9 +5,11 @@ import { compact as sdkCompact, createSyntheticSourceInfo, VERSION } from '@eare
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 = '保留产品的最新颜色/尺寸、用户决定、店铺/品类绑定、已测试工具及版本。任何未确认项继续标注待确认。历史原文保留在会话树,可memory_search检索。';
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.
@ -58,16 +60,30 @@ export function compactionExtension(host) {
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, parentUnchanged: tail[0]?.parentId === recovery.leafId,
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: tail[1]?.type === 'context_edit' && tail[1].targetId === tail[0]?.id && tail[1].replacement === null};
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('本地预算恢复分支已变化,未派发摘要;原记录已保留');
@ -76,7 +92,7 @@ export function compactionExtension(host) {
host.compacting = true;
}
const raw = event.preparation;
const options = {bindingHash: host.store.hash, version: host.currentWorkflow?.version};
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
@ -88,6 +104,7 @@ export function compactionExtension(host) {
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} : {})};
@ -178,8 +195,85 @@ export async function recoverCompactionWithoutResult(host, id, record, purpose)
localDisposition: record.originalLookup.status === 'failed' ? 'failed' : 'rejected', originalTreePreserved: true};
}
/** Reinterpret the retained response as an SDK checkpoint, never an ordinary
* assistant reply. Unsupported/missing/split proofs remain retained for review. */
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;
@ -196,28 +290,20 @@ export async function recoverCompaction(host, id, record, message, purpose) {
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 (plan.expectedParts !== 1 || metadata.part !== 1 || host.manager.getLeafId() !== plan.leafId || branchHash(host) !== plan.branchHash
|| host.manager.getSessionFile() !== plan.sessionFile || metadata.firstKeptEntryId !== plan.firstKeptEntryId || metadata.tokensBefore !== plan.tokensBefore
|| digest(plan.preparation.settings) !== digest(host.session.settingsManager.getCompactionSettings(host.session.model))
|| !host.manager.getBranch().some(entry => entry.id === plan.firstKeptEntryId)) {
if (!currentCheckpoint(host,plan) || metadata.firstKeptEntryId !== plan.firstKeptEntryId || metadata.tokensBefore !== plan.tokensBefore) {
return retainReview(host, id, record, message, 'checkpoint_branch_or_parts_unproven');
}
let calls = 0;
const result = await sdkCompact(restorePreparation(plan.preparation), host.session.model, 'retained-response-in-memory', undefined, plan.instructions,
undefined, 'off', () => {
if (++calls !== 1) throw Error('原摘要未包含完整压缩计划,未继续调用');
const stream = createAssistantMessageEventStream();
queueMicrotask(() => {stream.push({type: 'start', partial: message}); stream.push({type: 'done', reason: 'stop', message}); stream.end(message);});
return stream;
}, undefined, {enabled: false, maxRetries: 0});
if (branchHash(host) !== plan.branchHash || result.firstKeptEntryId !== plan.firstKeptEntryId || result.tokensBefore !== plan.tokensBefore) {
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');
}
host.manager.appendCompaction(result.summary, result.firstKeptEntryId, result.tokensBefore,
{...result.details, jiansunCompactionPlanId: plan.id, jiansunRecoveredRequestId: id}, true, result.usage);
await atomic(path.join(host.store.dir, 'session.json'), {file: host.manager.getSessionFile()});
await host.store.appendEvent({type: 'compaction_recovered', id, planId: plan.id, branchHash: plan.branchHash, toolsExecuted: 0});
host.needsReopen = true;
return {phase: 'complete', requestId: record.requestId, reposted: false, internalCompaction: true, compactionApplied: true, reopenRequired: true, toolsExecuted: 0, canvasWrites: 0};
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,6 +1,5 @@
import { workflowHistory } from './workflow-context.mjs';
import { presentText } from './stream-presentation.mjs';
import { contextTextLength, exceedsModelBudget } from './context-usage.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) => {
@ -34,7 +33,7 @@ const layerSnapshot = (layer, limit = 240) => {
};
/** A transport projection only: the SDK's original transcript and tool evidence stay intact. */
export function projectContext(context,{bindingHash,templateOriginal}={}) {
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));
@ -155,6 +154,15 @@ export function projectContext(context,{bindingHash,templateOriginal}={}) {
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,
@ -167,47 +175,6 @@ export function projectContext(context,{bindingHash,templateOriginal}={}) {
});
return { messages };
}
export const transportProjection = (context, { bindingHash, version, templateOriginal } = {}) =>
projectContext(workflowHistory(context, { version }), { bindingHash, templateOriginal });
export function boundProductionContext(context, model) {
const fits = candidate => contextTextLength(candidate) <= 80_000 && !exceedsModelBudget(candidate, model, 0.8);
if (fits(context)) return context;
// Keep the rule snapshot and the current user instruction, plus recent
// assistant/tool exchanges. Dropping an exchange never leaves orphaned
// tool results in an Anthropic or Responses request.
const currentUser = context.messages.findLastIndex(message => message.role === 'user');
const anchors = new Set();
const groups = [];
const pending = new Map();
for (let index = 0; index < context.messages.length; index++) {
const message = context.messages[index];
if (message.role === 'system' || index === currentUser) {
anchors.add(index);
continue;
}
if (message.role === 'toolResult') {
pending.get(message.toolCallId)?.push(index);
continue;
}
const group = [index];
groups.push(group);
if (message.role === 'assistant') {
for (const part of message.content ?? []) {
if (part.type === 'toolCall') pending.set(part.id, group);
}
}
}
const projection = kept => ({ ...context, messages: context.messages.filter((_, index) => kept.has(index)) });
let result = projection(anchors);
for (const group of groups.reverse()) {
const candidate = new Set([...anchors, ...group]);
const next = projection(candidate);
if (!fits(next)) break;
for (const index of group) anchors.add(index);
result = next;
}
return result;
}
export const transportProjection = (context, { version, ...options } = {}) =>
projectContext(workflowHistory(context, { version }), options);
export const promptChars = (context, options) => JSON.stringify(transportProjection(context, options)).length;

View File

@ -161,7 +161,8 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
result = await host.recover(pending[0].id, { executeReadOnly: false });
result.text = result.phase === 'unknown' ? `原请求仍待核查(${result.requestId || pending[0].id}),未重发。`
: result.internalCompaction ? result.compactionApplied
? '原内部会话摘要已恢复为SDK压缩断点。没有执行原工作流请求或画布操作;请重新打开会话。'
? '已取回原摘要并恢复会话进度。'
: result.compactionContinuation ? '已取回原摘要,制作继续时会补齐剩余段落。'
: result.originalResultUnavailable
? result.originalExecutionStatus === 'succeeded'
? '原内部摘要请求已成功,但上游未保留可取回的结果。摘要未应用,原始会话树完整保留;未执行原工作流或画布操作,也未重发原请求。'

View File

@ -125,6 +125,15 @@ export class ProjectStore {
try { const entry = JSON.parse(line); return entry.type === 'provider_prepared' && entry.id === id && (!entry.bindingHash || entry.bindingHash === this.hash); } catch { return false; }
});
}
readToolReceipt(manager, toolCallId, offset) {
const entry = manager.getBranch().findLast(row =>
row.type === 'message' && row.message.role === 'toolResult' && row.message.toolCallId === toolCallId);
if (!entry) throw Error('本分支没有对应的工具回执');
const text = entry.message.content.filter(item => item.type === 'text').map(item => item.text).join('\n');
const preview = text.slice(offset, offset + 8000);
const end = offset + preview.length;
return {toolCallId,text:preview,nextOffset:end < text.length ? end : null};
}
async search(query, manager) {
if (typeof query !== 'string' || !query || query.length > 200) throw Error('搜索词无效');
const hits = manager.getEntries().filter(e => e.type === 'message' && ['user', 'assistant'].includes(e.message?.role)).map(e => {

View File

@ -260,10 +260,22 @@ test('the one-click goal resumes on changed fields at the same count without nam
} finally { await x.close(); }
});
test('a production turn uses its model budget and the authenticated canvas even without a full context snapshot',async()=>{
const x=await setup((_,n)=>n===1
?sse({tool_calls:[{index:0,id:'plan',type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls')
:sse({content:'等待原请求。'},'stop'),undefined,{plan:()=>({plan:'本款商品资料'.repeat(24000)}),
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;
@ -271,8 +283,8 @@ test('a production turn uses its model budget and the authenticated canvas even
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,2);
assert.ok(JSON.stringify(x.requests[1].messages).length <= 80_000);
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();}
@ -511,8 +523,8 @@ test('projection bounds stale canvas bodies without deleting original facts, err
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:['旧店铺专属规范']}})}]};
const original=JSON.stringify(old),projected=projectContext({messages:[old]},{bindingHash:'current'});
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('旧规则域历史'));
@ -627,3 +639,126 @@ test('automatic compaction and subsequent inference share one user-turn call bud
assert.equal(x.calls, 1);
} 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();
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();}
});
}

View File

@ -238,3 +238,18 @@ PhotoCraft 用正式文件独立导入了 5 张主图和 1 张 SKU,并按原
本批未执行 98K 模型调用、新原生客户端构建、Photoshop 外部兼容及实际三类导出。阶段 D 继续使用输出与花色作为执行单元。后续核验 Pi 原生压缩和作业恢复,再推进项目级主代理与实际需要的 Skill 执行绑定。
## 第八批 · 阶段 D,Pi 原生上下文压缩与恢复
一键制作达到输入预算时,由 Pi 原生会话确定压缩位置并写入断点。制作请求使用同一处派发前预算检查。单条超大的工具回执在请求中提供预览和读取位置,完整原文留在当前项目的 Pi 会话,主代理可以按回执编号分页读取。
| 触发条件 | 出口 | 验证 |
| --- | --- | --- |
| 生产回合累计超过输入预算 | Pi 只省略未派发的空错误,并保留目标状态、完整工具历史和独立图位原请求。压缩后在同一个目标继续 | A23 本地通过。使用锁定的 Pi SDK 1.5.2 和不同品类的灯具主图夹具;实际写入会话、关闭并重开。原回复、工具回执和图位核查编号仍可读取 |
| 摘要请求在第一段或末段中断 | 按原编号核查。已确认的摘要片段直接复用。仅在目标继续执行时补发尚未派发的后续片段;核查本身只读 | 两种情况均通过。本地模拟原号查询期间新增 POST 为 0,原请求落定后两段摘要各发送一次,只写入一个压缩断点 |
| 摘要回执已完整,断点尚未写入时退出 | 重开按原会话、项目与输出绑定恢复断点,继续使用已收到的摘要 | 通过独立重开验证。已有两段回执在恢复时新增摘要 POST 为 0,再次核查同一请求不会重复写入断点 |
| 单条制作工具回执过大 | 上下文保留回执编号与预览,按需分段读取实际归档原文 | 通过灯具主图准备回执分页测试,模型只收到受预算约束的请求,原画布身份校验通过 |
证据位于 `D:/AI Code/gongxiangp2/output/xiaoyi-harness-implementation-20261125/batch-08/`。Agent 套件 318 项通过,最终原生请求回归 39 项通过,见 `phase-d-regression.log` 与 `native-wire-regression.log`。另用顾家电脑桌正式主图发布映射的 5 张模板输入重复了 3 个断点场景,均通过,见 `desk-compaction-recovery.log`。本批使用本地模拟上游,未执行 98K 调用、新客户端构建、Photoshop 兼容与三类实际导出。
下一切片推进项目级目标所有权,并梳理正式 Skill 实际依赖的执行工具。