@agimon-ai/doompi-autocompact 0.0.1-alpha.44 → 0.0.1-alpha.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/adapters/compaction/policy.cjs +8 -0
- package/dist/adapters/compaction/policy.cjs.map +1 -0
- package/dist/adapters/compaction/policy.d.cts +7 -0
- package/dist/adapters/compaction/policy.d.cts.map +1 -0
- package/dist/adapters/compaction/policy.d.mts +7 -0
- package/dist/adapters/compaction/policy.d.mts.map +1 -0
- package/dist/adapters/compaction/policy.mjs +8 -0
- package/dist/adapters/compaction/policy.mjs.map +1 -0
- package/dist/adapters/pi/extension.cjs +44 -0
- package/dist/adapters/pi/extension.cjs.map +1 -0
- package/dist/{src/adapters → adapters}/pi/extension.d.cts +2 -0
- package/dist/adapters/pi/extension.d.cts.map +1 -0
- package/dist/{src/adapters → adapters}/pi/extension.d.mts +2 -0
- package/dist/adapters/pi/extension.d.mts.map +1 -0
- package/dist/adapters/pi/extension.mjs +44 -0
- package/dist/adapters/pi/extension.mjs.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
- package/dist/{src/adapters → adapters}/telemetry/logSinkTelemetry.d.cts +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
- package/dist/{src/adapters → adapters}/telemetry/logSinkTelemetry.d.mts +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
- package/dist/extensions/pi.cjs +1 -1
- package/dist/extensions/pi.d.cts +1 -1
- package/dist/extensions/pi.d.mts +1 -1
- package/dist/extensions/pi.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/services/summarizationModel.cjs.map +1 -0
- package/dist/services/summarizationModel.d.cts.map +1 -0
- package/dist/services/summarizationModel.d.mts.map +1 -0
- package/dist/services/summarizationModel.mjs.map +1 -0
- package/dist/types/constants.cjs.map +1 -0
- package/dist/types/constants.mjs.map +1 -0
- package/dist/types/index.d.cts +8 -0
- package/dist/types/index.d.cts.map +1 -0
- package/dist/types/index.d.mts +8 -0
- package/dist/types/index.d.mts.map +1 -0
- package/package.json +16 -6
- package/src/exports/webClient.ts +1 -0
- package/src/types/autocompactSettings.ts +97 -0
- package/src/types/constants.ts +27 -0
- package/src/web/autocompactSettings.ts +31 -0
- package/src/web/index.ts +15 -0
- package/src/web/tsconfig.json +23 -0
- package/dist/checkpointWorker.cjs +0 -2
- package/dist/checkpointWorker.cjs.map +0 -1
- package/dist/checkpointWorker.d.cts +0 -19
- package/dist/checkpointWorker.d.cts.map +0 -1
- package/dist/checkpointWorker.d.mts +0 -19
- package/dist/checkpointWorker.d.mts.map +0 -1
- package/dist/checkpointWorker.mjs +0 -2
- package/dist/checkpointWorker.mjs.map +0 -1
- package/dist/src/adapters/compaction/policy.cjs +0 -8
- package/dist/src/adapters/compaction/policy.cjs.map +0 -1
- package/dist/src/adapters/compaction/policy.d.cts +0 -7
- package/dist/src/adapters/compaction/policy.d.cts.map +0 -1
- package/dist/src/adapters/compaction/policy.d.mts +0 -7
- package/dist/src/adapters/compaction/policy.d.mts.map +0 -1
- package/dist/src/adapters/compaction/policy.mjs +0 -8
- package/dist/src/adapters/compaction/policy.mjs.map +0 -1
- package/dist/src/adapters/pi/extension.cjs +0 -44
- package/dist/src/adapters/pi/extension.cjs.map +0 -1
- package/dist/src/adapters/pi/extension.d.cts.map +0 -1
- package/dist/src/adapters/pi/extension.d.mts.map +0 -1
- package/dist/src/adapters/pi/extension.mjs +0 -44
- package/dist/src/adapters/pi/extension.mjs.map +0 -1
- package/dist/src/adapters/telemetry/logSinkTelemetry.cjs +0 -2
- package/dist/src/adapters/telemetry/logSinkTelemetry.cjs.map +0 -1
- package/dist/src/adapters/telemetry/logSinkTelemetry.d.cts.map +0 -1
- package/dist/src/adapters/telemetry/logSinkTelemetry.d.mts.map +0 -1
- package/dist/src/adapters/telemetry/logSinkTelemetry.mjs +0 -2
- package/dist/src/adapters/telemetry/logSinkTelemetry.mjs.map +0 -1
- package/dist/src/services/summarizationModel.cjs.map +0 -1
- package/dist/src/services/summarizationModel.d.cts.map +0 -1
- package/dist/src/services/summarizationModel.d.mts.map +0 -1
- package/dist/src/services/summarizationModel.mjs.map +0 -1
- package/dist/src/types/constants.cjs.map +0 -1
- package/dist/src/types/constants.mjs.map +0 -1
- package/dist/src/types/index.d.cts +0 -6
- package/dist/src/types/index.d.cts.map +0 -1
- package/dist/src/types/index.d.mts +0 -6
- package/dist/src/types/index.d.mts.map +0 -1
- /package/dist/{src/services → services}/summarizationModel.cjs +0 -0
- /package/dist/{src/services → services}/summarizationModel.d.cts +0 -0
- /package/dist/{src/services → services}/summarizationModel.d.mts +0 -0
- /package/dist/{src/services → services}/summarizationModel.mjs +0 -0
- /package/dist/{src/types → types}/constants.cjs +0 -0
- /package/dist/{src/types → types}/constants.mjs +0 -0
package/README.md
CHANGED
|
@@ -35,7 +35,8 @@ subject to token caps and Pi's native-compaction clamp:
|
|
|
35
35
|
2. combine it with later messages and allow the model to decide whether compaction is ready;
|
|
36
36
|
3. combine again and force compaction on the final pass.
|
|
37
37
|
|
|
38
|
-
Summarization runs in
|
|
38
|
+
Summarization runs asynchronously in the background, on the session's own provider, so a model
|
|
39
|
+
registered by a Pi provider extension summarizes through that extension. Checkpoints are
|
|
39
40
|
persisted as hidden session entries and used for later steering.
|
|
40
41
|
|
|
41
42
|
DoomPi uses the configured planning subagent model and thinking level when available, then falls
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const e=require("../../types/constants.cjs");let t=require("@earendil-works/pi-coding-agent");const n=/<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i,r=/\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;function i(e){return typeof e==`object`&&!!e}function a(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function o(e){return e===1||e===2||e===3}function s(e){if(e.type===`message`&&e.message.role===`assistant`)return e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
`).trim()||void 0}function c(e){return i(e)&&typeof e.role==`string`}function l(e){if(!i(e)||!a(e.readFiles)||!a(e.modifiedFiles)||!Array.isArray(e.retainedMessages)||!e.retainedMessages.every(c)||!i(e.doomAutocompact))return;let t=e.doomAutocompact;if(!(t.version!==2||t.pass!==2&&t.pass!==3||typeof t.cycle!=`number`||typeof t.requestId!=`string`||typeof t.snapshotLeafId!=`string`||typeof t.tokensBefore!=`number`))return{readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],retainedMessages:[...e.retainedMessages],doomAutocompact:{version:2,cycle:t.cycle,pass:t.pass,requestId:t.requestId,snapshotLeafId:t.snapshotLeafId,tokensBefore:t.tokensBefore}}}function u(){return{version:2,cycle:1,pass:1,phase:`waiting`,checkpointQueue:[],exhaustedPasses:[],invalidAttempts:0,baselineTokens:0,baselinePending:!1,readFiles:[],modifiedFiles:[]}}function d(t={}){let n=0,r={};for(let i of[1,2,3]){let a=Math.max(t[i]??e.COMPACTION_THRESHOLDS[i].ratio,n);r[i]=a,n=a}return r}function f(n,r,i=0,a={}){let o=e.COMPACTION_THRESHOLDS[n],s=d(a)[n],c=Math.max(0,Math.min(i,r)),l=r-c,u=c+Math.min(Math.floor(l*s),o.capTokens),f=r-t.DEFAULT_COMPACTION_SETTINGS.reserveTokens;return f>c?Math.min(u,f):u}function p(e){return e.findLast(e=>e.type===`compaction`||e.type===`custom`&&e.customType===`doom-autocompact-checkpoint`||e.type===`custom_message`&&(e.customType===`doom-autocompact-checkpoint`||e.customType===`doom-autocompact-context`))}function m(e){let t=e.findLastIndex(e=>e.type===`compaction`||e.type===`custom_message`&&e.customType===`doom-autocompact-context`);return e.slice(t+1).some(e=>{if(e.type!==`message`||e.message.role!==`assistant`)return!1;let{stopReason:t,usage:n}=e.message;return t===`aborted`||t===`error`||!n?!1:(n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite)>0})}function h(e,n){let r=e.findIndex(e=>e.id===n);return r===-1?[]:e.slice(r+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>(0,t.sessionEntryToContextMessages)(e))}function g(e,t){let n=t.findLastIndex(e=>e.type===`compaction`),r=t.slice(n+1).findLast(e=>e.type===`custom_message`&&e.customType===`doom-autocompact-context`);if(!r||r.type!==`custom_message`)return{messages:e,retainedMessageCount:0};let i=l(r.details),a=y(r);if(!i||!a)return{messages:e,invalidMarker:!0,retainedMessageCount:0};let o=e.findLastIndex(e=>e.role===`custom`&&e.customType===`doom-autocompact-context`&&l(e.details)?.doomAutocompact.requestId===i.doomAutocompact.requestId);return o===-1?{messages:e,invalidMarker:!0,retainedMessageCount:0}:{messages:[{role:`compactionSummary`,summary:a,tokensBefore:i.doomAutocompact.tokensBefore,timestamp:e[o]?.timestamp??Date.now()},...i.retainedMessages,...e.slice(o+1)],marker:i.doomAutocompact,retainedMessageCount:i.retainedMessages.length}}function _(e){let t={read:new Set,written:new Set,edited:new Set};for(let n of e)if(n.role===`assistant`)for(let e of n.content){if(e.type!==`toolCall`)continue;let n=typeof e.arguments.path==`string`?e.arguments.path:void 0;n&&(e.name===`read`?t.read.add(n):e.name===`write`?t.written.add(n):e.name===`edit`&&t.edited.add(n))}return t}function v(e){if(!i(e)||e.version!==2||typeof e.cycle!=`number`||!o(e.pass)||e.phase!==`waiting`&&e.phase!==`checkpoint_pending`&&e.phase!==`checkpoint_ready`&&e.phase!==`compacting`)return;let t=e.baselineTokens??0;if(typeof t!=`number`||t<0)return;let n=e.baselinePending??!1;if(typeof n!=`boolean`)return;let r=e.checkpointQueue??[];if(!Array.isArray(r)||!r.every(o)||r.some((e,t)=>t>0&&e<=r[t-1]))return;let s=e.exhaustedPasses??[];if(!Array.isArray(s)||!s.every(o))return;let c=e.invalidAttempts??0;if(!(typeof c!=`number`||c<0)&&!(!a(e.readFiles)||!a(e.modifiedFiles))&&(e.requestId===void 0||typeof e.requestId==`string`)&&(e.compactionPass===void 0||e.compactionPass===2||e.compactionPass===3)&&!(`latestCheckpointEntryId`in e)&&(e.latestCheckpointSnapshotLeafId===void 0||typeof e.latestCheckpointSnapshotLeafId==`string`)&&(e.lastAttemptLeafId===void 0||typeof e.lastAttemptLeafId==`string`)&&(e.snapshotLeafId===void 0||typeof e.snapshotLeafId==`string`)&&!(e.snapshotTokens!==void 0&&(typeof e.snapshotTokens!=`number`||e.snapshotTokens<0))&&(e.pendingCheckpoint===void 0||typeof e.pendingCheckpoint==`string`))return{version:2,cycle:e.cycle,pass:e.pass,phase:e.phase,checkpointQueue:[...r],exhaustedPasses:[...s],invalidAttempts:c,baselineTokens:t,baselinePending:n,readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],...e.requestId?{requestId:e.requestId}:{},...e.compactionPass?{compactionPass:e.compactionPass}:{},...e.latestCheckpointSnapshotLeafId?{latestCheckpointSnapshotLeafId:e.latestCheckpointSnapshotLeafId}:{},...e.lastAttemptLeafId?{lastAttemptLeafId:e.lastAttemptLeafId}:{},...e.snapshotLeafId?{snapshotLeafId:e.snapshotLeafId}:{},...e.snapshotTokens===void 0?{}:{snapshotTokens:e.snapshotTokens},...e.pendingCheckpoint?{pendingCheckpoint:e.pendingCheckpoint}:{}}}function y(e){if(e)return e.type===`compaction`?e.summary.trim()||void 0:e.type===`custom`?i(e.data)&&typeof e.data.summary==`string`&&e.data.summary.trim()||void 0:e.type===`custom_message`?(typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
3
|
+
`)).trim()||void 0:s(e)}function b(e){let t=e.match(n),r=e.replace(n,``).trim();return t?{summary:r,shouldCompact:t[1]?.toLowerCase()===`true`}:{summary:r}}function x(t){return e.CHECKPOINT_HEADINGS.every(e=>t.includes(e))}function S(e,t,n,r){return`${e}:${t}:${n}:${r??`root`}`}function C(e,t,n){return{version:2,cycle:e,pass:t,requestId:n}}function w(e,t,n){let r=new Set([...e.modifiedFiles,...n?.modifiedFiles??[],...t?[...t.edited,...t.written]:[]]),i=new Set([...e.readFiles,...n?.readFiles??[],...t?[...t.read]:[]]);for(let e of r)i.delete(e);return{readFiles:[...i].sort(),modifiedFiles:[...r].sort()}}function T(e){if(!(!i(e)||!a(e.readFiles)||!a(e.modifiedFiles)))return{readFiles:e.readFiles,modifiedFiles:e.modifiedFiles}}function E(e,t){let n=[];t.readFiles.length>0&&n.push(`<read-files>\n${t.readFiles.join(`
|
|
4
|
+
`)}\n</read-files>`),t.modifiedFiles.length>0&&n.push(`<modified-files>\n${t.modifiedFiles.join(`
|
|
5
|
+
`)}\n</modified-files>`);let i=e.replace(r,``).trim();return n.length>0?`${i}\n\n${n.join(`
|
|
6
|
+
|
|
7
|
+
`)}`:i}exports.baselineUsageIsSettled=m,exports.checkpointRequestDetails=C,exports.checkpointSummaryFromEntry=y,exports.compactionRatios=d,exports.contextDetailsFromUnknown=l,exports.createInitialState=u,exports.createRequestId=S,exports.fileDetailsFromUnknown=T,exports.fileOperationsFromMessages=_,exports.isStructuredCheckpoint=x,exports.latestCheckpointArtifactEntry=p,exports.mergeFileDetails=w,exports.parseCheckpointDecision=b,exports.parseState=v,exports.projectContextMessages=g,exports.retainedMessagesAfterSnapshot=h,exports.thresholdTokens=f,exports.withCanonicalFileSections=E;
|
|
8
|
+
//# sourceMappingURL=policy.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.cjs","names":["COMPACTION_THRESHOLDS","DEFAULT_COMPACTION_SETTINGS","sessionEntryToContextMessages","CHECKPOINT_HEADINGS"],"sources":["../../../src/adapters/compaction/policy.ts"],"sourcesContent":["import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/index.ts';\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: SessionEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.doomAutocompact)) return undefined;\n const marker = value.doomAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n doomAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\nexport function latestCheckpointArtifactEntry(branchEntries: SessionEntry[]): SessionEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n (entry.type === 'custom_message' &&\n (entry.customType === CHECKPOINT_MESSAGE_TYPE || entry.customType === CONTEXT_MESSAGE_TYPE)),\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: SessionEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) =>\n entry.type === 'compaction' || (entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE),\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: SessionEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: SessionEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE);\n if (!markerEntry || markerEntry.type !== 'custom_message') {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerEntry.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.doomAutocompact.requestId === details.doomAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.doomAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.doomAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: SessionEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n if (entry.type === 'custom_message') {\n const content =\n typeof entry.content === 'string'\n ? entry.content\n : entry.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":"8FAyBA,MAAM,EAAyB,sDACzB,EAAuB,+EAE7B,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,CACtC,CAEA,SAAS,EAAc,EAAmC,CACxD,OAAO,MAAM,QAAQ,CAAK,GAAK,EAAM,MAAO,GAAS,OAAO,GAAS,QAAQ,CAC/E,CAEA,SAAS,EAAO,EAA0C,CACxD,OAAO,IAAU,GAAK,IAAU,GAAK,IAAU,CACjD,CAEA,SAAS,EAAc,EAAyC,CAC1D,KAAM,OAAS,WAAa,EAAM,QAAQ,OAAS,YAMvD,OALa,EAAM,QAAQ,QACxB,OAAQ,GAAU,EAAM,OAAS,MAAM,CAAC,CACxC,IAAK,GAAU,EAAM,IAAI,CAAC,CAC1B,KAAK;CAAI,CAAC,CACV,KACO,GAAK,IAAA,EACjB,CAEA,SAAS,EAAqB,EAA6C,CACzE,OAAO,EAAS,CAAK,GAAK,OAAO,EAAM,MAAS,QAClD,CAEA,SAAgB,EAA0B,EAAuD,CAG/F,GAFI,CAAC,EAAS,CAAK,GAAK,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,EAC1G,EAAQ,cAAc,OAAS,GACjC,EAAS,KAAK,qBAAqB,EAAQ,cAAc,KAAK;CAAI,EAAE,oBAAoB,EAE1F,IAAM,EAAa,EAAQ,QAAQ,EAAsB,EAAE,CAAC,CAAC,KAAK,EAClE,OAAO,EAAS,OAAS,EAAI,GAAG,EAAW,MAAM,EAAS,KAAK;;CAAM,IAAM,CAC7E"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { AutocompactPass, AutocompactRatioOverrides } from "../../types/index.cjs";
|
|
2
|
+
import "@earendil-works/pi-coding-agent";
|
|
3
|
+
//#region src/adapters/compaction/policy.d.ts
|
|
4
|
+
declare function thresholdTokens(pass: AutocompactPass, contextWindow: number, baselineTokens?: number, configured?: AutocompactRatioOverrides): number;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { thresholdTokens };
|
|
7
|
+
//# sourceMappingURL=policy.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.d.cts","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"mappings":";;;iBAqHgB,gBACd,MAAM,iBACN,uBACA,yBACA,aAAY"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { AutocompactPass, AutocompactRatioOverrides } from "../../types/index.mjs";
|
|
2
|
+
import "@earendil-works/pi-coding-agent";
|
|
3
|
+
//#region src/adapters/compaction/policy.d.ts
|
|
4
|
+
declare function thresholdTokens(pass: AutocompactPass, contextWindow: number, baselineTokens?: number, configured?: AutocompactRatioOverrides): number;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { thresholdTokens };
|
|
7
|
+
//# sourceMappingURL=policy.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.d.mts","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"mappings":";;;iBAqHgB,gBACd,MAAM,iBACN,uBACA,yBACA,aAAY"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{CHECKPOINT_HEADINGS as e,COMPACTION_THRESHOLDS as t}from"../../types/constants.mjs";import{DEFAULT_COMPACTION_SETTINGS as n,sessionEntryToContextMessages as r}from"@earendil-works/pi-coding-agent";const i=/<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i,a=/\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;function o(e){return typeof e==`object`&&!!e}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return e===1||e===2||e===3}function l(e){if(e.type===`message`&&e.message.role===`assistant`)return e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
`).trim()||void 0}function u(e){return o(e)&&typeof e.role==`string`}function d(e){if(!o(e)||!s(e.readFiles)||!s(e.modifiedFiles)||!Array.isArray(e.retainedMessages)||!e.retainedMessages.every(u)||!o(e.doomAutocompact))return;let t=e.doomAutocompact;if(!(t.version!==2||t.pass!==2&&t.pass!==3||typeof t.cycle!=`number`||typeof t.requestId!=`string`||typeof t.snapshotLeafId!=`string`||typeof t.tokensBefore!=`number`))return{readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],retainedMessages:[...e.retainedMessages],doomAutocompact:{version:2,cycle:t.cycle,pass:t.pass,requestId:t.requestId,snapshotLeafId:t.snapshotLeafId,tokensBefore:t.tokensBefore}}}function f(){return{version:2,cycle:1,pass:1,phase:`waiting`,checkpointQueue:[],exhaustedPasses:[],invalidAttempts:0,baselineTokens:0,baselinePending:!1,readFiles:[],modifiedFiles:[]}}function p(e={}){let n=0,r={};for(let i of[1,2,3]){let a=Math.max(e[i]??t[i].ratio,n);r[i]=a,n=a}return r}function m(e,r,i=0,a={}){let o=t[e],s=p(a)[e],c=Math.max(0,Math.min(i,r)),l=r-c,u=c+Math.min(Math.floor(l*s),o.capTokens),d=r-n.reserveTokens;return d>c?Math.min(u,d):u}function h(e){return e.findLast(e=>e.type===`compaction`||e.type===`custom`&&e.customType===`doom-autocompact-checkpoint`||e.type===`custom_message`&&(e.customType===`doom-autocompact-checkpoint`||e.customType===`doom-autocompact-context`))}function g(e){let t=e.findLastIndex(e=>e.type===`compaction`||e.type===`custom_message`&&e.customType===`doom-autocompact-context`);return e.slice(t+1).some(e=>{if(e.type!==`message`||e.message.role!==`assistant`)return!1;let{stopReason:t,usage:n}=e.message;return t===`aborted`||t===`error`||!n?!1:(n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite)>0})}function _(e,t){let n=e.findIndex(e=>e.id===t);return n===-1?[]:e.slice(n+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>r(e))}function v(e,t){let n=t.findLastIndex(e=>e.type===`compaction`),r=t.slice(n+1).findLast(e=>e.type===`custom_message`&&e.customType===`doom-autocompact-context`);if(!r||r.type!==`custom_message`)return{messages:e,retainedMessageCount:0};let i=d(r.details),a=x(r);if(!i||!a)return{messages:e,invalidMarker:!0,retainedMessageCount:0};let o=e.findLastIndex(e=>e.role===`custom`&&e.customType===`doom-autocompact-context`&&d(e.details)?.doomAutocompact.requestId===i.doomAutocompact.requestId);return o===-1?{messages:e,invalidMarker:!0,retainedMessageCount:0}:{messages:[{role:`compactionSummary`,summary:a,tokensBefore:i.doomAutocompact.tokensBefore,timestamp:e[o]?.timestamp??Date.now()},...i.retainedMessages,...e.slice(o+1)],marker:i.doomAutocompact,retainedMessageCount:i.retainedMessages.length}}function y(e){let t={read:new Set,written:new Set,edited:new Set};for(let n of e)if(n.role===`assistant`)for(let e of n.content){if(e.type!==`toolCall`)continue;let n=typeof e.arguments.path==`string`?e.arguments.path:void 0;n&&(e.name===`read`?t.read.add(n):e.name===`write`?t.written.add(n):e.name===`edit`&&t.edited.add(n))}return t}function b(e){if(!o(e)||e.version!==2||typeof e.cycle!=`number`||!c(e.pass)||e.phase!==`waiting`&&e.phase!==`checkpoint_pending`&&e.phase!==`checkpoint_ready`&&e.phase!==`compacting`)return;let t=e.baselineTokens??0;if(typeof t!=`number`||t<0)return;let n=e.baselinePending??!1;if(typeof n!=`boolean`)return;let r=e.checkpointQueue??[];if(!Array.isArray(r)||!r.every(c)||r.some((e,t)=>t>0&&e<=r[t-1]))return;let i=e.exhaustedPasses??[];if(!Array.isArray(i)||!i.every(c))return;let a=e.invalidAttempts??0;if(!(typeof a!=`number`||a<0)&&!(!s(e.readFiles)||!s(e.modifiedFiles))&&(e.requestId===void 0||typeof e.requestId==`string`)&&(e.compactionPass===void 0||e.compactionPass===2||e.compactionPass===3)&&!(`latestCheckpointEntryId`in e)&&(e.latestCheckpointSnapshotLeafId===void 0||typeof e.latestCheckpointSnapshotLeafId==`string`)&&(e.lastAttemptLeafId===void 0||typeof e.lastAttemptLeafId==`string`)&&(e.snapshotLeafId===void 0||typeof e.snapshotLeafId==`string`)&&!(e.snapshotTokens!==void 0&&(typeof e.snapshotTokens!=`number`||e.snapshotTokens<0))&&(e.pendingCheckpoint===void 0||typeof e.pendingCheckpoint==`string`))return{version:2,cycle:e.cycle,pass:e.pass,phase:e.phase,checkpointQueue:[...r],exhaustedPasses:[...i],invalidAttempts:a,baselineTokens:t,baselinePending:n,readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],...e.requestId?{requestId:e.requestId}:{},...e.compactionPass?{compactionPass:e.compactionPass}:{},...e.latestCheckpointSnapshotLeafId?{latestCheckpointSnapshotLeafId:e.latestCheckpointSnapshotLeafId}:{},...e.lastAttemptLeafId?{lastAttemptLeafId:e.lastAttemptLeafId}:{},...e.snapshotLeafId?{snapshotLeafId:e.snapshotLeafId}:{},...e.snapshotTokens===void 0?{}:{snapshotTokens:e.snapshotTokens},...e.pendingCheckpoint?{pendingCheckpoint:e.pendingCheckpoint}:{}}}function x(e){if(e)return e.type===`compaction`?e.summary.trim()||void 0:e.type===`custom`?o(e.data)&&typeof e.data.summary==`string`&&e.data.summary.trim()||void 0:e.type===`custom_message`?(typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
3
|
+
`)).trim()||void 0:l(e)}function S(e){let t=e.match(i),n=e.replace(i,``).trim();return t?{summary:n,shouldCompact:t[1]?.toLowerCase()===`true`}:{summary:n}}function C(t){return e.every(e=>t.includes(e))}function w(e,t,n,r){return`${e}:${t}:${n}:${r??`root`}`}function T(e,t,n){return{version:2,cycle:e,pass:t,requestId:n}}function E(e,t,n){let r=new Set([...e.modifiedFiles,...n?.modifiedFiles??[],...t?[...t.edited,...t.written]:[]]),i=new Set([...e.readFiles,...n?.readFiles??[],...t?[...t.read]:[]]);for(let e of r)i.delete(e);return{readFiles:[...i].sort(),modifiedFiles:[...r].sort()}}function D(e){if(!(!o(e)||!s(e.readFiles)||!s(e.modifiedFiles)))return{readFiles:e.readFiles,modifiedFiles:e.modifiedFiles}}function O(e,t){let n=[];t.readFiles.length>0&&n.push(`<read-files>\n${t.readFiles.join(`
|
|
4
|
+
`)}\n</read-files>`),t.modifiedFiles.length>0&&n.push(`<modified-files>\n${t.modifiedFiles.join(`
|
|
5
|
+
`)}\n</modified-files>`);let r=e.replace(a,``).trim();return n.length>0?`${r}\n\n${n.join(`
|
|
6
|
+
|
|
7
|
+
`)}`:r}export{g as baselineUsageIsSettled,T as checkpointRequestDetails,x as checkpointSummaryFromEntry,p as compactionRatios,d as contextDetailsFromUnknown,f as createInitialState,w as createRequestId,D as fileDetailsFromUnknown,y as fileOperationsFromMessages,C as isStructuredCheckpoint,h as latestCheckpointArtifactEntry,E as mergeFileDetails,S as parseCheckpointDecision,b as parseState,v as projectContextMessages,_ as retainedMessagesAfterSnapshot,m as thresholdTokens,O as withCanonicalFileSections};
|
|
8
|
+
//# sourceMappingURL=policy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.mjs","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"sourcesContent":["import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/index.ts';\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: SessionEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.doomAutocompact)) return undefined;\n const marker = value.doomAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n doomAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\nexport function latestCheckpointArtifactEntry(branchEntries: SessionEntry[]): SessionEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n (entry.type === 'custom_message' &&\n (entry.customType === CHECKPOINT_MESSAGE_TYPE || entry.customType === CONTEXT_MESSAGE_TYPE)),\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: SessionEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) =>\n entry.type === 'compaction' || (entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE),\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: SessionEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: SessionEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE);\n if (!markerEntry || markerEntry.type !== 'custom_message') {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerEntry.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.doomAutocompact.requestId === details.doomAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.doomAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.doomAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: SessionEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n if (entry.type === 'custom_message') {\n const content =\n typeof entry.content === 'string'\n ? entry.content\n : entry.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":"4MAyBA,MAAM,EAAyB,sDACzB,EAAuB,+EAE7B,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,CACtC,CAEA,SAAS,EAAc,EAAmC,CACxD,OAAO,MAAM,QAAQ,CAAK,GAAK,EAAM,MAAO,GAAS,OAAO,GAAS,QAAQ,CAC/E,CAEA,SAAS,EAAO,EAA0C,CACxD,OAAO,IAAU,GAAK,IAAU,GAAK,IAAU,CACjD,CAEA,SAAS,EAAc,EAAyC,CAC1D,KAAM,OAAS,WAAa,EAAM,QAAQ,OAAS,YAMvD,OALa,EAAM,QAAQ,QACxB,OAAQ,GAAU,EAAM,OAAS,MAAM,CAAC,CACxC,IAAK,GAAU,EAAM,IAAI,CAAC,CAC1B,KAAK;CAAI,CAAC,CACV,KACO,GAAK,IAAA,EACjB,CAEA,SAAS,EAAqB,EAA6C,CACzE,OAAO,EAAS,CAAK,GAAK,OAAO,EAAM,MAAS,QAClD,CAEA,SAAgB,EAA0B,EAAuD,CAG/F,GAFI,CAAC,EAAS,CAAK,GAAK,CAAC,EAAc,EAAM,SAAS,GAAK,CAAC,EAAc,EAAM,aAAa,GACzF,CAAC,MAAM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sB,EAAE,CAAC,CAAC,KAAK,EAClE,OAAO,EAAS,OAAS,EAAI,GAAG,EAAW,MAAM,EAAS,KAAK;;CAAM,IAAM,CAC7E"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const e=require("../../types/constants.cjs"),t=require("../compaction/policy.cjs"),n=require("../../services/summarizationModel.cjs"),r=require("../telemetry/logSinkTelemetry.cjs");let i=require("@agimon-ai/doompi-config"),a=require("@agimon-ai/doompi-extension-contracts/cordis-host"),o=require("@agimon-ai/doompi-extension-contracts/context-contributions"),s=require("@agimon-ai/doompi-extension-contracts/ui-hub"),c=require("@earendil-works/pi-coding-agent");const l=`@root`,u=`doom-autocompact`,d={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function f(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function p(e){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r?.type!==`custom`||r.customType!==`doom-autocompact-state`)continue;let i=t.parseState(r.data);if(i)return i}}function m(e){for(let t of e.sessionManager.getBranch().toReversed())if((t.type!==`custom`||t.customType!==`doom-autocompact-state`)&&t.type!==`label`)return t.id;return l}function h(e){return e instanceof Error?e.message:String(e)}function g(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}const _=Object.freeze({entries:Object.freeze([]),errors:Object.freeze([])});function v(e){if(!e)return _;try{return e.snapshot()}catch(e){return{entries:[],errors:[{source:o.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,id:`service-snapshot`,label:`Context contributions`,order:0,message:h(e)}]}}}function y(e){let t=e.entries.map(e=>`### ${e.label}\n${e.text}`);return t.push(...e.errors.map(e=>`### ${e.label}\n(unavailable: ${e.message})`)),t.length>0?t.join(`
|
|
2
|
+
|
|
3
|
+
`):`(no registered context contributions)`}function b(e,t){let n=g(e);return{...n?{planPath:n.path}:{},contributions:t.entries,contributionErrors:t.errors}}function x(e){return`<compaction-runtime-state>
|
|
4
|
+
Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
|
|
5
|
+
<active-plan>
|
|
6
|
+
${e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`}
|
|
7
|
+
</active-plan>
|
|
8
|
+
<context-contributions>
|
|
9
|
+
${y({entries:e.contributions,errors:e.contributionErrors})}
|
|
10
|
+
</context-contributions>
|
|
11
|
+
</compaction-runtime-state>`}function S(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.contribution_count":e.contributions.length,"autocompact.runtime.contribution_error_count":e.contributionErrors.length}}function C(e){let t=e.plan?`Source: ${e.plan.path}\n\n${e.plan.content}`:`(no active plan document)`,n=[e.readFiles.length>0?`Read files: ${e.readFiles.join(`, `)}`:void 0,e.modifiedFiles.length>0?`Modified files: ${e.modifiedFiles.join(`, `)}`:void 0].filter(e=>!!e);return`<compaction-steering priority="user,plan,context-contributions,important-context,recent-messages">
|
|
12
|
+
<user-prompt source="conversation">
|
|
13
|
+
Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
|
|
14
|
+
</user-prompt>
|
|
15
|
+
<active-plan>
|
|
16
|
+
${t}
|
|
17
|
+
</active-plan>
|
|
18
|
+
<context-contributions>
|
|
19
|
+
${y(e.contextContributions)}
|
|
20
|
+
</context-contributions>
|
|
21
|
+
<important-context>
|
|
22
|
+
${n.length>0?n.join(`
|
|
23
|
+
`):`(none recorded outside the conversation)`}
|
|
24
|
+
</important-context>
|
|
25
|
+
</compaction-steering>`}function w(e,t){let n=e===2?`Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.
|
|
26
|
+
|
|
27
|
+
`:``;return`Create Doom autocompact checkpoint pass ${e}.
|
|
28
|
+
|
|
29
|
+
${C(t)}
|
|
30
|
+
|
|
31
|
+
Apply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
|
|
32
|
+
|
|
33
|
+
${n}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.
|
|
34
|
+
|
|
35
|
+
## Goal
|
|
36
|
+
## Constraints & Preferences
|
|
37
|
+
## Progress
|
|
38
|
+
### Done
|
|
39
|
+
### In Progress
|
|
40
|
+
### Blocked
|
|
41
|
+
## Key Decisions
|
|
42
|
+
## Next Steps
|
|
43
|
+
## Critical Context`}function T(e,n,r){let i=t.projectContextMessages((0,c.buildSessionContext)(n).messages,n).messages;if(e===1||!r)return i;let a=n.findIndex(e=>e.id===r);return a===-1?i:n.slice(a+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>(0,c.sessionEntryToContextMessages)(e))}const E={enabled:!0,ratios:{}};function D(e,t){let n;try{n=(0,i.loadDoomConfig)((0,i.getHarnessState)().root??e).modes}catch(e){return process.emitWarning(`Doom autocompact configuration could not be loaded; using the active session model instead.`),t?.(e),E}let r=n?.autocompact,a=(r&&(r.model!==void 0||r.thinking!==void 0)?{...r.model?{model:r.model}:{},...r.thinking?{thinking:r.thinking}:{}}:void 0)??n?.planning?.subagents,o=r?.thresholds;return{enabled:r?.enabled??!0,...a?{agent:a}:{},ratios:{...o?.pass1===void 0?{}:{1:o.pass1},...o?.pass2===void 0?{}:{2:o.pass2},...o?.pass3===void 0?{}:{3:o.pass3}}}}function O(e){let t=D(e.cwd).agent,r=t?.model?n.parseModelReference(t.model):void 0,i=r?e.modelRegistry.find(r.provider,r.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?r?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function k(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);let i=e.context.modelRegistry.getProvider(n.model.provider);if(!i)throw Error(`No provider is registered for "${n.model.provider}" in this session.`);return(0,c.generateSummary)(e.messages,n.model,c.DEFAULT_COMPACTION_SETTINGS.reserveTokens,r.apiKey,r.headers,e.signal,e.instructions,e.previousCheckpoint,n.thinkingLevel,(e,t,n)=>i.streamSimple(e,t,n),r.env)}function A(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function j(n,i,a={}){let h=a.resolveModel??O,_=a.generateCheckpoint??(e=>k(e,h)),y=a.telemetry??r.createAutocompactTelemetry(),C=a.doomIntegrations??!0,E=new Set,j=new Set,M=new Set,N=!0,P=0,F=t.createInitialState(),I,L,R,z,B=!1;n.effect(()=>async()=>{N=!1,P+=1,L?.abort(Error(`Autocompact runtime is shutting down.`)),L=void 0,await Promise.allSettled(M),R=void 0,z=void 0,I=void 0,E.clear(),j.clear(),F=t.createInitialState(),B=!1,await y.shutdown()},`${u}/runtime`),n.inject([o.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE],e=>{let t=(0,o.requireDoomContextContributions)(e);return z=t,()=>{z===t&&(z=void 0)}}),C&&n.inject([s.DOOM_UI_HUB_SERVICE],e=>{let t=(0,s.requireDoomUiHub)(e).registerFooter({source:u,id:`autocompact`,order:20});return R=t,()=>{t.dispose(),R===t&&(R=void 0)}});let V=e=>{if(!N)return;let t=F.phase===d.checkpointPending?`summarizing`:F.phase===d.checkpointReady?`applying`:void 0;R?.update(t?{fullText:`Compacting p${F.pass}`,compactText:`C${F.pass}`}:void 0);let n=e??I;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${F.pass} (${t})…`:void 0)},H=()=>{N&&(i.appendEntry(e.STATE_CUSTOM_TYPE,{...F}),V())},U=()=>{delete F.requestId,delete F.snapshotLeafId,delete F.snapshotTokens,delete F.pendingCheckpoint,delete F.compactionPass},W=e=>{F.checkpointQueue=F.checkpointQueue.filter(t=>t!==e)},G=e=>{N&&(F=p(e.sessionManager.getBranch())??t.createInitialState(),!(F.phase===d.checkpointReady&&F.requestId&&F.snapshotLeafId&&F.pendingCheckpoint||F.phase===d.waiting)&&(L?.abort(),L=void 0,F.phase=d.waiting,U(),H()))},ee=t=>{N&&i.sendMessage({customType:e.RESUME_MESSAGE_TYPE,content:`${t} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:F.cycle,pass:F.pass}},{triggerTurn:!0,deliverAs:`steer`})},K=(e,t)=>{let n=F.invalidAttempts+1,r=n>=3;return F.phase=d.waiting,t&&(F.lastAttemptLeafId=t),r?(W(e),F.exhaustedPasses=[...F.exhaustedPasses,e],F.invalidAttempts=0):F.invalidAttempts=n,U(),H(),{attempts:n,exhausted:r}},te=(e,t)=>{if(!N||e!==F.requestId||F.phase!==d.checkpointPending)return;let n=F.pass,{attempts:r,exhausted:i}=K(n,F.snapshotLeafId),a=t instanceof Error?t.message:String(t);A(I,i?`Doom autocompact summarization pass ${n} failed ${r} times and was abandoned: ${a}`:`Doom autocompact summarization pass ${n} failed: ${a}`,`error`)},ne=(e,t)=>{!N||B||(B=!0,y.recordWarning(r.AUTOCOMPACT_EVENT.configurationLoadFailed,t,f(e,{"autocompact.cycle":F.cycle,"autocompact.pass":F.pass})))},q=(e,t,n)=>{if(N)for(let i of t.errors)A(e,`Doom autocompact context contribution degraded (${i.source}/${i.id}): ${i.message}`,`warning`),y.recordWarning(r.AUTOCOMPACT_EVENT.contextContributionDegraded,Error(i.message),{...n,"autocompact.context_contribution.source":i.source,"autocompact.context_contribution.id":i.id,"autocompact.context_contribution.order":i.order})},J=(t,n,r)=>{if(!N)return{contributions:[],contributionErrors:[]};let a=v(z);q(t,a,r);let o=b(n,a);return i.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:x(o),display:!1,details:{version:2,...o}}),o},re=(n,a)=>{if(!N||!F.requestId||!F.snapshotLeafId||!F.pendingCheckpoint)return!1;let o=a.sessionManager.getBranch(),s=t.projectContextMessages((0,c.buildSessionContext)(o).messages,o).messages,l=t.mergeFileDetails(F,t.fileOperationsFromMessages(s)),u=F.requestId,p=F.cycle,h=t.withCanonicalFileSections(F.pendingCheckpoint,l),g={...l,doomAutocompact:{version:2,cycle:p,pass:n,requestId:u,snapshotLeafId:F.snapshotLeafId,tokensBefore:F.snapshotTokens??a.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,F.snapshotLeafId)},_=a.isIdle();i.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:h,display:!1,details:g});let v=m(a),b=f(a,{"autocompact.request.id":u,"autocompact.cycle":p,"autocompact.pass":n}),x=J(a,o,b);return _&&i.setLabel(v,`autocompact:c${p}:p${n}`),F.readFiles=l.readFiles,F.modifiedFiles=l.modifiedFiles,delete F.latestCheckpointSnapshotLeafId,F.phase=d.waiting,F.checkpointQueue=[],F.exhaustedPasses=[],F.invalidAttempts=0,F.baselinePending=!0,delete F.lastAttemptLeafId,U(),F.cycle+=1,F.pass=1,H(),y.recordEvent(r.AUTOCOMPACT_EVENT.contextCommitted,f(a,{"autocompact.request.id":u,"autocompact.cycle":p,"autocompact.pass":n,"autocompact.snapshot_leaf_id":g.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":g.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":g.retainedMessages.length,"autocompact.apply_mode":_?`idle`:`turn_end`,...S(x)})),_&&ee(`Asynchronous compaction completed.`),!0},ie=(e,n,i)=>{if(!N)return;let a=P,o=n.sessionManager.getBranch(),s=m(n),c=t.createRequestId(n.sessionManager.getSessionId(),F.cycle,e,s),l=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(o)):void 0,u=T(e,o,F.latestCheckpointSnapshotLeafId),p=v(z),h=f(n,{"autocompact.request.id":c,"autocompact.cycle":F.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":s,"autocompact.tokens_before":i,"autocompact.message_count.before":u.length});q(n,p,h),F.phase=d.checkpointPending,F.pass=e,F.requestId=c,F.snapshotLeafId=s,F.snapshotTokens=i,delete F.pendingCheckpoint,delete F.compactionPass,delete F.lastAttemptLeafId,H(),L?.abort(),L=new AbortController;let b=L.signal,x=y.runInSpan(`doom_autocompact.checkpoint`,h,async()=>{await y.recordEvent(r.AUTOCOMPACT_EVENT.checkpointStarted,h);try{let t=await _({messages:u,instructions:w(e,{plan:g(o),contextContributions:p,readFiles:F.readFiles,modifiedFiles:F.modifiedFiles}),...l?{previousCheckpoint:l}:{},context:n,signal:b});if(!N||a!==P)throw b.reason??Error(`Autocompact checkpoint became stale.`);if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await y.recordEvent(r.AUTOCOMPACT_EVENT.checkpointCompleted,{...h,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw N&&a===P&&await y.recordError(r.AUTOCOMPACT_EVENT.checkpointFailed,e,h),e}}).then(e=>{!N||a!==P||c!==F.requestId||F.phase!==d.checkpointPending||(F.phase=d.checkpointReady,F.pendingCheckpoint=e.trim(),H(),I&&Q(I))}).catch(e=>{N&&a===P&&te(c,e)});M.add(x),x.finally(()=>M.delete(x))},Y=e=>{if(!N||F.phase!==d.waiting||e.hasPendingMessages())return!1;let n=D(e.cwd,t=>ne(e,t));if(!n.enabled)return!1;let r=e.getContextUsage();if(!r||r.tokens===null)return!1;if(F.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(F.baselineTokens=r.tokens,F.baselinePending=!1,H(),!1):!1;let i=m(e);if(F.lastAttemptLeafId===i)return!1;for(let e of[1,2,3])e<F.pass||F.checkpointQueue.includes(e)||F.exhaustedPasses.includes(e)||r.tokens>=t.thresholdTokens(e,r.contextWindow,F.baselineTokens,n.ratios)&&F.checkpointQueue.push(e);let a=F.checkpointQueue[0];return a?(ie(a,e,r.tokens),!0):!1},X=(n,r)=>{if(!N)return;let a=F.snapshotLeafId;i.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(F.cycle,n,F.requestId??`completed`),summary:r}),a&&(F.latestCheckpointSnapshotLeafId=a)},Z=e=>{if(!N||F.phase!==d.checkpointReady||!F.requestId||!F.pendingCheckpoint)return`none`;let n=F.pass,i=t.parseCheckpointDecision(F.pendingCheckpoint);if(!t.isStructuredCheckpoint(i.summary)){let t=F.snapshotLeafId,i=F.requestId,{attempts:a,exhausted:o}=K(n,t),s=Error(`Summarization pass ${n} returned an incomplete checkpoint.`);return A(e,o?`Doom autocompact summarization pass ${n} returned an incomplete checkpoint ${a} times and was abandoned.`:`Doom autocompact summarization pass ${n} returned an incomplete checkpoint.`,`error`),y.recordError(r.AUTOCOMPACT_EVENT.checkpointInvalid,s,f(e,{"autocompact.cycle":F.cycle,"autocompact.pass":n,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...i?{"autocompact.request.id":i}:{}})),`invalid`}return F.invalidAttempts=0,n===1?(X(1,i.summary),W(1),F.phase=d.waiting,F.pass=2,U(),H(),`pass1`):n===2&&i.shouldCompact!==!0?(X(2,i.summary),W(2),F.phase=d.waiting,F.pass=3,U(),H(),`deferred`):(F.pendingCheckpoint=i.summary,re(n,e)?`committed`:`invalid`)};function Q(e){N&&(I=e,e.isIdle()&&Z(e)!==`committed`&&Y(e))}i.on(`context`,(e,n)=>{if(!N)return;let i=t.projectContextMessages(e.messages,n.sessionManager.getBranch());if(i.invalidMarker){let e=n.sessionManager.getLeafId()??l;j.has(e)||(j.add(e),y.recordError(r.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),f(n,{"autocompact.leaf_id":e})));return}if(i.marker)return E.has(i.marker.requestId)||(E.add(i.marker.requestId),y.recordEvent(r.AUTOCOMPACT_EVENT.contextApplied,f(n,{"autocompact.request.id":i.marker.requestId,"autocompact.cycle":i.marker.cycle,"autocompact.pass":i.marker.pass,"autocompact.snapshot_leaf_id":i.marker.snapshotLeafId,"autocompact.tokens_before":i.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":i.messages.length,"autocompact.message_count.retained":i.retainedMessageCount}))),{messages:i.messages}});let $=e=>{N&&(P+=1,L?.abort(Error(`Autocompact session generation was replaced.`)),L=void 0,E.clear(),j.clear(),I=e,G(e),Q(e))};i.on(`session_start`,(e,t)=>$(t)),i.on(`session_tree`,(e,t)=>$(t)),i.on(`turn_end`,(e,t)=>{if(N){if(I=t,t.isIdle()){Q(t);return}F.phase===d.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Z(t)!==`none`||Y(t)}}),i.on(`agent_settled`,(e,t)=>{N&&Q(t)}),i.on(`session_before_compact`,e=>{if(!(!N||e.reason!==`threshold`))return F.phase===d.checkpointPending||F.phase===d.checkpointReady||F.baselinePending?{cancel:!0}:void 0}),i.on(`session_compact`,(e,n)=>{if(!N)return;P+=1,L?.abort(),L=void 0;let a=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(F,void 0,a);F.readFiles=o.readFiles,F.modifiedFiles=o.modifiedFiles,delete F.latestCheckpointSnapshotLeafId,F.baselinePending=!0,F.phase=d.waiting,U(),F.checkpointQueue=[],F.exhaustedPasses=[],F.invalidAttempts=0,delete F.lastAttemptLeafId,i.setLabel(e.compactionEntry.id,`autocompact:c${F.cycle}:external`);let s=F.cycle,c=f(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),l=J(n,n.sessionManager.getBranch(),c);F.cycle+=1,F.pass=1,H(),y.recordEvent(r.AUTOCOMPACT_EVENT.nativeCompactionCompleted,f(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...S(l)}))})}async function M(e){let t=await(0,a.connectDoomCordisHost)(e,`@agimon-ai/doompi-autocompact`),n=t.root.plugin(N,{pi:e});try{await n}catch(e){try{await n.dispose()}finally{await t.dispose()}throw e}let r;e.on(`session_shutdown`,()=>r??=(async()=>{try{await n.dispose()}finally{await t.dispose()}})())}function N(e,t){j(e,t.pi)}exports.autocompactExtension=M,exports.default=M,exports.autocompactRuntimeConfig=D,exports.generateCheckpointWithPi=k,exports.installAutocompactRuntime=j,exports.resolveDoomSummarizationModel=O;
|
|
44
|
+
//# sourceMappingURL=extension.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.cjs","names":["parseState","DOOM_CONTEXT_CONTRIBUTIONS_SERVICE","projectContextMessages","buildSessionContext","sessionEntryToContextMessages","loadDoomConfig","getHarnessState","parseModelReference","generateSummary","DEFAULT_COMPACTION_SETTINGS","createAutocompactTelemetry","createInitialState","requireDoomContextContributions","DOOM_UI_HUB_SERVICE","requireDoomUiHub","STATE_CUSTOM_TYPE","RESUME_MESSAGE_TYPE","AUTOCOMPACT_EVENT","RUNTIME_STATE_MESSAGE_TYPE","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","retainedMessagesAfterSnapshot","CONTEXT_MESSAGE_TYPE","createRequestId","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","baselineUsageIsSettled","thresholdTokens","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","parseCheckpointDecision","isStructuredCheckpoint","fileDetailsFromUnknown","connectDoomCordisHost"],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport {\n DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,\n requireDoomContextContributions,\n type DoomContextContributionEntry,\n type DoomContextContributionError,\n type DoomContextContributionsService,\n type DoomContextContributionsSnapshot,\n} from '@agimon-ai/doompi-extension-contracts/context-contributions';\nimport type { DoomFooterContributionHandle } from '@agimon-ai/doompi-extension-contracts/footer';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n generateSummary,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n thresholdTokens,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type {\n AutocompactContextDetails,\n AutocompactPass,\n AutocompactRatioOverrides,\n AutocompactState,\n} from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-autocompact';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: DoomContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly DoomContextContributionEntry[];\n contributionErrors: readonly DoomContextContributionError[];\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: DoomContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nfunction readContextContributionsSnapshot(\n service: DoomContextContributionsService | undefined,\n): DoomContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: DoomContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n contextContributions: DoomContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.contribution_count': snapshot.contributions.length,\n 'autocompact.runtime.contribution_error_count': snapshot.contributionErrors.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to Pi; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {} };\n\n/**\n * What the Doom config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n */\nexport function autocompactRuntimeConfig(\n cwd: string,\n onLoadFailure?: (error: unknown) => void,\n): AutocompactRuntimeConfig {\n let modes: ReturnType<typeof loadDoomConfig>['modes'];\n try {\n modes = loadDoomConfig(getHarnessState().root ?? cwd).modes;\n } catch (error) {\n process.emitWarning('Doom autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n };\n}\n\n/** Explicit Doom model selection honors the configured summarization model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = autocompactRuntimeConfig(ctx.cwd).agent;\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\n/**\n * Summarization borrows the session's own provider instead of re-resolving one.\n *\n * The selected model can come from a Pi provider extension, and that extension's\n * `streamSimple` closure lives only in this process: it is never in Pi's global api\n * registry, so any other thread or process sees `No API provider registered for api`.\n * Passing the composed provider in as `generateSummary`'s stream function keeps\n * summarization on exactly the path the agent's own requests take.\n */\nexport async function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n const provider = input.context.modelRegistry.getProvider(selection.model.provider);\n if (!provider) {\n throw new Error(`No provider is registered for \"${selection.model.provider}\" in this session.`);\n }\n return generateSummary(\n input.messages,\n selection.model,\n DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n auth.apiKey,\n // A null header value suppresses a provider default, which the narrower\n // `generateSummary` signature does not model but every provider honors.\n auth.headers as Record<string, string> | undefined,\n input.signal,\n input.instructions,\n input.previousCheckpoint,\n selection.thinkingLevel,\n (model, context, options) => provider.streamSimple(model, context, options),\n auth.env,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: DoomFooterContributionHandle | undefined;\n let contextContributionsService: DoomContextContributionsService | undefined;\n let configLoadFailureReported = false;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution = undefined;\n contextContributionsService = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n configLoadFailureReported = false;\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n cordis.inject([DOOM_CONTEXT_CONTRIBUTIONS_SERVICE], (contextContributionsContext) => {\n const service = requireDoomContextContributions(contextContributionsContext);\n contextContributionsService = service;\n return () => {\n if (contextContributionsService === service) contextContributionsService = undefined;\n };\n });\n\n if (doomIntegrations) {\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = requireDoomUiHub(uiContext).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footerContribution = contribution;\n return () => {\n contribution.dispose();\n if (footerContribution === contribution) footerContribution = undefined;\n };\n });\n }\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n /**\n * Both failure paths share one attempt budget: a summarizer that keeps failing would\n * otherwise cost a full summarization call every turn for the rest of the session, so the\n * pass is abandoned once the budget is spent and becomes eligible again on the next cycle.\n */\n const registerFailedAttempt = (\n pass: AutocompactPass,\n failedLeafId: string | undefined,\n ): { attempts: number; exhausted: boolean } => {\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n return { attempts, exhausted };\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const pass = state.pass;\n const { attempts, exhausted } = registerFailedAttempt(pass, state.snapshotLeafId);\n const reason = error instanceof Error ? error.message : String(error);\n notify(\n currentContext,\n exhausted\n ? `Doom autocompact summarization pass ${pass} failed ${attempts} times and was abandoned: ${reason}`\n : `Doom autocompact summarization pass ${pass} failed: ${reason}`,\n 'error',\n );\n };\n\n // A configuration that cannot be read degrades every later pass silently, and the process\n // warning never reaches the log sink. Report it once per session instead of once per turn.\n const reportConfigLoadFailure = (ctx: ExtensionContext, error: unknown): void => {\n if (!active || configLoadFailureReported) return;\n configLoadFailureReported = true;\n void telemetry.recordWarning(\n AUTOCOMPACT_EVENT.configurationLoadFailed,\n error,\n telemetryAttributes(ctx, { 'autocompact.cycle': state.cycle, 'autocompact.pass': state.pass }),\n );\n };\n\n const reportContributionFailures = (\n ctx: ExtensionContext,\n snapshot: DoomContextContributionsSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n for (const error of snapshot.errors) {\n notify(\n ctx,\n `Doom autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n 'warning',\n );\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes,\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { contributions: [], contributionErrors: [] };\n }\n const contextContributions = readContextContributionsSnapshot(contextContributionsService);\n reportContributionFailures(ctx, contextContributions, attributes);\n const snapshot = runtimeStateSnapshot(branch, contextContributions);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 2, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const contextContributions = readContextContributionsSnapshot(contextContributionsService);\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportContributionFailures(ctx, contextContributions, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n contextContributions,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n // Read per evaluation rather than once at install, so turning the ladder off\n // or moving a threshold in settings takes effect on the next turn instead of\n // the next session.\n const configured = autocompactRuntimeConfig(ctx.cwd, (error) => reportConfigLoadFailure(ctx, error));\n if (!configured.enabled) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n for (const pass of [1, 2, 3] as const) {\n if (pass < state.pass || state.checkpointQueue.includes(pass) || state.exhaustedPasses.includes(pass)) continue;\n if (usage.tokens >= thresholdTokens(pass, usage.contextWindow, state.baselineTokens, configured.ratios)) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const { attempts, exhausted } = registerFailedAttempt(pass, failedLeafId);\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin(autocompactPlugin, { pi });\n try {\n await fiber;\n } catch (error) {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\ninterface AutocompactPluginConfig {\n readonly pi: ExtensionAPI;\n}\n\nfunction autocompactPlugin(cordis: Context, config: AutocompactPluginConfig): void {\n installAutocompactRuntime(cordis, config.pi);\n}\n\nexport default autocompactExtension;\n"],"mappings":"8cA6DA,MAAM,EAAoB,QAGpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,YACd,EAqCA,SAAS,EACP,EACA,EAAyC,CAAC,EACd,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,aAAa,EACrD,GAAG,CACL,CACF,CAEA,SAAS,EAAqB,EAAsD,CAClF,IAAK,IAAI,EAAQ,EAAO,OAAS,EAAG,GAAS,EAAG,IAAY,CAC1D,IAAM,EAAQ,EAAO,GACrB,GAAI,GAAO,OAAS,UAAY,EAAM,aAA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,CAC7C"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { SummarizationModel } from "../../services/summarizationModel.cjs";
|
|
2
2
|
import { AutocompactTelemetry } from "../telemetry/logSinkTelemetry.cjs";
|
|
3
|
+
import "../../types/index.cjs";
|
|
4
|
+
import "@agimon-ai/doompi-config";
|
|
3
5
|
import { Context } from "@deepseek-ai/cordis";
|
|
4
6
|
import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
|
|
5
7
|
//#region src/adapters/pi/extension.d.ts
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.cts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;KA0EK,qBAAqB,kBAAkB;UAoBlC;EACR,UAAU;EACV;EACA;EACA,SAAS;EACT,QAAQ;;UAGO;EACf,sBAAsB,OAAO,8BAA8B;EAC3D,gBAAgB,SAAS,qBAAqB;EAC9C,YAAY;EACZ;;iBA8Rc,0BACd,QAAQ,SACR,IAAI,cACJ,eAAc;;iBAgmBM,qBAAqB,IAAI,eAAe"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { SummarizationModel } from "../../services/summarizationModel.mjs";
|
|
2
2
|
import { AutocompactTelemetry } from "../telemetry/logSinkTelemetry.mjs";
|
|
3
|
+
import "../../types/index.mjs";
|
|
4
|
+
import "@agimon-ai/doompi-config";
|
|
3
5
|
import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
|
|
4
6
|
import { Context } from "@deepseek-ai/cordis";
|
|
5
7
|
//#region src/adapters/pi/extension.d.ts
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.mts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;KA0EK,qBAAqB,kBAAkB;UAoBlC;EACR,UAAU;EACV;EACA;EACA,SAAS;EACT,QAAQ;;UAGO;EACf,sBAAsB,OAAO,8BAA8B;EAC3D,gBAAgB,SAAS,qBAAqB;EAC9C,YAAY;EACZ;;iBA8Rc,0BACd,QAAQ,SACR,IAAI,cACJ,eAAc;;iBAgmBM,qBAAqB,IAAI,eAAe"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{CHECKPOINT_MESSAGE_TYPE as e,CONTEXT_MESSAGE_TYPE as t,RESUME_MESSAGE_TYPE as n,RUNTIME_STATE_MESSAGE_TYPE as r,STATE_CUSTOM_TYPE as i}from"../../types/constants.mjs";import{baselineUsageIsSettled as a,checkpointRequestDetails as o,checkpointSummaryFromEntry as s,createInitialState as c,createRequestId as l,fileDetailsFromUnknown as u,fileOperationsFromMessages as d,isStructuredCheckpoint as f,latestCheckpointArtifactEntry as p,mergeFileDetails as m,parseCheckpointDecision as h,parseState as g,projectContextMessages as _,retainedMessagesAfterSnapshot as ee,thresholdTokens as te,withCanonicalFileSections as ne}from"../compaction/policy.mjs";import{parseModelReference as v}from"../../services/summarizationModel.mjs";import{AUTOCOMPACT_EVENT as y,createAutocompactTelemetry as re}from"../telemetry/logSinkTelemetry.mjs";import{getHarnessState as b,loadDoomConfig as ie}from"@agimon-ai/doompi-config";import{connectDoomCordisHost as x}from"@agimon-ai/doompi-extension-contracts/cordis-host";import{DOOM_CONTEXT_CONTRIBUTIONS_SERVICE as S,requireDoomContextContributions as ae}from"@agimon-ai/doompi-extension-contracts/context-contributions";import{DOOM_UI_HUB_SERVICE as oe,requireDoomUiHub as se}from"@agimon-ai/doompi-extension-contracts/ui-hub";import{DEFAULT_COMPACTION_SETTINGS as C,buildSessionContext as w,generateSummary as T,sessionEntryToContextMessages as E}from"@earendil-works/pi-coding-agent";const D=`@root`,O=`doom-autocompact`,k={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function A(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function ce(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.type!==`custom`||n.customType!==`doom-autocompact-state`)continue;let r=g(n.data);if(r)return r}}function j(e){for(let t of e.sessionManager.getBranch().toReversed())if((t.type!==`custom`||t.customType!==`doom-autocompact-state`)&&t.type!==`label`)return t.id;return D}function M(e){return e instanceof Error?e.message:String(e)}function le(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}const N=Object.freeze({entries:Object.freeze([]),errors:Object.freeze([])});function P(e){if(!e)return N;try{return e.snapshot()}catch(e){return{entries:[],errors:[{source:S,id:`service-snapshot`,label:`Context contributions`,order:0,message:M(e)}]}}}function F(e){let t=e.entries.map(e=>`### ${e.label}\n${e.text}`);return t.push(...e.errors.map(e=>`### ${e.label}\n(unavailable: ${e.message})`)),t.length>0?t.join(`
|
|
2
|
+
|
|
3
|
+
`):`(no registered context contributions)`}function ue(e,t){let n=le(e);return{...n?{planPath:n.path}:{},contributions:t.entries,contributionErrors:t.errors}}function de(e){return`<compaction-runtime-state>
|
|
4
|
+
Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
|
|
5
|
+
<active-plan>
|
|
6
|
+
${e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`}
|
|
7
|
+
</active-plan>
|
|
8
|
+
<context-contributions>
|
|
9
|
+
${F({entries:e.contributions,errors:e.contributionErrors})}
|
|
10
|
+
</context-contributions>
|
|
11
|
+
</compaction-runtime-state>`}function I(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.contribution_count":e.contributions.length,"autocompact.runtime.contribution_error_count":e.contributionErrors.length}}function L(e){let t=e.plan?`Source: ${e.plan.path}\n\n${e.plan.content}`:`(no active plan document)`,n=[e.readFiles.length>0?`Read files: ${e.readFiles.join(`, `)}`:void 0,e.modifiedFiles.length>0?`Modified files: ${e.modifiedFiles.join(`, `)}`:void 0].filter(e=>!!e);return`<compaction-steering priority="user,plan,context-contributions,important-context,recent-messages">
|
|
12
|
+
<user-prompt source="conversation">
|
|
13
|
+
Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
|
|
14
|
+
</user-prompt>
|
|
15
|
+
<active-plan>
|
|
16
|
+
${t}
|
|
17
|
+
</active-plan>
|
|
18
|
+
<context-contributions>
|
|
19
|
+
${F(e.contextContributions)}
|
|
20
|
+
</context-contributions>
|
|
21
|
+
<important-context>
|
|
22
|
+
${n.length>0?n.join(`
|
|
23
|
+
`):`(none recorded outside the conversation)`}
|
|
24
|
+
</important-context>
|
|
25
|
+
</compaction-steering>`}function fe(e,t){let n=e===2?`Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.
|
|
26
|
+
|
|
27
|
+
`:``;return`Create Doom autocompact checkpoint pass ${e}.
|
|
28
|
+
|
|
29
|
+
${L(t)}
|
|
30
|
+
|
|
31
|
+
Apply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
|
|
32
|
+
|
|
33
|
+
${n}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.
|
|
34
|
+
|
|
35
|
+
## Goal
|
|
36
|
+
## Constraints & Preferences
|
|
37
|
+
## Progress
|
|
38
|
+
### Done
|
|
39
|
+
### In Progress
|
|
40
|
+
### Blocked
|
|
41
|
+
## Key Decisions
|
|
42
|
+
## Next Steps
|
|
43
|
+
## Critical Context`}function pe(e,t,n){let r=_(w(t).messages,t).messages;if(e===1||!n)return r;let i=t.findIndex(e=>e.id===n);return i===-1?r:t.slice(i+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>E(e))}const R={enabled:!0,ratios:{}};function z(e,t){let n;try{n=ie(b().root??e).modes}catch(e){return process.emitWarning(`Doom autocompact configuration could not be loaded; using the active session model instead.`),t?.(e),R}let r=n?.autocompact,i=(r&&(r.model!==void 0||r.thinking!==void 0)?{...r.model?{model:r.model}:{},...r.thinking?{thinking:r.thinking}:{}}:void 0)??n?.planning?.subagents,a=r?.thresholds;return{enabled:r?.enabled??!0,...i?{agent:i}:{},ratios:{...a?.pass1===void 0?{}:{1:a.pass1},...a?.pass2===void 0?{}:{2:a.pass2},...a?.pass3===void 0?{}:{3:a.pass3}}}}function B(e){let t=z(e.cwd).agent,n=t?.model?v(t.model):void 0,r=n?e.modelRegistry.find(n.provider,n.modelId):void 0,i=r??e.model;if(!i)return;let a=t?.thinking??(r?n?.thinking:void 0)??e.thinkingLevel;return{model:i,...a?{thinkingLevel:a}:{}}}async function V(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);let i=e.context.modelRegistry.getProvider(n.model.provider);if(!i)throw Error(`No provider is registered for "${n.model.provider}" in this session.`);return T(e.messages,n.model,C.reserveTokens,r.apiKey,r.headers,e.signal,e.instructions,e.previousCheckpoint,n.thinkingLevel,(e,t,n)=>i.streamSimple(e,t,n),r.env)}function H(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function U(g,v,b={}){let ie=b.resolveModel??B,x=b.generateCheckpoint??(e=>V(e,ie)),C=b.telemetry??re(),T=b.doomIntegrations??!0,E=new Set,M=new Set,N=new Set,F=!0,L=0,R=c(),U,W,G,K,q=!1;g.effect(()=>async()=>{F=!1,L+=1,W?.abort(Error(`Autocompact runtime is shutting down.`)),W=void 0,await Promise.allSettled(N),G=void 0,K=void 0,U=void 0,E.clear(),M.clear(),R=c(),q=!1,await C.shutdown()},`${O}/runtime`),g.inject([S],e=>{let t=ae(e);return K=t,()=>{K===t&&(K=void 0)}}),T&&g.inject([oe],e=>{let t=se(e).registerFooter({source:O,id:`autocompact`,order:20});return G=t,()=>{t.dispose(),G===t&&(G=void 0)}});let me=e=>{if(!F)return;let t=R.phase===k.checkpointPending?`summarizing`:R.phase===k.checkpointReady?`applying`:void 0;G?.update(t?{fullText:`Compacting p${R.pass}`,compactText:`C${R.pass}`}:void 0);let n=e??U;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${R.pass} (${t})…`:void 0)},J=()=>{F&&(v.appendEntry(i,{...R}),me())},Y=()=>{delete R.requestId,delete R.snapshotLeafId,delete R.snapshotTokens,delete R.pendingCheckpoint,delete R.compactionPass},X=e=>{R.checkpointQueue=R.checkpointQueue.filter(t=>t!==e)},he=e=>{F&&(R=ce(e.sessionManager.getBranch())??c(),!(R.phase===k.checkpointReady&&R.requestId&&R.snapshotLeafId&&R.pendingCheckpoint||R.phase===k.waiting)&&(W?.abort(),W=void 0,R.phase=k.waiting,Y(),J()))},ge=e=>{F&&v.sendMessage({customType:n,content:`${e} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:R.cycle,pass:R.pass}},{triggerTurn:!0,deliverAs:`steer`})},Z=(e,t)=>{let n=R.invalidAttempts+1,r=n>=3;return R.phase=k.waiting,t&&(R.lastAttemptLeafId=t),r?(X(e),R.exhaustedPasses=[...R.exhaustedPasses,e],R.invalidAttempts=0):R.invalidAttempts=n,Y(),J(),{attempts:n,exhausted:r}},_e=(e,t)=>{if(!F||e!==R.requestId||R.phase!==k.checkpointPending)return;let n=R.pass,{attempts:r,exhausted:i}=Z(n,R.snapshotLeafId),a=t instanceof Error?t.message:String(t);H(U,i?`Doom autocompact summarization pass ${n} failed ${r} times and was abandoned: ${a}`:`Doom autocompact summarization pass ${n} failed: ${a}`,`error`)},ve=(e,t)=>{!F||q||(q=!0,C.recordWarning(y.configurationLoadFailed,t,A(e,{"autocompact.cycle":R.cycle,"autocompact.pass":R.pass})))},Q=(e,t,n)=>{if(F)for(let r of t.errors)H(e,`Doom autocompact context contribution degraded (${r.source}/${r.id}): ${r.message}`,`warning`),C.recordWarning(y.contextContributionDegraded,Error(r.message),{...n,"autocompact.context_contribution.source":r.source,"autocompact.context_contribution.id":r.id,"autocompact.context_contribution.order":r.order})},ye=(e,t,n)=>{if(!F)return{contributions:[],contributionErrors:[]};let i=P(K);Q(e,i,n);let a=ue(t,i);return v.sendMessage({customType:r,content:de(a),display:!1,details:{version:2,...a}}),a},be=(e,n)=>{if(!F||!R.requestId||!R.snapshotLeafId||!R.pendingCheckpoint)return!1;let r=n.sessionManager.getBranch(),i=_(w(r).messages,r).messages,a=m(R,d(i)),o=R.requestId,s=R.cycle,c=ne(R.pendingCheckpoint,a),l={...a,doomAutocompact:{version:2,cycle:s,pass:e,requestId:o,snapshotLeafId:R.snapshotLeafId,tokensBefore:R.snapshotTokens??n.getContextUsage()?.tokens??0},retainedMessages:ee(r,R.snapshotLeafId)},u=n.isIdle();v.sendMessage({customType:t,content:c,display:!1,details:l});let f=j(n),p=A(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e}),h=ye(n,r,p);return u&&v.setLabel(f,`autocompact:c${s}:p${e}`),R.readFiles=a.readFiles,R.modifiedFiles=a.modifiedFiles,delete R.latestCheckpointSnapshotLeafId,R.phase=k.waiting,R.checkpointQueue=[],R.exhaustedPasses=[],R.invalidAttempts=0,R.baselinePending=!0,delete R.lastAttemptLeafId,Y(),R.cycle+=1,R.pass=1,J(),C.recordEvent(y.contextCommitted,A(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e,"autocompact.snapshot_leaf_id":l.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":l.doomAutocompact.tokensBefore,"autocompact.message_count.before":i.length,"autocompact.message_count.retained":l.retainedMessages.length,"autocompact.apply_mode":u?`idle`:`turn_end`,...I(h)})),u&&ge(`Asynchronous compaction completed.`),!0},xe=(e,t,n)=>{if(!F)return;let r=L,i=t.sessionManager.getBranch(),a=j(t),o=l(t.sessionManager.getSessionId(),R.cycle,e,a),c=e>1?s(p(i)):void 0,u=pe(e,i,R.latestCheckpointSnapshotLeafId),d=P(K),f=A(t,{"autocompact.request.id":o,"autocompact.cycle":R.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":a,"autocompact.tokens_before":n,"autocompact.message_count.before":u.length});Q(t,d,f),R.phase=k.checkpointPending,R.pass=e,R.requestId=o,R.snapshotLeafId=a,R.snapshotTokens=n,delete R.pendingCheckpoint,delete R.compactionPass,delete R.lastAttemptLeafId,J(),W?.abort(),W=new AbortController;let m=W.signal,h=C.runInSpan(`doom_autocompact.checkpoint`,f,async()=>{await C.recordEvent(y.checkpointStarted,f);try{let n=await x({messages:u,instructions:fe(e,{plan:le(i),contextContributions:d,readFiles:R.readFiles,modifiedFiles:R.modifiedFiles}),...c?{previousCheckpoint:c}:{},context:t,signal:m});if(!F||r!==L)throw m.reason??Error(`Autocompact checkpoint became stale.`);if(!n.trim())throw Error(`Summarization returned an empty checkpoint.`);return await C.recordEvent(y.checkpointCompleted,{...f,"autocompact.checkpoint.characters":n.length}),n}catch(e){throw F&&r===L&&await C.recordError(y.checkpointFailed,e,f),e}}).then(e=>{!F||r!==L||o!==R.requestId||R.phase!==k.checkpointPending||(R.phase=k.checkpointReady,R.pendingCheckpoint=e.trim(),J(),U&&$(U))}).catch(e=>{F&&r===L&&_e(o,e)});N.add(h),h.finally(()=>N.delete(h))},Se=e=>{if(!F||R.phase!==k.waiting||e.hasPendingMessages())return!1;let t=z(e.cwd,t=>ve(e,t));if(!t.enabled)return!1;let n=e.getContextUsage();if(!n||n.tokens===null)return!1;if(R.baselinePending)return a(e.sessionManager.getBranch())?(R.baselineTokens=n.tokens,R.baselinePending=!1,J(),!1):!1;let r=j(e);if(R.lastAttemptLeafId===r)return!1;for(let e of[1,2,3])e<R.pass||R.checkpointQueue.includes(e)||R.exhaustedPasses.includes(e)||n.tokens>=te(e,n.contextWindow,R.baselineTokens,t.ratios)&&R.checkpointQueue.push(e);let i=R.checkpointQueue[0];return i?(xe(i,e,n.tokens),!0):!1},Ce=(t,n)=>{if(!F)return;let r=R.snapshotLeafId;v.appendEntry(e,{...o(R.cycle,t,R.requestId??`completed`),summary:n}),r&&(R.latestCheckpointSnapshotLeafId=r)},we=e=>{if(!F||R.phase!==k.checkpointReady||!R.requestId||!R.pendingCheckpoint)return`none`;let t=R.pass,n=h(R.pendingCheckpoint);if(!f(n.summary)){let n=R.snapshotLeafId,r=R.requestId,{attempts:i,exhausted:a}=Z(t,n),o=Error(`Summarization pass ${t} returned an incomplete checkpoint.`);return H(e,a?`Doom autocompact summarization pass ${t} returned an incomplete checkpoint ${i} times and was abandoned.`:`Doom autocompact summarization pass ${t} returned an incomplete checkpoint.`,`error`),C.recordError(y.checkpointInvalid,o,A(e,{"autocompact.cycle":R.cycle,"autocompact.pass":t,"autocompact.checkpoint.attempts":i,"autocompact.checkpoint.exhausted":a,...r?{"autocompact.request.id":r}:{}})),`invalid`}return R.invalidAttempts=0,t===1?(Ce(1,n.summary),X(1),R.phase=k.waiting,R.pass=2,Y(),J(),`pass1`):t===2&&n.shouldCompact!==!0?(Ce(2,n.summary),X(2),R.phase=k.waiting,R.pass=3,Y(),J(),`deferred`):(R.pendingCheckpoint=n.summary,be(t,e)?`committed`:`invalid`)};function $(e){F&&(U=e,e.isIdle()&&we(e)!==`committed`&&Se(e))}v.on(`context`,(e,t)=>{if(!F)return;let n=_(e.messages,t.sessionManager.getBranch());if(n.invalidMarker){let e=t.sessionManager.getLeafId()??D;M.has(e)||(M.add(e),C.recordError(y.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),A(t,{"autocompact.leaf_id":e})));return}if(n.marker)return E.has(n.marker.requestId)||(E.add(n.marker.requestId),C.recordEvent(y.contextApplied,A(t,{"autocompact.request.id":n.marker.requestId,"autocompact.cycle":n.marker.cycle,"autocompact.pass":n.marker.pass,"autocompact.snapshot_leaf_id":n.marker.snapshotLeafId,"autocompact.tokens_before":n.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":n.messages.length,"autocompact.message_count.retained":n.retainedMessageCount}))),{messages:n.messages}});let Te=e=>{F&&(L+=1,W?.abort(Error(`Autocompact session generation was replaced.`)),W=void 0,E.clear(),M.clear(),U=e,he(e),$(e))};v.on(`session_start`,(e,t)=>Te(t)),v.on(`session_tree`,(e,t)=>Te(t)),v.on(`turn_end`,(e,t)=>{if(F){if(U=t,t.isIdle()){$(t);return}R.phase===k.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&we(t)!==`none`||Se(t)}}),v.on(`agent_settled`,(e,t)=>{F&&$(t)}),v.on(`session_before_compact`,e=>{if(!(!F||e.reason!==`threshold`))return R.phase===k.checkpointPending||R.phase===k.checkpointReady||R.baselinePending?{cancel:!0}:void 0}),v.on(`session_compact`,(e,t)=>{if(!F)return;L+=1,W?.abort(),W=void 0;let n=u(e.compactionEntry.details),r=m(R,void 0,n);R.readFiles=r.readFiles,R.modifiedFiles=r.modifiedFiles,delete R.latestCheckpointSnapshotLeafId,R.baselinePending=!0,R.phase=k.waiting,Y(),R.checkpointQueue=[],R.exhaustedPasses=[],R.invalidAttempts=0,delete R.lastAttemptLeafId,v.setLabel(e.compactionEntry.id,`autocompact:c${R.cycle}:external`);let i=R.cycle,a=A(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason}),o=ye(t,t.sessionManager.getBranch(),a);R.cycle+=1,R.pass=1,J(),C.recordEvent(y.nativeCompactionCompleted,A(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...I(o)}))})}async function W(e){let t=await x(e,`@agimon-ai/doompi-autocompact`),n=t.root.plugin(G,{pi:e});try{await n}catch(e){try{await n.dispose()}finally{await t.dispose()}throw e}let r;e.on(`session_shutdown`,()=>r??=(async()=>{try{await n.dispose()}finally{await t.dispose()}})())}function G(e,t){U(e,t.pi)}export{W as autocompactExtension,W as default,z as autocompactRuntimeConfig,V as generateCheckpointWithPi,U as installAutocompactRuntime,B as resolveDoomSummarizationModel};
|
|
44
|
+
//# sourceMappingURL=extension.mjs.map
|