提前压缩主小壹上下文并保留制作关键事实
This commit is contained in:
parent
ae788c7f26
commit
8bc34cf419
@ -12,7 +12,8 @@ import { BridgeError } from './bridge-error.mjs';
|
||||
import { protectSession, redactText } from './credentials.mjs';
|
||||
import { productionTools, callProductionTool, closeProductionTurn, describeProductionOutput, piGoalState, runPiProductionGoal, unfinishedProductionTurn } from './production-goal.mjs';
|
||||
import { productionVideoTools } from './production-operations.mjs';
|
||||
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { createAgentSession, DEFAULT_COMPACTION_SETTINGS, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { getSupportedThinkingLevels } from '@earendil-works/pi-ai';
|
||||
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
|
||||
import { atomic } from './store.mjs';
|
||||
import { workerTurnBudget } from './worker-receipts.mjs';
|
||||
@ -30,6 +31,13 @@ import { NativeExtensionUI } from './native-ui.mjs';
|
||||
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
|
||||
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
|
||||
|
||||
const MAIN_CONTEXT_BUDGET = 150_000;
|
||||
const COMPACTION_FACTS = `压缩摘要用于继续当前工作。合并旧摘要和本次记录,保留仍有效的事实及其原始编号:
|
||||
- 在途及已付费的出图请求号、候选号、各图位状态和各图位已采用的候选。
|
||||
- 已做的决定及理由,以及未解决的问题。
|
||||
- 当前成品、当前屏、锁定的知识库版本和已写出的文件路径。
|
||||
遇到状态变更,以最新明确回执为准。保留未确认状态,不猜测缺失编号或结果。`;
|
||||
|
||||
// 98k sends a single data line for terminal errors after the HTTP status is committed.
|
||||
// Observe the structured code before the provider parser drops it from errorMessage.
|
||||
function observeUnknownOutcome(response, onUnknownOutcome) {
|
||||
@ -419,6 +427,15 @@ export class DetailPiAgent {
|
||||
try {
|
||||
options.signal?.throwIfAborted();
|
||||
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');
|
||||
if (purpose === 'compaction') {
|
||||
// Keep Pi's summary generator, including split turns, retries and overflow recovery.
|
||||
context = {...context, systemPrompt: context.systemPrompt + '\n\n' + COMPACTION_FACTS};
|
||||
if (['medium','high','xhigh','max'].includes(options.reasoning)) {
|
||||
const supported = getSupportedThinkingLevels(model);
|
||||
const reasoning = supported.includes('low') ? 'low' : supported.find(level => level === 'minimal');
|
||||
if (reasoning) options = {...options, reasoning};
|
||||
}
|
||||
}
|
||||
if (!worker) {
|
||||
const {textChars: inputChars, totalChars} = contextLengths(context);
|
||||
if (!host.compacting) await host.updateContextUsage(null, 'running');
|
||||
@ -524,11 +541,13 @@ export class DetailPiAgent {
|
||||
systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM,
|
||||
});
|
||||
host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath)));
|
||||
const model = runtime.getModel('jiansun-native-98k', info.model.id);
|
||||
const reserveTokens = Math.max(DEFAULT_COMPACTION_SETTINGS.reserveTokens, model.contextWindow - MAIN_CONTEXT_BUDGET);
|
||||
const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime,
|
||||
model: runtime.getModel('jiansun-native-98k', info.model.id),
|
||||
model,
|
||||
thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined,
|
||||
resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal','update_goal'] : []),
|
||||
settingsManager: SettingsManager.inMemory({retry:mainRetry}), sessionManager: host.manager,
|
||||
settingsManager: SettingsManager.inMemory({retry:mainRetry, compaction:{reserveTokens}}), sessionManager: host.manager,
|
||||
});
|
||||
const workerSettings = SettingsManager.inMemory({retry,cacheWarming:'off',compaction:{enabled:false},enableSkillCommands:false});
|
||||
let workerResources;
|
||||
|
||||
@ -17,7 +17,7 @@ import { auditResponse, InvalidToolReply } from '../src/response-audit.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
import { normalizeContext } from '@earendil-works/pi-ai/compat';
|
||||
import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
|
||||
import { SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { DEFAULT_COMPACTION_SETTINGS, SessionManager, SettingsManager, shouldCompact } 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';
|
||||
@ -661,18 +661,20 @@ test('a terminal marker without a completion reason remains unproven and cannot
|
||||
assert.throws(() => auditResponse(sse(broken,'tool_calls'),'openai-chat'),InvalidToolReply);
|
||||
});
|
||||
|
||||
async function compactionFixture({ withCanvas, callBudget = 4, large = false, pendingStep, rateLimit = false } = {}) {
|
||||
async function compactionFixture({ withCanvas, callBudget = 4, large = false, contextWindow = 64_000, historyInput = large ? 50_000 : 5_000, pendingStep, rateLimit = false } = {}) {
|
||||
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 ? 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 } } });
|
||||
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: historyInput, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: historyInput + 500, 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 requests = [];
|
||||
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', contextWindow:64000, contextWindowSource:'fixture' }, pending: [] }, stream(model) {
|
||||
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat', contextWindow, contextWindowSource:'fixture', reasoning:true, reasoningEfforts:['low','high'] }, thinkingLevel:'high', pending: [] }, stream(model, context, options) {
|
||||
requests.push({model:model.id, systemPrompt:context.systemPrompt, reasoning:options.reasoning});
|
||||
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 } } };
|
||||
@ -710,26 +712,43 @@ async function compactionFixture({ withCanvas, callBudget = 4, large = false, pe
|
||||
};
|
||||
}
|
||||
const host = await openAgent({ store, transport:broker?undefined:transport, broker, canvas, callBudget, productionGoal:goal });
|
||||
return { host, get calls() { return calls; }, get canvasCalls() { return canvasCalls; }, close: async () => { await host.dispose(); await cleanup(dir); } };
|
||||
return { host, requests, get calls() { return calls; }, get canvasCalls() { return canvasCalls; }, close: async () => { await host.dispose(); await cleanup(dir); } };
|
||||
}
|
||||
test('compaction with a connected canvas does not call an inactive edit run or show the internal summary', async () => {
|
||||
const x = await compactionFixture({ withCanvas: true });
|
||||
try {
|
||||
const result = await x.host.compact();
|
||||
assert.match(result.summary, /original evidence/); assert.ok(x.calls > 0); assert.equal(x.canvasCalls, 0);
|
||||
assert.deepEqual(x.host.session.settingsManager.getCompactionSettings(x.host.session.model), DEFAULT_COMPACTION_SETTINGS);
|
||||
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('the Pi defaults compact from the native session threshold',async()=>{
|
||||
const x=await compactionFixture({large:true});
|
||||
test('the main session compacts above 150k with production facts and lower summary effort',async()=>{
|
||||
const x=await compactionFixture({large:true,contextWindow:272_000,historyInput:180_000});
|
||||
try {
|
||||
const settings=x.host.session.settingsManager;
|
||||
assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:16384,keepRecentTokens:20000});
|
||||
assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:122_000,keepRecentTokens:20_000});
|
||||
assert.deepEqual(Object.fromEntries(Object.entries(settings.getRetrySettings()).filter(([k])=>['enabled','maxRetries','baseDelayMs'].includes(k))),
|
||||
{enabled:true,maxRetries:6,baseDelayMs:3000});
|
||||
await x.host.prompt('继续');
|
||||
assert.equal(x.calls,3);
|
||||
const compactionSettings=settings.getCompactionSettings(x.host.session.model);
|
||||
assert.equal(shouldCompact(180_500,272_000,DEFAULT_COMPACTION_SETTINGS),false);
|
||||
assert.equal(shouldCompact(150_000,272_000,compactionSettings),false);
|
||||
assert.equal(shouldCompact(150_001,272_000,compactionSettings),true);
|
||||
const summaries=x.requests.slice(0,-1);
|
||||
for (const {systemPrompt,reasoning} of summaries) {
|
||||
assert.equal(reasoning,'low');
|
||||
for (const fact of [
|
||||
'在途及已付费','出图请求号','候选号','各图位状态','各图位已采用的候选',
|
||||
'已做的决定及理由','未解决的问题','当前成品','当前屏','锁定的知识库版本','已写出的文件路径',
|
||||
]) {
|
||||
assert.ok(systemPrompt.includes(fact),fact);
|
||||
}
|
||||
}
|
||||
assert.equal(x.requests.at(-1).reasoning,'high');
|
||||
assert.ok(x.requests.every(request=>request.model==='qa'));
|
||||
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')));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user